Let (cos(x)exp(x)) be any simpy function. I want to change the sympy function into the function (a*cos(x) exp(x)+b) and fit the parameters (a,b) to data.
I don't now, if there is a direct way, to fit a sympy function. The pip package symfit 0.2.3 is not working (https://symfit.readthedocs.io/en/stable/tutorial.html) - there is an error when trying to import parts of the packages.
One can use the sympy function lambdify to create a numpy function like this
from sympy import symbols
from sympy import cos, exp
from sympy import lambdify
x = symbols('x')
python_formula = lambdify(x,cos(x)*exp(x), 'numpy')
I would now multiply my parameters like
def function(x,a,b,python_formula):
return a*python_formula(x) +b
Unfortunately, if I use scipy.optimize.curve_fit like
optimizedParameters, pcov = opt.curve_fit(function, x_data, y_data);
it will take the "python_formula" argument in my function as an optimizable parameter and will crash. I also did not find a way, to specify the fit parameter
(https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html).
If you have an idea, how to generally fit a sympy function or a way to fix the code, I would be thankful to hear it.
You need to use a function factory, so that the lambdified function is bound at the moment of the definition and not when your script is sourced
from sympy import symbols
from sympy import cos, exp
from sympy import lambdify
from scipy.optimize import curve_fit
### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
def make_f2opt(lambdified):
return lambda x, a, b: a*lambdified(x)+b
### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
x = symbols('x')
python_formula = lambdify(x,cos(x)*exp(x), 'numpy')
### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
f2opt = make_f2opt(python_formula)
### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
parameter, covariance = curve_fit(f2opt, x_data, y_data)
Related
Good day Everyone, I'm new there hope someone will guide me and help me with my query.
is there away to plot the wave of signal using python? i have 9 points of frequency an power and i want it plot it using python v3.6.
i found some recourse like here and here and here and here i have try the code in below , but i want the graph shows as wave not in same that way. any suggest ?
code is :
# importing the required module
import matplotlib.pyplot as plt
# x axis values
x = [54,58,61,62,64,65,66,69,72] # frequency
# corresponding y axis values
y = [2,2.5,4,3,2.5,3.5,4.5,3,2] # Power
# plotting the points
plt.plot(x, y)
# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
# giving a title to my graph
plt.title('My first graph!')
# function to show the plot
plt.show()
code of sin-wave, how i modify the code in below to assign the value of frequency and power as : freq = [54,58,61,62,64,65,66,69,72] # frequency and Power = [2,2.5,4,3,2.5,3.5,4.5,3,2] # Power
import numpy as np
import matplotlib
matplotlib.use('TKAgg') #use matplotlib backend TkAgg (optional)
import matplotlib.pyplot as plt
sample_rate = 200 # sampling frequency in Hz (atleast 2 times f)
t = np.linspace(0,5,sample_rate) #time axis
f = 100 #Signal frequency in Hz
sig = np.sin(2*np.pi*f*(t/sample_rate))
plt.plot(t,sig)
plt.xlabel("Time")
plt.ylabel("Amplitude")
plt.tight_layout()
plt.show()
I have the following signal and I want to do the following:
s= 4*np.cos(4*np.pi*pow(10,6)*t+30)+2*np.sin(8*np.pi*pow(10,6)*t+15)+np.cos(12*np.pi*pow(10,6)*t)+0.5*np.cos(16*np.pi*pow(10,6)*t) # the signal
I want to draw signal spectrum using matplotlib and numpy,
the find its bandwidth and determine if it's periodic or not
I use this code available here(https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/spectrum_demo.html)
thanks for helping
I am not 100% sure if I now what you want to do but it seems plotting and returning all the turning points of your function should help you a lot with your problem.
Therefore you may try this:
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import argrelextrema
def func(t):
# messures the time in units of
# pow(10,6)*t
exp = 4*np.cos(4*np.pi*t+30)+\
2*np.sin(8*np.pi*t+15)+\
np.cos(12*np.pi*t)+\
0.5*np.cos(16*np.pi*t)
return exp
max_time = 2
time_steps = 400
# defining the signal
X = np.linspace(0,max_time,time_steps)
Y = func(X)
# getting all the max and min values
minimas = argrelextrema(Y, np.less)
maximas = argrelextrema(Y, np.greater)
# plot the singal
plt.plot(X,Y)
# plot minimas and maximas
plt.scatter(X[minimas],Y[minimas],color='r')
plt.scatter(X[maximas],Y[maximas],color='g')
plt.xlabel('t*10**6')
plt.ylabel('signal')
plt.show()
This code is designed for calculating a linear regression by defining a function "standRegres" which compile by ourself. Although we can do the lm by the functions in sklearn or statsmodels, here we just try to construct the function by ourself. But unfortunately, I confront error and can't conquer it. So, I'm here asking for your favor to help.
The whole code runs without any problem until the last row. If I run the last row, an Error message emerges: "ValueError: ndarray is not contiguous".
import os
import pandas as pd
import numpy as np
import pylab as pl
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
# load data
iris = load_iris()
# Define a DataFrame
df = pd.DataFrame(iris.data, columns = iris.feature_names)
# take a look
df.head()
#len(df)
# rename the column name
df.columns = ['sepal_length','sepal_width','petal_length','petal_width']
X = df[['petal_length']]
y = df['petal_width']
from numpy import *
#########################
# Define function to do matrix calculation
def standRegres(xArr,yArr):
xMat = mat(xArr); yMat = mat(yArr).T
xTx = xMat.T * xMat
if linalg.det(xTx) == 0.0:
print ("this matrix is singular, cannot do inverse!")
return NA
else :
ws = xTx.I * (xMat.T * yMat)
return ws
# test
x0 = np.ones((150,1))
x0 = pd.DataFrame(x0)
X0 = pd.concat([x0,X],axis = 1)
# test
standRegres(X0,y)
This code runs without any problem until the last row. If I run the last row, an Error message emerges: "ValueError: ndarray is not contiguous".
I dry to solve it but don't know how. Could you help me? Quite appreciate for that!
Your problem stems from using the mat function. Stick to array.
In order to use array, you'll need to use the # sign for matrix multiplication, not *. Finally, you have a line that says xTx.I, but that function isn't defined for general arrays, so we can use numpy.linalg.inv.
def standRegres(xArr,yArr):
xMat = array(xArr); yMat = array(yArr).T
xTx = xMat.T # xMat
if linalg.det(xTx) == 0.0:
print ("this matrix is singular, cannot do inverse!")
return NA
else :
ws = linalg.inv(xTx) # (xMat.T # yMat)
return ws
# test
x0 = np.ones((150,1))
x0 = pd.DataFrame(x0)
X0 = pd.concat([x0,X],axis = 1)
# test
standRegres(X0,y)
# Output: array([-0.36651405, 0.41641913])
hey I'm trying to get matplotlib.animation to plot n plots in one graph like the first code block below, but when I run the script everything seems to run except none of the plots show up.
import matplotlib.pyplot as plt
# Data to be ploted
x = []
y = []
x2 = []
y2 = []
for i in range(-9,9):
x.append(i)
y.append(i**2)
x2.append(i)
y2.append(i**3)
# plot the data
plt.plot(x,y, label = 'first line')
# plot other data points
plt.plot(x2,y2, label = 'second line')
# add this before plt.show() to add labels to graph
plt.xlabel('X value')
plt.ylabel('Y value')
# add a title to graph
plt.title('interesting graph\nsubtitle')
plt.legend()
plt.show()
here is the code using animate:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
# better face
style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def anima(i):
graph_data = open('a.txt').read()
lines = graph_data.split('\n')
dataPoints = []
for i in lines:
# ignor empty lines
if len(i) > 1:
line = i.split('|') # delimiter is |
for a in range(len(line)):
try:
dataPoints[a].append(int(line[a]))
# if there is no dataPoint[a] it gets created
except:
dataPoints.append(int(line[a]))
# modify axis
ax1.clear()
# plot
for i in range(len(dataPoints)-1):
ax1.plot(dataPoints[1],dataPoints[i+1])
#where to animate, what to animate, how often to update
ani = animation.FuncAnimation(fig, anima, interval = 1000)
plt.show()
in a.txt I have this:
1|56|80|62
2|123|135|55
12|41|12|23
60|12|45|23
12|43|56|54
25|123|23|31
2|213|31|84
61|1|68|54
62|2|87|31
63|4|31|53
64|8|13|13
65|16|51|65
66|32|43|84
80|62|42|15
update:
I gave up on reading a file and am having a threaded function generate values for me and instead for having everything in one plot I am having everything in subplots(the number is going to be edited soon). when I run the code with a normal plot it works fine, but when I try to use animate... it shows the graphs but no plot once again. my problem is showing the animated plot
# check if os is linux
import platform
if str(platform.system()).lower() == str('linux').lower():
# must be set befor importing any other matplotlib
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from threading import Thread
# Change style
style.use('fivethirtyeight')
fig = plt.figure()
#list with all datapoints eg: [timeList],[graph1List]....
data_points = []
# 'name' of each graph in the list
graphs_ = [0]
def create_plots():
xs = []
ys = []
for i in range(-10,11):
x = i
y = i**3
xs.append(x)
ys.append(y)
data_points.append(xs)
data_points.append(ys)
t = Thread(target=create_plots)
t.start()
def anima(i):
for i in range(len(graphs_)):
graphs_[i]=fig.add_subplot(211+i)
graphs_[i].clear()
graphs_[i].plot(0,i+1)
while len(data_points) == 0:
print('.')
ani = animation.FuncAnimation(fig, anima, interval=1000)
plt.show()
1) Are you sure your anima(i) function gets called?
2) Why are you overwriting the variable i in anima(i) and again in line?
for i in lines:
# ignor empty lines
In command line, I want to give python hist.py -n 1000 -o /dir and output will be png in the assigning directory. Can anyone help on it?
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import argparse
import os, sys, errno
def plotData(outputDir):
outFilename = "hist.pdf"
outFilepath = os.path.join(outputDir)
parser = argparse.ArgumentParser()
parser.add_argument("-n","--number", help="display a square of a given number",type=int)
parser.add_argument('-o', '--outputDir', required=True,
help='The directory to which plot files should be saved')
args = parser.parse_args()
num=(args.number)
outFilepath=(args.outputDir)
# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
#num=input()
x = mu + sigma * np.random.randn(int(num))
num_bins = 50
# the histogram of the data
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
plt.plot(bins, y, 'r--')
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')
# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)
plt.savefig (outFilepath,outFilename)
plt.show()
plt.close()
I could give random variable but not directory from terminal command line.
I have used args.outputDir but it does not work for me.
and i am learners