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_constraintfunction penalizes fits that exceed the threshold in the base region.The
nl_constraintsfunction ensures that parabolic fits maintain an increasing slope.The
poi_constraintsfunction ensures that the fit slope at the POI stays within the given bounds.Weighted residuals are applied to emphasize ascending points in parabolic fitting.