Created
December 14, 2020 19:05
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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