OptaPlanner wrappers for Python. Currently significantly slower than OptaPlanner in Java or Kotlin.

Overview

OptaPy

Binder

OptaPy is an AI constraint solver for Python to optimize the Vehicle Routing Problem, Employee Rostering, Maintenance Scheduling, Task Assignment, School Timetabling, Cloud Optimization, Conference Scheduling, Job Shop Scheduling, Bin Packing and many more planning problems.

OptaPy wraps the OptaPlanner engine internally, but using OptaPy in Python is significantly slower than using OptaPlanner in Java or Kotlin.

Warning
OptaPy is an experimental technology. It is at least 20 times slower than using OptaPlanner in Java or Kotlin. It is currently not supported in any way or form for production use.

Get started

Prerequisites

  1. Install Python 3.9 or later

  2. Install JDK 11 or later with JAVA_HOME configured appropriately.

Build

  1. Install the python build module (if not already installed):

    pip install build
  2. In the optapy-core directory, use the command below to build the optapy python wheel into the dist directory:

    cd optapy-core
    python -m build
  3. Install it into a virtual environment using pip:

    # Activate a virtual environment first
    source my_project/venv/bin/activate
    pip install dist/optapy-0.0.0-py3-none-any.whl

Run

Running run.sh runs optapy-quickstarts/school-timetabling/main.py after building optapy and installing it to optapy-quickstarts/school-timetabling/venv.

Source code overview

Domain

In OptaPlanner, the domain has three parts:

  • Problem Facts, which do not change

  • Planning Entities, which have one or more planning variables

  • Planning Solution, which define the facts and entities of the problem

Problem Facts

To declare Problem Facts, use the @problem_fact decorator

from optapy import problem_fact
@problem_fact
class Timeslot:
    def __init__(self, id, dayOfWeek, startTime, endTime):
        self.id = id
        self.dayOfWeek = dayOfWeek
        self.startTime = startTime
        self.endTime = endTime

Planning Entities

To declare Planning Entities, use the @planning_entity decorator

from optapy import planning_entity, planning_id, planning_variable

@planning_entity
class Lesson:
    def __init__(self, id, subject, teacher, studentGroup, timeslot=None, room=None):
        self.id = id
        self.subject = subject
        self.teacher = teacher
        self.studentGroup = studentGroup
        self.timeslot = timeslot
        self.room = room

    @planning_id
    def getId(self):
        return self.id

    @planning_variable(Timeslot, value_range_provider_refs=["timeslotRange"])
    def getTimeslot(self):
        return self.timeslot

    def setTimeslot(self, newTimeslot):
        self.timeslot = newTimeslot

    @planning_variable(Room, value_range_provider_refs=["roomRange"])
    def getRoom(self):
        return self.room

    def setRoom(self, newRoom):
        self.room = newRoom
  • @planning_variable method decorators are used to indicate what fields can change. The method MUST follow JavaBean style conventions and have a corresponding setter (i.e. getRoom(self), setRoom(self, newRoom)). The first parameter of the decorator is the type of the Planning Variable (required). The value_range_provider_refs parameter tells OptaPlanner what value range providers on the Planning Solution this Planning Variable can take values from.

  • @planning_id is used to uniquely identify an entity object of a particular class. The same Planning Id can be used on entities of different classes, but the ids of all entities in the same class must be different.

Planning Solution

To declare the Planning Solution, use the @planning_solution decorator

from optapy import planning_solution, problem_fact_collection_property, value_range_provider, planning_entity_collection_property, planning_score

@planning_solution
class TimeTable:
    def __init__(self, timeslotList=[], roomList=[], lessonList=[], score=None):
        self.timeslotList = timeslotList
        self.roomList = roomList
        self.lessonList = lessonList
        self.score = score

    @problem_fact_collection_property(Timeslot)
    @value_range_provider(range_id = "timeslotRange")
    def getTimeslotList(self):
        return self.timeslotList

    @problem_fact_collection_property(Room)
    @value_range_provider(range_id = "roomRange")
    def getRoomList(self):
        return self.roomList

    @planning_entity_collection_property(Lesson)
    def getLessonList(self):
        return self.lessonList

    @planning_score(HardSoftScore)
    def getScore(self):
        return self.score

    def setScore(self, score):
        self.score = score
  • @value_range_provider(range_id) is used to indicate a method returns values a Planning Variable can take. It can be referenced by its id in the value_range_provider_refs parameter of @planning_variable. It should also have a @problem_fact_collection_property or a @planning_entity_collection_property.

  • @problem_fact_collection_property(type) is used to indicate a method returns Problem Facts. The first parameter of the decorator is the type of the Problem Fact Collection (required). It should be a list.

  • @planning_entity_collection_property(type) is used to indicate a method returns Planning Entities. The first parameter of the decorator is the type of the Planning Entity Collection (required). It should be a list.

  • @planning_score(scoreType) is used to tell OptaPlanner what field holds the score. The method MUST follow JavaBean style conventions and have a corresponding setter (i.e. getScore(self), setScore(self, score)). The first parameter of the decorator is the score type (required).

Constraints

You define your constraints by using the ConstraintFactory

import java
from domain import Lesson
from optapy import get_class, constraint_provider
from optapy.types import Joiners, HardSoftScore

# Get the Java class corresponding to the Lesson Python class
LessonClass = get_class(Lesson)

@constraint_provider
def defineConstraints(constraintFactory):
    return [
        # Hard constraints
        roomConflict(constraintFactory),
        # Other constraints here...
    ]

def roomConflict(constraintFactory):
    # A room can accommodate at most one lesson at the same time.
    return constraintFactory \
            .fromUniquePair(LessonClass, [
            # ... in the same timeslot ...
                Joiners.equal(lambda lesson: lesson.timeslot),
            # ... in the same room ...
                Joiners.equal(lambda lesson: lesson.room)]) \
            .penalize("Room conflict", HardSoftScore.ONE_HARD)
Note
Since from is a keyword in python, to use the constraintFactory.from function, you access it like constraintFactory.from_(class, [joiners…​])

Solve

from optapy import get_class, solve
from optapy.types import SolverConfig, Duration
from constraints import defineConstraints
from domain import TimeTable, Lesson, generateProblem
import java

solverConfig = SolverConfig().withEntityClasses(get_class(Lesson)) \
    .withSolutionClass(get_class(TimeTable)) \
    .withConstraintProviderClass(get_class(defineConstraints)) \
    .withTerminationSpentLimit(Duration.ofSeconds(30))

solution = solve(solverConfig, generateProblem())

solution will be a TimeTable instance with planning variables set to the final best solution found.

More information

Comments
  • Add JPype support

    Add JPype support

    This PR adds JPype support, which allows it to be used with regular Python. It is approximately 3 times slower than the GraalVM version, which is 10 time slower than Java.

    opened by Christopher-Chianelli 12
  • TypeError: Ambiguous overloads ... when using ConstraintCollectors.compose

    TypeError: Ambiguous overloads ... when using ConstraintCollectors.compose

    I am currently trying to optimize some shifts. As these shifts start every 8 hours I want to make sure that no person does more than 2 shifts in a row and has to work 24h at once.

    My idea was to group all shift assignments by person and then use a composed collector to get the earliest and latest shift and then make sure these shifts do not fill the entire 24 hours (because another constraint is that every person gets exactly 3 shifts).

    ONE_DAY_IN_SECONDS = 24 * 60 * 60
    def diff_in_seconds(earliest, latest):
        # I tried timedelta before but that did not work either
        return (latest - earliest).total_seconds()
    
    def no_24h_marathon(constraint_factory):
        return constraint_factory.forEach(assignment_class).groupBy(
            lambda a: a.person.name,
            ConstraintCollectors.compose(
                ConstraintCollectors.min(lambda a: a.shift.start),
                ConstraintCollectors.max(lambda a: a.shift.end),
                more_than_16h,
            )
        ).penalize("No 24h marathon", HardSoftScore.ONE_HARD, lambda _, c: c > ONE_DAY_IN_SECONDS )
    

    When I do this I get this TypError about overloads when trying to solve:

    TypeError: Ambiguous overloads found for org.optaplanner.core.api.score.stream.ConstraintCollectors.min(function) between:
    	public static org.optaplanner.core.api.score.stream.uni.UniConstraintCollector org.optaplanner.core.api.score.stream.ConstraintCollectors.min(java.util.function.Function)
    	public static org.optaplanner.core.api.score.stream.tri.TriConstraintCollector org.optaplanner.core.api.score.stream.ConstraintCollectors.min(org.optaplanner.core.api.function.TriFunction)
    	public static org.optaplanner.core.api.score.stream.quad.QuadConstraintCollector org.optaplanner.core.api.score.stream.ConstraintCollectors.min(org.optaplanner.core.api.function.QuadFunction)
    	public static org.optaplanner.core.api.score.stream.bi.BiConstraintCollector org.optaplanner.core.api.score.stream.ConstraintCollectors.min(java.util.function.BiFunction)
    

    Should I use a different approach? Any and every help would be greatly appreciated. Thanks for this python wrapper, it helps a lot!

    opened by MrGreenTea 8
  • Return value is not compatible with required type

    Return value is not compatible with required type

    Hi, I am getting the Return value is not compatible with required type error - how can I tell the types involved (expected and actual), so I can solve this error?

    By the way, is the NotADirectoryError and PermissionError errors following the TypeError in the end 'real', or are theycaused by the type mismatch?

    Thanks

    C:\Users\User\Project\venv\Scripts\python.exe C:/Users/User/Project/optapy1.py
    11:11:20,084 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
    11:11:20,084 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
    11:11:20,084 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [jar:file:/C:/Users/User/AppData/Local/Temp/tmpy3fynomc/optapy-8.11.0.Final-sources.jar!/logback.xml]
    11:11:20,084 |-WARN in ch.qos.logback.classic.LoggerContext[default] - Resource [logback.xml] occurs multiple times on the classpath.
    11:11:20,084 |-WARN in ch.qos.logback.classic.LoggerContext[default] - Resource [logback.xml] occurs at [jar:file:/C:/Users/User/AppData/Local/Temp/tmpy3fynomc/optapy-8.11.0.Final-sources.jar!/logback.xml]
    11:11:20,084 |-WARN in ch.qos.logback.classic.LoggerContext[default] - Resource [logback.xml] occurs at [jar:file:/C:/Users/User/AppData/Local/Temp/tmpy3fynomc/optapy-8.11.0.Final.jar!/logback.xml]
    11:11:20,091 |-INFO in [email protected] - URL [jar:file:/C:/Users/User/AppData/Local/Temp/tmpy3fynomc/optapy-8.11.0.Final-sources.jar!/logback.xml] is not of type file
    11:11:20,152 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
    11:11:20,152 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
    11:11:20,156 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [consoleAppender]
    11:11:20,159 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
    11:11:20,204 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [org.optaplanner] to INFO
    11:11:20,204 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to WARN
    11:11:20,204 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [consoleAppender] to Logger[ROOT]
    11:11:20,205 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
    11:11:20,207 |-INFO in [email protected] - Registering current configuration as safe fallback point
    
    Traceback (most recent call last):
      File "C:\Users\User\Project\optapy1.py", line 129, in <module>
        solution = solve(solverConfig, generateProblem())
      File "C:\Users\User\Project\venv\lib\site-packages\optapy\optaplanner_java_interop.py", line 299, in solve
        solution = _unwrap_java_object(PythonSolver.solve(solver_config,
    TypeError: Return value is not compatible with required type.
    
    Traceback (most recent call last):
      File "C:\Program Files\Python39\lib\shutil.py", line 616, in _rmtree_unsafe
        os.unlink(fullname)
    PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\User\\AppData\\Local\\Temp\\tmpy3fynomc\\antlr-runtime-3.5.2.jar'
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "C:\Program Files\Python39\lib\tempfile.py", line 801, in onerror
        _os.unlink(path)
    PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\User\\AppData\\Local\\Temp\\tmpy3fynomc\\antlr-runtime-3.5.2.jar'
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "C:\Program Files\Python39\lib\weakref.py", line 656, in _exitfunc
        f()
      File "C:\Program Files\Python39\lib\weakref.py", line 580, in __call__
        return info.func(*info.args, **(info.kwargs or {}))
      File "C:\Program Files\Python39\lib\tempfile.py", line 816, in _cleanup
        cls._rmtree(name)
      File "C:\Program Files\Python39\lib\tempfile.py", line 812, in _rmtree
        _shutil.rmtree(name, onerror=onerror)
      File "C:\Program Files\Python39\lib\shutil.py", line 740, in rmtree
        return _rmtree_unsafe(path, onerror)
      File "C:\Program Files\Python39\lib\shutil.py", line 618, in _rmtree_unsafe
        onerror(os.unlink, fullname, sys.exc_info())
      File "C:\Program Files\Python39\lib\tempfile.py", line 804, in onerror
        cls._rmtree(path)
      File "C:\Program Files\Python39\lib\tempfile.py", line 812, in _rmtree
        _shutil.rmtree(name, onerror=onerror)
      File "C:\Program Files\Python39\lib\shutil.py", line 740, in rmtree
        return _rmtree_unsafe(path, onerror)
      File "C:\Program Files\Python39\lib\shutil.py", line 599, in _rmtree_unsafe
        onerror(os.scandir, path, sys.exc_info())
      File "C:\Program Files\Python39\lib\shutil.py", line 596, in _rmtree_unsafe
        with os.scandir(path) as scandir_it:
    NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\\Users\\User\\AppData\\Local\\Temp\\tmpy3fynomc\\antlr-runtime-3.5.2.jar'
    
    Process finished with exit code 1
    
    opened by ScDor 7
  • Add workflow to run SonarCloud on main

    Add workflow to run SonarCloud on main

    The majority of testing is done on in Python tests; the Java tests mostly act as a sanity check, since in order to actually test all the parts, we need to test in Python (otherwise, we are just testing how we think it works, not how it actually works).

    In order to let Python tests contribute to the test coverage, the action downloads the JaCoCo runtime agent, and add it as an argument when the test JVM starts.

    Closes #116

    opened by Christopher-Chianelli 6
  • Fix issues in Sonarcloud action

    Fix issues in Sonarcloud action

    • setup-python fails if it cannot find a requirements.txt file if cache-dependency-path is not set
    • For some reason, Java 11 JVM crash with Python JaCoCo execution, but Java 17 JVM does not
    opened by Christopher-Chianelli 5
  • Launch two solver in a row make the second one crash

    Launch two solver in a row make the second one crash

    Hello, I have a problem that I split into two parts. When I run a first solver with the first part, then at the end a second solver with the second part. The second one crashes systematically with the error : java.lang.RuntimeException: java.lang.IllegalArgumentException: OptaPySolver does not exist in global scope The strangest thing is that if I change the order of my problems it is always the one I put first that works. As if running the solver twice would cause it to crash. Is this a known bug ?

    opened by adrdv 3
  • Support for

    Support for "dropped nodes"?

    Hello,

    I am currently testing a situation where most of the customer's demands are higher than any vehicle capacity (using the default constraints provided by the vehicle routing example)

    The results are interesting since it show that most vehicles are allocated "over capacity" - is this expected behavior?

    Thanks!

    opened by bilics 3
  • [bot]: Bump optaplanner-build-parent from 8.30.0.Final to 8.31.1.Final

    [bot]: Bump optaplanner-build-parent from 8.30.0.Final to 8.31.1.Final

    Bumps optaplanner-build-parent from 8.30.0.Final to 8.31.1.Final.

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies java 
    opened by dependabot[bot] 2
  • [bot]: Bump version.org.ow2.asm from 9.3 to 9.4

    [bot]: Bump version.org.ow2.asm from 9.3 to 9.4

    Bumps version.org.ow2.asm from 9.3 to 9.4. Updates asm-util from 9.3 to 9.4

    Updates asm-tree from 9.3 to 9.4

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies java 
    opened by dependabot[bot] 2
  • [bot]: Bump gizmo from 1.0.11.Final to 1.4.0.Final

    [bot]: Bump gizmo from 1.0.11.Final to 1.4.0.Final

    Bumps gizmo from 1.0.11.Final to 1.4.0.Final.

    Commits
    • 33e0179 [maven-release-plugin] prepare release 1.4.0.Final
    • 9c1c4b3 Merge pull request #131 from Ladicek/bitwise-operations
    • c5b8084 Merge pull request #129 from oliv37/patch-1
    • a9869fa Merge pull request #130 from oliv37/patch-2
    • af71b0c Small change to how float and double fields are compared in generated `eq...
    • d242b19 Add methods for emitting bitwise AND, OR, XOR
    • 25e1f1f Merge pull request #128 from Ladicek/improvements
    • 500be52 Add documentation of high-level utilities and improve consistency
    • d82fdb9 Add high-level utilities for generating equals, hashCode and toString m...
    • 05307df Add a high-level utility for generating StringBuilder chains
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies java 
    opened by dependabot[bot] 2
  • Integration with GraphHopper (or other routing service)

    Integration with GraphHopper (or other routing service)

    Hi,

    Is it just a matter of replacing the distance calculator with such service?

    And the "final result" would then contain the comprehensive list of lat/lng with the complete routing?

    Thanks for any pointers!

    opened by bilics 2
  • jpyinterpreter - float, int str constructor support

    jpyinterpreter - float, int str constructor support

    Python float and int accept str as constructor arguments, so jpyinterpreter should too.

    Expected behaviour:

    a = float('inf')
    b  = float('1.0')
    assert a == infinity
    assert b == 1.0
    
    opened by Christopher-Chianelli 0
  • jpyinterpreter - Keep module attributes' type infomation

    jpyinterpreter - Keep module attributes' type infomation

    When a module is loaded via LOAD_MODULE, jpyinterpreter currently does not have access to the type of attributes in the modules. This result in losing type infomation when a Type is loaded from a module, generating less efficient Java bytecode.

    enhancement 
    opened by Christopher-Chianelli 0
  • jpyinterpreter - make FOR_ITER use Java iterator loop format when possible

    jpyinterpreter - make FOR_ITER use Java iterator loop format when possible

    Currently, in order to fully support all the forms a Python iterator can take, jpyinterpreter generates the following code for FOR_ITER:

    try {
        do {
            TOS' = next(TOS)
             // code in for block
        } while(true);
    } catch (StopIteration e) {
        // code after for block
    }
    

    This is highly atypical in Java, and the JVM probably would have a harder time optimizing its standard for iterator loop:

    while (TOS.hasNext()) {
        TOS' = TOS.next();
        // code in for block
    }
     // code after for block
    

    We can look at TOS to see if it a known iterator type (i.e. PythonIterator), and if so, generate the more typical Java loop.

    enhancement 
    opened by Christopher-Chianelli 0
  • jpyinterpreter - Support match statements

    jpyinterpreter - Support match statements

    See https://peps.python.org/pep-0634/

    This require the following opcodes:

    • COPY_DICT_WITHOUT_KEYS
    • GET_LEN
    • MATCH_MAPPING
    • MATCH_SEQUENCE
    • MATCH_KEYS
    • MATCH_CLASS(count)
    enhancement 
    opened by Christopher-Chianelli 1
  • jpyinterpreter - support classes defined in functions

    jpyinterpreter - support classes defined in functions

    Python implement the equivalent of Java's anonymous classes with the LOAD_BUILD_CLASS opcode. It loads the __build_class__ builtin method to the top of the stack. The __build_class__ method has the following signature __build_class__(func: code, name: str, *bases: tuple[type], metaclass: callable = NOOP, **kwargs: dict), where:

    • func is the code object, that when executed, its locals become the (static) fields and (virtual, static and class) methods for the created type.
    • name the name of the created class
    • bases the superclasses of the created class
    • metaclass, it __prepare__ attribute, if present, is called JUST BEFORE the class body is executed (given the name and base classes). prepare returns a dictionary-like object which is used to store the class member definitions during evaluation of the class body. In other words, the class body is evaluated as a function block (just like it is now), except that the local variables dictionary is replaced by the dictionary returned from prepare. This dictionary object can be a regular dictionary or a custom mapping type. Once the class body has finished evaluating, the metaclass will be called (as a callable) with the class dictionary, which is no different from the current metaclass mechanism.
    • kwargs - passed to the metaclass during type instruction (see https://peps.python.org/pep-3115/)

    (Source: https://stackoverflow.com/a/1833013)

    Note due to the way this is set up, Python will always return a NEW class (that is, if the function is called twice, the classes that got created will be different). To prevent a memory leak, we would need to create a new ClassLoader to store the bytecode of the created class (see https://stackoverflow.com/a/148707)

    enhancement 
    opened by Christopher-Chianelli 0
Releases(8.31.1b0)
  • 8.31.1b0(Dec 12, 2022)

    Add support for Python 3.11 for jpyinterpreter, significantly improving Python 3.11 score calculation speeds.

    Also optimize how calls are done in the interpreter, which can provide a modest improvement to score calculation speeds for some constraints.

    Source code(tar.gz)
    Source code(zip)
  • 8.30.0b0(Nov 22, 2022)

    Add the ConstraintVerifier API to allow testing of constraints. See https://www.optapy.org/docs/latest/constraint-streams/constraint-streams.html#constraintStreamsTesting for details.

    Source code(tar.gz)
    Source code(zip)
  • 8.28.0b0(Oct 27, 2022)

    This is the first release of optapy that includes jpyinterpreter, a module created to translate Python function bytecode to equivalent Java bytecode to massively increase performance by avoiding Foreign Function Interface (FFI) calls. You don't need to do anything in order to use it; it is on by default. Functions and classes that cannot be translated will be proxied to their CPython functions and types.

    Bug fixes:

    • Support ValueRange, CountableValueRange and entity @value_range_provider
    • Support arbitary PythonComparable as @planning_id
    Source code(tar.gz)
    Source code(zip)
  • 8.23.0a0(Jul 6, 2022)

    • Bug Fix: SolverManager solve and solveAndListen will now show exceptions
    • Bug Fix: A Uni, Bi, and Tri Constraint Stream can now join an UniConstraintStream
    Source code(tar.gz)
    Source code(zip)
  • 8.21.0a0(Jun 16, 2022)

    Dependency Upgrades:

    JPype1 upgraded to 1.4.0, which fixes ambiguity errors when dealing with overloaded methods

    New Features:

    • get_class is not longer required when interacting with SolverConfig and Constraint Streams
    • Pythonic version of Constraint Stream, Joiners, and ConstraintCollectors methods
    • New decorators @custom_shadow_variable and @variable_listener, which can be used to create a custom shadow variable that changes when a geninue @planning_variable (or another shadow variable) changes.
    Source code(tar.gz)
    Source code(zip)
  • 8.19.0a1(May 17, 2022)

    • Remove memory leak caused by old best solution being retained until solving finishes
    • Add support for tuple and set collections, and collections that extend the collection.abc abstract base classes
    • Allow group by keys to be interacted with like normal python objects
    Source code(tar.gz)
    Source code(zip)
  • 8.19.0a0(Mar 29, 2022)

    New Features:

    • Ability to load a SolverConfig via XML from solver_config_create_from_xml_file(pathlib.Path)
    • Can modify the log level of optapy at runtime with logging

    Fixed Bugs:

    • Logback configuration logs will no longer appear
    Source code(tar.gz)
    Source code(zip)
  • 8.17.0a0(Mar 8, 2022)

    • New decorator @planning_list_variable, which can be used to model variables as an ordered disjoint set (for example, the customers to visit in vehicle routing).
    • Support for @problem_change, which allows changing the problem during solving.
    • List available subpackages in optapy.config, validate collection decorators.
    Source code(tar.gz)
    Source code(zip)
  • 8.16.1a0(Feb 9, 2022)

    • Upgrade OptaPlanner version to 8.16.1.Final
    • Add @easy_score_calculator decorator
    • Add @incremental_score_calculator decorator
    • Fix bug in ScoreManager that causes an exception in concurrent requests in different threads
    • Add SolverStatus to optapy.types
    Source code(tar.gz)
    Source code(zip)
  • 8.14.0a0(Dec 17, 2021)

    New Features:

    • All Python Types are supported in Joiners/ConstraintCollectors/etc, so that TypeError now never happens. If you happen to return a bad type in a method that expects a particular type (ex: returning a str instead of a bool in a filter), a TypeError will be raised with some general helping info
    • The following API from OptaPlanner have been exposed: SolverFactory, SolverManager, ScoreManager (which can be accessed via solver_factory_create, solver_manager_create, score_manager_create).
    • The following annotations from OptaPlanner been exposed as annotations: @anchor_shadow_variable, @inverse_relation_shadow_variable, @planning_pin; pinning_filter is also now available as an optional value that can be defined on @planning_entity
    • SolverFactory is for blocking solving, SolverManager is for asynchronously solving, ScoreManager is to get the score and violated constraints without solving.
    • Type stubs have been added via stubgenj

    Deprecations:

    • from have been deprecated in OptaPlanner (from_ in OptaPy) due to its semantics changing depending on if over-constrained planning is used. Now use forEach/forEachIncludingNullVars instead, which has consistent semantics in both regular and over-constrained planning.

    Breaking Changes:

    • solve as a global function has been removed from OptaPy as there is no equivalent static method in OptaPlanner yet. Replace solve(solver_config, problem) with solver_factory_create(solver_config).buildSolver().solve(problem).
    Source code(tar.gz)
    Source code(zip)
  • 8.11.0a2(Oct 7, 2021)

  • 8.11.0a1(Sep 16, 2021)

  • 8.11.0a0(Sep 16, 2021)

Owner
OptaPy
Python module for OptaPlanner (Alpha)
OptaPy
PaddleRobotics is an open-source algorithm library for robots based on Paddle, including open-source parts such as human-robot interaction, complex motion control, environment perception, SLAM positioning, and navigation.

简体中文 | English PaddleRobotics paddleRobotics是基于paddle的机器人开源算法库集,包括人机交互、复杂运动控制、环境感知、slam定位导航等开源算法部分。 人机交互 主动多模交互技术TFVT-HRI 主动多模交互技术是通过视觉、语音、触摸传感器等输入机器人

185 Dec 26, 2022
Flower - A Friendly Federated Learning Framework

Flower - A Friendly Federated Learning Framework Flower (flwr) is a framework for building federated learning systems. The design of Flower is based o

Adap 1.8k Jan 01, 2023
Prometheus Exporter for data scraped from datenplattform.darmstadt.de

darmstadt-opendata-exporter Scrapes data from https://datenplattform.darmstadt.de and presents it in the Prometheus Exposition format. Pull requests w

Martin Weinelt 2 Apr 12, 2022
A hybrid framework (neural mass model + ML) for SC-to-FC prediction

The current workflow simulates brain functional connectivity (FC) from structural connectivity (SC) with a neural mass model. Gradient descent is applied to optimize the parameters in the neural mass

Yilin Liu 1 Jan 26, 2022
Pytorch implementation of

EfficientTTS Unofficial Pytorch implementation of "EfficientTTS: An Efficient and High-Quality Text-to-Speech Architecture"(arXiv). Disclaimer: Somebo

Liu Songxiang 109 Nov 16, 2022
Chinese Advertisement Board Identification(Pytorch)

Chinese-Advertisement-Board-Identification. We use YoloV5 to extract the ROI of the location of the chinese word. Next, we sort the bounding box and recognize every chinese words which we extracted.

Li-Wei Hsiao 12 Jul 21, 2022
VQGAN+CLIP Colab Notebook with user-friendly interface.

VQGAN+CLIP and other image generation system VQGAN+CLIP Colab Notebook with user-friendly interface. Latest Notebook: Mse regulized zquantize Notebook

Justin John 227 Jan 05, 2023
AI that generate music

PianoGPT ai that generate music try it here https://share.streamlit.io/annasajkh/pianogpt/main/main.py or here https://huggingface.co/spaces/Annas/Pia

Annas 28 Nov 27, 2022
This repository contains the source codes for the paper AtlasNet V2 - Learning Elementary Structures.

AtlasNet V2 - Learning Elementary Structures This work was build upon Thibault Groueix's AtlasNet and 3D-CODED projects. (you might want to have a loo

Théo Deprelle 123 Nov 11, 2022
Code for the paper "Training GANs with Stronger Augmentations via Contrastive Discriminator" (ICLR 2021)

Training GANs with Stronger Augmentations via Contrastive Discriminator (ICLR 2021) This repository contains the code for reproducing the paper: Train

Jongheon Jeong 174 Dec 29, 2022
Multi-Modal Machine Learning toolkit based on PyTorch.

简体中文 | English TorchMM 简介 多模态学习工具包 TorchMM 旨在于提供模态联合学习和跨模态学习算法模型库,为处理图片文本等多模态数据提供高效的解决方案,助力多模态学习应用落地。 近期更新 2022.1.5 发布 TorchMM 初始版本 v1.0 特性 丰富的任务场景:工具

njustkmg 1 Jan 05, 2022
Place holder for HOPE: a human-centric and task-oriented MT evaluation framework using professional post-editing

HOPE: A Task-Oriented and Human-Centric Evaluation Framework Using Professional Post-Editing Towards More Effective MT Evaluation Place holder for dat

Lifeng Han 1 Apr 25, 2022
Experimental Python implementation of OpenVINO Inference Engine (very slow, limited functionality). All codes are written in Python. Easy to read and modify.

PyOpenVINO - An Experimental Python Implementation of OpenVINO Inference Engine (minimum-set) Description The PyOpenVINO is a spin-off product from my

Yasunori Shimura 7 Oct 31, 2022
Diagnostic tests for linguistic capacities in language models

LM diagnostics This repository contains the diagnostic datasets and experimental code for What BERT is not: Lessons from a new suite of psycholinguist

61 Jan 02, 2023
A PyTorch implementation of "Signed Graph Convolutional Network" (ICDM 2018).

SGCN ⠀ A PyTorch implementation of Signed Graph Convolutional Network (ICDM 2018). Abstract Due to the fact much of today's data can be represented as

Benedek Rozemberczki 251 Nov 30, 2022
Implementation for Panoptic-PolarNet (CVPR 2021)

Panoptic-PolarNet This is the official implementation of Panoptic-PolarNet. [ArXiv paper] Introduction Panoptic-PolarNet is a fast and robust LiDAR po

Zixiang Zhou 126 Jan 01, 2023
The official project of SimSwap (ACM MM 2020)

SimSwap: An Efficient Framework For High Fidelity Face Swapping Proceedings of the 28th ACM International Conference on Multimedia The official reposi

Six_God 2.6k Jan 08, 2023
Code for Emergent Translation in Multi-Agent Communication

Emergent Translation in Multi-Agent Communication PyTorch implementation of the models described in the paper Emergent Translation in Multi-Agent Comm

Facebook Research 75 Jul 15, 2022
official Pytorch implementation of ICCV 2021 paper FuseFormer: Fusing Fine-Grained Information in Transformers for Video Inpainting.

FuseFormer: Fusing Fine-Grained Information in Transformers for Video Inpainting By Rui Liu, Hanming Deng, Yangyi Huang, Xiaoyu Shi, Lewei Lu, Wenxiu

77 Dec 27, 2022
CityLearn Challenge Multi-Agent Reinforcement Learning for Intelligent Energy Management, 2020, PikaPika team

Citylearn Challenge This is the PyTorch implementation for PikaPika team, CityLearn Challenge Multi-Agent Reinforcement Learning for Intelligent Energ

bigAIdream projects 10 Oct 10, 2022