scipy spherical harmonics imaginary part - python

In the documentation of scipy(http://docs.scipy.org/doc/scipy-0.15.0/reference/generated/scipy.special.sph_harm.html) it clearly states that scipy.special.sph_harm returns a complex float. given by the expression shown in the link. When trying trying to insert some values however, i keep on getting only a negligible value of what is expected.
The real(ie. not imaginary) value I believe is something closer to the absolute value expected if you compute the mathematical expression in the link:
from scipy.special import sph_harm,lpmv
m=2;n=5;th=2.1;ph=0.4
print(sph_harm(m,n,th,ph))
#returns (0.36574435883734352+2.5429495084534193e-310j) (essentially no imag.part
def norm(m,n): #sqrt part
return np.sqrt((2*n+1)/(4*np.pi) * \
np.math.factorial(n-m)/np.math.factorial(n+m))
def ie(m,theta): #imaginary exponential part
return np.exp(1j*m*theta)
out=norm(m,n)*ie(m,th)*lpmv(m,n,np.cos(ph)) #lpmv=legendre
print(out,abs(out))
#returns (-0.179310129764-0.31877392206j) 0.365744358837
Is there something wrong with the sph_harm or am I somehow using it wrong?
I am using scipy v0.15.1

Related

Sympy not properly displaying conjugate of square root of real

I keep getting expressions like this image, despite declaring these symbols as reals.
The code to reproduce is:
import sympy as sp
delta = sp.Symbol('delta', real=True)
f = sp.sqrt(1/delta)
prod = sp.conjugate(f)*f
prod.subs(delta,delta)
I expected to get 1/delta
Also trying simplify() does not work either.
According to the official SymPy Docs for conjugate, it looks like the function is supposed to return the complex conjugate for its input. In other words, it takes the complex part of the number and flips the sign.
In your example, you are taking the square root of a variable. If delta = -1, then the resulting conjugate could be unreal and thus different than if delta was any other integer. Thus, SymPy wraps the result in a conjugate object.
If you want to tell Sympy that your variable delta is positive (and thus f must be real), then you should define it as delta = sp.Symbol('delta', real=True, positive=True).

How to return a finite (float) value with nonlinsolve in SymPy?

I am very new to programming, and had to use sympy for a school project.
I think I get that using nonlinsolve to return an angle gives an ImageSet with the angle + 2n*pi. However I want it to return only the value of the angle (in the interval [0,pi/2]), and as one value and not an interval.
from sympy import nonlinsolve, symbols,cos
x=symbols('x')
print(nonlinsolve([cos(x)-1],[x]).args[0][0])
I want the result to be 0 and not 2*n*pi.
Clarification : I know that the result is correct, but I only want one value, that I can use algebraically, and I don't know how Sympy works (how to manipulate ImageSets)
So I might be wrong because i dont use sympy, but the solution that solvers return seems to be corect to me.
ImageSet(Lambda(_n, 2*_n*pi), Integers)
From what I understand solver returned lambda function. Cosinus is a cyclic function which means it reapeats it's value every 2PI. So the solver says first solution (_n = 0) is 0, second (_n = 1) is 2pi and so on.
look at the function plot and it will hopefully make sense:
Wolfram Alpha - (cos(x) - 1)
EDIT: I think you need to use intersect method of imageset like this( note that intersect returns all the intersections, here i selected just the first one):
from sympy import nonlinsolve, symbols,cos, Interval
import math
x = symbols('x')
f = nonlinsolve([cos(x)-1], [x]).args[0][0]
sol = f.intersect(Interval(0, math.pi/2)).args[0]
print(sol)

Sum with Pythons uncertainties giving a different result than expected

A friend of mine is evaluating data with Pythons package uncertainties. I am her statistics consulter, and I have come up with a weird result in her code.
sum(array) and sqrt(sum(unumpy.std_devs(array)**2)) yield different results, with the second one being the variance method as usually used in engineering.
Now, I know that the variance approach is only suited for when the error is small compared to the partial derivate (because of the Taylor series) which isn't given in this case, but how does uncertainties handle this? And how can I reproduce in any way what uncertainties does!?
You forgot to square the standard error to make it the variance. This should work and be equal to the error of sum(array):
sqrt(sum(unumpy.std_devs(array)**2))
Then
from uncertainties import unumpy
import random
import math
a = [uc.ufloat(random.random(), random.random()) for _ in range(100)]
sa = unumpy.std_devs(sum(a))
sb = math.sqrt(sum(unumpy.std_devs(a)**2))
print(sa)
print(sb)
print(sa == sb)
Will result with something like
5.793714811166615
5.793714811166615
True
This results due to my array being an AffineScalarFunc (as opposed to a Variable), and thus they not only store the value but also all the variables that the value depends on [1].
Now, my values are not fully independent (which wasn't clear at all at first sight*), and thus sum(array) also considers the off-diagonal elements of my covariance matrix in accordance to this formula (sorry that the article is in German, but English Wikipedias formula isn't as intuitive), whereas sqrt(sum(unumpy.std_devs(array)**2)) obviously doesn't and just adds up the diagonal elements.
A way to reproduce what uncertainties does is:
from uncertainties import covariance_matrix
sum=0
for i in range(0,len(array)):
for j in range(0,len(array)):
sum+=covariancematrix(array)[i][j]
print(sqrt(sum))
And then unumpy.std_devs(sum(array))==sqrt(sum) is True.
*Correlation due to the use of data taken from the same interpolation (of measurements) and because the length of a measurement was calculated as the difference of two times (and meassurement were consecutive, so the times are now correlated!)

Function to calculate and plot arctanx

I need to write a function that can write and solve the inverse of tan for values that I input as two arrays. Sometimes the array on the denominator contains zero so always a division by zero occurs. I don't know how to get rid of the error and make the answer return pi/2 instead.
def deviation(x):
if capture(x)==True:
for i in range(len(yvf)):
theta=sp.arctan(xvf/yvf) #xvf and yvf are two arrays
First of all: write xvf[i] and yvf[i] to access the single elements of the arrays one after the other.
Secondly discern if yvf[i] equals zero or not:
if yvf[i] == 0:
theta = math.pi/2.0
else:
theta = sp.arctan(xvf[i]/yvf[i])
If you import numpy, I suggest using arctan2 instead of arctan (see this doc). This function manages zero values in the 2nd argument.
If not, you can solve this problem with atan2 function of math library and zip built-in function :
import math
xvf = [0.,2.,2.]
yvf = [20.,0.,2.]
def arctan(xvf,yvf):
return [math.atan2(x,y) for x,y in zip(xvf,yvf)]
print arctan(xvf,yvf)

How to take a derivative of Function, then evaluate using real numbers?

I have a massive, ugly expression. I need to take its derivative, then plug in some numbers and evaluate it.
This is to calculate the total error in the output of an electrical circuit.
The actual formula looks like this:
Almost all those variables on the right are temperature dependent, and I am concerned with the overall temperature sensitivity, dReff/dT.
But let's make things simpler for the sake of explanation. Let's say I have a much simpler formula:
R(T) = 2*R_0(T)
I would like to get the derivative in terms of the variables:
dR/dT = 2*dR_0/dT
And then, knowing dR_0/dT from a datasheet, I would like to be able to plug it in:
dR_0/dT = 2ohms/°C
dR/dT = 2*2ohms/°C = 4ohms/°C
Now, I've used python and sympy to get me pretty far but now I'm stuck. It looks like this:
from sympy import *
T = Symbol('T')
R_0 = Function('R_0')(T)
R = 2*R_0
diffR = Symbol('diffR')
diffR = R.diff(T)
At this point if you print diffR, you get the following
2*Derivative(R_0(T),T)
How to I get the rest of the way? Is there a way to plug in values for the derivative term?
One solution is to make another symbol for the derivative:
dR0 = Function('R_0')(T).diff(T)
Then, you can substitute in for this in your larger derivative expression.
expr.subs(dR0, value)
This works in the few examples I've tried. Their might be an easier way to do this, but I only deal with sympy when strictly needed.

Categories