|
| 1 | +# greyjack/score_calculation/score_calculators/GreynetScoreCalculator.py |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | +from typing import TYPE_CHECKING, Any, Dict, List, Tuple |
| 5 | + |
| 6 | +from greyjack.score_calculation.scores.ScoreVariants import ScoreVariants |
| 7 | +from greyjack.variables.GJFloat import GJFloat |
| 8 | +from greyjack.variables.GJInteger import GJInteger |
| 9 | +from greyjack.variables.GJBinary import GJBinary |
| 10 | +from copy import deepcopy |
| 11 | +import numpy as np |
| 12 | + |
| 13 | +if TYPE_CHECKING: |
| 14 | + from greyjack.score_calculation.greynet.builder import ConstraintBuilder |
| 15 | + from greyjack.score_calculation.greynet.session import Session |
| 16 | + |
| 17 | +class GreynetScoreCalculator: |
| 18 | + """ |
| 19 | + An incremental score calculator that uses the Greynet rule engine. |
| 20 | + This calculator holds the Greynet session and provides methods for |
| 21 | + the ScoreRequester to interact with it efficiently. |
| 22 | + """ |
| 23 | + def __init__(self, constraint_builder: 'ConstraintBuilder', score_variant: ScoreVariants): |
| 24 | + """ |
| 25 | + Initializes the calculator by building the Greynet session from the |
| 26 | + provided constraint definitions. |
| 27 | +
|
| 28 | + Args: |
| 29 | + constraint_builder (ConstraintBuilder): The Greynet constraint builder |
| 30 | + containing all the rules for the problem. |
| 31 | + score_variant (ScoreVariants): The score variant enumeration that |
| 32 | + corresponds to the score class used in the constraint builder. |
| 33 | + """ |
| 34 | + from greyjack.score_calculation.greynet.builder import ConstraintBuilder as GreynetConstraintBuilder |
| 35 | + if not isinstance(constraint_builder, GreynetConstraintBuilder): |
| 36 | + raise TypeError("constraint_builder must be an instance of greynet.ConstraintBuilder") |
| 37 | + |
| 38 | + self.session: 'Session' = constraint_builder.build() |
| 39 | + self.score_variant = score_variant |
| 40 | + self.is_incremental = True |
| 41 | + self.score_type = self.session.score_class |
| 42 | + |
| 43 | + # This mapping is populated by the ScoreRequester during initialization. |
| 44 | + # It is essential for translating the solver's variable indices to domain objects. |
| 45 | + # Key: var_idx (int) -> Value: (fact_object, attribute_name_str) |
| 46 | + self.var_idx_to_entity_map: Dict[int, Tuple[Any, str]] = {} |
| 47 | + |
| 48 | + self.first_call_apply_deltas_internal = True |
| 49 | + |
| 50 | + def initial_load(self, planning_entities: Dict[str, List[Any]], problem_facts: Dict[str, List[Any]]): |
| 51 | + """ |
| 52 | + Performs the initial population of the Greynet session with all facts |
| 53 | + from the problem domain. This should only be called once. |
| 54 | +
|
| 55 | + Args: |
| 56 | + planning_entities (dict): A dictionary of planning entity lists. |
| 57 | + problem_facts (dict): A dictionary of problem fact lists. |
| 58 | + """ |
| 59 | + self.session.clear() |
| 60 | + |
| 61 | + for group_name in problem_facts: |
| 62 | + self.session.insert_batch(problem_facts[group_name]) |
| 63 | + |
| 64 | + for group_name in planning_entities: |
| 65 | + initialized_entities = self.build_initialized_entities(planning_entities, group_name) |
| 66 | + self.session.insert_batch(initialized_entities) |
| 67 | + |
| 68 | + self.session.flush() |
| 69 | + |
| 70 | + def build_initialized_entities(self, planning_entities, group_name): |
| 71 | + |
| 72 | + current_planning_entities_group = planning_entities[group_name] |
| 73 | + initialized_entities = [] |
| 74 | + |
| 75 | + for entity in current_planning_entities_group: |
| 76 | + new_entity = self.build_initialized_entity(entity) |
| 77 | + initialized_entities.append(new_entity) |
| 78 | + |
| 79 | + return initialized_entities |
| 80 | + |
| 81 | + def build_initialized_entity(self, entity): |
| 82 | + entity_attributes_dict = entity.__dict__ |
| 83 | + new_entity_kwargs = {} |
| 84 | + for attribute_name in entity_attributes_dict: |
| 85 | + attribute_value = entity_attributes_dict[attribute_name] |
| 86 | + |
| 87 | + if type(attribute_value) in {GJFloat, GJInteger, GJBinary}: |
| 88 | + value = attribute_value.planning_variable.initial_value |
| 89 | + |
| 90 | + if value is None: |
| 91 | + raise ValueError("All planning variables must have initial value for scoring by greynet") |
| 92 | + else: |
| 93 | + value = attribute_value |
| 94 | + |
| 95 | + new_entity_kwargs[attribute_name] = value |
| 96 | + |
| 97 | + new_entity = type(entity)(**new_entity_kwargs) |
| 98 | + return new_entity |
| 99 | + |
| 100 | + def get_score(self) -> Any: |
| 101 | + """ |
| 102 | + Retrieves the current total score from the Greynet session. |
| 103 | + Assumes all pending changes have been flushed. |
| 104 | +
|
| 105 | + Returns: |
| 106 | + A score object (e.g., HardSoftScore) representing the current state. |
| 107 | + """ |
| 108 | + score = self.session.get_score() |
| 109 | + return score |
| 110 | + |
| 111 | + def _full_sync_and_get_score(self, sample: List[float]) -> Any: |
| 112 | + """ |
| 113 | + A non-incremental way to get a score for a full solution vector. |
| 114 | + This modifies the session state and is primarily for debugging or fallback. |
| 115 | + """ |
| 116 | + changed_facts, original_vals = self._apply_deltas_internal(list(enumerate(sample))) |
| 117 | + score = self.get_score() |
| 118 | + self._revert_deltas_internal(changed_facts, original_vals) |
| 119 | + return score |
| 120 | + |
| 121 | + def _apply_and_get_score_for_batch(self, deltas: List[List[Tuple[int, float]]]) -> List[Any]: |
| 122 | + """ |
| 123 | + Applies a batch of deltas, gets the score for each, and reverts the state |
| 124 | + between each delta application. This is the primary method for incremental scoring. |
| 125 | + """ |
| 126 | + scores = [] |
| 127 | + for delta_set in deltas: |
| 128 | + if not delta_set: |
| 129 | + scores.append(self.get_score()) |
| 130 | + continue |
| 131 | + |
| 132 | + changed_facts, original_values = self._apply_deltas_internal(delta_set) |
| 133 | + scores.append(self.get_score()) |
| 134 | + self._revert_deltas_internal(changed_facts, original_values) |
| 135 | + |
| 136 | + |
| 137 | + return scores |
| 138 | + |
| 139 | + def _apply_deltas_internal(self, deltas: List[Tuple[int, float]]) -> Tuple[Dict[int, Any], Dict[int, Any]]: |
| 140 | + """ |
| 141 | + Internal helper to apply changes to the session state. |
| 142 | + |
| 143 | + Returns: |
| 144 | + A tuple containing (dict of changed_facts, dict of original_values) for reverting. |
| 145 | + """ |
| 146 | + changed_facts: Dict[int, Any] = {} |
| 147 | + original_facts: Dict[int, Any] = {} |
| 148 | + |
| 149 | + if self.first_call_apply_deltas_internal: |
| 150 | + self.session.clear() |
| 151 | + for var_idx, new_value in deltas: |
| 152 | + old_entity, attr_name = self.var_idx_to_entity_map[var_idx] |
| 153 | + new_entity = self.build_initialized_entity(old_entity) |
| 154 | + self.var_idx_to_entity_map[var_idx] = (new_entity, attr_name) |
| 155 | + self.first_call_apply_deltas_internal = False |
| 156 | + |
| 157 | + # removing previous values |
| 158 | + for var_idx, new_value in deltas: |
| 159 | + entity, attr_name = self.var_idx_to_entity_map[var_idx] |
| 160 | + entity_id = id(entity) |
| 161 | + |
| 162 | + if entity_id not in original_facts: |
| 163 | + original_facts[entity_id] = entity |
| 164 | + |
| 165 | + self.session.retract_batch(list(original_facts.values())) |
| 166 | + |
| 167 | + # inserting new values |
| 168 | + for var_idx, new_value in deltas: |
| 169 | + entity, attr_name = self.var_idx_to_entity_map[var_idx] |
| 170 | + entity_id = id(entity) |
| 171 | + |
| 172 | + if entity_id not in changed_facts: |
| 173 | + changed_facts[entity_id] = deepcopy(entity) |
| 174 | + |
| 175 | + setattr(changed_facts[entity_id], attr_name, new_value) |
| 176 | + |
| 177 | + self.session.insert_batch(list(changed_facts.values())) |
| 178 | + self.session.flush() |
| 179 | + |
| 180 | + return changed_facts, original_facts |
| 181 | + |
| 182 | + def _revert_deltas_internal(self, changed_facts: Dict[int, Any], original_facts: Dict[int, Any]): |
| 183 | + """Internal helper to revert changes to the session state.""" |
| 184 | + |
| 185 | + self.session.retract_batch(list(changed_facts.values())) |
| 186 | + self.session.insert_batch(list(original_facts.values())) |
| 187 | + self.session.flush() |
| 188 | + |
| 189 | + pass |
0 commit comments