Coverage for backend/core/auxiliary/methods/copy_flowsheet/copy_formulas.py: 88%
18 statements
« prev ^ index » next coverage.py v7.10.7, created at 2025-11-06 23:27 +0000
« prev ^ index » next coverage.py v7.10.7, created at 2025-11-06 23:27 +0000
1from core.auxiliary.models.PropertyValue import PropertyValue
2from ..replace_expression_ids import get_formula_keys, extract_id_from_formula_key, replace_props
3from .copy_caching import ModelLookupDict
4from typing import List
6def update_formulas(model_lookups: ModelLookupDict) -> None:
7 """
8 Each expression references the property values by their primary key.
9 This is called after the property values have been updated,
10 so that we can update their formulas to reference the new property values.
11 """
12 property_values = model_lookups[PropertyValue]
13 for property_value in property_values:
14 if property_value.formula:
15 formula_keys = get_formula_keys(property_value.formula)
16 # example formula key: prop_500
17 formula_ids = [extract_id_from_formula_key(key) for key in formula_keys]
18 # list of ids
19 new_property_values: List[PropertyValue] = [property_values.get_model(pk) for pk in formula_ids]
20 if None in new_property_values: 20 ↛ 22line 20 didn't jump to line 22 because the condition on line 20 was never true
21 #Gracefully handle the case where a formula key does not match any property value.
22 property_value.formula = "Failed to copy formula, could not find property in flowsheet."
23 continue
24 new_formula_ids = [property_values.get_model(pk).pk for pk in formula_ids]
25 new_formula_props = [f"prop{pk}" for pk in new_formula_ids]
26 property_value.formula = replace_props(
27 property_value.formula, new_formula_props
28 )
29 PropertyValue.objects.bulk_update(
30 property_values,
31 ['formula'],)