### Get Initial Concentrations and System Sizes Source: https://github.com/bjodah/chempy/blob/master/examples/Ammonia.ipynb Retrieves the initial concentrations and the number of species in the equilibrium system. Requires 'eqsys' to be initialized. ```python init_conc, eqsys.ns ``` -------------------------------- ### Import Libraries and Setup Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetic_model_fitting.ipynb Imports necessary libraries for data analysis, plotting, and chempy functionalities. Sets up matplotlib for inline plotting. ```python import bz2, codecs, collections, functools, itertools, json import numpy as np import matplotlib.pyplot as plt import chempy import chempy.equilibria from chempy.electrolytes import ionic_strength from chempy.kinetics.arrhenius import fit_arrhenius_equation from chempy.printing import number_to_scientific_latex, as_per_substance_html_table from chempy.properties.water_density_tanaka_2001 import water_density from chempy.units import rescale, to_unitless, default_units as u from chempy.util.regression import least_squares, irls, avg_params, plot_fit, plot_least_squares_fit, plot_avg_params from chempy._solution import QuantityDict %matplotlib inline print(chempy.__version__) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_ode_time_dependent_units.ipynb Imports modules for reaction systems, units, ODE integration, and plotting. Ensure these libraries are installed. ```python import math from collections import defaultdict from chempy import ReactionSystem from chempy.units import ( default_units as u, SI_base_registry as ureg ) from chempy.kinetics.ode import get_odesys from chempy.kinetics.rates import SinTemp %matplotlib inline ``` -------------------------------- ### Setup and Check Autonomous Interface for Logarithmic System Source: https://github.com/bjodah/chempy/blob/master/examples/_switch_between_reduced_ode_systems.ipynb Creates a logarithmic ODE system with an autonomous interface and asserts its property. Also retrieves its roots and expressions. ```python rsalogsys_A = LogLogSys_apart.from_other(rssys_A, autonomous_interface=True) assert rsalogsys_A.autonomous_interface rsalogsys_A.roots, rsalogsys_A.exprs ``` -------------------------------- ### Solve equilibrium with initial solid NaCl Source: https://github.com/bjodah/chempy/blob/master/examples/NaCl_precipitation.ipynb Solves the equilibrium system starting with solid NaCl present. Asserts that the solution is successful and sane. ```python sol, info, sane = eqsys.root({'Na+': 0, 'Cl-': 0, 'NaCl': 2}) assert info['success'] and sane sol ``` -------------------------------- ### Import necessary libraries Source: https://github.com/bjodah/chempy/blob/master/examples/_eyring_kinetics_ramped_temperature.ipynb Imports essential libraries for symbolic mathematics, plotting, numerical operations, and ChemPy functionalities. This setup is required for all subsequent examples. ```python import sympy as sm import matplotlib.pyplot as plt import numpy as np from chempy import ReactionSystem from chempy.units import to_unitless, SI_base_registry as si, default_units as u, default_constants as const from chempy.kinetics.ode import get_odesys from chempy.kinetics.rates import RampedTemp sm.init_printing() %matplotlib inline ``` -------------------------------- ### Set initial concentrations Source: https://github.com/bjodah/chempy/blob/master/examples/ammonical_cupric_solution.ipynb Initializes a dictionary with the starting concentrations for each chemical species. Note that water is set to its approximate molar concentration in pure water. ```python init_conc = defaultdict(float, {'H+': 1e-7, 'OH-': 1e-7, 'NH4+': 0, 'NH3': 1.0, 'Cu+2': 1e-2, 'H2O': 55.5}) ``` -------------------------------- ### Get ODE system for integration Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_radiolysis_analytic.ipynb Obtains the system of ordinary differential equations from the reaction system. ```python odesys, extra = get_odesys(rsys, include_params=False) ``` -------------------------------- ### Symbolic Setup for Reversible Batch Reactor Source: https://github.com/bjodah/chempy/blob/master/chempy/kinetics/tests/_derive_analytic_cstr_bireac.ipynb Sets up symbolic variables and the rate expressions for a reversible reaction in a batch reactor. Defines forward and reverse rates and the differential equation for the extent of reaction. ```python # Pseudo reversible reaction (batch reactor) # # A + B <-> C # t a0 b0-x c0 + x import sympy kf, kb, a0, b0, c0, x = sympy.symbols('k_{\rm\ f} k_{\rm\ b} a0 b0 c0 x', real=True, nonnegative=True) rf = kf*a0*(b0-x) rb = kb*(c0+x) dxdt = (rf - rb).expand().factor(x) dxdt ``` -------------------------------- ### Get symbolic form of equations with NumSysLog Source: https://github.com/bjodah/chempy/blob/master/examples/Ammonia.ipynb Generates the symbolic equations for the system using NumSysLog, including initial concentrations and equilibrium constants as parameters. ```python numsys_log = NumSysLog(eqsys, backend=sp) f = numsys_log.f(y, list(i)+list(K)) f ``` -------------------------------- ### Continue Integration from Root Time Source: https://github.com/bjodah/chempy/blob/master/examples/protein_binding_unfolding_4state_model.ipynb Integrates the ODE system starting from the time and state where the root condition was met in the previous step. ```python xout2, yout2, info_LA = integrate_and_plot(psysLA, first_step=0.0, t0=tout1[-1], c0=dict(zip(odesys.names, Cout1[-1, :]))) ``` -------------------------------- ### Get ODE System and Examine Expressions Source: https://github.com/bjodah/chempy/blob/master/examples/aqueous_radiolysis.ipynb Obtains the ordinary differential equation (ODE) system from the reaction system and displays the first three ODE expressions. ```python odesys, extra = get_odesys(rsys) odesys.exprs[:3] # take a look at the first three ODEs in the system ``` -------------------------------- ### Get ODE system and extra information Source: https://github.com/bjodah/chempy/blob/master/examples/Robertson_kinetics.ipynb Generates the system of ordinary differential equations (ODEs) for the reaction system, including parameters. Returns the ODE system and additional information. ```python odesys, extra = get_odesys(rsys, include_params=True) odesys.exprs ``` -------------------------------- ### Get ODE System with Time-Dependent Temperature Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_ode_time_dependent_units.ipynb Generates the ODE system from the reaction system, substituting the time-dependent temperature profile and specifying the unit registry. ```python odesys, extra = get_odesys(rsys, include_params=False, substitutions={ 'temperature': st}, unit_registry=ureg) ``` -------------------------------- ### Solve equilibrium with higher initial solid NaCl Source: https://github.com/bjodah/chempy/blob/master/examples/NaCl_precipitation.ipynb Solves the equilibrium system starting with a higher amount of solid NaCl. Asserts that the solution is successful and sane. ```python sol, info, sane = eqsys.root({'Na+': 0, 'Cl-': 0, 'NaCl': 5.0}) assert info['success'] and sane sol ``` -------------------------------- ### Obtain initial condition-based symbolic solution Source: https://github.com/bjodah/chempy/blob/master/examples/_eyring_kinetics_ramped_temperature_2nd_order.ipynb Substitutes the solved integration constant back into the symbolic solution to get the final expression with the correct initial condition. ```python yunit0 = y.subs(C1, _C1).simplify() ``` -------------------------------- ### Get native ODE system and integrate Source: https://github.com/bjodah/chempy/blob/master/examples/_integrated.ipynb Obtains a native ODE system using the get_native function and then uses plot_against_analytic to compare its results with an analytic solution using the 'gsl' integrator. ```python nsys = get_native(rsys, odesys, 'gsl') ``` ```python plot_against_analytic(nsys, conc, integrator='gsl', atol=1e-16, rtol=1e-16) ``` -------------------------------- ### Set up initial conditions and parameters Source: https://github.com/bjodah/chempy/blob/master/examples/_eyring_kinetics.ipynb Sets the initial concentrations for the reactants and products, the time span for integration, and reaction parameters like temperature. ```python NOBr0_M = 0.7 init_cond = dict( NOBr=NOBr0_M*u.M, NO=0*u.M, Br=0*u.M ) t = 5*u.second params = dict( temperature=T_K*u.K ) ``` -------------------------------- ### Get Number of Expressions Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_ode_time_dependent_autonomous.ipynb Returns the number of expressions (equations) in the ODE system. ```python len(odesys.exprs) ``` -------------------------------- ### Set up parameters and initial conditions with units Source: https://github.com/bjodah/chempy/blob/master/examples/kinetics_decay_chain_units_varied_params.ipynb Initializes reaction parameters and initial concentrations with explicit units using `chempy.units`. This ensures dimensional consistency throughout the simulation. ```python params = {'A1': 1e11/u.s, 'A2': 2e11/u.s, 'Ea_R_1': 8e3*u.K, 'Ea_R_2': 8.5e3*u.K, 'temperature': 300*u.K} c0 = defaultdict(lambda: 0*u.molar, {'A': 1*u.molar}) variables = c0.copy() variables.update(params) rsys.rates(variables) ``` -------------------------------- ### Get Parameter Names Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_ode_time_dependent_autonomous.ipynb Retrieves the names of the parameters used in the ODE system. ```python odesys.param_names ``` -------------------------------- ### Initialize Reaction System Source: https://github.com/bjodah/chempy/blob/master/examples/aqueous_radiolysis.ipynb Sets up a reaction system for aqueous radiolysis with hardcoded production rates. ```python rsys = ReactionSystem(prod_rxns + reactions, species) rsys ``` -------------------------------- ### Create and display an equilibrium system Source: https://github.com/bjodah/chempy/blob/master/examples/Ammonia.ipynb Initializes an EqSystem object with the defined equilibria and substances, then displays the system representation. ```python eqsys = EqSystem(equilibria, subst) eqsys ``` -------------------------------- ### Get composition balance vectors Source: https://github.com/bjodah/chempy/blob/master/examples/Ammonia.ipynb Retrieves the composition balance vectors for the equilibrium system. ```python eqsys.composition_balance_vectors() ``` -------------------------------- ### Set up CSTR ODE System Source: https://github.com/bjodah/chempy/blob/master/chempy/kinetics/tests/_derive_analytic_cstr_bireac.ipynb Initializes a CSTR ODE system using ChempPy's ReactionSystem and get_odesys for a simple reaction. ```python %matplotlib inline import numpy as np from chempy import ReactionSystem from chempy.kinetics.ode import get_odesys rsys = ReactionSystem.from_string("OH + OH -> H2O2; 'k'") cstr, extra = get_odesys(rsys, include_params=False, cstr=True) fr, fc = extra['cstr_fr_fc'] print(cstr.names, cstr.param_names) cstr.exprs ``` -------------------------------- ### Get substance names from ReactionSystem Source: https://github.com/bjodah/chempy/blob/master/examples/Robertson_kinetics.ipynb Returns a list of names of all substances present in the ReactionSystem. ```python rsys3.substance_names() ``` -------------------------------- ### Get Jacobian Matrix Shape Source: https://github.com/bjodah/chempy/blob/master/examples/aqueous_radiolysis.ipynb Retrieves the Jacobian matrix of the ODE system and prints its shape. ```python j = odesys.get_jac() j.shape ``` -------------------------------- ### Set up initial concentrations and equilibria Source: https://github.com/bjodah/chempy/blob/master/examples/Ammonia.ipynb Defines initial concentrations for species and sets up equilibrium objects for water autoionization and ammonia protolysis, including their equilibrium constants. ```python init_conc = {'H+': 1e-7, 'OH-': 1e-7, 'NH4+': 1e-7, 'NH3': 1.0, 'H2O': 55.5} x0 = [init_conc[k] for k in substance_names] H2O_c = init_conc['H2O'] w_autop = Equilibrium({'H2O': 1}, {'H+': 1, 'OH-': 1}, 10**-14/H2O_c) NH4p_pr = Equilibrium({'NH4+': 1}, {'H+': 1, 'NH3': 1}, 10**-9.26) equilibria = w_autop, NH4p_pr [(k, init_conc[k]) for k in substance_names] ``` -------------------------------- ### Pre-process Arguments for Autonomous System with Different Inputs Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_ode_time_dependent_autonomous.ipynb Demonstrates the pre_process method of the autonomous system with different input values for time, state variables, and parameters. ```python asys.pre_process(1, [0,1,2,3,4], [5,6,7,8]) ``` -------------------------------- ### Get rate expression for a reaction Source: https://github.com/bjodah/chempy/blob/master/examples/_Expr_custom_Gibbs_kinetics_odesys.ipynb Retrieves and displays the rate expression for the last reaction in `rs2`. ```python rs2.rxns[-1].rate_expr() ``` -------------------------------- ### Set Initial Conditions and Parameters Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_ode_time_dependent_units.ipynb Initializes concentrations for the species, defines parameters for the time-dependent temperature (base, amplitude, frequency, phase), and sets the simulation duration. ```python init_conc = defaultdict(lambda: 0*u.M, HNO2=1*u.M, H2O=55*u.M) params = dict( Tbase=300*u.K, Tamp=10*u.K, Tangvel=2*math.pi/(10*u.s), Tphase=-math.pi/2 ) duration = 60*u.s ``` -------------------------------- ### Get Native ODE System Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_demo.ipynb Obtains a native (compiled) version of the ODE system using the 'cvode' integrator from pyodesys. ```python nativesys = get_native(rsys, odesys, 'cvode') ``` -------------------------------- ### Create and Analyze Reaction System Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_demo.ipynb Initializes a ReactionSystem from a string and obtains an ODE system for integration. Displays the reaction system object. ```python rsys = ReactionSystem.from_string(system_str, name='Iron(II)/Iron(III) speciation') # "[H2O]" = 1.0 (actually 55.4 at RT) odesys, extra = get_odesys(rsys, SymbolicSys=ScaledSys, dep_scaling=1e6) rsys ``` -------------------------------- ### Set initial conditions and parameters for integration Source: https://github.com/bjodah/chempy/blob/master/examples/kinetics_ode_time_dependent.ipynb Defines the initial concentrations of species, parameters for the sinusoidal temperature (base, amplitude, angular velocity, phase), and the simulation duration. ```python init_conc = defaultdict(lambda: 0, HNO2=1, H2O=55) params = dict( Tbase=300, Tamp=10, Tangvel=2*math.pi/10, Tphase=-math.pi/2 ) duration = 60 ``` -------------------------------- ### Prepare Arguments for Original ODE System Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_ode_time_dependent_autonomous.ipynb Prepares the arguments for the original ODE system's callback functions using pre_process. ```python argsode = odesys.pre_process(*odesys.to_arrays(1, init_conc, params)) argsode ``` -------------------------------- ### Get symbolic form of equations with NumSysLin Source: https://github.com/bjodah/chempy/blob/master/examples/Ammonia.ipynb Generates the symbolic equations for the system using NumSysLin, which represents the system in a linear form. ```python numsys_lin = NumSysLin(eqsys, backend=sp) numsys_lin.f(y, i) ``` -------------------------------- ### Integrate System with Default First Step Source: https://github.com/bjodah/chempy/blob/master/examples/protein_binding_unfolding_4state_model.ipynb Integrates a system using a default first step size and a specified number of steps. Useful for standard integration tasks. ```python _ , _, info_tLA = integrate_and_plot(tsysLA, first_step=0.0) {k: info_tLA[k] for k in ('nfev', 'njev', 'n_steps')} ``` -------------------------------- ### Get Jacobian of the ODE system Source: https://github.com/bjodah/chempy/blob/master/examples/Robertson_kinetics.ipynb Computes and returns the Jacobian matrix of the ODE system. This is useful for stability analysis and numerical integration. ```python odesys.get_jac() ``` -------------------------------- ### Define initial conditions and parameter values Source: https://github.com/bjodah/chempy/blob/master/examples/_ode_system_sympy_symbols.ipynb Sets up the initial concentrations for substances and assigns numerical values to the symbolic parameters (K1, K3, R1f, R3f) for numerical integration. ```python c0 = {'E': 5, 'A': 2, 'P': 0, 'X': 0} params = {K1: 17, K3: 23, R1f: 63, R3f: 43} ``` -------------------------------- ### Create and display equilibrium system Source: https://github.com/bjodah/chempy/blob/master/examples/_FeSCN.ipynb Constructs an EqSystem object from the defined equilibria and substances. Displaying the object shows a summary of the system. ```python eqsys = chempy.equilibria.EqSystem(equilibria, substances) eqsys ``` -------------------------------- ### Extracting Non-Internal Info from Dictionary Source: https://github.com/bjodah/chempy/blob/master/examples/protein_binding_unfolding_4state_model.ipynb Filters a dictionary to exclude items with keys starting with 'internal'. Useful for cleaning up simulation results. ```python {k: v for k, v in info_native2.items() if not k.startswith('internal')} ``` -------------------------------- ### Get the ODE system from a reaction system Source: https://github.com/bjodah/chempy/blob/master/examples/_integrated.ipynb Generates the system of ordinary differential equations (ODEs) and additional information from a given reaction system. ```python odesys, extra = get_odesys(rsys) ``` -------------------------------- ### Create a reaction system from an equilibrium Source: https://github.com/bjodah/chempy/blob/master/examples/_integrated.ipynb Sets up a chemical reaction system using an Equilibrium object and converts it into reactions with specified rate constants. ```python eq = Equilibrium.from_string('Fe+3 + SCN- = FeSCN+2; 10**2.065') rsys = ReactionSystem(eq.as_reactions(kf=900)) rsys ``` -------------------------------- ### Prepare Arguments for Autonomous System Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_ode_time_dependent_autonomous.ipynb Initializes SymPy for pretty printing and prepares the arguments (state variables, parameters) for the autonomous system's callback functions using pre_process. ```python import sympy as sym sym.init_printing() args = _x, _y, _p = asys.pre_process(*asys.to_arrays(1, init_conc, params)) args ``` -------------------------------- ### Henry's Law Constant Calculation Source: https://github.com/bjodah/chempy/blob/master/README.rst Example of using the `chempy.henry.Henry` class to calculate the Henry's law constant at a specific temperature. ```python from chempy.henry import Henry kH_O2 = Henry(1.2e-3, 1800, ref='carpenter_1966') print('%.1e' % kH_O2(298.15)) 1.2e-03 ``` -------------------------------- ### Set Initial Concentrations and Parameters Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_ode_time_dependent_autonomous.ipynb Initializes the concentrations of species and defines the parameters for the reaction system, including thermodynamic and temperature-related values. Sets the simulation duration. ```python init_conc = defaultdict(lambda: 0, HNO2=1, H2O=55) params = dict( Tbase=300, Tamp=10, Tangvel=2*math.pi/10, Tphase=-math.pi/2, dH1=85e3, dS1=10, dH2=70e3, dS2=20 ) duration = 60 ``` -------------------------------- ### Create a ReactionSystem instance Source: https://github.com/bjodah/chempy/blob/master/examples/protein_binding_unfolding_4state_model.ipynb Constructs the complete ReactionSystem by combining the defined equilibria and reactions. It specifies forward and backward rate constants for reversible reactions and includes the irreversible aggregation reaction. ```python rsys = ReactionSystem( eq_dis.as_reactions(kb=kinetics_as, new_name='ligand-protein association') + eq_u.as_reactions(kb=kinetics_f, new_name='protein folding') + (r_agg,), substances, name='4-state CETSA system') ``` -------------------------------- ### Get and Print Analytic Solution Shape Source: https://github.com/bjodah/chempy/blob/master/chempy/kinetics/tests/_derive_analytic_cstr_bireac.ipynb Calculates the analytic solution using `get_analytic` and prints its shape. This is useful for verifying the dimensions of the analytic result. ```python yref = get_analytic(res) print(yref.shape) ``` -------------------------------- ### Define reaction parameters and create ReactionSystem Source: https://github.com/bjodah/chempy/blob/master/examples/_eyring_kinetics_ramped_temperature.ipynb Sets up physical constants and defines a chemical reaction system using the EyringParam model. This prepares the system for numerical integration. ```python R = 8.314472 T_K = 290 kB = 1.3806504e-23 h = 6.62606896e-34 dH = 80e3 dS = 10 rsys1 = ReactionSystem.from_string(""" NOBr -> NO + Br; EyringParam(dH={dH}*J/mol, dS={dS}*J/K/mol) """.format(dH=dH, dS=dS)) kref = 20836643994.118652*T_K*np.exp(-(dH - T_K*dS)/(R*T_K)) kref ``` -------------------------------- ### Prepare arguments for autonomous system evaluation Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_ode_time_dependent_autonomous_units.ipynb Initializes printing for symbolic math and prepares the arguments (state variables, parameters) needed to evaluate the autonomous system's functions (f and j) at a specific time point. ```python import sympy as sym sym.init_printing() args = _x, _y, _p = asys.pre_process(1*u.s, init_conc, params) args ``` -------------------------------- ### Integrate Scaled Linear Systems Source: https://github.com/bjodah/chempy/blob/master/examples/_switch_between_reduced_ode_systems.ipynb Integrates a list of scaled linear ODE systems. Requires prior setup of the systems using `symmetric_factory` and `from_other`. ```python stlogresults = integrate_systems(stlogsystems, nsteps=500) ``` -------------------------------- ### Set initial conditions and time Source: https://github.com/bjodah/chempy/blob/master/examples/_eyring_kinetics_2nd_order_reversible.ipynb Defines the initial concentrations of species and the time duration for the simulation. ```python Fe0 = 6e-3 SCN0 = 2e-3 init_cond = { 'Fe+3': Fe0*u.M, 'SCN-': SCN0*u.M, 'FeSCN+2': 0*u.M } t = 3*u.second ``` -------------------------------- ### Display initial concentrations Source: https://github.com/bjodah/chempy/blob/master/examples/Ammonia.ipynb Prints the dictionary containing the initial concentrations of all species in the system. ```python init_conc ``` -------------------------------- ### Get Jacobian from ODE System Source: https://github.com/bjodah/chempy/blob/master/examples/protein_binding_unfolding_4state_model.ipynb Computes and extracts the symbolic Jacobian matrix from an ODE system using sympy's cse for common subexpression elimination. ```python cses, (jac_in_cse,) = odesys.be.cse(odesys.get_jac()) jac_in_cse ``` -------------------------------- ### Define Eyring parameters and ReactionSystem Source: https://github.com/bjodah/chempy/blob/master/examples/_eyring_kinetics_2nd_order_reversible.ipynb Sets up physical constants and defines Eyring parameters (enthalpy and entropy of activation) for forward and backward reactions. Creates a ReactionSystem using these parameters. ```python R = 8.314472 T_K = 273.15 + 20 # 20 degree celsius kB = 1.3806504e-23 h = 6.62606896e-34 dHf = 74e3 dSf = R*np.log(h/kB/T_K*1e16) dHb = 79e3 dSb = dSf - 23 rsys1 = ReactionSystem.from_string(""" Fe+3 + SCN- -> FeSCN+2; EyringParam(dH={dHf}*J/mol, dS={dSf}*J/K/mol) FeSCN+2 -> Fe+3 + SCN-; EyringParam(dH={dHb}*J/mol, dS={dSb}*J/K/mol) """.format(dHf=dHf, dSf=dSf, dHb=dHb, dSb=dSb)) kf_ref = 20836643994.118652*T_K*np.exp(-(dHf - T_K*dSf)/(R*T_K)) kb_ref = 20836643994.118652*T_K*np.exp(-(dHb - T_K*dSb)/(R*T_K)) ``` -------------------------------- ### Set initial conditions and time span Source: https://github.com/bjodah/chempy/blob/master/examples/_eyring_kinetics_ramped_temperature_2nd_order.ipynb Defines the initial concentrations of reactants and products, and the total time for the simulation. ```python NO2_M = 1.0 init_cond = dict( NO2=NO2_M*u.M, N2O4=0*u.M ) t = 20*u.second ``` -------------------------------- ### Get Last Expression of Autonomous System Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_ode_time_dependent_autonomous.ipynb Retrieves the last expression from the autonomous system, which typically corresponds to the time derivative of the newly introduced state variable. ```python asys.exprs[-1] ``` -------------------------------- ### Prepare arguments for original ODE system evaluation Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_ode_time_dependent_autonomous_units.ipynb Prepares the arguments (state variables, parameters) for evaluating the original ODE system's functions at a specific time point. ```python argsode = odesys.pre_process(1*u.s, init_conc, params) argsode ``` -------------------------------- ### Import ChemPy and necessary libraries Source: https://github.com/bjodah/chempy/blob/master/examples/_FeSCN.ipynb Imports the ChemPy library along with numpy and matplotlib for numerical operations and plotting. It also prints the installed ChemPy version. ```python from collections import defaultdict import numpy as np import matplotlib.pyplot as plt %matplotlib inline import chempy from chempy.chemistry import Species, Equilibrium from chempy.equilibria import EqSystem print('ChemPy: %s' % chempy.__version__) ``` -------------------------------- ### Run simulation with MassAction(EyringHS.fk) and parameters Source: https://github.com/bjodah/chempy/blob/master/examples/_eyring_kinetics_2nd_order_reversible.ipynb Executes the simulation using the ReactionSystem defined with MassAction(EyringHS.fk), passing Eyring parameters as a dictionary. ```python integrate_and_plot(rsys3, dict(temperature=T_K*u.K, dHf=dHf*u.J/u.mol, dSf=dSf*u.J/u.mol/u.K, dHb=dHb*u.J/u.mol, dSb=dSb*u.J/u.mol/u.K)) ``` -------------------------------- ### Compare Integration Steps Source: https://github.com/bjodah/chempy/blob/master/examples/protein_binding_unfolding_4state_model.ipynb Compares the number of steps, function evaluations, and Jacobian evaluations for different integration approaches (root-finding vs. direct integration). ```python print(' root LA root+LA LN') for k in 'n_steps nfev njev'.split(): print(' '.join(map(str, (k, info_root[k], info_LA[k], info_root[k] + info_LA[k], info_LN[k])))) ``` -------------------------------- ### Integrate and Plot with Scaled System Source: https://github.com/bjodah/chempy/blob/master/examples/aqueous_radiolysis.ipynb A helper function to integrate and plot using a scaled ODE system. It simplifies the setup for simulations involving dependency scaling. ```python def integrate_and_plot_scaled(rsys, dep_scaling, *args, **kwargs): integrate_and_plot(get_odesys( rsys, SymbolicSys=ScaledSys, dep_scaling=dep_scaling)[0], *args, **kwargs) ``` -------------------------------- ### Import necessary libraries and set up display Source: https://github.com/bjodah/chempy/blob/master/examples/ammonical_cupric_solution.ipynb Imports core ChemPy modules, SymPy, Matplotlib, and defines a helper function for displaying LaTeX. ```python from collections import defaultdict from chempy import atomic_number from chempy.chemistry import Species, Equilibrium from chempy.equilibria import EqSystem, NumSysLin, NumSysLog, NumSysSquare from IPython.display import Latex, display import matplotlib.pyplot as plt %matplotlib inline def show(s): # convenience function display(Latex('$'+s+'$')) import sympy; import chempy; print('SymPy: %s, ChemPy: %s' % (sympy.__version__, chempy.__version__)) ``` -------------------------------- ### Get shape of reference solution array Source: https://github.com/bjodah/chempy/blob/master/examples/kinetics_cstr.ipynb Calculates the shape of the reference solution array obtained from the get_ref function, indicating the number of time points and dependent variables. ```python yref = get_ref(res) yref.shape ``` -------------------------------- ### Integrate systems with root return and continuation Source: https://github.com/bjodah/chempy/blob/master/examples/_switch_between_reduced_ode_systems.ipynb Integrates the system up to a root and then continues integration for another species ('C') from the state at the root. This is useful for analyzing specific events or transitions in the system. ```python res_A = rssys_A.integrate(indep_end, init_conc, return_on_root=True, **integrate_kw) res_C = psys[2].integrate(indep_end - res_A.xout[-1], res_A.yout[-1, :], **integrate_kw) ``` -------------------------------- ### Prepare simplified system for EqSystem Source: https://github.com/bjodah/chempy/blob/master/examples/ammonical_cupric_solution.ipynb Selects a subset of species and equilibria, replacing the original precipitation equilibria with the newly derived ones. It also adjusts the initial concentrations to match the simplified species list. ```python #skip_subs, skip_eq = (4, 4) # (0, 0), (1, 1), (3, 3), (4, 4), (11, 9) skip_subs, skip_eq = (1, 3) simpl_subs = substances[:-skip_subs] simpl_eq = equilibria[:-skip_eq] + new_eqs simpl_c0 = {k.name: init_conc[k.name] for k in simpl_subs} ``` -------------------------------- ### Set Initial Conditions and Solve ODE System Source: https://github.com/bjodah/chempy/blob/master/examples/_surface_reactions_homogeneous.ipynb Defines the initial concentrations of species, the simulation end time, and solves the ODE system using the 'cvode' integrator with specified rate constants. ```python c0 = defaultdict(lambda: 0*u.M, H2O2=.2*u.M, **{'vacancy(ads)': conc_vacancy}) tend = 3600*u.s result, result_extra = odesys_extra['unit_aware_solve']( (1e-7*u.s, tend), c0, dict( k_ads_H2O2=.1/u.M/u.s, k_split_H2O2ads=.2/u.M/u.s, k_abst_OHads_H2O2=.3/u.M/u.s, k_disprop_HO2=.4/u.M/u.s ), integrator='cvode' ) ``` -------------------------------- ### Get ODE system without parameters Source: https://github.com/bjodah/chempy/blob/master/examples/Robertson_kinetics.ipynb Generates the ODE system for the reaction system, excluding parameters and setting lower bounds for concentrations. Returns the ODE system and parameter information. ```python odesys3, extra3 = get_odesys(rsys3, include_params=False, lower_bounds=[0, 0, 0]) extra3['param_keys'], extra3['unique'] ``` -------------------------------- ### Define parameter variations for integration Source: https://github.com/bjodah/chempy/blob/master/examples/kinetics_decay_chain_units_varied_params.ipynb Prepares a dictionary of parameters for integration, specifically varying the 'Ea_R_2' parameter across a list of values. This setup is for exploring the sensitivity of the system to this particular parameter. ```python params2 = params.copy() pk = 'Ea_R_2' params2[pk] = [8.1e3, 8.2e3, 8.3e3]*u.K ``` -------------------------------- ### Initialize concentration and solve equilibrium system Source: https://github.com/bjodah/chempy/blob/master/examples/_carbon_dioxide.ipynb Initializes the concentration of species and sets up an equilibrium system. This snippet is commented out and requires adjustments for mass conservation of gases before it can be executed. ```python #init_conc = defaultdict(lambda: 0*u.molar, {'H2O': 55.5*u.molar, 'CO2(g)': 1*u.atm}) #eqsys = EqSystem(reactions, species) #eqsys # Before this works, mass conservation equations must be adjusted to deal with an "infinite" amount of gas: #eqsys.root(init_conc, state=298.15*u.K) ``` -------------------------------- ### Define substances for the four-state model Source: https://github.com/bjodah/chempy/blob/master/examples/protein_binding_unfolding_4state_model.ipynb Defines the chemical substances involved in the model, including their compositions and LaTeX names. This setup helps ChemPy enforce mass conservation and reduce ODE system unknowns. ```python substances = OrderedDict([ ('N', Substance('N', composition={'protein': 1}, latex_name='[N]')), ('U', Substance('U', composition={'protein': 1}, latex_name='[U]')), ('A', Substance('A', composition={'protein': 1}, latex_name='[A]')), ('L', Substance('L', composition={'ligand': 1}, latex_name='[L]')), ('NL', Substance('NL', composition={'protein': 1, 'ligand': 1}, latex_name='[NL]')) ]) ``` -------------------------------- ### Construct symbolic rates with SymPy Source: https://github.com/bjodah/chempy/blob/master/examples/Robertson_kinetics.ipynb Demonstrates constructing a ReactionSystem using symbolic rate constants defined with SymPy. It then generates the ODE system and prints its attributes. ```python # We could also have used SymPy to construct symbolic rates: import sympy rsys_sym = ReactionSystem.from_string(""" A -> B; sp.Symbol('k1') B + C -> A + C; sp.Symbol('k2') 2 B -> B + C; sp.Symbol('k3') """, rxn_parse_kwargs=dict(globals_={'sp': sympy}), substance_factory=lambda formula: Substance(formula)) odesys_sym, _ = get_odesys(rsys_sym, params=True) for attr in 'exprs params names param_names'.split(): print(getattr(odesys_sym, attr)) ``` -------------------------------- ### Instantiate species and reactions Source: https://github.com/bjodah/chempy/blob/master/examples/_carbon_dioxide.ipynb Creates Species objects from keys and Equilibrium objects from the defined reaction strings. Prints the string representation of each reaction. ```python species = [Species.from_formula(s) for s in species_keys] reactions = [Equilibrium.from_string(s, species_keys) for s in eq_str.split('\n')[1:-1]] print('\n'.join(map(str , reactions))) ``` -------------------------------- ### Get symbolic equations with reduced row echelon form and log system Source: https://github.com/bjodah/chempy/blob/master/examples/Ammonia.ipynb Generates the symbolic equations for the system using NumSysLog, with options enabled for reduced row echelon form (rref) and preserving equilibrium. ```python numsys_rref_log = NumSysLog(eqsys, True, True, backend=sp) numsys_rref_log.f(y, list(i)+list(K)) ``` -------------------------------- ### Integrate and Plot Apart Logarithmic Systems (Unscaled) Source: https://github.com/bjodah/chempy/blob/master/examples/_switch_between_reduced_ode_systems.ipynb Sets up and integrates unscaled linear ODE systems using `symmetric_factory(None)`, then plots the results. ```python ualogsystems = [LogLogSys_apart.from_other(ls, description='ual ' + ls.description) for ls in unscaled_linear] ualogresults = integrate_systems(ualogsystems, nsteps=500) plot_results(ualogsystems, ualogresults, vline_post_proc=lambda x: np.abs(np.exp(x) - indep0), xlim=[indep0*10, indep_end]) ``` -------------------------------- ### Integrate the ODE system numerically Source: https://github.com/bjodah/chempy/blob/master/examples/_ode_system_sympy_symbols.ipynb Performs numerical integration of the ODE system over a specified time span (implicitly from 0 to 42) starting from the initial conditions `c0` and using the provided `params`. It specifies 'cvode' as the integration method. ```python result = odesys.integrate(42, c0, params, integrator='cvode') ``` -------------------------------- ### Instantiate the reaction system Source: https://github.com/bjodah/chempy/blob/master/examples/_ode_system_sympy_symbols.ipynb Creates an instance of the defined reversible reaction system. ```python rsys = mono_rev_single() ``` -------------------------------- ### Calculate Water Density using ChemPy Source: https://github.com/bjodah/chempy/blob/master/README.rst Demonstrates how to use the `water_density_tanaka_2001` parametrization to calculate the concentration of H2O at different temperatures. Requires importing `Substance`, the density function, and unit conversion utilities. ```python >>> from chempy import Substance >>> from chempy.properties.water_density_tanaka_2001 import water_density as rho >>> from chempy.units import to_unitless, default_units as u >>> water = Substance.from_formula('H2O') >>> for T_C in (15, 25, 35): ... concentration_H2O = rho(T=(273.15 + T_C)*u.kelvin, units=u)/water.molar_mass(units=u) ... print('[H2O] = %.2f M (at %d °C)' % (to_unitless(concentration_H2O, u.molar), T_C)) ... [H2O] = 55.46 M (at 15 °C) [H2O] = 55.35 M (at 25 °C) [H2O] = 55.18 M (at 35 °C) ``` -------------------------------- ### Define integration parameters and helper functions Source: https://github.com/bjodah/chempy/blob/master/examples/_switch_between_reduced_ode_systems.ipynb Sets up common keyword arguments for ODE integration and defines helper functions for integrating multiple systems and formatting integration results. ```python indep_end = 1e18 init_conc = {'A': 1, 'B': 0, 'C': 0} integrate_kw = dict(integrator='cvode', atol=1e-6, rtol=1e-6, nsteps=5000, record_rhs_xvals=True, record_jac_xvals=True) def integrate_systems(systems, **kwargs): for k, v in integrate_kw.items(): if k not in kwargs: kwargs[k] = v return [odesys.integrate(indep_end, init_conc, record_order=True, record_fpe=True, return_on_error=True, **kwargs) for odesys in systems] def descr_str(info): keys = 'n_steps nfev time_cpu success'.split() if isinstance(info, dict): nfo = info else: nfo = {} for d in info: for k in keys: if k in nfo: if k == 'success': nfo[k] = nfo[k] and d[k] else: nfo[k] += d[k] else: nfo[k] = d[k] return ' (%d steps, %d rhs evals., %.5g s CPUt)' % tuple([nfo[k] for k in keys[:3]]) + ( '' if nfo['success'] else ' - failed!') def plot_result(description, res, ax=None, vline_post_proc=None, colors=('k', 'r', 'g'), xlim=None): if ax is None: ax = plt.subplot(1, 1, 1) vk = 'steps rhs_xvals jac_xvals'.split() # 'fe_underflow fe_overflow fe_invalid fe_divbyzero' res.plot(xscale='log', yscale='log', ax=ax, c=colors, info_vlines_kw=dict(vline_keys=vk, post_proc=vline_post_proc)) lines = ax.get_lines() for idx, val in enumerate([1 - 0.04*1e-7, 0.04*1e-7]): ax.plot(1e-7, val, marker='o', c=colors[idx]) for idx, val in enumerate([0.2083340149701255e-7, 0.8333360770334713e-13, 0.9999999791665050]): ax.plot(1e11, val, marker='o', c=colors[idx]) ax.legend(loc='best') ax.set_title(description + descr_str(res.info)) if xlim is not None: ax.set_xlim(xlim) def plot_results(systems, results, axes=None, **kwargs): if axes is None: _fig, axes = plt.subplots(2, 2, figsize=(14, 14)) for idx, (odesys, res) in enumerate(zip(systems, results)): plot_result(odesys.description, res, ax=axes.flat[idx], **kwargs) ``` -------------------------------- ### Define Thermodynamic Parameters Source: https://github.com/bjodah/chempy/blob/master/examples/protein_binding_unfolding_4state_model.ipynb Sets up a dictionary of thermodynamic parameters, including gas constant, Boltzmann constant, Planck's constant, and specific enthalpy, entropy, and heat capacity values for different processes (dissociation, unfolding, aggregation, etc.). Includes a reference temperature. ```python import math from collections import defaultdict defaul_c0 = defaultdict(float, {'N': 1e-9, 'L': 1e-8}) params = dict( R=8.314472, # or N_A & k_B k_B=1.3806504e-23, h=6.62606896e-34, # k_B/h == 2.083664399411865e10 K**-1 * s**-1 He_dis=-45e3, Se_dis=-400, Cp_dis=1.78e3, Tref_dis=298.15, He_u=60e3, Cp_u=20.5e3, Tref_u=298.15, Ha_agg=106e3, Sa_agg=70, Ha_as=4e3, Sa_as=-10, Ha_f=90e3, Sa_f=50, temperature=50 + 273.15 ) ``` -------------------------------- ### Define physical constants and reaction system (EyringParam) Source: https://github.com/bjodah/chempy/blob/master/examples/_eyring_kinetics_ramped_temperature_2nd_order.ipynb Sets up physical constants and defines a ReactionSystem for the dimerization of NO2 to N2O4 using EyringParam for rate determination. ```python R = 8.314472 T_K = 290 dTdt_Ks = 3 kB = 1.3806504e-23 h = 6.62606896e-34 dH = 80e3 dS = 10 rsys1 = ReactionSystem.from_string(""" 2 NO2 -> N2O4; EyringParam(dH={dH}*J/mol, dS={dS}*J/K/mol) """.format(dH=dH, dS=dS)) ``` -------------------------------- ### Solve system with custom initial guess Source: https://github.com/bjodah/chempy/blob/master/examples/Ammonia.ipynb Solves the equilibrium system using the 'root' method, providing a custom initial guess (x0) for the concentrations. ```python x, res, sane = eqsys.root(init_conc, x0=eqsys.as_per_substance_array( {'H+': 1e-11, 'OH-': 1e-3, 'NH4+': 1e-3, 'NH3': 1.0, 'H2O': 55.5})) res['success'], sane ``` -------------------------------- ### Set initial concentrations and plot results Source: https://github.com/bjodah/chempy/blob/master/examples/_integrated.ipynb Initializes concentrations for the reaction species and calls the plot_against_analytic function to visualize the numerical and analytical solutions. ```python conc = {'Fe+3': 10e-3, 'SCN-': 2e-3, 'FeSCN+2': 2e-4} plot_against_analytic(odesys, conc) ``` -------------------------------- ### Compare Integration Times Source: https://github.com/bjodah/chempy/blob/master/examples/protein_binding_unfolding_4state_model.ipynb Compares the wall-clock time taken by the pure Python integration versus the native C++ extension integration, highlighting the performance improvement. ```python info['time_wall']/info_native['time_wall'] ``` -------------------------------- ### Inspect ReactionSystem class Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_radiolysis_analytic.ipynb Displays the docstring for the ReactionSystem class to understand its usage. ```python ReactionSystem? ``` -------------------------------- ### Load and Preprocess Experimental Data Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetic_model_fitting.ipynb Loads experimental data from a bz2 compressed JSON file, transforms time and absorbance values, and organizes it into a dictionary keyed by ionic strength and temperature. ```python transform = np.array([[1e-3, 0], [0, 1e-4]]) # converts 1st col: ms -> s and 2nd col to absorbance _reader = codecs.getreader("utf-8") _dat = {tuple(k): np.dot(np.array(v), transform) for k, v in json.load(_reader(bz2.BZ2File('specdata.json.bz2')))} data = collections.defaultdict(list) for (tI, tT, tR), v in _dat.items(): k = (tI, tT) # tokens for ionic strength and temperatures data[k].append(v) assert len(data) == len(ionic_strengths)*len(temperatures) and all(len(serie) == nrep for serie in data.values()) ``` -------------------------------- ### Generate ODE System (Commented Out) Source: https://github.com/bjodah/chempy/blob/master/examples/_arrhenius_kinetics.ipynb This commented-out code shows how to generate an ODE system from the reaction system, which would typically be used for dynamic simulations. ```python # Still failing #odesys = get_odesys(rsys, units=SI_base_registry)[0] ``` -------------------------------- ### Simplify Initial Conditions with Solved Constants Source: https://github.com/bjodah/chempy/blob/master/chempy/kinetics/tests/_derive_analytic_cstr_bireac.ipynb Simplifies the expressions for the initial conditions after substituting the solved integration constants. ```python [expr.subs(t, 0).simplify() for expr in exprs2] ``` -------------------------------- ### Define Species and Reaction System for Surface Reactions Source: https://github.com/bjodah/chempy/blob/master/examples/_surface_reactions_homogeneous.ipynb Sets up a reaction system with species defined in different phases (aqueous and adsorbed) and a factory function to handle species creation, including adsorbed species and vacancies. ```python ads_token = '(ads)' phases = {'(aq)': 0, ads_token: 1} ads_comp = -1 vacancy = Species('vacancy(ads)', composition={ads_comp: 1}, phase_idx=phases[ads_token], latex_name='vacancy(ads)') def substance_factory(name): if name == vacancy.name: return vacancy s = Species.from_formula(name, phases=phases) if name.endswith(ads_token): s.composition[ads_comp] = 1 return s rsys = ReactionSystem.from_string(""" vacancy(ads) + H2O2 -> H2O2(ads); 'k_ads_H2O2' H2O2(ads) + vacancy(ads) -> 2 OH(ads); 'k_split_H2O2ads' OH(ads) + H2O2 -> H2O + HO2 + vacancy(ads); 'k_abst_OHads_H2O2' HO2 + HO2 -> O2 + H2O2; 'k_disprop_HO2' """, substance_factory=substance_factory) rsys ``` -------------------------------- ### Set initial concentrations, parameters, and duration Source: https://github.com/bjodah/chempy/blob/master/examples/_kinetics_ode_time_dependent_autonomous_units.ipynb Defines the initial concentrations of species, reaction parameters (including those for the temperature function and rate laws), and the simulation duration. Units are handled using the chempy unit registry. ```python init_conc = defaultdict(lambda: 0*u.M, HNO2=1*u.M, H2O=55*u.M) params = dict( Tbase=300*u.K, Tamp=10*u.K, Tangvel=2*math.pi/(10*u.s), Tphase=-math.pi/2, dH1=85e3*u.J/u.mol, dS1=10*u.J/u.K/u.mol, dH2=70e3*u.J/u.mol, dS2=20*u.J/u.K/u.mol ) duration = 60*u.s ``` -------------------------------- ### Set initial conditions and time for integration Source: https://github.com/bjodah/chempy/blob/master/examples/_eyring_kinetics_ramped_temperature.ipynb Defines the initial concentrations of species and the total time for the reaction simulation. Units are handled using ChemPy's unit registry. ```python NOBr0_M = 0.7 init_cond = dict( NOBr=NOBr0_M*u.M, NO=0*u.M, Br=0*u.M ) t = 20*u.second ``` -------------------------------- ### Simplify a thermodynamic parameter Source: https://github.com/bjodah/chempy/blob/master/examples/_Expr_custom_Gibbs_kinetics_odesys.ipynb Demonstrates simplifying a thermodynamic parameter `dCp_R` and accessing its simplified form. ```python dCp_R = 18.8*u.cal/u.K/u.mol/dc.molar_gas_constant dCp_R, dCp_R.simplified ``` -------------------------------- ### Assert and display ODE system parameters Source: https://github.com/bjodah/chempy/blob/master/examples/_ode_system_sympy_symbols.ipynb Asserts that the ODE system has exactly 4 parameters and then displays these symbolic parameters. ```python assert len(odesys.params) == 4 odesys.params ``` -------------------------------- ### Create Partially Solved System (Alternative Invariants) Source: https://github.com/bjodah/chempy/blob/master/examples/protein_binding_unfolding_4state_model.ipynb Creates a PartiallySolvedSystem using a different set of linear invariants ('L', 'A') to demonstrate flexibility in system reduction. Prints the simplified Jacobian. ```python psysLA = PartiallySolvedSystem(odesys, extra['linear_dependencies'](['L', 'A']), **no_invar) print(psysLA.be.cse(psysLA.get_jac())[1][0]) psysLA['L'], psysLA.jacobian_singular() ``` -------------------------------- ### Import necessary ChemPy classes Source: https://github.com/bjodah/chempy/blob/master/examples/NaCl_precipitation.ipynb Imports the Species, Equilibrium, and EqSystem classes from ChemPy for setting up chemical systems. ```python from chempy.chemistry import Species from chempy.equilibria import EqSystem from chempy.equilibria import Equilibrium ```