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