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: str)[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).

Type: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
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]]
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
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
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
_generate

True if the solver needs to be generated

Type:bool
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.
  • driver (Driver) – driver used to load the solver configuration. If set to None, then default_driver will be used.
Returns:

MiniZinc solver configuration compatible with the driver.

Return type:

Solver

Raises:
classmethod lookup(tag: str, driver=None)[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.
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
__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 = 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.
add_string(code: str) → None[source]

Adds a string of MiniZinc code to the Model.

Parameters:code (str) – A string contain MiniZinc code
class minizinc.model.Checker(path: pathlib.Path)[source]

An interface to a MiniZinc solution checker

checker

The file path to the solution checker file.

Type:Path
check(solution) → str[source]

Check the Solution object using Checker

This method runs the Checker model on the solution provided. The output from the checker model is returned as a string.

Parameters:solution (Union[Solution, Mapping[str, Any]]) – The solution given to the checker

Instances

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

Abstract representation of a MiniZinc instance in Python.

branch()[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
method

Query the Method used by the Instance.

Returns:Method of the goal used by the Instance.
Return type:Method
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, ignore_errors=False, **kwargs)[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:Tuple[Status, Optional[Dict], Dict] – tuple containing 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, **kwargs)[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)
  • **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, **kwargs)[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.
class minizinc.CLI.CLIInstance(solver: minizinc.solver.Solver, model: Optional[minizinc.model.Model] = None, driver: Optional[minizinc.CLI.driver.CLIDriver] = None)[source]
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.
add_string(code: str) → None[source]

Adds a string of MiniZinc code to the Model.

Parameters:code (str) – A string contain MiniZinc code
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, **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.
  • **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.
Yields:

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

method

Query the Method used by the Instance.

Returns:Method of the goal used by the Instance.
Return type:Method
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, ignore_errors=False, **kwargs)[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:Tuple[Status, Optional[Dict], Dict] – tuple containing solving status, values assigned, and statistical information.
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, **kwargs)[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.

Utilities

minizinc.find_driver(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 the MiniZinc API or 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 API or executable.
Returns:

Returns a Driver object when found or None.

Return type:

Optional[Driver]

Drivers

class minizinc.driver.Driver[source]

The abstract representation of a MiniZinc driver within MiniZinc Python.

check_version() → None[source]

Raises an error if the MiniZinc version is incompatible with MiniZinc Python.

Raises:ConfigurationError – An error noting the discrepancy between the required version of MiniZinc and the version of MiniZinc found.
make_default() → None[source]

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

minizinc_version

Reports the version of the MiniZinc Driver

Report the full version 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
class minizinc.CLI.CLIDriver(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.

executable

The path to the executable used to access the MiniZinc Driver

Type:Path
check_version()[source]

Raises an error if the MiniZinc version is incompatible with MiniZinc Python.

Raises:ConfigurationError – An error noting the discrepancy between the required version of MiniZinc and the version of MiniZinc found.
make_default() → None[source]

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

minizinc_version

Reports the version of the MiniZinc Driver

Report the full version 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

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], line: int = 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.MiniZincAssertionError(location: Optional[minizinc.error.Location] = None, message: str = '')[source]

Exception raised for MiniZinc assertions that failed during instance evaluation

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

Exception raised for type errors found in an MiniZinc Instance

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

Exception raised for syntax errors found in an MiniZinc Instance