Révision | 1980f1515b14262f67c4adcde777ce04a494c981 (tree) |
---|---|
l'heure | 2007-05-23 16:58:06 |
Auteur | iselllo |
Commiter | iselllo |
I added the code Python-codes/newaxis.py. This simple code shows how to
use the newaxis feature in manipulating the arrays. Everything is done
to explain the suggestions by Anne Archibald about how to speed up the
code to solve Smoluchowsky equations
@@ -0,0 +1,49 @@ | ||
1 | +#! /usr/bin/env python | |
2 | +from scipy import * | |
3 | +import pylab # used to read the .csv file | |
4 | + | |
5 | +# this is a simple test code I use to understand how newaxis works in SciPy | |
6 | +# and to understand how Anne Archibald was able to re-express concisely the creation | |
7 | +# of k-mers in Smoluchowsky equation | |
8 | + | |
9 | + | |
10 | +kern=arange(16) | |
11 | +kern.shape=(4,4) | |
12 | +print 'kern is', kern | |
13 | + | |
14 | +y=array([1,2,4,3]) | |
15 | +#y=arange(4) | |
16 | + | |
17 | +print 'y is',y | |
18 | + | |
19 | +kyn=kern*y[:,newaxis]*y[newaxis,:] | |
20 | +# the position of the newaxis determines that one vector y is seen as y[i] and the other | |
21 | +# as y[j] | |
22 | +# See this also by calculating | |
23 | +#kyn=kern*y[newaxis,:] | |
24 | +# and | |
25 | +#kyn=kern*y[:,newaxis] | |
26 | + | |
27 | +print 'kyn is', kyn | |
28 | + | |
29 | +z=y[:,newaxis]+y[newaxis,:] | |
30 | +print 'z is',z | |
31 | + | |
32 | + | |
33 | +k=0 | |
34 | +#This is now the whole point: if you look at the code to solve smoluchowsky equation | |
35 | +# first you see that in the loop there is the condition: | |
36 | +# i+1+j+1=k+1 ---> j=k-i-1 | |
37 | +#The matrix red implements exactly this: the first element is i and it varies in | |
38 | +# arange(k), whereas the 2nd one is j and it is equal to k-i-1. | |
39 | +# note that while k is fixed each time, arange(k) is an array! | |
40 | +# in the code by Anne, there is also a loop on k and finally red is summed to get the creator | |
41 | +# (apart from a trivial multiplication times a factor 0.5) | |
42 | +red=kyn[arange(k),k-arange(k)-1] | |
43 | + | |
44 | +print 'red is',red | |
45 | + | |
46 | +print 'sum(red) is',sum(red) #this works OK, since fixing k=0 sets the creator =0 (I can | |
47 | +#not create the fundamental monomer | |
48 | + | |
49 | +print 'So far so good' | |
\ No newline at end of file |