Coverage for backend/core/auxiliary/methods/export_scenario_data.py: 66%

40 statements  

« prev     ^ index     » next       coverage.py v7.10.7, created at 2025-11-06 23:27 +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 

10 

11 

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 

17 

18# Tested in test_mss.py 

19def export_scenario_data(flowsheet: Flowsheet, scenario: Scenario): 

20 # Create a column for each property value 

21 solutions = Solution.objects.filter(scenario=scenario).order_by("solve_index") 

22 property_values = PropertyValue.objects.filter(flowsheet=flowsheet, solutions__in=solutions).distinct() 

23 

24 # Create a list of blanks to fill in missing data 

25 blanks = [None for _ in range(values_per_index(scenario))] 

26 

27 columns = {} 

28 data = {} 

29 

30 for uo_name, prop_key, prop_id in property_values.values_list( 

31 "property__set__simulationObject__componentName", # Link to PropertyInfo -> PropertySet -> SimulationObject Name 

32 "property__key", # PropertyInfo key 

33 "id" 

34 ): 

35 column_name = f"{uo_name} - {prop_key} ({prop_id})" 

36 columns[prop_id] = column_name 

37 data[column_name] = [] 

38 

39 # Populate the columns 

40 current_solve_index = 0 

41 

42 for solution in solutions: 

43 if solution.solve_index > current_solve_index: 

44 # Fill in blanks for missing solve indices 

45 for _ in range(solution.solve_index - current_solve_index - 1): 45 ↛ 46line 45 didn't jump to line 46 because the loop on line 45 never started

46 for column_name in data.keys(): 

47 data[column_name].extend(blanks) 

48 current_solve_index = solution.solve_index 

49 

50 column_name = columns[solution.property_id] 

51 # Because the values are an array, we flatten them into the data column 

52 data[column_name].extend(solution.values) 

53 

54 return data 

55 

56def collate(data: dict[str,list]): 

57 """ 

58 Collate the data into rows for CSV export 

59 """ 

60 # Collate the data into rows 

61 # Each row is a dict with keys as column names 

62 rows = [] 

63 max_length = max((len(v) for v in data.values()),default=0) 

64 for i in range(max_length): 

65 row = {} 

66 for key, values in data.items(): 

67 row[key] = values[i] if i < len(values) else None 

68 rows.append(row) 

69 return rows 

70 

71