nca.engine¶
The rust kernel of the non-compartmental analysis.
pkpdutils-core carries the vectorized core of the analysis as compiled code.
This module is the boundary between the two: it decides whether a batch can go
there at all (unsupported_reason), lays the batch and the options out as the
dicts of the abi (batch_dict, options_dict) and runs them (run_kernel),
giving back the same mapping of one array per variable that
pkpdutils.nca.nca.run_rows gives back, so that nca assembles the result of
either engine with the same code.
The dependency is hard: pkpdutils-core is installed with pkpdutils and
this module imports it at import time. What is not hard is the analysis a
build of it carries, and that is the asymmetry the whole module is built
around:
pkpdutils_core.is_supportedand thepkpdutils_core.UnsupportedErrorofpkpdutils_core.analyze_batchare the authority on what the kernel analyses.unsupported_reasonforwards to the first of them and holds no refusal of its own, so a kernel release which changes one needs no change here; the three conditions it does answer itself are about the python objects and are no refusal of the kernel (see its docstring).- A batch which only
analyze_batchrefuses (a unit the registry of the kernel cannot read) raisesUnsupportedErrorandncafalls back, so the reason is the kernel's own sentence, word for word, either way, andtests/nca/test_engine.pyasserts the two agree on every refusal rather than asserting a text of its own.
The two engines report the same variables with the same numbers, and one
analysis in a different order: a batch of several routes. The python core runs
one group per route and takes the union of their variables in the order the
routes appear in the batch (pkpdutils.nca.nca.merge_rows), where the kernel
reports the union in its canonical order. Nothing of the result but the order
of its variables differs, and the order of the kernel does not depend on which
route the batch names first.
Because the two engines are held to one answer rather than trusted to agree,
this module also carries the comparison itself: compare_engines is every way
in which two mappings of one analysis can disagree and compare_with_python
is the gate pkpdutils.nca.nca.nca runs it from, armed by the environment
variable COMPARE_VARIABLE. The gate compares the answer of a batch which
reached the kernel, so by construction it cannot see the other direction, a
batch which quietly never got there; that one is covered by the cross-check of
tests/conftest.py, which asks both predicates about every batch of the test
suite. The two are complements, not alternatives.
What the gate adds over the reference comparisons of the suite is the argument
for having it, so it is named here rather than left to a judgement.
tests/nca/test_benchmark_datasets.py and tests/nca/test_validation.py hold
the main parameters of theophylline and indomethacin against WinNonlin, PKNCA
and NonCompart within 1e-8, single dose, bolus, infusion and extravascular:
dense cover of those variables on those batches, and the measure of it is that
a mutation of aumc_inf_pred by 1e-5 for every batch of three samples or more
fails 25 tests with the gate disarmed. The gate compares every batch the
caller builds, and these are the parts of an answer no reference table of the
suite reaches, the multiple dose analysis among them (the interval_* point
variables, the steady state, n_doses, tau, the flags INCOMPLETE_INTERVAL
and EXTRAPOLATED_TROUGH, and a last interval completed within tau_tolerance):
flagsandc0_methodas exact integers, which no table of another tool carries and which a tolerance would not compare anyway (_compare_columns),- the point variables of a kept candidate table (
candidate_t_first,candidate_n_points,candidate_r2_adj), which are no column of a parameter table, - a limit of quantification and a terminal window given by hand, neither of which the benchmark scenarios exercise,
- a batch of several routes and the order of its variables, which is the order
of the columns of
NCAResult.to_dataframeand of every rendered table, - the positions of
NaN, the dtype of every column and the unit string the kernel reports for every variable, which the host neither adopts nor drops.
What the gate does not reach is every analysis the dispatch refuses, since
a batch which never goes to the kernel is held against nothing: the acceptance
criteria, the named partial areas, the effect curve and the unit conversion of
a result (unsupported_reason, the table of docs/benchmark.md). Every one of
those is held to the python core alone, by the reference tests of the suite,
and the day the kernel carries one of them the gate compares it without a word
being changed here.
The uncertainty of a group curve is the case that day came for: the kernel
propagates it inside analyze_batch and the python core propagates it inside
python_rows of nca, which are the two answers the gate already holds
against each other, so every x_sd, x_se, x_ci_low, x_ci_high,
x_geomean and x_geocv of a group batch is compared without a line of gate
code of its own. The bootstrap is comparable at all because both engines draw
from the kernel (kernel_normals) and nca resolves the seed before it
dispatches, so the two run the same replicates rather than two samples of one
distribution.
The analyses which are dispatched to the kernel but never pass through nca
are no business of the gate either: ParameterResult.summarize,
time_to_steady_state, nca_sparse and nca_urine (whose rate and
midpoint are point variables of the kernel's own answer). Each of them is
held by a fixture of tests/conftest.py (summary_engine, tss_engine,
sparse_engine, urine_engine) which runs every test of it through both
engines and asserts at teardown that the engine the test names is the one
which ran, and by one test which compares the two answers variable by variable.
Where a reference table does cover a variable, the gate's value is breadth and
diagnosis rather than a sensitivity the suite lacks: of that aumc_inf_pred
mutation the armed run says which variable, which batch and both numbers in
its first failure, where the disarmed run says that 25 published numbers no
longer match.
UnsupportedError is the one exception a caller answers by taking its own
path, and it is re-exported here so that nca catches it without importing
the kernel itself. Every other exception of the bindings is a disagreement
about the contract (a KeyError naming a key of the batch or of the options, a
TypeError, a ValueError the kernel refused the batch with) and must
propagate: the day NCAOptions gains a field without a release of
pkpdutils-core, that KeyError is what says so, and a except ValueError
anywhere on this path would turn it into every batch silently taking the python
path for good.
UnsupportedError
module-attribute
¶
The refusal of an analysis this build of the kernel does not carry.
A subclass of ValueError. It is raised for exactly the two outcomes of
"this build does not support this analysis", the refusal of
pkpdutils_core.is_supported and a refusal the kernel itself reports, and for
nothing else, so it is the one exception a caller answers by taking the python
path (pkpdutils.nca.nca.nca).
FORCED_REASON
module-attribute
¶
The reason unsupported_reason gives while _force_python is set.
EMPTY_REASON
module-attribute
¶
The reason unsupported_reason gives for a batch without a single sample.
Together with FORCED_REASON the only reason of this module which is not the
kernel's own, and the only one of the two about a real batch. pkpdutils-core
(0.2.0 to 0.3.0) derives the variables of its result from the routes of the rows it ran,
so a batch of no rows comes back with one column instead of with the empty
column of every variable python reports (docs/carry-forward.md of the kernel
names the fix, which belongs on its side). The host therefore answers an empty
batch itself, which costs nothing: there is no row to analyse.
MIXED_LABELS_REASON
module-attribute
¶
MIXED_LABELS_REASON = "a terminal window which names a sample of a batch whose labels do not share one type, which one type per label column cannot carry"
The reason unsupported_reason gives for a batch of labels of several types.
The third reason of this module which is not the kernel's own and the second
one about a real batch. A coordinate travels under one type for the whole
column where a window key travels under its own, so a batch whose labels are
of several types and whose options name one of them by hand would be refused
by the kernel with a plain ValueError - no UnsupportedError, so no
fallback - where the python core matches the label and answers. The host
therefore refuses it itself, which routes it to the python core, and the
refusal is the narrowest one which covers the defect (mixed_label_dim,
_names_a_sample): a batch of such labels without a window given by hand is
analysed by the kernel as before, since nothing of its labels is ever read.
HOST_VARIABLES
module-attribute
¶
The variables of a result which the host writes itself, not the kernel.
nca writes the number of subjects behind every sample from
Timecourses.n_subjects after the rows are run, so run_rows does not report
it and run_kernel drops the column of the kernel rather than reporting it one
step early, which would place it in front of the uncertainty variables of the
result instead of behind them. The kernel's own column is compared against the
one of the host rather than adopted.
MIXED_ROUTE_DOSING_REASON
module-attribute
¶
MIXED_ROUTE_DOSING_REASON = "a batch of several routes of which only some have a multiple dose row, whose variables the python core reports per route"
The reason unsupported_reason gives for routes which differ in their dosing.
The python core runs one group per route and reports the steady state variables
of the groups which have a multiple dose row, so a batch of an oral arm of
single doses and an intravenous arm of several has no cl_ss_f, where the
kernel reports one union over the rows and carries it as a column of NaN. The
variables of the two engines then differ and not only their order, which no
host side sorting fixes, so such a batch takes the python path until the
kernel reports the variables per route. A batch whose routes all have a
multiple dose row, or none of them, is carried (_python_order puts its
variables in the order of the core).
This refusal is a workaround and no permanent condition of the host, unlike the three before it: it exists because the kernel reports one union of variables instead of the variables of every route, and it goes when the kernel does.
NORMALS_PER_CALL
module-attribute
¶
The draws one call of kernel_normals asks the kernel for, 4 Mi of them, 32 MB.
The kernel hands out at most 16 Mi in one call and says to ask for a long range in pieces, since the draws of a piece are those of the whole. This is that piece, a quarter of the kernel's own ceiling, so that the peak of a large request is a fraction of the array it fills rather than a second copy of it.
COMPARE_VARIABLE
module-attribute
¶
The environment variable which arms the differential gate.
Set to anything but an empty string, 0, false, no or off, every batch
the kernel analyses is analysed by the python core as well and the two answers
are compared, which costs more than either engine alone and is meant for a
test run and for a bisection, never for production. The suite runs with it in
continuous integration (.github/workflows/ci-cd.yml), which is the acceptance
evidence that the two engines agree on every batch the tests build.
COMPARE_REL
module-attribute
¶
The relative tolerance the values of the two engines are compared with.
The tolerance of tests/nca/test_reference.py, which the analysis is held to
against pkdb_analysis 0.3.1; the two engines are held to the same one.
COMPARE_ABS
module-attribute
¶
The absolute tolerance the values of the two engines are compared with.
KERNEL_UNITLESS
module-attribute
¶
The variables of the mapping whose unit the kernel reports for nobody.
pkpdutils-core (0.2.0 to 0.3.0) reports a unit for every parameter of its result and
none for its flags, which carry no unit on either side (PARAMETER_UNITS
spells them dimensionless). A name of this set is left out of the unit
comparison only while the kernel really reports nothing for it: the day it
reports one, the comparison takes it like any other, so the exemption cannot go
stale. Every other variable of the mapping is compared, which is what makes a
unit the kernel stops reporting a disagreement rather than a silence.
FALSE_WORDS
module-attribute
¶
The values of COMPARE_VARIABLE which leave the gate disarmed.
KernelInput
¶
A batch and its options laid out once as the dicts of the abi.
unsupported_reason and run_kernel both need batch_dict and
options_dict, and the conversion copies the whole batch, so nca builds
one KernelInput and hands it to both rather than converting twice. The
dicts are built on first use, so an analysis the host answers itself
(FORCED_REASON, EMPTY_REASON, MIXED_LABELS_REASON) converts nothing.
Hold the batch and the options, converting nothing yet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timecourses
|
Timecourses
|
the batch |
required |
options
|
NCAOptions
|
the options of the analysis |
required |
EngineMismatch
¶
Bases: RuntimeError
The two engines disagreed on a batch while the differential gate was armed.
No ValueError, so that nothing on the dispatch of pkpdutils.nca.nca.nca
can mistake it for the refusal of an analysis and answer it by taking the
python path: a disagreement is reported to whoever armed the gate and
never swallowed.
unsupported_reason
¶
Why the kernel would refuse this analysis, None when it would run it.
The kernel decides, the host forwards: every refusal of the kernel (an
effect curve, the acceptance criteria, the named partial areas, a bootstrap
whose seed the options leave open, the unit conversion of a result, and
whatever a later release adds) is the answer of
pkpdutils_core.is_supported, text and order included, so that a release
which changes a refusal changes it here without a change of the host.
nca draws the seed of a bootstrap before it asks, so the refusal of a
seedless one is one a caller of nca never meets.
The host answers before it asks only what the kernel cannot see, which is
a statement about the python objects and no refusal of the kernel's, and
each of them is named rather than written here (FORCED_REASON,
EMPTY_REASON, MIXED_LABELS_REASON, MIXED_ROUTE_DOSING_REASON).
is_supported itself accepts all four of them: it says nothing about the python path being pinned, and it answers
None for an empty batch and for a batch of mixed labels, whose analysis
the kernel then answers with one column or rejects with a plain
ValueError. One refusal of the kernel is invisible to is_supported
too, a unit string its registry cannot read, and it is raised by
run_kernel as an UnsupportedError, which nca answers with the
fallback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timecourses
|
Timecourses
|
the batch |
required |
options
|
NCAOptions
|
the options of the analysis |
required |
Other Parameters:
| Name | Type | Description |
|---|---|---|
prepared |
KernelInput | None
|
the conversion of this batch and these options which
|
Returns:
| Type | Description |
|---|---|
str | None
|
The reason, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
kernel_normals
¶
The standard normal draws of a range of flat indices, from the kernel.
The bootstrap's draws are the kernel's on both paths, whether the kernel
analysed the batch or the python core did (pkpdutils_core.bootstrap_normals).
They are a pure function of the seed and the index, so a seed gives one
answer whichever engine ran and whether in python or in the browser, which
numpy's generator cannot promise: it guarantees its stream only on the same
build, in the same environment, on the same machine, and reserves the right
to change a distribution method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
the seed of the bootstrap; every integer of |
required |
start
|
int
|
the flat index of the first draw, in the C order of
|
required |
count
|
int
|
how many draws |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The |
dose_arrays
¶
The dosing protocol of every row as the three (N, max_doses) arrays of the abi.
A batch without doses has max_doses == 0 and three empty arrays rather
than the None of run_rows, since the abi always carries the three
fields. A batch which gives amounts without times is dosed at time 0, as
run_rows reads it, and a dose without a duration is no infusion and is
NaN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timecourses
|
Timecourses
|
the batch |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The amounts, the times and the durations, |
ndarray
|
every row. |
batch_dict
¶
The batch as the dict of batch/1, one key per field of the abi Batch.
The arrays travel as C-contiguous doubles of shape (n_samples,
n_time), the dose arrays as (n_samples, max_doses) and lloq as
(n_samples,), every one of them in the row order of the analysis. The
enumerations travel as the strings both sides spell them with and the
coordinates as records which carry their dtype (_coordinate), since the
kernel labels the samples of a batch with them
(TerminalPhase.windows).
contract is no key of it: the bindings speak one contract and write it
themselves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timecourses
|
Timecourses
|
the batch |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The dict |
dict[str, Any]
|
|
mixed_label_dim
¶
The sample dimension whose labels the two encoders of the host disagree about.
A coordinate travels under one type for the whole column
(_coordinate_values), as the kernel's Coordinate carries one, where
encode_window_key keeps the type of every single key of
TerminalPhase.windows. For a column whose values share one type the two
agree, and for one whose values do not, the column travels as text while a
key of it travels as its own type: the kernel then holds Str("1") against
Int(1), finds no sample of that name and refuses the batch with a plain
ValueError, where the python core matches the label (sample_keys).
Such a batch is therefore the host's own refusal
(MIXED_LABELS_REASON) rather than a batch the kernel may see, and the
refusal is as narrow as the defect: a value whose record is the text of
the label itself (TEXT_KEY_TYPES, a string as itself and a date or a
datetime as its isoformat) meets the text of the column whichever way the
column was tagged, so a column of dates and a column of dates and strings
are both carried faithfully and are not refused. Only the sample
dimensions are read, since the label of a sample is the value of its
dimension coordinate and nothing else (sample_keys), and a window keyed
by anything which is no label of the batch is refused by the host before
either engine is reached (sample_windows).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timecourses
|
Timecourses
|
the batch. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The name of the first sample dimension whose labels do not survive the |
str | None
|
crossing, or |
options_dict
¶
The options as the dict of the nca options of version 1.
One key per field of NCAOptions, which the bindings read by name: a
field the model gains and the kernel does not map is refused by the
kernel, naming the key, and a field it loses is refused the same way, so
an option cannot go silently inert. _nca_options_version is no key of
it, as contract is no key of the batch.
The terminal windows travel as the typed records of encode_window_key
and not as a mapping keyed by the label, because a python dict key says no
more about whether it is a string, a number or a tuple than a JSON key
does. An interval of two times is a tuple on both sides, where
BaseModel.model_dump writes a list for one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
options
|
NCAOptions
|
the options of the analysis |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The dict |
dict[str, Any]
|
|
kernel_result
¶
Run the kernel on a batch and give back its result as it comes.
The six sections of the bindings: parameters, units over the variables
of every section, flags, point_variables, booleans and texts.
run_kernel flattens the ones the host analyses with; the others are read
from here by whatever compares the two engines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timecourses
|
Timecourses
|
the batch |
required |
options
|
NCAOptions
|
the options of the analysis |
required |
Other Parameters:
| Name | Type | Description |
|---|---|---|
prepared |
KernelInput | None
|
the conversion of the batch and the options, made once by the
caller which asked |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The result of |
Raises:
| Type | Description |
|---|---|
UnsupportedError
|
if this build of the kernel does not carry the
analysis, which |
ValueError
|
if |
run_kernel
¶
Run the kernel on a batch, as run_rows runs the python core.
The parameters of the kernel, its point variables as (N, K) arrays and
its flags, in the layout and the order pkpdutils.nca.nca.run_rows
reports: one (N,) array per parameter, the variables the host writes
itself left out (HOST_VARIABLES) and the numbers in the units the batch
was measured in (_as_computed). flags is the last variable of a batch
of one route; a batch of several is sorted into python's order by
_python_order, which carries flags inside the block of the group
merge_rows reports first. The units of the kernel are not adopted
either: nca derives the unit of every variable of its result with pint,
from the units of the batch, whichever engine computed the numbers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timecourses
|
Timecourses
|
the batch |
required |
options
|
NCAOptions
|
the options of the analysis |
required |
Other Parameters:
| Name | Type | Description |
|---|---|---|
units |
dict[str, str] | None
|
a dict the unit the kernel reports for every variable of its
result is written into, the one part of its answer which
|
prepared |
KernelInput | None
|
the conversion of the batch and the options, see
|
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
One array per variable, |
Raises:
| Type | Description |
|---|---|
UnsupportedError
|
if this build of the kernel does not carry the
analysis, which |
ValueError
|
if |
comparing
¶
Whether the differential gate is armed (COMPARE_VARIABLE).
One lookup of the environment per analysis, which is what an ordinary run
of pkpdutils.nca.nca.nca pays for the gate. The value is read every time
rather than once at import, so that a test arms and disarms it with
monkeypatch.setenv.
Returns:
| Type | Description |
|---|---|
bool
|
Whether the two engines are to be compared. |
note_comparison
¶
Record that the gate compared the two engines on one batch.
Called by the dispatch of pkpdutils.nca.nca.nca after a comparison and
deliberately not by compare_with_python itself: the tests of the gate
call that function directly with COMPARE_VARIABLE set by monkeypatch,
so a counter kept inside it could never be zero and the sentinel which
reads it would be satisfied by the gate's own unit tests instead of by the
batch of an analysis.
comparisons
¶
How many batches the gate compared since this module was imported.
The witness tests/conftest.py fails a test session on: a run which says
it armed the gate and compared nothing took the whole suite through one
engine while reporting the agreement of two, which is the one failure of
this gate that nothing else can see - every test passes, in the ordinary
way, and the evidence is a job that was never armed.
Read as a floor and not as an exact count: nothing is asserted against the
number itself, only against its being above zero. importlib.reload of
this module sets it back to zero, which one test of
tests/nca/test_engine.py does on purpose and repairs afterwards by
replaying the count through note_comparison, so an armed run whose last
comparison came before that test still reports what it compared.
Returns:
| Type | Description |
|---|---|
int
|
The number of batches |
compare_engines
¶
Every way in which two mappings of the same analysis disagree.
The mappings are the ones the two engines report
(pkpdutils.nca.nca.run_analysis_rows and run_kernel), in the layout the
result is assembled from, and the two unit mappings are the unit of every
variable as each engine spells it.
What is compared, and how:
- the names, in both directions: a variable one engine reports and the other does not is named rather than skipped, which is the one way a comparison of two mappings can pass by looking at nothing
- the order of the variables they share, since it is the order of the
columns of
NCAResult.to_dataframeand of every table rendered from a result, so a swap is observable to a user - the shape and the dtype of every column, a counted variable being an integer on both sides and a measured one a double
- the positions of
NaN, exactly: a parameter which isNaNin one engine and a number in the other is a disagreement about whether the analysis has an answer at all, and a tolerance must never hide it - the numbers, within
COMPARE_RELandCOMPARE_ABS, except a column which counts rather than measures: a flag word and the rule ofc0_methodare compared exactly, since a relative tolerance on a bit field would let a high bit differ unnoticed - the units, as strings, exactly
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
python
|
Mapping[str, ndarray]
|
one array per variable, as the python core reports them |
required |
kernel
|
Mapping[str, ndarray]
|
one array per variable, as the kernel reports them |
required |
Other Parameters:
| Name | Type | Description |
|---|---|---|
units_python |
Mapping[str, str]
|
the unit of every variable as the host derives it with pint |
units_kernel |
Mapping[str, str]
|
the unit of every variable as the kernel reports it |
Returns:
| Type | Description |
|---|---|
list[str]
|
One sentence per disagreement, naming the variable and both values; |
list[str]
|
empty when the two engines agree. |
host_units
¶
The unit of every named variable as the host derives it with pint.
pkpdutils.nca.nca._to_result derives the unit of every variable of a
result this way, whichever engine computed the numbers, so these are the
units a caller of nca really sees. A name the host knows no expression
for is left out rather than raising: it is a variable of the kernel alone,
which compare_engines reports by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
names
|
Iterable[str]
|
the variables to derive the units of |
required |
timecourses
|
Timecourses
|
the analysed batch, which carries the units |
required |
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
The unit of every name, in the order of the names. |
compare_with_python
¶
Hold the kernel's answer against the python core's, and raise if they differ.
The gate of pkpdutils.nca.nca.nca, armed by COMPARE_VARIABLE: the two
mappings are the answers of the two engines to one batch and the units are
the kernel's own, which are held against pint's derivation (host_units) -
the one part of the kernel's answer the host does not adopt, so a kernel
which computed a parameter in another unit than the host believes is a
disagreement here rather than a wrong number nobody can see.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timecourses
|
Timecourses
|
the analysed batch, which carries the units and names the shape in the message |
required |
Other Parameters:
| Name | Type | Description |
|---|---|---|
kernel |
Mapping[str, ndarray]
|
the mapping of the kernel |
python |
Mapping[str, ndarray]
|
the mapping of the python core on the same batch |
units_kernel |
Mapping[str, str]
|
the unit of every variable as the kernel reports it
( |
Raises:
| Type | Description |
|---|---|
EngineMismatch
|
if the two engines disagree in any way
|