[Tutor] python magazine
Friends, I am sorry if this query is not appropriate to this forum. Is there any online magazine dedicated to python especially its features and How-to's that i can subscribe for. Thanks, Bala ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] set and sets.Set
Friends, Someone please write me the difference between creating set with set() and a sets.Set(). >>> a=set([1,2,3]) >>> b=sets.Set([1,2,3]) >>> print a set([1, 2, 3]) >>> print b Set([1, 2, 3]) Thanks, Bala ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] circular looping
Friends, I have a list. I have to do some comparison of each item in the list with each other items in the list. from numpy import zeros a=zeros((5,5)) myres=['R', 'N', 'L', 'C', 'M'] DON=['R','N','L'] ; ALL=['R','L','M','S'] for x in myres: for y in myres: if x in DON: if y in ALL: a[res.index(x),res.index(y)] = 1 else: continue But here the value of y changes sequentially. I want y to cycle through the list something like the following. Is there any function to do such circular iteration. cycle 1 y's value should be 'N', 'L', 'C', 'M, 'R' index 1,2,3,4,0 of myres cycle 2 y's value should be 'L', 'C', 'M, 'R', 'N' index 2,3,4,0,1 ,, cycle 3 y's value should be 'C', 'M', 'R', 'N','L' index 3,4,0,1,2 ,, Thank you, Bala ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] extract a submatrix
Friends, Excuse me if this question is not appropriate for this forum. I have a matrix of size 550,550. I want to extract only part of this matrix say first 330 elements, i dnt need the last 220 elements in the matrix. is there any function in numpy that can do this kind of extraction. I am quite new to numpy. How can do the same ? Thank you, Bala ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] extract a submatrix
Dear Eike, Thank you so much, the simple slicing operation solved my problem. Thank you for the links, i am just going through the same. Dave I wanted was to extract a matrix of dimension 330,330 from a matrix of dimension 550,550. Sorry if my previous post was not clear. I am able to do it by slicing as suggested by Eike. Thank you, Bala On Mon, Jul 12, 2010 at 1:17 PM, Dave Angel wrote: > > > Bala subramanian wrote: > >> Friends, >> Excuse me if this question is not appropriate for this forum. I have a >> matrix of size 550,550. I want to extract only part of this matrix say >> first >> 330 elements, i dnt need the last 220 elements in the matrix. is there any >> function in numpy that can do this kind of extraction. I am quite new to >> numpy. How can do the same ? >> >> Thank you, >> Bala >> >> >> > I don't know numpy, and it probably would be better to use that forum. But > there are several people here who do, and one of them will probably help. > > However, I would point out that if you fetch the first 220 elements of a > 550x550 matrix, you'll have 302170 elements left. > > DaveA > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] searching for multiple strings in line.starswith()
Friends, I have to extract the line from a file that does not contain a set of strings in the start of the line, i wrote the following code. for index, line in enumerate(myvar.split('\n')): if line.startswith('') not in ['#Cluster','#Centroid','#End']: line=line.split() print line The code works without error but it seems that the condition is not applied. What is the correct way of searching for multiple strings at the start of a line. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] problem with subprocess
Dear Friends, I have to do a series of job in a remote machine. I put each job in a text file called 'job' as and wrote the following code that can read each line in the text file and execute the job. I login to the machine and run the script as 'python job.py'. But when i logout from the machine, the job gets killed. So i submitted the job in background as 'python job.py &'. Even in this case, when i logout from the machine, the job gets killed. Why is this so. How can i avoid the same ? #!/usr/bin/env python from sys import argv import subprocess for line in open('job'): subprocess.call(line,shell=True) Thanks, Bala ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problem with subprocess
Thank you so much. I could see the job running with nohup after logout. Bala On Fri, Jul 30, 2010 at 3:49 PM, Hugo Arts wrote: > On Fri, Jul 30, 2010 at 2:36 PM, Bala subramanian > wrote: > > Dear Friends, > > > > I have to do a series of job in a remote machine. I put each job in a > text > > file called 'job' as and wrote the following code that can read each line > in > > the text file and execute the job. > > > > Why not just write a shellscript? that's essentially a list of jobs > anyway. if you make the first line of the file #! /bin/bash you can > basically execute it directly. > > > I login to the machine and run the script as 'python job.py'. But when i > > logout from the machine, the job gets killed. So i submitted the job in > > background as 'python job.py &'. Even in this case, when i logout from > the > > machine, the job gets killed. Why is this so. How can i avoid the same ? > > > > you need to run 'nohup python job.py'. background process still get > SIGHUP when you log out, so they'll still exit. > > http://www.computerhope.com/unix/unohup.htm > > Hugo > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] module for clustering
Friends, I have X and Y points and i want to cluster these points in 2D space, Kindly suggest if there is any module that is loaded with python to do that or any other package for the same. Thanks, Bala ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] extracting a column from many files
Dear friends, I want to extract certain 6 different columns from a many files and write it to 6 separate output files. I took some help from the following link http://mail.python.org/pipermail/tutor/2004-November/033475.html to write one column from many input files to a particular output file. Since i have to extract 6 such columns, i wanted to loop the output file writing part. This block of the script is shown in bold below. I see some odd output file names. Kindly suggest me i ) how best or should i do this loop part ii) explanation of the working *row=map(None,*value) *below which i adopted from the above tutor-mail list link. Thanks in advance, Bala #!/usr/bin/env python from sys import argv lst_files=argv[1:] sh=[];st=[];sta=[];buc=[];pro=[];ope=[] def extract(fname)*:* A=[];B=[];C=[];D=[];E=[];F=[] data=open(fname).readlines() for number, line in enumerate(data): if " Duplex" and " Shear" in line: number=number+3 for x in range(0,8): new=data[number] A.append(new[19:26]) B.append(new[27:34]) C.append(new[37:42]) D.append(new[44:54]) E.append(new[56:63]) F.append(new[69:75]) number = number + 1 sh.append(A) st.append(B) sta.append(C) buc.append(D) pro.append(E) ope.append(F) for x in lst_files: extract(x) *list=[sh,st,sta,buc,pro,ope]* *for value in list:* *row=map(None,*value)* *out=open(str(value) + '.txt','w') for num in row: out.write('\t'.join(num)) out.write('\n') out.close()* ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] extracting a column from many files
Hi, I have to extract say column 1, column 2 . column 6 (six different columns) from 10 different input files. The function "extract" to extract the columns works fine. For each column extracted from the input files, i have to write it in one output file. I have to make 6 output files correspondingly. How should i loop the writing of output files. Also, you had suggested previously the following way of creating list of row lists from the list of column lists rows = map(None, *listOfColumns) I am not getting how this works. Thanks, Bala On Thu, Feb 19, 2009 at 12:38 PM, Kent Johnson wrote: > On Thu, Feb 19, 2009 at 5:41 AM, Bala subramanian > wrote: > > Dear friends, > > > > I want to extract certain 6 different columns from a many files and write > it > > to 6 separate output files. I took some help from the following link > > > > http://mail.python.org/pipermail/tutor/2004-November/033475.html > > > > to write one column from many input files to a particular output file. > Since > > i have to extract 6 such columns, i wanted to loop the output file > writing > > part. > > Do you want the resulting files to have a single column, or one column > per input file? The mail you cite has one column per file. > > > This block of the script is shown in bold below. I see some odd output > > file names. > > You are using the string representation of the values as the file > name! What do you want to call the files? > > > Kindly suggest me i ) how best or should i do this loop part > > ii) explanation of the working row=map(None,*value) below which i adopted > > from the above tutor-mail list link. > > Please clarify what you want to do first. > Kent > > > > > Thanks in advance, > > Bala > > > > #!/usr/bin/env python > > from sys import argv > > lst_files=argv[1:] > > > > sh=[];st=[];sta=[];buc=[];pro=[];ope=[] > > > > def extract(fname): > > A=[];B=[];C=[];D=[];E=[];F=[] > > data=open(fname).readlines() > > for number, line in enumerate(data): > > if " Duplex" and " Shear" in line: > > number=number+3 > > for x in range(0,8): > > new=data[number] > > A.append(new[19:26]) > > B.append(new[27:34]) > > C.append(new[37:42]) > > D.append(new[44:54]) > > E.append(new[56:63]) > > F.append(new[69:75]) > > number = number + 1 > > sh.append(A) > > st.append(B) > > sta.append(C) > > buc.append(D) > > pro.append(E) > > ope.append(F) > > > > for x in lst_files: > > extract(x) > > > > list=[sh,st,sta,buc,pro,ope] > > for value in list: > > row=map(None,*value) > > out=open(str(value) + '.txt','w') > > for num in row: > > out.write('\t'.join(num)) > > out.write('\n') > > out.close() > > > > > > > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] extracting a column from many files
> > > file1: > 1a1 1b1 1c1 1d1 1e1 1f1 > 2a1 2b1 2c1 2d1 2e1 2f1 > 3a1 3b1 3c1 3d1 3e1 3f1 > > file2: > 1a2 1b2 1c2 1d2 1e2 1f2 > 2a2 2b2 2c2 2d2 2e2 2f2 > 3a2 3b2 3c2 3d2 3e2 3f2 > > How do you want the output files to look like? > I want to extract 1a1 2a1 3a1 from file 1, similarly 1a2 2a2 3a2 from file 2 ( same columns) and then make a new output file of the following format 1a1 1a2 --- 2a1 2a2 --- 3a1 3a2 --- Similarly for the 2nd, 3rd, 4th..columns in the input files. Thanks, Bala ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] overwriting input file
Hello all, query 1) How should i overwrite the input file I want to open 5 files one by one, do some operation on the lines and write the modified lines on the same file (overwritting). Can some please tell me how to do it. pat1=" R" pat2="U5" pat3="A3" from sys import argv files=argv[1:] for names in files: out=open(names + '_new','w') # Here i creat new files to write the content which i dnt want for line in open(names): if pat1 in line: line=line.replace(pat1," ") if pat2 in line: line=line.replace(pat2,"U ") if pat3 in line: line=line.replace(pat3,"A ") out.write(line) query 2) How should I use wild cards to open files in python. Say I have files with names *.dat in a directory, i want the program to open every file with extension .dat and do the process. Thanks in advance, Bala ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] learning new features of python
Dear Friends, Is there any website/tutorial that explains new features that are constantly getting embedded in python. This would be helpful for python lovers to grow with python and adopt new styles of codes. Just for an example, i read in Mark Luts "learning python" book, the various forms of except statements except name except name, value <-- present style except name as value <-- expected to be available in python 3.0 Similaraly in Alan Guald Learn to program link, he has given information on opening a file with file() and open() functions. Thanks, Bala ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] concatenating files
Hai, I have file1.dat,file2.dat...file 300.dat in one directory. I want to concatenate all the files in a single file (total.dat) with a string "END" separating the file contents. my total.dat should be file1.dat contents END file2.dat contents END file300.dat. now i have another 400 such *.dat files in another directory whose contents i hve to append to "total.dat", how can i do this task. i need to do something like, updating the file total.dat without overwritting it. Thanks, Bala ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] statistics with python
Dear python friends, someone kindly suggest me packages, modules and documentation resources (especially) to i) plot graphs using python. ii) statistical analysis using python. Thanks in advance, Bala ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] dynamically creating list
Dear Friends, I have a text output file from a program that does clustering. Now i have to parse the text output file to separate data points belonging to each cluster. I am thinking to design the algo. in the following way. i) ask the user the text output file ii) ask the user for the number of clusters created (say 5) iii) create 5 lists inside the program, write data points belonging to 5 different cluster in the 5 lists created 1) Now my question is, how to make this list creation dynamics, say if user enter number of clusters = 4, i would create four list. If the user enter 3, then i shd create three lists inside my program. How to do this dynamic creation of list depending on user input. 2) Is there any other better way or object that i can use to do this effectively. Thanks in advance, Bala ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] swapping lines between files
Dear Friends, Thanks for your replies for my previous mail. I have two files as follows. file 1 file2 200 1 3.55 210 2 4.55 242 3 1.22 248 4 3.10 25651.11 Now i have to replace 1,2,3,4,5 in *file 2* with 200,210,242,248,256 in * file1*. Simply *replacing position 1 in file2 with values in file1*. Can i do it with zip function, if yes how to do it. Here both files contain same number of lines. Thanks, Bala ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] returning values from function.
Friends, I wrote the following code to create two different list. One containing data points of all clusters and another containing list of individual cluster data points. The script is as follows. #!/usr/bin/env python from sys import argv # STEP 1: a) ACCUMULATING ALL DATA POINTS IN AND A LIST b) CREATING LIST OF INDIVIDUAL CLUSTERS print argv[1], argv[2] data=[] # list of all data points all=[ [] for value in range(int(argv[2])) ] # Creating an empty list of lists of size n (No of clusters) def cluster(infile=argv[1],n=int(argv[2])): for index, line in enumerate(infile): if line.startswith('#Consensus'): line=line.split() data.extend(line[2]) # data now should contain data points of all clusters for value in range(n): for index, line in enumerate(data): if data[index] == str(value): zero=index+1 all[value].append(zero) #return data, all ( I even tried by un commenting the return statement ) print all print data The final print statement returns a empty list ie all and data. I have the following queries i) Why the print statement returns empty lists ii) Is return really required here, if i understand the namespace well, the function cluster actually modifies the global variables data and all. iii) I even tried by using a return statement but still the script returns empty list. iv) Is there any fancy or better of way of doing this python. Thanks, Bala ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] text editor and debugger for python
Friends, I do the scripting in Linux. I use vi editor to code. It is not very convenient for me. Kindly suggest me a best free *text editor* ( i can code and debug the code simultaneously ) *for python* based on your experience. Thanks Bala ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] printing files
Friends, My files are like below file1 file2 RemarkRemark --- --- I have huge number of such files. I want to concatenate all files in one huge file. I could do it with a script. But i want to omit the first line (ie Remark in each file) and concatenate. How to do the same ? flist=glob.glob(*.txt) out=open('all','w') for files in flist: handle=open(flist).readlines() print>>out, handle <-- Here i want to write only from second line. I dnt want to loop over handle here and putting all lines except the first one in another variable. Is there any fancy way of doing it. out.close() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] plotting with python
Friends, I am not sure if this forum is appropriate to ask question about a particular package. After getting suggestions from some of you for python based plotting, I have just started with matplotlib. I am bit confused with the relation between matplotlib and pylab. In the matplotlib homepage, example plots are shown with both * matplotlib.pyplot* and* pylab*. Inaddition within matplotlib, there is a module called *matplotlib.pylab* i) matplotlib and pylab -> both are same or different modules ?. Is there any advantage of using one over the other ? ii) Is it like i can plot the graphs with both matplotlib and pylab ? iii) can some kindly show me an example of ploting multy Y axes plot, ie NXY. Thanks in advance, Bala ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] installation of scipy
Friends i installed scipy in fedora10 using yum. when i import stats module in it, i got the following warning. someone pls englihten me on this. >>> from scipy import stats /usr/lib/python2.5/site-packages/scipy/sparse/linalg/dsolve/linsolve.py:20: DeprecationWarning: scipy.sparse.linalg.dsolve.umfpack will be removed, install scikits.umfpack instead ' install scikits.umfpack instead', DeprecationWarning ) Thanks, Bala ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] curve fitting
Friends, I wish to do some curve fitting with python by defining my own equations. Could someone please give some guidance or examples on doing the same. Thanks, Bala ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] python assignments
Dear friends, I covered few introductory books on python. B4 going for an advanced book, i want to take up small, small assignments and try to solve with python. Can someone please suggest me any url where i can have assignments and solutions. Thanks, Bala ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] creating a regularly placed fields in a line
Friends, I wrote a small piece of code (given below). The aim is to take each line in a file, split the fields, replace the first four fields and then write the new lines in a output file. The input and output are given in the attached file. The output contains fields which are irregularly placed depending up on the size of the field. I am thinking to fix the size of each field. Kindly provide me some way on how i can do the same or a better way to fix placement of fields. with open('tmp') as tp: for line in tp: line=line.split() p1=atm_type[line[0]];p2=atm_type[line[1]] p3=atm_type[line[2]];p4=atm_type[line[3]] new='\t'.join(line[4:10]) bond.write(' %s\t%s\t%s\t%s\t%s\n' % (p1,p2,p3,p4,new) ) -- C. Balasubramanian test.output Description: Binary data ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] extracting lines between patterns.
Friends, Could someone please give some hint on how to extract lines between two patterns in a file. I use the re module to compile my patterns but not able to figure out how i can use these patterns to extract the lines lying in between. Thanks, Bala ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] extracting lines between patterns.
The code is given below. Here i try to extract lines that are between the two patterns atomtype and mol.type #!/usr/bin/env python import re mypat=re.compile(r'^[ atomtypes ]$[ moleculetype ]',re.MULTILINE) data=open('test.dat').read() extr=re.findall(mypat,data) print extr The data file is something like the following, [ defaults ] ; nbfunccomb-rule gen-pairs fudgeLJ fudgeQQ 1 2 no 0.5 0.8333 [ atomtypes ] ;name bond_type mass charge ptype N3 N3 0.0 0.0A HH 0.0 0.0 A CT CT 0.0 0.0 A HP HP 0.0 0.0 A O2 O2 0.0 0.0 A [ moleculetype ] ;namenrexcl tripe3 On Mon, May 14, 2012 at 9:53 AM, Russel Winder wrote: > On Mon, 2012-05-14 at 09:31 +0200, Bala subramanian wrote: > > Friends, > > Could someone please give some hint on how to extract lines between two > > patterns in a file. I use the re module to compile my patterns but not > able > > to figure out how i can use these patterns to extract the lines lying in > > between. > > Without the source code you already have, it is difficult to provide any > constructive suggestions. > > -- > Russel. > > = > Dr Russel Winder t: +44 20 7585 2200 voip: > sip:russel.win...@ekiga.net > 41 Buckmaster Roadm: +44 7770 465 077 xmpp: rus...@winder.org.uk > London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder > -- C. Balasubramanian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List Indexing Issue
Hi, I would suggest you to use the biopython package. It has a PDB parser with which you can extract any specific information like atom name, residue, chain etc as you wish. Bala On Wed, May 9, 2012 at 3:19 AM, Jerry Hill wrote: > On Tue, May 8, 2012 at 4:00 PM, Spyros Charonis > wrote: > > Hello python community, > > > > I'm having a small issue with list indexing. I am extracting certain > > information from a PDB (protein information) file and need certain > fields of > > the file to be copied into a list. The entries look like this: > > > > ATOM 1512 N VAL A 222 8.544 -7.133 25.697 1.00 48.89 > > N > > ATOM 1513 CA VAL A 222 8.251 -6.190 24.619 1.00 48.64 > > C > > ATOM 1514 C VAL A 222 9.528 -5.762 23.898 1.00 48.32 > > C > > > > I am using the following syntax to parse these lines into a list: > ... > > charged_res_coord.append(atom_coord[i].split()[1:9]) > > You're using split, assuming that there will be blank spaces between > your fields. That's not true, though. PDB is a fixed length record > format, according to the documentation I found here: > http://www.wwpdb.org/docs.html > > If you just have a couple of items to pull out, you can just slice the > string at the appropriate places. Based on those docs, you could pull > the x, y, and z coordinates out like this: > > > x_coord = atom_line[30:38] > y_coord = atom_line[38:46] > z_coord = atom_line[46:54] > > If you need to pull more of the data out, or you may want to reuse > this code in the future, it might be worth actually parsing the record > into all its parts. For a fixed length record, I usually do something > like this: > > pdbdata = """ > ATOM 1512 N VAL A 222 8.544 -7.133 25.697 1.00 48.89 > N > ATOM 1513 CA VAL A 222 8.251 -6.190 24.619 1.00 48.64 > C > ATOM 1514 C VAL A 222 9.528 -5.762 23.898 1.00 48.32 > C > ATOM 1617 N GLU A1005 11.906 -2.722 7.994 1.00 44.02 > N > """.splitlines() > > atom_field_spec = [ >slice(0,6), >slice(6,11), >slice(12,16), >slice(16,18), >slice(17,20), >slice(21,22), >slice(22,26), >slice(26,27), >slice(30,38), >slice(38,46), >slice(46,54), >slice(54,60), >slice(60,66), >slice(76,78), >slice(78,80), >] > > for line in pdbdata: >if line.startswith('ATOM'): >data = [line[field_spec] for field_spec in atom_field_spec] >print(data) > > > You can build all kind of fancy data structures on top of that if you > want to. You could use that extracted data to build a namedtuple for > convenient access to the data by names instead of indexes into a list, > or to create instances of a custom class with whatever functionality > you need. > > -- > Jerry > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- C. Balasubramanian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] removing sq. of items.
Friends, While iterating through each list item and printing/writing it, why does the sq. brackets get printed/written to the file. Just a small eg.code is given below. >>>N=100 >>> myl=range(1,100+1) >>> new=[myl[i:i+15] for i in range(0, len(myl),15)] >>> for x in new: print x Thanks, Bala ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] removing sq. of items.
Hi, I infact want write each of the item in the sliced list to a file. On Wed, May 23, 2012 at 11:59 AM, Sarma Tangirala wrote: > > > On 23 May 2012 15:21, Bala subramanian wrote: > >> Friends, >> While iterating through each list item and printing/writing it, why does >> the sq. brackets get printed/written to the file. Just a small eg.code is >> given below. >> >> >>>N=100 >> >>> myl=range(1,100+1) >> >>> new=[myl[i:i+15] for i in range(0, len(myl),15)] >> >>> for x in new: print x >> >> > When you slice 'myl[i:i+15]' you are creating a new list and adding that > to 'new'. So essentially you are nesting new lists within a > list comprehension. > > Hope that helps! > > >> Thanks, >> Bala >> >> >> >> >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > An monkey typed up this email. Please excuse him if he made a stupid error! > -- C. Balasubramanian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] passing global variable as argument.
Friends, I want to define a function that can populate an array by taking its name (which is defined globally). I defined two empty arrays as follows and a function that can populate the array. REF_F1=np.array([]) REF_F2=np.array([]) # populating the given array def ref(ln,REF_F1): global REF_F1 REF_F1=np.zeros((ln,3),dtype='float32') for i in range(ln): for j in range(3): REF_F1x[i,j]=resid[Index[i]].cent()[j] ref(ln, REF_F2) In this case, when i pass REF_F2 as argument, the fn. always populates array REF_F1. I also tried something like the following *def ref(ln,x=REF_F1)* and then calling as *ref(ln,x=REF_F2)*. The result is the same. Could someone please give me hint on how pass global variables as arguments. Thanks, Bala -- C. Balasubramanian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] passing global variable as argument.
Thank you wayne and steven. You suggestion to create a fresh array within the function and assigning it to variable worked fine and the result was exactly what i was looking for. In future i remember not to use global variables as fn. parameters. thanks once again for detailed explanation, bala On Mon, Jul 16, 2012 at 5:06 PM, Steven D'Aprano wrote: > Bala subramanian wrote: > >> Friends, >> I want to define a function that can populate an array by taking its name >> (which is defined globally). I defined two empty arrays as follows and a >> function that can populate the array. >> > > In general it is tricky to resize and populate numpy arrays in place. It > is usually better to just create a fresh array and reassign it. Something > like this should probably work: > > def ref(length): > arr = np.zeros((length, 3), dtype='float32') > for i in range(length): > for j in range(3): > arr[i, j] = resid[Index[i]].cent()[j] > return arr > > > ref_f1 = ref(3) > ref_f2 = ref(5) > > > should work for you. (I can't test it because you don't say what resid and > Index are.) > > > > To explain why your earlier code does not work the way you expect, read on: > > > > REF_F1=np.array([]) >> REF_F2=np.array([]) >> >> # populating the given array >> def ref(ln,REF_F1): >> > > So far this is good -- your function takes an argument called "REF_F1", > which can be any array you like. It's just a local name. > > The function sees REF_F1 is a local variable. > > > global REF_F1 >> > > But this is no good, because now you declare the name REF_F1 to be global > instead of local. So now the function sees REF_F1 as a global variable, and > everything that you do to it, occurs to the global called REF_F1. > > By the way, this bug is no longer permitted in the latest version of > Python. Using Python 3.2: > > py> x = 23 > py> def func(x): > ... global x > ... print("x =", x) > ... > File "", line 1 > SyntaxError: name 'x' is parameter and global > > > In general, if you feel the need to use "global", 90% of the time you are > doing something wrong and will have problems. You should avoid using global > unless absolutely necessary. > > > > -- > Steven > __**_ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > -- C. Balasubramanian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] suggestion for an editor
Friends, At present i write programs using vi editor. I am interested to change to something else. My specific need is that i want to select a portion/small segment of my program (for eg. a nested loop) and then monitor processing time it takes for that portion while i run the program. By this i hope to find the segment that takes time and modify to achieve better speed. Can someone please share their experience. Thanks, Bala -- C. Balasubramanian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] checking input parameters
Friends, I use the following way to check for the input parameters. I would like to know if there is a any better way to show or describe the script usage. So when the user just runs it without any input params., the program shd not execute but just shows the documentation. from sys import argv if not argv[1:]: print 'Program usage: python script file-list1 file-list2' print 'file list should contain the names of the atom list' Thanks, Bala -- C. Balasubramanian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] index of elements in numpy array
Friends, I have a 2D matrix (a numpy array) and i am looping over each row in the matrix. I would like to know how i can find the index of each element in a while looping a row. Is there any function in numpy. Thanks -- C. Balasubramanian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] index of elements in numpy array
Thank you all for the answer. Below, i have pasted a sample code that shows what i am intending to do. The code fails at line 13 as numpy array dnt have a index attribute. 1 #!/usr/bin/env python 2 import numpy as np 3 4 a=np.array([1,2,3,4,5,6,7,8,9,10,11,12]) 5 6 b=np.reshape(a,(3,4)) 7 8 z=[100,101,102,103,104,106,107,108,109,110,111,112] 9 10 # loop over each row 11 for i1, d1 in enumerate(b): 12 # each x in d1 - value in z corresponding to index of x in d1 13 d1=[x-z[d1.index(x)] for x in d1] If d1 is a simple list, i can fetch the index of its element as d1.index(x). So i would like to know how can achieve the same with numpy array. Thanks once again, Bala On Fri, Sep 14, 2012 at 12:39 AM, Dave Angel wrote: > On 09/13/2012 04:16 PM, Bala subramanian wrote: >> Friends, >> I have a 2D matrix (a numpy array) and i am looping over each row in >> the matrix. I would like to know how i can find the index of each >> element in a while looping a row. Is there any function in numpy. >> >> Thanks >> > > Perhaps you're asking a more general question. When iterating over a > collection, sometimes you not only want the object, but you also want > the index you might have used to fetch it. > > for row in rows: >dosomething with row > > for index, row in enumerate(rows): >dosomething with row and with index > > Now if rows be a list, or whatever numpy decides to call it, then you > can manipulate the particular one with rows[index]. > > > > -- > > DaveA > -- C. Balasubramanian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] combining c and python
Friends, I code in python and so far able to write simple scripts for my needs. Now i want to try the combination of c and python. 1) could someone please suggest me some good documentation on how python and C can be combined. Some tutorials with simple examples. 2) If i know that a specific part (loop in my case) within my python script consumes more processing time, is it possible to implement/use 'c' only for that part. Precisely using C within python ? Any link for documentation on such implementation would be of great help to me. Thanks, Bala ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] 1d to 2d array creation
Friends, I have an 1d array like a=[1, 1, 2, 2, 2, 3, 3, 1, 1, 1], i have to convert it to 2d array for plotting as follows. The 2d array is filled by a[colum index] to obtain the new array shown below. [ [ 1., 1., 0., 0., 0., 0., 0., 1., 1., 1.], [ 0., 0., 2., 2., 2., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 3., 3., 0., 0., 0.] ] I wrote the following simple code for the conversion. However i guess there should be more fancy/speeder way to do that. Also i need to create such 2d-array from larger 1d arrays of size 2,3 items etc. Hence i would like to request hints for a better code for the purpose. Here no. rows in my case is always = no. of discrete values in array a. >>>my=1 >>>for i in range(3): >>> for j in range(10): >>> if a[j] == my : b[i,j]=my >>> else: b[i,j]=0 >>> my +=1 Thanks, Bala ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] serial to parallel
Friends, In the previous mail there was an "mistake" i was not aware of. So pls dnt get upset. For frame in trajectory-A: > cunt= str(frame.time) It is count =str(frame.time). A counter to find frame number. Thanks joel for letting me to know it. Bala On Mon, Nov 5, 2012 at 11:46 AM, Bala subramanian wrote: > Friends, > I use a python package to analyse molecular trajectories. For those > not familiar, I have described the the problem below. > I have two trajectories A,B. Each trajectory has a collection of > frames. A frame is a numpy array. > For frame in trajectory-A: > cunt= str(frame.time) > function(trajectoryB, frame, outfile=cunt+'.txt') > process all .txt files > > The function is described in the package that I use. It also has a > built-in counter for each frame. > I want to convert this to a parallel code in the following way. Each > processor can take one frame from trajectory-A and applies the > function and write the corresponding output file. > This is the first time I am trying such parallelism. I would > appreciate your guidance on how I can do it. The original code is > pasted below. > --- > #!/usr/bin/env python > import MDAnalysis > from MDAnalysis.analysis.align import rmsd,fasta2select, rms_fit_trj > import argparse > import numpy as np > > parser = argparse.ArgumentParser(description=info) > # a series of parser.add_argument definitions > > U1=MDAnalysis.Universe(args.rtop,args.rtrj) # open trajectory-A > U2=MDAnalysis.Universe(args.ttop,args.ttrj) # open trajectory-B > > > for fr in U1.trajectory: > nd='%0*d' % ( 5,fr.frame) > rms_fit_trj(U2,U1.selectAtoms('all'),rmsdfile=str(nd) + '.rmsd') > > Thanks in advance, > Bala -- C. Balasubramanian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor