Manipulate return values in python - python

I am trying to convert decimal degrees to degrees, minutes and seconds using the following code:
def dd2dms(deg):
d = int(deg)
md = abs(deg - d) * 60
m = int(md)
sd = (md - m) * 60
return [d, m, sd]
full = 500/60
print(full)
print(dd2dms(full))
But I get the following output:
8.333333333333334 [8, 20, 0]
I would like to get the output as:
8.333333333333334 8:20:0
How can I achieve this? I am taking baby steps in learning Python. :)

Here's a little class built around your angle that has a conversion function for dms and also a nicely formatted string representation:
class Angle(float):
def __init__(self, degrees):
self.degrees = degrees
def __repr__(self):
return "<Angle of {}° ({})>".format(self.degrees, self.dms)
#property
def dms(self):
deg = self.degrees
d = int(deg)
md = abs(deg - d) * 60
m = int(md)
sd = (md - m) * 60
return "{:g}:{:g}:{:g}".format(d, m, sd)
Demo:
In[1]: a = Angle(90.173)
In[2]: print(a)
90.173
In[3]: print(a.dms)
90:10:22.8
In[4]: a
Out[4]: <Angle of 90.173° (90:10:22.8)>
Since it inherits from float, you can even calculate with it. Note though that the return value will be a normal float (not an Angle) without further adaption of the class.

If it is just for display purposes something like:
print("{0}:{1}:{2}".format(*dd2dms(full)))

If dd2dms returns an array, you just need to extract the array elements, convert them to strings and then concatenate. If you're just beginning to learn Python, try something easy like this:
result = dd2dms(full)
print(str(result[0]) + ":" + str(result[1]) + ":" + str(result[2]))
where result[i] returns the i-th element of array result, str() constructs a string from its argument, and then you can just concatenate the strings with +.

Remove square brackets from return statement (to return a tuple instead a list):
return d, m, sd
and format output string:
"%s:%s:%s" % dd2dms(full)
Full snippet:
def dd2dms(deg):
d = int(deg)
md = abs(deg - d) * 60
m = int(md)
sd = (md - m) * 60
return d, m, sd
full = 500/60
print(full)
print("%s:%s:%s" % dd2dms(full))

In python 3.6 you can use use literal string interpolation https://www.python.org/dev/peps/pep-0498/ to do the following:
def dd2dms(deg):
d = int(deg)
md = abs(deg - d) * 60
m = int(md)
sd = (md - m) * 60
return f'{d}:{m}:{sd}'
You can even do computations in the strings
for instance, you could do :
def dd2dms(deg):
d = int(deg)
md = abs(deg - d) * 60
m = int(md)
return f'{d}:{m}:{(md - m) * 60}'
However, it's usually better to declare your variables explicitly.

Related

Optimizing mathematical formula implementation with concatenations of summations

I'm trying to implement this following formula in Python. It's basically a long concatenation os summations, where an additional summation is added each time a new 'element' is needed. To simply explain the formula's structure, here's how this formula goes in order from 2 to 5 elements:
2 elements
3 elements
4 elements
5 elements
By the way, here's the g function shown in the formulas:
g function
Now, I foolishly tried coding this formula with my extremely barebones python programming skills. The initial goal was to try this with 15 elements, but given that it contained a lot of nested for loops and factorials, I quickly noticed that I could not really obtain a result from that.
At the end I ended up with this monstrous code, that would finish just after the heat death of the universe:
from ast import Str
import math
pNuevos = [0,2,2,2,2,1,1,1,2,2,2,1,2,2,1,1]
pTotales = [0,10,10,7,8,7,7,7,7,7,10,7,8,7,8,8]
def PTirada (personajes):
tirada = 0.05/personajes
return tirada
def Ppers1 (personajes, intentos):
p1pers = ((math.factorial(intentos-1)) / ((math.factorial(4))*(math.factorial(intentos-5)))) * (PTirada(personajes)**5) * ((1-PTirada(personajes))**(intentos-5))
return p1pers
def Ppers2 (personajes, intentos):
p2pers = 0
for i in range(10,intentos+1):
p2pers = p2pers + ( (math.factorial(intentos-1)) / ((math.factorial(4))*(math.factorial(i-5))*(math.factorial(intentos-i))) ) * (PTirada(personajes)**i) * ((1 - 2*(PTirada(personajes))) **(intentos-i))
p2pers = 2*p2pers
return p2pers
def Activate (z) :
probability1 = 0
probability2 = 0
probability3 = 0
probability4 = 0
probability5 = 0
probability6 = 0
probability7 = 0
probability8 = 0
probability9 = 0
probability10 = 0
probability11 = 0
probability12 = 0
probability13 = 0
probability14 = 0
for i in range (5*pNuevos[1], z-5*pNuevos[2]+1):
for j in range (5*pNuevos[2], z-i-5*pNuevos[3]+1):
for k in range (5*pNuevos[3], z-j-i-5*pNuevos[4]+1):
for l in range (5*pNuevos[4], z-k-j-i-5*pNuevos[5]+1):
for m in range (5*pNuevos[5], z-l-k-j-i-5*pNuevos[6]+1):
for n in range (5*pNuevos[6], z-m-l-k-j-i-5*pNuevos[7]+1):
for o in range (5*pNuevos[7], z-n-m-l-k-j-i-5*pNuevos[8]+1):
for p in range (5*pNuevos[8], z-o-n-m-l-k-j-i-5*pNuevos[9]+1):
for q in range (5*pNuevos[9], z-p-o-n-m-l-k-j-i-5*pNuevos[10]+1):
for r in range (5*pNuevos[10], z-q-p-o-n-m-l-k-j-i-5*pNuevos[11]+1):
for s in range (5*pNuevos[11], z-r-q-p-o-n-m-l-k-j-i-5*pNuevos[12]+1):
for t in range (5*pNuevos[12], z-s-r-q-p-o-n-m-l-k-j-i-5*pNuevos[13]+1):
for u in range (5*pNuevos[13], z-t-s-r-q-p-o-n-m-l-k-j-i-5*pNuevos[14]+1):
for v in range (5*pNuevos[14], z-u-t-s-r-q-p-o-n-m-l-k-j-i-5*pNuevos[15]+1):
probability14 = probability14 + eval("Ppers"+str(pNuevos[14])+"("+str(pTotales[14])+","+str(v)+")") * eval("Ppers"+str(pNuevos[15])+"("+str(pTotales[15])+","+str(z-v-u-t-s-r-q-p-o-n-m-l-k-j-i)+")")
probability13 = probability13 + eval("Ppers"+str(pNuevos[13])+"("+str(pTotales[13])+","+str(u)+")") * probability14
probability12 = probability12 + eval("Ppers"+str(pNuevos[12])+"("+str(pTotales[12])+","+str(t)+")") * probability13
probability11 = probability11 + eval("Ppers"+str(pNuevos[11])+"("+str(pTotales[11])+","+str(s)+")") * probability12
probability10 = probability10 + eval("Ppers"+str(pNuevos[10])+"("+str(pTotales[10])+","+str(r)+")") * probability11
probability9 = probability9 + eval("Ppers"+str(pNuevos[9])+"("+str(pTotales[9])+","+str(q)+")") * probability10
probability8 = probability8 + eval("Ppers"+str(pNuevos[8])+"("+str(pTotales[8])+","+str(p)+")") * probability9
probability7 = probability7 + eval("Ppers"+str(pNuevos[7])+"("+str(pTotales[7])+","+str(o)+")") * probability8
probability6 = probability6 + eval("Ppers"+str(pNuevos[6])+"("+str(pTotales[6])+","+str(n)+")") * probability7
probability5 = probability5 + eval("Ppers"+str(pNuevos[5])+"("+str(pTotales[5])+","+str(m)+")") * probability6
probability4 = probability4 + eval("Ppers"+str(pNuevos[4])+"("+str(pTotales[4])+","+str(l)+")") * probability5
probability3 += eval("Ppers"+str(pNuevos[3]) + "("+str(pTotales[3])+","+str(k)+")") * probability4
probability2 += eval("Ppers"+str(pNuevos[2]) + "("+str(pTotales[2])+","+str(j)+")") * probability3
probability1 += eval("Ppers"+str(pNuevos[1]) + "("+str(pTotales[1])+","+str(i)+")") * probability2
return probability1
print (str(Activate(700)))
Edit: Alright I think it would be helpful to explain a couple things:
-First of all, I was trying to find ways the code could run faster, as I'm aware the nested for loops are a performance hog. I was also hoping there would be a way to optimize so many factorial operations.
-Also, the P(A) function described in the g function represents the probability of an event happening, which is already in the code, in the first function from the top.
There's also the function f in the formula, which is just a simplification of the function g for specific cases.
The function f is the second function in the code, whereas g is the third function in the code.
I will try to find a way to simplify the multiple summations, and thanks for the tip of not using eval()!
I'm sorry again for not specifying the question more, and for that mess of code also.
I would expect to break it down with something like this:
def main():
A = 0.5
m = 10
result = g(A, m)
return
def sigma(k, m):
''' function to deal with the sum loop'''
for k in range(10, m+1):
# the bits in the formula
pass
return
def g(A, m):
''' function to deal with g '''
k=10
return 2 * sigma(k,m)
if __name__=='__main__':
''' This is executed when run from the command line '''
main()
Or alternatively to do similar with classes.
I expect you also need a function for p(A) and one for factorials.

Fraction Value Problem in Ctypes to PARI/GP

I have written a code to compare the solution of sympy and PARI/GP, but when I give a fraction value D=13/12, I get error, TypeError: int expected instead of float.
So I changed p1[i] = pari.stoi(c_long(numbers[i - 1])) to p1[i] = pari.stoi(c_float(numbers[i - 1])), but then nfroots gives no output, note that I have to use fraction in A, B, C, D which might take $10^10$ digits after decimal point.
How can I solve this problem?
The code is given below to download the libpari.dll file, click here -
from ctypes import *
from sympy.solvers import solve
from sympy import Symbol
pari = cdll.LoadLibrary("libpari.dll")
pari.stoi.restype = POINTER(c_long)
pari.cgetg.restype = POINTER(POINTER(c_long))
pari.gtopoly.restype = POINTER(c_long)
pari.nfroots.restype = POINTER(POINTER(c_long))
(t_VEC, t_COL, t_MAT) = (17, 18, 19) # incomplete
pari.pari_init(2 ** 19, 0)
def t_vec(numbers):
l = len(numbers) + 1
p1 = pari.cgetg(c_long(l), c_long(t_VEC))
for i in range(1, l):
#Changed c_long to c_float, but got no output
p1[i] = pari.stoi(c_long(numbers[i - 1]))
return p1
def Quartic_Comparison():
x = Symbol('x')
a=0;A=0;B=1;C=-7;D=13/12 #PROBLEM 1
solution=solve(a*x**4+A*x**3+B*x**2+ C*x + D, x)
print(solution)
V=(A,B,C,D)
P = pari.gtopoly(t_vec(V), c_long(-1))
res = pari.nfroots(None, P)
print("elements as long (only if of type t_INT): ")
for i in range(1, pari.glength(res) + 1):
print(pari.itos(res[i]))
return res #PROBLEM 2
f=Quartic_Comparison()
print(f)
The error is -
[0.158343724039430, 6.84165627596057]
Traceback (most recent call last):
File "C:\Users\Desktop\PARI Function ellisdivisible - Copy.py", line 40, in <module>
f=Quartic_Comparison()
File "C:\Users\Desktop\PARI Function ellisdivisible - Copy.py", line 32, in Quartic_Comparison
P = pari.gtopoly(t_vec(V), c_long(-1))
File "C:\Users\Desktop\PARI Function ellisdivisible - Copy.py", line 20, in t_vec
p1[i] = pari.stoi(c_long(numbers[i - 1]))
TypeError: int expected instead of float
The PARI/C type system is very powerful and can also work with user-defined precision. Therefore PARI/C needs to use its own types system, see e.g. Implementation of the PARI types https://pari.math.u-bordeaux.fr/pub/pari/manuals/2.7.6/libpari.pdf.
All these internal types are handled as pointer to long in the PARI/C world. Don't be fooled by this, but the type has nothing to do with long. It is perhaps best thought of as an index or handle, representing a variable whose internal representation is hidden from the caller.
So whenever switching between PARI/C world and Python you need to convert types.
Conversion are described e.g. in section 4.4.6 in the above mentioned PDF file.
To convert a double to the corresponding PARI type (= t_REAL) one would therefore call the conversion function dbltor.
With the definition of
pari.dbltor.restype = POINTER(c_long)
pari.dbltor.argtypes = (c_double,)
one could get a PARI vector (t_VEC) like this:
def t_vec(numbers):
l = len(numbers) + 1
p1 = pari.cgetg(c_long(l), c_long(t_VEC))
for i in range(1, l):
p1[i] = pari.dbltor(numbers[i - 1])
return p1
User-defined Precision
But the type Python type double has limited precision (search e.g. for floating point precision on stackoverflow).
Therefore if you want to work with defined precision I would recommend to use gdiv.
Define it e.g. like so:
V = (pari.stoi(A), pari.stoi(B), pari.stoi(C), pari.gdiv(pari.stoi(13), pari.stoi(12)))
and adjust t_vec accordingly, to get a vector of these PARI numbers:
def t_vec(numbers):
l = len(numbers) + 1
p1 = pari.cgetg(c_long(l), c_long(t_VEC))
for i in range(1, l):
p1[i] = numbers[i - 1]
return p1
You then need to use realroots to calculate the roots in this case, see https://pari.math.u-bordeaux.fr/dochtml/html-stable/Polynomials_and_power_series.html#polrootsreal.
You could likewise use rtodbl to convert a PARI type t_REAL back to a double. But the same applies, since with using a floating point number you would loose precision. One solution here could be to convert the result to a string and display the list with the strings in the output.
Python Program
A self-contained Python program that considers the above points might look like this:
from ctypes import *
from sympy.solvers import solve
from sympy import Symbol
pari = cdll.LoadLibrary("libpari.so")
pari.stoi.restype = POINTER(c_long)
pari.stoi.argtypes = (c_long,)
pari.cgetg.restype = POINTER(POINTER(c_long))
pari.cgetg.argtypes = (c_long, c_long)
pari.gtopoly.restype = POINTER(c_long)
pari.gtopoly.argtypes = (POINTER(POINTER(c_long)), c_long)
pari.dbltor.restype = POINTER(c_long)
pari.dbltor.argtypes = (c_double,)
pari.rtodbl.restype = c_double
pari.rtodbl.argtypes = (POINTER(c_long),)
pari.realroots.restype = POINTER(POINTER(c_long))
pari.realroots.argtypes = (POINTER(c_long), POINTER(POINTER(c_long)), c_long)
pari.GENtostr.restype = c_char_p
pari.GENtostr.argtypes = (POINTER(c_long),)
pari.gdiv.restype = POINTER(c_long)
pari.gdiv.argtypes = (POINTER(c_long), POINTER(c_long))
(t_VEC, t_COL, t_MAT) = (17, 18, 19) # incomplete
precision = c_long(38)
pari.pari_init(2 ** 19, 0)
def t_vec(numbers):
l = len(numbers) + 1
p1 = pari.cgetg(c_long(l), c_long(t_VEC))
for i in range(1, l):
p1[i] = numbers[i - 1]
return p1
def quartic_comparison():
x = Symbol('x')
a = 0
A = 0
B = 1
C = -7
D = 13 / 12
solution = solve(a * x ** 4 + A * x ** 3 + B * x ** 2 + C * x + D, x)
print(f"sympy: {solution}")
V = (pari.stoi(A), pari.stoi(B), pari.stoi(C), pari.gdiv(pari.stoi(13), pari.stoi(12)))
P = pari.gtopoly(t_vec(V), -1)
roots = pari.realroots(P, None, precision)
res = []
for i in range(1, pari.glength(roots) + 1):
res.append(pari.GENtostr(roots[i]).decode("utf-8")) #res.append(pari.rtodbl(roots[i]))
return res
f = quartic_comparison()
print(f"PARI: {f}")
Test
The output on the console would look like:
sympy: [0.158343724039430, 6.84165627596057]
PARI: ['0.15834372403942977487354358292473161327', '6.8416562759605702251264564170752683867']
Side Note
Not really asked in the question, but just in case you want to avoid 13/12 you could transform your formula from
to

Pretty-printing physical quantities with automatic scaling of SI prefixes

I am looking for an elegant way to pretty-print physical quantities with the most appropriate prefix (as in 12300 grams are 12.3 kilograms). A simple approach looks like this:
def pprint_units(v, unit_str, num_fmt="{:.3f}"):
""" Pretty printer for physical quantities """
# prefixes and power:
u_pres = [(-9, u'n'), (-6, u'µ'), (-3, u'm'), (0, ''),
(+3, u'k'), (+6, u'M'), (+9, u'G')]
if v == 0:
return num_fmt.format(v) + " " + unit_str
p = np.log10(1.0*abs(v))
p_diffs = np.array([(p - u_p[0]) for u_p in u_pres])
idx = np.argmin(p_diffs * (1+np.sign(p_diffs))) - 1
u_p = u_pres[idx if idx >= 0 else 0]
return num_fmt.format(v / 10.**u_p[0]) + " " + u_p[1] + unit_str
for v in [12e-6, 3.4, .123, 3452]:
print(pprint_units(v, 'g', "{: 7.2f}"))
# Prints:
# 12.00 µg
# 3.40 g
# 123.00 mg
# 3.45 kg
Looking over units and Pint, I could not find that functionality. Are there any other libraries which typeset SI units more comprehensively (to handle special cases like angles, temperatures, etc)?
I have solved the same problem once. And IMHO with more elegance. No degrees or temperatures though.
def sign(x, value=1):
"""Mathematical signum function.
:param x: Object of investigation
:param value: The size of the signum (defaults to 1)
:returns: Plus or minus value
"""
return -value if x < 0 else value
def prefix(x, dimension=1):
"""Give the number an appropriate SI prefix.
:param x: Too big or too small number.
:returns: String containing a number between 1 and 1000 and SI prefix.
"""
if x == 0:
return "0 "
l = math.floor(math.log10(abs(x)))
if abs(l) > 24:
l = sign(l, value=24)
div, mod = divmod(l, 3*dimension)
return "%.3g %s" % (x * 10**(-l + mod), " kMGTPEZYyzafpnµm"[div])
CommaCalc
Degrees like that:
def intfloatsplit(x):
i = int(x)
f = x - i
return i, f
def prettydegrees(d):
degrees, rest = intfloatsplit(d)
minutes, rest = intfloatsplit(60*rest)
seconds = round(60*rest)
return "{degrees}° {minutes}' {seconds}''".format(**locals())
edit:
Added dimension of the unit
>>> print(prefix(0.000009, 2))
9 m
>>> print(prefix(0.9, 2))
9e+05 m
The second output is not very pretty, I know. You may want to edit the formating string.
edit:
Parse inputs like 0.000009 m². Works on dimensions less than 10.
import unicodedata
def unitprefix(val):
"""Give the unit an appropriate SI prefix.
:param val: Number and a unit, e.g. "0.000009 m²"
"""
xstr, unit = val.split(None, 2)
x = float(xstr)
try:
dimension = unicodedata.digit(unit[-1])
except ValueError:
dimension = 1
return prefix(x, dimension) + unit
The decimal module can help. Morover it prevents bad float rounding.
import decimal
prefix="yzafpnµm kMGTPEZY"
shift=decimal.Decimal('1E24')
def prettyprint(x,baseunit):
d=(decimal.Decimal(str(x))*shift).normalize()
m,e=d.to_eng_string().split('E')
return m + " " + prefix[int(e)//3] + baseunit
print(prettyprint (12300,'g'))
>>>> '12.3 kg'
it can be tuned to manage format.
If you're interested in using Pint, check out the to_compact method. This hasn't made it into the documentation, but I think it does what you're looking for!
Here is the implementation of the example from the OP:
import pint
ureg = pint.UnitRegistry()
for v in [12e-6, 3.4, .123, 3452]:
print('{:~7.2f}'.format((v * ureg('g')).to_compact()))
>>> 12.00 ug
>>> 3.40 g
>>> 123.00 mg
>>> 3.45 kg

Obfuscated mandlebrot function - can someone deobfuscate it?

I'm new to python and i've become very interested in it's ability to produce fractal images. I've written a few simple ones myself, but I just discovered a script for Mandelbrot fractals... it produces beautiful, full color images at your desired resolution.... but the code is obfuscated to look like ASCII art of a Mandelbrot.... really cool, but silly if you want to read it easily. It contains functions I haven't learned yet in python, so if someone can indent the script to look like normal python script, that'd be great.
The script:
_ = (
255,
lambda
V ,B,c
:c and Y(V*V+B,B, c
-1)if(abs(V)<6)else
( 2+c-4*abs(V)**-0.4)/i
) ;v, x=7200,4800;C=range(v*x
);import struct;P=struct.pack;M,\
j ='<QIIHHHH',open('M.bmp','wb').write
for X in j('BM'+P(M,v*x*3+26,26,12,v,x,1,24))or C:
i ,Y=_;j(P('BBB',*(lambda T:(T*80+T**9
*i-950*T **99,T*70-880*T**18+701*
T **9 ,T*i**(1-T**45*2)))(sum(
[ Y(0,(A%3/3.+X%v+(X/v+
A/3/3.-x/2)/1j)*2.5
/x -2.7,i)**2 for \
A in C
[:9]])
/9)
) )
As I said, the art is cool, but too hard to read! If someone can do this, I'd be greatly thankful.
Note: This is not meant as a definitive answer, but as an effort for a step-by-step de-obfuscation. If you can provide an additional step to make things clearer, it would be great if you could add it to this answer.
Okay, let's start by giving the code proper newlines and indentation:
_ = (255,
lambda V, B, c: c and Y(V*V + B, B, c-1) if(abs(V) < 6) else (2 + c - 4 * abs(V)**-0.4)/i)
v, x = 7200, 4800
C = range(v*x)
import struct
P=struct.pack
M, j = '<QIIHHHH', open('M.bmp','wb').write
for X in j('BM' + P(M, v*x*3+26, 26, 12, v, x, 1, 24)) or C:
i, Y = _
j(
P('BBB',
*(lambda T: (T * 80 + T**9 * i - 950 * T**99, T*70 - 880* T**18 + 701* T**9, T* i**(1-T**45*2)))(
sum([Y(0, (A%3/3. + X%v + (X/v + A/3/3. - x/2)/1j) * 2.5/x - 2.7, i)**2 for A in C[:9]]) / 9
)
)
)
A bit better, but still confusing. For example, defining P as an alias for struct.pack, and all those two-declarations-in-one lines. If we get rid of them, and move the lambda definition outside the loop, we get this:
import struct
i = 255
Y = lambda V, B, c: c and Y(V*V + B, B, c-1) if(abs(V) < 6) else (2 + c - 4 * abs(V)**-0.4)/i
v = 7200
x = 4800
C = range(v*x)
M = '<QIIHHHH'
color = lambda T: (T * 80 + T**9 * i - 950 * T**99, T*70 - 880* T**18 + 701 * T**9, T * i**(1-T**45*2))
f = open('M.bmp','wb')
for X in f.write('BM' + struct.pack(M, v*x*3+26, 26, 12, v, x, 1, 24)) or C:
f.write(
struct.pack('BBB',
*color(sum([Y(0, (A%3/3. + X%v + (X/v + A/3/3. - x/2)/1j) * 2.5/x - 2.7, i)**2 for A in C[:9]]) / 9))
)
Things are starting to get a bit clearer now. The loop is writing color values for each pixel, and the lambda returns a 3-tuple, representing the blue, green and red values of each pixel.
import struct
i = 255
Y = lambda V, B, c: c and Y(V*V + B, B, c-1) if abs(V) < 6 else (
(2 + c - 4 * abs(V)**-0.4)/i)
v = 7200
x = 4800
C = range(v*x)
M = '<QIIHHHH'
color = lambda T: (T * 80 + T**9 * i - 950 * T**99,
T*70 - 880* T**18 + 701 * T**9,
T * i**(1-T**45*2))
f = open('M.bmp', 'wb')
for X in f.write('BM' + struct.pack(M, v*x*3+26, 26, 12, v, x, 1, 24)) or C:
f.write(struct.pack('BBB',
*color(sum(
[Y(0, (A%3/3. + X%v + (X/v + A/3/3. - x/2)/1j) * 2.5/x - 2.7, i)**2
for A in C[:9]]) / 9))
)
As per your comment, the asterisk (the star, *) unpacks a list into an argument list.
After many hours, here's the nearly 100 MB image produced of the Mandelbrot set:

Non-sequential substitution in SymPy

I'm trying to use [SymPy][1] to substitute multiple terms in an expression at the same time. I tried the [subs function][2] with a dictionary as parameter, but found out that it substitutes sequentially.
In : a.subs({a:b, b:c})
Out: c
The problem is the first substitution resulted in a term that can be substituted by the second substitution, but it should not (for my cause).
Any idea on how to perform the substitutions simultaneously, without them interfering with each other?
Edit:
This is a real example
In [1]: I_x, I_y, I_z = Symbol("I_x"), Symbol("I_y"), Symbol("I_z")
In [2]: S_x, S_y, S_z = Symbol("S_x"), Symbol("S_y"), Symbol("S_z")
In [3]: J_is = Symbol("J_IS")
In [4]: t = Symbol("t")
In [5]: substitutions = (
(2 * I_x * S_z, 2 * I_x * S_z * cos(2 * pi * J_is * t) + I_y * sin(2 * pi * J_is * t)),
(I_x, I_x * cos(2 * pi * J_is * t) + 2 * I_x * S_z * sin(2 * pi * J_is * t)),
(I_y, I_y * cos(2 * pi * J_is * t) - 2 * I_x * S_z * sin(2 * pi * J_is * t))
)
In [6]: (2 * I_x * S_z).subs(substitutions)
Out[7]: (I_y*cos(2*pi*J_IS*t) - 2*I_x*S_z*sin(2*pi*J_IS*t))*sin(2*pi*J_IS*t) + 2*S_z*(I_x*cos(2*pi*J_IS*t) + 2*I_x*S_z*sin(2*pi*J_IS*t))*cos(2*pi*J_IS*t)
Only the appropriate substitution should happen, in this case only the first one. So the expected output should be the following:
In [6]: (2 * I_x * S_z).subs(substitutions)
Out[7]: I_y*sin(2*pi*J_IS*t) + 2*I_x*S_z*cos(2*pi*J_IS*t)
The current version of sympy provides the keyword simultaneous. The complicated operations in the previous answers are no more necessary:
In [1]: (x*sin(y)).subs([(x,y),(y,x)],simultaneous=True)
Out[1]: y⋅sin(x)
The subs(self,*args) method is defined (in part) this way:
In [11]: x.subs??
...
sequence = args[0]
if isinstance(sequence, dict):
return self._subs_dict(sequence)
elif isinstance(sequence, (list, tuple)):
return self._subs_list(sequence)
If you pass subs a dict, you lose control over the order of the substitutions.
While if you pass subs a list or tuple, you can control the order.
This doesn't allow you to do simultaneous substitutions. That would lead to difficulties if the user were to pass stuff like x.subs([(x,y),(y,x)]). So I doubt sympy has a method for doing simultaneous substitutions. Instead I believe all substutions are either unordered (if you pass a dict) or, at best, done by a 1-pass ordered substitution (if you pass a list or tuple):
In [17]: x.subs([(x,y),(y,z)])
Out[18]: z
In [19]: x.subs([(y,z),(x,y)])
Out[19]: y
PS. _subs_list(self, sequence) is defined (in part) like this:
In [14]: x._subs_list??
...
for old, new in sequence:
result = result.subs(old, new)
This nails down the order in which the subs are done.
Example for #~unutbu's answer:
>>> import ordereddict # collections.OrderedDict in Python 2.7+
>>> from sympy import *
>>> x,y,z = symbols('xyz')
>>> x.subs(ordereddict.OrderedDict([(x,y),(y,z)]))
y
>>> x.subs(ordereddict.OrderedDict([(y,z),(x,y)]))
z
Answering the edited question.
In your example you can use some temporary variables which will not be over-written be subsequent substitutions. Then, once all of the potentially overlapping substitutions have been made, you can replace the temporary variables with the real ones.
This example works for the question, if your full problem contains more complex substitutions, I think you should still be able to create temporary variables to avoid overlapping substitutions.
from sympy import Symbol, sin, cos, pi
I_x, I_y, I_z = Symbol("I_x"), Symbol("I_y"), Symbol("I_z")
S_x, S_y, S_z = Symbol("S_x"), Symbol("S_y"), Symbol("S_z")
J_is = Symbol("J_IS")
t = Symbol("t")
I_x_temp, I_y_temp, I_z_temp = Symbol("I_x_temp"), Symbol("I_y_temp"), Symbol("I_z_temp")
f = 2*I_x*S_z
answer = I_y*sin(2*pi*J_is*t) + 2*I_x*S_z*cos(2*pi*J_is*t)
subs1a = [
(2*I_x*S_z, 2*I_x_temp*S_z*cos(2*pi*J_is*t) + I_y_temp*sin(2*pi*J_is*t)),
(I_x, I_x_temp*cos(2* pi*J_is*t) + 2*I_x_temp*S_z*sin(2*pi*J_is*t)),
(I_y, I_y_temp*cos(2*pi*J_is*t) - 2*I_x_temp*S_z* sin(2*pi*J_is*t))
]
subs_temp = [(I_x_temp, I_x), (I_y_temp, I_y), (I_z_temp, I_z)]
print f
f = f.subs(subs1a)
print f
f = f.subs(subs_temp)
print f
print f == answer # True
Note, you can also perform two substitutions back to back:
f.subs(subs1a).subs(subs_temp) == answer
The Keyword simultaneous will do non-clashing subs regardless of the input (dict or sequence):
>>> x.subs([(x,y),(y,z)],simultaneous=1)
y
>>> x.subs([(y,z),(x,y)],simultaneous=1)
y

Categories