changes of os.chdir(instance.jobdirname) os.chdir('..')
[django_unres.git] / django_simple / todo / jobfiles.py
1 import logging
2
3 from django.db.models.signals import post_save, post_delete
4 from django.dispatch import receiver
5 from .models import Task
6 import os
7 import shutil
8 import subprocess
9 import json
10 from string import Template
11 import textwrap
12
13 logging.basicConfig()
14 logger = logging.getLogger(__name__)
15
16 def write_ssbond(ssbond):
17      list=[]
18      for e in ssbond:
19            list.append(e[0])
20            list.append(e[1])
21      list_sorted=sorted(list)
22      
23      if len(list)>0:
24        return str(len(list))+' '+' '.join(map(str,list_sorted))+'\n'+\
25             str(len(ssbond))+' '+' '.join(map(str,list))+'\n'
26      else: 
27        return '0\n'
28
29
30 @receiver(post_save, sender=Task)
31 def write_on_task_save(sender, instance, **kwargs):
32    if instance.ready and not instance.done and instance.running==0:
33      if (not os.path.isdir(instance.jobdirname)):
34         os.mkdir(instance.jobdirname)
35 #     os.chdir(instance.jobdirname)
36  
37
38
39 #md=Template('nstep=$nstep ntwe=100  ntwx=100   dt=0.20 damax=10.0 lang=1'+
40 #   't_bath=300 reset_vel=0 respa ntime_split=1 maxtime_split=512 mdpdb')
41 #wrapper = textwrap.TextWrapper(width=70)
42 #word_list = wrapper.wrap(text=md.substitute(nstep=str(nstep)))
43
44      w="""WSC=1.00000 WSCP=1.23315 WELEC=0.84476 WBOND=1.00000 WANG=0.62954              &
45 WSCLOC=0.10554 WTOR=1.34316 WTORD=1.26571 WCORRH=0.19212 WCORR5=0.00000        &
46 WCORR6=0.00000 WEL_LOC=0.37357 WTURN3=1.40323 WTURN4=0.64673 WTURN6=0.00000    &
47 WVDWPP=0.23173 WHPB=1.00000 WSCCOR=0.25                                        &
48 CUTOFF=7.00000 WCORR4=0.00000
49 """
50
51      with open(instance.jobdirname+'/file.inp','w') as f:
52        f.write(instance.name + ' UNRES server job'+ '\n')
53
54        if instance.type == 'min' :
55
56           control_line = 'SEED='+str(instance.md_seed)+' ' \
57              + instance.min_choice \
58              + ' pdbstart pdbref BOXX=1000. BOXY=1000. BOXZ=1000. '
59           if not instance.min_overlap:
60             control_line = control_line+'overlap '
61           if not instance.min_searchsc:
62             control_line = control_line+'nosearchsc '
63           if instance.min_pdbout:
64             control_line = control_line+'pdbout '
65           if instance.min_unres_pdb:
66             control_line = control_line+'unres_pdb '
67             
68           type_line = 'print_min_ini print_min_res print_min_stat'\
69             +' MAXMIN='+str(instance.min_maxmin)\
70             +' MAXFUN='+str(instance.min_maxfun)
71            
72
73        seq=instance.md_seq.replace(" ","")
74        dimen3=len(seq)
75        if dimen3>1:
76           if seq[0]=='X':
77             dimen3-=1
78           if seq[-1]=='X':
79             dimen3-=1
80   
81        nogly ='CDSQKIPTFNHLRWAVEYM'
82        seq2 = ''.join([c for c in seq if c in nogly])
83   
84        dimen3=(dimen3+len(seq2))*3
85          
86             
87        if instance.type == 'md' :
88           control_line = 'SEED='+str(instance.md_seed)+' '\
89            +instance.md_start +' md one_letter BOXX=1000. BOXY=1000. BOXZ=1000. '
90           if instance.md_pdbref:
91              control_line = control_line+'pdbref '
92             
93           type_line = 'reset_vel=0'\
94              +' t_bath='+str(instance.md_temp)\
95              +' nstep='+str(instance.md_nstep)\
96              +' ntwe='+str(instance.md_ntwe)\
97              +' ntwx='+str(instance.md_ntwx)\
98              +' dt='+str(instance.md_dt)
99           if instance.md_lang == 'langevin':
100             type_line = type_line + ' lang=1 '
101             type_line = type_line + 'scal_fric='+str(instance.md_scal_fric)
102           if instance.md_lang == 'berendsen':
103             type_line = type_line + ' lang=0 tbf '
104             type_line = type_line + 'tau_bath='+str(instance.md_tau)
105           if instance.md_respa:
106             type_line = type_line + ' respa '
107           if instance.md_mdpdb:
108             type_line = type_line + ' mdpdb '
109
110        if instance.type == 'remd' :
111           control_line = 'SEED='+str(instance.md_seed)+' '\
112            +instance.md_start +' re one_letter BOXX=1000. BOXY=1000. BOXZ=1000. '
113           if instance.md_pdbref:
114              control_line = control_line+'pdbref '
115            
116             
117           type_line = 'reset_vel='+ str(instance.remd_nstex)\
118              +' nstep='+str(instance.md_nstep)\
119              +' ntwe='+str(instance.md_ntwe)\
120              +' ntwx='+str(instance.remd_nstex)\
121              +' dt='+str(instance.md_dt)
122           if instance.md_lang == 'langevin':
123             type_line = type_line + ' lang=1 '
124             type_line = type_line + 'scal_fric='+str(instance.md_scal_fric)
125           if instance.md_lang == 'berendsen':
126             type_line = type_line + ' lang=0 tbf '
127             type_line = type_line + 'tau_bath='+str(instance.md_tau)
128           if instance.md_respa:
129             type_line = type_line + ' respa '
130           if instance.md_mdpdb:
131             type_line = type_line + ' mdpdb '
132           
133           type_line2 = 'nrep='+str(instance.remd_nrep) \
134              +' nstex='+str(instance.remd_nstex) \
135              +' tlist mlist sync nsyn='+str(instance.remd_nstex)\
136              +' traj1file  rest1file '
137
138        if instance.md_start == 'pdbstart':
139              type_line = type_line + ' preminim cart'
140
141        wrapper = textwrap.TextWrapper(width=70)
142
143        word_list = wrapper.wrap(text=control_line)
144        for element in word_list[:-1]:
145            f.write('{:79}'.format(element)+'&\n')
146        f.write(word_list[-1]+'\n')
147
148        word_list = wrapper.wrap(text=type_line)
149        for element in word_list[:-1]:
150            f.write('{:79}'.format(element)+'&\n')
151        f.write(word_list[-1]+'\n')
152           
153        if instance.md_start == 'pdbstart':
154          f.write('print_min_ini print_min_res print_min_stat\n')
155
156        
157        if instance.type == 'remd' :
158           word_list = wrapper.wrap(text=type_line2)
159           for element in word_list[:-1]:
160               f.write('{:79}'.format(element)+'&\n')
161           f.write(word_list[-1]+'\n')
162
163           tmp1=json.loads(instance.remd_multi_t)
164           string1=" "
165           word_list = wrapper.wrap(text=string1.join(tmp1))
166           for element in word_list[:-1]:
167               f.write('{:79}'.format(element)+'&\n')
168           f.write(word_list[-1]+'\n')
169
170           tmp1=json.loads(instance.remd_multi_m)
171           string1=" "
172           word_list = wrapper.wrap(text=string1.join(tmp1))
173           for element in word_list[:-1]:
174               f.write('{:79}'.format(element)+'&\n')
175           f.write(word_list[-1]+'\n')
176
177        f.write(w)
178
179
180        if instance.type == 'min' or instance.md_start == 'pdbstart':
181           f.write('plik.pdb\n')
182           f.write(write_ssbond(instance.ssbond))
183           f.write('0\n')
184
185
186        if instance.type == 'md' and instance.md_start != 'pdbstart':
187
188           if instance.md_pdbref:
189              f.write('plik.pdb\n')
190           f.write(str(len(seq))+'\n')
191           for i in range(0,len(seq),80):
192              f.write(seq[i:i+80]+'\n')
193           f.write('0\n0\n')
194
195        if instance.type == 'remd' and instance.md_start != 'pdbstart':
196
197           if instance.md_pdbref:
198              f.write('plik.pdb\n')             
199           f.write(str(len(seq))+'\n')
200           for i in range(0,len(seq),80):
201              f.write(seq[i:i+80]+'\n')
202           f.write('0\n0\n')
203
204
205        
206         
207      if instance.type == 'min':
208       os.chdir(instance.jobdirname)
209       shutil.copy('../files/pbs.csh','.')
210       ret_code = subprocess.Popen(' /opt/torque/bin/qsub pbs.csh', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
211       os.chdir('..')
212      elif instance.type == 'md':
213       os.chdir(instance.jobdirname)
214       f1 = open('../files/pbs_md.csh', 'r')
215       f2 = open('pbs.csh', 'w')
216       for line in f1:
217            f2.write(line.replace('$dimen3',str(dimen3) ))
218       f1.close()
219       f2.close()  
220
221       f1 = open('file.seq', 'w')
222       for i in range(0,len(seq),80):
223              f1.write(seq[i:i+80]+'\n')
224       f1.close()
225
226       ret_code = subprocess.Popen(' /opt/torque/bin/qsub pbs.csh', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)      
227       os.chdir('..')
228      else:
229       tmp1=json.loads(instance.remd_multi_m)
230       nreplicas=sum(map(int, tmp1))
231       
232 # hardcoded for 4 core nodes with FGPROC=2
233       nodes=int(nreplicas*2/4)
234       reszta = nreplicas*2-nodes*4
235       if reszta == 0 :
236         pbs = '#PBS -l nodes='+str(nodes)+':ppn=4'
237       else:
238         pbs = '#PBS -l nodes='+str(nodes)+':ppn=4+1:ppn='+str(reszta)
239
240       os.chdir(instance.jobdirname)
241       f1 = open('../files/pbs8.csh', 'r')
242       f2 = open('pbs8.csh', 'w')
243       for line in f1:
244           if '#PBS -l nodes=4:ppn=4' in line:
245            f2.write(line.replace('#PBS -l nodes=4:ppn=4', pbs))
246           else:
247            tmp1=json.loads(instance.remd_multi_t)
248            f2.write(line.replace('$temperatures','"'+" ".join(tmp1)+'"'))
249       f1.close()
250       f2.close()
251       os.chdir('..')  
252
253 # write wham & cluster input
254       with open(instance.jobdirname+'/file_wham.inp','w') as f:
255           if instance.md_nstep/instance.remd_nstex*nreplicas<=8000:
256               isampl=1
257           else:
258               isampl=int(instance.md_nstep/instance.remd_nstex*nreplicas/8000)
259
260           if instance.md_pdbref:
261             f.write('SEED='+str(instance.md_seed)+' isampl='+str(isampl)+
262                ' einicheck=1 rescale=2 delta=0.02 cxfile classify\n')
263           else:    
264             f.write('SEED='+str(instance.md_seed)+' isampl='+str(isampl)+
265               ' einicheck=1 rescale=2 delta=0.02 cxfile\n')
266           f.write('nres='+str(len(seq))+' one_letter\n')
267           for i in range(0,len(seq),80):
268              f.write(seq[i:i+80]+'\n')
269
270           f.write(write_ssbond(instance.ssbond))
271
272
273           f.write(w)
274           f.write('\n')
275           f.write('nt='+str(instance.remd_nrep)+' replica read_iset\n')
276           tmp1=json.loads(instance.remd_multi_t)
277           for element in tmp1:
278               f.write('nr=1 temp='+element+' fi=0.0 0.0 0.0 0.0 0.0\n')
279               f.write('kh= 0.0 Q0=0.0\n')
280           rec=instance.md_nstep/instance.remd_nstex
281           f.write('nfile_cx=1 rec_start='+str(rec/10)
282                   +' rec_end='+str(rec)+' totraj='+str(nreplicas)+'\n')
283           f.write('file_MD000\n')
284           if instance.md_pdbref:
285              f.write('pdbref\n')
286              f.write('plik.pdb\n')
287
288            
289       with open(instance.jobdirname+'/file_cluster.inp','w') as f:
290           f.write(instance.name + ' UNRES server job'+ '\n')
291           f.write('nres='+str(len(seq))
292              +' one_letter rescale=2 PRINT_CART PDBOUT=1 iopt=1'
293              +' temper='+str(instance.remd_cluter_temp)+'\n')
294           f.write(w)
295           for i in range(0,len(seq),80):
296              f.write(seq[i:i+80]+'\n')
297           f.write(write_ssbond(instance.ssbond))
298       
299       os.chdir(instance.jobdirname)  
300       ret_code = subprocess.Popen(' /opt/torque/bin/qsub pbs8.csh', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
301       os.chdir('..')
302      
303      print ret_code.stdout.readlines()
304      logger.warning("Dir \"%s\" has been saved." % instance.jobdirname)
305      
306 @receiver(post_delete, sender=Task)
307 def delete_on_task_del(sender, instance, **kwargs):     
308    if instance.jobdirname:
309       if os.path.isdir(instance.jobdirname):
310          shutil.rmtree(instance.jobdirname)
311          logger.warning("Dir \"%s\" has been rm." % instance.jobdirname)         
312