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()