pkpdutils-core 0.2.0__tar.gz → 0.2.2__tar.gz

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.
Files changed (51) hide show
  1. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/Cargo.lock +5 -5
  2. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/Cargo.toml +1 -1
  3. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/PKG-INFO +2 -2
  4. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/README.md +1 -1
  5. {pkpdutils_core-0.2.0/crates/core → pkpdutils_core-0.2.2/crates/abi}/README.md +4 -0
  6. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/core/Cargo.toml +2 -2
  7. {pkpdutils_core-0.2.0/crates/units → pkpdutils_core-0.2.2/crates/core}/README.md +4 -0
  8. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/core/src/assemble.rs +135 -20
  9. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/core/src/lib.rs +227 -5
  10. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/core/src/terminal.rs +95 -8
  11. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/python/Cargo.toml +2 -2
  12. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/python/README.md +1 -1
  13. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/python/src/lib.rs +77 -14
  14. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/python/src/options.rs +8 -0
  15. {pkpdutils_core-0.2.0/crates/abi → pkpdutils_core-0.2.2/crates/units}/README.md +4 -0
  16. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/units/src/lib.rs +115 -1
  17. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/units/src/registry.rs +104 -2
  18. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/units/tests/data/pint_gate.json +18156 -7345
  19. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/units/tests/pint_gate.rs +2 -2
  20. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/LICENSE +0 -0
  21. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/Cargo.toml +0 -0
  22. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/src/batch.rs +0 -0
  23. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/src/enums.rs +0 -0
  24. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/src/lib.rs +0 -0
  25. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/src/nonfinite.rs +0 -0
  26. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/src/options.rs +0 -0
  27. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/src/result.rs +0 -0
  28. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/src/window.rs +0 -0
  29. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/tests/data/enum_values.json +0 -0
  30. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/tests/data/options_all_fields.json +0 -0
  31. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/tests/data/options_default.json +0 -0
  32. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/tests/data/options_effect.json +0 -0
  33. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/tests/data/options_full.json +0 -0
  34. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/tests/data/options_manual_points.json +0 -0
  35. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/tests/data/options_windows.json +0 -0
  36. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/abi/tests/options_from_python.rs +0 -0
  37. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/core/examples/kernel_timing.rs +0 -0
  38. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/core/src/auc.rs +0 -0
  39. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/core/src/blq.rs +0 -0
  40. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/core/src/dose.rs +0 -0
  41. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/core/src/pack.rs +0 -0
  42. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/core/src/parameters.rs +0 -0
  43. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/core/src/shard.rs +0 -0
  44. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/python/LICENSE +0 -0
  45. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/python/src/convert.rs +0 -0
  46. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/python/src/result.rs +0 -0
  47. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/python/tests/test_bindings.py +0 -0
  48. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/units/Cargo.toml +0 -0
  49. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/units/src/format.rs +0 -0
  50. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/crates/units/src/parameter.rs +0 -0
  51. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.2}/pyproject.toml +0 -0
@@ -238,7 +238,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
238
238
 
239
239
  [[package]]
240
240
  name = "pkpdutils-abi"
241
- version = "0.2.0"
241
+ version = "0.2.2"
242
242
  dependencies = [
243
243
  "bitflags",
244
244
  "serde",
@@ -248,7 +248,7 @@ dependencies = [
248
248
 
249
249
  [[package]]
250
250
  name = "pkpdutils-core"
251
- version = "0.2.0"
251
+ version = "0.2.2"
252
252
  dependencies = [
253
253
  "pkpdutils-abi",
254
254
  "pkpdutils-units",
@@ -258,7 +258,7 @@ dependencies = [
258
258
 
259
259
  [[package]]
260
260
  name = "pkpdutils-oracles"
261
- version = "0.2.0"
261
+ version = "0.2.2"
262
262
  dependencies = [
263
263
  "pkpdutils-abi",
264
264
  "pkpdutils-core",
@@ -270,7 +270,7 @@ dependencies = [
270
270
 
271
271
  [[package]]
272
272
  name = "pkpdutils-python"
273
- version = "0.2.0"
273
+ version = "0.2.2"
274
274
  dependencies = [
275
275
  "mimalloc",
276
276
  "numpy",
@@ -281,7 +281,7 @@ dependencies = [
281
281
 
282
282
  [[package]]
283
283
  name = "pkpdutils-units"
284
- version = "0.2.0"
284
+ version = "0.2.2"
285
285
  dependencies = [
286
286
  "serde",
287
287
  "serde_json",
@@ -5,7 +5,7 @@ members = ["crates/abi", "crates/core", "crates/python", "crates/units"]
5
5
  exclude = ["spike"]
6
6
 
7
7
  [workspace.package]
8
- version = "0.2.0"
8
+ version = "0.2.2"
9
9
  edition = "2024"
10
10
  rust-version = "1.100"
11
11
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pkpdutils-core
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Classifier: Development Status :: 4 - Beta
5
5
  Classifier: Intended Audience :: Science/Research
6
6
  Classifier: Operating System :: OS Independent
@@ -45,7 +45,7 @@ result = pkpdutils_core.analyze_batch(batch, options, n_workers=None)
45
45
 
46
46
  `analyze_batch` is the single dose analysis. An analysis which is well formed and which this build does not carry raises `pkpdutils_core.UnsupportedError`, a subclass of `ValueError`, and that one exception is what a host answers by analysing the batch its own way. Every other failure keeps its natural type: a `KeyError`, a `TypeError` or a `ValueError` naming a key means the caller and this build disagree about the contract, which is a defect and never a reason to take another path. `is_supported` asks the same question without raising and returns the reason as a string, and a host asks it first.
47
47
 
48
- Not carried today: the analysis of an effect curve, the multiple dose analysis (a `tau` or a protocol of more than one dose), the acceptance criteria, the named partial areas, the propagation of the uncertainty of a group curve and the unit conversion of a result.
48
+ Not carried today: the analysis of an effect curve, the multiple dose analysis (a `tau` or a protocol of more than one dose), the acceptance criteria, the named partial areas, the propagation of the uncertainty of a group curve and the unit conversion of a result. One more is not carried and `is_supported` does not report it: a unit string the curated unit registry of this build cannot read. That registry is narrower than pint, deliberately, so it refuses a time in `week`, `month` or `year`, a concentration in `U/l`, a prefixed `kilohour`, pint's implicit product `mg l` and its fractional exponent `hr ** 0.5`, and it also refuses a spelling pint over-forgives, such as `mg//l`, which pint reads as `mg / l`. What this build reads is a property of this build, so every one of them is an `UnsupportedError` and a host whose own engine reads the string analyses the batch there. Answering it means deriving the unit of every parameter of the result, which is the analysis itself, so `analyze_batch` is what reports it and a host which routes on the type rather than on the predicate takes its own path for it as for any other refusal.
49
49
 
50
50
  ## Threads, and a warning about `fork`
51
51
 
@@ -20,7 +20,7 @@ result = pkpdutils_core.analyze_batch(batch, options, n_workers=None)
20
20
 
21
21
  `analyze_batch` is the single dose analysis. An analysis which is well formed and which this build does not carry raises `pkpdutils_core.UnsupportedError`, a subclass of `ValueError`, and that one exception is what a host answers by analysing the batch its own way. Every other failure keeps its natural type: a `KeyError`, a `TypeError` or a `ValueError` naming a key means the caller and this build disagree about the contract, which is a defect and never a reason to take another path. `is_supported` asks the same question without raising and returns the reason as a string, and a host asks it first.
22
22
 
23
- Not carried today: the analysis of an effect curve, the multiple dose analysis (a `tau` or a protocol of more than one dose), the acceptance criteria, the named partial areas, the propagation of the uncertainty of a group curve and the unit conversion of a result.
23
+ Not carried today: the analysis of an effect curve, the multiple dose analysis (a `tau` or a protocol of more than one dose), the acceptance criteria, the named partial areas, the propagation of the uncertainty of a group curve and the unit conversion of a result. One more is not carried and `is_supported` does not report it: a unit string the curated unit registry of this build cannot read. That registry is narrower than pint, deliberately, so it refuses a time in `week`, `month` or `year`, a concentration in `U/l`, a prefixed `kilohour`, pint's implicit product `mg l` and its fractional exponent `hr ** 0.5`, and it also refuses a spelling pint over-forgives, such as `mg//l`, which pint reads as `mg / l`. What this build reads is a property of this build, so every one of them is an `UnsupportedError` and a host whose own engine reads the string analyses the batch there. Answering it means deriving the unit of every parameter of the result, which is the analysis itself, so `analyze_batch` is what reports it and a host which routes on the type rather than on the predicate takes its own path for it as for any other refusal.
24
24
 
25
25
  ## Threads, and a warning about `fork`
26
26
 
@@ -168,6 +168,10 @@ uv run --with-editable path/to/pkpdutils python scripts/crosswalk_gate.py --chec
168
168
 
169
169
  `scripts/pint_gate.py` writes `crates/units/tests/data/pint_gate.json`, pint's answer for every unit spelling of the package and every derived parameter unit, and `scripts/crosswalk_gate.py` writes `crates/oracles/tests/data/crosswalk.json`, the map from the variables of `pkpdutils` to the column names of the three NCA tools; the sections above describe both. `scripts/vendor_oracles.py --check` is the third, and it needs no checkout unless `--source` is given.
170
170
 
171
+ ## Release
172
+
173
+ A tag `vx.y.z` publishes the distribution to PyPI and creates the release of this repository from `release-notes/x.y.z.md`. [docs/release.md](docs/release.md) has the steps.
174
+
171
175
  ## License
172
176
 
173
177
  MIT, see `LICENSE`.
@@ -14,8 +14,8 @@ categories.workspace = true
14
14
  [dependencies]
15
15
  # the version is what a published `pkpdutils-core` resolves against; the path is
16
16
  # what the workspace builds
17
- pkpdutils-abi = { path = "../abi", version = "0.2.0" }
18
- pkpdutils-units = { path = "../units", version = "0.2.0" }
17
+ pkpdutils-abi = { path = "../abi", version = "0.2.2" }
18
+ pkpdutils-units = { path = "../units", version = "0.2.2" }
19
19
  thiserror.workspace = true
20
20
  rayon = { workspace = true, optional = true }
21
21
 
@@ -168,6 +168,10 @@ uv run --with-editable path/to/pkpdutils python scripts/crosswalk_gate.py --chec
168
168
 
169
169
  `scripts/pint_gate.py` writes `crates/units/tests/data/pint_gate.json`, pint's answer for every unit spelling of the package and every derived parameter unit, and `scripts/crosswalk_gate.py` writes `crates/oracles/tests/data/crosswalk.json`, the map from the variables of `pkpdutils` to the column names of the three NCA tools; the sections above describe both. `scripts/vendor_oracles.py --check` is the third, and it needs no checkout unless `--source` is given.
170
170
 
171
+ ## Release
172
+
173
+ A tag `vx.y.z` publishes the distribution to PyPI and creates the release of this repository from `release-notes/x.y.z.md`. [docs/release.md](docs/release.md) has the steps.
174
+
171
175
  ## License
172
176
 
173
177
  MIT, see `LICENSE`.
@@ -94,9 +94,10 @@ const CANDIDATE_VARIABLES: [CandidateVariable; 3] = [
94
94
  ///
95
95
  /// # Errors
96
96
  ///
97
- /// [`KernelError::Batch`] naming the variable whose unit could not be derived: the units of a
98
- /// batch are no part of `Batch::validate`, so a string which is no unit, and a batch with doses
99
- /// but without a dose unit, reach this point. Python raises in the same place.
97
+ /// Whatever [`unit_of`] refuses: the units of a batch are no part of `Batch::validate`, so a
98
+ /// unit this build cannot read and a batch with doses but without a dose unit both reach this
99
+ /// point. The first is a [`KernelError::Unsupported`] a host routes its own path on, the second
100
+ /// a [`KernelError::Batch`] naming the variable.
100
101
  pub(crate) fn result_of(
101
102
  batch: &Batch,
102
103
  options: &NcaOptions,
@@ -331,15 +332,34 @@ fn acceptance_variables(n_samples: usize) -> Vec<BooleanColumn> {
331
332
  ///
332
333
  /// # Errors
333
334
  ///
334
- /// [`KernelError::Batch`] naming the variable and the reason, which is a unit of the batch the
335
- /// registry does not read or a placeholder the batch does not provide.
335
+ /// [`KernelError::Unsupported`] for a unit of the batch the registry of this build could not
336
+ /// read, whatever the reason (`UnitError::is_unsupported`): a time in `week`, a concentration in
337
+ /// `U/l`, a prefixed `kilohour`, pint's `mg l` or `hr ** 0.5`, a spelling pint over-forgives
338
+ /// (`mg//l`, which it reads as `mg / l`) and a string which is no unit anywhere. What this build
339
+ /// reads is a property of this build, so a host whose own engine reads it analyses the batch
340
+ /// there and the refusal is one a host routes on rather than an error at its user. Every one of
341
+ /// these quotes the offending unit string itself, which is why the refusal does not carry the
342
+ /// variable name: the variable is wherever the derivation happened to reach it first and says
343
+ /// nothing about the batch.
344
+ ///
345
+ /// [`KernelError::Batch`] naming the variable for the failures which are not about reading a
346
+ /// string: a placeholder the batch does not provide, which is a batch with doses and no dose
347
+ /// unit and whose variable is the one piece of information in that message. Python raises in the
348
+ /// same place.
336
349
  fn unit_of(
337
350
  name: &str,
338
351
  expression: &str,
339
352
  context: &UnitContext,
340
353
  ) -> Result<(String, f64), KernelError> {
341
- parameter_unit(expression, context)
342
- .map_err(|e| KernelError::Batch(format!("the unit of {name} cannot be derived: {e}")))
354
+ parameter_unit(expression, context).map_err(|e| {
355
+ if e.is_unsupported() {
356
+ KernelError::Unsupported {
357
+ what: format!("a unit which the registry of this build does not read ({e})"),
358
+ }
359
+ } else {
360
+ KernelError::Batch(format!("the unit of {name} cannot be derived: {e}"))
361
+ }
362
+ })
343
363
  }
344
364
 
345
365
  #[cfg(test)]
@@ -925,21 +945,116 @@ mod tests {
925
945
  }
926
946
  }
927
947
 
948
+ /// The batch of `oral_curve` with one of its three unit strings replaced.
949
+ fn with_unit(which: &str, unit: &str) -> Batch {
950
+ let mut batch = oral_curve();
951
+ match which {
952
+ "unit" => batch.unit = unit.to_string(),
953
+ "time_unit" => batch.time_unit = unit.to_string(),
954
+ "dose_unit" => batch.dose_unit = Some(unit.to_string()),
955
+ other => panic!("'{other}' is no unit of a batch"),
956
+ }
957
+ batch
958
+ }
959
+
928
960
  #[test]
929
- fn a_unit_the_batch_cannot_spell_is_refused_by_name() {
930
- // The units of a batch are no part of `Batch::validate`, so a string which is no unit
931
- // reaches the assembly; python raises there too (`ureg.parse_units`).
932
- let nonsense = Batch {
933
- unit: "banana".to_string(),
934
- ..oral_curve()
935
- };
936
- let error = crate::analyze_batch(&nonsense, &linear()).unwrap_err();
937
- assert!(
938
- matches!(&error, crate::KernelError::Batch(message) if message.contains("banana")),
939
- "{error}"
940
- );
961
+ fn a_unit_the_registry_cannot_read_is_a_refusal_and_not_a_batch_error() {
962
+ // What this build reads is a property of this build, so a unit it cannot read is not a
963
+ // defect of the batch: the batch is analysable, by a host whose own engine reads the
964
+ // string, and `KernelError::Unsupported` is what says so. Reported as
965
+ // `KernelError::Batch` it reaches the user of that host as an exception, since the
966
+ // fallback catches the refusal and deliberately nothing broader, and none of these is a
967
+ // corner case: `week` is the time base of a monoclonal antibody study, `U/l` a clinical
968
+ // concentration, and `mg//l` is read by pint as `mg / l` and therefore computed by
969
+ // `pkpdutils` 1.4.0.
970
+ //
971
+ // Every way the parse can fail, as the unit of the values, of the times and of the
972
+ // doses, since each reaches the derivation through another placeholder and a dose unit
973
+ // reaches it only for some parameters.
974
+ let deep = format!("{}hr{}", "(".repeat(80), ")".repeat(80));
975
+ for spelling in [
976
+ // a unit pint has and this registry does not
977
+ "week",
978
+ "month",
979
+ "year",
980
+ "U/l",
981
+ // a prefix on a unit which is not prefixable
982
+ "kilohour",
983
+ "hectoliter",
984
+ // pint's implicit product and its fractional exponent
985
+ "mg l",
986
+ "hr**0.5",
987
+ // the two limits this build puts on an expression it would otherwise read
988
+ "hr**100",
989
+ deep.as_str(),
990
+ // a spelling pint over-forgives, which 1.4.0 computes: `mg/l` and `hr**2`
991
+ "mg//l",
992
+ "hr**--2",
993
+ // and a string which is no unit anywhere. The host refuses these before a batch is
994
+ // built at all (`Timecourses.from_arrays` parses every unit with pint), so the
995
+ // classification is invisible from there; it is uniform because the rule is one
996
+ // line, and a direct caller of the binding gets the same answer as everyone else
997
+ "mg/",
998
+ "/mg",
999
+ "()",
1000
+ "(mg",
1001
+ "mg)",
1002
+ "2*mg",
1003
+ "mg**",
1004
+ "mg.l",
1005
+ "",
1006
+ ] {
1007
+ for which in ["unit", "time_unit", "dose_unit"] {
1008
+ let batch = with_unit(which, spelling);
1009
+ let error = crate::analyze_batch(&batch, &linear()).unwrap_err();
1010
+ let crate::KernelError::Unsupported { what } = &error else {
1011
+ panic!("{which} = '{spelling}' is {error}, not a refusal");
1012
+ };
1013
+ // the refusal quotes the unit itself, which is why it names no variable: the
1014
+ // variable is wherever the derivation reached it first. Clipped, as every error
1015
+ // of the registry clips the host string it echoes
1016
+ let quoted: String = spelling
1017
+ .chars()
1018
+ .take(pkpdutils_units::MAX_ERROR_TEXT)
1019
+ .collect();
1020
+ assert!(
1021
+ what.contains(&quoted),
1022
+ "the refusal of {which} = '{spelling}' does not quote it: {what}"
1023
+ );
1024
+ }
1025
+ }
1026
+ }
1027
+
1028
+ #[test]
1029
+ fn a_unit_which_reads_is_analysed_and_one_the_batch_lacks_is_a_batch_error() {
1030
+ // The other side of the rule above, and the mutation which would catch a classification
1031
+ // that refuses wholesale: the ordinary units of a batch are read and analysed here and
1032
+ // not handed back to the host.
1033
+ for (unit, time_unit, dose_unit) in [
1034
+ ("mg/l", "hr", "mg"),
1035
+ ("ug/ml", "min", "mg/kg"),
1036
+ ("mmol/l", "day", "mmol"),
1037
+ ("IU/l", "s", "IU"),
1038
+ ("mg/l", "hour", "milligram"),
1039
+ ] {
1040
+ let batch = Batch {
1041
+ unit: unit.to_string(),
1042
+ time_unit: time_unit.to_string(),
1043
+ dose_unit: Some(dose_unit.to_string()),
1044
+ ..oral_curve()
1045
+ };
1046
+ let result = crate::analyze_batch(&batch, &linear());
1047
+ assert!(
1048
+ result.is_ok(),
1049
+ "'{unit}' over '{time_unit}' with a dose in '{dose_unit}' is {:?}",
1050
+ result.err()
1051
+ );
1052
+ }
941
1053
 
942
- // a dose dependent parameter needs a dose unit, which a batch with doses may lack
1054
+ // and the one unit failure which is no failure to read a string: a dose dependent
1055
+ // parameter needs a dose unit, which a batch with doses may lack. The batch is
1056
+ // incomplete rather than unreadable, python raises in the same place, and the variable
1057
+ // the message names is the one piece of information in it
943
1058
  let doseless = Batch {
944
1059
  dose_unit: None,
945
1060
  ..oral_curve()
@@ -48,14 +48,26 @@ use crate::terminal::Candidate;
48
48
  #[derive(Debug, Clone, PartialEq, thiserror::Error)]
49
49
  #[non_exhaustive]
50
50
  pub enum KernelError {
51
- /// The batch itself is malformed, with the reason `pkpdutils_abi::Batch::validate` gave,
52
- /// or one of its units is no unit, which that check does not cover (`crate::assemble`).
51
+ /// The batch itself is malformed, with the reason `pkpdutils_abi::Batch::validate` gave, or
52
+ /// it carries doses without a dose unit, which that check does not cover
53
+ /// (`crate::assemble`). A unit string this build cannot read is
54
+ /// [`KernelError::Unsupported`] instead, whatever the reason the parser gives: what this
55
+ /// build reads is a property of the build, and the batch is analysable by a host which reads
56
+ /// it.
53
57
  #[error("the batch is not analysable: {0}")]
54
58
  Batch(String),
55
59
  /// The options are malformed or contradict each other.
56
60
  #[error("the options are not analysable: {0}")]
57
61
  Options(String),
58
62
  /// An analysis this build does not carry, named by what was asked for.
63
+ ///
64
+ /// Every one of these but one is decided before a row runs and is therefore also what
65
+ /// `is_supported` of the python binding answers (`refuse_what_is_not_carried`). The one
66
+ /// which is not is a unit of the batch which the curated registry of `pkpdutils-units`
67
+ /// cannot read: answering it means deriving the unit of every parameter, which is the
68
+ /// analysis, so it is reported where that happens (`crate::assemble::unit_of`) and the
69
+ /// predicate does not see it. A host which routes on the type rather than on the predicate
70
+ /// is unaffected, which is what both are documented to do.
59
71
  #[error("{what} is not implemented by this build")]
60
72
  Unsupported {
61
73
  /// The analysis, the option or the route which is missing.
@@ -103,7 +115,9 @@ pub fn analyze(request: &AnalysisRequest) -> Result<AnalysisResult, KernelError>
103
115
  /// [`KernelError::Options`] for a malformed input, naming the field, and
104
116
  /// [`KernelError::Unsupported`] for an analysis of another plan: an effect curve, a multiple
105
117
  /// dose protocol, a partial area, the acceptance criteria, the propagation of an uncertainty and
106
- /// the unit conversion of the result.
118
+ /// the unit conversion of the result - and for a unit string of the batch which the curated
119
+ /// registry of this build cannot read (`week`, `U/l`), the one refusal which is decided while the
120
+ /// result is assembled rather than before the rows run.
107
121
  pub fn analyze_batch(batch: &Batch, options: &NcaOptions) -> Result<AnalysisResult, KernelError> {
108
122
  let shards = automatic_shards(batch.n_samples(), batch.n_time);
109
123
  analyze_batch_in_shards(batch, options, shards)
@@ -227,6 +241,12 @@ impl Rows<'_> {
227
241
  ///
228
242
  /// Every one of these is a different parameter set or a step beyond the single dose analysis, so
229
243
  /// a wrong number is the alternative to a named error.
244
+ ///
245
+ /// These are the refusals which are decided from the batch and the options alone, which is why
246
+ /// the predicate of the python binding (`unsupported_reason`) is these seven and is held to them
247
+ /// by a test. The eighth refusal of this build, a unit string the registry cannot read, is not
248
+ /// here: it is answered by deriving the units of the parameters, which is what the analysis does
249
+ /// (`assemble::unit_of`).
230
250
  fn refuse_what_is_not_carried(batch: &Batch, options: &NcaOptions) -> Result<(), KernelError> {
231
251
  let unsupported = |what: &str| {
232
252
  Err(KernelError::Unsupported {
@@ -392,9 +412,23 @@ const WINDOW_DEFAULT_KEY: &str = "*";
392
412
 
393
413
  /// Whether a sample label and a key of the window mapping are the same label.
394
414
  ///
415
+ /// `TerminalPhase.windows` is a python `dict` and the check of its keys a python `set`, so what
416
+ /// "the same label" means is what `==` means there, and python compares the numbers of its
417
+ /// numeric tower across their types: `1 == 1.0`, `True == 1` and `False == 0.0` are all true, and
418
+ /// a `dict` keyed `1` is read by `1.0` because the two also hash alike. A column of a batch
419
+ /// carries one dtype, so a float coordinate of `[1.0, 2.0]` with a window keyed `1` is a batch
420
+ /// `pkpdutils` 1.4.0 analyses and nothing on the host side has anything to flag; this comparison
421
+ /// is where the two could disagree, so this is where they are held together
422
+ /// (`a_numeric_label_matches_a_key_of_another_type_as_python_does`).
423
+ ///
424
+ /// Numbers are therefore compared by value, with a boolean as the `1` and `0` python makes of it,
425
+ /// and exactly: python compares an `int` and a `float` without rounding the `int` to a double, so
426
+ /// the float is taken to the integers and not the other way round ([`int_is_float`]). A `NaN`
427
+ /// label equals nothing, itself included, as in python.
428
+ ///
395
429
  /// `WindowLabel` tells a date and a datetime from a string, where a coordinate of a batch has no
396
430
  /// dtype for either and carries both as text, so a date key is matched against the text of the
397
- /// coordinate. Everything else compares as itself.
431
+ /// coordinate. Text, `None` and a tuple compare as themselves, element by element.
398
432
  fn same_label(label: &WindowLabel, key: &WindowLabel) -> bool {
399
433
  match (label, key) {
400
434
  (WindowLabel::Str(text), WindowLabel::Date(key) | WindowLabel::Datetime(key)) => {
@@ -403,10 +437,68 @@ fn same_label(label: &WindowLabel, key: &WindowLabel) -> bool {
403
437
  (WindowLabel::Tuple(label), WindowLabel::Tuple(key)) => {
404
438
  label.len() == key.len() && label.iter().zip(key).all(|(l, k)| same_label(l, k))
405
439
  }
406
- _ => label == key,
440
+ _ => match (numeric_label(label), numeric_label(key)) {
441
+ (Some(label), Some(key)) => same_number(label, key),
442
+ // not both numbers: a number is no string, no date and no `None`, exactly as in
443
+ // python, and two labels of the same kind compare as themselves
444
+ _ => label == key,
445
+ },
407
446
  }
408
447
  }
409
448
 
449
+ /// A label as the number python would compare, `None` for a label which is no number.
450
+ ///
451
+ /// A boolean is a number in python, `True` being `1` and `False` being `0`, and it is a label of
452
+ /// a batch because a coordinate may be a boolean column.
453
+ fn numeric_label(label: &WindowLabel) -> Option<Number> {
454
+ match label {
455
+ WindowLabel::Int(value) => Some(Number::Int(*value)),
456
+ WindowLabel::Bool(value) => Some(Number::Int(i64::from(*value))),
457
+ WindowLabel::Float(value) => Some(Number::Float(*value)),
458
+ WindowLabel::Tuple(_)
459
+ | WindowLabel::None
460
+ | WindowLabel::Datetime(_)
461
+ | WindowLabel::Date(_)
462
+ | WindowLabel::Str(_) => None,
463
+ }
464
+ }
465
+
466
+ /// One label of [`numeric_label`]: a python `int` (a boolean among them) or a python `float`.
467
+ #[derive(Clone, Copy)]
468
+ enum Number {
469
+ /// An integer, and a boolean as the integer python makes of it.
470
+ Int(i64),
471
+ /// A float.
472
+ Float(f64),
473
+ }
474
+
475
+ /// Whether two numeric labels are equal as python's `==` has them.
476
+ fn same_number(label: Number, key: Number) -> bool {
477
+ match (label, key) {
478
+ (Number::Int(label), Number::Int(key)) => label == key,
479
+ // `NaN` equals nothing, itself included, which is what the float comparison already does
480
+ (Number::Float(label), Number::Float(key)) => label == key,
481
+ (Number::Int(int), Number::Float(float)) | (Number::Float(float), Number::Int(int)) => {
482
+ int_is_float(int, float)
483
+ }
484
+ }
485
+ }
486
+
487
+ /// Whether an integer and a float are the same number, as python compares the two.
488
+ ///
489
+ /// Python compares an `int` and a `float` exactly and does not round the `int` to a double, so
490
+ /// `10**17 + 1 == 1e17` is false there although both sides are the same `f64`. The float is
491
+ /// therefore taken to the integers and never the other way round, and a float which is not an
492
+ /// integer, which is not finite or which is outside the range of an `i64` is equal to no `i64`:
493
+ /// `fract` of an infinity and of a `NaN` is a `NaN`, which fails the first test, and the range
494
+ /// is checked before the cast, which saturates.
495
+ fn int_is_float(int: i64, float: f64) -> bool {
496
+ // `i64::MIN` is a power of two and exact as an `f64`, and so is its negation, which is one
497
+ // past `i64::MAX` and therefore an exclusive bound
498
+ let min = i64::MIN as f64;
499
+ float.fract() == 0.0 && float >= min && float < -min && float as i64 == int
500
+ }
501
+
410
502
  /// The label of every sample of a batch, in the row order of the analysis.
411
503
  ///
412
504
  /// Mirrors `sample_keys` of `src/pkpdutils/nca/nca.py`.
@@ -461,6 +553,8 @@ fn dimension_labels(batch: &Batch, dim: &str, size: usize) -> Vec<WindowLabel> {
461
553
 
462
554
  #[cfg(test)]
463
555
  mod tests {
556
+ use pkpdutils_abi::{SampleCoordinate, TerminalPhase};
557
+
464
558
  use super::*;
465
559
 
466
560
  #[test]
@@ -482,6 +576,134 @@ mod tests {
482
576
  );
483
577
  }
484
578
 
579
+ #[test]
580
+ fn a_numeric_label_matches_a_key_of_another_type_as_python_does() {
581
+ // `TerminalPhase.windows` is a python `dict` and the check of its keys a python `set`, so
582
+ // a label and a key are the same label when python's `==` says so, and python compares
583
+ // its numeric tower across the types: a float coordinate of `[1.0, 2.0]` with a window
584
+ // keyed `1` is a batch `pkpdutils` 1.4.0 analyses. The column of a batch carries one
585
+ // dtype, so nothing on the host side has anything to flag and this comparison is the
586
+ // only place the two engines could disagree.
587
+ let int = WindowLabel::Int;
588
+ let float = WindowLabel::Float;
589
+ let bool_label = WindowLabel::Bool;
590
+ for (label, key) in [
591
+ (float(1.0), int(1)),
592
+ (int(1), float(1.0)),
593
+ (bool_label(true), int(1)),
594
+ (int(1), bool_label(true)),
595
+ (bool_label(false), float(0.0)),
596
+ (float(0.0), bool_label(false)),
597
+ (float(-2.0), int(-2)),
598
+ // exactly representable on both sides, and python says they are equal
599
+ (float(1e17), int(100_000_000_000_000_000)),
600
+ (int(i64::MIN), float(-9_223_372_036_854_775_808.0)),
601
+ // and a label of the same kind, which compared equal before this one did
602
+ (int(7), int(7)),
603
+ (float(1.5), float(1.5)),
604
+ (bool_label(true), bool_label(true)),
605
+ (
606
+ WindowLabel::Tuple(vec![float(1.0), int(2)]),
607
+ WindowLabel::Tuple(vec![int(1), float(2.0)]),
608
+ ),
609
+ ] {
610
+ assert!(same_label(&label, &key), "{label:?} is not {key:?}");
611
+ assert!(same_label(&key, &label), "{key:?} is not {label:?}");
612
+ }
613
+
614
+ // and the other half, which a comparison made loose enough to fix the above could start
615
+ // matching: every one of these is `False` in python too
616
+ for (label, key) in [
617
+ (int(2), bool_label(true)),
618
+ (float(1.5), int(1)),
619
+ (float(1.0), int(2)),
620
+ // python compares an int and a float exactly and does not round the int to a double,
621
+ // so this pair is `False` there although both sides are the same `f64`
622
+ (int(100_000_000_000_000_001), float(1e17)),
623
+ // beyond the range of an `i64`, where a saturating cast would match `i64::MAX`
624
+ (int(i64::MAX), float(9.3e18)),
625
+ (int(i64::MIN), float(-9.3e18)),
626
+ // 2^63 exactly, the one float which separates an exclusive upper bound from an
627
+ // inclusive one: it is one above `i64::MAX`, so python says it is no `i64` at all
628
+ (int(i64::MAX), float(9_223_372_036_854_775_808.0)),
629
+ (int(0), float(f64::INFINITY)),
630
+ (int(0), float(f64::NEG_INFINITY)),
631
+ // a `NaN` equals nothing, itself included, as in python
632
+ (float(f64::NAN), float(f64::NAN)),
633
+ (int(0), float(f64::NAN)),
634
+ // a number is no string, no date, no `None` and no tuple
635
+ (int(1), WindowLabel::Str("1".to_string())),
636
+ (float(1.0), WindowLabel::Str("1.0".to_string())),
637
+ (int(1), WindowLabel::None),
638
+ (bool_label(true), WindowLabel::Str("True".to_string())),
639
+ (int(1), WindowLabel::Tuple(vec![int(1)])),
640
+ (
641
+ WindowLabel::Tuple(vec![int(1), int(2)]),
642
+ WindowLabel::Tuple(vec![int(1)]),
643
+ ),
644
+ ] {
645
+ assert!(!same_label(&label, &key), "{label:?} is {key:?}");
646
+ assert!(!same_label(&key, &label), "{key:?} is {label:?}");
647
+ }
648
+
649
+ // the reproduction, end to end, and the mutation beside it: a key which genuinely names
650
+ // no sample has to go on being refused, which is what a comparison made loose enough to
651
+ // fix the above would stop doing
652
+ let times = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0];
653
+ let curve = [1.0, 10.0, 8.0, 6.0, 4.0, 2.0];
654
+ let labelled = |values: Coordinate| Batch {
655
+ coords: vec![SampleCoordinate {
656
+ name: "subject".to_string(),
657
+ dims: vec!["subject".to_string()],
658
+ values,
659
+ }],
660
+ ..parameters::tests::one(&times, &curve)
661
+ };
662
+ let windowed = |key: Option<WindowLabel>| NcaOptions {
663
+ terminal: TerminalPhase {
664
+ windows: key.map(|key| [(key, (1.0, 3.0))].into()),
665
+ ..TerminalPhase::default()
666
+ },
667
+ ..parameters::tests::linear()
668
+ };
669
+ let t_last = |result: &AnalysisResult| parameters::tests::value(result, "lambda_z_t_last");
670
+
671
+ // without the window the regression of this curve runs to its last point, so the
672
+ // assertions below say that the window was found and not that the number is 3.0 anyway
673
+ let open = parameters::tests::run(&labelled(Coordinate::Float(vec![1.0])), &windowed(None));
674
+ assert_eq!(t_last(&open), 5.0);
675
+
676
+ for (coordinate, key) in [
677
+ (Coordinate::Float(vec![1.0]), int(1)),
678
+ (Coordinate::Int(vec![1]), float(1.0)),
679
+ (Coordinate::Bool(vec![true]), int(1)),
680
+ (Coordinate::Int(vec![1]), bool_label(true)),
681
+ ] {
682
+ let batch = labelled(coordinate.clone());
683
+ let result = parameters::tests::run(&batch, &windowed(Some(key.clone())));
684
+ assert_eq!(
685
+ t_last(&result),
686
+ 3.0,
687
+ "the window of {key:?} did not reach {coordinate:?}"
688
+ );
689
+ }
690
+
691
+ for (coordinate, key) in [
692
+ (Coordinate::Float(vec![1.0]), int(2)),
693
+ (Coordinate::Float(vec![1.5]), int(1)),
694
+ (Coordinate::Int(vec![2]), bool_label(true)),
695
+ (Coordinate::Int(vec![1]), WindowLabel::Str("1".to_string())),
696
+ (Coordinate::Float(vec![f64::NAN]), float(f64::NAN)),
697
+ ] {
698
+ let batch = labelled(coordinate.clone());
699
+ let error = analyze_batch(&batch, &windowed(Some(key.clone()))).unwrap_err();
700
+ assert!(
701
+ matches!(&error, KernelError::Options(message) if message.contains("names no sample")),
702
+ "the window of {key:?} reached {coordinate:?}: {error}"
703
+ );
704
+ }
705
+ }
706
+
485
707
  #[test]
486
708
  fn a_contract_error_passes_through_unchanged() {
487
709
  let contract =