Skip to content

stevenshave/MathematicaEquationToPython

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 

Repository files navigation

MathematicaEquationToPython

A python program to parse lists of Mathematica CForm equations and produce python functions

My work often involves the derivation of high order multicomponent protein/ligand/dna binding equations with multiple solutions. Converting these equations, even using Mathematica's CForm conversion routines becomes combersome with large formulas of > 100s-1000s of lines.

This program allows the direct conversion of mathematica CForm expressions containing lists of solutions to python functions for inclusion in other programs.

Example usage

A trivial example is simple 1:1 binding, in a protein + ligand system, where ligand binds to protein with a known KD (dissociation constant).

We can derive the equation for this in Mathematica as follows:

eqtn = {
   a == af + ax,
   x == xf + ax,
   ax*kdax == af*xf,
    y == (x - xf)/x};
toEliminate = {af, xf, ax}
Export["mme_a,x,ax__ax_x.txt", 
 CForm[y /. Solve[Simplify[Eliminate[eqtn, toEliminate]], y]]]

This writes a CForm expression containing two solutions as bellow:

List((a + kdax + x - Sqrt(-4*a*x + Power(a + kdax + x,2)))/(2.*x),(a + kdax + x 
+ Sqrt(-4*a*x + Power(a + kdax + x,2)))/(2.*x))

To a file named "mme_a,x,ax__ax_x.txt". Named in this way as a conventient convention describing the model system. Whereby "mme" stands for Mathematica Equation, "a,x,ax" shows which species can be present, and "__ax_x" denotes the readout/result is a fraction of x in complex with ax (interpret as ax/x).

Conversion of this file into a python file containing callable functions can be achieved as follows:

./mathematicaCFormToPython.py mme_a,x,ax__ax_x.txt mme_a,x,ax__ax_x.py

Resulting in a python file containing:

# Auto generated by MathematicaEquationToPython
# https://github.com/stevenshave/MathematicaEquationToPython

__license__ = "MIT"
import numpy as np
def eqtn0(a,x,kdax):
	return (a+kdax+x-np.lib.scimath.sqrt(-4*a*x+np.power(a+kdax+x,2)))/(2.*x)
def eqtn1(a,x,kdax):
	return (a+kdax+x+np.lib.scimath.sqrt(-4*a*x+np.power(a+kdax+x,2)))/(2.*x)

About

A python program to parse lists of Mathematica CForm equations and produce python functions

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages