API#
Detailed API for all the classes and functions in the server of the clinguin package.
ClinguinBackends#
Module that contains the backends
- class ClingoBackend[source]#
Bases:
object
This backend contains the basic clingo functionality for a backend using clingo.
- __init__(args)[source]#
Creates the Backend with the given arguments. It will setup all attributes by calling
_init_ds_constructors
and_restart
.Generally this method should NOT be overwritten by custom backends. Instead, custom backends should overwrite specialized methods.
- Parameters
args (ArgumentParser) β The arguments from the argument parser that are given for the registered options.
- _add_assumption(symbol, value='true')[source]#
Adds an assumption to the list of assumptions.
- Parameters
symbol (clingo.Symbol) β The clingo symbol to be added as a True assumption
value (true) β The value of the assumption either βtrueβ or βfalseβ
- _add_atom(predicate_symbol)[source]#
Adds an atom if it hasnβt been already added
- Parameters
predicate_symbol (clingo.Symbool) β The symbol for the atom
- _add_domain_state_constructor(method)[source]#
Adds a method name to the domain constructors. The provided method needs to be annotated with
@property
or@cached_property
- Parameters
method (str) β Name of the property method
- property _assumption_list#
A list of assumptions in the format of form (a, True) or (a, False)
- _call_solver_with_cache(ds_id, ds_tag, models, opt_mode, enum_mode)[source]#
Generic function to call the using exiting cache on browsing. Un UNSAT it returns the output saved in the cache
- Parameters
ds_id β Identifier used in the cache
- Returns
The program tagged
- _clear_cache(methods=None)[source]#
Clears the cache of domain state constructor methods
- Parameters
methods (list, optional) β A list with the methods to remove the cache from. If no value is passed then all cache is removed
- property _constants_argument_list#
Gets the constants as a list of strings in the format β-c <name>=<value>β
- _create_ctl()[source]#
Initializes the control object (domain-control). It is used when the server is started or after a restart.
See also
- property _ctl_arguments_list#
Gets the list of arguments used for creating a control object
- property _domain_state#
Gets the domain state by calling all the domain constructor methods
Some domain state constructors might skip the computation if the UI does not require them.
- property _ds_assume#
Adds information about the assumptions.
Includes predicate
_clinguin_assume/2
for every atom that was assumed, where the second argument is either true or false.
- property _ds_brave#
Computes brave consequences adds them as predicates
_any/1
. This are atoms that appear in some model. If it is not used in the UI files then the computation is not performed.It uses a cache that is erased after an operation makes changes in the control.
- property _ds_brave_optimal#
Computes brave consequences for only optimal solutions adds them as predicates
_any_opt/1
. This are atoms that appear in some optimal model. If it is not used in the UI files then the computation is not performed.It uses a cache that is erased after an operation makes changes in the control.
- property _ds_browsing#
Adds information about the browsing state
Includes predicate
_clinguin_browsing/0
if the user is browsing solutions
- property _ds_cautious#
Computes cautious consequences adds them as predicates
_all/1
. This are atoms that appear in all models. If it is not used in the UI files then the computation is not performed.It uses a cache that is erased after an operation makes changes in the control.
- property _ds_cautious_optimal#
Computes cautious consequences of optimal models adds them as predicates
_all_opt/1
. This are atoms that appear in all optimal models. If it is not used in the UI files then the computation is not performed.It uses a cache that is erased after an operation makes changes in the control.
- property _ds_constants#
Adds constants values.
Includes predicate
_clinguin_const/2
for each constant provided in the command line and used in the domain files.
- property _ds_context#
Adds context information from the client.
Includes predicate
_clinguin_context/2
indicating each key and value in the context.
- property _ds_external#
Adds information about the external atoms
Includes predicate
_clinguin_external/2
for every external atom that has been set.
- property _ds_model#
Computes model and adds all atoms as facts. When the model is being iterated by the user, the current model is returned. It will use as optimality the mode set in the command line as default-opt-mode (ignore by default).
It uses a cache that is erased after an operation makes changes in the control.
- property _ds_opt#
Adds program to pass with optimality information.
- Includes predicates:
_clinguin_cost/1
: With a single tuple indicating the cost of the current model_clinguin_cost/2
: With the index and cost value, linearizing predicate_clinguin_cost/1
_clinguin_optimal/0
: If the solution is optimal_clinguin_optimizing/0
: If there is an optimization in the program
- property _ds_unsat#
Adds information about the statisfiablity of the domain control
Includes predicate
_clinguin_unsat/0
if the domain control is unsat
- _ground(program='base', arguments=None)[source]#
Grounds the provided program
- Parameters
program (str) β The name of the program to ground (defaults to βbaseβ)
arguments (list, optional) β The list of arguments to ground the program. Defaults to an empty list.
- _init_command_line()[source]#
Initializes the attributes based on the command-line arguments provided. This method is called when the server starts or after a restart.
- Variables
_domain_files (list) β The list of domain files provided via command line.
_ui_files (list) β The list of UI files provided via command line.
_constants (dict) β The dictionary of constants provided via command line.
_clingo_ctl_arg (list) β The list of clingo control arguments provided via command line.
If any command line arguments are added in
register_options
, they should be initialized here.Example
def _init_command_line(self): super()._init_command_line() self._my_custom_attr = self._args.my_custom_option
- _init_ds_constructors()[source]#
This method initializes the domain state constructors list and the backup cache dictionary. It also adds the default domain state constructors to the list. This method is called only when the server starts.
- Variables
_domain_state_constructors (list) β A list to store the domain state constructors.
_backup_ds_cache (dict) β A dictionary to store the backup domain state cache.
It can be extended by custom backends to add/edit domain state constructors. Adding a domain state constructor should be done by calling
_add_domain_state_constructor
.Example
@property def _ds_my_custom_constructor(self): # Creates custom program return "my_custom_program." def _init_ds_constructors(self): super()._init_ds_constructors() self._add_domain_state_constructor("_ds_my_custom_constructor")
- _init_interactive()[source]#
Initializes the attributes that will change during the interaction. This method is called when the server starts or after a restart.
- Variables
_context (list) β A list to store the context set by the general handler of requests.
_handler (clingo.SolveHandle) β The handler set while browsing in the next_solution operation.
_iterator (iter) β The iterator set while browsing in the next_solution operation.
_ctl (clingo.Control) β The domain control set in _init_ctl.
_ui_state (
UIState
) β A UIState object used to handle the UI construction,_update_ui_state. (set in every call to) β
_atoms (set[str]) β A set to store the atoms set dynamically in operations during the interaction.
_assumptions (set[(str,bool)]) β A set to store the assumptions set dynamically in operations during the
interaction. (the UI, set dynamically in operations during the) β
_externals (dict) β A dictionary with true, false and released sets of external atoms
_model (list[clingo.Symbol]) β The model set in on_model.
_unsat_core (list[int]) β The unsatisfiable core set in on_model.
_cost (list) β A list to store the cost set in on_model.
_optimal (bool) β A boolean indicating if the solution is optimal, set in on_model.
_optimizing (bool) β A boolean indicating if the solver is currently optimizing, set in on_model.
_messages (list[tuple[str,str,str]]) β A list to store the messages (title, content, type) to be shown in
interaction. β
- property _is_browsing#
Property to tell if clinguin is in browsing mode.
- _load_and_add()[source]#
Loads domain files and atoms into the control.
This method iterates over the domain files and atoms specified in the instance and loads them into the control. It raises an exception if a domain file does not exist or if there is a syntax error in the logic program file.
- Raises
Exception β If a domain file does not exist or if there is a syntax error in the logic program file.
See also
- _load_file(f)[source]#
Loads a file into the control. This method can be overwritten if any pre-processing is needed.
- Parameters
f (str) β The file path
- _on_model(model)[source]#
This method is called each time a model is obtained by the domain control. It sets the model, and optimization attributes. It can be extended to add custom features of the model.
- Parameters
model (clingo.Model) β The found clingo model
- _outdate()[source]#
Outdates all the dynamic values when a change has been made. Any current interaction in the models wil be terminated by canceling the search and removing the iterator.
See also
- _restart()[source]#
Restarts the backend by setting all attributes, initializing controls and grounding. It is automatically called when the server starts.
See also
_init_command_line
,_init_interactive
,_outdate
,_init_ctl
,_ground
- _set_constant(name, value)[source]#
Sets a constant in the backend and restarts the control.
- Parameters
name (str) β name of the constant
value (Any) β value of the constant
- _set_context(context)[source]#
Sets the context. Used by general endpoint handler after a request.
- Parameters
context β The context dictionary
- _set_external(symbol, name)[source]#
Sets the external value of a symbol.
- Parameters
symbol (clingo.Symbol) β The clingo symbol to be set
name (str) β Either βtrueβ, βfalseβ or βreleaseβ
- _ui_uses_predicate(name, arity)[source]#
Returns a truth value of weather the ui_files contain the given signature.
- Parameters
name (str) β Predicate name
arity (int) β Predicate arity
- _update_ui_state()[source]#
Updates the UI state by calling all domain state methods and creating a new control object (ui_control) using the UI files provided
- add_assumption(atom, value='true')[source]#
Adds an atom a as an assumption.
If the value is βtrueβ, the atom is assumed to be true. This assumption can be considered as an integrity constraint:
:- not a.
forcing the program to entail the given atom.If the value is βfalseβ, the atom is assumed to be false: This assumption can be considered as an integrity constraint:
:- a.
forcing the program to never entail the given atom.Notice that the assumption must be generated by your domain encoding.
- Parameters
atom (str) β The clingo symbol to be added as a true assumption
value (str) β The value of the assumption either βtrueβ or βfalseβ
- add_atom(predicate)[source]#
Adds an atom, restarts the control and grounds
- Parameters
predicate (str) β The clingo symbol to be added
- clear_atoms()[source]#
Removes all atoms and resets the backend. and finally updates the model and returns the updated gui as a Json structure.
- download(show_prg=None, file_name='clinguin_download.lp')[source]#
Downloads the current model. It must be selected first via
select
.- Parameters
show_prg (_type_, optional) β Program to filter output using show statements. Defaults to None.
file_name (str, optional) β The name of the file for the download. Defaults to βclinguin_download.lpβ.
- get()[source]#
Updates the UI and transforms the facts into a JSON. This method will be automatically called after executing all the operations.
- ground(program, arguments=None)[source]#
Grounds the given program. Notice that the base program is grounded when the server starts. This operation can be used for grounding encodings with multiple programs in a multi-shot setting.
- Parameters
program (str) β The name of the program to ground used in the #program directive
arguments (tuple, optional) β The list of arguments to ground the program. Defaults to an empty list.
instance (These are the arguments of your #program directive. For) β
step (in #program) β
- next_solution(opt_mode='ignore')[source]#
Obtains the next solution. If a no browsing has been started yet, then it calls solve, otherwise it iterates the models in the last call. To keep the atoms shown in the solution, use
select
.- Parameters
opt_mode β The clingo optimization mode, bu default is βignoreβ, to browse only optimal models use βoptNβ
- classmethod register_options(parser)[source]#
Registers options in the command line.
It can be extended by custom backends to add custom command-line options.
- Parameters
parser (ArgumentParser) β A group of the argparse argument parser
Example
@classmethod def register_options(cls, parser): ClingoBackend.register_options(parser) parser.add_argument( "--my-custom-option", help="Help message", nargs="*", )
- remove_assumption(atom)[source]#
Removes an atom from the assumptions list regardless of its value. This will allow the atom to take any value in the solution.
- Parameters
atom (str) β The clingo symbol to be removed
- remove_assumption_signature(atom)[source]#
Removes from the list of assumptions those matching the given atom. Unlike function remove_assumption, this one allows for partial matches using the placeholder constant any. This will allow the atom to take any value in the solution.
- Parameters
atom (str) β The atom description as a symbol, where the reserver word any is used to state that anything can take part of that position. For instance, person(anna,any), will remove all assumptions of atom person, where the first argument is anna.
- remove_atom(predicate)[source]#
Removes an atom (if present), restarts the control and grounds again
- Parameters
predicate (str) β The clingo symbol to be added
- restart()[source]#
Restarts the backend. It will initialize all attributes, remove atoms, assumptions and externals, restart the control object by initializing all parameters, controls, ending the browsing and grounding.
- select(show_prg='')[source]#
Select the current solution during browsing. All atoms in the solution are added as assumptions in the backend.
- Parameters
show_program (str) β An optional show program to filter atoms
- set_constant(name, value)[source]#
Sets a constant value. Will reinitialize the control, ground and set arguments
- set_external(atom, value)[source]#
Sets the value of an external. Externals must be defined in the domain files using #external. The truth value of external atoms can then be provided by the user via this function.
- Parameters
atom (str) β The clingo symbol to be set
value (str) β The value (release, true or false)
- class ClingoDLBackend[source]#
Bases:
ClingoBackend
Backend that allows programs using clingodl theory atoms as input. It also includes the assignment in the domain state.
- _create_ctl(*args, **kwargs)#
Registers the ClingoDLTheory.
Important
Extends
ClingoBackend._create_ctl
- property _ds_assign#
Adds program with assignments
Includes predicate
_clinguin_assign/2
with the assignments.
- _init_command_line(*args, **kwargs)#
Sets the dl configuration
Important
Extends
ClingoBackend._init_command_line
- _init_ds_constructors(*args, **kwargs)#
Important
- _init_interactive(*args, **kwargs)#
Initializes the list of the assignments
- Variables
_assignment (List[Tuple[str, int]]) β The list of assignments
Important
Extends
ClingoBackend._init_interactive
- _load_file(*args, **kwargs)#
Uses the program builder to rewrite the theory atoms.
Important
Extends
ClingoBackend._load_file
- _on_model(*args, **kwargs)#
Sets the assignment from the model
Important
Extends
ClingoBackend._on_model
- _outdate(*args, **kwargs)#
Sets the assignment to empty.
Important
Extends
ClingoBackend._outdate
- _prepare(*args, **kwargs)#
Prepares the theory before solving
Important
Extends
ClingoBackend._prepare
- classmethod register_options(*args, **kwargs)#
Adds the dl-config option.
Important
Extends
ClingoBackend.register_options
- class ClingraphBackend[source]#
Bases:
ClingoBackend
Extends ClingoBackend. With this Backend it is possible to include clingraph images in the UI. The image is rendered based on a visualization encoding every time the UI is updated. Then, they are sent the client as Base64 encoding.
- _compute_clingraph_graphs(domain_state)[source]#
Computes all the graphs using the encoding and the domain state
- Parameters
domain_state (str) β The model, brave, and cautious consequences (domain-state)
- _create_image_from_graph(graphs, position=None, key=None)[source]#
Creates the image of the graph using clingraph
- Parameters
graphs (dic) β
position (int) β
key (int) β
- _init_command_line(*args, **kwargs)#
Sets the arguments for computing clingraph images.
Important
Extends
ClingoBackend._init_command_line
- _replace_uifb_with_b64_images_clingraph(graphs)[source]#
Replaces the clingraph predicates of the UI with the computed graphs.
- Parameters
graphs (dic) β
- _ui_uses_predicate(*args, **kwargs)#
Returns a truth value of weather the ui_files contain the given signature.
- Parameters
name (str) β Predicate name
arity (int) β Predicate arity
Important
Overwrites
ClingoBackend._ui_uses_predicate
- _update_ui_state(*args, **kwargs)#
Updates the UI state by calling all domain state methods and creating a new control object (ui_control) using the ui_files provided
Important
Extends
ClingoBackend._update_ui_state
- class ExplanationBackend[source]#
Bases:
ClingoBackend
Extends ClingoBackend. This backend will treat an UNSAT result by adding the Minimal Unsatisfiable Core (MUC) to the domain-state, thus allowing the UI to show the faulty assumptions.
- property _assumption_list#
Gets the set of assumptions used for solving. It includes the assumptions from the assumption signatures provided.
Warning
Overwrites
ClingoBackend._assumption_list
- property _ds_mus#
Adds information about the Minimal Unsatisfiable Set (MUS) Includes predicate
_clinguin_mus/1
for every assumption in the MUC It uses a cache that is erased after an operation makes changes in the control.
- _ground(*args, **kwargs)#
Sets the list of assumptions that were taken from the input files using the assumption_signature.
- Variables
_assumptions_from_signature (Set[Tuple(str,bool)]) β The set of assumptions from the assumption signatures
arguments (list, optional) β The list of arguments to ground the program. Defaults to an empty list.
Important
Extends
ClingoBackend._ground
- _init_command_line(*args, **kwargs)#
Sets the assumption signature and the transformer used for the input files
- Variables
_assumption_sig (List[Tuple[str, int]]) β The list of assumption signatures
_assumption_transformer (clingexplaid.AssumptionTransformer) β The transformer used for the input files
Important
Extends
ClingoBackend._init_command_line
- _init_ds_constructors(*args, **kwargs)#
Important
- _load_file(*args, **kwargs)#
Loads a file into the control. Transforms the program to add choices around assumption signatures.
- Parameters
f (str) β The file path
Important
Extends
ClingoBackend._load_file
- classmethod register_options(*args, **kwargs)#
Registers command line options for ClingraphBackend.
Important
Extends
ClingoBackend.register_options
ClinguinContext#
- class ClinguinContext[source]#
Makes available a set of python functions to be used in a UI encoding for handling strings.
- concat(*args)[source]#
Concatenates the given symbols as a string
Example
attr(s_l(I), label, @concat("Semester ",I)):-semester(I).
Label will be Semester 1
- Parameters
args β All symbols
- Returns
The string concatenating all symbols
- format(s, *args)[source]#
Formats the string with the given arguments
Example
attr(s_l(I), label, @format("Semester {}!",I)):-semester(I).
Label will be Semester 1!
- Parameters
s (str) β The string to format, for example β{0} and {1}β
args β All symbols that can be accessed by the position starting in 0. If there is a single tuple as an argument, then its arguments are considered one by one.
- Returns
The string obtained by formatting the string with the given arguments
ClinguinUI#
- class UIState[source]#
Bases:
object
The UIState is the low-level-access-class for handling the facts defining the UI state
- add_message(title, message, attribute_type='info')[source]#
Adds a ββMessageββ (aka. Notification/Pop-Up) for the user with a certain title and message.
- property is_empty#
Checks whether the factbase is empty. if so return true, else false.
- replace_attribute(old_attribute, new_attribute)[source]#
Replaces the old_attribute with the new_attribute.
- replace_images_with_b64(image_attribute_key='image')[source]#
Replaces all images in the ui-state by b64
- unifiers = [<class 'clinguin.server.data.element.ElementDao'>, <class 'clinguin.server.data.attribute.AttributeDao'>, <class 'clinguin.server.data.callback.WhenDao'>]#