initial git commit
[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('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       shutil.copy('../files/pbs.csh','.')
209       ret_code = subprocess.Popen(' /opt/torque/bin/qsub pbs.csh', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
210      elif instance.type == 'md':
211       f1 = open('../files/pbs_md.csh', 'r')
212       f2 = open('pbs.csh', 'w')
213       for line in f1:
214            f2.write(line.replace('$dimen3',str(dimen3) ))
215       f1.close()
216       f2.close()  
217
218       f1 = open('file.seq', 'w')
219       for i in range(0,len(seq),80):
220              f1.write(seq[i:i+80]+'\n')
221       f1.close()
222
223       ret_code = subprocess.Popen(' /opt/torque/bin/qsub pbs.csh', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)      
224      else:
225       tmp1=json.loads(instance.remd_multi_m)
226       nreplicas=sum(map(int, tmp1))
227       
228 # hardcoded for 4 core nodes with FGPROC=2
229       nodes=int(nreplicas*2/4)
230       reszta = nreplicas*2-nodes*4
231       if reszta == 0 :
232         pbs = '#PBS -l nodes='+str(nodes)+':ppn=4'
233       else:
234         pbs = '#PBS -l nodes='+str(nodes)+':ppn=4+1:ppn='+str(reszta)
235
236       f1 = open('../files/pbs8.csh', 'r')
237       f2 = open('pbs8.csh', 'w')
238       for line in f1:
239           if '#PBS -l nodes=4:ppn=4' in line:
240            f2.write(line.replace('#PBS -l nodes=4:ppn=4', pbs))
241           else:
242            tmp1=json.loads(instance.remd_multi_t)
243            f2.write(line.replace('$temperatures','"'+" ".join(tmp1)+'"'))
244       f1.close()
245       f2.close()  
246
247 # write wham & cluster input
248       with open('file_wham.inp','w') as f:
249           if instance.md_nstep/instance.remd_nstex*nreplicas<=8000:
250               isampl=1
251           else:
252               isampl=int(instance.md_nstep/instance.remd_nstex*nreplicas/8000)
253
254           if instance.md_pdbref:
255             f.write('SEED='+str(instance.md_seed)+' isampl='+str(isampl)+
256                ' einicheck=1 rescale=2 delta=0.02 cxfile classify\n')
257           else:    
258             f.write('SEED='+str(instance.md_seed)+' isampl='+str(isampl)+
259               ' einicheck=1 rescale=2 delta=0.02 cxfile\n')
260           f.write('nres='+str(len(seq))+' one_letter\n')
261           for i in range(0,len(seq),80):
262              f.write(seq[i:i+80]+'\n')
263
264           f.write(write_ssbond(instance.ssbond))
265
266
267           f.write(w)
268           f.write('\n')
269           f.write('nt='+str(instance.remd_nrep)+' replica read_iset\n')
270           tmp1=json.loads(instance.remd_multi_t)
271           for element in tmp1:
272               f.write('nr=1 temp='+element+' fi=0.0 0.0 0.0 0.0 0.0\n')
273               f.write('kh= 0.0 Q0=0.0\n')
274           rec=instance.md_nstep/instance.remd_nstex
275           f.write('nfile_cx=1 rec_start='+str(rec/10)
276                   +' rec_end='+str(rec)+' totraj='+str(nreplicas)+'\n')
277           f.write('file_MD000\n')
278           if instance.md_pdbref:
279              f.write('pdbref\n')
280              f.write('plik.pdb\n')
281
282            
283       with open('file_cluster.inp','w') as f:
284           f.write(instance.name + ' UNRES server job'+ '\n')
285           f.write('nres='+str(len(seq))
286              +' one_letter rescale=2 PRINT_CART PDBOUT=1 iopt=1'
287              +' temper='+str(instance.remd_cluter_temp)+'\n')
288           f.write(w)
289           for i in range(0,len(seq),80):
290              f.write(seq[i:i+80]+'\n')
291           f.write(write_ssbond(instance.ssbond))
292         
293       ret_code = subprocess.Popen(' /opt/torque/bin/qsub pbs8.csh', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
294      
295      print ret_code.stdout.readlines()
296      os.chdir('..')
297      logger.warning("Dir \"%s\" has been saved." % instance.jobdirname)
298      
299 @receiver(post_delete, sender=Task)
300 def delete_on_task_del(sender, instance, **kwargs):     
301    if instance.jobdirname:
302       if os.path.isdir(instance.jobdirname):
303          shutil.rmtree(instance.jobdirname)
304          logger.warning("Dir \"%s\" has been rm." % instance.jobdirname)         
305