API

This part of the documentation lists the full API reference of all public classes and functions.

Solvers

class minizinc.solver.Solver(name: str, version: str, id: str, executable: Optional[str] = None, mznlib: str = '', mznlibVersion: int = 1, description: str = '', tags: List[str] = <factory>, stdFlags: List[str] = <factory>, extraFlags: List[Tuple[str, str, str, str]] = <factory>, requiredFlags: List[str] = <factory>, inputType: str = 'FZN', supportsMzn: bool = False, supportsFzn: bool = True, supportsNL: bool = False, needsSolns2Out: bool = False, needsMznExecutable: bool = False, needsStdlibDir: bool = False, needsPathsFile: bool = False, isGUIApplication: bool = False, _identifier: Optional[str] = None)[source]

The representation of a MiniZinc solver configuration in MiniZinc Python.

name

The name of the solver.

Type:str
version

The version of the solver.

Type:str
id

A unique identifier for the solver, “reverse domain name” notation.

Type:str
executable

The executable for this solver that can run FlatZinc files. This can be just a file name (in which case the solver has to be on the current $PATH), or an absolute path to the executable, or a relative path (which is interpreted relative to the location of the configuration file). This attribute is set to None if the solver is integrated into MiniZinc.

Type:Optional[str]
mznlib

The solver-specific library of global constraints and redefinitions. This should be the name of a directory (either an absolute path or a relative path, interpreted relative to the location of the configuration file). For solvers whose libraries are installed in the same location as the MiniZinc standard library, this can also take the form -G, e.g., -Ggecode (this is mostly the case for solvers that ship with the MiniZinc binary distribution).

Type:str
mznlibVersion

Currently undocumented in the MiniZinc documentation.

Type:int
description

Currently undocumented in the MiniZinc documentation.

Type:str
tags

Each solver can have one or more tags that describe its features in an abstract way. Tags can be used for selecting a solver using the –solver option. There is no fixed list of tags, however we recommend using the following tags if they match the solver’s behaviour: - cp: for Constraint Programming solvers - mip: for Mixed Integer Programming solvers - float: for solvers that support float variables - api: for solvers that use the internal C++ API

Type:List[str]
stdFlags

Which of the standard solver command line flags are supported by this solver. The standard flags are -a, -n, -s, -v, -p, -r, -f.

Type:List[str]
extraFlags

Extra command line flags supported by the solver. Each entry must be a tuple of four strings. The first string is the name of the option (e.g. --special-algorithm). The second string is a description that can be used to generate help output (e.g. “which special algorithm to use”). The third string specifies the type of the argument (int, bool, float or string). The fourth string is the default value.

Type:List[Tuple[str,str,str,str]]
requiredFlags

Currently undocumented in the MiniZinc documentation.

Type:List[str]
supportsMzn

Whether the solver can run MiniZinc directly (i.e., it implements its own compilation or interpretation of the model).

Type:bool
supportsFzn

Whether the solver can run FlatZinc. This should be the case for most solvers.

Type:bool
supportsNL

Whether the solver conforms to the AMPL NL standard. The NL format is used if supportsFZN is False.

Type:bool
needsSolns2Out

Whether the output of the solver needs to be passed through the MiniZinc output processor.

Type:bool
needsMznExecutable

Whether the solver needs to know the location of the MiniZinc executable. If true, it will be passed to the solver using the mzn-executable option.

Type:bool
needsStdlibDir

Whether the solver needs to know the location of the MiniZinc standard library directory. If true, it will be passed to the solver using the stdlib-dir option.

Type:bool
needsPathsFile

Currently undocumented in the MiniZinc documentation.

Type:bool
isGUIApplication

Whether the solver has its own graphical user interface, which means that MiniZinc will detach from the process and not wait for it to finish or to produce any output.

Type:bool
_identifier

A string to specify the solver to MiniZinc driver. If set to None, then a solver configuration file should be generated.

Type:Optional[str]
configuration() → Iterator[str][source]

Gives the identifier for the current solver configuration.

Gives an identifier argument that can be used by a CLIDriver to identify the solver configuration. If the configuration was loaded using the driver and is thus already known, then the identifier will be yielded. If the configuration was changed or started from scratch, the configuration will be saved to a file and it will yield the name of the file.

Yields:str – solver identifier to be used for the --solver <id> flag.
classmethod load(path: pathlib.Path)[source]

Loads a solver configuration from a file.

Load solver configuration from a MiniZinc solver configuration given by the file on the given location.

Parameters:

path (str) – location to the solver configuration file to be loaded.

Returns:

MiniZinc solver configuration compatible with the driver.

Return type:

Solver

Raises:
classmethod lookup(tag: str, driver=None, refresh=False)[source]

Lookup a solver configuration in the driver registry.

Access the MiniZinc driver’s known solver configuration and find the configuation matching the given tag. Tags are matched in similar to minizinc --solver tag. The order of solver configuration attributes that are considered is: full id, id ending, tags.

Parameters:
  • tag (str) – tag (or id) of a solver configuration to look up.
  • driver (Driver) – driver which registry will be searched for the solver. If set to None, then default_driver will be used.
  • refresh (bool) – Forces the driver to refresh the cache of available solvers.
Returns:

MiniZinc solver configuration compatible with the driver.

Return type:

Solver

Raises:

LookupError – No configuration could be located with the given tag.

output_configuration() → str[source]

Formulates a valid JSON specification for the Solver

Formulates a JSON specification of the solver configuration meant to be used by MiniZinc. When stored in a .msc file it can be used directly as a argument to the --solver flag or stored on the MiniZinc solver configuration path. In the latter case it will be usable directly from the executable and visible when in minizinc --solvers.

Returns:
JSON string containing the solver specification that can be
read by MiniZinc
Return type:str

Models

class minizinc.model.Method[source]

Enumeration that represents of a solving method.

SATISFY

Represents a satisfaction problem.

MINIMIZE

Represents a minimization problem.

MAXIMIZE

Represents a maximization problem.

class minizinc.model.Model(files: Union[pathlib.Path, str, List[Union[pathlib.Path, str]], None] = None)[source]

The representation of a MiniZinc model in Python

output_type

the type used to store the solution values created in the process of solving the Instance. This attribute is particularly helpful when comparing the results of multiple instances together. The type must support initialisation with the assignments returned by MiniZinc. These assignments currently always include “__output_item” and include “objective” if the instance is not a satisfaction problem.

Type:Type
Raises:MiniZincError – when an error occurs during the parsing or type checking of the model object.
__getitem__(key: str) → Any[source]

Get parameter of Model.

This method overrides the default implementation of item access (obj[key]) for models. Item access on a Model can be used to get parameters of the Model.

Parameters:key (str) – Identifier of the parameter.
Returns:The value assigned to the parameter.
Raises:KeyError – The parameter you are trying to access is not known.
__setitem__(key: str, value: Any)[source]

Set parameter of Model.

This method overrides the default implementation of item access (obj[key] = value) for models. Item access on a Model can be used to set parameters of the Model.

Parameters:
  • key (str) – Identifier of the parameter.
  • value (Any) – Value to be assigned to the parameter.
add_file(file: Union[pathlib.Path, str], parse_data: bool = False) → None[source]

Adds a MiniZinc file (.mzn, .dzn, or .json) to the Model.

Parameters:
  • file (Union[Path, str]) – Path to the file to be added
  • parse_data (bool) – Signal if the data should be parsed for usage within Python. This option is ignored if the extra dzn is not enabled.
Raises:

MiniZincError – when an error occurs during the parsing or type checking of the model object.

add_string(code: str) → None[source]

Adds a string of MiniZinc code to the Model.

Parameters:code (str) – A string contain MiniZinc code
Raises:MiniZincError – when an error occurs during the parsing or type checking of the model object.

Instances

class minizinc.instance.Instance(solver: minizinc.solver.Solver, model: Optional[minizinc.model.Model] = None, driver: Optional[minizinc.driver.Driver] = None)[source]

Representation of a MiniZinc instance in Python.

Raises:MiniZincError – when an error occurs during the parsing or type checking of the model object.
add_file(file: Union[pathlib.Path, str], parse_data: bool = True) → None[source]

Adds a MiniZinc file (.mzn, .dzn, or .json) to the Model.

Parameters:
  • file (Union[Path, str]) – Path to the file to be added
  • parse_data (bool) – Signal if the data should be parsed for usage within Python. This option is ignored if the extra dzn is not enabled.
Raises:

MiniZincError – when an error occurs during the parsing or type checking of the model object.

add_string(code: str) → None[source]

Adds a string of MiniZinc code to the Model.

Parameters:code (str) – A string contain MiniZinc code
Raises:MiniZincError – when an error occurs during the parsing or type checking of the model object.
analyse()[source]

Discovers basic information about a CLIInstance

Analyses a given instance and discovers basic information about set model such as the solving method, the input parameters, and the output parameters. The information found will be stored among the attributes of the instance.

branch() → Iterator[minizinc.instance.Instance][source]

Create a branch of the current instance

Branches from the current instance and yields a child instance. Any changes made to the child instance can not influence the current instance. WARNING: The branch method assumes that no changes will be made to the parent method while the child instance is still alive. Changes to the parent model are locked until the child method are destroyed.

Yields:Instance – branched child instance
files() → Iterator[List[pathlib.Path]][source]

Gets list of files of the Instance

Files will create a list of paths to the files that together form the Instance. Parts of the Instance might be saved to files and are only guaranteed to exist while within the created context.

Yields:List of Path objects to existing and created files
flat(timeout: Optional[datetime.timedelta] = None, optimisation_level: Optional[int] = None, **kwargs)[source]

Produce a FlatZinc file for the instance.

Parameters:
  • timeout (Optional[timedelta]) – Set the time limit for the process of flattening the instance. TODO: An exception is raised if the timeout is reached.
  • optimisation_level (Optional[int]) –

    Set the MiniZinc compiler optimisation level.

    • 0: Disable optimisation
    • 1: Single pass optimisation (default)
    • 2: Flatten twice to improve flattening decisions
    • 3: Perform root-node-propagation
    • 4: Probe bounds of all variables at the root node
    • 5: Probe values of all variables at the root node
  • **kwargs – Other flags to be passed to the compiler. -- can be omitted in the name of the flag. If the type of the flag is Boolean, then its value signifies its occurrence.
Yields:

Tuple containing the files of the FlatZinc model, the output model and a dictionary the statistics of flattening

input

Query the input parameters of the Instance.

Returns:A mapping from parameter identifiers to their Types.
Return type:Dict[str, Type]
method

Query the Method used by the Instance.

Returns:Method of the goal used by the Instance.
Return type:Method
output

Query the output parameters of the Instance.

Returns:A mapping from parameter identifiers to their Types.
Return type:Dict[str, Type]
solutions(timeout: Optional[datetime.timedelta] = None, nr_solutions: Optional[int] = None, processes: Optional[int] = None, random_seed: Optional[int] = None, all_solutions=False, intermediate_solutions=False, free_search: bool = False, optimisation_level: Optional[int] = None, verbose: bool = False, debug_output: Optional[pathlib.Path] = None, **kwargs) → AsyncIterator[minizinc.result.Result][source]

An asynchronous generator for solutions of the MiniZinc instance.

This method provides an asynchronous generator for the solutions of the MiniZinc instance. Every (intermediate) solution is yielded one at a time, the last item yielded from the generator will not contain a new solution, but will return the final Status and all remaining statistical values. For more information regarding this methods and its arguments, see the documentation of solve().

Yields:Result – A Result object containing the current solving status, values assigned, and statistical information.
solve(timeout: Optional[datetime.timedelta] = None, nr_solutions: Optional[int] = None, processes: Optional[int] = None, random_seed: Optional[int] = None, all_solutions: bool = False, intermediate_solutions: bool = False, free_search: bool = False, optimisation_level: Optional[int] = None, **kwargs) → minizinc.result.Result[source]

Solves the Instance using its given solver configuration.

Find the solutions to the given MiniZinc instance using the given solver configuration. First, the Instance will be ensured to be in a state where the solver specified in the solver configuration can understand the problem and then the solver will be requested to find the appropriate solution(s) to the problem.

Parameters:
  • timeout (Optional[timedelta]) – Set the time limit for the process of solving the instance.
  • nr_solutions (Optional[int]) – The requested number of solution. (Only available on satisfaction problems and when the -n flag is supported by the solver).
  • processes (Optional[int]) – Set the number of processes the solver can use. (Only available when the -p flag is supported by the solver).
  • random_seed (Optional[int]) – Set the random seed for solver. (Only available when the -r flag is supported by the solver).
  • free_search (bool) – Allow the solver to ignore the search definition within the instance. (Only available when the -f flag is supported by the solver).
  • all_solutions (bool) – Request to solver to find all solutions. (Only available on satisfaction problems and when the -a flag is supported by the solver)
  • intermediate_solutions (bool) – Request the solver to output any intermediate solutions that are found during the solving process. (Only available on optimisation problems and when the -a flag is supported by the solver)
  • optimisation_level (Optional[int]) –

    Set the MiniZinc compiler optimisation level.

    • 0: Disable optimisation
    • 1: Single pass optimisation (default)
    • 2: Flatten twice to improve flattening decisions
    • 3: Perform root-node-propagation
    • 4: Probe bounds of all variables at the root node
    • 5: Probe values of all variables at the root node
  • **kwargs – Other flags to be passed onto the solver. -- can be omitted in the name of the flag. If the type of the flag is Boolean, then its value signifies its occurrence.
Returns:

tuple containing solving status, values assigned in the solution, and statistical information. If no solutions is found the second member of the tuple is None.

Return type:

Tuple[Status, Optional[Union[List[Dict], Dict]], Dict]

Raises:

MiniZincError – An error occurred while compiling or solving the model instance.

solve_async(timeout: Optional[datetime.timedelta] = None, nr_solutions: Optional[int] = None, processes: Optional[int] = None, random_seed: Optional[int] = None, all_solutions=False, intermediate_solutions=False, free_search: bool = False, optimisation_level: Optional[int] = None, **kwargs) → minizinc.result.Result[source]

Solves the Instance using its given solver configuration in a coroutine.

This method returns a coroutine that finds solutions to the given MiniZinc instance. For more information regarding this methods and its arguments, see the documentation of solve().

Returns:tuple containing solving status, values assigned, and statistical information.
Return type:Tuple[Status, Optional[Union[List[Dict], Dict]], Dict]
Raises:MiniZincError – An error occurred while compiling or solving the model instance.

Results

class minizinc.result.Result(status: minizinc.result.Status, solution: Any, statistics: Dict[str, Union[float, int, datetime.timedelta]])[source]

Representation of a MiniZinc solution in Python

status

The solving status of the MiniZinc instance

Type:Status
solution

Variable assignments made to form the solution

Type:Any
statistics

Statistical information generated during the search for the Solution

Type:Dict[str, Union[float, int, timedelta]]
__getitem__(key)[source]

Retrieves solution or a member of a solution.

Overrides the default implementation of item access (obj[key]) to retrieve a solution object or member of a solution from the result object.

  • If the Result object does not contain any solutions, then a KeyError will always be raised.
  • If the Result object contains a single solutions, then the names of a variable can be used in this method to retrieve its value in the solution.
  • If the Result object contains multiple solutions, then a single integer can be used to retrieve the solution object or a tuple of an integer and the name of a variable can be used to retrieve the value of that variable in the numbered solution object.
Parameters:key – solution number or name of the solution member.
Returns:Solution object or the value of the member in the solution.
Raises:KeyError – No solution was found, solution number is out of range, or no solution member with this name exists.
__len__()[source]

Returns the number of solutions included in the Result object

Returns:number of solution that can be accessed
Return type:int
objective

Returns objective of the solution

Returns the objective of the solution when possible. If no solutions have been found or the problem did not have an objective, then None is returned instead.

Returns:best objective found or None
Return type:Optional[Union[int, float]]
class minizinc.result.Status[source]

Enumeration to represent the status of the solving process.

ERROR

An error occurred during the solving process.

UNKNOWN

No solutions have been found and search has terminated without exploring the whole search space.

UNBOUNDED

The objective of the optimisation problem is unbounded.

UNSATISFIABLE

No solutions have been found and the whole search space was explored.

SATISFIED

A solution was found, but possibly not the whole search space was explored.

ALL_SOLUTIONS

All solutions in the search space have been found.

OPTIMAL_SOLUTION

A solution has been found that is optimal according to the objective.

has_solution() → bool[source]

Returns true if the status suggest that a solution has been found.

Drivers

class minizinc.driver.Driver(executable: pathlib.Path)[source]

Driver that interfaces with MiniZinc through the command line interface.

The command line driver will interact with MiniZinc and its solvers through the use of a minizinc executable. Driving MiniZinc using its executable is non-incremental and can often trigger full recompilation and might restart the solver from the beginning when changes are made to the instance.

Raises:ConfigurationError – If an the driver version is found to be incompatible with MiniZinc Python
_executable

The path to the executable used to access the MiniZinc

Type:Path
available_solvers(refresh=False)[source]

Returns a list of available solvers

This method returns the list of solvers available to the Driver object according to the current environment. Note that the list of solvers might be cached for future usage. The refresh argument can be used to ignore the current cache.

Parameters:refresh (bool) – When set to true, the Driver will rediscover the available solvers from the current environment.
Returns:
A dictionary that maps solver tags to MiniZinc
solver configurations that can be used with the Driver object.
Return type:Dict[str, List[Solver]]
executable

Reports the Path of the MiniZinc executable used by the Driver object

Returns:location of the MiniZinc executable
Return type:Path
classmethod find(path: Optional[List[str]] = None, name: str = 'minizinc') → Optional[minizinc.driver.Driver][source]

Finds MiniZinc Driver on default or specified path.

Find driver will look for the MiniZinc executable to create a Driver for MiniZinc Python. If no path is specified, then the paths given by the environment variables appended by MiniZinc’s default locations will be tried.

Parameters:
  • path – List of locations to search.
  • name – Name of the executable.
Returns:

Returns a Driver object when found or None.

Return type:

Optional[Driver]

make_default() → None[source]

Method to override the current default MiniZinc Python driver with the current driver.

minizinc_version

Reports the version text of the MiniZinc Driver

Report the full version text of MiniZinc as reported by the driver, including the driver name, the semantic version, the build reference, and its authors.

Returns:the version of as reported by the MiniZinc driver
Return type:str
parsed_version

Reports the version of the MiniZinc Driver

Report the parsed version of the MiniZinc Driver as a tuple of integers. The tuple is ordered: major, minor, patch.

Returns:the parsd version reported by the MiniZinc driver
Return type:Tuple[int, ..]

Errors

exception minizinc.error.ConfigurationError[source]

Exception raised during the configuration of MiniZinc

message

Explanation of the error

Type:str
minizinc.error.parse_error(error_txt: bytes) → minizinc.error.MiniZincError[source]

Parse error from bytes array (raw string)

Parse error scans the output from a MiniZinc driver to generate the appropriate MiniZincError. It will make the distinction between different kinds of errors as found by MiniZinc and tries to parse the relevant information to the error. The different kinds of errors are represented by different sub-classes of MiniZincError.

Parameters:error_txt (bytes) – raw string containing a MiniZinc error. Generally this should be the error stream of a driver.
Returns:An error generated from the string
exception minizinc.error.MiniZincError(location: Optional[minizinc.error.Location] = None, message: str = '')[source]

Exception raised for errors caused by a MiniZinc Driver

location

File location of the error

Type:Optional[Location]
message

Explanation of the error

Type:str
class minizinc.error.Location(file: Optional[pathlib.Path], lines: Tuple[int, int] = (0, 0), columns: Tuple[int, int] = (0, 0))[source]

Representation of a location within a file

file

Path to the file

Type:Optional[Path]
line

Line within the file (default: 0)

Type:int
columns

Columns on the line, from/to (default: (0, 0))

Type:Tuple[int,int]
exception minizinc.error.EvaluationError(location: Optional[minizinc.error.Location] = None, message: str = '')[source]

Exception raised for errors due to an error during instance evaluation by the MiniZinc Driver

exception minizinc.error.AssertionError(location: Optional[minizinc.error.Location] = None, message: str = '')[source]

Exception raised for MiniZinc assertions that failed during instance evaluation

exception minizinc.error.TypeError(location: Optional[minizinc.error.Location] = None, message: str = '')[source]

Exception raised for type errors found in an MiniZinc Instance

exception minizinc.error.SyntaxError(location: Optional[minizinc.error.Location] = None, message: str = '')[source]

Exception raised for syntax errors found in an MiniZinc Instance

Helper Functions

minizinc.helpers.check_result(model: minizinc.model.Model, result: minizinc.result.Result, solver: minizinc.solver.Solver, solution_nrs: Optional[Sequence[int]] = None) → bool[source]

Checks a result object for a model using the given solver.

Check the correctness of the solving process using a (different) solver configuration. The solver configuration is now used to confirm is assignment of the variables is correct. By default only the last solution will be checked. A sequence of solution numbers can be provided to check multiple solutions.

Parameters:
  • model (Model) – To model for which the solution was provided
  • result (Result) – The solution to be checked
  • solver (Solver) – The solver configuration used to check the solutions.
  • solution_nrs – The index set of solutions to be checked. (default: -1)
Returns:

True if the given result object is correctly verified.

Return type:

bool

minizinc.helpers.check_solution(model: minizinc.model.Model, solution: Union[Any, Dict[str, Any]], status: minizinc.result.Status, solver: minizinc.solver.Solver) → bool[source]

Checks a solution for a model using the given solver.

Check the correctness of the solving process using a (different) solver configuration. A new model instance is created and will be assigned all available values from the given solution. The Instance.solve() method is then used to ensure that the same solution with the same expected status is reached. Note that this method will not check the optimality of a solution.

Parameters:
  • model (Model) – To model for which the solution was provided
  • solution (Union[DataClass, Dict[str, Any]]) – The solution to be checked
  • status (Status) – The expected (compatible) MiniZinc status
  • solver (Solver) – The solver configuration used to check the solution.
Returns:

True if the given solution are correctly verified.

Return type:

bool