-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCompareGridSimulations.tsx
More file actions
211 lines (191 loc) · 7.85 KB
/
Copy pathCompareGridSimulations.tsx
File metadata and controls
211 lines (191 loc) · 7.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import React, { useMemo, useState } from "react";
import { useQueries } from "@tanstack/react-query";
import { CircularProgress, NativeSelect, Typography } from "@equinor/eds-core-react";
import { getGridSimulationResult, ResultIsPending } from "@/api/api";
import { MainContainer } from "@/components/styles";
import { GridSimulationResult } from "@/dto/GridSimulation";
import LineChart, { LineSeries } from "@/components/LineChart";
import {
collectOutputSubstances,
pointOutput,
significantSubstances,
visiblePhaseKinds,
} from "@/functions/GridSimulation";
import { optionName } from "@/functions/Substance";
import { useAvailableModels } from "@/contexts/ModelContext";
import { buildModelSections, phaseLabel } from "@/utils/modelUtils";
import ModelAccordionLayout, { AccordionItem } from "@/components/ModelAccordionLayout";
interface CompareGridSimulationsProps {
gridIds: string[];
}
const modelChainLabel = (result: GridSimulationResult): string => {
const firstSim = result.simulations[0];
if (!firstSim) return "Unknown model";
return firstSim.input.models.map((m) => m.modelId).join(" → ") || "Unknown model";
};
interface CompareSectionProps {
results: GridSimulationResult[];
modelIndex: number;
phaseKind: string;
}
const CompareSection: React.FC<CompareSectionProps> = ({ results, modelIndex, phaseKind }) => {
const allSubstances = useMemo(() => {
const substances = new Set<string>();
results.forEach((r) =>
significantSubstances(r.simulations, modelIndex, phaseKind).forEach((s) => substances.add(s))
);
if (substances.size === 0) {
results.forEach((r) =>
collectOutputSubstances(r.simulations, modelIndex, phaseKind).forEach((s) => substances.add(s))
);
}
return Array.from(substances).sort();
}, [results, modelIndex, phaseKind]);
const [substance, setSubstance] = useState<string>("");
const selectedSubstance = substance || allSubstances[0] || "";
const xAxisSubstance = results[0]?.axes[0]?.substance ?? "";
const unifiedXValues = Array.from(
new Set(results.flatMap((r) => r.simulations.map((sim) => sim.input.concentrations[xAxisSubstance] ?? 0)))
).sort((a, b) => a - b);
const series: LineSeries[] = results.map((r) => {
const valueToSim = new Map(r.simulations.map((sim) => [sim.input.concentrations[xAxisSubstance] ?? 0, sim]));
return {
label: `${modelChainLabel(r)} · ${r.axes[0]?.substance ?? ""}`,
data: unifiedXValues.map((x) => {
const sim = valueToSim.get(x);
return sim ? pointOutput(sim, selectedSubstance, modelIndex, phaseKind) : null;
}),
};
});
const axisSubstances = new Set(results.map((r) => r.axes[0]?.substance).filter(Boolean));
const xAxisLabel =
axisSubstances.size === 1 ? `${[...axisSubstances][0]} (ppm·mol)` : "Varied concentration (ppm·mol)";
const unit = phaseKind === "aqueous" ? "wt%" : "ppm·mol";
return (
<>
<NativeSelect
id={`compare-${modelIndex}-${phaseKind}`}
label="Output substance"
value={selectedSubstance}
onChange={(e) => setSubstance(e.target.value)}
style={{ maxWidth: "400px", marginBottom: "1rem" }}
>
{allSubstances.map((s) => (
<option key={s} value={s}>
{optionName(s)}
</option>
))}
</NativeSelect>
{selectedSubstance === "" ? (
<Typography variant="body_short" italic>
No output substances available to compare.
</Typography>
) : (
<LineChart
xValues={unifiedXValues}
series={series}
xAxisLabel={xAxisLabel}
yAxisLabel={`${selectedSubstance} (${unit})`}
aspectRatio={2}
/>
)}
</>
);
};
const CompareGridSimulations: React.FC<CompareGridSimulationsProps> = ({ gridIds }) => {
const { models } = useAvailableModels();
const queries = useQueries({
queries: gridIds.map((id) => ({
queryKey: ["grid-simulation", id],
queryFn: () => getGridSimulationResult(id),
retry: (_count: number, error: Error) => error instanceof ResultIsPending,
retryDelay: () => 2000,
})),
});
const isLoading = queries.some((q) => q.isLoading);
const hasError = queries.some((q) => q.isError);
const results = queries.map((q) => q.data).filter((data): data is GridSimulationResult => data !== undefined);
const header = (
<Typography variant="h2" style={{ marginBottom: "2rem" }}>
Compare Grid Simulations
</Typography>
);
if (gridIds.length === 0) {
return (
<MainContainer>
{header}
<Typography variant="body_short">No grid simulations selected for comparison.</Typography>
</MainContainer>
);
}
if (isLoading) {
return (
<MainContainer>
{header}
<CircularProgress />
</MainContainer>
);
}
if (hasError) {
return (
<MainContainer>
{header}
<Typography variant="body_short" style={{ color: "red" }}>
Error loading grid simulation results
</Typography>
</MainContainer>
);
}
const firstSim = results[0]?.simulations[0];
const inputModels = firstSim?.input.models ?? [];
const sections = buildModelSections(inputModels, models);
const allPhasesByModel = new Map<number, string[]>();
sections.forEach((section) => {
section.indices.forEach((modelIndex) => {
const phases = new Set<string>();
results.forEach((r) => {
visiblePhaseKinds(r.simulations, modelIndex).forEach((k) => phases.add(k));
});
const order = ["co2-rich", "aqueous"];
allPhasesByModel.set(
modelIndex,
order.filter((k) => phases.has(k))
);
});
});
const items: AccordionItem[] = [];
sections.forEach((section) => {
section.indices.forEach((modelIndex) => {
const phases = allPhasesByModel.get(modelIndex) ?? [];
const modelName =
models.find((m) => m.modelId === inputModels[modelIndex]?.modelId)?.displayName ??
inputModels[modelIndex]?.modelId;
if (phases.length === 1) {
items.push({
key: `${section.category}-${modelIndex}`,
header: `${section.category}: ${modelName}`,
content: <CompareSection results={results} modelIndex={modelIndex} phaseKind={phases[0]} />,
});
} else {
phases.forEach((phaseKind) => {
items.push({
key: `${section.category}-${modelIndex}-${phaseKind}`,
header: `${section.category}: ${modelName} — ${phaseLabel(phaseKind)}`,
content: <CompareSection results={results} modelIndex={modelIndex} phaseKind={phaseKind} />,
});
});
}
});
});
return (
<MainContainer>
{header}
<Typography variant="body_short" style={{ marginBottom: "1rem" }}>
Comparing {results.length} grid simulations. Each line shows how the selected output substance responds
across the configured range.
</Typography>
<ModelAccordionLayout items={items} />
</MainContainer>
);
};
export default CompareGridSimulations;