Double integrate with sipy - python-3.x

I want ask how can calculate this integral with python
enter image description here
from scipy import integrate
Hight_above_ground = 2.5
surface_ground = 81
surface_collector = 65
f = (np.cos(tilt)*np.cos(tilt)) / (PI * s **2 )
(1/surface_ground) * integrate.dblquad(f, 0, surface_ground, 0, surface_collector)
NB : A1 and A2 are 2 surface areas A1 is surface_gound and A2 is surface_collector
and this the error given
Traceback (most recent call last):
File "Bifacial_systems.py", line 34, in <module>
(1/surface_ground)*integrate.dblquad(f, 0, surface_ground, 0, surface_collector)
File "C:\Users\S1-DEV-Manel\AppData\Local\Programs\Python\Python36\lib\site-packages\scipy\integrate\quadpack.py", line 602, in dblquad
opts={"epsabs": epsabs, "epsrel": epsrel})
File "C:\Users\S1-DEV-Manel\AppData\Local\Programs\Python\Python36\lib\site-packages\scipy\integrate\quadpack.py", line 826, in nquad
return _NQuad(func, ranges, opts, full_output).integrate(*args)
File "C:\Users\S1-DEV-Manel\AppData\Local\Programs\Python\Python36\lib\site-packages\scipy\integrate\quadpack.py", line 881, in integrate
**opt)
File "C:\Users\S1-DEV-Manel\AppData\Local\Programs\Python\Python36\lib\site-packages\scipy\integrate\quadpack.py", line 352, in quad
points)
File "C:\Users\S1-DEV-Manel\AppData\Local\Programs\Python\Python36\lib\site-packages\scipy\integrate\quadpack.py", line 463, in _quad
return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
File "C:\Users\S1-DEV-Manel\AppData\Local\Programs\Python\Python36\lib\site-packages\scipy\integrate\quadpack.py", line 881, in integrate
**opt)
File "C:\Users\S1-DEV-Manel\AppData\Local\Programs\Python\Python36\lib\site-packages\scipy\integrate\quadpack.py", line 352, in quad
points)
File "C:\Users\S1-DEV-Manel\AppData\Local\Programs\Python\Python36\lib\site-packages\scipy\integrate\quadpack.py", line 463, in _quad
return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
ValueError: invalid callable given

You have to rewrite your integrand making expressing expressiong dA1 and dA2 in terms of theta1, theta2, d theta1 and d theta2. Assuming that dA1 dA2 = d theta1 d theta2 the solution would be
from scipy.integrate import dblquad
def integrand(theta1, theta2, S):
return np.cos(theta1)*np.cos(theta2)/S**2
S = 1
dblquad(integrand, 0, np.pi/2, 0, lambda x: np.pi/2-x, args=(S,))
In case you end up with an integral of higher order you can use nquad

Related

How to fix 'FileNotFoundError' when using pyx.canvas.writeGSfile() in Python?

I would like to generate a jpeg or png file using the Pyx module. I found
pyx.canvas.writeGSfile() which I tried to use in the following code:
from pyx import *
def mark(x, y):
return path.circle(x, y, 0.1)
if __name__ == '__main__':
c = canvas.canvas()
# r = 70
f = trafo.scale(0.7, 1)
circle = path.circle(0, 0, 2)
a, b = circle.split([0, 2])
c.stroke(a, [style.linewidth.Thick, f])
d1 = f.apply(*circle.at(0.5*circle.arclen()))
d2 = f.apply(*circle.at(circle.arclen()))
c.fill(mark(*d1))
c.fill(mark(*d2))
c.writeGSfile('test.jpeg')
But it spits back the following error:
Traceback (most recent call last):
File "/Python/pyx/test.py", line 19, in <module>
c.writeGSfile('test.png')
File "\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pyx\canvas.py", line 474, in writeGSfile
p = config.Popen(cmd, stdin=config.PIPE)
File "\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pyx\config.py", line 218, in Popen
return subprocess.Popen(cmd, *args, **kwargs)
File "\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 997, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
I tried to debug but I'm having trouble understanding the processing.py section. Any ideas?
You need to have ghostscript installed (gs) to generate bitmap output.

pymc3 model with ODE solver using theano

I am using a model where the mean response depends on the solution to an ODE. I am trying to fit this model using pymc3, but am running into problems (relating to missing test values) when joining the ODE solver to the model.
Model
y_t is Lognormally distributed with mean mu_t and standard deviation sigma.
mu_t is the solution to a set of ODE's at time t.
Problem
Theano/ pymc3 gives an error because the theano tensor variables used in solving the ODE have no test values. See below for a copy of the errors. I've tried setting
th.config.compute_test_value = 'ignore'
but I think that pymc3 changes it back to require test values. I am fairly new to theano and pymc3, so I apologise if I am missing something obvious.
Code
Imports
import pymc3 as pm
import theano as th
import theano.tensor as tt
from FormatData import *
import pandas as pd
Functions to solve ODE
# Runge Kutta integrator
def rungekuttastep(h, y, fprime, *args):
k1 = h*fprime(y, *args)
k2 = h*fprime(y + 0.5*k1, *args)
k3 = h*fprime(y + 0.5*k2, *args)
k4 = h*fprime(y + k3, *args)
y_np1 = y + (1./6.)*k1 + (1./3.)*k2 + (1./3.)*k3 + (1./6.)*k4
return y_np1
# ODE equations for my model
def ODE(y, *args):
alpha = args
yprime = tt.zeros_like(y)
yprime = tt.set_subtensor(yprime[0], alpha[0]*y[1] - alpha[1]*y[0])
yprime = tt.set_subtensor(yprime[1], -alpha[2]*y[0]*y[1])
return yprime
# Function to return ODE values given parameters
def calcFittedTitreVals(alpha, niter, hsize, inits):
y0 = tt.vector('y0')
h = tt.scalar('h')
i = tt.iscalar('i')
alpha0 = tt.scalar('alpha0')
alpha1 = tt.scalar('alpha1')
alpha2 = tt.scalar('alpha2')
result, updates = th.scan(fn=lambda y0, h: rungekuttastep(h, y0, ODE, alpha0, alpha1, alpha2),
outputs_info=[{'initial': y0}], non_sequences=h, n_steps=i)
odeint = th.function(inputs=[h, y0, i, alpha0, alpha1, alpha2], outputs=result, updates=updates)
z1 = odeint(h=hsize, # size of the interval
y0=inits, # starting values
i=niter, # number of iterations
alpha0=alpha[0], alpha1=alpha[1], alpha2=alpha[2])
C = z1[:, 0]
A = z1[:, 1]
return C, A
Generate Data
t = np.arange(0, 45, 0.1) # times at which to solve ODE
alpha = np.array([2, 0.4, 0.0001]) # true paramter values ODE
C, A = calcFittedTitreVals(alpha, niter=450, hsize=0.1, inits=[0, 1200])
td = np.arange(0, 45, 1) # times at which I observe data
sigma = 0.1
indices = np.array(np.searchsorted(t, td)).flatten()
DATA = pd.DataFrame(
data={'observed': np.random.lognormal(np.log(C[indices]), sigma),
'true': C[indices], 'time': td})
pymc3 model function
def titreLogNormal(Y, hsize, inits, times):
Y = th.shared(Y)
inits = th.shared(inits)
timesG = np.arange(0, 45, step=hsize)
indices = np.array(np.searchsorted(timesG, times)).flatten()
nTsteps = th.shared(timesG.shape[0])
hsize = th.shared(hsize)
y0 = tt.vector('y0')
h = tt.scalar('h')
i = tt.iscalar('i')
alpha0 = tt.scalar('alpha0')
alpha1 = tt.scalar('alpha1')
alpha2 = tt.scalar('alpha2')
result, updates = th.scan(fn=lambda y0, h: rungekuttastep(h, y0, ODE, alpha0, alpha1, alpha2),
outputs_info=[{'initial': y0}], non_sequences=h, n_steps=i)
odeint = th.function(inputs=[h, y0, i, alpha0, alpha1, alpha2], outputs=result, updates=updates)
model = pm.Model()
with model:
alpha = pm.Gamma('alpha', 0., 10., shape=3, testval=[2, 0.4, 0.001])
sigma = pm.Gamma('sigma', 0.1, 0.1, testval=0.1)
res = odeint(h=hsize, y=inits, i=nTsteps, alpha0=alpha[0], alpha1=alpha[1], alpha2=alpha[2])
mu = pm.Deterministic("mu", res[indices, 0])
y = pm.Lognormal('y', mu, sigma, observed=Y)
return model
Create model with data
model = titreLogNormal(
Y=np.array(DATA[['observed']]).flatten(),
hsize=0.1, inits={'a': 0, 'p': 1200},
times=np.array(DATA[['time']]).flatten())
Errors
Traceback (most recent call last):
File "/home/millerp/.local/lib/python3.5/site-packages/theano/gof/op.py", line 625, in __call__
storage_map[ins] = [self._get_test_value(ins)]
File "/home/millerp/.local/lib/python3.5/site-packages/theano/gof/op.py", line 581, in _get_test_value
raise AttributeError('%s has no test value %s' % (v, detailed_err_msg))
AttributeError: y0 has no test value
Backtrace when that variable is created:
File "/home/millerp/pycharm/pycharm-edu-3.5.1/helpers/pydev/_pydev_bundle/pydev_console_utils.py", line 251, in add_exec
more = self.do_add_exec(code_fragment)
File "/home/millerp/pycharm/pycharm-edu-3.5.1/helpers/pydev/_pydev_bundle/pydev_ipython_console.py", line 41, in do_add_exec
res = bool(self.interpreter.add_exec(codeFragment.text))
File "/home/millerp/pycharm/pycharm-edu-3.5.1/helpers/pydev/_pydev_bundle/pydev_ipython_console_011.py", line 455, in add_exec
self.ipython.run_cell(line, store_history=True)
File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2717, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2821, in run_ast_nodes
if self.run_code(code, result):
File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-2-54c976fefe1e>", line 99, in <module>
times=np.array(DATA[['time']]).flatten()
File "<ipython-input-2-54c976fefe1e>", line 71, in titreLogNormal
y0 = tt.vector('y0')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-2-54c976fefe1e>", line 99, in <module>
times=np.array(DATA[['time']]).flatten()
File "<ipython-input-2-54c976fefe1e>", line 86, in titreLogNormal
outputs_info=[{'initial': y0}], non_sequences=h, n_steps=i)
File "/home/millerp/.local/lib/python3.5/site-packages/theano/scan_module/scan.py", line 660, in scan
tensor.shape_padleft(actual_arg), 0),
File "/home/millerp/.local/lib/python3.5/site-packages/theano/tensor/basic.py", line 4429, in shape_padleft
return DimShuffle(_t.broadcastable, pattern)(_t)
File "/home/millerp/.local/lib/python3.5/site-packages/theano/gof/op.py", line 639, in __call__
(i, ins, node, detailed_err_msg))
ValueError: Cannot compute test value: input 0 (y0) of Op InplaceDimShuffle{x,0}(y0) missing default value.
Backtrace when that variable is created:
File "/home/millerp/pycharm/pycharm-edu-3.5.1/helpers/pydev/_pydev_bundle/pydev_console_utils.py", line 251, in add_exec
more = self.do_add_exec(code_fragment)
File "/home/millerp/pycharm/pycharm-edu-3.5.1/helpers/pydev/_pydev_bundle/pydev_ipython_console.py", line 41, in do_add_exec
res = bool(self.interpreter.add_exec(codeFragment.text))
File "/home/millerp/pycharm/pycharm-edu-3.5.1/helpers/pydev/_pydev_bundle/pydev_ipython_console_011.py", line 455, in add_exec
self.ipython.run_cell(line, store_history=True)
File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2717, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2821, in run_ast_nodes
if self.run_code(code, result):
File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-2-54c976fefe1e>", line 99, in <module>
times=np.array(DATA[['time']]).flatten()
File "<ipython-input-2-54c976fefe1e>", line 71, in titreLogNormal
y0 = tt.vector('y0')

Can't display patches with mplleaflet

I'm trying to display a circle of fixed size in a leaflet map.
I tried with .add_artist()(see here) and I'm now trying with .add_patch()
import mplleaflet
import matplotlib.pyplot as plt
import matplotlib as mpl
fig, ax = plt.subplots()
x = 2.363561
y = 48.951918
r = 20
circle1 = mpl.patches.Circle((x,y), radius=r)
circle2= plt.Circle((x, y), r, color='r')
#ax.add_patch(circle1)
#ax.add_patch(circle2)
mplleaflet.show(fig=ax.figure)
You can try to uncomment one of the two commented lines, it doesn't matter which line is uncommented, same error pops.
Here is the trace I get :
Traceback (most recent call last):
File "<ipython-input-81-1fdd7f4a9d12>", line 16, in <module>
mplleaflet.show(fig = ax.figure)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\_display.py", line 180, in show
save_html(fig, fileobj=f, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\_display.py", line 131, in save_html
html = fig_to_html(fig, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\_display.py", line 84, in fig_to_html
exporter.run(fig)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\mplexporter\exporter.py", line 51, in run
self.crawl_fig(fig)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\mplexporter\exporter.py", line 118, in crawl_fig
self.crawl_ax(ax)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\mplexporter\exporter.py", line 138, in crawl_ax
self.draw_patch(ax, patch)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\mplexporter\exporter.py", line 227, in draw_patch
mplobj=patch)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\leaflet_renderer.py", line 125, in draw_path
rings = list(iter_rings(data, pathcodes))
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\utils.py", line 14, in iter_rings
raise ValueError('Unrecognized code: {}'.format(code))
ValueError: Unrecognized code: C
Any idea on how to solve this ?
===========================
EDIT :
Just to see what would happen, I tried doing the same thing than this, which is changing
elif code == 'L': ring.append(point)
to
elif code == 'L' or code == 'Z' or code == 'S' or code == 'C': ring.append(point)
in mplleaflet\utils.py, line 11 and 12. Here is what I got :
===========================
EDIT 2 to answer comment
mpl.patches.Rectangle and plt.Rectangle show up :
rect1 = mpl.patches.Rectangle((x,y), 1, 1, color = 'r')
rect2 = plt.Rectangle((x, y), 1, 1, fc='r')
Which seems to fit with a rectangle of 1 degree in latitude and 1 degree longitude (see here) (maybe ? Seems a bit small).
As for Polygons, well... At least they show up, but I guess there is a projection problem :
regpol1 = mpl.patches.RegularPolygon((x,y), 100, radius=r, color = 'r')
cirpol1 = mpl.patches.CirclePolygon((x +50,y), radius=r, color = 'b')

Python Deap GP Evaluating individual causes error

I am currently experiencing an issue whenever I try to evaluate an individual using the GP portion of DEAP.
I receive the following error:
Traceback (most recent call last):
File "ImageGP.py", line 297, in <module>
pop, logs = algorithms.eaSimple(pop, toolbox, 0.9, 0.1, 60, stats=mstats, halloffame=hof, verbose=True)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/deap/algorithms.py", line 148, in eaSimple
for ind, fit in zip(invalid_ind, fitnesses):
File "ImageGP.py", line 229, in evalFunc
func = toolbox.compile(expr=individual)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/deap/gp.py", line 451, in compile
return eval(code, pset.context, {})
File "<string>", line 1
lambda oValue,oAvg13,oAvg17,oAvg21,sobelVal(v),sobelVal(h),edgeVal,blotchVal: [[[0, 75, 82.2857142857, 83.0, 82.9090909091, 4, 12, 4, 180], ... Proceed to print out all of my data ... [0, 147, 151.244897959, 150.728395062, 150.73553719, 248, 244, 5, 210]]]
^
SyntaxError: invalid syntax
If anyone has any ideas about what could be causing this problem, then I would really appreciate some advice. My current evaluation function looks like this:
def evalFunc(individual, data, points):
func = toolbox.compile(expr=individual)
total = 1.0
for point in points:
tmp = [float(x) for x in data[point[1]][point[0]][1:9]]
total += int((0 if (func(*tmp)) < 0 else 1) == points[2])
print ("Fitness: " + str(total))
return total,
Where the data contains the data being used (the values for the 8 variables listed in the error) and point specifying the x and y co-ordinates from which to get those 8 values. Thank you for your suggestions!

Receiving Type Error: 0 while updating pandas df using Data Nitro

I am updating a Pandas Data Frame.
The script looks up for a product. If the product is already in data frame, it just updates it columns with accumulated new values.
If the product is not there it creates a new set of rows to insert the values of the product.
Code
for m in range(0,len(product_sales_price)):
if exact_match(str(sales_record[n-1]),str(product_sales_price[m]))==True:
total_product_daily_sales = counter * product_sales_price[m+1]
'''
print(total_product_daily_sales)
'''
total_product_daily_net_profit = total_product_daily_sales *.1
print(counter)
print(product_sales_price[m+1])
print(total_product_daily_sales)
print(total_product_daily_net_profit)
print(m)
print(product_sales_price[m])
if (product_revenue_and_net_profit_df.ix[:,0] == product_sales_price[m]).any() == True :
product_revenue_and_net_profit_df.ix[:,:][(product_revenue_and_net_profit_df.ix[:,
0] == product_sales_price[m])] = [
product_revenue_and_net_profit_df.ix[:,0][(product_revenue_and_net_profit_df.ix[:,
0] == product_sales_price[m])],
product_revenue_and_net_profit_df.ix[:,1][(product_revenue_and_net_profit_df.ix[:,
0] == product_sales_price[m])]+counter,
product_revenue_and_net_profit_df.ix[:,2][(product_revenue_and_net_profit_df.ix[:,
0] == product_sales_price[
m])]+total_product_daily_sales,product_revenue_and_net_profit_df.ix[:,
3][(product_revenue_and_net_profit_df.ix[:,0] == product_sales_price[
m])]+total_product_daily_net_profit]
else:
product_revenue_and_net_profit_df.ix[(product_revenue_and_net_profit_df.shape[0]+1),:] = (
[product_sales_price[m],counter,total_product_daily_sales,
total_product_daily_net_profit]
)
Run Time
<sale_frequency time (in seconds):
1
423.44
423.44
42.344
0
Bushwacker Dodge Pocket Style Fender Flare Set of 4
Traceback (most recent call last):
File "32\scriptStarter.py", line 120, in <module>
File "C:\Python Projects\Amazon-Sales\amazon_analysis.py", line 162, in <module>
print (timeit.timeit(fn + "()", "from __main__ import "+fn, number=1))
File "C:\Users\onthego\Anaconda3\lib\timeit.py", line 219, in timeit
return Timer(stmt, setup, timer).timeit(number)
File "C:\Users\onthego\Anaconda3\lib\timeit.py", line 184, in timeit
timing = self.inner(it, self.timer)
File "<timeit-src>", line 6, in inner
File "C:\Python Projects\Amazon-Sales\amazon_analysis.py", line 91, in sale_frequency
m])]+total_product_daily_net_profit]
File "C:\Users\onthego\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2122, in __setitem__
self._setitem_array(key, value)
File "C:\Users\onthego\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2142, in _setitem_array
self.ix._setitem_with_indexer(indexer, value)
File "C:\Users\onthego\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 448, in _setitem_with_indexer
elif np.array(value).ndim == 2:
File "C:\Users\onthego\Anaconda3\lib\site-packages\pandas\core\series.py", line 521, in __getitem__
result = self.index.get_value(self, key)
File "C:\Users\onthego\Anaconda3\lib\site-packages\pandas\core\index.py", line 1595, in get_value
return self._engine.get_value(s, k)
File "pandas\index.pyx", line 100, in pandas.index.IndexEngine.get_value (pandas\index.c:3113)
File "pandas\index.pyx", line 108, in pandas.index.IndexEngine.get_value (pandas\index.c:2844)
File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:3704)
File "pandas\hashtable.pyx", line 375, in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:7224)
File "pandas\hashtable.pyx", line 381, in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:7162)
KeyError: 0
>>>
>>>
>>>

Resources