Yes, I love python. However, I am no expert. Most of the stuff I write in python is dirty and ugly code. Sometimes I figure out new things (things that programmers already know) and sometimes I forget these things. So, here are a few tips and tricks that I use from time to time. Really, I am writing this for future Rhett when he does a google search for “how do you save data to a file in python”.
Saving data to a file
Suppose I am modeling a basketball falling through the air. I want to plot this data, so I save position and time data in lists. For example: Here is the info from scipy.org that covers this same stuff.
x = [0.1, 0.2, 0.3, 0.41, 0.52]
t=[1, 2, 3, 4, 5]
In this case, there really isn’t a problem. However, what if I have 1000 data points in each list and I want to use it again? If the program only takes a second to run, I will just re-create that data. Sometimes this is not feasible. What if I want to model throwing a basketball 1000 times and each time it takes about 1 second to calculate. 1000 seconds is not too long to wait, not too long unless you are impatient like me. Ok, how do you save this sucker as a file?
Here is a super-simple sample:
Of course, the key here is the “savetxt” function. If you don’t import the pylab module, it might not work. I think the savetxt function is part of numpy (which is in pylab) – just load pylab to be safe. Also, the file is saved to the same folder as your python script is in. The default settings for the savetxt function makes a space delimited file – you can change that if you want a comma delimiter, just add this:
One more note: Python is ruthlessly obedient. If you just spent 20 hours running a program and you save the file as temp_data.txt. Then later you run something and save it as temp_data.txt – done. It just overwrote your previous data. You can’t blame python, it is just doing what you told it to do.
What about getting the data back? Here is another sample that takes the data from the file created by the previous program and plots it.
The genfromtxt function basically is the inverse function of savetxt function. Notice that I had a list of lists for my data – I separated this into two separate lists for plotting (gotta keep em separated).
Everyone uses functions. But what if you want to make one yourself? It really isn’t too difficult. Let me start with a sample program. Suppose I want to use the same program as above, but I want to see what happens as I change the acceleration. One simple (and ugly) way would be to just keep copying the code from above how ever many times you want to change the acceleration. Another way would be to make a function that takes an acceleration and creates the data. Then you could just call this function as many times as you like.
Just to make this simple, suppose I want to look at the distance the object travels after 3 seconds as a function of acceleration.
Here, I created a function calc_dist(). It takes one parameter – the acceleration (which I labeled as ac so it wouldn’t get messed up with the variable a). The function is essentially the same as the previous program – but the key is the return. At the end of the function, what do you want it to give back? For this case, I have it just returning the final distance. It is possible to return any number of things. Suppose I wanted to also return the time (even though I already know that). At the end of the function, I would just put:
When I call this function, I could say result=calc(a), but result would be a list such that result would be the position and result would be the time.
The key thing to remember is to not make variables that appear both in the function and outside the function. This is bad. This is like crossing the streams from the Ghostbusters’ proton packs. Why are they called proton packs anyway?
Going through a list
I actually already used this idea above. What if I have a list of positions, and I want to print them:
The old Rhett would have made a variable n = 0 and then said something like “while n < 10:” and then in the loop have n = n +1. This python way is much easier. The ‘len’ is the length of the list and range says how high n should go. You don’t have to increment n yourself, python does it for you.
Oh, notice that I reference data[n]? Since data is a list of list – actually it looks like this:
The element data would be the 4th in the list with the first element in that 4th thing – remember python starts with 0 being the first element.
Histograms and Random Numbers
Histograms are useful – and super easy to make with MatPlotLib (which is in the pylab module). Here is a sample program:
Here is the output from that program:
This really shows two useful functions:
- hist(): this is just like the plot function (and it is in pylab). Just pass the list of data to the function and it will make a histogram. Boom. That simple. If you like, you can tell it how many bins to make (in this case I said 10 – which happens to be the default). I also made the bars green (I don’t know why, but blue always shows up funny on the webpage). Also, I turned on the grid. This is the matplotlib documentation on histograms.
- nomralvariate(): This function produces a random number from the normal distribution. If I just used the “random()” function, the histogram would be boring and flat. The normalvariate function is not in pylab, so you have to load the random module. The main arguments it takes are the average and the standard deviation of the distribution you want. Here is a description of other functions in the random module.
Oh, and you are welcome future Rhett. I hope you still have at least a little bit of hair.