Note
Go to the end to download the full example code or to run this example in your browser via Binder.
Exporting equations to code, spreadsheets and PMML#
A discovered equation is small enough to run anywhere: in a PLC, a spreadsheet,
a simulator or a scoring engine. eqdisco.export writes it as Python, C,
MATLAB/Octave or Julia source, as an Excel formula, as LaTeX, and as a PMML 4.4
document. With protected=True the code reproduces the protected operators of
eqdisco exactly; this example verifies that the generated Python and NumPy code
predict the same values as the equation itself.
import matplotlib.pyplot as plt
import numpy as np
import eqdisco as eq
from eqdisco import export
rng = np.random.default_rng(0)
X = rng.uniform(0.5, 3, (200, 2))
y = 2.5 * X[:, 0] * np.exp(-0.3 * X[:, 1]) - np.log(X[:, 1]) + 0.01 * rng.normal(size=200)
model = eq.SymbolicRegressor(population_size=300, generations=25, functions=("add", "sub", "mul", "div", "exp", "log"), optimize="lm", feature_names=["flow", "time"], random_state=0).fit(X, y)
eqn = eq.simplify.simplify(model.equation_, X, y, refit=True)
Source code and formulas#
print(export.to_python(eqn, name="yield_model"))
print(export.to_c(eqn, name="yield_model"))
print(export.to_excel(eqn, {"flow": "B2", "time": "C2"}))
print(export.to_latex(eqn, lhs="Y"))
pmml = export.to_pmml(eqn, target="yield")
print(pmml.count("<Apply"), "Apply elements in the PMML document")
import math
def _pdiv(a, b):
return a / b if abs(b) > 1e-10 else 1.0
def _plog(a):
return math.log(abs(a)) if abs(a) > 1e-300 else 0.0
def _ppow(a, b):
return abs(a) ** b if a != 0 else 0.0
def yield_model(flow, time):
return -0.16363091785454678 * ((time - flow + (-3.6982947133137816)) * (_plog(time + 0.5838449022547934 * flow + 1) + _plog(1.5468294899394592 * _pdiv(flow, time))) + (-1.3840376375425658 * time + 7.020953136898399) * (time - flow) + time - _plog(-3.405173958607722 * (time + 0.6800228429502003) + 0.4777947390726642 * (math.exp(min(time, 100.0))))) + 0.9566686418082396
#include <math.h>
static double pdiv(double a, double b) { return fabs(b) > 1e-10 ? a / b : 1.0; }
static double plog(double a) { return fabs(a) > 1e-300 ? log(fabs(a)) : 0.0; }
double yield_model(double flow, double time)
{
return -0.16363091785454678 * ((time - flow + (-3.6982947133137816)) * (plog(time + 0.5838449022547934 * flow + 1.0) + plog(1.5468294899394592 * pdiv(flow, time))) + (-1.3840376375425658 * time + 7.020953136898399) * (time - flow) + time - plog(-3.405173958607722 * (time + 0.6800228429502003) + 0.4777947390726642 * (exp(fmin(time, 100.0))))) + 0.9566686418082396;
}
=-0.163630917854547*((C2-B2+(-3.69829471331378))*((IF(ABS((C2+0.583844902254793*B2+1))>0,LN(ABS((C2+0.583844902254793*B2+1))),0))+(IF(ABS((1.54682948993946*(IF(ABS(C2)>1E-10,B2/C2,1))))>0,LN(ABS((1.54682948993946*(IF(ABS(C2)>1E-10,B2/C2,1))))),0)))+(-1.38403763754257*C2+7.0209531368984)*(C2-B2)+C2-(IF(ABS((-3.40517395860772*(C2+0.6800228429502)+0.477794739072664*(EXP(MIN(C2,100)))))>0,LN(ABS((-3.40517395860772*(C2+0.6800228429502)+0.477794739072664*(EXP(MIN(C2,100)))))),0)))+0.95666864180824
Y = - 0.1636 time - 0.1636 \left(7.021 - 1.384 time\right) \left(- flow + time\right) - 0.1636 \left(\log{\left(\frac{1.547 flow}{time} \right)} + \log{\left(0.5838 flow + time + 1 \right)}\right) \left(- flow + time - 3.698\right) + 0.1636 \log{\left(- 3.405 time + 0.4778 e^{time} - 2.316 \right)} + 0.9567
52 Apply elements in the PMML document
Verifying the generated code#
namespace = {}
exec(export.to_python(eqn, name="f_py"), namespace) # code written by eqdisco itself
exec(export.to_python(eqn, name="f_np", numpy=True), namespace)
ref = eqn.predict(X)
py = np.array([namespace["f_py"](*row) for row in X])
vec = namespace["f_np"](X[:, 0], X[:, 1])
print(f"largest difference from eqdisco: Python {np.max(np.abs(py - ref)):.1e}, NumPy {np.max(np.abs(vec - ref)):.1e}")
fig, ax = plt.subplots(figsize=(4.5, 3.2))
ax.semilogy(np.sort(np.abs(py - ref) + 1e-17), color="#285780", label="Python (math)")
ax.semilogy(np.sort(np.abs(vec - ref) + 1e-17), color="#D55E00", label="NumPy")
ax.set_xlabel("sample (sorted by error)")
ax.set_ylabel("|generated code - eqdisco|")
ax.legend(frameon=False, fontsize=8)

largest difference from eqdisco: Python 0.0e+00, NumPy 0.0e+00
<matplotlib.legend.Legend object at 0x72b452198f50>
Parameter study: protected or plain operators#
Plain operators give the textbook formula; they differ from eqdisco only where a protected operator acts (division by ~0, logarithm of a negative number).
Xbad = np.column_stack([np.linspace(-1, 3, 50), np.linspace(-1, 3, 50)])
ns_plain = {}
exec(export.to_python(eqn, name="g", protected=False, numpy=True), ns_plain)
with np.errstate(all="ignore"):
plain = ns_plain["g"](Xbad[:, 0], Xbad[:, 1])
print("rows where plain and protected operators differ:", int(np.sum(~np.isclose(plain, eqn.predict(Xbad), equal_nan=False))), "of", len(Xbad))
fig, ax = plt.subplots(figsize=(4.5, 3.2))
ax.plot(Xbad[:, 1], eqn.predict(Xbad), color="#285780", lw=2, label="protected (eqdisco)")
ax.plot(Xbad[:, 1], plain, color="#D55E00", ls="--", label="plain operators")
ax.set_xlabel("time (also outside the data range)")
ax.legend(frameon=False, fontsize=8)
plt.show()

rows where plain and protected operators differ: 50 of 50
Total running time of the script: (0 minutes 8.788 seconds)