0%
Loading...

Software

The tools we built for MOSAIC — what they do, how to run them, and where the source lives.

Software

Software

Overview

Overview of the MOSAIC software tools
Figure 0. Overview of the MOSAIC software tools.

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.

Software

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 TimeAttentionEncoder plus DeepKernelGP.

    RatioTimePredictor was 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. TimeAttentionEncoder was replaced by RatioFeatureEncoder, 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 in RatioTimePredictor.

  • 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.py leaves --fit_ode off unless it is passed. scripts/Val.sh and scripts/Val.ps1 pass it, together with --max_time 24. app.py calls the same Model/ 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.

  1. Pretrain the encoder. RatioFeatureEncoder maps 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.
  2. Freeze the encoder. The score head is not used again. Each training pair becomes the 17-dimensional vector [ratio | embedding].
  3. 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.
  4. 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 + β · std with β = 2, on a grid over [0.1, 10].[1]

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

ML4OCRP full workflow Synthetic observations, preprocessing, OCRP training, sampling guidance, per-ID time query, and an in silico check. 1. Synthetic observations InSilicoValidation 1 fitting_ratio.py Simulate the BxB1 recombination ODE for each cell-group ID. ratio_data.csv param_data.csv Data/Original 2 fitting_score.py Turn each ratio into a score with a Gaussian peaked at the target ratio. score_data.csv Data/Original | reads ratio_data.csv 2. ML4OCRP software Model/ 3 preprocess_data.py Inner-join ratio and score on (id, time), then sort each ID. id_data_dict.npy id to (times, ratios, scores) Data/Preprocessed 4 ocrp_model_train.py Pretrain the ratio encoder, freeze it, then fit the deep-kernel GP. OCRP_model.pth Data/Model | reads id_data_dict.npy 5 predict_ratio_and_recommend_by_ucb.py Maximise the GP mean, and choose the next ratio with UCB. predict_result.csv GLOBAL_OPTIMAL_RATIO, UCB_RECOMMEND Data/Predict | reads OCRP_model.pth 6 query_per_id.py --fit_ode Per ID, fit ODE plus residual GP and find the time of the optimal ratio. predict_id_time_dict.npy time, status -1 / 1 / 0 Data/Predict | also reads id_data_dict.npy 3. In silico check InSilicoValidation 7 get_actual_ratio.py Integrate the true ODE at each predicted (id, time). actual_ratios_at_predicted_times.csv reads param_data.csv Data/Predict Status codes from query_per_id.py: -1 already seen in history, 1 predicted in the future, 0 not reached. Grey boxes are scripts. Blue boxes are the files they write. Order matches scripts/Val.sh.

Figure 1-1. The in silico check runs from synthetic 24 h ratios through training and a per-group time query to an ODE comparison at the predicted times.

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. Preprocesspreprocess_data.pyAlgorithm 1 · build_id_data_dict
4. Trainocrp_model_train.pyAlgorithm 2 · RatioFeatureEncoder
Algorithm 3 · pretrain_ratio_encoder
Algorithm 4 · build_global_dataset
Algorithm 5 · train_ocrp_model
5. Recommendpredict_ratio_and_recommend_by_ucb.pyAlgorithm 6 · predict_optimal_ratio
Algorithm 7 · ucb_acquisition
6. Time queryquery_per_id.pyAlgorithm 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.

Scatter plot of cell-group identifier against ratio at 24 h, with a point for each of 40 groups and grey horizontal lines at ten target ratios
Figure 1-2. Each group's ratio at 24 h lies near one of ten targets spaced logarithmically from 0.5 to 6.

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_fnShapeFormula
gaussianSymmetric peak at --opt_ratiomax_score * exp(-((ratio - opt_ratio)^2) / (2 * sigma^2))
log_gaussianAsymmetric peak at --opt_ratioThe same Gaussian, evaluated on log(ratio)
bimodalPeaks at --opt_ratio and --opt_ratio_2Weighted sum of two Gaussians, scaled so the taller peak equals --max_score
sigmoidIncreasing S, midpoint --opt_ratiomax_score / (1 + exp(-(ratio - opt_ratio) / sigma))
linearStraight ramp0 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.

Line plot of five scoring functions against ratio from 0.5 to 6: a symmetric peak, an asymmetric peak, a two-peak curve, an increasing sigmoid, and a straight ramp
Figure 1-3. The check scores the same ratios with five shapes: two single peaks, two peaks, an increasing sigmoid, and a linear ramp.

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 functionTrue optimumPredictedAbs. errorRegretScore RMSEUCB
Gaussian2.502.510.00600.0102.50
Log-Gaussian2.502.480.0250.00040.0102.44
Bimodal4.003.730.270.2070.0773.72
Sigmoid6.006.00000.0046.00
Linear6.006.00000.0316.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.

Five panels, each overlaying the true scoring curve in yellow, the OCRP posterior mean in blue, pink training points, and dashed lines at the true and predicted optima
Figure 1-4. OCRP recovers the single-peak and monotonic scores. The two-peak score is the loose case: the predicted ratio is 3.73 against a true peak at 4.00.
Two bar charts of absolute error and score regret for the symmetric peak, asymmetric peak, two-peak function, sigmoid, and linear ramp
Figure 1-5. Absolute error stays within 0.03 except for the two-peak function, whose regret is 0.21.

Architecture

OCRP model architecture Frozen ratio encoder, deep-kernel Gaussian process, and two readouts of the score posterior. RatioFeatureEncoder dashed: pretraining only ratio R^1 Linear 1 to 32 ReLU Linear 32 to 16 embedding d_model = 16 score head Linear 16 to 1 | MSE GP input Raw ratio is kept. The encoder is frozen,so only get_feature is used. concat(ratio, embedding) (N, 1 + 16) = (N, 17) DeepKernelGP Exact GP. Kernel is evaluated in the learned 8-dimensional space. Linear 17 to 32 ReLU Linear 32 to 8 latent z R^8 kernel on z ZeroMean | Scale | RBF-ARD ExactGP Gaussian noise p(score) N(mu, sigma^2) Readout The ratio is the only free variable. GP parameters stay fixed. global optimum maximise mu on [0.01, 5] UCB next ratio maximise mu + beta * sigma Encoder: MSE on observed scores, then frozen. GP: exact marginal log-likelihood. Source: Model/ocrp_model.py | defaults hidden_dim = 32, d_model = 16, feat_dim = 8

Figure 1-6. After pretraining, the Gaussian process reads the raw ratio concatenated with a frozen embedding. Mean and UCB are two readouts of the same posterior.

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.13All scripts
NumPyArrays and .npy dictionaries
pandasCSV tables
PyTorchEncoder, Gaussian process tensors, and device selection
GPyTorchExact deep-kernel Gaussian process
SciPyODE integration and parameter fitting in the time query and the in silico scripts
scikit-learnResidual Gaussian process in the time query
tqdmProgress display during the per-ID query
MatplotlibFigures written by InSilicoValidation/test_score_shapes.py
Streamlitapp.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.

  1. 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.

    Screenshot of the Preprocess tab with data-source choices, save paths, and a CSV upload control
    Figure 1-7. The Preprocess tab accepts the ratio and score tables, or an existing id_data_dict.npy.
    Screenshot of a data table beside a scatter plot of score against ratio
    Figure 1-8. After the merge, every ratio–score pair is plotted with ratio on the horizontal axis and score on the vertical axis.
  2. Train. Fit the encoder and the deep-kernel Gaussian process. Width, pretraining, validation fraction, and the marginal-likelihood reduction are on the page.

    Screenshot of the Train tab with width, pretraining, validation-fraction, and marginal-likelihood controls
    Figure 1-9. Training uses the same encoder and deep-kernel Gaussian process as the command line.
    Screenshot of a training log ending in a checkpoint-saved message
    Figure 1-10. A finished run writes OCRP_model.pth. With hidden_dim left at 32, that checkpoint can be loaded by the command-line scripts.
  3. 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.

    Screenshot of the Recommend tab with search bounds, number of starts, and the UCB coefficient
    Figure 1-11. Recommendation searches the posterior mean for the best ratio and scores a grid with UCB.
    Screenshot of reported optimal ratio and predicted score, with curves of posterior mean, standard deviation, and UCB against ratio
    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.
  4. 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.

    Screenshot of the Query tab with a target ratio, a tolerance, ODE-fitting options, and a progress bar
    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.
    Screenshot of query summary counts, a per-group status table, and a bar chart of predicted times
    Figure 1-14. Each group returns a time and a status: already seen, predicted in the future, or not reached.
Software

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}
    FitnR2RMSE
    Experiment 1 alone210.8050.134
    Experiment 2 alone420.8560.091
    Both batches, one plane630.6380.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.

    FitnR2RMSE
    Shared logistic, both batches630.8010.118
    Experiment 1 under that curve210.7810.142
    Experiment 2 under that curve420.8150.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

1. Filename to ratio setting CSV planned filename, blue fraction build_id_ratio_dict.py mapping.npy data/1_settings and data/2_settings 2. Stage features Phyphox Excel 1_original, stage 2 of 5 2_original, its only stage data_preprocess.py extracted_features.npy processed_data.pkl 3. Shared mixing model Both feature files plus both mapping.npy files fit_model.py Logistic blue-fraction model combined_modeling_data.pkl mixing_model.npy fit surface, residuals, and QQ plot Pure yellow is ratio 0 and pure blue is ratio 1. Their measured Hue and Saturation anchor each experiment before the shared curve is fit.

Figure 2-1. Stage features from both phyphox experiments are rescaled by each batch's pure yellow and pure blue, then fit with one logistic.

Dependencies

Python 3.12 or newer. Packages below are the ones imported by the three scripts.

PackageUsed for
numpyArrays, circular means, and .npy dictionaries
pandasTables, the sample-sheet CSV, and phyphox Excel files
openpyxlReading .xlsx workbooks through pandas
matplotlibFit surface, residual plots, predicted-versus-actual plot, and QQ plot
scipyLogistic least squares and the t distribution for coefficient tests
statsmodelsLinear 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:

FileContent
data/2_processed/combined_modeling_data.pklCombined modelling table, including endpoints, normalised colour, and predicted ratio
data/2_processed/mixing_model.npyThree 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:

ExperimentYellow HueYellow SaturationBlue HueBlue Saturation
1177.788°0.791215.408°0.990
2107.502°0.272210.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.

Scatter plot of predicted against prepared blue volume fraction, with a red identity line, blue circles for experiment 1, and orange triangles for experiment 2
Figure 2-2. Predicted fraction against the prepared fraction (n = 63). Points on the red line agree with the shared curve. Scatter is larger for experiment 1, matching its RMSE of 0.142.
Three-dimensional surface of the shared logistic in normalised hue and saturation, with blue circles for experiment 1 and orange triangles for experiment 2
Figure 2-3. The shared logistic in 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.
Histogram of residuals, fitted ratio minus measured ratio, with a longer tail on the positive side
Figure 2-4. Residuals (fitted ratio minus measured ratio) mostly fall within about ±0.2. The longer positive tail means the fit is high on some samples. Residual skew is 0.57.
Scatter plot of residuals against fitted blue volume fraction, with blue circles for experiment 1 and orange triangles for experiment 2
Figure 2-5. Residuals stay around zero from low to high fitted fractions, without a strong funnel.
Normal quantile-quantile plot of the residuals, with the upper tail departing from the reference line
Figure 2-6. The normal QQ plot shows the same mild right skew as the histogram: the upper tail leaves the reference line. Kurtosis is −0.33.

Software availability

The source code for CalcRatio is available in the GitLab repository.

Software

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.

Video 1. Desktiny interface demonstration.

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.

  1. Open the Desktiny 0.1.4 download page.
  2. Download Desktiny-0.1.4-windows-x64-compact.zip, which is approximately 40.3 MB.
  3. Right-click the archive, select “Extract All”, and extract its complete contents into a folder.
  4. Open the extracted folder and double-click Desktiny.exe.
  5. 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

Desktiny cultivation window: a hand-drawn glass tank holding eight small bacteria, with a pink HP bar, a yellow-green HUNGER bar, and a Feed button above it
Figure 3-1. Cultivation interface preview in version 0.1.4.
Interface elementWhat it representsHow players should respond
HP (pink)Current environmental and bacterial population health, ranging from 0–100; fuller is betterCheck nutrient and waste levels, improve the environment, and wait for recovery
HUNGER (yellow-green)Remaining nutrients, ranging from 0–100; fuller is betterClick Feed to replenish nutrients when the bar decreases
FeedDirect feeding buttonAdds 22 nutrient points each time, up to a maximum of 100
CleanCleaning action in the right-click menuRemoves 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.

Desktiny third-stage window: the same hand-drawn glass tank holding eight bacteria, drawn larger than in the first stage
Figure 3-2. Third-stage interface preview in version 0.1.4.

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:

OptionPurpose
SpeedSwitches the game speed; faster speeds also make care requirements arise sooner
AFK CareTurns automatic care on or off, allowing you to step away briefly
Return to MenuSaves current progress and returns to the main menu
QuitSaves 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:

ComponentResponsibility
GameManager.gdRun state, local saves, encountered appearances, and Science Log unlocks
WindowManager.gdWindow modes, scene transitions, and desktop wandering windows
EnvironmentSystem.gdNutrient consumption, waste accumulation, feeding, and cleaning
BacteriaSystem.gdGrowth, health, division, and stage progression
ProbabilityModel.gdRule-based probabilities for appearance outcomes
EventSystem.gdEvent conditions, consequences, and science notes
UI scripts and scenesRendering, 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

  1. 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
  2. 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
Back
To Top