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

_load_file

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_ctl()[source]#

Creates the domain control and loads the domain files.

_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

_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

_clear_cache

_prepare()[source]#

Does any preparation before a solve call.

_restart()[source]#

Restarts the backend by setting all attributes, initializing controls and grounding. It is automatically called when the server starts.

_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_assumptions()[source]#

Removes all assumptions.

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)

stop_browsing()[source]#

Stops the current browsing.

update()[source]#

Updates the UI by clearing the cache and computing the models again.

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

_init_ds_constructors(*args, **kwargs)#
_init_interactive(*args, **kwargs)#

Initializes the list of the assignments

Variables

_assignment (List[Tuple[str, int]]) – The list of assignments

_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.

_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

classmethod register_options(parser)[source]#

Registers command line options for ClingraphBackend.

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

_init_ds_constructors(*args, **kwargs)#
_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

stringify(s, capitalize=False)[source]#

Turns a value into a string without underscore and capitalized if requested

Example

attr(s_l(I), label, @stringify(semester_1, true)). # Semester 1

Label will be Semester 1

Parameters

s – The value to transform

Returns

The string without _

ClinguinUI#

class UIState[source]#

Bases: object

The UIState is the low-level-access-class for handling the facts defining the UI state

__init__(ui_files, domain_state, constants_arg_list)[source]#
_set_fb_symbols(symbols)[source]#
add_attribute(cid, key, value)[source]#

Adds an attribute to the factbase.

add_attribute_direct(new_attribute)[source]#

Directly adds an attribute.

add_element(cid, t, parent)[source]#

Adds an element to the factbase.

add_message(title, message, attribute_type='info')[source]#

Adds a β€˜β€™Message’’ (aka. Notification/Pop-Up) for the user with a certain title and message.

get_attributes(key=None)[source]#

Get all attributes.

get_attributes_for_element_id(element_id)[source]#

Get all attributes for one element id.

get_attributes_grouped()[source]#

Get all attributes grouped by element id.

get_callbacks()[source]#

Get all callbacks.

get_callbacks_for_element_id(element_id)[source]#

Get all callbacks for one element id.

get_callbacks_grouped()[source]#

Get all callbacks grouped by element id.

get_elements()[source]#

Get all elements.

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

classmethod symbols_to_facts(symbols)[source]#

Converts a iterable symbols to a string of facts.

ui_control()[source]#

Generates a ClingoControl Object to compute the UI state

unifiers = [<class 'clinguin.server.data.element.ElementDao'>, <class 'clinguin.server.data.attribute.AttributeDao'>, <class 'clinguin.server.data.callback.WhenDao'>]#
update_ui_state()[source]#

Computes the answer set representing the UI state