System Black Box

The BlackBox modules provides utilities to run external scripts and programs in a constrained environment and parse the result.

class optilog.blackbox.SystemBlackBox(arguments, unbuffer=False, constraints=None, parsing_info=None)

Blackbox that runs an external subprocess (usually a binary).

Parameters
  • arguments (List[Union[str, BlackBoxArgument]]) – List of arguments for the command to be executed. Placeholders might be used, such as SystemBlackBox.Instance and SystemBlackBox.Seed, that will be replaced during execution.

  • unbuffer (Union[str, bool]) – Path to the unbuffer binary, which may be desirable to unbuffer the pipe of the call. If it is a boolean, it will search unbuffer in the PATH. See the unbuffer documentation for more information.

  • constraints (Optional[ExecutionConstraints]) – Defines the execution constraints for the Configuration Process

  • parsing_info (Optional[ParsingInfo]) – Optional ParsingInfo object used for parsing the output of the blackbox

Instance = '__BLACKBOX_SUBS_INSTANCE__'

Automatically substitutable instance argument

Seed = '__BLACKBOX_SUBS_SEED__'

Automatically substitutable seed argument

WallTime = '__BLACKBOX_SUBS_WALLTIME__'

Automatically substitutable WallTime argument

CPUTime = '__BLACKBOX_SUBS_CPUTIME__'

Automatically substitutable CPUTime argument

Memory = '__BLACKBOX_SUBS_MEMORY__'

Automatically substitutable Memory argument

property returncode: int

Return code of the execution Accessible after the execution has finished.

property stdout: str

Stdout output of the execution. Accessible after the execution has finished.

property stderr: str

Stderr output of the execution. Accessible after the execution has finished.

format_config(args)

Formats the configurable parameters of the blackbox, and concats them with args. By default, all parameters are formatted as --param-name=value. This method is expected to be overwritten for commands that expect the parameters in a different format.

Parameters

args (list) – List of current arguments

Returns

Final list of strings with the parameters to be called

run(instance, seed=None, constraints=None, stdout=BlackBoxRedirection.Default, stderr=BlackBoxRedirection.Stdout, text=True)

Executes the blackbox and stores its standard output

Parameters
  • instance (str) – Instance to execute

  • seed (Optional[int]) – Seed of the execution

  • constraints (Optional[ExecutionConstraints]) – Defines the execution constraints for the Configuration Process. If it is None, the default constraints of the constructor will be used. Otherwise, these new constraints will be used.

  • stdout (Union[str, BlackBoxRedirection]) – Where to redirect stdout. If it is a string, the output will be redirected to the specified path.

  • stderr (Union[str, BlackBoxRedirection]) – Where to redirect stderr. If it is a string, the output will be redirected to the specified path.

  • text (bool) – Whether the output is text based or binary

get(key)

Returns the value assigned to a given parameter name.

Parameters

key (str) – Parameter name.

Return type

Union[int, float, bool, str]

Returns

Parameter value.

classmethod get_config()
Return type

Dict[str, Dict[str, str]]

Returns

A dictionary with all the configurable parameters of the solver. Each parameter has defined its type (int, float, bool or categorical), its domain, and its default value.

property parsed

Dictionary with all the parsed elements from the execution. Accessible after the execution has finished.

set(key, value, check_domain=True)

Sets the value for a given parameter.

Parameters
  • key (str) – Parameter name.

  • value – Parameter value.

  • value – int or float or bool or str

Raises

KeyError: if param is not found inside the blackbox.

classmethod set_default(value, check_domain=True)

Sets the value for a given parameter in the default configuration

Parameters
  • key (str) – Parameter name.

  • value – Parameter value.

  • value – int or float or bool or str

Raises

KeyError: if param is not found inside the blackbox.

class optilog.blackbox.BlackBoxRedirection(value)

Blackbox redirection options

Default = 1

Default redirection

Stdout = 2

Redirect output to stdout.

Null = 3

Redirect output to null (ignore output).

Process = 4

Redirect output to parent process file descriptors. n Example: Redirecting stdout to Process will “automatically print” the stdout output of the subprocess.

Here we have a basic example of a blackbox execution with parsing and memory limitations. Notice the usage of the placeholder SystemBlackBox.Instance. This will be replaced by the instance specified passed to run.

 1from optilog.blackbox import SystemBlackBox, ExecutionConstraints, RunSolver
 2from optilog.running import ParsingInfo
 3
 4parsing_info = ParsingInfo()
 5parsing_info.add_filter('conflicts', 'Num conflicts: (\d+)', cast_to=int)
 6
 7executor = SystemBlackBox(
 8    ['./solver.sh', SystemBlackBox.Instance],
 9    constraints=ExecutionConstraints( # will inject call with runsolver found in PATH
10        s_wall_time=100,
11        s_real_memory='100M',
12        enforcer=RunSolver()
13    ),
14    parsing_info=parsing_info
15)
16
17executor.run('path/to/instance')  # wraps: ./solver.sh path/to/instance
18
19print(executor.conflicts) # 34
20print(executor.parsed) # {'conflicts': 34}

Here we have a more complex example with configuration. To have a higher flexibility, we extend the BlackBox class. As ./solver.sh expects the boolean parameters as flags, we override the format_config method to add the flag only when needed, instead of having –flag=True to the command call. Notice that we still have to add the args reveived by format_config.

 1from optilog.blackbox import SystemBlackBox
 2from optilog.running import ParsingInfo
 3from optilog.tuning.basis import Int, Real, Bool
 4
 5
 6parsing_info = ParsingInfo()
 7parsing_info.add_filter('conflicts', 'Num conflicts: (\d+)', cast_to=int)
 8parsing_info.add_filter('instance', 'Instance Path: (.+)')
 9
10class ExampleSolverBB(SystemBlackBox):
11
12    config = {
13        'incReduceDB': Int(0, 2147483647, default=300),
14        'R': Real(1.001, 4.999, default=1.4),
15        'C': Bool(default=False)
16    }
17
18    def __init__(self, *args, **kwargs):
19        super().__init__(arguments=['./solver.sh', SystemBlackBox.Instance], *args, **kwargs)
20
21    def format_config(self, args):
22        config = self.configured.copy()
23        c = config.pop('C', False)
24        extra_args = []
25        if c:
26            extra_args += ['--C']
27        return args + extra_args + [
28            f'--{k}={v}'
29            for k, v in config.items()
30        ]
31
32
33executor = ExampleSolverBB(parsing_info=parsing_info)
34
35executor.set('incReduceDB', 20)  # Set the parameter --incReduceDB=20
36executor.set('C', True)  # Set the flag --C
37
38executor.run('path/to/instance') # wraps: ./solver.sh path/to/instance --C --incReduceDB=20
39
40print(executor.conflicts)
41...
42print(executor.parsed)
43...
44print(executor.stdout)
45...