bim2sim.kernel.decision package
Decision system.
- This package contains:
class Decision (and child classes) for representing decisions
class DecisionBunch for handling collections of Decision elements
class DecisionHandler to handle decisions
functions save() and load() to save to file system
- class bim2sim.kernel.decision.BoolDecision(*args, **kwargs)
Bases:
Decision
Accepts input convertable as bool
- NEGATIVES = ('n', 'no', 'nein', 'n', '0')
- POSITIVES = ('y', 'yes', 'ja', 'j', '1')
- class bim2sim.kernel.decision.Decision(question: str, console_identifier: str = None, validate_func: Callable = None, key: str = None, global_key: str = None, allow_skip=False, validate_checksum=None, related: List[str] = None, context: List[str] = None, default=None, group: str = None, representative_global_keys: list = None)
Bases:
object
A question and a value which should be set to answer the question.
- Args:
question: The question asked to the user console_identifier: Additional information to identify related in
console
validate_func: callable to validate the users input key: key is used by DecisionBunch to create answer dict global_key: unique key to identify decision. Required for saving allow_skip: set to True to allow skipping the decision and user None as
value
- validate_checksum: if provided, loaded decisions are only valid if
checksum matches
related: iterable of GUIDs this decision is related to (frontend) context: iterable of GUIDs for additional context to this decision
(frontend)
default: default answer group: group of decisions this decision belongs to representative_global_keys: list of global keys of elements that this
decision also has the answer for
- Example:
>>> decision = Decision("How much is the fish?", allow_skip=True)
# the following is usually done by child classes. Here it’s a hack to make plain Decisions work >>> decision._validate = lambda value: True
>>> decision.value # will raise ValueError Traceback (most recent call last): ValueError: Can't get value from invalid decision. >>> decision.value = 10 # ok >>> decision.value 10 >>> decision.freeze() # decision cant be changed afterwards >>> decision.value = 12 # value cant be changed, will raise AssertionError Traceback (most recent call last): AssertionError: Can't change value of frozen decision >>> decision.freeze(False) # unfreeze decision >>> decision.reset() # reset to initial state >>> decision.skip() # set value to None, only works if allow_skip flag set
- CANCEL = 'cancel'
- SKIP = 'skip'
- SKIPALL = 'skip all'
- static build_checksum(item)
Create checksum for item.
- convert(value)
Convert value to inner type.
- deserialize_value(value)
rebuild value from json deserialized object
- freeze(freeze=True)
Freeze this Decision to prevent further manipulation.
- Args:
freeze: the freeze state
- Raises:
AssertionError: If the Decision is currently pending
- get_body()
Returns list of tuples representing items of CollectionDecision else None
- get_options()
Get all available options.
- get_question() str
Get the question.
- get_serializable()
Returns json serializable object representing state of decision
- options = ['skip', 'skip all', 'cancel']
- reset()
Reset the Decision to it’s initial state.
- Raises:
AssertionError: if Decision is frozen
- reset_from_deserialized(kwargs)
Reset decision from its serialized form.
- serialize_value()
Return JSON serializable value.
- skip()
Set value to None und mark as solved.
- valid() bool
Check if Decision is valid.
- validate(value) bool
Checks value with validate_func and returns truth value.
- property value
Answer value of decision.
- Raises:
ValueError: On accessing the value before it is set or by setting an invalid value AssertionError: By changing a frozen Decision
- class bim2sim.kernel.decision.DecisionBunch(decisions: Iterable[Decision] = ())
Bases:
list
Collection of decisions.
- get_reduced_bunch(criteria: str = 'key')
Reduces the decisions to one decision per unique key.
To reduce the number of decisions in some cases the same answer can be used for multiple decisions. This method allows to reduce the number of decisions based on a given criteria.
- Args:
- criteria: criteria based on which the decisions should be reduced.
Possible are ‘key’ and ‘question’.
- Returns:
- unique_decisions: A DecisionBunch with only unique decisions based
on criteria
- to_serializable() dict
Create JSON serializable dict of decisions.
- valid() bool
Check status of all decisions.
- validate_global_keys()
Check if all global keys are unique.
- Raises:
AssertionError on bad keys.
- exception bim2sim.kernel.decision.DecisionCancel
Bases:
DecisionException
Exception raised on canceling Decisions
- exception bim2sim.kernel.decision.DecisionException
Bases:
Exception
Base Exception for Decisions
- exception bim2sim.kernel.decision.DecisionSkip
Bases:
DecisionException
Exception raised on skipping Decision
- exception bim2sim.kernel.decision.DecisionSkipAll
Bases:
DecisionException
Exception raised on skipping all Decisions
- class bim2sim.kernel.decision.GuidDecision(*args, multi=False, **kwargs)
Bases:
Decision
Accepts GUID(s) as input. Value is a set of GUID(s)
- deserialize_value(value)
rebuild value from json deserialized object
- serialize_value()
Return JSON serializable value.
- class bim2sim.kernel.decision.ListDecision(*args, choices: List[Any | Tuple[Any, str]], live_search=False, **kwargs)
Bases:
Decision
Accepts index of list element as input.
- Args:
choices: a list of values where str(value) is used for labels or a list of (value, label) tuples live_search:
- property choices
Available choices for the Decision.
- get_body()
Returns list of tuples representing items of CollectionDecision else None
- validate(value)
Checks value with validate_func and returns truth value.
- exception bim2sim.kernel.decision.PendingDecisionError
Bases:
DecisionException
Exception for unsolved Decisions
- class bim2sim.kernel.decision.RealDecision(*args, unit: Quantity = None, **kwargs)
Bases:
Decision
Accepts input of type real.
- Args:
unit: the unit of the Decisions value
- convert(value)
Convert value to inner type.
- get_body()
Returns list of tuples representing items of CollectionDecision else None
- get_debug_answer()
- get_question()
Get the question.
- reset_from_deserialized(kwargs)
Reset decision from its serialized form.
- serialize_value()
Return JSON serializable value.
- class bim2sim.kernel.decision.Status(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
Enum
Enum for status of Decision
- error = 6
- ok = 2
- pending = 1
- skipped = 5
- class bim2sim.kernel.decision.StringDecision(*args, min_length=1, **kwargs)
Bases:
Decision
Accepts string input
- bim2sim.kernel.decision.convert(from_version, to_version, data)
convert stored decisions to new version
- bim2sim.kernel.decision.convert_0_to_0_1(data)
- bim2sim.kernel.decision.load(path) Dict[str, Any]
Load previously solved Decisions from file system.
- bim2sim.kernel.decision.save(bunch: DecisionBunch, path)
Save solved Decisions to file system
Submodules
bim2sim.kernel.decision.console module
Decision handling via console.
- class bim2sim.kernel.decision.console.ConsoleDecisionHandler
Bases:
DecisionHandler
DecisionHandler to user with an interactive console.
- static collection_progress(collection)
- get_answers_for_bunch(bunch: DecisionBunch) list
Collect and return answers for given decision bunch.
- static get_body_txt(body)
- static get_default_txt(decision)
- static get_input_txt(decision)
- static get_matches_list(search_words: str, search_list: list) list
get patterns for a search name, and get afterwards the related elements from list that matches the search
- static get_options_txt(options)
- static parse_bool_input(raw_input)
Convert input to bool
- static parse_guid_input(raw_input)
- static parse_list_input(raw_input, items)
- static parse_real_input(raw_input, unit=None)
Convert input to float
- static parse_string_input(raw_input)
- user_input(decision, extra_options=None, progress='')
- user_input_live(decision, input_txt, options)
bim2sim.kernel.decision.decisionhandler module
DecisionHandlers prepare decisions to allow easy answering.
DecisionHandlers are designed to handle DecisionBunch yielding generators.
- Example:
>>> def de_gen(): ... decision = StringDecision("Whats your name?") ... yield DecisionBunch([decision]) ... print(decision.value)
>>> handler = DebugDecisionHandler(["R2D2"])
>>> # version 1: no further interaction needed >>> handler.handle(de_gen()) "R2D2"
>>> # version 2: iterate over decisions and answers and apply them on your own >>> for decision, answer in handler.decision_answer_mapping(de_gen()): ... decision.value = answer "R2D2"
- class bim2sim.kernel.decision.decisionhandler.DebugDecisionHandler(answers: Iterable)
Bases:
DecisionHandler
Simply use a predefined list of values as answers.
- decision_answer_mapping(*args, **kwargs)
Generator method yielding tuples of decision and answer.
the return value of decision_generator can be obtained from self.return_value
- get_answers_for_bunch(bunch: DecisionBunch) list
Collect and return answers for given decision bunch.
- class bim2sim.kernel.decision.decisionhandler.DecisionHandler
Bases:
object
Basic DecisionHandler for decision solving
- decision_answer_mapping(decision_generator: Generator[DecisionBunch, None, None])
Generator method yielding tuples of decision and answer.
the return value of decision_generator can be obtained from self.return_value
- get_answers_for_bunch(bunch: DecisionBunch) list
Collect and return answers for given decision bunch.
- get_body(decision)
- get_options(decision)
- get_question(decision)
- handle(decision_gen: Generator[DecisionBunch, None, Any], saved_decisions: Dict[str, Dict[str, Any]] = None) Any
Processes decisions by applying saved answers or mapping new ones.
This function iterates over a generator of DecisionBunch objects, either applying previously saved decisions from previous project runs or allowing the user to map new decisions based on the provided generator. If saved decisions are provided, it tries to find and apply the corresponding answers to the decisions. If a decision cannot be matched to a saved answer, a ValueError is raised.
- Args:
- decision_gen (Generator[DecisionBunch, None, Any]):
A generator that yields DecisionBunch objects.
- saved_decisions (Dict[str, Dict[str, Any]], optional):
A dictionary of saved decisions, where the key is a global decision key and the value is a dictionary containing decision
details, including the ‘value’. Defaults to None.
- Returns:
Any: The return value is typically determined by the subclass implementation or external logic.
- Raises:
ValueError: If saved decisions are provided but a decision in decision_gen does not have a corresponding saved answer.
- parse(decision, raw_answer)
- static parse_bool_input(raw_input)
Convert input to bool
- static parse_guid_input(raw_input)
- static parse_list_input(raw_input, items)
- static parse_real_input(raw_input, unit=None)
Convert input to float
- static parse_string_input(raw_input)
- shutdown(success)
Shut down handler
- validate(decision, value)