Software
Overview
We developed three software tools to support MOSAIC’s research and outreach. ML4OCRP predicts a preferred cell ratio, recommends the next ratio to test, and estimates when individual cell groups may reach a target ratio. CalcRatio supports hardware data analysis. Desktiny introduces the project’s core concepts through an interactive desktop cultivation game. Together, these tools support experimental decision-making, quantitative measurement, and science communication.
ML4OCRP
Abstract
Machine Learning for Optimal Cell Ratio Prediction (ML4OCRP) recommends a cell ratio for a stochastic differentiation system and tells each cell group when that ratio is expected. The attainable ratios form a small discrete set, treated here as ten. Measuring every candidate is expensive, and each cell group is observed as a short, noisy trajectory rather than a single number. ML4OCRP fits the ratio–score relationship that has already been measured, proposes a globally preferred ratio, and uses predictive uncertainty to choose the next ratio worth sampling.
Why OCRP
Our measurement approach provides cell ratios and their corresponding experimental scores, but only at a limited number of discrete points. These measurements alone cannot reveal how untested ratios will perform or where the global optimum lies. To address this gap, we developed ML4OCRP to model the relationship between cell ratio and score, predict the optimal ratio, and use prediction uncertainty to recommend the next ratio to test. By turning measurement data into actionable experimental guidance, ML4OCRP helps us search more effectively for the cell ratio that maximises our target score. The software also includes an independent time-query function to estimate when a cell population reaches a target ratio.
- OCRP learns score as a function of ratio only. A deep-kernel Gaussian process returns both a predicted score and an uncertainty, so the same model can name a predicted optimum and recommend the next experiment.
- The time query is separate. Given a target ratio, it asks, for each cell group, whether that ratio was already seen, will be reached later, or is not reached inside the search horizon. The current query fits the modelling group's BxB1 recombination ODE and a residual on top of it. Combining that mechanistic model with the software was a goal from the start; this is the version that implements it.
Optimisation iteration
-
Version 1.0
The first version defined the data contract and a joint model. Ratio and score tables were inner-joined on
(id, time), grouped by cell group, and packed into a padded tensor of(time, ratio, score). A Transformer encoder (TimeAttentionEncoder) compressed each variable-length trajectory into one global feature, using a learnable token in the style of BERT's[CLS]token. That feature was repeated at every time point, concatenated with the current ratio, and passed to a deep-kernel Gaussian process (DeepKernelGP) that predicted score. Upper confidence bound (UCB) on the posterior then suggested the next ratio to sample. The intention was to let one model absorb both the time course of the ratio and the ratio–score map. -
Version 2.0
The program was split into command-line modules: preprocessing, the model definition, training helpers, training, ratio recommendation, and a per-group time query. The split was to keep the code organised, with one responsibility per file. Each job can be run with its own arguments. The network was still
TimeAttentionEncoderplusDeepKernelGP.RatioTimePredictorwas added because leaving time in the attention model was not working. It fitted a scikit-learn Gaussian process from time to ratio for each cell group. A query first looked for a historical time within a tolerance of the target ratio. If none existed, it searched the predicted mean forward in time and returned the earliest crossing, or reported that the ratio was not reached. -
Version 3.0
The optimal-ratio prediction was still poor. Because that prediction is the main task, OCRP was reduced to the ratio–score map.
TimeAttentionEncoderwas replaced byRatioFeatureEncoder, which embeds a scalar ratio and is pretrained with an auxiliary score head. The padded trajectory tensor and the saved global feature were removed with the old encoder. The time course stayed inRatioTimePredictor. -
Version 4.0 (Final version)
The time query is where the mechanistic model enters the software. From the beginning, the aim was to combine the modelling group's BxB1 recombination ODE with ML4OCRP; this version is the one that does it. For each cell group the predictor fits that ODE and then a residual Gaussian process or polynomial, instead of a Gaussian process on time alone.
Fitting the ODE for every cell group is slow, so
query_per_id.pyleaves--fit_odeoff unless it is passed.scripts/Val.shandscripts/Val.ps1pass it, together with--max_time 24.app.pycalls the sameModel/implementation. The interface is there both for teammates who are not running the command line and for demonstration. In the browser, the per-group query runs one group at a time so the page can show progress. It does not start the process pool used by the command-line query.
Learn more about ML4OCRP
OCRP predicts the score of a ratio that may not have been measured.
- Pretrain the encoder.
RatioFeatureEncodermaps the scalar ratio through a linear layer (1 to 32), a ReLU, and a linear layer (32 to 16). A linear head on that 16-dimensional embedding predicts score. This stage only teaches the encoder a useful representation. - Freeze the encoder. The score head is not used again. Each training pair becomes the 17-dimensional vector
[ratio | embedding]. - Fit a deep-kernel Gaussian process. An MLP (17 to 32, ReLU, 32 to 8) maps that vector into a latent space. An exact Gaussian process with a zero mean and an automatic-relevance-determination RBF kernel lives in that space, with a Gaussian observation noise. Training maximises the exact marginal likelihood.
-
Read the posterior in two ways.
- The predicted optimum maximises the posterior mean by multi-start gradient steps on the ratio interval
[0.01, 5]. - The next experiment maximises UCB,
mean + β · stdwithβ = 2, on a grid over[0.1, 10].[1]
- The predicted optimum maximises the posterior mean by multi-start gradient steps on the ratio interval
The time query does not go through this network. For each cell group it fits BxB1 kinetic parameters, models the residual between the ODE and the observed ratios, and searches for the time at which the predicted ratio meets the target. The result is a time and a status: -1 if the ratio was already seen in the recorded history, 1 if it is predicted in the future, and 0 if it is not reached.
Workflow
The nine algorithms are set out in full below — the pseudocode inside steps 3–6 of the workflow above. Steps 1 (fitting_ratio.py), 2 (fitting_score.py), and 7 (get_actual_ratio.py) have no separate algorithm.
| Workflow step | Script | Procedure |
|---|---|---|
| 3. Preprocess | preprocess_data.py | Algorithm 1 · build_id_data_dict |
| 4. Train | ocrp_model_train.py | Algorithm 2 · RatioFeatureEncoder |
Algorithm 3 · pretrain_ratio_encoder | ||
Algorithm 4 · build_global_dataset | ||
Algorithm 5 · train_ocrp_model | ||
| 5. Recommend | predict_ratio_and_recommend_by_ucb.py | Algorithm 6 · predict_optimal_ratio |
Algorithm 7 · ucb_acquisition | ||
| 6. Time query | query_per_id.py | Algorithm 8 · RatioTimePredictor.fit_id |
Algorithm 9 · RatioTimePredictor.query |
Table 1-1. The nine-step workflow, the script that runs each step, and the algorithm that carries it out.
Step 3 · Preprocess
Algorithm 1 Merge ratio and score tables build_id_data_dict
Input: ratio table; score table; join type merge_how
Output: \mathrm{id\_data\_dict}[\mathrm{id}] = (\mathrm{times},\mathrm{ratios},\mathrm{scores})
\mathrm{merged}\gets join the tables on (\mathrm{id},\mathrm{time}) using merge_how
for each (\mathrm{id},\mathrm{rows}) in \mathrm{merged} do
sort \mathrm{rows} by time
\mathrm{id\_data\_dict}[\mathrm{id}]\gets(\mathrm{time},\mathrm{ratio},\mathrm{score})
end for
return \mathrm{id\_data\_dict}
Step 4 · Train
Algorithm 2 Encode a ratio RatioFeatureEncoder
Input: ratio x of shape (\ldots,1)
Output: embedding of size d_{\mathrm{model}}; a scalar score during pretraining
h\gets\mathrm{ReLU}(\mathrm{Linear}(1\to\mathrm{hidden\_dim})(x))
\mathrm{embedding}\gets\mathrm{Linear}(\mathrm{hidden\_dim}\to d_{\mathrm{model}})(h)
\mathrm{score}\gets\mathrm{Linear}(d_{\mathrm{model}}\to 1)(\mathrm{embedding}) // pretraining only
return \mathrm{embedding} from get_feature; (\mathrm{embedding},\mathrm{score}) from the pretraining forward pass
Algorithm 3 Pretrain the encoder pretrain_ratio_encoder
Input: sequences of (\mathrm{time},\mathrm{ratio},\mathrm{score}); \mathrm{epochs}, \mathrm{lr}, \mathrm{batch\_size}
Output: encoder in eval mode
\mathrm{pairs}\gets every (\mathrm{ratio},\mathrm{score}) from every sequence // time is not an input
for \mathrm{epoch}\gets 1 to \mathrm{epochs} do
for each minibatch of \mathrm{pairs} do
(\cdot,\mathrm{predicted\_score})\gets\mathrm{encoder}(\mathrm{ratio})
step Adam on \mathrm{mean\_squared\_error}(\mathrm{predicted\_score},\mathrm{score})
end for
end for
\mathrm{encoder.eval()}
return \mathrm{encoder}
Algorithm 4 Build the Gaussian-process dataset build_global_dataset
Input: sequences; frozen encoder
Output: dataset of (x,\mathrm{score}), with x shaped (1+d_{\mathrm{model}})
for each (\mathrm{time},\mathrm{ratio},\mathrm{score}) in every sequence do
\mathrm{embedding}\gets\mathrm{encoder.get\_feature}(\mathrm{ratio})
x\gets\mathrm{concatenate}(\mathrm{ratio},\mathrm{embedding})
store (x,\mathrm{score})
end for
return the stacked dataset
Algorithm 5 Fit the deep-kernel Gaussian process train_ocrp_model
Input: \mathrm{id\_data\_dict}; widths; learning rate; epoch counts
Output: checkpoint OCRP_model.pth
pretrain the encoder, then freeze every encoder parameter
\mathrm{dataset}\gets\mathrm{build\_global\_dataset}(\mathrm{encoder})
(\mathrm{train\_set},\mathrm{val\_set})\gets random split of \mathrm{dataset} by \mathrm{val\_ratio}
\mathrm{likelihood}\gets\mathrm{GaussianLikelihood}
\mathrm{gp}\gets\mathrm{DeepKernelGP}(\mathrm{train}_x,\mathrm{train}_y)
feature \gets ReLU MLP from 1+d_{\mathrm{model}} to d_{\mathrm{feat}}
mean \gets 0; kernel \gets scale \times RBF with one length-scale per latent dimension
for \mathrm{epoch}\gets 1 to n_{\mathrm{epochs}} do
\mathrm{loss}\gets\mathrm{reduce}(-\mathrm{exact\_marginal\_log\_likelihood}(\mathrm{gp}(\mathrm{train}_x),\mathrm{train}_y))
step Adam on the GP and the likelihood
end for
save encoder, GP, likelihood, \mathrm{train}_x, \mathrm{train}_y, and config
return the checkpoint path
Step 5 · Recommend
Algorithm 6 Predict the optimal ratio predict_optimal_ratio
Input: GP; frozen encoder; interval [\mathrm{low},\mathrm{high}]; n_{\mathrm{starts}}; n_{\mathrm{steps}}
Output: (\mathrm{best\_ratio},\mathrm{best\_mean})
\mathrm{best\_mean}\gets-\infty
for each \mathrm{start} in \mathrm{linspace}(\mathrm{low},\mathrm{high},n_{\mathrm{starts}}) do
\mathrm{ratio}\gets\mathrm{start}
for \mathrm{step}\gets 1 to n_{\mathrm{steps}} do
x\gets\mathrm{concatenate}(\mathrm{ratio},\mathrm{encoder.get\_feature}(\mathrm{ratio}))
step Adam on -\mathrm{gp}(x).\mathrm{mean}
clamp \mathrm{ratio} to [\mathrm{low},\mathrm{high}]
end for
if \mathrm{gp}(\mathrm{ratio}).\mathrm{mean}>\mathrm{best\_mean} then
keep this ratio
end if
end for
return \mathrm{best\_ratio},\mathrm{best\_mean}
Algorithm 7 Recommend the next ratio ucb_acquisition
Input: GP; likelihood; frozen encoder; interval [\mathrm{low},\mathrm{high}]; n_{\mathrm{candidates}}; \beta
Output: (\mathrm{best\_ratio},\mathrm{best\_ucb})
\mathrm{best\_ucb}\gets-\infty
for each \mathrm{ratio} in \mathrm{linspace}(\mathrm{low},\mathrm{high},n_{\mathrm{candidates}}) do
x\gets\mathrm{concatenate}(\mathrm{ratio},\mathrm{encoder.get\_feature}(\mathrm{ratio}))
\mathrm{posterior}\gets\mathrm{gp}(x)
\mathrm{ucb}\gets\mathrm{posterior.mean}+\beta\cdot\mathrm{posterior.std}
if \mathrm{ucb}>\mathrm{best\_ucb} then
keep this ratio
end if
end for
return \mathrm{best\_ratio},\mathrm{best\_ucb}
Step 6 · Time query
Algorithm 8 Fit one cell group RatioTimePredictor.fit_id
Input: \mathrm{id}; \mathrm{times}; \mathrm{ratios}; \mathrm{fit\_ode}; \mathrm{model\_type}
Output: stored residual model, kinetic parameters, and history
if the series has fewer than \mathrm{min\_points} then
return skip this \mathrm{id}
end if
if \mathrm{fit\_ode} then
\mathrm{parameters}\gets differential evolution on the ODE mean squared error
if that search fails then
\mathrm{parameters}\gets bounded local minimization, or the defaults
end if
else
\mathrm{parameters}\gets default kinetics
end if
\mathrm{ode\_ratio}\gets BxB1 ODE at each observed time
\mathrm{residual}\gets\mathrm{ratios}-\mathrm{ode\_ratio}
if \mathrm{model\_type} is \mathrm{gpr} then
fit a Gaussian process from time to residual
else
fit a polynomial from time to residual
end if
store the residual model, parameters, and (\mathrm{times},\mathrm{ratios})
Algorithm 9 Query time to the target ratio RatioTimePredictor.query
Input: \mathrm{id}; \mathrm{target\_ratio}; \mathrm{max\_time}
Output: (\mathrm{found},\mathrm{time})
if some historical |\mathrm{ratio}-\mathrm{target\_ratio}|\le\mathrm{tolerance} then
return the earliest such time
end if
if the target is above every observed ratio and the last slope \le 0 then
return not found
end if
if the target is below every observed ratio and the last slope \ge 0 then
return not found
end if
t_{\mathrm{left}}\gets last observed time
t_{\mathrm{right}}\gets\mathrm{max\_time}\times\mathrm{horizon\_factor}
for \mathrm{iteration}\gets 1 to \mathrm{search\_iter} do
evaluate \mathrm{predict\_ratio} on a uniform grid from t_{\mathrm{left}} to t_{\mathrm{right}}
if \mathrm{predicted\_ratio}-\mathrm{target\_ratio} never changes sign then
return not found
end if
shrink [t_{\mathrm{left}},t_{\mathrm{right}}] to the first sign-change interval
if the interval is narrower than \mathrm{time\_atol} then
break
end if
end for
t\gets midpoint of [t_{\mathrm{left}},t_{\mathrm{right}}]
if |\mathrm{predict\_ratio}(t)-\mathrm{target\_ratio}|\le\mathrm{query\_tol\_factor}\times\mathrm{tolerance} then
return (\mathrm{found},t)
end if
return not found
The synthetic ratio table has more cell groups than target ratios. Each group's ratio at 24 h lies near one of ten values, log-spaced from 0.5 to 6. fitting_score.py then labels those ratios. The comparison across scoring functions is in Score shapes.
Score shapes
fitting_score.py can turn the same ratios into scores with five functions. The default remains the symmetric Gaussian, so a call that omits --score_fn is unchanged.
--score_fn | Shape | Formula |
|---|---|---|
gaussian | Symmetric peak at --opt_ratio | max_score * exp(-((ratio - opt_ratio)^2) / (2 * sigma^2)) |
log_gaussian | Asymmetric peak at --opt_ratio | The same Gaussian, evaluated on log(ratio) |
bimodal | Peaks at --opt_ratio and --opt_ratio_2 | Weighted sum of two Gaussians, scaled so the taller peak equals --max_score |
sigmoid | Increasing S, midpoint --opt_ratio | max_score / (1 + exp(-(ratio - opt_ratio) / sigma)) |
linear | Straight ramp | 0 at --linear_min, --max_score at --linear_max, clipped outside |
Table 1-2. The five score shapes fitting_score.py accepts, and the formula behind each.
test_score_shapes.py builds one ratio table (40 cell groups whose 24 h ratios lie near the ten default targets, seed 0) and scores it with each function. OCRP is trained with the default schedule: 100 pretraining epochs, 200 Gaussian-process epochs, seed 0. The predicted optimum maximises the posterior mean on [0.5, 6], the same interval as the targets. Regret is the true score at the true optimum minus the true score at the predicted ratio. Score RMSE compares the posterior mean with the true scoring function on that interval.
| Scoring function | True optimum | Predicted | Abs. error | Regret | Score RMSE | UCB |
|---|---|---|---|---|---|---|
| Gaussian | 2.50 | 2.51 | 0.006 | 0 | 0.010 | 2.50 |
| Log-Gaussian | 2.50 | 2.48 | 0.025 | 0.0004 | 0.010 | 2.44 |
| Bimodal | 4.00 | 3.73 | 0.27 | 0.207 | 0.077 | 3.72 |
| Sigmoid | 6.00 | 6.00 | 0 | 0 | 0.004 | 6.00 |
| Linear | 6.00 | 6.00 | 0 | 0 | 0.031 | 6.00 |
Table 1-3. In-silico recovery of each score shape: the true optimum against what the model predicts.
The symmetric peak, the asymmetric peak, the sigmoid, and the linear ramp stay within 0.03 of the true optimum, and the regret is at most 0.0004. The two-peak function is looser: the predicted ratio is 3.73 against the taller peak at 4.00, and the regret is 0.21. UCB on that fit recommends 3.72.
Architecture
Dependencies
From the repository root, the setup script creates a conda environment named ocrp with Python 3.13 and installs the pinned packages in scripts/requirements.txt.
Windows:
powershell -ExecutionPolicy Bypass -File scripts\setup_env.ps1
conda activate ocrp
$env:KMP_DUPLICATE_LIB_OK = "TRUE"
Mac or Linux:
bash scripts/setup_env.sh
conda activate ocrp
export KMP_DUPLICATE_LIB_OK=TRUE
The same packages are required if you run the scripts or the GUI directly.
| Package | Used for |
|---|---|
| Python 3.13 | All scripts |
| NumPy | Arrays and .npy dictionaries |
| pandas | CSV tables |
| PyTorch | Encoder, Gaussian process tensors, and device selection |
| GPyTorch | Exact deep-kernel Gaussian process |
| SciPy | ODE integration and parameter fitting in the time query and the in silico scripts |
| scikit-learn | Residual Gaussian process in the time query |
| tqdm | Progress display during the per-ID query |
| Matplotlib | Figures written by InSilicoValidation/test_score_shapes.py |
| Streamlit | app.py only |
Table 1-4. Packages the ML4OCRP scripts need.
On Windows and Mac, PyTorch and the Intel OpenMP runtime used by NumPy can abort at import. The activate lines above set KMP_DUPLICATE_LIB_OK for that terminal. app.py and InSilicoValidation/test_score_shapes.py set it before importing the libraries. scripts/Val.sh and scripts/Val.ps1 set it for the pipeline.
Training and the per-ID query select MPS, then CUDA, then CPU when --device is omitted. Ratio recommendation selects CUDA, then CPU.
How to use it
The ML4OCRP source code is at https://gitlab.igem.org/2026/software/shanghaitech-china/ml4ocrp. It is Apache License 2.0.
From the repository root, the seven-step pipeline finds the repository from the script path. It uses the conda environment named ocrp when that environment exists, and otherwise uses python on PATH. It passes --fit_ode and --max_time 24. The synthetic table ends at 24 h, and query_per_id.py defaults --max_time to 12 h.
Windows:
powershell -ExecutionPolicy Bypass -File scripts\Val.ps1
Mac or Linux:
bash scripts/Val.sh
On Unix the same pipeline is make -f scripts/Makefile pipeline. The score-shape check behind the result table is make -f scripts/Makefile score-shapes, which runs InSilicoValidation/test_score_shapes.py. The workbench is make -f scripts/Makefile gui.
The Python scripts resolve ../Data from their own directory, including Data/Model for the checkpoint, so run them from Model/ or InSilicoValidation/, not from the repository root. A laboratory run, without the synthetic data or the final ODE check, is:
cd Model
python preprocess_data.py
python ocrp_model_train.py
python predict_ratio_and_recommend_by_ucb.py
python query_per_id.py --fit_ode
--fit_ode is off unless you pass it, because fitting the ODE for every cell group is slow. scripts/Val.sh and scripts/Val.ps1 pass it, and they also pass --max_time 24. Every other hyperparameter is an optional flag with a default. The full list, including types and help text, is in Model/SCRIPT_ARGUMENTS.md. Common overrides are --d_model, --hidden_dim, --n_epochs, and --beta.
GUI: WebOcrp
From the repository root, with the same environment active:
streamlit run app.py
The page is both a way for teammates to run the pipeline without the command line and a demonstration of the same software. It imports Model/, so it trains and queries the same model as the command line. Checkpoints written by either side can be read by the other when hidden_dim stays at its default of 32.
The workbench has four tabs.
-
Preprocess. Upload the two CSVs, point at local files, or load an existing
id_data_dict.npy. After a successful merge, every ratio–score pair is drawn on one scatter plot, with ratio on the horizontal axis and score on the vertical axis.
Figure 1-7. The Preprocess tab accepts the ratio and score tables, or an existing id_data_dict.npy.
Figure 1-8. After the merge, every ratio–score pair is plotted with ratio on the horizontal axis and score on the vertical axis. -
Train. Fit the encoder and the deep-kernel Gaussian process. Width, pretraining, validation fraction, and the marginal-likelihood reduction are on the page.
Figure 1-9. Training uses the same encoder and deep-kernel Gaussian process as the command line.
Figure 1-10. A finished run writes OCRP_model.pth. Withhidden_dimleft at 32, that checkpoint can be loaded by the command-line scripts. -
Recommend. Load
OCRP_model.pth, report the ratio that maximises the predicted score, and report the UCB recommendation. The page also plots mean, standard deviation, and UCB against ratio.
Figure 1-11. Recommendation searches the posterior mean for the best ratio and scores a grid with UCB.
Figure 1-12. The plotted mean is the predicted score. The UCB curve, mean plus β times the standard deviation, marks the next ratio to sample. -
Query. For the recommended ratio, or for a ratio you type, fit each cell group and return a time and a status. This tab walks the groups one by one so a progress bar can update. It does not start the process pool used by
query_per_id.py.
Figure 1-13. The query walks cell groups one at a time so the page can show progress. It does not start the command-line process pool.
Figure 1-14. Each group returns a time and a status: already seen, predicted in the future, or not reached.
CalcRatio
Abstract
Software support for the hardware pigment-mixing tests. See our Hardware page. Phyphox colour recordings of blue and yellow solutions are turned into a blue volume fraction.[2] See our Measurement page.
Two phyphox experiments mixed blue and yellow pigment stocks in known volume ratios. The stocks did not start at the same concentration, and the camera exposure was not the same, so a single plane fitted to raw Hue and Saturation does not transfer from one experiment to the other.
CalcRatio keeps each experiment's pure yellow (ratio = 0) and pure blue (ratio = 1) as colour endpoints. A sample is written as its position between those endpoints, z_hue and z_saturation. One logistic curve, shared by both experiments, maps that position to the blue volume fraction. On 63 samples the shared fit has R-squared = 0.801 and RMSE = 0.118. The raw Hue–Saturation plane on the same rows has R-squared = 0.638.
Experiment 1 (data/1_*) has five recorded stages; the model uses stage 2 (21 samples). Experiment 2 (data/2_*) has one stage and uses that stage (42 samples).
This is the second fit. The first used only Hue and Saturation and had to be repeated for each batch. Adding each batch's pure blue and pure yellow is what lets one curve cover both batches. The two steps are written out under Optimisation iteration.
Why this pipeline
Hardware needs a fraction it can compare across batches. The phone records Hue and Saturation, not the volume fraction directly. Two facts from the mixing experiment decide the form of the model.
The same volume ratio does not land on the same Hue and Saturation when the stock concentrations or the exposure change. Pure yellow and pure blue measured in that same batch carry those changes. Scaling Hue and Saturation by those two readings puts both batches into one coordinate system: 0 at that batch's yellow and 1 at that batch's blue.
The blue volume fraction lies between 0 and 1. It rises as the sample moves from yellow toward blue, and the rise flattens near the two pure stocks. A logistic of the rescaled hue and saturation has that shape. The fitted equation and the comparison with the first plane are in Optimisation iteration.
Path defaults below are relative to the repository root. The scripts resolve them from the folder that contains scripts, so they do not depend on the working directory. A relative path passed on the command line is still relative to the working directory. Run the commands below from the repository root.
python scripts/build_id_ratio_dict.py
python scripts/data_preprocess.py
python scripts/data_preprocess.py -i data/1_original \
-o data/1_processed \
--dict_file data/1_settings/mapping.npy \
-n 5 \
--key_stage 2
python scripts/fit_model.py
The first preprocess command is experiment 2 (one stage). The second is experiment 1 (five stages, keep stage 2).
Optimisation iteration
The predictors changed once. The first equation saw only the sample colour and had to be fit again for every batch. The second equation also sees that batch's pure blue and pure yellow, and one fit is shared.
-
Version 1: Hue and Saturation, one plane per batch
The sample's Hue and Saturation were the only inputs. Each experiment got its own plane:
\mathrm{ratio} = a_0 + a_1\,\mathrm{Hue} + a_2\,\mathrm{Saturation}Fit n R2 RMSE Experiment 1 alone 21 0.805 0.134 Experiment 2 alone 42 0.856 0.091 Both batches, one plane 63 0.638 0.159 Table 2-1. Per-batch Hue–Saturation planes against one plane fitted to both batches.
Inside one batch the plane follows the prepared fraction. Forcing both batches onto that same plane drops R2 from about 0.8 to 0.638, because the pure-stock colours are different. A new concentration or a new exposure needs a new pair of coefficients.
-
Version 2: Hue, Saturation, Blue, and Yellow, one curve across batches
Blue and Yellow are the Hue and Saturation of the pure blue stock and the pure yellow stock measured in the same batch. They rescale the sample before the fraction is predicted:
\begin{aligned} z_{\mathrm{hue}} &= \frac{\mathrm{Hue} - \mathrm{Yellow\_Hue}}{\mathrm{Blue\_Hue} - \mathrm{Yellow\_Hue}} \\ z_{\mathrm{saturation}} &= \frac{\mathrm{Saturation} - \mathrm{Yellow\_Saturation}}{\mathrm{Blue\_Saturation} - \mathrm{Yellow\_Saturation}} \\ \mathrm{ratio} &= \frac{1}{1+\exp\left(-(-1.1397 + 1.4533\, z_{\mathrm{hue}} + 1.8247\, z_{\mathrm{saturation}})\right)} \end{aligned}The three coefficients are estimated once, on all 63 rows.
Fit n R2 RMSE Shared logistic, both batches 63 0.801 0.118 Experiment 1 under that curve 21 0.781 0.142 Experiment 2 under that curve 42 0.815 0.103 Table 2-2. The shared logistic curve against the per-batch planes.
The shared curve is a little looser than each batch's own Hue–Saturation plane, and much tighter than one Hue–Saturation plane placed on both batches at once. A later batch keeps these coefficients. It only needs its own pure blue and pure yellow measured under the same conditions, which supplies Blue and Yellow for the rescaling.
Workflow and architecture
Dependencies
Python 3.12 or newer. Packages below are the ones imported by the three scripts.
| Package | Used for |
|---|---|
numpy | Arrays, circular means, and .npy dictionaries |
pandas | Tables, the sample-sheet CSV, and phyphox Excel files |
openpyxl | Reading .xlsx workbooks through pandas |
matplotlib | Fit surface, residual plots, predicted-versus-actual plot, and QQ plot |
scipy | Logistic least squares and the t distribution for coefficient tests |
statsmodels | Linear Hue–Saturation baseline and the residual QQ plot |
Table 2-3. Packages the CalcRatio scripts need.
Raw output
python scripts/fit_model.py prints the following. Residuals are fitted ratio minus measured ratio.
mixing model
z_hue = (Hue - Yellow_Hue) / (Blue_Hue - Yellow_Hue)
z_saturation = (Saturation - Yellow_Saturation) / (Blue_Saturation - Yellow_Saturation)
ratio = 1 / (1 + exp(-(-1.1397 + 1.4533 * z_hue + 1.8247 * z_saturation)))
parameters
coef std_err t p
intercept -1.1397 0.1314 -8.6743 0.0
z_hue 1.4533 0.1538 9.4490 0.0
z_saturation 1.8247 0.2084 8.7550 0.0
R-squared: 0.8012
RMSE: 0.1176
baseline ratio ~ Hue + Saturation R-squared: 0.6375
pure yellow / pure blue endpoints
Yellow_Hue Yellow_Saturation Blue_Hue Blue_Saturation
group
1 177.788 0.791 215.408 0.990
2 107.502 0.272 210.154 0.586
fit by group
1: n=21 R-squared=0.7809 RMSE=0.1417
2: n=42 R-squared=0.8152 RMSE=0.1034
residual skew: 0.5731694436244197
residual kurtosis: -0.3345401332238507
Saved files:
| File | Content |
|---|---|
data/2_processed/combined_modeling_data.pkl | Combined modelling table, including endpoints, normalised colour, and predicted ratio |
data/2_processed/mixing_model.npy | Three coefficients and the stage index used for each experiment |
Table 2-4. The files CalcRatio writes.
Reading the fit
The intercept and both colour coefficients have p-values below 0.001 (60 residual degrees of freedom). z_hue and z_saturation each move the predicted fraction in the blue direction.
An RMSE of 0.118 is about twelve percentage points of blue volume fraction. The largest absolute residual on this fit is 0.257. That is a usable check of the hardware colour channel across the two stocks. It is coarse if the hardware needs the fraction to a few percentage points.
Experiment 2 (n = 42) is the tighter group: R2 = 0.815, RMSE = 0.103. Experiment 1 (n = 21) is looser: R2 = 0.781, RMSE = 0.142. Residual skew is 0.57 and kurtosis is -0.33, so the errors lean slightly positive and do not show a heavy tail.
A straight line fitted inside one experiment alone is a little tighter (about 0.80 for experiment 1 and 0.86 for experiment 2). That line belongs to one stock pair and one camera setup. The shared logistic is the model that accepts a new pair after the pure yellow and pure blue of that pair have been measured.
Endpoint colours show why the normalisation is doing the work:
| Experiment | Yellow Hue | Yellow Saturation | Blue Hue | Blue Saturation |
|---|---|---|---|---|
| 1 | 177.788° | 0.791 | 215.408° | 0.990 |
| 2 | 107.502° | 0.272 | 210.154° | 0.586 |
Table 2-5. Pure yellow and pure blue endpoints for each experiment.
Experiment 1's pure yellow on stage 2 is 177.8°, while samples with 5–25% blue sit near 126–139°. The pure-yellow reading is not at the yellow end of that stage, so some z_hue values fall below 0. Stage 1 of the same recordings tracks ratio more closely (correlation about 0.94) than stage 2 (about 0.82). The fit follows the requested stage 2. If stage 2 is a second illumination rather than the sample, the endpoints should be recomputed.
The ratio of stock concentrations was not entered as its own parameter. Only the ratio of the two strengths would change the curve, and that ratio is not separated from the logistic intercept on these two batches. The measured endpoints already carry the batch-to-batch colour shift.
Reading the figure
Blue circles are experiment 1. Orange triangles are experiment 2.
z_hue and z_saturation. Experiment 2 sits between the yellow and blue endpoints. Experiment 1 extends below z_hue = 0 because its stage-2 pure yellow is not the yellow extreme of that series.
Software availability
The source code for CalcRatio is available in the GitLab repository.
Desktiny
Why Desktiny
Desktiny is a science outreach game about our project, developed in collaboration with the iHP team. Its main purpose is to help the public understand ShanghaiTech-China 2026's MOSAIC project. Through a hands-on desktop experience that users can observe over time, we aim to introduce people without a background in synthetic biology to the project's core concepts: cell states, stochastic differentiation, and population composition.
The game turns feedback from the cultivation process into visible changes: nutrients are gradually consumed, waste accumulates, and environmental conditions affect the health of the bacterial population. As the population grows, its care requirements also increase. Players need to decide when to replenish nutrients and when to clean based on the current state.
Character appearances and event notes provide another incentive to explore. Players can observe game outcomes resulting from different initial traits and cultivation experiences, view appearances they have encountered in the collection, and review related knowledge in the Science Log. We hope this “action—feedback—observation—reading” cycle provides an accessible interactive medium for science outreach on microbial cultivation and synthetic biology.
Desktiny is an educational and experiential tool. Character colours represent simplified game states, and their probabilities are determined by gameplay rules. HP is an abstract environmental health indicator.
Video Demonstration
The following recording provides a visual introduction to the Desktiny interface.
Installation and set-up
Download the Windows demo
The current release supports Windows x64. Users do not need to install Godot, Python, or any other development environment.
- Open the Desktiny 0.1.4 download page.
- Download
Desktiny-0.1.4-windows-x64-compact.zip, which is approximately 40.3 MB. - Right-click the archive, select “Extract All”, and extract its complete contents into a folder.
- Open the extracted folder and double-click
Desktiny.exe. - Press any key on the title screen to enter the menu, then select New Game to begin.
Extract the archive completely before running the game, and keep all files included in the package.
Display and compatibility launch
The cultivation interface is a small transparent desktop window: HP, HUNGER, and Feed remain visible above the fermentation tank for convenient viewing and interaction at any time. The desktop background shows through the transparent areas of the window.
If launching directly causes graphics startup issues, try Play-Compatibility.cmd in the same folder to launch in compatibility graphics mode.
Game progress is saved locally. When updating the game, you can extract the new version into a different folder; do not delete the following save directory if you want to retain Continue and Science Log progress:
%APPDATA%\Godot\app_userdata\Desktiny\
Running from source
Users who wish to inspect or modify the implementation can visit the official iGEM software source repository. After downloading the source code, use Godot 4.7.2 Standard to import project.godot from the root directory, wait for resource import to finish, then press F5 to run.
Regular players only need the Windows game package. Windows x64 export templates matching the Godot version are required only when building your own executable. The team's code is released under the MIT open-source license; licenses and attributions for third-party components are provided in the relevant files in the repository.
Starting a culture
Select New Game from the main menu to enter the initial trait setup screen. Players can allocate points among four traits: reproduction, adaptation, metabolism, and resilience, with a total of no more than 20. These settings contribute to growth, care, or appearance probability calculations in the game; they are game parameters, not experimentally measured biological traits.
For your first playthrough, you can use the default configuration and confirm it to begin cultivation. If a save already exists, select Continue to resume the previous session.
Progress bars
| Interface element | What it represents | How players should respond |
|---|---|---|
| HP (pink) | Current environmental and bacterial population health, ranging from 0–100; fuller is better | Check nutrient and waste levels, improve the environment, and wait for recovery |
| HUNGER (yellow-green) | Remaining nutrients, ranging from 0–100; fuller is better | Click Feed to replenish nutrients when the bar decreases |
| Feed | Direct feeding button | Adds 22 nutrient points each time, up to a maximum of 100 |
| Clean | Cleaning action in the right-click menu | Removes 28 waste points each time, down to a minimum of 0 |
Table 3-1. The cultivation interface: what each element shows and how to respond to it.
Feeding and cleaning
To feed, click Feed directly above the tank. To clean, right-click the fermentation tank and select Clean.
The two actions share a cooldown. After a care action, you may need to wait briefly before performing the next one; repeated rapid clicks do not provide unlimited nutrient replenishment or waste removal. When an event popup appears, read and confirm it before the game resumes.
Nutrients decrease during cultivation, while waste gradually accumulates. Feeding alone cannot resolve waste problems; if HUNGER is still sufficiently full but HP is falling, check whether cleaning is needed.
Under the current rules, nutrient levels below 20 or waste levels of 55 or higher damage health. With nutrients at least 50 and waste below 30, the environment supports health recovery. Players can use this feedback to guide care without waiting until HP becomes very low.
Division and stage changes
During cultivation, the bacterial population accumulates growth progress and divides when the conditions are met. The current population cap is 8; continued growth after reaching the cap leads to subsequent cultivation stages.
The game has three stages. Characters become larger when advancing to a new stage, but do not continuously enlarge over time within the same stage. Population size, stage, and cultivation experiences also affect subsequent appearances and care requirements.
Reaching the third stage satisfies the completion condition for the session. After completion, further division and passaging stop, but maintenance and desktop interactions remain available. If HP falls to 0, the session ends in failure. For your first playthrough, we recommend learning feeding and cleaning before trying different trait configurations.
Exploring the desktop
Go to Desktop in the right-click menu lets bacteria leave the fermentation tank and move around the desktop; events that send them outside may also occur during the game.
To recall them, right-click the fermentation tank and select Return to Tank. Bacteria outside the tank will start returning, which takes some time. You can also right-click a bacterium on the desktop and use its return option.
Collection and Science Log
Open Collection from the main menu to browse character appearances in a centered scrolling interface. Appearances not yet encountered are shown as ?; only those that have actually appeared in the current session display images. Collection cards are for browsing only: they cannot be clicked to select appearances or configure their quantities. Click Back at the bottom to return.
Starting a New Game clears the current session's collection; using Continue restores the collection from the save. When the game is reopened and no session has yet been started or loaded, the collection remains undisplayed.
Science Log is an event-driven science notebook. Relevant entries unlock after corresponding events such as feeding, cleaning, division, or environmental stress occur; content whose events have not been triggered does not automatically become available. Unlocked Science Log records persist across New Game sessions, supporting gradual exploration and review.
Pace, saving and continuing
Right-click the fermentation tank to access the following options:
| Option | Purpose |
|---|---|
| Speed | Switches the game speed; faster speeds also make care requirements arise sooner |
| AFK Care | Turns automatic care on or off, allowing you to step away briefly |
| Return to Menu | Saves current progress and returns to the main menu |
| Quit | Saves current progress and exits the game |
Table 3-2. Options on the fermentation tank's right-click menu.
Automatic care is a convenience feature in the game and does not imply that real experiments can run without supervision. At the end of a session, we recommend returning to the menu or exiting through the menu; use Continue next time to resume care.
Implementation and Reproducibility
Desktiny is implemented in GDScript using Godot. Responsibilities are organised across state management, simulation systems, event handling, and interface code:
| Component | Responsibility |
|---|---|
GameManager.gd | Run state, local saves, encountered appearances, and Science Log unlocks |
WindowManager.gd | Window modes, scene transitions, and desktop wandering windows |
EnvironmentSystem.gd | Nutrient consumption, waste accumulation, feeding, and cleaning |
BacteriaSystem.gd | Growth, health, division, and stage progression |
ProbabilityModel.gd | Rule-based probabilities for appearance outcomes |
EventSystem.gd | Event conditions, consequences, and science notes |
| UI scripts and scenes | Rendering, controls, menus, collection, and desktop interaction |
During cultivation, environment and growth updates change the run state. Event checks trigger the corresponding responses and notes, while the interface reflects the current state.
Software Availability
Desktiny is available as an MIT-licensed open-source project. Third-party components retain their respective licences.
References
- Srinivas, N., Krause, A., Kakade, S. M. & Seeger, M. (2010). Gaussian Process Optimization in the Bandit Setting: No Regret and Experimental Design. Proceedings of the 27th International Conference on Machine Learning, 1015–1022. https://arxiv.org/abs/0912.3995
- Staacks, S., Hütz, S., Heinke, H. & Stampfer, C. (2018). Advanced tools for smartphone-based experiments: phyphox. Physics Education, 53(4), 045009. https://doi.org/10.1088/1361-6552/aac05e
Linked mentions
6Contribution 2
- …normalise hue and saturation before a shared logistic fit. Across 63 dye-mixture samples, the fit achieved R² = 0.801 and RMSE = 0.118. Methods and resultsunder · Low-Cost Optical Devices and Colour Calibration
- …Its source and Windows demo offer a starting point for outreach adaptations. The game is intended for education and experiential learning. Software documentation · Source · Windows demounder · 5. Communicating Project Concepts: The Desktiny Educational Game