# Class CalculatedObservations

Namespace
  adas_core.Application.Customizations.H12O.UCIN

Assembly
  adas-core.Application.dll

Implements the UCIN-specific clinical calculations that derive secondary PatientObservation values (Complexity, Oxygenation_Index, Respiratory, IntravenousLines, Medication, ERMedication, Monitor, Surgery, Temp_Gradient, TAm alert, etc.) from incoming raw observations and active PatientTreatment entries, using the catalogue of codes, groups, and types configured in ApiSettings.

    public class CalculatedObservations : ICalculatedObservations

Inheritance
  object
  CalculatedObservations

Implements
  ICalculatedObservations

Inherited Members
  object.Equals(object)
  object.Equals(object, object)
  object.GetHashCode()
  object.GetType()
  object.MemberwiseClone()
  object.ReferenceEquals(object, object)
  object.ToString()

Extension Methods
  NumberUtils.IsNumber(object)
  NumberUtils.ToDouble(object)
  ObjectUtils.ToStr(object?)

## Constructors

### CalculatedObservations(IServiceProvider)

Initializes a new instance of the CalculatedObservations class, resolving its dependencies (observation, medicine, and treatment services, plus the logger) from the supplied IServiceProvider and loading the configured code catalogues (EEG, bolus medications, transcutaneous, regional brain saturation, surgery, respiratory, ONi, ventilation modes, ECMO, and notes indicating medication) from ApiSettings.

    public CalculatedObservations(IServiceProvider serviceProvider)

#### Parameters

`serviceProvider` IServiceProvider

  The application's service provider used to resolve the required dependencies and configuration.

## Methods

### CalculateActiveBolus(ObjectId)

Recalculates the "OpiateBoluses" observation for a patient based on the bolus treatments returned by `GetActiveBolus`. Skips persistence when the value is unchanged from the last stored observation.

    public Task CalculateActiveBolus(ObjectId patientId)

#### Parameters

`patientId` ObjectId

  The unique identifier of the patient.

#### Returns

Task

  A task that represents the asynchronous calculation operation.

### CalculateAsistResp(BasePatientObservation)

Calculates the patient's respiratory assistance score from the supplied observation's `Value` (matched against the configured respiratory-type catalogue) or from the latest stored `Resp_Mode` when the supplied observation is `ONi`. Active ONi treatment (or a non-expired last ONi observation) forces the score to 10. Persists the resulting `Respiratory` observation and returns the original input unchanged.

    public Task<BasePatientObservation> CalculateAsistResp(BasePatientObservation obs)

#### Parameters

`obs` BasePatientObservation

  The base patient observation that triggered the calculation (expected to be a PatientObservation).

#### Returns

Task<BasePatientObservation>

  A task that resolves to the same base patient observation that was passed in.

### CalculateComplexity(BasePatientObservation, bool)

Recalculates the patient's overall `Complexity` observation from scratch using the latest values for the configured complexity-contributing observations (weight, medication, surgery, intravenous lines, monitor, and respiratory), the active ECMO treatment state, and the optionally supplied `obs` which is preferred over the database value when it is newer and not expired. The result is persisted only when its integer value differs from the last stored complexity observation, with time inconsistencies resolved via `FixTimeInconsistencyWithLast`. Returns the original observation unchanged.

    public Task<BasePatientObservation> CalculateComplexity(BasePatientObservation obs, bool ignoreObs = false)

#### Parameters

`obs` BasePatientObservation

  The base patient observation that triggered the recalculation.

`ignoreObs` bool

  When true, the supplied `obs` is not added to the calculation inputs (useful for synthetic observations like ECMO).

#### Returns

Task<BasePatientObservation>

  A task that resolves to the same base patient observation that was passed in.

### CalculateIntravenousLineObservation(BasePatientObservation)

Recomputes the `IntravenousLines` complexity score by reconciling the incoming `IntravenousLinesObs` against the patient's active intravenous lines. Detects and corrects common ICCA mis-clicks (inserts incorrectly carrying a remove time), updates an existing line in place when only the duration changed, and otherwise adds the new line to the active set. The aggregated score is capped at 10 and persisted with bounds [0, 10]. `InvalidCastException`s are logged and swallowed.

    public Task<BasePatientObservation?> CalculateIntravenousLineObservation(BasePatientObservation obs)

#### Parameters

`obs` BasePatientObservation

  The base patient observation that triggered the calculation (expected to be a PatientObservation whose `Value` is a PatientIntravenousLinesValue).

#### Returns

Task<BasePatientObservation>

  A task that resolves to the original base patient observation when processing succeeds or fails gracefully with logging; resolves to null when the function returns early because the incoming observation is a duplicate insert (in which case the caller should not overwrite the stored observation).

### CalculateMedicineObservation(List<Medicine>, ObjectId)

Convenience overload that recalculates the "Medication" and "ERMedication" observations for a patient using the supplied list of active medicines, building a transient PatientTreatment for the underlying call.

    public Task CalculateMedicineObservation(List<Medicine> activeMedicines, ObjectId patientId)

#### Parameters

`activeMedicines` List<Medicine>

  The list of active Medicine instances currently associated with the patient.

`patientId` ObjectId

  The unique identifier of the patient.

#### Returns

Task

  A task that represents the asynchronous calculation operation.

### CalculateMedicineObservation(List<Medicine>, List<Medicine>, PatientTreatment)

Maintains the patient's active medicine list according to the treatment's `OrderControl` (`NW` adds, `XO` adds if missing, `DC` removes), counts the distinct medicine types, persists the `Medication` observation if its value changed, and then recalculates the `ERMedication` observation.

    public Task CalculateMedicineObservation(List<Medicine> activeMedicines, List<Medicine> medicines, PatientTreatment treatment)

#### Parameters

`activeMedicines` List<Medicine>

  The list of active medicines for the patient. Modified in-place.

`medicines` List<Medicine>

  The medicines to add or remove depending on `OrderControl`.

`treatment` PatientTreatment

  The treatment that triggered the recalculation.

#### Returns

Task

  A task that represents the asynchronous calculation operation.

### CalculateMonitor(object)

Recalculates the `Monitor` observation by adding 1 point for each active transcutaneous / regional-brain-saturation / EEG monitoring signal (codes from the configured catalogues) found in the most recent observations and active treatments. Persists the resulting observation with bounds [0, 3]. Returns early with a warning when no recent monitor observations are found.

    public Task CalculateMonitor(object monitorObservation)

#### Parameters

`monitorObservation` object

  The trigger for the calculation. Accepts either a PatientObservation (preferred when available) or a PatientTreatment. The patient identifier is derived from whichever type is supplied.

#### Returns

Task

  A task that represents the asynchronous calculation operation.

### CalculateOxygenationIndex(BasePatientObservation)

Computes the Oxygenation Index (PMAP × FiO2 × 100 / PaO2) using the supplied observation plus the latest stored `AirPressure_Mean`, `FiO2`, and `PaO2` values. Persists the resulting `Oxygenation_Index` observation with a 10-second expiration matching FiO2's expiration window. Skipped gracefully when PaO2 is zero, when any of the inputs cannot be parsed, or when an exception is caught and logged.

    public Task CalculateOxygenationIndex(BasePatientObservation obs)

#### Parameters

`obs` BasePatientObservation

  The observation that triggered the calculation (one of `AirPressure_Mean`, `FiO2`, or `PaO2`).

#### Returns

Task

  A task that represents the asynchronous calculation operation.

### CalculateTAmAlert(BasePatientObservation)

Applies the red-alert rule for mean arterial pressure (TAm) in neonates: when TAm is below the patient's gestational age (in weeks) for the first week, or below the fixed gestational age thereafter, the `TAm` observation's `Status` is set to `Alert`; otherwise it is set to `Ok`. If the supplied observation is a gestational-age value (not TAm), a fresh TAm observation is re-inserted with the recalculated status. The threshold is read from the latest `Age_Gestational` observation when its value is below 2 weeks, otherwise from the latest `Age_Gestational_Fixed`.

    public Task CalculateTAmAlert(BasePatientObservation obs)

#### Parameters

`obs` BasePatientObservation

  The base patient observation that triggered the alert evaluation (`TAm`, `Age_Gestational`, or `Age_Gestational_Fixed`).

#### Returns

Task

  A task that represents the asynchronous calculation operation.

### CalculateTempGradient(BasePatientObservation)

Computes the temperature gradient between the incubator and the patient (incubator − patient) when both temperatures have been observed within 10 minutes of each other. Persists the `Temp_Gradient` observation with the resulting value, after shifting its timestamp via `CheckObsWithSameTimeExistsAndIncrementTime` to avoid colliding with a previous gradient observation. Returns early when the companion temperature is missing or the two readings fall outside the 10-minute window.

    public Task CalculateTempGradient(BasePatientObservation obs)

#### Parameters

`obs` BasePatientObservation

  The base patient observation that triggered the calculation (`Temp_Patient` or `Temp_Incubator`).

#### Returns

Task

  A task that represents the asynchronous calculation operation.

### CalculateVentilationMode(BasePatientObservation)

Maps a `Resp_Mode` observation's value to a discrete `Resp_Type` (HighFrequencyVentilation, Invasive, NonInvasive, or None) by matching it against the configured catalogues for each mode.

    public Task CalculateVentilationMode(BasePatientObservation obs)

#### Parameters

`obs` BasePatientObservation

  The respiratory-mode observation expected to be a PatientObservation.

#### Returns

Task

  A task that represents the asynchronous insert operation.

### CheckObsExistsAndIncrementTime(BasePatientObservation)

For hourly accumulation observations, checks whether another observation with the same name already exists within the same hour and, if so, shifts this observation's `Time` forward by one second so the system can identify the most recent entry.

    public Task<BasePatientObservation> CheckObsExistsAndIncrementTime(BasePatientObservation obs)

#### Parameters

`obs` BasePatientObservation

  The base patient observation expected to be a PatientObservation.

#### Returns

Task<BasePatientObservation>

  A task that represents the asynchronous operation. The task result contains the (possibly time-shifted) base patient observation.

### CheckObsWithSameTimeExistsAndIncrementTime(BasePatientObservation)

For temperature observations, checks whether another observation with the same name already exists at the exact same timestamp and, if so, shifts this observation's `Time` forward by one second so the system can identify the most recent entry.

    public Task<BasePatientObservation> CheckObsWithSameTimeExistsAndIncrementTime(BasePatientObservation obs)

#### Parameters

`obs` BasePatientObservation

  The base patient observation expected to be a PatientObservation.

#### Returns

Task<BasePatientObservation>

  A task that represents the asynchronous operation. The task result contains the (possibly time-shifted) base patient observation.

### CheckSurgeryExpired(BasePatientObservation)

When a "Surgery" observation is marked as expired, inserts a follow-up "Surgery" observation with value `0` at the same time plus one second, signaling that the surgery complexity contribution has been removed. Errors are logged and rethrown.

    public Task CheckSurgeryExpired(BasePatientObservation obs)

#### Parameters

`obs` BasePatientObservation

  The base patient observation expected to be a PatientObservation with `Name == "Surgery"`.

#### Returns

Task

  A task that represents the asynchronous insert operation.

#### Exceptions

InvalidCastException

  Thrown when `obs` cannot be cast to PatientObservation.

Exception

  Rethrown after the underlying exception is written to the console for diagnostics.

### CheckTreatmentMedicines(PatientTreatment)

Resolves the medicines associated with a treatment (by matching its codes and notes against the medicine catalogue, falling back to `NotesIndicatingMedication` patterns), aggregates the patient's active treatments and medicines, detects parenteral nutrition (NPT) treatments, and triggers `CalculateMedicineObservation` to update the Medication and ERMedication observations.

    public Task CheckTreatmentMedicines(PatientTreatment treatment)

#### Parameters

`treatment` PatientTreatment

  The treatment whose medicines should be checked.

#### Returns

Task

  A task that represents the asynchronous check operation.

### FixTimeInconsistencyWithLast(PatientObservation)

Resolves time-inconsistencies for a new patient observation when it arrives with the same (down-to-the-second) timestamp as the latest stored observation of the same name. The new observation's `Time` is shifted forward by one second, and a fresh MongoDB.Bson.ObjectId is generated to avoid duplicate-key collisions.

    public Task<PatientObservation?> FixTimeInconsistencyWithLast(PatientObservation newObservation)

#### Parameters

`newObservation` PatientObservation

  The new patient observation to evaluate for time inconsistencies.

#### Returns

Task<PatientObservation>

  A task that represents the asynchronous operation. The task result contains the fixed PatientObservation if the input had a valid name; otherwise, null.

### GetActiveTreatmentsByPatient(ObjectId)

Retrieves all treatments currently considered active for the specified patient, delegating the actual retrieval to the configured ITreatmentService.

    public Task<IEnumerable<PatientTreatment?>> GetActiveTreatmentsByPatient(ObjectId id)

#### Parameters

`id` ObjectId

  The unique identifier of the patient.

#### Returns

Task<IEnumerable<PatientTreatment>>

  A collection of active PatientTreatment objects for the patient.

### Map(PatientDiagnosis)

Identity mapping for a PatientDiagnosis: returns the supplied instance unchanged, wrapped in a completed task. Provided to satisfy the customization contract; diagnoses do not currently require UCIN-specific calculation.

    public Task<PatientDiagnosis> Map(PatientDiagnosis diagnosis)

#### Parameters

`diagnosis` PatientDiagnosis

  The PatientDiagnosis to map.

#### Returns

Task<PatientDiagnosis>

  A task containing the same PatientDiagnosis instance that was passed in.

### Map(PatientTreatment)

Maps a PatientTreatment to its processed form, computing the end time of single-dose treatments, evaluating the medicines associated with the treatment's codes/notes, and dispatching the appropriate downstream calculations (bolus, monitor, surgery, ECMO complexity, and ONi observations) based on the configured code catalogues.

    public Task<PatientTreatment> Map(PatientTreatment treatment)

#### Parameters

`treatment` PatientTreatment

  The PatientTreatment to be mapped.

#### Returns

Task<PatientTreatment>

  A task that represents the asynchronous mapping operation. The task result contains the processed PatientTreatment.

#### Exceptions

ArgumentNullException

  Thrown when the `treatment` parameter is `null`.

### Map(PumpObservation)

Identity mapping for a PumpObservation: returns the supplied instance unchanged, wrapped in a completed task. Provided to satisfy the customization contract; pump observations do not currently require UCIN-specific calculation.

    public Task<PumpObservation> Map(PumpObservation pumpObservation)

#### Parameters

`pumpObservation` PumpObservation

  The pump observation to map.

#### Returns

Task<PumpObservation>

  A task containing the same PumpObservation instance that was passed in.

### MapSourceAlarm(PatientObservation, PatientObservationAlarm)

Identity mapping for a source alarm observation paired with a PatientObservationAlarm: returns the supplied observation unchanged, wrapped in a completed task. Provided to satisfy the customization contract; alarms are not currently transformed in the UCIN customization.

    public Task<PatientObservation> MapSourceAlarm(PatientObservation obs, PatientObservationAlarm alarmToInsert)

#### Parameters

`obs` PatientObservation

  The patient observation that triggered the alarm.

`alarmToInsert` PatientObservationAlarm

  The alarm metadata to be inserted alongside the observation.

#### Returns

Task<PatientObservation>

  A task containing the same PatientObservation instance that was passed in.

### Map<T>(T, bool)

Applies the appropriate clinical calculations to a raw patient observation based on its Name, code, coding system, and expiration state, producing derived observations (respiratory assistance, oxygenation index, ventilation mode, TAm alert, parsed weight, temperature gradient, intravenous lines, monitor, surgery expiration, complexity, and hourly/temperature time-increment handling).

    public Task<T?> Map<T>(T obs, bool onlyByName) where T : BasePatientObservation

#### Parameters

`obs` T

  The observation to map or transform in-place.

`onlyByName` bool

  Reserved for future use. When true, restricts the mapping strategy to name-based lookups only.

#### Returns

Task<T>

  A Task<TResult> that resolves to the (possibly transformed) observation, or null when the input observation has no name.

#### Type Parameters

`T`

  The concrete observation type, deriving from BasePatientObservation.

### ParseWeight(BasePatientObservation)

Converts a weight observation expressed in kilograms to grams in-place (updates `Units` to `"gr"` and multiplies `Value` by 1000). Returns the observation unchanged when it is not a PatientObservation or when its value cannot be parsed; the error is also logged.

    public Task<BasePatientObservation> ParseWeight(BasePatientObservation obs)

#### Parameters

`obs` BasePatientObservation

  The base patient observation expected to be a PatientObservation with a numeric value.

#### Returns

Task<BasePatientObservation>

  A task that resolves to the (possibly converted) base patient observation.

### PreMapList(List<PatientObservation>)

Identity mapping for a list of PatientObservation instances: returns the supplied list unchanged, wrapped in a completed task. Provided to satisfy the customization contract; the pre-mapping phase does not currently require UCIN-specific transformation.

    public Task<List<PatientObservation>> PreMapList(List<PatientObservation> listToInsert)

#### Parameters

`listToInsert` List<PatientObservation>

  The list of patient observations to be pre-mapped.

#### Returns

Task<List<PatientObservation>>

  A task containing the original list of patient observations.

### SendAlarm(PatientObservation, string, Name?)

Placeholder alarm dispatch hook used by the customization contract. The UCIN customization does not currently implement custom alarm dispatching; calling this method always throws.

    public Task SendAlarm(PatientObservation obs, string name, AlarmEnum.Name? code)

#### Parameters

`obs` PatientObservation

  The patient observation that triggered the alarm.

`name` string

  The alarm display name.

`code` AlarmEnum.Name?

  The optional alarm code from AlarmEnum.Name.

#### Returns

Task

  Never returns a result.

#### Exceptions

NotImplementedException

  Always thrown because alarm dispatch is not implemented in the UCIN customization.