-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSingleCalibrationPage.jsx
313 lines (274 loc) · 10.4 KB
/
SingleCalibrationPage.jsx
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import React, { useEffect, useState } from "react";
import { useParams, Link as RouterLink } from "react-router-dom";
import { CircularProgress, Button, Typography, Box } from "@mui/material";
import {checkTaskCallback, colors, DefaultDict} from "./utilities"
import Link from '@mui/material/Link';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/Card';
import NavigateNextIcon from '@mui/icons-material/NavigateNext';
import CalibrationChart from "./components/CalibrationChart";
import CableIcon from '@mui/icons-material/Cable';
import {
Table,
TableBody,
TableCell,
TableRow,
} from "@mui/material";
import PioreactorIcon from "./components/PioreactorIcon"
import dayjs from 'dayjs';
import Snackbar from '@mui/material/Snackbar';
import TuneIcon from '@mui/icons-material/Tune';
import Chip from '@mui/material/Chip';
import DoNotDisturbOnOutlinedIcon from '@mui/icons-material/DoNotDisturbOnOutlined';
import CheckCircleOutlineOutlinedIcon from '@mui/icons-material/CheckCircleOutlineOutlined';
function formatPolynomial(coefficients) {
const superscripts = {
0: '⁰', 1: '¹', 2: '²', 3: '³', 4: '⁴', 5: '⁵', 6: '⁶', 7: '⁷', 8: '⁸', 9: '⁹'
};
const toSuperscript = (num) => {
return String(num)
.split('')
.map(digit => superscripts[digit] || '')
.join('');
};
// Define thresholds for extreme magnitudes.
const LOWER_THRESHOLD = 1e-3;
const UPPER_THRESHOLD = 1e5;
let result = '';
coefficients.forEach((coef, i) => {
if (coef === 0) return;
const power = coefficients.length - i - 1;
const absCoef = Math.abs(coef);
let term = '';
// Add sign
if (result) {
term += coef > 0 ? ' + ' : ' - ';
} else if (coef < 0) {
term += '-';
}
// Only display the coefficient if it's not 1 (or -1) for non-constant terms.
if (absCoef !== 1 || power === 0) {
if (absCoef < LOWER_THRESHOLD || absCoef >= UPPER_THRESHOLD) {
term += absCoef.toExponential(3);
} else {
term += absCoef.toFixed(3);
}
}
// Add the variable and its exponent if needed.
if (power > 0) {
term += 'x';
if (power > 1) term += toSuperscript(power);
}
result += term;
});
return result || '0';
}
function SingleCalibrationPage(props) {
React.useEffect(() => {
document.title = props.title;
}, [props.title]);
return (
<>
<Box>
<Box sx={{ display: "flex", justifyContent: "space-between", mb: 1 }}>
<Typography variant="h5" component="h2">
<Box fontWeight="fontWeightBold">
Calibrations
</Box>
</Typography>
<Box sx={{display: "flex", flexDirection: "row", justifyContent: "flex-start", flexFlow: "wrap"}}>
</Box>
</Box>
</Box>
<SingleCalibrationPageCard />
</>
)
}
function SingleCalibrationPageCard() {
const { pioreactor_unit, device, calibration_name } = useParams();
const unitsColorMap = new DefaultDict(colors)
const [calibration, setCalibration] = useState(null);
const [loading, setLoading] = useState(true);
const [snackbarOpen, setSnackbarOpen] = useState(false);
const [snackbarMessage, setSnackbarMessage] = useState('');
useEffect(() => {
fetchSingleCalibration();
}, [pioreactor_unit, device, calibration_name]);
const fetchSingleCalibration = async () => {
const apiUrl = `/api/workers/${pioreactor_unit}/calibrations/${device}/${calibration_name}`;
try {
const response = await fetch(apiUrl);
const firstResponse = await response.json();
const data = await checkTaskCallback(firstResponse.result_url_path)
setCalibration(data.result[pioreactor_unit]);
} catch (err) {
console.error("Failed to fetch calibration:", err);
} finally {
setLoading(false);
}
};
const handleSnackbarClose = (e, reason) => {
if (reason === 'clickaway') {
return;
}
setSnackbarOpen(false)
}
const handleSetActive = async () => {
const apiUrl = `/api/workers/${pioreactor_unit}/active_calibrations/${device}/${calibration_name}`;
try {
const response = await fetch(apiUrl, { method: "PATCH" });
if (!response.ok) {
throw new Error("Failed to activate calibration");
}
setSnackbarMessage("Calibration set as Active")
setSnackbarOpen(true);
setTimeout(fetchSingleCalibration, 300)
} catch (err) {
console.error("Error setting active calibration:", err);
}
};
const handleRemoveActive = async () => {
const apiUrl = `/api/workers/${pioreactor_unit}/active_calibrations/${device}`;
const response = await fetch(apiUrl, { method: "DELETE" });
if (!response.ok) {
throw new Error("Failed to remove active calibration");
}
setSnackbarMessage("Calibration removed as Active")
setSnackbarOpen(true);
setTimeout(fetchSingleCalibration, 200);
};
if (loading) {
return (
<Box textAlign="center" mt={4}>
<CircularProgress />
</Box>
);
}
if (!calibration) {
return (
<Box mt={3}>
<Typography variant="body1" color="error">
Unable to find calibration data.
</Typography>
</Box>
);
}
const {
calibration_type,
created_at,
curve_data_,
x,
y,
recorded_data,
is_active,
} = calibration;
return (
<Card>
<CardContent sx={{p: 2}}>
<Typography variant="h6" mb={2}>
<Link component={RouterLink} to={`/calibrations/${pioreactor_unit}`} color="inherit" underline="hover" sx={{cursor: "pointer"}} > <PioreactorIcon sx={{verticalAlign: "middle", marginRight: "1px"}} /> {pioreactor_unit} </Link>
<NavigateNextIcon sx={{verticalAlign: "middle", marginRight: "3px"}}/>
<Link component={RouterLink} to={`/calibrations/${pioreactor_unit}/${device}`} color="inherit" underline="hover" sx={{cursor: "pointer"}} > {device} </Link>
<NavigateNextIcon sx={{verticalAlign: "middle", marginRight: "3px"}}/>
{calibration_name}
</Typography>
<CalibrationChart calibrations={[calibration]} deviceName={device} unitsColorMap={unitsColorMap} highlightedModel={{pioreactorUnit: null, calbrationName: null}} title={`Calibration curve for ${calibration_name}`} />
<Box sx={{px: 5, mt: 1}} >
<Table size="small">
<TableBody>
<TableRow>
<TableCell><strong>Calibration name</strong></TableCell>
<TableCell>
<Chip
size="small"
icon={<TuneIcon/>}
label={calibration_name}
/>
</TableCell>
</TableRow>
<TableRow>
<TableCell><strong>Pioreactor</strong></TableCell>
<TableCell>
<Chip
size="small"
icon={<PioreactorIcon/>}
label={pioreactor_unit}
clickable
component={RouterLink}
to={`/calibrations/${pioreactor_unit}`}
/>
</TableCell>
</TableRow>
<TableRow>
<TableCell><strong>Active</strong></TableCell>
<TableCell>{is_active ? <><Chip size="small" label={"Active"} icon={<CheckCircleOutlineOutlinedIcon />} sx={{backgroundColor: "white"}} /></>: ""}</TableCell>
</TableRow>
<TableRow>
<TableCell><strong>Device</strong></TableCell>
<TableCell>{device}</TableCell>
</TableRow>
<TableRow>
<TableCell><strong>Calibration type</strong></TableCell>
<TableCell>{calibration_type}</TableCell>
</TableRow>
<TableRow>
<TableCell><strong>Calibrated on</strong></TableCell>
<TableCell>{dayjs(created_at).format('YYYY-MM-DD') }</TableCell>
</TableRow>
<TableRow>
<TableCell><strong>Fit polynomial</strong></TableCell>
<TableCell>
y={formatPolynomial(curve_data_)}
</TableCell>
</TableRow>
<TableRow >
<TableCell ><strong>Recorded data - {x}</strong></TableCell>
<TableCell sx={{maxWidth: "600px", whiteSpace: "pre-line", wordWrap: "break-word"}}>
<code>{JSON.stringify(recorded_data['x'])}</code><br/>
</TableCell>
</TableRow>
<TableRow >
<TableCell ><strong>Recorded data - {y}</strong></TableCell>
<TableCell sx={{maxWidth: "600px", whiteSpace: "pre-line", wordWrap: "break-word"}}>
<code>{JSON.stringify(recorded_data['y'])}</code><br/>
</TableCell>
</TableRow>
</TableBody>
</Table>
</Box>
<Box mt={2}>
<Button
startIcon={<DoNotDisturbOnOutlinedIcon/>}
variant="text"
color="secondary"
disabled={!is_active}
onClick={handleRemoveActive}
sx={{ textTransform: "none", float: "right", ml: 1 }}
>
Set inactive
</Button>
<Button
startIcon={<CheckCircleOutlineOutlinedIcon />}
variant="contained"
color="primary"
disabled={ is_active}
onClick={handleSetActive}
sx={{ textTransform: "none", float: "right", }}
>
Set active
</Button>
</Box>
<Snackbar
anchorOrigin={{vertical: "bottom", horizontal: "center"}}
open={snackbarOpen}
onClose={handleSnackbarClose}
message={snackbarMessage}
autoHideDuration={7000}
resumeHideDuration={2000}
key={"snackbar" + pioreactor_unit + device + calibration_name}
/>
</CardContent>
</Card>
);
}
export default SingleCalibrationPage;