File size: 13,744 Bytes
45e2a28
81e15fe
 
 
 
9435413
 
9160077
 
 
5ae2332
 
81e15fe
 
 
9435413
9160077
9435413
81e15fe
 
 
 
 
9160077
 
1078b07
 
 
3d6f980
 
 
 
 
 
5c1d275
 
3d6f980
 
 
 
 
 
 
 
1078b07
 
5e85a67
1078b07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9160077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81e15fe
 
5ae2332
81e15fe
5ae2332
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d96a10e
5ae2332
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d96a10e
5ae2332
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81e15fe
7b70c21
 
 
 
 
81e15fe
7b70c21
81e15fe
7b70c21
81e15fe
7b70c21
 
81e15fe
 
7b70c21
 
 
 
 
81e15fe
7b70c21
81e15fe
7b70c21
81e15fe
7b70c21
 
81e15fe
 
 
45e2a28
 
81e15fe
 
 
 
 
 
 
5ae2332
81e15fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfad619
81e15fe
dfad619
5ae2332
 
 
54ab346
81e15fe
 
 
 
 
 
 
5ae2332
 
45e2a28
 
 
5ae2332
 
 
 
45e2a28
5ae2332
45e2a28
 
 
 
 
81e15fe
45e2a28
5ae2332
 
81e15fe
45e2a28
 
 
 
 
 
81e15fe
5ae2332
 
 
d96a10e
81e15fe
 
e161839
81e15fe
 
 
 
 
 
 
 
 
 
5ae2332
81e15fe
 
5ae2332
81e15fe
 
 
 
 
 
 
 
 
 
 
 
 
5ae2332
81e15fe
 
 
 
 
5ae2332
81e15fe
 
5ae2332
81e15fe
 
 
 
 
 
 
 
 
 
 
 
 
5ae2332
81e15fe
 
dfad619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81e15fe
dfad619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56eae50
45e2a28
81e15fe
 
 
 
dfad619
81e15fe
 
 
5ae2332
dfad619
 
 
 
 
 
 
 
81e15fe
 
dfad619
81e15fe
dfad619
81e15fe
 
 
 
dfad619
81e15fe
 
 
5ae2332
 
81e15fe
dfad619
 
 
 
 
 
 
81e15fe
 
 
dfad619
81e15fe
 
 
 
dfad619
81e15fe
dfad619
81e15fe
dfad619
 
 
 
 
81e15fe
 
dfad619
81e15fe
 
 
5ae2332
 
81e15fe
 
3e0071d
 
 
b444bf3
3e0071d
 
b444bf3
 
3e0071d
 
 
dfad619
b444bf3
3e0071d
 
 
dfad619
b444bf3
 
 
 
 
 
 
 
 
 
 
81e15fe
b444bf3
 
81e15fe
dfad619
81e15fe
dfad619
 
 
 
 
 
 
81e15fe
dfad619
81e15fe
dfad619
81e15fe
 
 
5ae2332
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
from dash import Dash, Input, Output, State, no_update
from data.functions import *
from transportEqs import *
from Kps_function.read_Kps_model import *
import os
from figure import build_figure
from main_layout import build_main_layout
from instructions import build_instructions_layout
from rst_info import build_rst_layout
from dash import html, dcc
import base64
import io

app = Dash(
    __name__,
    assets_folder=os.path.join(os.path.dirname(__file__), "assets"),
    suppress_callback_exceptions=True,
    #external_stylesheets=[dbc.themes.BOOTSTRAP],
)

# --------------------------------------------------------------------
# Layout
# --------------------------------------------------------------------
app.layout = html.Div([
    dcc.Location(id="url", refresh=False),

    html.Header(
        html.Div([
            html.A(
                html.Img(
                    src="/assets/gov-fda-new-white.svg",
                    alt="U.S. Food and Drug Administration",
                    className="fda-logo",
                ),
                href="https://www.fda.gov",
                target="_blank",
                className="site-brand",
            ),

            html.Span(
                "Extraction condition justification tool",
                className="site-tool-title",
            ),

            html.Nav([
                dcc.Link("Model", href="/"),
                dcc.Link("Quick start", href="/instructions"),
                dcc.Link("About this tool", href="/rst"),
            ], className="site-nav", **{"aria-label": "Main navigation"}),
        ], className="site-container site-header-inner"),
        className="site-header",
    ),

    html.Main(
        html.Div(id="page-content"),
        id="main-content",
        className="site-container site-main",
    ),

    html.Footer(
        html.Div("Office of Science and Engineering Laboratories · Contact", className="site-container"),
        className="site-footer",
    ),
])

app.validation_layout = html.Div([
    app.layout,
    build_main_layout(),
    build_instructions_layout(),
    build_rst_layout(),
])

@app.callback(
    Output("page-content", "children"),
    Input("url", "pathname")
)
def route(pathname):
    if pathname == "/instructions":
        return build_instructions_layout()
    elif pathname == "/rst":
        return build_rst_layout()
    else:
        return build_main_layout()

# --------------------------------------------------------------------
# Callbacks
# --------------------------------------------------------------------

@app.callback(
    Output("solute_upload_container", "style"),
    Input("solute_source", "value"),
)
def show_solute_upload(solute_source):

    if solute_source == "upload":
        return {"display": "block"}

    return {"display": "none"}

@app.callback(
    Output("uploaded_solute_data", "data"),
    Output("solute_upload_status", "children"),
    Input("solute_upload", "contents"),
    State("solute_upload", "filename"),
    prevent_initial_call=True,
)
def load_solute_file(contents, filename):

    if contents is None:
        return None, ""

    try:
        content_type, content_string = contents.split(",")

        decoded = base64.b64decode(content_string)

        uploaded_df = pd.read_excel(
            io.BytesIO(decoded)
        )

        required_columns = [
            "CASRN",
            "MW",
            "LogP",
            #"Vabc",
        ]

        missing = [
            col for col in required_columns
            if col not in uploaded_df.columns
        ]

        if missing:
            return (
                None,
                f"Missing required columns: {', '.join(missing)}"
            )

        numeric_columns = [
            "MW",
            "LogP",
            #"Vabc",
        ]

        for col in numeric_columns:
            uploaded_df[col] = pd.to_numeric(
                uploaded_df[col],
                errors="coerce"
            )

        if uploaded_df[numeric_columns].isna().any().any():
            return (
                None,
                "One or more required numeric values are missing or invalid."
            )

        return (
            uploaded_df.to_dict("records"),
            f"Loaded {len(uploaded_df)} solutes from {filename}"
        )

    except Exception as e:
        return None, f"Could not read file: {e}"

@app.callback(
    Output("c1_solvent", "disabled"),
    Output("c1_volume", "disabled"),
    Output("c1_swelling", "disabled"),
    Output("c1_temp", "disabled"),
    Output("c1_iterations", "disabled"),
    Input("condition1_mode", "value"),
    State("c1_solvent", "value"),
)
def toggle_condition1_inputs(mode, current_value):
    disable = (mode != "in_vitro")

    return disable, disable, disable, disable, disable

@app.callback(
    Output("c2_solvent", "disabled"),
    Output("c2_volume", "disabled"),
    Output("c2_swelling", "disabled"),
    Output("c2_temp", "disabled"),
    Output("c2_iterations", "disabled"),
    Input("condition2_mode", "value"),
    State("c2_solvent", "value"),
)
def toggle_condition2_inputs(mode, current_value):
    disable = (mode != "in_vitro")

    return disable, disable, disable, disable, disable

@app.callback(
    Output("mm0_chart", "figure"),
    Output("solute_calculate_warning", "children"),

    Input("calculate", "n_clicks"),
    State("matrix", "value"),
    State("tg", "value"),
    State("crystal", "value"),
    State("density", "value"),
    State("polymer_volume", "value"),
    State("surface_area", "value"),

    # Condition 1
    State("condition1_mode", "value"),
    State("c1_solvent", "value"),
    State("c1_volume", "value"),
    State("c1_swelling", "value"),
    State("c1_temp", "value"),
    State("c1_time", "value"),
    State("c1_iterations", "value"),
    # Condition 2
    State("condition2_mode", "value"),
    State("c2_solvent", "value"),
    State("c2_volume", "value"),
    State("c2_swelling", "value"),
    State("c2_temp", "value"),
    State("c2_time", "value"),
    State("c2_iterations", "value"),
    # MC
    State("samples", "value"),
    State("mc_option", "value"),
    # Solutes
    State("solute_source", "value"),
    State("uploaded_solute_data", "data"),
    prevent_initial_call=True,
)

def update_chart(n_clicks,
                 matrix, tg, crystal, density, polymer_volume, surface_area,
                 c1_mode, c1_solvent, c1_volume, c1_swelling,
                 c1_temp, c1_time, c1_iter,
                 c2_mode, c2_solvent, c2_volume,
                 c2_swelling, c2_temp, c2_time, c2_iter,samples,mc_option,solute_source,uploaded_solute_data):

    # ---------------------------------------------------------
    # Validate solute source
    # ---------------------------------------------------------
    if solute_source == "default":

        current_soluteData = soluteData.copy()

    elif solute_source == "upload":

        if not uploaded_solute_data:
            return (
                no_update,
                "Please upload a valid Excel file before calculating."
            )

        current_soluteData = pd.DataFrame.from_records(
            uploaded_solute_data
        )

    else:
        return (
            no_update,
            "Please select either the default or user-defined chemical set."
        )

    df = pd.DataFrame()
    df['CASRN'] = current_soluteData['CASRN'].to_numpy()

    current_soluteData["LogP"] = current_soluteData["LogP"].clip(upper=10)
    current_soluteData["Vabc"] = current_soluteData["MW"]

    N = int(samples)
    pindex = np.where(polymers == matrix)[0][0]
    CHRIS_category = categories[pindex]
    Polymer_Density = float(density)
    Polymer_Tg = float(tg) + 273.15
    Polymer_X = float(crystal)/100.

    L = float(polymer_volume)/float(surface_area)

    # Condition 1
    ExtractionTime = float(c1_time) * 3600.
    if c1_mode == 'in_vivo_conservative':
        c1_dist = ConservativeMonteCarlo(current_soluteData, CHRIS_category, L, ExtractionTime, N)

    elif c1_mode == 'in_vivo_tissue':
        c1_dist = TissueMonteCarlo(current_soluteData, CHRIS_category, L, ExtractionTime, N)

    else:
        Solvent_Name = c1_solvent
        Solvent_MW = Solvent_MWs[Solvent_Name]
        Solvent_Density = Solvent_Densities[Solvent_Name]
        Solvent_PI = Solvent_PIs[Solvent_Name]
        ExtractionT = float(c1_temp) + 273.15
        Ms_M0 = float(c1_swelling)
        Swell = 1.+(Ms_M0-1.)*Polymer_Density/Solvent_Density
        w = (Ms_M0 - 1.)/(Ms_M0-Polymer_X)
        Iterations = float(c1_iter)
        Lbath = float(c1_volume) / float(surface_area)

        c1_dist = ExtractMonteCarlo(current_soluteData, Solvent_PI, w, ExtractionT, Polymer_Tg, Solvent_Name, Solvent_MW,
                                                    ExtractionTime, Swell, Iterations, CHRIS_category, L, Lbath, N)

    # Condition 2
    ExtractionTime = float(c2_time) * 3600.
    if c2_mode == 'in_vivo_conservative':
        c2_dist = ConservativeMonteCarlo(current_soluteData, CHRIS_category, L, ExtractionTime, N)

    elif c2_mode == 'in_vivo_tissue':
        c2_dist = TissueMonteCarlo(current_soluteData, CHRIS_category, L, ExtractionTime, N)

    else:
        Solvent_Name = c2_solvent
        Solvent_MW = Solvent_MWs[Solvent_Name]
        Solvent_Density = Solvent_Densities[Solvent_Name]
        Solvent_PI = Solvent_PIs[Solvent_Name]
        ExtractionT = float(c2_temp) + 273.15
        Ms_M0 = float(c2_swelling)
        Swell = 1. + (Ms_M0 - 1.) * Polymer_Density / Solvent_Density
        w = (Ms_M0 - 1.) / (Ms_M0 - Polymer_X)
        Iterations = float(c2_iter)
        Lbath = float(c2_volume) / float(surface_area)

        c2_dist = ExtractMonteCarlo(current_soluteData, Solvent_PI, w, ExtractionT, Polymer_Tg, Solvent_Name, Solvent_MW,
                                                    ExtractionTime, Swell, Iterations, CHRIS_category, L, Lbath, N)

    if mc_option == "absolute":
        c1_lower, c1_median, c1_upper = np.percentile(
            c1_dist,
            [25, 50, 75],
            axis=1
        )

        c2_lower, c2_median, c2_upper = np.percentile(
            c2_dist,
            [25, 50, 75],
            axis=1
        )

        df['Condition 1'] = c1_median
        df['Cond1_err_plus'] = c1_upper - c1_median
        df['Cond1_err_minus'] = c1_median - c1_lower

        df['Condition 2'] = c2_median
        df['Cond2_err_plus'] = c2_upper - c2_median
        df['Cond2_err_minus'] = c2_median - c2_lower

    elif mc_option == "ratio":

        ratio_dist = np.divide(
            c1_dist,
            c2_dist,
            out=np.full_like(c1_dist, np.nan),
            where=c2_dist > 0
        )

        ratio_lower, ratio_median, ratio_upper = np.percentile(
            ratio_dist,
            [25, 50, 75],
            axis=1
        )

        df['Ratio'] = ratio_median
        df['Ratio_err_plus'] = ratio_upper - ratio_median
        df['Ratio_err_minus'] = ratio_median - ratio_lower

    fig = build_figure(df, mc_option)

    return fig, ""

def ConservativeMonteCarlo(soluteData, CHRIS_category, L, time, N):

    nSolutes = len(soluteData)
    distributions = zeros((nSolutes, N))

    for iSolute in range(nSolutes):

        Solute_MW = soluteData['MW'].iloc[iSolute]

        D_CHRIS = get_D_CHRIS(
            Solute_MW,
            CHRIS_category,
            N=N
        )

        tau = D_CHRIS * time / L**2
        mass = Conservative(tau)

        distributions[iSolute, :] = mass

    return distributions

def TissueMonteCarlo(soluteData, CHRIS_category, L, time, N):

    nSolutes = len(soluteData)
    distributions = zeros((nSolutes, N))

    for iSolute in range(nSolutes):

        Solute_MW = soluteData['MW'].iloc[iSolute]
        Solute_logP = soluteData['LogP'].iloc[iSolute]

        D_CHRIS = get_D_CHRIS(
            Solute_MW,
            CHRIS_category,
            N=N
        )

        tau = D_CHRIS * time / L**2

        Dt = get_Dt(N)
        Kpt = get_Kpt(Solute_logP, N)

        beta = (1. / Kpt) * sqrt(Dt / D_CHRIS)

        mass = SolubilityLimited(beta, tau)

        distributions[iSolute, :] = mass

    return distributions

def ExtractMonteCarlo(
        soluteData, Solvent_PI, w, ExtractionT,
        Polymer_Tg, Solvent_Name, Solvent_MW,
        ExtractionTime, Swell, Iterations,
        CHRIS_category, L, Lbath, N):

    nSolutes = len(soluteData)
    distributions = zeros((nSolutes, N))

    for iSolute in range(nSolutes):

        Solute_MW = soluteData['MW'].iloc[iSolute]
        Solute_logP = soluteData['LogP'].iloc[iSolute]
        Solute_Vabc = soluteData['Vabc'].iloc[iSolute]

        if Solvent_Name == 'blood':

            Kps = get_Kpb(Solute_logP, N)

        else:

            ToKPS = array([[Solute_logP, Solvent_PI]])

            model = QuantileGridFromCoeffs(
                export_dir='Kps_function/Kps_model'
            )

            Kps = 10 ** model.sample(
                ToKPS,
                n_samples=N
            )[0]

        D_Extract = get_D_Extract(
            w,
            ExtractionT,
            Polymer_Tg,
            Solvent_Name,
            Solvent_MW,
            Solute_MW,
            Solute_Vabc,
            CHRIS_category,
            N=N
        )

        tau = D_Extract * ExtractionTime / L**2
        alpha = Lbath / L / Kps
        massExtraction = zeros(N)

        for i in range(N):
            massExtraction[i] = Extraction(
                tau[i],
                alpha[i],
                Kps[i],
                Swell,
                Iterations
            )

        distributions[iSolute, :] = massExtraction

    return distributions


if __name__ == "__main__":
    app.run(debug=True)