Skip to contents

This function calculates the cost for fitting either a linear or parabolic model to a segment of the melatonin profile. The objective minimizes the residual error while ensuring the fit adheres to predefined constraints.

Usage

objective_function(
  params,
  x,
  y,
  poi,
  fit_type,
  slope_bounds,
  base_id,
  region,
  weight_base,
  threshold = threshold
)

Arguments

params

Numeric vector of parameters to optimize:

  • If fit_type == "linear", params[1] is the slope (m).

  • If fit_type == "parabolic", params[1:2] represent coefficients (a, b), and c is computed.

x

Numeric vector of x-coordinates (time points in decimal format).

y

Numeric vector of y-coordinates (melatonin concentrations).

poi

List containing:

  • x: x-coordinate of the Point of Interest (POI).

  • y: y-coordinate of the POI.

fit_type

Character. Either "linear" or "parabolic" to specify the fitting model.

slope_bounds

Numeric vector of length 2 defining the allowed slope range.

base_id

Numeric vector indicating which points belong to the base segment (1 = base, 0 = ascending).

region

Character. Either "base" or "ascending" to specify the segment being fitted.

weight_base

Logical. If TRUE, assigns a lower weight to base points in the residual computation.

threshold

Numeric. Upper bound constraint for base fitting. Default is threshold.

Value

Numeric value representing the total cost (sum of squared residuals and constraint penalties).

Details

  • The function supports both linear and parabolic fits.

  • The base_constraint function penalizes fits that exceed the threshold in the base region.

  • The nl_constraints function ensures that parabolic fits maintain an increasing slope.

  • The poi_constraints function ensures that the fit slope at the POI stays within the given bounds.

  • Weighted residuals are applied to emphasize ascending points in parabolic fitting.

Examples

x <- c(0, 1, 2, 3, 4)
y <- c(0.5, 1.0, 2.0, 3.5, 5.0)
poi <- list(x = 2, y = 2.0)
params <- c(1.5)  # Linear slope example
slope_bounds <- c(-2, 2)
objective_function(params, x, y, poi, "linear", slope_bounds, base_id = c(1,1,0,0,0), "ascending", weight_base = TRUE)
#> [1] 0.125