File size: 6,499 Bytes
6150a83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.integrate import odeint
from scipy.optimize import fsolve
import gradio as gr

# Population and time settings
population_size = 100
time_points = np.linspace(0, 24, 100)

# PK parameters for Enrofloxacin and Ciprofloxacin
pk_parameters = {
    'Enrofloxacin': {
        'Cmax_mean': 1.35, 'Cmax_std': 0.15,
        'Tmax_mean': 4.00, 'Tmax_std': 1,
        'Ke_mean': 0.03, 'Ke_std': 0.003,
        'F_mean': 0.7, 'F_std': 0.1,
        'Vd_mean': 24.76, 'Vd_std': 3.67,
        'pKa': 6.0,
        'type': 'acidic'
    },
    'Ciprofloxacin': {
        'Cmax_mean': 0.08, 'Cmax_std': 0.01,
        'Tmax_mean': 3.44, 'Tmax_std': 1.01,
        'Ke_mean': 0.04, 'Ke_std': 0.01,
        'F_mean': 0.6, 'F_std': 0.1,
        'Vd_mean': 17.46, 'Vd_std': 6.40,
        'pKa': 7.7,
        'type': 'acidic'
    }
}

# MIC values for pathogens
MIC_values = {
    'E.coli': 0.06,
    'S.Enteritidis': 0.1,
    'M.gallisepticum': 0.1,
    'C.perfringens': 0.12
}

# Ionization calculations
def unionized_fraction_acidic(pH, pKa):
    return 1 / (1 + 10 ** (pH - pKa))

def unionized_fraction_basic(pH, pKa):
    return 1 / (1 + 10 ** (pKa - pH))

def calculate_unionized_concentration(concentration, pH, pKa, drug_type):
    if drug_type == "acidic":
        unionized_fraction = unionized_fraction_acidic(pH, pKa)
    elif drug_type == "basic":
        unionized_fraction = unionized_fraction_basic(pH, pKa)
    else:
        raise ValueError("Invalid drug type. Must be 'acidic' or 'basic'.")
    return concentration * unionized_fraction

# Simulate drug concentration
def pk_model(C, t, ka, ke, Vd, F, dose):
    dCdt = (F * dose * ka / Vd) * np.exp(-ka * t) - (ke * C[0])
    return dCdt

def solve_for_ka(Tmax_target, ke):
    ka_guess = max(ke * 2, 0.01)
    def equation(ka): return (np.log(ka) - np.log(ke)) / (ka - ke) - Tmax_target
    ka_solution = fsolve(equation, ka_guess)
    return ka_solution[0] if ka_solution[0] > 0 else 0.05

def simulate_concentration(dose, ke, Vd, F, Cmax_target, drug_type, pH, pKa):
    ka = solve_for_ka(pk_parameters['Enrofloxacin']['Tmax_mean'], ke)
    concentration = odeint(pk_model, [0], time_points, args=(ka, ke, Vd, F, dose))[:, 0]
    if np.max(concentration) > 0:
        concentration *= (Cmax_target / np.max(concentration))
    return calculate_unionized_concentration(concentration, pH, pKa, drug_type)

def simulate_multiple_doses(pk_params, doses, pH):
    all_data = []
    for molecule, params in pk_params.items():
        for i in range(population_size):
            F = np.random.normal(params['F_mean'], params['F_std'])
            ke = np.random.normal(params['Ke_mean'], params['Ke_std'])
            Vd = np.random.normal(params['Vd_mean'], params['Vd_std'])
            Cmax_target = np.random.normal(params['Cmax_mean'], params['Cmax_std'])
            pKa = params['pKa']
            ref_conc = simulate_concentration(10, ke, Vd, F, Cmax_target, params['type'], pH, pKa)
            for dose in doses:
                scaled_conc = ref_conc * (dose / 10)
                all_data.extend([{
                    'Individual': i + 1,
                    'Molecule': molecule,
                    'Dose': dose,
                    'Time': t,
                    'Concentration': conc
                } for t, conc in zip(time_points, scaled_conc)])
    return pd.DataFrame(all_data)

def calculate_pkpd_metrics(concentrations, time_points, MIC):
    AUC = np.trapz(concentrations, time_points)
    Cmax = np.max(concentrations)
    T_above_MIC = time_points[concentrations > MIC]
    T_above_MIC_duration = (T_above_MIC[-1] - T_above_MIC[0]) if len(T_above_MIC) > 0 else 0
    AUIC = np.trapz(concentrations[concentrations > MIC] - MIC, time_points[concentrations > MIC]) if np.any(concentrations > MIC) else 0
    return AUC, Cmax, T_above_MIC_duration, AUIC

def plot_pkpd_and_ionization(pk_params, df, MIC, doses, pH_range):
    fig, axes = plt.subplots(len(pk_params), len(doses) + 1, figsize=(20, len(pk_params) * 5))
    for row, (molecule, params) in enumerate(pk_params.items()):
        pKa = params['pKa']
        for col, dose in enumerate(doses):
            group = df[(df['Molecule'] == molecule) & (df['Dose'] == dose)]
            mean_conc = group.groupby('Time')['Concentration'].mean().values
            ax = axes[row, col]
            ax.plot(time_points[:len(mean_conc)], mean_conc, label=f"{molecule}, Dose: {dose} mg/kg")
            ax.axhline(MIC, color='red', linestyle='--', label=f'MIC = {MIC:.2f}')

            # Calculate PKPD metrics
            AUC, Cmax, T_above_MIC, AUIC = calculate_pkpd_metrics(mean_conc, time_points[:len(mean_conc)], MIC)

            # Fill AUIC area
            ax.fill_between(time_points[:len(mean_conc)], MIC, mean_conc, where=(mean_conc > MIC), color='green', alpha=0.3, label="AUIC")
            ax.text(0.6 * time_points[-1], 0.8 * np.max(mean_conc),
                    f"AUC: {AUC:.2f}\nCmax: {Cmax:.2f}\nT>MIC: {T_above_MIC:.2f} h\nAUIC: {AUIC:.2f}",
                    fontsize=9, bbox=dict(facecolor='white', alpha=0.8))

            ax.set_title(f"{molecule} - Dose {dose} mg/kg")
            ax.set_xlabel('Time (h)')
            ax.set_ylabel('Concentration (mg/L)')
            ax.legend()
        ax = axes[row, -1]
        unionized = [unionized_fraction_acidic(pH, pKa) for pH in pH_range]
        ax.plot(pH_range, unionized, label=f"Ionization Profile ({molecule})")
        ax.set_title(f"Ionization Profile: {molecule}")
        ax.set_xlabel('pH')
        ax.set_ylabel('Unionized Fraction')
        ax.legend()
    plt.tight_layout()
    return fig

# Gradio Function
def gradio_function(pH_input, pathogen, dose_input):
    if pathogen not in MIC_values:
        raise ValueError("Invalid pathogen.")
    MIC = MIC_values[pathogen]
    doses = [int(d) for d in dose_input.split(',')]
    pH_range = np.linspace(0, 14, 100)
    df = simulate_multiple_doses(pk_parameters, doses, pH_input)
    fig = plot_pkpd_and_ionization(pk_parameters, df, MIC, doses, pH_range)
    return fig


# Gradio Interface
interface = gr.Interface(
    fn=gradio_function,
    inputs=[
        gr.Slider(0, 14, step=0.1, label="Water pH Value"),
        gr.Dropdown(list(MIC_values.keys()), label="Pathogen"),
        gr.Textbox(value="5,15,20", label="Doses (mg/kg, comma-separated)")
    ],
    outputs=gr.Plot(),
    title="Qomics All Rights Reserved (C)",
    live=True
)


interface.launch()