I particularly like:
- the use of enumerator in loops: for i,x in enumerate(array)
- decorators as a simple way of enhancing methods: @method
- one-line swapping of variables: a,b=b,a
Tips and tricks on using Python and associated tools for astronomical and scientific purposes. Written by an astronomer who uses Python on a daily basis to do science.
import uncertainties as unc
import uncertainties.unumpy as unumpy
import numpy
import nemmen
# Defines x and y
x=numpy.linspace(0,10,50)
y=numpy.linspace(15,20,50)
# Defines the error arrays, values follow a normal distribution
# (method random_normal defined in http://astropython.blogspot.com/2012/04/how-to-generate-array-of-random-numbers.html)
errx=nemmen.random_normal(0.1,0.2,50); errx=numpy.abs(errx)
erry=nemmen.random_normal(0.3,0.2,50); erry=numpy.abs(erry)
# Defines special arrays holding the values *and* errors
x=unumpy.uarray(( x, errx ))
y=unumpy.uarray(( y, erry ))
"""
Now any operation that you carry on xerr and yerr will
automatically propagate the associated errors, as long
as you use the methods provided with uncertainties.unumpy
instead of using the numpy methods.
Let's for instance define z as
z = log10(x+y**2)
and estimate errz.
"""
z=unumpy.log10(x+y**2)
# Print the propagated error errz
errz=unumpy.std_devs(z)
print errz
def random_normal(mean,std,n):
"""
Returns an array of n elements of random variables, following a normal
distribution with the supplied mean and standard deviation.
"""
import scipy
return std*scipy.random.standard_normal(n)+mean
import fish
import time
steps=input('How many steps? ')
# Progress bar initialization
peixe = fish.ProgressFish(total=steps)
for i in range(steps):
# Progress bar
peixe.animate(amount=i)
time.sleep(0.1)