I'm trying to solve these two integrals, I want to use a numerical approach because C_i will eventually become more complicated and I want to use it for all cases. Currently, C_i is just a constant so _quad is not able to solve it. I'm assuming because it is a Heaviside function and it is having trouble finding the a,b. Please correct me if I'm approaching this wrongly.
Equation 33
In [1]: import numpy as np
...: import scipy as sp
...: import sympy as smp
...: from sympy import DiracDelta
...: from sympy import Heaviside
In [2]: C_i = smp.Function('C_i')
In [3]: t, t0, x, v = smp.symbols('t, t0, x, v', positive=True)
In [4]: tot_l = 10
In [5]: C_fm = (1/tot_l)*v*smp.Integral(C_i(t0), (t0, (-x/v)+t, t))
In [6]: C_fm.doit()
Out[6]:
0.1*v*Integral(C_i(t0), (t0, t - x/v, t))
In [7]: C_fm.doit().simplify()
Out[7]:
0.1*v*Integral(C_i(t0), (t0, t - x/v, t))
In [8]: C_fms = C_fm.doit().simplify()
In [9]: t_arr = np.arange(0,1000,1)
In [10]: f_mean = smp.lambdify((x, v, t), C_fms, ['scipy', {'C_i': lambda e: 0.8}])
In [11]: try2 = f_mean(10, 0.1, t_arr)
Traceback (most recent call last):
File "/var/folders/rd/wzfh_5h110l121rmlxn61v440000gn/T/ipykernel_3164/3786931540.py", line 1, in <module>
try2 = f_mean(10, 0.1, t_arr)
File "<lambdifygenerated-1>", line 2, in _lambdifygenerated
return 0.1*v*quad(lambda t0: C_i(t0), t - x/v, t)[0]
File "/opt/anaconda3/lib/python3.9/site-packages/scipy/integrate/quadpack.py", line 348, in quad
flip, a, b = b < a, min(a, b), max(a, b)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Equation 34
In [12]: C_i = smp.Function('C_i')
In [13]: t, tao, x, v = smp.symbols('t, tao, x, v', positive=True)
In [14]: I2 = v*smp.Integral((C_i(t-tao))**2, (tao, 0, t))
In [15]: I2.doit()
Out[15]:
v*Integral(C_i(t - tao)**2, (tao, 0, t))
In [16]: I2.doit().simplify()
Out[16]:
v*Integral(C_i(t - tao)**2, (tao, 0, t))
In [17]: I2_s = I2.doit().simplify()
In [18]: tao_arr = np.arange(0,1000,1)
In [19]: I2_sf = smp.lambdify((v, tao), I2_s, ['scipy', {'C_i': lambda e: 0.8}])
In [20]: try2 = I2_sf(0.1, tao_arr)
Traceback (most recent call last):
File "/var/folders/rd/wzfh_5h110l121rmlxn61v440000gn/T/ipykernel_3164/4262383171.py", line 1, in <module>
try2 = I2_sf(0.1, tao_arr)
File "<lambdifygenerated-2>", line 2, in _lambdifygenerated
return v*quad(lambda tao: C_i(t - tao)**2, 0, t)[0]
File "/opt/anaconda3/lib/python3.9/site-packages/scipy/integrate/quadpack.py", line 351, in quad
retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
File "/opt/anaconda3/lib/python3.9/site-packages/scipy/integrate/quadpack.py", line 463, in _quad
return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
File "/opt/anaconda3/lib/python3.9/site-packages/sympy/core/expr.py", line 345, in __float__
raise TypeError("Cannot convert expression to float")
TypeError: Cannot convert expression to float
So you are passing an unevaluated Integrate to lambdify, which in turn translates it call to scipy.integrate.quad.
Looks like the integrals can't be evaluated even with doit and simplify calls. Have you actually looked at C_fms and I2_s? That's one of the first things I'd do when running this code!
I've never looked at this approach. I have seen people lambdify the objective expression, and then try to use that in quad directly.
quad has specific requirements (check the docs!). The objective function must return a single number, and the bounds must also be numbers.
In the first error, you are passing array t_arr as the t bound, and it got the usual ambiguity error when checking where it is bigger than the other bound, 0. That's that b < a test. quad cannot use arrays as bounds.
I not sure why the second case gets avoids this problem - bounds must be coming from somewhere else. But the error comes when quad calls the objective function, and expects a float return. Instead the function returns a sympy expression which sympy can't convert to float. My guess there's some variable in the expression that's still a sympy.symbol.
In diagnosing lambdify problems, it's a good idea to look at the generated code. One way is with help on the function, help(I2_sf). But with that you need to be able to read and understand python, including any numpy and scipy functions. That's not always easy.
Have you tried to use sympy's own numeric integrator? Trying to combine sympy and numpy/scipy often has problems.
I am currently working on a python script to print pieces of information on running EC2 instances on AWS using Boto3. I am trying to print the InstanceID, InstanceType, and PublicIp. I looked through Boto3's documentation and example scripts so this is what I am using:
import boto3
ec2client = boto3.client('ec2')
response = ec2client.describe_instances()
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
instance_id = instance["InstanceId"]
instance_type = instance["InstanceType"]
instance_ip = instance["NetworkInterfaces"][0]["Association"]
print(instance)
print(instance_id)
print(instance_type)
print(instance_ip)
When I run this, "instance" prints one large block of json code, my instanceID, and type. But I am getting an error since adding NetworkInterfaces.
instance_ip = instance["NetworkInterfaces"][0]["Association"]
returns:
Traceback (most recent call last):
File "/Users/me/AWS/describeInstances.py", line 12, in <module>
instance_ip = instance["NetworkInterfaces"][0]["Association"]
KeyError: 'Association'
What am I doing wrong while trying to print the PublicIp?
Here is the structure of NetworkInterfaces for reference:
The full Response Syntax for reference can be found here (https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_instances)
Association man not always may be present. Also an instance may have more then one interface. So your working loop could be:
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
instance_id = instance["InstanceId"]
instance_type = instance["InstanceType"]
#print(instance)
print(instance_id, instance_type)
for network_interface in instance["NetworkInterfaces"]:
instance_ip = network_interface.get("Association", "no-association")
print(' -', instance_ip)
I installed the dataframe package in Octave and would like to programmatically assert that the package version is at least 1.2.0. Does octave provide a way to check a package version programmatically?
Version = ver('dataframe')
% Version =
% scalar structure containing the fields:
% Name = dataframe
% Version = 1.2.0
% Release = [](0x0)
% Date = 2017-08-14
Obviously Version.Version is still a string, but you can process that further, e.g. with strsplit, to obtain the major-minor-patch numbers.
strsplit( Version.Version, '.' )
% ans =
% {
% [1,1] = 1
% [1,2] = 2
% [1,3] = 0
% }
Alternatively you can also use
Out = pkg('list', 'dataframe')
which also contains a 'version' field, as well as some extra information.
How do I get this code to work in 3?
Please note that I am not asking about "foo".upper() at the string instance level.
import string
try:
print("string module, upper function:")
print(string.upper)
foo = string.upper("Foo")
print("foo:%s" % (foo))
except (Exception,) as e:
raise
output on 2:
string module, upper function:
<function upper at 0x10baad848>
foo:FOO
output on 3:
string module, upper function:
Traceback (most recent call last):
File "dummytst223.py", line 70, in <module>
test_string_upper()
File "dummytst223.py", line 63, in test_string_upper
print(string.upper)
AttributeError: module 'string' has no attribute 'upper'
help(string) wasn't very helpful either. Far as I can tell, the only function left is string.capwords.
Note: a bit hacky, but here's a my short-term workaround.
import string
try:
_ = string.upper
except (AttributeError,) as e:
def upper(s):
return s.upper()
string.upper = upper
All of the string module-level functions you describe were removed in Python 3. The Python 2 string module documentation contains this note:
You should consider these functions as deprecated, although they will not be removed until Python 3.
If you have string.upper(foo) in Python 2, you need to convert that to foo.upper() in Python 3.
I am working on a project where I have to use ctypes to call a few C functions from a C file in a Python script. I have created a shared object from the C file and used it inside my Python script.
I have defined the C struct in ctypes, but I am getting a RuntimeError while running my Python script. The error is:
ffi_prep_cif failed
I have included ffi.h header in my C file and again created the shared object, but I'm still getting the same error. Any suggestions?
The code which I have written for the wrapper in Python is as follows:
if __name__ == "__main__":
lib_fib = ctypes.CDLL('./lib6.so')
class model_t(ctypes.Structure):
_fields__ = [('weight', ctypes.POINTER(ctypes.c_float)),
('threshold', ctypes.c_float)]
data = [1.0, 2.0, 3.0]
f1 = 2.5
l = len(data)
m = model_t()
m.weight = (ctypes.c_float * l)(*data)
m.threshold = (ctypes.c_float * 1)(l)
chr_p = ctypes.POINTER(ctypes.c_char)
c = 'abcd'
l1 = len(c)
chr_p = (ctypes.c_char * l1)(*c)
out = lib_fib.new_classify(m, chr_p)
print out`
I am trying to replace Python function called self.abc_prob() with C new_classify(). This is a part of my C function, which I want to call using ctypes:
extern double
new_classify(model_t *model_ptr, char *s)
{
char bigram[3]; /* Used only when debugging */
float *model_weights = model_ptr->weights;
float threshold = model_ptr->threshold;
/* ... */