ResidualErrorModel

Enum ResidualErrorModel 

pub enum ResidualErrorModel {
    Constant {
        a: f64,
    },
    Proportional {
        b: f64,
    },
    Combined {
        a: f64,
        b: f64,
    },
    Exponential {
        sigma: f64,
    },
}
Expand description

Residual error model for parametric estimation algorithms.

Unlike crate::ErrorModel which uses observations, this uses the model prediction to compute the standard deviation.

§Usage in SAEM

The error model affects:

  1. Likelihood computation in E-step: L(y|f) = N(y; f, σ²)
  2. Residual weighting in M-step: weighted_res² = (y-f)²/σ²

§Examples

use pharmsol::ResidualErrorModel;

// Constant (additive) error: σ = 0.5
let constant = ResidualErrorModel::Constant { a: 0.5 };
assert!((constant.sigma(100.0) - 0.5).abs() < 1e-10);

// Proportional error: σ = 0.1 * |f|
let proportional = ResidualErrorModel::Proportional { b: 0.1 };
assert!((proportional.sigma(100.0) - 10.0).abs() < 1e-10);

// Combined error: σ = sqrt(0.5² + 0.1² * f²)
let combined = ResidualErrorModel::Combined { a: 0.5, b: 0.1 };
// For f=100: σ = sqrt(0.25 + 100) = sqrt(100.25) ≈ 10.01

Variants§

§

Constant

Constant (additive) error model

σ = a

Error is independent of the predicted value. Appropriate when measurement error is constant regardless of concentration.

Fields

§a: f64

Additive error standard deviation

§

Proportional

Proportional error model

σ = b * |f|

Error scales linearly with the prediction. Appropriate when measurement error is a constant percentage of the value.

Note: Uses |f| to handle negative predictions gracefully.

Fields

§b: f64

Proportional coefficient (e.g., 0.1 = 10% CV)

§

Combined

Combined (additive + proportional) error model

σ = sqrt(a² + b² * f²)

This is the standard saemix error model from func_aux.R:

g <- cutoff(sqrt(ab[1]^2 + ab[2]^2 * f^2))

The combined model:

  • Dominates at low concentrations (a term)
  • Scales proportionally at high concentrations (b term)

Fields

§a: f64

Additive component (a)

§b: f64

Proportional component (b)

§

Exponential

Exponential error model (for log-transformed data)

σ = σ_exp (constant on log scale)

When data is analyzed on the log scale:

log(Y) = log(f) + ε, where ε ~ N(0, σ²)

This corresponds to multiplicative error on the original scale.

Fields

§sigma: f64

Error standard deviation on log scale

Implementations§

§

impl ResidualErrorModel

pub fn constant(a: f64) -> ResidualErrorModel

Create a constant (additive) error model

§Arguments
  • a - Standard deviation (must be positive)

pub fn proportional(b: f64) -> ResidualErrorModel

Create a proportional error model

§Arguments
  • b - Proportional coefficient (e.g., 0.1 for 10% CV)

pub fn combined(a: f64, b: f64) -> ResidualErrorModel

Create a combined (additive + proportional) error model

§Arguments
  • a - Additive component
  • b - Proportional component

pub fn exponential(sigma: f64) -> ResidualErrorModel

Create an exponential error model

§Arguments
  • sigma - Standard deviation on log scale

pub fn sigma(&self, prediction: f64) -> f64

Compute sigma (standard deviation) for a given prediction

§Arguments
  • prediction - The model prediction (f)
§Returns

The standard deviation σ at this prediction value. Returns a cutoff minimum to avoid numerical issues with very small σ.

pub fn variance(&self, prediction: f64) -> f64

Compute variance for a given prediction

§Arguments
  • prediction - The model prediction (f)
§Returns

The variance σ² at this prediction value.

pub fn weighted_squared_residual( &self, observation: f64, prediction: f64, ) -> f64

Compute the weighted residual for M-step sigma updates

For the M-step in SAEM, we compute the normalized residual:

  • For constant/additive: (y - f)² (unweighted)
  • For proportional: (y - f)² / f² (weighted by prediction)
  • For combined: (y - f)² / (a² + b²*f²) (using current sigma params)

This matches R saemix’s approach in main_mstep.R where for proportional error: resk <- sum((yobs - fk)**2 / cutoff(fk**2, .Machine$double.eps))

§Arguments
  • observation - The observed value (y)
  • prediction - The model prediction (f)
§Returns

The weighted squared residual for sigma estimation.

pub fn log_likelihood(&self, observation: f64, prediction: f64) -> f64

Compute log-likelihood contribution for a single observation

Assuming normal distribution:

log L(y|f,σ) = -0.5 * [log(2π) + log(σ²) + (y-f)²/σ²]
§Arguments
  • observation - The observed value (y)
  • prediction - The model prediction (f)
§Returns

The log-likelihood contribution.

pub fn with_updated_sigma(self, new_sigma: f64) -> ResidualErrorModel

Update the error model parameters based on M-step sufficient statistics

In SAEM, the residual error is estimated in the M-step. This method updates the appropriate parameter based on the new estimate.

§Arguments
  • new_sigma - The new sigma estimate from M-step
§Returns

A new error model with updated parameters.

pub fn primary_parameter(&self) -> f64

Get the primary sigma parameter value

For Constant: returns a For Proportional: returns b For Combined: returns a (additive component) For Exponential: returns sigma

pub fn is_proportional(&self) -> bool

Check if this is a proportional error model

pub fn is_constant(&self) -> bool

Check if this is a constant (additive) error model

pub fn is_combined(&self) -> bool

Check if this is a combined error model

pub fn is_exponential(&self) -> bool

Check if this is an exponential error model

Trait Implementations§

§

impl Clone for ResidualErrorModel

§

fn clone(&self) -> ResidualErrorModel

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for ResidualErrorModel

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Default for ResidualErrorModel

§

fn default() -> ResidualErrorModel

Returns the “default value” for a type. Read more
§

impl<'de> Deserialize<'de> for ResidualErrorModel

§

fn deserialize<__D>( __deserializer: __D, ) -> Result<ResidualErrorModel, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
§

impl PartialEq for ResidualErrorModel

§

fn eq(&self, other: &ResidualErrorModel) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

impl Serialize for ResidualErrorModel

§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
§

impl Copy for ResidualErrorModel

§

impl StructuralPartialEq for ResidualErrorModel

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> ByRef<T> for T

§

fn by_ref(&self) -> &T

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<T> Context for T
where T: Clone + Default,

§

fn vector_from_element<V>(&self, len: usize, value: <V as VectorCommon>::T) -> V
where V: Vector<C = Self>,

§

fn vector_from_vec<V>(&self, vec: Vec<<V as VectorCommon>::T>) -> V
where V: Vector<C = Self>,

§

fn vector_zeros<V>(&self, len: usize) -> V
where V: Vector<C = Self>,

§

fn dense_mat_zeros<V>( &self, rows: usize, cols: usize, ) -> <V as DefaultDenseMatrix>::M
where V: Vector<C = Self> + DefaultDenseMatrix,

§

impl<T> DistributionExt for T
where T: ?Sized,

§

fn rand<T>(&self, rng: &mut (impl Rng + ?Sized)) -> T
where Self: Distribution<T>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> Boilerplate for T
where T: Copy + Send + Sync + Debug + PartialEq + 'static,

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> Scalar for T
where T: 'static + Clone + PartialEq + Debug,

Source§

impl<T> Scalar for T
where T: 'static + Clone + PartialEq + Debug,

§

impl<T> SendAlias for T

§

impl<T> SyncAlias for T