Spaces:
Sleeping

File size: 7,454 Bytes
5c71581
4b88607
 
 
5c71581
4b88607
 
 
 
 
 
 
 
 
 
 
 
0d71fef
4b88607
0d71fef
 
 
 
 
 
 
4b88607
 
 
 
 
 
 
 
 
 
 
 
f0291f1
4b88607
0d71fef
 
4b88607
0d71fef
 
4b88607
2930d06
4b88607
 
 
f0291f1
2930d06
f0291f1
 
2930d06
 
9c18a37
2930d06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d71fef
 
 
 
2930d06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b88607
5c71581
ac2fbc4
5c71581
 
ac2fbc4
 
5453539
 
 
 
 
 
 
 
 
 
 
5c71581
ac2fbc4
0d71fef
 
524a1a3
 
4b88607
 
5680df7
4b88607
 
 
 
 
 
f0bd3c1
 
 
ac2fbc4
 
 
 
 
 
 
 
 
 
 
 
 
4b88607
ac2fbc4
 
f0bd3c1
5c71581
 
 
 
 
f0bd3c1
 
 
 
ac2fbc4
f0bd3c1
ac2fbc4
 
 
 
 
4b88607
 
ac2fbc4
 
 
 
 
 
 
 
1b19ca4
 
4b88607
 
5680df7
5c71581
 
 
 
 
5680df7
4b88607
f0bd3c1
4b88607
5680df7
 
4b88607
 
 
5680df7
4b88607
 
 
 
 
5680df7
4b88607
9c18a37
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# VERSION: 2.4 - Fixed equil2 parameter names (2025-10-01)
library(dplyr)
library(tidyr)
library(purrr)
library(units)

MW <- list(
  Ca = 40.078, Mg = 24.305, Na = 22.990, K = 39.098, NH4 = 18.039,
  Cl = 35.453, PO4 = 94.9714, SO4 = 96.06, Ox = 88.019,
  Citr = 192.124, Urate = 168.11
)

mgL_to_mmolL <- function(mgL_values, molecular_weight) {
  mgL_values / molecular_weight
}

normalize_records_to_df <- function(records) {
  df_raw <- jsonlite::fromJSON(
    jsonlite::toJSON(records, auto_unbox = TRUE), 
    simplifyVector = TRUE,
    simplifyDataFrame = FALSE
  )
  df <- as.data.frame(df_raw, stringsAsFactors = FALSE)
  for (col in names(df)) {
    df[[col]] <- as.numeric(unlist(df[[col]]))
  }
  return(df)
}

convert_and_validate <- function(df) {
  df <- df |> dplyr::rename_with(~gsub("\\s+", "", .x))
  
  required_cols <- c("Na_mmolL", "K_mmolL", "NH4_mmolL", "Cl_mmolL", "SO4_mmolL", "pH")
  missing_required <- setdiff(required_cols, colnames(df))
  if (length(missing_required) > 0) {
    stop(paste("Missing required columns:", paste(missing_required, collapse = ", ")))
  }
  
  convert_with_fallback <- function(df, col_mmol, col_mg, mw, min_value = 0) {
    if (col_mmol %in% names(df)) {
      vals <- as.numeric(unlist(df[[col_mmol]]))
      return(pmax(vals, min_value))
    } else if (col_mg %in% names(df)) {
      vals <- as.numeric(unlist(df[[col_mg]]))
      return(pmax(mgL_to_mmolL(vals, mw), min_value))
    } else {
      return(rep(min_value, nrow(df)))
    }
  }
  
  ca_values <- convert_with_fallback(df, "Ca_mmolL", "Ca_mgL", MW$Ca, min_value = 0)
  mg_values <- convert_with_fallback(df, "Mg_mmolL", "Mg_mgL", MW$Mg, min_value = 0.01)
  po4_values <- convert_with_fallback(df, "PO4_mmolL", "PO4_mgL", MW$PO4, min_value = 0)
  ox_values <- convert_with_fallback(df, "Ox_mmolL", "Ox_mgL", MW$Ox, min_value = 0)
  citr_values <- convert_with_fallback(df, "Citr_mmolL", "Citr_mgL", MW$Citr, min_value = 0.01)
  urate_values <- convert_with_fallback(df, "Urate_mmolL", "Urate_mgL", MW$Urate, min_value = 0.01)
  
  cols_to_remove <- grep("_mgL$", names(df), value = TRUE)
  df <- df |> select(-any_of(cols_to_remove))
  
  optional_mmol_cols <- c("Ca_mmolL", "Mg_mmolL", "PO4_mmolL", "Ox_mmolL", "Citr_mmolL", "Urate_mmolL")
  df <- df |> select(-any_of(optional_mmol_cols))
  
  df_converted <- df |>
    mutate(
      Ca_mmolL = ca_values,
      Mg_mmolL = mg_values,
      PO4_mmolL = po4_values,
      Ox_mmolL = ox_values,
      Citr_mmolL = citr_values,
      Urate_mmolL = urate_values
    )
  
  for (col in names(df_converted)) {
    df_converted[[col]] <- as.numeric(unlist(df_converted[[col]]))
  }
  
  if (any(!is.finite(df_converted$pH) | df_converted$pH < 3 | df_converted$pH > 9, na.rm = TRUE)) {
    stop("Invalid pH values detected. Expected range: 4.0-8.5")
  }
  
  conc_cols <- c("Na_mmolL", "K_mmolL", "Ca_mmolL", "Mg_mmolL", "NH4_mmolL", 
                 "Cl_mmolL", "PO4_mmolL", "SO4_mmolL", "Ox_mmolL", "Citr_mmolL", "Urate_mmolL")
  
  for (col in conc_cols) {
    if (col %in% names(df_converted)) {
      if (any(df_converted[[col]] < 0, na.rm = TRUE)) {
        stop(paste("Negative concentrations detected in column:", col))
      }
    }
  }
  
  return(df_converted)
}

# WRAPPER corretto per equil2 - usa nomi parametri corretti dalla documentazione
call_equil2_with_units <- function(Na, K, Ca, Mg, NH4, Cl, PO4, SO4, C2O4, Citrate, Uric, pH) {
  # equil2 usa nomi specifici: sodium_mEq_L, potassium_mEq_L, calcium_mg_dL, etc.
  # Conversioni: mmol/L -> unità richieste da equil2
  
  result <- equil2::equil2(
    sodium_mEq_L = units::set_units(Na, "mmol_sodium/L"),
    potassium_mEq_L = units::set_units(K, "mmol_potassium/L"),
    calcium_mg_dL = units::set_units(Ca * MW$Ca / 10, "mg_calcium/dL"),
    magnesium_mg_dL = units::set_units(Mg * MW$Mg / 10, "mg_magnesium/dL"),
    ammonia_mEq_L = units::set_units(NH4, "mmol_ammonia/L"),
    chloride_mEq_L = units::set_units(Cl, "mmol_chloride/L"),
    phosphate_mg_dL = units::set_units(PO4 * MW$PO4 / 10, "mg_phosphate/dL"),
    sulfate_mg_dL = units::set_units(SO4 * MW$SO4 / 10, "mg_sulfate/dL"),
    oxalate_mg_dL = units::set_units(C2O4 * MW$Ox / 10, "mg_oxalate/dL"),
    citrate_mg_dL = units::set_units(Citrate * MW$Citr / 10, "mg_citrate/dL"),
    urate_mg_dL = units::set_units(Uric * MW$Urate / 10, "mg_urate/dL"),
    pH = pH
  )
  
  return(result)
}

run_equil2_dataframe <- function(df_mmol) {
  if (nrow(df_mmol) == 0) {
    return(list(n = 0, success_count = 0, records = list()))
  }
  
  if (nrow(df_mmol) > 1000) {
    stop("Too many records. Maximum 1000 records per request.")
  }
  
  results <- vector("list", nrow(df_mmol))
  
  for (i in seq_len(nrow(df_mmol))) {
    # Estrai valori come scalari numerici
    Na <- as.numeric(df_mmol$Na_mmolL[i])
    K <- as.numeric(df_mmol$K_mmolL[i])
    Ca <- as.numeric(df_mmol$Ca_mmolL[i])
    Mg <- as.numeric(df_mmol$Mg_mmolL[i])
    NH4 <- as.numeric(df_mmol$NH4_mmolL[i])
    Cl <- as.numeric(df_mmol$Cl_mmolL[i])
    PO4 <- as.numeric(df_mmol$PO4_mmolL[i])
    SO4 <- as.numeric(df_mmol$SO4_mmolL[i])
    C2O4 <- as.numeric(df_mmol$Ox_mmolL[i])
    Citrate <- as.numeric(df_mmol$Citr_mmolL[i])
    Uric <- as.numeric(df_mmol$Urate_mmolL[i])
    pH_val <- as.numeric(df_mmol$pH[i])
    
    # Validazione
    if (any(is.na(c(Na, K, Ca, Mg, NH4, Cl, PO4, SO4, C2O4, Citrate, Uric, pH_val)))) {
      results[[i]] <- list(
        SS_CaOx = NA_real_, SS_Brushite = NA_real_,
        SS_HAp = NA_real_, SS_UricAcid = NA_real_,
        DG_CaOx = NA_real_, DG_Brushite = NA_real_,
        DG_HAp = NA_real_, DG_UricAcid = NA_real_,
        status = "error", error_message = "NA values detected in input"
      )
      next
    }
    
    # Chiamata equil2 con units wrapper
    results[[i]] <- tryCatch({
      equil_result <- call_equil2_with_units(Na, K, Ca, Mg, NH4, Cl, PO4, SO4, C2O4, Citrate, Uric, pH_val)
      
      # equil_result è un dataframe con colonne: species, super_saturation, neg_delta_Gibbs
      ss_map <- setNames(equil_result$super_saturation, equil_result$species)
      dg_map <- setNames(equil_result$neg_delta_Gibbs, equil_result$species)
      
      list(
        SS_CaOx = as.numeric(ss_map["Calcium Oxalate"]),
        SS_Brushite = as.numeric(ss_map["Brushite"]),
        SS_HAp = as.numeric(ss_map["Hydroxyapatite"]),
        SS_UricAcid = as.numeric(ss_map["Uric Acid"]),
        DG_CaOx = as.numeric(dg_map["Calcium Oxalate"]),
        DG_Brushite = as.numeric(dg_map["Brushite"]),
        DG_HAp = as.numeric(dg_map["Hydroxyapatite"]),
        DG_UricAcid = as.numeric(dg_map["Uric Acid"]),
        status = "success",
        error_message = NA_character_
      )
    }, error = function(e) {
      list(
        SS_CaOx = NA_real_, SS_Brushite = NA_real_,
        SS_HAp = NA_real_, SS_UricAcid = NA_real_,
        DG_CaOx = NA_real_, DG_Brushite = NA_real_,
        DG_HAp = NA_real_, DG_UricAcid = NA_real_,
        status = "error", error_message = conditionMessage(e)
      )
    })
  }
  
  results_df <- bind_rows(results)
  output_df <- bind_cols(df_mmol, results_df)
  final_results <- jsonlite::fromJSON(
    jsonlite::toJSON(output_df, dataframe = "rows", auto_unbox = TRUE)
  )
  success_count <- sum(results_df$status == "success", na.rm = TRUE)
  
  return(list(
    n = nrow(output_df),
    success_count = success_count,
    records = final_results,
    computation_time = as.character(Sys.time())
  ))
}