pkpdutils-core 0.2.0__tar.gz → 0.2.1__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.1}/Cargo.lock +5 -5
  2. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/Cargo.toml +1 -1
  3. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/PKG-INFO +2 -2
  4. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/README.md +1 -1
  5. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/core/Cargo.toml +2 -2
  6. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/core/src/assemble.rs +135 -20
  7. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/core/src/lib.rs +227 -5
  8. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/python/Cargo.toml +2 -2
  9. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/python/README.md +1 -1
  10. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/python/src/lib.rs +77 -14
  11. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/python/src/options.rs +8 -0
  12. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/units/src/lib.rs +115 -1
  13. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/units/src/registry.rs +104 -2
  14. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/LICENSE +0 -0
  15. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/Cargo.toml +0 -0
  16. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/README.md +0 -0
  17. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/src/batch.rs +0 -0
  18. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/src/enums.rs +0 -0
  19. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/src/lib.rs +0 -0
  20. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/src/nonfinite.rs +0 -0
  21. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/src/options.rs +0 -0
  22. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/src/result.rs +0 -0
  23. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/src/window.rs +0 -0
  24. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/tests/data/enum_values.json +0 -0
  25. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/tests/data/options_all_fields.json +0 -0
  26. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/tests/data/options_default.json +0 -0
  27. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/tests/data/options_effect.json +0 -0
  28. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/tests/data/options_full.json +0 -0
  29. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/tests/data/options_manual_points.json +0 -0
  30. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/tests/data/options_windows.json +0 -0
  31. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/abi/tests/options_from_python.rs +0 -0
  32. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/core/README.md +0 -0
  33. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/core/examples/kernel_timing.rs +0 -0
  34. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/core/src/auc.rs +0 -0
  35. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/core/src/blq.rs +0 -0
  36. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/core/src/dose.rs +0 -0
  37. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/core/src/pack.rs +0 -0
  38. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/core/src/parameters.rs +0 -0
  39. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/core/src/shard.rs +0 -0
  40. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/core/src/terminal.rs +0 -0
  41. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/python/LICENSE +0 -0
  42. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/python/src/convert.rs +0 -0
  43. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/python/src/result.rs +0 -0
  44. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/python/tests/test_bindings.py +0 -0
  45. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/units/Cargo.toml +0 -0
  46. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/units/README.md +0 -0
  47. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/units/src/format.rs +0 -0
  48. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/units/src/parameter.rs +0 -0
  49. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/units/tests/data/pint_gate.json +0 -0
  50. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/crates/units/tests/pint_gate.rs +0 -0
  51. {pkpdutils_core-0.2.0 → pkpdutils_core-0.2.1}/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.1"
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.1"
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.1"
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.1"
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.1"
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.1"
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.1
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
 
@@ -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.1" }
18
+ pkpdutils-units = { path = "../units", version = "0.2.1" }
19
19
  thiserror.workspace = true
20
20
  rayon = { workspace = true, optional = true }
21
21
 
@@ -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 =
@@ -36,8 +36,8 @@ parallel = ["pkpdutils-core/parallel"]
36
36
  # `parallel` feature of the kernel is not enabled here by default: which features a wheel carries
37
37
  # is settled where the wheel is built, and a build without it runs every shard plan in the
38
38
  # calling thread, which is the same numbers and one thread
39
- pkpdutils-abi = { path = "../abi", version = "0.2.0" }
40
- pkpdutils-core = { path = "../core", version = "0.2.0" }
39
+ pkpdutils-abi = { path = "../abi", version = "0.2.1" }
40
+ pkpdutils-core = { path = "../core", version = "0.2.1" }
41
41
  pyo3 = { workspace = true }
42
42
  numpy = { workspace = true }
43
43
  # The allocator of the extension module, set as the `#[global_allocator]` in `src/lib.rs`. It is
@@ -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
 
@@ -51,11 +51,16 @@ create_exception!(
51
51
  other way, and it is a type and not a sentence so that the rule can be written as one \
52
52
  line which cannot be got wrong: catch `UnsupportedError` and fall back, let everything \
53
53
  else through. The failures it must not be confused with - an options dict carrying a key \
54
- or an enumeration value this build does not spell, a batch the kernel refuses - mean that \
55
- the caller and this build disagree about the contract or that the data is malformed, and \
56
- both of those are defects to fix rather than work to route elsewhere. Several of them are \
57
- a plain `ValueError`, so a host which caught `ValueError` would swallow exactly the \
58
- disagreement this design exists to make loud.\n\n\
54
+ or an enumeration value this build does not spell, a malformed batch the kernel refuses - \
55
+ mean that the caller and this build disagree about the contract or that the data is \
56
+ malformed, and both of those are defects to fix rather than work to route elsewhere. \
57
+ Several of them are a plain `ValueError`, so a host which caught `ValueError` would \
58
+ swallow exactly the disagreement this design exists to make loud.\n\n\
59
+ A unit string of the batch which the curated registry of this build cannot read (a time in \
60
+ `week`, a concentration in `U/l`) is one of these refusals and not one of those defects: \
61
+ what this build reads is a property of this build, and a host whose own engine reads the \
62
+ string analyses the batch there. It is the one refusal `is_supported` does not see, since \
63
+ answering it means deriving the units of the result.\n\n\
59
64
  It subclasses `ValueError`, which is what this refusal was before it had a type of its \
60
65
  own, so a caller which catches `ValueError` keeps catching it.\n\n\
61
66
  `is_supported` asks the same question without raising, and a host asks it first."
@@ -84,14 +89,18 @@ create_exception!(
84
89
  /// - an [`UnsupportedError`], and nothing else is one. The batch and the options are well
85
90
  /// formed and this build does not carry the analysis they ask for. This is the one a host
86
91
  /// answers by taking its own path; [`is_supported`] is the same question without an
87
- /// exception, and a host asks it first.
92
+ /// exception, and a host asks it first. One of these refusals is one the predicate cannot
93
+ /// answer: a unit string the curated registry of the kernel cannot read (a time in `week`, a
94
+ /// concentration in `U/l`, pint's `mg l`, a spelling pint over-forgives such as `mg//l`). A
95
+ /// host which routes on the type, which is what this one is for, sees no difference; a host
96
+ /// which took the predicate as the whole answer would raise at its user.
88
97
  /// - a `KeyError`, a `TypeError` or a `ValueError` naming a key of the batch or of the options.
89
98
  /// The caller and this build disagree about the contract, which is a defect of one of the
90
99
  /// two and never a reason to analyse the batch some other way. A field or an enumeration
91
100
  /// value `NCAOptions` gains without a release of this crate lands here, loudly, in the test
92
101
  /// suite of the host.
93
- /// - a `ValueError` carrying what the kernel refused the batch with: a malformed batch, a unit
94
- /// which is no unit, options which contradict each other.
102
+ /// - a `ValueError` carrying what the kernel refused the batch with: a malformed batch, doses
103
+ /// without a dose unit, options which contradict each other.
95
104
  ///
96
105
  /// A `RuntimeError` is the fourth and is a bug: see [`guarded`] and [`result_into_python`].
97
106
  #[pyfunction]
@@ -144,6 +153,15 @@ fn unsupported(refusal: &kernel::KernelError) -> PyErr {
144
153
  /// kernel's own, bare: it names the analysis which is missing and not this build, since the
145
154
  /// host writes it into a line of its own and [`analyze_batch`] is what raises.
146
155
  ///
156
+ /// `None` is "nothing here says this build would refuse it" and not a promise that it will not:
157
+ /// one refusal of the kernel is invisible here, a unit string of the batch which its curated
158
+ /// registry cannot read (a time in `week`, a concentration in `U/l`). Answering that one means
159
+ /// deriving the unit of every parameter of the result, which is the analysis itself, so it is
160
+ /// [`analyze_batch`] which reports it - as an [`UnsupportedError`], like every other refusal, so
161
+ /// a host which routes on the type is right either way. Mirroring the registry here, or in the
162
+ /// host, would be a second copy of a curated list which drifts from the first in silence, and
163
+ /// that is worse than the one call which answers it exactly.
164
+ ///
147
165
  /// # Errors
148
166
  ///
149
167
  /// Whatever the conversion of the batch or of the options raises, which is a disagreement about
@@ -570,14 +588,57 @@ mod tests {
570
588
  assert!(message.contains("is_supported"), "{message}");
571
589
 
572
590
  // and what the kernel itself refuses, which the predicate does not answer for: a
573
- // unit no registry knows is found while the result is assembled
591
+ // batch with doses and no dose unit, found while the result is assembled
574
592
  let batch = batch_dict(py, 2);
575
- batch.set_item("unit", "banana/l").unwrap();
593
+ batch.set_item("dose_unit", py.None()).unwrap();
576
594
  let err = analyze_batch(py, &batch, &options_dict(py), None).unwrap_err();
577
595
  assert!(err.is_instance_of::<PyValueError>(py), "{err}");
596
+ assert!(!err.is_instance_of::<UnsupportedError>(py), "{err}");
578
597
  let message = err.to_string();
579
598
  assert!(message.contains("the batch is not analysable"), "{message}");
580
- assert!(message.contains("banana"), "{message}");
599
+ assert!(message.contains("cl_f"), "{message}");
600
+ });
601
+ }
602
+
603
+ #[test]
604
+ fn a_unit_the_registry_cannot_read_reaches_the_host_as_a_refusal() {
605
+ // The one refusal of the kernel the predicate does not answer for, and the reason this
606
+ // test exists: `week` is the time base of a monoclonal antibody, a depot and an oncology
607
+ // study, `U/l` an ordinary clinical concentration and `mg//l` a typo pint forgives and
608
+ // `pkpdutils` 1.4.0 therefore computes. Reported as a plain `ValueError` every one of
609
+ // them reaches the user of the host, whose fallback catches `UnsupportedError` and,
610
+ // deliberately, nothing broader.
611
+ Python::attach(|py| {
612
+ for (key, spelling) in [
613
+ ("time_unit", "week"),
614
+ ("time_unit", "month"),
615
+ ("unit", "U/l"),
616
+ ("dose_unit", "kilohour"),
617
+ ("unit", "mg l"),
618
+ ("unit", "mg//l"),
619
+ ("time_unit", "hr**--2"),
620
+ ("unit", "mg/"),
621
+ ] {
622
+ let batch = batch_dict(py, 2);
623
+ batch.set_item(key, spelling).unwrap();
624
+ // the predicate reads nothing about the units and says so
625
+ assert_eq!(
626
+ is_supported(py, &batch, &options_dict(py)).unwrap(),
627
+ None,
628
+ "{key} = {spelling}"
629
+ );
630
+ let err = analyze_batch(py, &batch, &options_dict(py), None).unwrap_err();
631
+ assert!(
632
+ err.is_instance_of::<UnsupportedError>(py),
633
+ "{key} = {spelling}: {err}"
634
+ );
635
+ let message = err.to_string();
636
+ assert!(message.contains(spelling), "{message}");
637
+ assert!(
638
+ message.contains("does not carry this analysis"),
639
+ "{message}"
640
+ );
641
+ }
581
642
  });
582
643
  }
583
644
 
@@ -611,10 +672,12 @@ mod tests {
611
672
  let err = analyze_batch(py, &batch_dict(py, 2), &unknown, None).unwrap_err();
612
673
  assert!(!err.is_instance_of::<UnsupportedError>(py), "{err}");
613
674
 
614
- // and a batch the kernel itself refuses, which is malformed data and not an
615
- // analysis of another plan
675
+ // and a batch the kernel itself refuses, which is incomplete data and not an
676
+ // analysis of another plan: doses without a dose unit, where a unit this build
677
+ // cannot read is a refusal
678
+ // (`a_unit_the_registry_cannot_read_reaches_the_host_as_a_refusal`)
616
679
  let batch = batch_dict(py, 2);
617
- batch.set_item("unit", "banana/l").unwrap();
680
+ batch.set_item("dose_unit", py.None()).unwrap();
618
681
  let err = analyze_batch(py, &batch, &options_dict(py), None).unwrap_err();
619
682
  assert!(err.is_instance_of::<PyValueError>(py), "{err}");
620
683
  assert!(!err.is_instance_of::<UnsupportedError>(py), "{err}");
@@ -120,6 +120,14 @@ const OPTION_KEYS: [&str; 24] = [
120
120
  /// are not is what `the_predicate_agrees_with_the_kernel` exists to catch: a predicate wider
121
121
  /// than the kernel turns into an exception at the user's call site, and a narrower one sends
122
122
  /// work this build carries down the slow path for good.
123
+ ///
124
+ /// Those seven are every refusal which can be read off a batch and its options. The kernel has
125
+ /// an eighth which cannot - a unit string its curated registry cannot read, answered by deriving
126
+ /// the units of the result - and it is deliberately not mirrored here: a copy of that registry
127
+ /// is a list which drifts in silence, where the refusal itself is exact. `None` is therefore
128
+ /// "nothing here refuses it" and not a promise that the analysis will run, and `analyze_batch`
129
+ /// stays the authority. It reports that one with the same `UnsupportedError` as every refusal of
130
+ /// this list, so a host which routes on the type is right either way.
123
131
  pub(crate) fn unsupported_reason(batch: &Batch, options: &NcaOptions) -> Option<String> {
124
132
  let reason = |what: &str| Some(what.to_string());
125
133
  if options.kind == Kind::Effect {
@@ -338,7 +338,7 @@ mod tests {
338
338
  use UnitError::*;
339
339
  let syntax = |e: UnitError| matches!(e, Syntax { .. });
340
340
  for input in [
341
- "mg/", "/mg", "mg*", "()", "mg//l", "mg**", "mg**1.5", "(mg", "mg)",
341
+ "mg/", "/mg", "mg*", "()", "mg//l", "mg**", "(mg", "mg)", "mg.l", "mg**1.", ".5*mg",
342
342
  ] {
343
343
  assert!(syntax(parse_unit(input).unwrap_err()), "{input}");
344
344
  }
@@ -367,6 +367,119 @@ mod tests {
367
367
  assert!(is_per_bodyweight("mg**200").is_err());
368
368
  }
369
369
 
370
+ #[test]
371
+ fn the_two_refusals_of_the_curation_have_an_error_of_their_own() {
372
+ // pint's implicit product and its fractional exponent are refused here deliberately
373
+ // (see the module documentation of `registry`), and each says so instead of landing in
374
+ // the catch-all of the parser: "a product needs a '*'" is what a person reading a
375
+ // fallback warning can act on, where "unexpected Name(\"l\")" is not.
376
+ for input in ["mg l", "mg (l)", "(mg)(l)", "(mg l)/hr", "mg l hr", "1 mg"] {
377
+ assert!(
378
+ matches!(
379
+ parse_unit(input).unwrap_err(),
380
+ UnitError::ImplicitProduct { .. }
381
+ ),
382
+ "{input}"
383
+ );
384
+ }
385
+ for input in [
386
+ "hr**0.5",
387
+ "mg**1.5",
388
+ "hr ** 0.5",
389
+ "mg**-1.5",
390
+ "mg**1.0",
391
+ "hr**.5",
392
+ ] {
393
+ assert!(
394
+ matches!(
395
+ parse_unit(input).unwrap_err(),
396
+ UnitError::FractionalExponent { .. }
397
+ ),
398
+ "{input}"
399
+ );
400
+ }
401
+ }
402
+
403
+ #[test]
404
+ fn a_string_this_registry_cannot_read_is_told_apart_from_a_unit_the_context_cannot_use() {
405
+ // The classification a host routes on, and the rule is one line: a string this build
406
+ // cannot read is not supported by this build, whatever the reason the parser gives. A
407
+ // new variant of `UnitError` is classified by hand in `is_unsupported`, where the
408
+ // exhaustive match refuses to compile without it.
409
+ let deep = format!(
410
+ "{}mg{}",
411
+ "(".repeat(MAX_DEPTH + 1),
412
+ ")".repeat(MAX_DEPTH + 1)
413
+ );
414
+ for input in [
415
+ // the time base of a monoclonal antibody, a depot or an oncology study, and the
416
+ // clinical spelling of an enzyme activity: the defect this classification was
417
+ // written for
418
+ "week",
419
+ "weeks",
420
+ "month",
421
+ "year",
422
+ "yr",
423
+ "U",
424
+ "U/l",
425
+ "mU/l",
426
+ // a prefix on a unit the registry does not let a prefix on
427
+ "kilohour",
428
+ "hectoliter",
429
+ // pint's syntax beyond this parser
430
+ "mg l",
431
+ "hr**0.5",
432
+ // the two limits of this build on an expression it would otherwise read
433
+ "mg**65",
434
+ deep.as_str(),
435
+ // a spelling pint over-forgives and `pkpdutils` 1.4.0 therefore computes (`mg/l`
436
+ // and `mg**2`): refusing the batch for it would narrow what a released library
437
+ // accepts, which is the defect and not the spelling
438
+ "mg//l",
439
+ "mg**--2",
440
+ // and a string which is no unit anywhere. Uniform with the rest because the rule is
441
+ // one line and because the host parses every unit with pint before a batch exists,
442
+ // so nothing of this class reaches the kernel through it anyway
443
+ "",
444
+ "mg/",
445
+ "/mg",
446
+ "()",
447
+ "(mg",
448
+ "mg)",
449
+ "2*mg",
450
+ "mg.l",
451
+ ] {
452
+ let error = parse_unit(input).unwrap_err();
453
+ assert!(error.is_unsupported(), "{input}: {error}");
454
+ }
455
+ // every spelling of the package reads, so none of them is ever classified at all
456
+ for input in [
457
+ "mg/l", "ug/ml", "hr", "min", "day", "s", "IU", "mIU/l", "mmol/l", "%",
458
+ ] {
459
+ assert!(parse_unit(input).is_ok(), "{input}");
460
+ }
461
+ // a unit which reads and is no dose is a defect of the batch and not of this build
462
+ let not_a_dose = check_dose_unit("mg/l").unwrap_err();
463
+ assert!(!not_a_dose.is_unsupported(), "{not_a_dose}");
464
+ // and so is an expression which needs a unit the context does not carry
465
+ let context = UnitContext {
466
+ unit: "mg/l",
467
+ time: "hr",
468
+ dose: None,
469
+ amount: None,
470
+ volume: None,
471
+ };
472
+ let missing = parameter_unit("{dose}/({unit})", &context).unwrap_err();
473
+ assert!(!missing.is_unsupported(), "{missing}");
474
+ // while the same expression over a unit this registry does not carry is a refusal
475
+ let week = UnitContext {
476
+ time: "week",
477
+ ..context.clone()
478
+ };
479
+ let refused = parameter_unit("{unit} * {time}", &week).unwrap_err();
480
+ assert!(refused.is_unsupported(), "{refused}");
481
+ }
482
+
370
483
  #[test]
371
484
  fn every_error_clips_the_host_string_it_echoes() {
372
485
  // a unit string crosses a host boundary and is unbounded, so no error
@@ -379,6 +492,7 @@ mod tests {
379
492
  parse_unit(&digits).unwrap_err(),
380
493
  parse_unit(&format!("mg {long}")).unwrap_err(),
381
494
  parse_unit(&format!("mg**{digits}")).unwrap_err(),
495
+ parse_unit(&format!("mg**1.{digits}")).unwrap_err(),
382
496
  parse_unit(&format!("{}mg{}", "(".repeat(5_000), ")".repeat(5_000))).unwrap_err(),
383
497
  check_dose_unit(&format!("mmHg{}", "*1".repeat(5_000))).unwrap_err(),
384
498
  parameter_unit(
@@ -10,7 +10,11 @@
10
10
  //! What it deliberately does not mirror is pint beyond those units: a prefix
11
11
  //! outside [`PREFIXES`] (no `hectoliter`), a prefixed unit which is not
12
12
  //! `prefixable` (no `kilohour`), pint's implicit product (`mg l`) and its
13
- //! fractional exponents (`hr ** 0.5`), all of which are an error here.
13
+ //! fractional exponents (`hr ** 0.5`), all of which are an error here. What
14
+ //! this registry can read is a property of this build and not of the string,
15
+ //! which is what [`UnitError::is_unsupported`] tells a host, so that a host
16
+ //! which reads the string itself can analyse such a batch instead of raising at
17
+ //! its user.
14
18
  //!
15
19
  //! One spelling names the same quantity differently: pint has `fermi`, whose
16
20
  //! symbol is `fm` and whose exact match beats the prefix decomposition, so `fm`
@@ -233,6 +237,73 @@ pub enum UnitError {
233
237
  /// Its dimension.
234
238
  dimension: String,
235
239
  },
240
+ /// Two units with no operator between them, pint's implicit product.
241
+ #[error("'{unit}' writes a product without a '*', which this registry does not read")]
242
+ ImplicitProduct {
243
+ /// The unit string.
244
+ unit: String,
245
+ },
246
+ /// An exponent which is not an integer, which pint reads and this registry does not.
247
+ #[error("an exponent of '{unit}' is not an integer, which this registry does not read")]
248
+ FractionalExponent {
249
+ /// The unit string.
250
+ unit: String,
251
+ },
252
+ }
253
+
254
+ impl UnitError {
255
+ /// Whether the error is a string this build could not read, rather than a unit it read and
256
+ /// the context cannot use.
257
+ ///
258
+ /// The rule is one line, and it is the one a host routes on: **a unit string this build
259
+ /// cannot read is not supported by this build.** Readability is a property of the build and
260
+ /// of nothing else, which is what `KernelError::Unsupported` of `pkpdutils-core` and
261
+ /// `UnsupportedError` in python mean, so a host whose own engine reads the string analyses
262
+ /// the batch there and no user sees an exception for it.
263
+ ///
264
+ /// `true`, therefore, for every way the parser can fail: a unit outside this curated
265
+ /// registry ([`UnitError::Unknown`]: `week`, `month`, `year`, `U`, and a prefix on a unit
266
+ /// which is not prefixable, `kilohour`, `hectoliter`), the syntax it deliberately does not
267
+ /// mirror ([`UnitError::ImplicitProduct`], pint's `mg l`;
268
+ /// [`UnitError::FractionalExponent`], pint's `hr ** 0.5`), the limits it puts on an
269
+ /// expression it would otherwise read ([`UnitError::Exponent`], [`UnitError::Nesting`]),
270
+ /// the empty string ([`UnitError::Empty`]) and whatever is left
271
+ /// ([`UnitError::Syntax`]).
272
+ ///
273
+ /// [`UnitError::Syntax`] belongs in that list even though pint refuses most of what lands
274
+ /// there, and the reason is a measurement rather than a taste: pint reads `mg//l` as
275
+ /// `mg / l` and `hr**--2` as `hr ** 2`, so `pkpdutils` 1.4.0 computes a batch spelled that
276
+ /// way and this parser does not. Refusing it as a malformed batch would narrow the input a
277
+ /// released library accepts, which is a defect whatever one thinks of the spelling, and
278
+ /// pint's permissiveness is not something a port of its kernel gets to change as a side
279
+ /// effect. Tightening it is a change against the host's own validation, where it would apply
280
+ /// with or without this build.
281
+ ///
282
+ /// `false` for the three errors which are not about reading a string at all, where the unit
283
+ /// read and the context is what is wrong:
284
+ ///
285
+ /// - [`UnitError::MissingPlaceholder`], a batch with doses and no dose unit, which is
286
+ /// incomplete rather than unreadable and which python raises on in the same place,
287
+ /// - [`UnitError::UnknownPlaceholder`], an expression of this build and not of the host,
288
+ /// - [`UnitError::NotADose`], a unit which reads and whose dimension is wrong for a dose.
289
+ ///
290
+ /// The match is exhaustive on purpose: a variant added later has to be classified by hand
291
+ /// here, where the two kinds are written down, instead of falling into one of them.
292
+ #[must_use]
293
+ pub fn is_unsupported(&self) -> bool {
294
+ match self {
295
+ UnitError::Empty
296
+ | UnitError::Unknown { .. }
297
+ | UnitError::Syntax { .. }
298
+ | UnitError::Exponent { .. }
299
+ | UnitError::Nesting { .. }
300
+ | UnitError::ImplicitProduct { .. }
301
+ | UnitError::FractionalExponent { .. } => true,
302
+ UnitError::MissingPlaceholder { .. }
303
+ | UnitError::UnknownPlaceholder { .. }
304
+ | UnitError::NotADose { .. } => false,
305
+ }
306
+ }
236
307
  }
237
308
 
238
309
  /// One named unit of a [`Unit`] with its exponent.
@@ -618,6 +689,11 @@ enum Token {
618
689
  Close,
619
690
  }
620
691
 
692
+ /// Whether `chars` holds an ascii digit at `at`.
693
+ fn digit_at(chars: &[char], at: usize) -> bool {
694
+ chars.get(at).is_some_and(char::is_ascii_digit)
695
+ }
696
+
621
697
  fn tokenize(s: &str) -> Result<Vec<Token>, String> {
622
698
  let chars: Vec<char> = s.chars().collect();
623
699
  let mut tokens = Vec::new();
@@ -644,11 +720,21 @@ fn tokenize(s: &str) -> Result<Vec<Token>, String> {
644
720
  } else if c == ')' {
645
721
  tokens.push(Token::Close);
646
722
  i += 1;
647
- } else if c.is_ascii_digit() {
723
+ } else if c.is_ascii_digit() || (c == '.' && digit_at(&chars, i + 1)) {
648
724
  let start = i;
649
725
  while i < chars.len() && chars[i].is_ascii_digit() {
650
726
  i += 1;
651
727
  }
728
+ // a decimal point belongs to the number only between digits, so that the parser can
729
+ // tell a fractional exponent, which pint reads and this registry deliberately
730
+ // refuses (`UnitError::FractionalExponent`), from a stray '.', which is no unit
731
+ // anywhere and stays a syntax error
732
+ if chars.get(i) == Some(&'.') && digit_at(&chars, i + 1) {
733
+ i += 1;
734
+ while i < chars.len() && chars[i].is_ascii_digit() {
735
+ i += 1;
736
+ }
737
+ }
652
738
  tokens.push(Token::Number(chars[start..i].iter().collect()));
653
739
  } else if c == '%' {
654
740
  tokens.push(Token::Name("%".to_string()));
@@ -675,6 +761,10 @@ enum Failure {
675
761
  Unknown(String),
676
762
  Exponent,
677
763
  Nesting,
764
+ /// Two atoms with no operator between them, pint's implicit product.
765
+ ImplicitProduct,
766
+ /// An exponent which is not an integer, pint's fractional exponent.
767
+ Fractional,
678
768
  }
679
769
 
680
770
  struct Parser {
@@ -701,6 +791,11 @@ impl Parser {
701
791
  self.pos += 1;
702
792
  left = left.over(&self.term()?).ok_or(Failure::Exponent)?;
703
793
  }
794
+ // a term where an operator belongs is pint's implicit product (`mg l`, `mg (l)`,
795
+ // `(mg)(l)`), which this registry deliberately does not read. It is answered
796
+ // here rather than by the leftover check of `parse_unit`, so that the one inside
797
+ // a parenthesis (`(mg l)/hr`) is the same error and not a missing parenthesis
798
+ Some(Token::Name(_) | Token::Open) => return Err(Failure::ImplicitProduct),
704
799
  _ => return Ok(left),
705
800
  }
706
801
  }
@@ -728,6 +823,11 @@ impl Parser {
728
823
  }
729
824
  match self.peek() {
730
825
  Some(Token::Number(digits)) => {
826
+ // a decimal point is in the token only between digits (`tokenize`), so this is
827
+ // pint's fractional exponent and not a number too long for an `i32`
828
+ if digits.contains('.') {
829
+ return Err(Failure::Fractional);
830
+ }
731
831
  let n: i32 = digits.parse().map_err(|_| Failure::Exponent)?;
732
832
  self.pos += 1;
733
833
  bounded(sign * n).ok_or(Failure::Exponent)
@@ -833,5 +933,7 @@ pub fn parse_unit(s: &str) -> Result<Unit, UnitError> {
833
933
  name: clipped(&name),
834
934
  unit: clipped(s),
835
935
  }),
936
+ Err(Failure::ImplicitProduct) => Err(UnitError::ImplicitProduct { unit: clipped(s) }),
937
+ Err(Failure::Fractional) => Err(UnitError::FractionalExponent { unit: clipped(s) }),
836
938
  }
837
939
  }
File without changes