Skip to content

result

Shared container of parameter results (NCAResult, FitResult): an xarray.Dataset over sample dimensions, units per variable, an integer flags variable, quantities, data frames and summaries.

ParameterResult

ParameterResult(ds)

Parameters of an analysis as an xarray.Dataset.

The dataset has one variable per parameter over the sample dimensions, an attrs["units"] on every variable and the integer variable flags. A parameter which does not apply to a sample is NaN. The analysis of group curves adds the derived variables of the uncertainty (x_se, x_ci_low, ...) and the number of subjects n; parameters lists the parameters themselves, derived_variables the derived ones, statistics the statistics of the analysis itself (statistic_variables, e.g. the goodness of fit of a curve fit) and point_variables the variables carrying an extra, non-sample dimension (such as predicted curves).

Wrap a result dataset.

Parameters:

Name Type Description Default
ds Dataset

dataset with a flags variable and attrs["units"] on every data variable.

required

Raises:

Type Description
ValueError

without a flags variable or without units on a variable.

sample_dims property

sample_dims

The sample dimensions.

point_variables property

point_variables

Names of the data-point variables (an extra dimension beyond the sample dims).

parameters property

parameters

Names of the parameters (the data variables except flags, n, the statistics, the status, the derived and the point variables).

status property

status

Names of the status variables present in the result (status_variables).

excluded property

excluded

The boolean excluded variable of the result, None without one.

A sample which is marked here is left out of summarize, summary_table, sample and every statistic which reads a result, unless include_excluded=True asks for it.

statistics property

statistics

Names of the statistics of the analysis present in the result (statistic_variables).

derived_variables property

derived_variables

Names of the uncertainty and summary variables (x_se, x_ci_low, ...).

has_uncertainty property

has_uncertainty

Whether any parameter carries a standard error.

units

units(name)

Unit string of a parameter.

Parameters:

Name Type Description Default
name str

name of the parameter.

required

Returns:

Type Description
str

The unit string of the parameter.

to_units

to_units(units)

Convert named variables of the result to other units.

The reporting units of a submission are not the units the data was measured in: an exposure in hour * nanogram / milliliter is reported as h*ng/mL, a clearance in liter / hour as mL/min. Every named variable is converted with pint, together with the variables derived from it, which carry the same quantity: the uncertainty and the summary variables (x_sd, x_se, x_ci_low, x_ci_high, x_geomean, x_median, x_min, ...) and the dose normalized variable (x_dn, which is converted per dose, so auc_inf_obs in h*ng/mL reports auc_inf_dn in h*ng/mL/mg). The dimensionless companions of a parameter (x_cv, x_geocv, x_n) are left as they are.

The values are multiplied by the conversion factor and attrs["units"] is rewritten with the canonical spelling of the target unit; the result is a new object, the one it was called on is unchanged. NCAOptions.units applies the conversion to the result of pkpdutils.nca.nca directly.

Parameters:

Name Type Description Default
units Mapping[str, str]

variable name to the unit to convert it to, e.g. {"auc_inf_obs": "h*ng/mL", "cl_f": "mL/min"}.

required

Returns:

Type Description
Self

The result with the named variables and their companions in the

Self

new units.

Raises:

Type Description
KeyError

if a name is not a variable of the result.

ValueError

if a unit is not a unit of the registry, or does not have the dimensionality of the variable.

decode_flags

decode_flags(value)

Names of the flags set in an integer flag value, in bit order.

Parameters:

Name Type Description Default
value int

an integer combination of flag_type values.

required

Returns:

Type Description
list[str]

The names of the set flags, in the declaration order of flag_type.

to_quantities

to_quantities(**indexers)

The scalar variables of one sample as pint quantities.

Parameters:

Name Type Description Default
**indexers Any

one label per sample dimension.

{}

Returns:

Type Description
dict[str, Quantity]

Variable name to quantity, for the parameters, the derived

dict[str, Quantity]

variables and n (every scalar data variable except flags).

Raises:

Type Description
ValueError

if the indexers do not name one label of every sample dimension.

sample

sample(
    name, dim=None, *, include_excluded=False, **indexers
)

A parameter as a ParameterSample for the statistics of pkpdutils.stats.

With dim, the individual values of name along dim, after the other sample dimensions were selected with indexers; the labels are the coordinate of dim and the coordinates along dim (period, sequence, ...) travel with the sample. Without dim, the summary statistics of a group result: x as the mean, x_sd (or x_se times the square root of n) as the standard deviation, x_n when present else n as the number of individuals, and x_geomean, x_geocv when present.

A sample which the result marks excluded (pkpdutils.nca.NCAResult.exclude) is left out, so that every statistic of pkpdutils.stats which reads a result reads the same individuals as the summary of it.

Every sample dimension besides dim takes one label, a value of its dimension coordinate (the position for a dimension without one). A coordinate along a sample dimension (period, sequence) is no indexer, it travels with the sample; a subset of the individuals is selected from the batch before the analysis (pkpdutils.timecourse.Timecourses.select).

Parameters:

Name Type Description Default
name str

name of the parameter.

required
dim str | None

the sample dimension the values run over, None for a summary sample.

None
include_excluded bool

read the excluded samples as well.

False
**indexers Any

one label per remaining sample dimension.

{}

Returns:

Type Description
ParameterSample

The sample.

Raises:

Type Description
ValueError

if name is not a variable, dim is not a sample dimension, the name of an indexer is not a sample dimension or is dim, an indexer is not one label of its dimension, a sample dimension besides dim is not indexed, or the summary sample has no group statistics.

flags

flags(**indexers)

Names of the flags set for one sample.

Parameters:

Name Type Description Default
**indexers Any

one label per sample dimension.

{}

Returns:

Type Description
list[str]

The names of the flags set for the sample.

Raises:

Type Description
ValueError

if the indexers do not name one label of every sample dimension.

rich_table

rich_table(
    *, parameters=None, digits=3, transpose=None, title=None
)

The result as a rich table for the console, the units in short symbols.

A result of a few samples is shown with one row per variable (name, unit, one column per sample), which fits a console; a result of many samples with one row per sample and one column per parameter, as to_dataframe lays it out. Every number is rounded to digits significant digits, the flags are written by name, and the frame of to_dataframe itself is unchanged and keeps the full precision.

Parameters:

Name Type Description Default
parameters Sequence[str] | None

the variables to show, in this order; by default every variable with one row per variable, and the headline parameters of the result type (console_parameters, every parameter if it names none) with one row per sample.

None
digits int

significant digits of the numbers.

3
transpose bool | None

one row per variable (True) or one row per sample (False); by default one row per variable up to eight samples.

None
title str | None

the title above the table; by default the type of the result, the number of samples and the sample dimensions.

None

Returns:

Type Description
Table

The table, built by pkpdutils.console.rich_table.

Raises:

Type Description
ValueError

if a name of parameters is not a variable of the result.

to_dataframe

to_dataframe()

One row per sample: the sample coordinates, every scalar variable and the decoded flags.

Every sample is a row, the excluded ones included, and the status variables of the result (status_variables: accepted, excluded and excluded_reason of an NCA) are columns between the parameters and the flags.

The point variables (the data and the predictions of a fit, the correlation matrix) are left out: they carry a dimension beyond the sample dimensions, and xarray.Dataset.to_dataframe of the whole dataset would repeat every sample once per point and per parameter pair. xarray.Dataset.to_dataframe also refuses a 0-dimensional dataset (no sample dimensions), so that case is built as a single-row frame directly.

Returns:

Type Description
DataFrame

The dataframe.

flag_table

flag_table()

One row per sample with a boolean column per flag.

Returns:

Type Description
DataFrame

The dataframe.

summary_table

summary_table(
    dim,
    *,
    by=None,
    parameters=None,
    stats=DEFAULT_STATISTICS,
    digits=3,
    units="column",
    unit_style="long",
    layout="parameters_rows",
    include_excluded=False,
)

The publication parameter table of this result, see pkpdutils.result.summary_table.

Parameters:

Name Type Description Default
dim str

the sample dimension the statistics are taken over.

required
by str | Sequence[str] | None

coordinate along dim to group the samples by, or several.

None
parameters Sequence[str] | None

the parameters of the table, every parameter of the result by default.

None
stats Sequence[str]

the statistics of the table, see pkpdutils.result.TABLE_STATISTICS.

DEFAULT_STATISTICS
digits int | Mapping[str, int]

significant digits of the numbers, one number for the whole table or one per parameter.

3
units Literal['column', 'header']

whether the unit is a column of its own or part of the parameter name.

'column'
unit_style Literal['long', 'short']

the long form of pint or its short symbols.

'long'
layout Literal['parameters_rows', 'parameters_columns', 'long']

parameters as rows, as columns, or one row per parameter, group and statistic.

'parameters_rows'
include_excluded bool

report the excluded samples as well.

False

Returns:

Type Description
DataFrame

The table, every cell a formatted string.

Raises:

Type Description
ValueError

as pkpdutils.result.summary_table.

summarize

summarize(dim, ci_level=0.95, *, include_excluded=False)

Summarize the parameters of individual samples over one sample dimension.

For every parameter x the summary carries the arithmetic mean x, x_sd, x_se, the coefficient of variation x_cv as a fraction, the t-based confidence interval x_ci_low/x_ci_high at ci_level, x_median, x_q25, x_q75, x_min, x_max, the count of finite values x_n and, for log-normal parameters (lognormal_parameters), x_geomean and x_geocv; flags is the union of the flags of the samples. pkpdutils.result.summary_table formats these numbers into the parameter table of a publication.

The derived and the statistic variables of the input are dropped: a statistic (statistic_variables, the goodness of fit and the counts of a fit) describes the analysis of one sample, not a quantity of which a mean over samples would mean anything, and is read from the unsummarized result. A point variable is dropped as well, unless it is listed in summarized_point_variables (the interval_* parameters of a multiple dose analysis), in which case it is reduced over dim like a parameter and keeps its extra dimension.

A discrete parameter (discrete_parameters: an observed time, a point count, a diagnostic of the terminal regression) carries no uncertainty: a standard error, a coefficient of variation or a confidence interval of a point count is not a quantity, so only x, x_median, x_q25, x_q75, x_min, x_max and x_n are reported for it, the same set the uncertainty of an analysis of group curves reports (pkpdutils.nca.uncertainty).

The two counts differ: n is the number of samples along dim, x_n the number of them at which x is finite, and every statistic of x uses x_n (x_se = x_sd / sqrt(x_n), the interval uses t with x_n - 1 degrees of freedom). A parameter which does not apply to every sample (no terminal phase, no dose) therefore has x_n < n.

A sample which the result marks excluded (pkpdutils.nca.NCAResult.exclude, Acceptance(exclude=True)) enters no statistic and is not counted, neither in n nor in x_n, and its flags are not part of the union; include_excluded=True summarizes every sample. The status variables themselves (status_variables) are dropped, as the derived and the statistic variables are.

Parameters:

Name Type Description Default
dim str

the sample dimension to reduce

required
ci_level float

level of the confidence interval of the mean

0.95
include_excluded bool

summarize the excluded samples as well

False

Returns:

Type Description
Self

The summary over the remaining sample dimensions.

Raises:

Type Description
ValueError

if dim is not a sample dimension of the result.

sample_coordinates

sample_coordinates(ds, sample_dims)

The coordinates of a dataset which live on the sample dimensions.

The dimension coordinates of the sample dimensions and every non-dimension coordinate along them (the period or the sequence of the individuals of a crossover study, the weight of the subjects) are carried from the analysed batch to its result, so that ParameterResult.sample finds them.

Parameters:

Name Type Description Default
ds Dataset

the dataset of the batch.

required
sample_dims Sequence[str]

the sample dimensions.

required

Returns:

Type Description
dict[str, DataArray]

Coordinate name to coordinate.

nan_percentile

nan_percentile(values, q, axis=-1)

Percentiles along one axis ignoring NaN, vectorized over the other axes.

Same result as numpy.nanpercentile(values, q, axis=axis) with the default linear interpolation, down to the last bit, but without its fallback to numpy.apply_along_axis, which is a python level loop over the reduced slices as soon as the array holds a single NaN. The slices are sorted instead (NaN sorts last), the finite count k of every slice gives the virtual index (k - 1) q / 100 and the two neighbouring order statistics are gathered and interpolated in one vectorized step, as numpy does for an array without NaN.

A slice without a single non-NaN value is NaN, without the RuntimeWarning numpy emits for it.

Parameters:

Name Type Description Default
values ndarray

the values; NaN is ignored, +-inf is an ordinary value, as in numpy.nanpercentile.

required
q float | Sequence[float]

percentile in [0, 100], or a sequence of them.

required
axis int

the axis to reduce.

-1

Returns:

Type Description
ndarray

The percentiles: the shape of values without axis for a single q,

ndarray

with the number of percentiles prepended for a sequence of them.

result_dimensions

result_dimensions(variables, sample_dims)

The dimensions the variables of a result add to its sample dimensions.

Every variable of a result lives over the sample dimensions of the analysed batch, and some of them over extra dimensions of their own: the point of the data and the parameter and parameter_ of the correlation matrix of a fit, the interval of the dosing intervals and the candidate of the terminal windows of an NCA. The extra dimensions are read from the layout the result is about to be built from, every dimension of a variable once its sample dimensions are taken out, so they follow the code which creates them. A sample dimension is taken out once per variable: a sample dimension named like an extra dimension (a batch over interval whose variables are laid out over (interval, interval)) leaves the second one behind, which is how such a collision shows.

Parameters:

Name Type Description Default
variables Mapping[str, Sequence[str]]

the dimensions of every data variable of the result, by name.

required
sample_dims Sequence[str]

the sample dimensions of the result.

required

Returns:

Type Description
set[str]

The names of the extra dimensions.

check_coordinate_collision

check_coordinate_collision(
    coords, variables, sample_dims=()
)

Raise if a name of the batch collides with a variable or a dimension of the result.

A result is built from the names of the batch, its sample dimensions and its coordinates along them (sample_coordinates), and from the names of the analysis, its data variables and the extra dimensions some of them carry (result_dimensions). A name on both sides breaks the result:

  • xr.Dataset and xr.DataArray refuse a name that is both a coordinate and a data variable (ValueError: variables {...} are found in both data_vars and coords), which a batch coordinate happening to be named n or after a parameter such as cmax would otherwise only surface as, deep inside the construction of the result;
  • a coordinate named like an extra dimension (parameter, point, interval) is silently replaced by the labels of that dimension, or stays along the sample dimensions under the name of another dimension, which xarray accepts and later operations trip over;
  • a sample dimension named like an extra dimension repeats that dimension in the variables which carry it, a result whose labels are silently wrong or an opaque conflicting sizes error of xarray;
  • a data variable named like an extra dimension is silently turned into a coordinate of the dimension it is named after.

Calling this before the result is built turns every case into a clear message which names what to rename. The extra dimensions are derived from variables, so the check covers every dimension the result introduces without a list of them to keep in step.

Parameters:

Name Type Description Default
coords Mapping[str, Any]

the coordinates of the batch that are about to be attached to the result, the coordinates of the sample dimensions included.

required
variables Mapping[str, Sequence[str]]

the dimensions of every data variable of the result, by name.

required
sample_dims Sequence[str]

the sample dimensions of the result.

()

Raises:

Type Description
ValueError

if a sample dimension, a coordinate of the batch or a variable of the result shares its name with a variable or with an extra dimension of the result.

decode_flags

decode_flags(flag_type, value)

Names of the flags set in an integer flag value, in bit order.

Parameters:

Name Type Description Default
flag_type type[IntFlag]

the IntFlag type the value belongs to.

required
value int

an integer combination of its members.

required

Returns:

Type Description
list[str]

The names of the set flags, in the declaration order of flag_type;

list[str]

the zero member and unnamed members are left out.

format_number

format_number(value, digits=3)

A number rounded to significant digits, without an exponent where one is not needed.

The shared formatting of the publication tables (pkpdutils.result.summary_table, pkpdutils.stats.ratio_table, pkpdutils.stats.ddi_table, pkpdutils.fit.proportionality_table): the value is rounded to digits significant digits and written in plain notation while its exponent lies in [-4, digits + 3), the range in which the plain form is no longer than the scientific one, and in scientific notation outside it.

Parameters:

Name Type Description Default
value float

the number; NaN and None give an empty cell.

required
digits int

significant digits.

3

Returns:

Type Description
str

The formatted number; "" for a missing value.

Raises:

Type Description
ValueError

if digits is not positive.

base_name

base_name(name)

The parameter a derived variable belongs to, None for a parameter itself.

Parameters:

Name Type Description Default
name str

name of a result variable, e.g. "auc_last_se".

required

Returns:

Type Description
str | None

The name of the parameter the variable is derived from, None for a

str | None

parameter.

summary_table

summary_table(
    result,
    dim,
    *,
    by=None,
    parameters=None,
    stats=DEFAULT_STATISTICS,
    digits=3,
    units="column",
    unit_style="long",
    layout="parameters_rows",
    include_excluded=False,
)

The parameter table of a publication: one row per parameter, formatted.

The statistics are those of ParameterResult.summarize(dim), read from the summary and formatted with digits significant digits as strings, so that the frame goes into a manuscript (to_csv, to_markdown, to_latex) without further rounding. cv and geocv are fractions in the summary and are written as percentages ("12.3 %"); range is the two order statistics in one cell ("10.2 - 14.8"); a statistic a parameter does not carry (the sd of a discrete parameter, the geomean of a parameter which is not log-normal) is an empty cell. The flags are not part of the table, ParameterResult.flag_table reports them.

The convention of the pharmacokinetic literature, "geometric mean [CV %]", is stats=("n", "geomean", "geocv"); the arithmetic convention "mean (SD)" is stats=("n", "mean", "sd").

Parameters:

Name Type Description Default
result ParameterResult

the result of the individual samples (not a summary).

required
dim str

the sample dimension the statistics are taken over, e.g. "individual".

required
by str | Sequence[str] | None

coordinate along dim to group the samples by (the dose group, the treatment), or several of them; one group of everything by default.

None
parameters Sequence[str] | None

the parameters of the table, in this order; every parameter of the result by default.

None
stats Sequence[str]

the statistics, in this order, see TABLE_STATISTICS.

DEFAULT_STATISTICS
digits int | Mapping[str, int]

significant digits of the numbers, one number for the whole table or a mapping of parameter name to its own number, in which case a parameter the mapping does not name keeps the default 3 ({"tmax": 1} writes the time of the maximum with one digit and every other parameter with three).

3
units Literal['column', 'header']

"column" gives the unit a column of its own (a row in the "parameters_columns" layout), "header" appends it to the parameter name ("cmax [milligram / liter]").

'column'
unit_style Literal['long', 'short']

"long" writes the unit as the result stores it, the canonical long form of pint (milligram / liter); "short" writes its short symbols (mg/l, pkpdutils.units.short_unit), the form a manuscript prints.

'long'
layout Literal['parameters_rows', 'parameters_columns', 'long']

"parameters_rows" (one row per parameter and group, one column per statistic), "parameters_columns" (the transpose: one column per parameter, one row per statistic and group) or "long" (one row per parameter, group and statistic).

'parameters_rows'
include_excluded bool

report the excluded samples as well; by default a sample which the result marks excluded (pkpdutils.nca.NCAResult.exclude) enters no statistic of the table and is not counted in n.

False

Returns:

Type Description
DataFrame

The table, every cell a string.

Raises:

Type Description
ValueError

if dim is not a sample dimension, a parameter is not a variable of the result, a statistic is unknown, units, unit_style or layout is not one of the values above, or a coordinate of by or another sample dimension is named like a column the table writes itself (parameter, unit, statistic, value or a statistic).