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