Skip to content

Instantly share code, notes, and snippets.

@thomasaarholt
Created December 14, 2020 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasaarholt/bb31e72882efc78b66c5936c4febaf36 to your computer and use it in GitHub Desktop.
Save thomasaarholt/bb31e72882efc78b66c5936c4febaf36 to your computer and use it in GitHub Desktop.
Example of using IndexedBase in order to do for loops in Sympy for memory conservation
import sympy as sp
import matplotlib.pyplot as plt
import numpy as np
def Gaussian(x, a, xc, sigma):
return a*sp.exp(-((x-xc)**2)/(2*sigma**2))
x, i, n = sp.symbols('x i n') # x is our main independent variable. i and n are indices
a, xc, sigma = sp.symbols('A xc sigma', cls=sp.IndexedBase) # parameters that are held in arrays
symbols = (x, a, xc, sigma, n)
Gauss = Gaussian(x, a[i], xc[i], sigma[i])
model = sp.Sum(Gauss, (i, 0, n-1)) # Sum over the parameters from (i=0 to i=n)
func = sp.lambdify(symbols, model, modules = 'numpy')
X = np.arange(100)
N = 10
A, XC, SIGMA = np.random.random((3, N))*100
y = func(X, A, XC, SIGMA, N)
plt.figure()
plt.plot(y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment