mgrowthctrl 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,549 @@
1
+ import io
2
+ import re
3
+ import json
4
+ from pathlib import Path
5
+ from collections.abc import Callable, Iterable, Sequence
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ import requests
10
+
11
+ from ..models.base import ModelNames
12
+
13
+ DEFAULT_ROOT_URL = "https://mgrowthdb.gbiomed.kuleuven.be"
14
+ "By default, remote data is fetched from the mGrowthDB database"
15
+
16
+
17
+ class Dataloader:
18
+ """
19
+ Class that encapsulates data and metadata that is ready for fitting to a CR
20
+ model. After instantiating, you need to invoke ``load_local_data`` or
21
+ ``load_remote_experiment`` to load some data source into the object's
22
+ properties.
23
+
24
+ Properties:
25
+ ===========
26
+
27
+ :df: The parsed dataframe
28
+ :time_col: The name of the time column in the dataframe
29
+ :names: A :class:`~mgrowthctrl.models.base.ModelNames` object that includes ``X`` and ``S`` lists
30
+ of consumer and substrate column names, respectively
31
+ :t: A numpy array of the time values
32
+ :Y: A numpy array of the measurements
33
+ """
34
+
35
+ def __init__(self, root_url=DEFAULT_ROOT_URL, api_key=None):
36
+ """
37
+ Construct a new instance of the dataloader
38
+
39
+ :param root_url: An optional custom URL for remote fetching.
40
+ :param api_key: An optional API key to enable pushing data to the
41
+ remote source.
42
+ """
43
+ self.root_url = root_url
44
+ self.api_key = api_key
45
+
46
+ self.df = None
47
+ self.time_col = None
48
+ self.names = None
49
+ self.t = None
50
+ self.Y = None
51
+
52
+ @property
53
+ def X_names(self):
54
+ "A shorthand to fetch the consumer (X) column names of the dataframe"
55
+ return self.names.X
56
+
57
+ @property
58
+ def S_names(self):
59
+ "A shorthand to fetch the substrate (S) column names of the dataframe"
60
+ return self.names.S
61
+
62
+ @property
63
+ def X_err_names(self):
64
+ "A shorthand to fetch the consumer (X) error column names of the dataframe"
65
+ return self.names.X_err
66
+
67
+ @property
68
+ def S_err_names(self):
69
+ "A shorthand to fetch the substrate (S) error column names of the dataframe"
70
+ return self.names.S_err
71
+
72
+ @property
73
+ def y0(self):
74
+ """
75
+ A shorthand to fetch the initial measurement values, e.g. for
76
+ prediction purposes
77
+ """
78
+ return self.Y[0]
79
+
80
+ @property
81
+ def start_time(self) -> float:
82
+ "The first time value"
83
+ return self.t[0]
84
+
85
+ @property
86
+ def end_time(self) -> float:
87
+ "The final time value"
88
+ return self.t[-1]
89
+
90
+ def load_local_data(
91
+ self,
92
+ data: pd.DataFrame | str | Path,
93
+ *,
94
+ time_col: str | Iterable[str] = ("Time (hours)", "Time", "time", "t"),
95
+ x_selector: str | Iterable[str] | Callable[[str], bool] | None = None,
96
+ s_selector: str | Iterable[str] | Callable[[str], bool] | None = None,
97
+ err_selector: str | Callable[[str], str | None] | None = None,
98
+ require_monotonic_time: bool = True,
99
+ clip_nonneg: float | None = 0.0,
100
+ ):
101
+ """
102
+ Process a pandas dataframe or a CSV file that will be parsed into a
103
+ dataframe. The given X and S selectors will be used to determine which
104
+ columns represent consumers (X) and substrates (S). At least one of the
105
+ two selectors needs to be provided.
106
+
107
+ :param data: Either a pandas DataFrame, or a file path to open
108
+ :param time_col: The name of the time column or a list of names to try
109
+ :param x_selector:
110
+ A regex, a list of values, or a callable that determines which
111
+ column represents a consumer.
112
+ :param s_selector:
113
+ A regex, a list of values, or a callable that determines which
114
+ column represents a substrate.
115
+ :param err_selector:
116
+ A regex or a callable that determines which column represents
117
+ measurement error. If it's a regex, it needs to have a single
118
+ capture group that returns the column it refers to, for example:
119
+ r'(.*) STD$'. If it's a callable, it needs to return the column it
120
+ refers to or None
121
+ :param require_monotonic_time: Whether to check if the values in the time column are monotonic
122
+ :param clip_nonneg:
123
+ A floor value that the values are clipped to, defaults to 0.0,
124
+ meaning that negative values are truncated to 0.
125
+ """
126
+ if isinstance(data, pd.DataFrame):
127
+ self.df = data
128
+ else:
129
+ try:
130
+ self.df = pd.read_csv(data)
131
+ except FileNotFoundError:
132
+ raise FileNotFoundError(f"Data file not found at {data}")
133
+
134
+ self.df.columns = [c.strip() for c in self.df.columns]
135
+
136
+ # Find time column
137
+ if isinstance(time_col, str):
138
+ if time_col not in self.df.columns:
139
+ raise ValueError(f"Could not find the requested time column time_col={repr(time_col)}")
140
+ self.time_col = time_col
141
+
142
+ elif isinstance(time_col, Iterable):
143
+ for candidate in time_col:
144
+ if candidate in self.df.columns:
145
+ self.time_col = candidate
146
+ break
147
+ else:
148
+ raise ValueError(f"Could not find a time column from time_col={repr(time_col)}")
149
+
150
+ # Coerce numeric for all non-time columns
151
+ state_cols_all = [c for c in self.df.columns if c != self.time_col]
152
+ for c in state_cols_all:
153
+ self.df[c] = pd.to_numeric(self.df[c], errors="coerce")
154
+
155
+ # Basic cleaning
156
+ if clip_nonneg is not None:
157
+ self.df[state_cols_all] = self.df[state_cols_all].clip(lower=clip_nonneg)
158
+
159
+ # Select X (consumers) & S (resources)
160
+ if x_selector is None and s_selector is None:
161
+ raise ValueError(
162
+ "You need to provide either an `x_selector` and/or `s_selector` parameter "
163
+ "to determine consumer (X) columns and substrate (S) columns"
164
+ )
165
+
166
+ X_names = None
167
+ S_names = None
168
+
169
+ if x_selector is not None:
170
+ X_names = [c for c in state_cols_all if _match_selector(c, x_selector)]
171
+
172
+ if s_selector is not None:
173
+ S_names = [
174
+ c
175
+ for c in state_cols_all
176
+ if _match_selector(c, s_selector)
177
+ ]
178
+
179
+ err_mapping = {}
180
+ if err_selector is not None:
181
+ for col in state_cols_all:
182
+ if value_col := _match_err_selector(col, err_selector):
183
+ if value_col not in state_cols_all:
184
+ raise ValueError(f"Could not find value column {value_col} for error column {col}, please check your `err_selector`")
185
+
186
+ err_mapping[value_col] = col
187
+
188
+ non_err_state_cols = set(state_cols_all) - set(err_mapping.values())
189
+
190
+ if X_names is None:
191
+ X_names = list(sorted(non_err_state_cols - set(S_names)))
192
+ if S_names is None:
193
+ S_names = list(sorted(non_err_state_cols - set(X_names)))
194
+
195
+ if len(X_names) == 0:
196
+ raise ValueError(
197
+ "No consumer (X) columns found. "
198
+ 'Adjust x_selector (e.g., r"(counts|abundance)") or pass a callable.'
199
+ )
200
+ if len(S_names) == 0:
201
+ raise ValueError(
202
+ "No resource (S) columns found. "
203
+ "Set s_selector or ensure your CSV has resource columns."
204
+ )
205
+
206
+ if err_selector is not None:
207
+ X_err_names = [err_mapping.get(name) for name in X_names]
208
+ S_err_names = [err_mapping.get(name) for name in S_names]
209
+ else:
210
+ X_err_names = []
211
+ S_err_names = []
212
+
213
+ self.names = ModelNames(
214
+ X=X_names,
215
+ S=S_names,
216
+ X_err=X_err_names,
217
+ S_err=S_err_names,
218
+ )
219
+
220
+ # Extract & sort by time, drop duplicates
221
+ self.t = pd.to_numeric(self.df[self.time_col], errors="coerce").to_numpy(dtype=float).ravel()
222
+ state_df = self.df[X_names + S_names].copy()
223
+
224
+ mask = np.isfinite(self.t)
225
+ self.t = self.t[mask]
226
+ state_df = state_df.iloc[mask, :]
227
+
228
+ order = np.argsort(self.t)
229
+ self.t = self.t[order]
230
+ state_df = state_df.iloc[order, :]
231
+
232
+ _, unique_idx = np.unique(self.t, return_index=True)
233
+ keep = np.sort(unique_idx)
234
+ self.t = self.t[keep]
235
+ state_df = state_df.iloc[keep, :]
236
+
237
+ if require_monotonic_time and np.any(np.diff(self.t) <= 0):
238
+ raise ValueError(
239
+ "Time must be strictly increasing after cleaning. "
240
+ "Disable with require_monotonic_time=False if needed."
241
+ )
242
+
243
+ self.Y = state_df.to_numpy(dtype=float)
244
+
245
+ if np.isinf(self.Y).any():
246
+ raise ValueError("Data contains infinite values after cleaning.")
247
+ if self.Y.shape[1] != (len(self.names.X) + len(self.names.S)):
248
+ raise RuntimeError("State matrix column count mismatch.")
249
+
250
+ def load_remote_experiment(
251
+ self,
252
+ experiment_id: str,
253
+ *,
254
+ prefer_average: bool = True,
255
+ bioreplicate_name: str | None = None,
256
+ time_round: int | None = 3,
257
+ include_other: bool = False,
258
+ keep_predicate: Callable[[dict], bool] | None = None,
259
+ clip_nonneg: float | None = 0.0,
260
+ require_monotonic_time: bool = True,
261
+ ):
262
+ """
263
+ Download an experiment's data from mGrowthDB and detect its consumer
264
+ and substrate columns. By default, looks for a bioreplicate in the
265
+ experiment marked as "average", otherwise fetches data from the first
266
+ bioreplicate. If given an explicit bioreplicate name that can be found
267
+ on mGrowthDB, will select that replicate instead.
268
+
269
+ :param experiment_id: Stable experiment identifier of the form ``EMGDBxxx``
270
+ :param prefer_average: Whether to look for the average bioreplicate or not
271
+ :param bioreplicate_name: If given, will select a specific bioreplicate by its name
272
+ :param time_round: The number of digits to round time values to
273
+ :param include_other: Whether to include measurements from unknown techniques
274
+ :param keep_predicate:
275
+ A callable that is invoked with the metadata of each measurement
276
+ context and decides whether to keep it in the dataframe or not
277
+ :param clip_nonneg:
278
+ A floor value that the values are clipped to defaults to 0.0,
279
+ meaning that negative values are truncated to 0
280
+ """
281
+ self.df, names, bioreplicate_metadata = _fetch_experiment_dataframe(
282
+ experiment_id,
283
+ prefer_average=prefer_average,
284
+ bioreplicate_name=bioreplicate_name,
285
+ time_round=time_round,
286
+ include_other=include_other,
287
+ keep_predicate=keep_predicate,
288
+ root_url=self.root_url,
289
+ )
290
+ self.names = names
291
+ self.time_col = "Time"
292
+
293
+ # Save metadata for debugging purposes:
294
+ self._remote_bioreplicate_metadata = bioreplicate_metadata
295
+
296
+ # coerce and clean
297
+ self.t = pd.to_numeric(self.df[self.time_col], errors="coerce").to_numpy(dtype=float).ravel()
298
+ M = self.df[names.X + names.S].copy()
299
+
300
+ if clip_nonneg is not None:
301
+ M = M.clip(lower=clip_nonneg)
302
+
303
+ mask = np.isfinite(self.t)
304
+ self.t = self.t[mask]
305
+ M = M.iloc[mask, :]
306
+
307
+ order = np.argsort(self.t)
308
+ self.t = self.t[order]
309
+ M = M.iloc[order, :]
310
+
311
+ _, uniq_idx = np.unique(self.t, return_index=True)
312
+ keep = np.sort(uniq_idx)
313
+ self.t = self.t[keep]
314
+ M = M.iloc[keep, :]
315
+
316
+ if require_monotonic_time and np.any(np.diff(self.t) <= 0):
317
+ raise ValueError("Time must be strictly increasing after cleaning.")
318
+
319
+ self.Y = M.to_numpy(dtype=float)
320
+ if np.any(np.isinf(self.Y)):
321
+ raise ValueError("Non-finite values remain in Y after cleaning.")
322
+
323
+ # TODO: Work in progress
324
+ def push_remote_data(self, label, df, value_col_index=1):
325
+ if self.api_key is None:
326
+ raise ValueError("You haven't provided an API key, which is necessary to push data")
327
+
328
+ url = f"{self.root_url}/api/v1/dashboard.json"
329
+
330
+ entries = []
331
+ time_col = df.columns[0]
332
+ for value_col in df.columns[1:]:
333
+ entries.append({
334
+ "label": value_col,
335
+ "format": "with-std",
336
+ "data": df[[time_col, value_col]].to_csv(index=False)
337
+ })
338
+
339
+ payload = {
340
+ "apiKey": self.api_key,
341
+ "entries": entries,
342
+ }
343
+ r = requests.post(url, data=json.dumps(payload))
344
+ r.raise_for_status()
345
+ r_json = r.json()
346
+
347
+ if "error" in r_json:
348
+ raise ValueError(f"Failed to push data: {r_json['error']}")
349
+
350
+
351
+ def _fetch_experiment_dataframe(
352
+ experiment_id: str,
353
+ *,
354
+ prefer_average: bool = True,
355
+ bioreplicate_name: str | None = None,
356
+ time_round: int | None = 3,
357
+ include_other: bool = False,
358
+ keep_predicate: Callable[[dict], bool] | None = None,
359
+ root_url: str | None = None,
360
+ ) -> tuple[pd.DataFrame, Sequence[str], Sequence[str]]:
361
+ root_url = root_url or DEFAULT_ROOT_URL
362
+
363
+ experiment = _get_json(f"{root_url}/api/v1/experiment/{experiment_id}.json")
364
+ experiment_bioreplicates = experiment.get("bioreplicates", []) or []
365
+
366
+ # Find target bioreplicate, prioritizing:
367
+ # 1) explicity selected
368
+ # 2) average
369
+ # 3) the first available
370
+ bioreplicate_metadata = None
371
+
372
+ if bioreplicate_name is not None:
373
+ bioreplicate_name = bioreplicate_name.strip()
374
+ for br in experiment_bioreplicates:
375
+ if br.get('name', '').strip() == bioreplicate_name:
376
+ bioreplicate_metadata = br
377
+ break
378
+
379
+ if bioreplicate_metadata is None:
380
+ bioreplicate_names = [br.get('name', '').strip() for br in experiment_bioreplicates]
381
+ message = (
382
+ f"Could not find bioreplicate with name {bioreplicate_name}."
383
+ f"Available options: {', '.join(bioreplicate_names)}"
384
+ )
385
+ raise ValueError(message)
386
+
387
+ if not bioreplicate_metadata and prefer_average:
388
+ for br in experiment_bioreplicates:
389
+ if br.get("isAverage"):
390
+ bioreplicate_metadata = br
391
+ break
392
+
393
+ if not bioreplicate_metadata and len(experiment_bioreplicates) > 0:
394
+ bioreplicate_metadata = experiment_bioreplicates[0]
395
+
396
+ if not bioreplicate_metadata:
397
+ raise ValueError(f"Could not find valid bioreplicate in the given experiment's data: {experiment_id}")
398
+
399
+ br_id = bioreplicate_metadata["id"]
400
+ bioreplicate_contexts = []
401
+
402
+ # Select specific measurement contexts from the bioreplicate data:
403
+ for mc in bioreplicate_metadata.get("measurementContexts", []) or []:
404
+ if keep_predicate and not keep_predicate(mc):
405
+ continue
406
+
407
+ if _is_X(mc):
408
+ kind = "X"
409
+ elif _is_S(mc):
410
+ kind = "S"
411
+ elif include_other:
412
+ kind = "other"
413
+ else:
414
+ continue
415
+
416
+ label = _label_for(mc)
417
+ bioreplicate_contexts.append((mc['id'], label, kind))
418
+
419
+ if not bioreplicate_contexts:
420
+ raise RuntimeError(f"No biological replicate data found for experiment {experiment_id}")
421
+
422
+ wide = None
423
+ X_names = []
424
+ S_names = []
425
+ X_err_names = []
426
+ S_err_names = []
427
+
428
+ # Extract measurement context data from full bioreplicate CSV:
429
+ br_df = _fetch_bioreplicate_csv(br_id, root_url)
430
+
431
+ if time_round is not None:
432
+ br_df["Time"] = br_df["Time"].round(time_round)
433
+
434
+ for mc_id, col_name, kind in bioreplicate_contexts:
435
+ mc_df = br_df[br_df["measurementContextId"] == mc_id]
436
+
437
+ if "std" in mc_df and mc_df["std"].isna().all():
438
+ mc_df = mc_df[["Time", "value"]].rename(columns={
439
+ "value": col_name,
440
+ })
441
+ else:
442
+ err_col_name = f"{col_name}_ERR"
443
+ mc_df = mc_df[["Time", "value", "std"]].rename(columns={
444
+ "value": col_name,
445
+ "std": err_col_name,
446
+ })
447
+ (X_err_names if kind == "X" else S_err_names).append(err_col_name)
448
+
449
+ (X_names if kind == "X" else S_names).append(col_name)
450
+
451
+ wide = mc_df if wide is None else pd.merge(wide, mc_df, on="Time", how="outer")
452
+
453
+ if wide is None:
454
+ raise ValueError(f"No bioreplicate data was found for experiment {experiment_id}")
455
+
456
+ # tidy up
457
+ wide = wide.sort_values("Time").reset_index(drop=True)
458
+
459
+ # ensure ordered columns actually exist after merge
460
+ existing = set(wide.columns)
461
+ X_names = [c for c in X_names if c in existing]
462
+ S_names = [c for c in S_names if c in existing]
463
+ X_err_names = [c for c in X_err_names if c in existing]
464
+ S_err_names = [c for c in S_err_names if c in existing]
465
+
466
+ names = ModelNames(X=X_names, S=S_names, X_err=X_err_names, S_err=S_err_names)
467
+
468
+ ordered = ["Time"] + X_names + S_names + X_err_names + S_err_names
469
+ df_final = wide[ordered]
470
+
471
+ return df_final, names, bioreplicate_metadata
472
+
473
+
474
+ def _fetch_bioreplicate_csv(br_id: int, root_url: str | None = None) -> pd.DataFrame:
475
+ """
476
+ Download bioreplicate CSV -> tidy DataFrame with ['Time', '<col1>', '<col2>'].
477
+ """
478
+ url = f"{root_url or DEFAULT_ROOT_URL}/api/v1/bioreplicate/{br_id}.csv"
479
+ r = requests.get(url, timeout=30)
480
+ r.raise_for_status()
481
+
482
+ df = pd.read_csv(io.StringIO(r.text))
483
+ df = df.rename(columns={"time": "Time"})
484
+
485
+ for numeric_column_name in ["Time", "value"]:
486
+ df[numeric_column_name] = pd.to_numeric(df[numeric_column_name], errors="coerce")
487
+
488
+ return df.dropna(subset=["Time", "value", "measurementContextId"]).sort_values("Time")
489
+
490
+
491
+ def _label_for(mc_meta: dict) -> str:
492
+ """
493
+ Build a safe, informative column label from MC metadata: <subject_name>__<TECH>
494
+ """
495
+ subj = mc_meta.get("subject", {}) or {}
496
+ ttype = (mc_meta.get("techniqueType") or "").lower()
497
+ base = subj.get("name") or subj.get("type") or f"MC{mc_meta.get('id', '')}"
498
+ base = re.sub(r"[^A-Za-z0-9_]+", "_", base).strip("_")
499
+ suffix = {
500
+ '16s': '16S-rRNA',
501
+ 'fc': 'FC',
502
+ 'od': 'OD',
503
+ 'plates': 'PC',
504
+ 'qpcr': 'qPCR',
505
+ }.get(ttype, (ttype.upper() or "VAL"))
506
+ return f"{base}__{suffix}"
507
+
508
+
509
+ def _is_X(mc_meta: dict) -> bool:
510
+ ttype = (mc_meta.get("techniqueType") or "").lower()
511
+ subj_type = (mc_meta.get("subject", {}).get("type") or "").lower()
512
+ return subj_type == "strain" and ttype in {'16s', 'fc', 'od', 'plates', 'qpcr'}
513
+
514
+
515
+ def _is_S(mc_meta: dict) -> bool:
516
+ ttype = (mc_meta.get("techniqueType") or "").lower()
517
+ subj_type = (mc_meta.get("subject", {}).get("type") or "").lower()
518
+ return subj_type == "metabolite" or ttype == "metabolite"
519
+
520
+
521
+ def _match_selector(col: str, sel: str | Iterable[str] | Callable[[str], bool] | None = None) -> bool:
522
+ if sel is None:
523
+ return False
524
+ if isinstance(sel, str):
525
+ return re.search(sel, col, flags=re.IGNORECASE) is not None
526
+ if isinstance(sel, Iterable):
527
+ return col in sel
528
+ if callable(sel):
529
+ return bool(sel(col))
530
+ raise TypeError("x_selector/s_selector must be a regex string, an iterable, or a callable")
531
+
532
+
533
+ def _match_err_selector(col: str, sel: str | Callable[[str], str | None] | None = None) -> str | None:
534
+ if sel is None:
535
+ return None
536
+ if isinstance(sel, str):
537
+ match = re.search(sel, col, flags=re.IGNORECASE)
538
+ if match is None:
539
+ return None
540
+ else:
541
+ return match.group(1)
542
+ if callable(sel):
543
+ return sel(col)
544
+
545
+
546
+ def _get_json(url: str) -> dict:
547
+ r = requests.get(url, timeout=30)
548
+ r.raise_for_status()
549
+ return r.json()