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
A public available dataset for road boundary detection in aerial images

Topo-boundary This is the official github repo of paper Topo-boundary: A Benchmark Dataset on Topological Road-boundary Detection Using Aerial Images

Zhenhua Xu 79 Jan 04, 2023
Notebook and code to synthesize complex and highly dimensional datasets using Gretel APIs.

Gretel Trainer This code is designed to help users successfully train synthetic models on complex datasets with high row and column counts. The code w

Gretel.ai 24 Nov 03, 2022
Simple tutorials on Pytorch DDP training

pytorch-distributed-training Distribute Dataparallel (DDP) Training on Pytorch Features Easy to study DDP training You can directly copy this code for

Ren Tianhe 188 Jan 06, 2023
Implementation of Heterogeneous Graph Attention Network

HetGAN Implementation of Heterogeneous Graph Attention Network This is the code repository of paper "Prediction of Metro Ridership During the COVID-19

5 Dec 28, 2021
Code for the paper "Ordered Neurons: Integrating Tree Structures into Recurrent Neural Networks"

ON-LSTM This repository contains the code used for word-level language model and unsupervised parsing experiments in Ordered Neurons: Integrating Tree

Yikang Shen 572 Nov 21, 2022
This code is an unofficial implementation of HiFiSinger.

HiFiSinger This code is an unofficial implementation of HiFiSinger. The algorithm is based on the following papers: Chen, J., Tan, X., Luan, J., Qin,

Heejo You 87 Dec 23, 2022
PhysCap: Physically Plausible Monocular 3D Motion Capture in Real Time

PhysCap: Physically Plausible Monocular 3D Motion Capture in Real Time The implementation is based on SIGGRAPH Aisa'20. Dependencies Python 3.7 Ubuntu

soratobtai 124 Dec 08, 2022
Super Resolution for images using deep learning.

Neural Enhance Example #1 — Old Station: view comparison in 24-bit HD, original photo CC-BY-SA @siv-athens. As seen on TV! What if you could increase

Alex J. Champandard 11.7k Dec 29, 2022
Code repository for the work "Multi-Domain Incremental Learning for Semantic Segmentation", accepted at WACV 2022

Multi-Domain Incremental Learning for Semantic Segmentation This is the Pytorch implementation of our work "Multi-Domain Incremental Learning for Sema

Pgxo20 24 Jan 02, 2023
FCOSR: A Simple Anchor-free Rotated Detector for Aerial Object Detection

FCOSR: A Simple Anchor-free Rotated Detector for Aerial Object Detection FCOSR: A Simple Anchor-free Rotated Detector for Aerial Object Detection arXi

59 Nov 29, 2022
A small fun project using python OpenCV, mediapipe, and pydirectinput

Here I tried a small fun project using python OpenCV, mediapipe, and pydirectinput. Here we can control moves car game when yellow color come to right box (press key 'd') left box (press key 'a') lef

Sameh Elisha 3 Nov 17, 2022
My freqtrade strategies

My freqtrade-strategies Hi there! This is repo for my freqtrade-strategies. My name is Ilya Zelenchuk, I'm a lecturer at the SPbU university (https://

171 Dec 05, 2022
Official implementation of Neural Bellman-Ford Networks (NeurIPS 2021)

NBFNet: Neural Bellman-Ford Networks This is the official codebase of the paper Neural Bellman-Ford Networks: A General Graph Neural Network Framework

MilaGraph 136 Dec 21, 2022
A module that used for encrypt code which includes RSA and AES

软件加密模块 requirement: Crypto,pycryptodome,pyqt5 本地加密信息为随机字符串 使用说明 命令行参数 -h 帮助 -checkWorking 检查是否能正常工作,后接1确认指令 -checkEndDate 检查截至日期,后接1确认指令 -activateCode

2 Sep 27, 2022
Registration Loss Learning for Deep Probabilistic Point Set Registration

RLLReg This repository contains a Pytorch implementation of the point set registration method RLLReg. Details about the method can be found in the 3DV

Felix Järemo Lawin 35 Nov 02, 2022
YOLOv3 in PyTorch > ONNX > CoreML > TFLite

This repository represents Ultralytics open-source research into future object detection methods, and incorporates lessons learned and best practices

Ultralytics 9.3k Jan 07, 2023
This PyTorch package implements MoEBERT: from BERT to Mixture-of-Experts via Importance-Guided Adaptation (NAACL 2022).

MoEBERT This PyTorch package implements MoEBERT: from BERT to Mixture-of-Experts via Importance-Guided Adaptation (NAACL 2022). Installation Create an

Simiao Zuo 34 Dec 24, 2022
This is the repository of shape matching algorithm Iterative Rotations and Assignments (IRA)

Description This is the repository of shape matching algorithm Iterative Rotations and Assignments (IRA), described in the publication [1]. Directory

MAMMASMIAS Consortium 6 Nov 14, 2022
Shape-Adaptive Selection and Measurement for Oriented Object Detection

Source Code of AAAI22-2171 Introduction The source code includes training and inference procedures for the proposed method of the paper submitted to t

houliping 24 Nov 29, 2022
[CVPR 2021] Teachers Do More Than Teach: Compressing Image-to-Image Models (CAT)

CAT arXiv Pytorch implementation of our method for compressing image-to-image models. Teachers Do More Than Teach: Compressing Image-to-Image Models Q

Snap Research 160 Dec 09, 2022