I have following lines of code working fine when inputs given in console:
import numpy as np
def simple_exponential_smoothing(actuals, n_forecast_periods,alpha):
return np.array([np.array([alpha*((1-alpha)**k)*actuals[len(actuals)-k-1] for k in range (len(actuals))]).sum()]*n_forecast_periods)
simple_exponential_smoothing(actuals, n_forecast_periods,alpha)
However, it doesn't work when try to get same user inputs in code itself:
import numpy as np
actuals = []
actuals = input("Input list:")
n_forecast_periods = int(input("Int:"))
alpha = float(input("float:"))
def simple_exponential_smoothing(actuals, n_forecast_periods,alpha):
return np.array([np.array([alpha*((1-alpha)**k)*actuals[len(actuals)-k-1] for k in range (len(actuals))]).sum()]*n_forecast_periods)
simple_exponential_smoothing(actuals, n_forecast_periods,alpha)
Apologize, if this is not a good question. I am new to Python.
I have already tried using map function for multiplication; too complex for me to use it in following setup.
Related
I'm relatively new to Sympy and had a lot of trouble with the information that I was able to scavenge on this site. My main goal is basically to take a string, representing some mathematical expression, and then save an image of that expression but in a cleaner form.
So for example, if this is the expression string:
"2**x+(3-(4*9))"
I want it to display like this
cleaner image.
This is currently the code that I have written in order to achieve this, based off of what I was able to read on StackExchange:
from matplotlib import pylab
from sympy.parsing.sympy_parser import parse_expr
from sympy.plotting import plot
from sympy.printing.preview import preview
class MathString:
def __init__(self, expression_str: str):
self.expression_str = expression_str
#property
def expression(self):
return parse_expr(self.expression_str)
def plot_expression(self):
return plot(self.expression)
def save_plot(self):
self.plot_expression().saveimage("imagePath",
format='png')
And then using a main function:
def main():
test_expression = '2**x+(3-(4*9))'
test = MathString(test_expression)
test.save_plot()
main()
However, when I run main(), it just sends me an actual graphical plot of the equation I provided. I've tried multiple other solutions but the errors ranged from my environment not supporting LaTeX to the fact that I am passing trying to pass the expression as a string.
Please help! I'm super stuck and do not understand what I am doing wrong! Given a certain address path where I can store my images, how can I save an image of the displayed expression using Sympy/MatPlotLib/whatever other libraries I may need?
The program in your question does not convert the expression from
string format to the sympy internal format. See below for examples.
Also, sympy has capabilities to detect what works best in your
environment. Running the following program in Spyder 5.0 with an
iPython 7.22 terminal, I get the output in Unicode format.
from sympy import *
my_names = 'x'
x = symbols(','.join(my_names))
ns1 = {'x': x}
my_symbols = tuple(ns1.values())
es1 = '2**x+(3-(4*9))'
e1 = sympify(es1, locals=ns1)
e2 = sympify(es1, locals=ns1, evaluate=False)
print(f"String {es1} with symbols {my_symbols}",
f"\n\tmakes expression {e1}",
f"\n\tor expression {e2}")
# print(simplify(e1))
init_printing()
pprint(e2)
Output (in Unicode):
# String 2**x+(3-(4*9)) with symbols (x,)
# makes expression 2**x - 33
# or expression 2**x - 4*9 + 3
# x
# 2 - 4⋅9 + 3
I have a fmu created in gt-suite. I am trying to work with it in python using python PyFMI package.
My code
from pyfmi import load_fmu
import numpy as np
model = load_fmu('AHUPIv2b.fmu')
t = np.linspace(0.,100.,100)
u = np.linspace(3.5,4.5,100)
v = np.linspace(900,1000,100)
u_traj = np.transpose(np.vstack((t,u)))
v_traj = np.transpose(np.vstack((t,v)))
input_object = (('InputVarI','InputVarP'),(u_traj,v_traj))
res = model.simulate(final_time=500, input=input_object, options={'ncp':500})
res = model.simulate(final_time=10)
model.simulate takes input as one of its parameters, Documentation says
input --
Input signal for the simulation. The input should be a 2-tuple
consisting of first the names of the input variable(s) and then
the data matrix.
'InputVarI','InputVarP' are the input variables and u_traj,v_traj are data matrices.
My code gives an error
gives an error -
TypeError: tuple indices must be integers or slices, not tuple
Is the input_object created wrong? Can someone help with how to create the input tuples correctly as per the documentation?
The input object is created incorrect. The second variable in the input tuple should be a single data matrix, not two data matrices.
The correct input should be:
data = np.transpose(np.vstack((t,u,v)))
input_object = (['InputVarI','InputVarP'],data)
See also pyFMI parameter change don't change the simulation output
I am trying to find the parametric equations for a certain set of plots, however when I implement the code I only get the first value back. The code is from a website, as I am not very proficient in python. I am using 3.6.5. Here is the code:
import numpy as np
import scipy as sp
from fractions import Fraction
def trigSeries(x):
f=sp.fft(x)
n=len(x)
A0=abs(f[0])/n
A0=Fraction(A0).limit_denominator(1000)
hn=np.ceil(n/2)
f=f[1:int(hn)]
A=2*abs(f)/n
P=sp.pi/2-sp.angle(f)
A=map(Fraction,A)
A=map(lambda a:a.limit_denominator(1000),A)
P=map(Fraction,P)
P=map(lambda a:a.limit_denominator(1000),P)
s=map(str,A)
s=map(lambda a: a+"*np.sin(", s)
s=map(lambda a,b,c :
a+str(b)+"-2*sp.pi*t*"+str(c)+")",
s,P,range(1,len(list(P))+1))
s="+".join(s)
s=str(A0)+"+"+s
return s
x=[5041,4333,3625,3018,2816,2967,3625,4535,5800,6811,7823,8834,8429,7418,6305,5193,4181,3018,3018,3777,4687,5496,6912,7974,9087]
y=[4494,5577,6930,8825,10990,13426,14509,15456,15456,15186,15321,17486,19246,21005,21276,21952,22223,23712,25877,27501,28178,28448,27636,26960,25742]
xf=trigSeries(x)
print(xf)
Any help would be appreciated.
I tried to make the code to work but i could not manage to do it.
The problem id that when you call map(...) You create an iterator, so in order to print it's content you have to do:
for data in iterator:
print(data)
The problem her is that when you apply the lambda function if you cycle over the variable it returns nothing.
You colud convert all the lambda in for cycles, but you have to think over the triple-argument lambda.
The problem is at the step
s=map(lambda a,b,c :
a+str(b)+"-2*sp.pi*t*"+str(c)+")",
s,P,range(1,len(list(P))+1))
it returns empty list. To resolve it, convert s and P to lists just before feeding to this map function. Add two lines above.
s = list(s)
P = list(P)
Output for your example
134723/25+308794/391*np.sin(-1016/709-2*sp.pi*t*1)+2537094/989*np.sin(641/835-2*sp.pi*t*2)+264721/598*np.sin(-68/241-2*sp.pi*t*3)+285344/787*np.sin(-84/997-2*sp.pi*t*4)+118145/543*np.sin(-190/737-2*sp.pi*t*5)+281400/761*np.sin(-469/956-2*sp.pi*t*6)+1451/8*np.sin(-563/489-2*sp.pi*t*7)+122323/624*np.sin(-311/343-2*sp.pi*t*8)+115874/719*np.sin(-137/183-2*sp.pi*t*9)+171452/861*np.sin(-67/52-2*sp.pi*t*10)+18152/105*np.sin(-777/716-2*sp.pi*t*11)+24049/125*np.sin(-107/76-2*sp.pi*t*12)
program of k nearest neighbour ML
import numpy as np
import math
import matplotlib.pyplot as plt
from matplotlib import style
from collections import Counter
dataset={'k':[[1,2],[2,3],[3,1]], 'r':[[6,5],[7,7],[8,6]]}
new_features=[5,7]
def k_nearest_neigh(data,predict,k=3):
distances = []
if len(data)>=k:
warnings.warn('jerk')
for group in data:
for features in data[group]:
eu_dist=np.linalg.norm(np.array(features)-np.array(predict))
distances.append([eu_dist,group])
print(distances)
votes=[i[1] for i in sorted(distances)[:k]]
print(Counter(votes).most_common(1))
vote_result=Counter(votes).most_common(1)[0][0]
return vote_result
result=k_nearest_neigh(dataset,new_features,k=3)
print(result)
Program throwing an error
line 32, in k_nearest_neigh
vote_result=Counter(votes).most_common(1)[0][0]
IndexError: list index out of range
Tried different ways and methods many times but the error is persistent.
your indentation is off: you should either warn or run the loop. here is one version how you could fix that:
def k_nearest_neigh(data,predict,k=3):
if len(data)>=k:
warnings.warn('jerk')
return
distances = []
for group in data: # do this whenever you issue no warning.
....
Say I have an expression which I would like to display in LateX form and one which is a result of an analytical calculation where variables like theta appear and are pretty printed in the end. I would like to print both in one line. Here an example:
from IPython.display import display, Math, Latex
import numpy as np
from sympy import *
init_printing()
# In[1]:
name='\Gamma^'+str(1)+'_{'+str(2)+str(3)+'}'+'='
# In[2]:
theta = symbols('theta')
# In[3]:
display(Math(name),theta)
The last command prints name in a pretty form (LateX) as well as theta. However, a line-break is added which I would like to omit. How can this be achieved?
You need to form latex string first. Use sympy.latex() to make string from any printable sympy variable:
display(Math(name + latex(theta)))
I also wrote simple function with variable number of arguments for such output. No need to wrap variables with latex() here:
def prlat(*args):
str = ''
for arg in args:
str += latex(arg)
display(Math(str))
prlat(name, theta, '= 0')