Coverage for backend/django/core/auxiliary/methods/export_scenario_data.py: 68%
42 statements
« prev ^ index » next coverage.py v7.10.7, created at 2025-12-18 04:00 +0000
« prev ^ index » next coverage.py v7.10.7, created at 2025-12-18 04:00 +0000
1from core.auxiliary.models.Scenario import Scenario
2from core.auxiliary.models.Flowsheet import Flowsheet
3from core.auxiliary.models.PropertyValue import PropertyValue
4from core.auxiliary.models.PropertyInfo import (
5 PropertyInfo,
6)
7from core.auxiliary.models.Solution import Solution
8from core.auxiliary.models.SolveState import SolveState, SolveValue
9from core.auxiliary.models.Solution import Solution
12def values_per_index(scenario: Scenario):
13 if not scenario.enable_dynamics: 13 ↛ 16line 13 didn't jump to line 16 because the condition on line 13 was always true
14 return 1
15 else :
16 return scenario.num_time_steps
18# Tested in test_mss.py
19def export_scenario_data(flowsheet: Flowsheet, scenario: Scenario, properties: list[int] | None = None):
20 # Create a column for each property value
21 if properties:
22 solutions = Solution.objects.filter(scenario=scenario, property__property_id__in=properties).order_by("solve_index")
23 else:
24 solutions = Solution.objects.filter(scenario=scenario).order_by("solve_index")
25 property_values = PropertyValue.objects.filter(flowsheet=flowsheet, solutions__in=solutions).distinct()
27 # Create a list of blanks to fill in missing data
28 blanks = [None for _ in range(values_per_index(scenario))]
30 columns = {}
31 data = {}
33 for uo_name, prop_key, prop_id in property_values.values_list(
34 "property__set__simulationObject__componentName", # Link to PropertyInfo -> PropertySet -> SimulationObject Name
35 "property__key", # PropertyInfo key
36 "id"
37 ):
38 column_name = f"{uo_name} - {prop_key}"
39 columns[prop_id] = column_name
40 data[column_name] = []
42 # Populate the columns
43 current_solve_index = 0
45 for solution in solutions:
46 if solution.solve_index > current_solve_index:
47 # Fill in blanks for missing solve indices
48 for _ in range(solution.solve_index - current_solve_index - 1): 48 ↛ 49line 48 didn't jump to line 49 because the loop on line 48 never started
49 for column_name in data.keys():
50 data[column_name].extend(blanks)
51 current_solve_index = solution.solve_index
53 column_name = columns[solution.property_id]
54 # Because the values are an array, we flatten them into the data column
55 data[column_name].extend(solution.values)
57 return data
59def collate(data: dict[str,list]):
60 """
61 Collate the data into rows for CSV export
62 """
63 # Collate the data into rows
64 # Each row is a dict with keys as column names
65 rows = []
66 max_length = max((len(v) for v in data.values()),default=0)
67 for i in range(max_length):
68 row = {}
69 for key, values in data.items():
70 row[key] = values[i] if i < len(values) else None
71 rows.append(row)
72 return rows