1
2
3 """
4 This module allows to cache Simcoal2 results, and return on the fly
5 in case the calculation was done.
6
7 """
8
9 from logging import debug
10 from sys import exit
11 import os
12 import tarfile
13 import tempfile
14 from PopGen.SimCoal.Controller import SimCoalController
15 from PopGen import Config
16
19 """Initializes the cache.
20
21 simcoalDir - where the binaries are
22
23 IMPORTANT: The cache only makes sense if the file nameunivically
24 identifies the model.
25 For now use use the model name as key,
26 and it will probably stay like that.
27 """
28 self.cacheDir = os.sep.join([Config.dataDir, 'SimCoal', 'cache'])
29 if simcoalDir == None:
30 self.simcoalDir = Config.simcoalDir
31 else:
32 self.simcoalDir = simcoalDir
33
34
35 - def run_simcoal(self, par_file, num_sims, ploydi = '1', parDir = None):
36 if parDir == None:
37 parDir = os.sep.join([Config.dataDir, 'SimCoal', 'runs'])
38 par_file_root = par_file[:-4]
39 tar_name = os.sep.join([self.cacheDir, ploydi, par_file_root +
40 '.tar.bz2'])
41 if os.access(tar_name, os.R_OK):
42 tf = tarfile.open(tar_name)
43 tar_num_sims = len(tf.getmembers()) - 3
44 else:
45 tar_num_sims = 0
46 if tar_num_sims >= num_sims:
47 tf.extractall(parDir)
48 tf.close()
49 return
50 else:
51 try:
52 tf.close()
53 except NameError:
54 pass
55 scc = SimCoalController(self.simcoalDir)
56 scc.run_simcoal(par_file, num_sims, ploydi, parDir)
57 tf = tarfile.open(tar_name, 'w:bz2')
58 tf.add(os.sep.join([parDir, par_file_root]), par_file_root)
59 tf.close()
60
62 '''
63 Lists available simulations.
64 '''
65 files = os.listdir(self.cacheDir + os.sep + ploidy)
66 sims = []
67 for file in files:
68 if file.endswith('.tar.bz2'):
69 sims.append(file[:-8])
70 return sims
71
73 '''
74 Makes available a cached simulation.
75
76 @param sim_name simulation name.
77
78 This mainly means untaring a file.
79 '''
80 if parDir == None:
81 parDir = os.sep.join([Config.dataDir, 'SimCoal', 'runs'])
82 tar_name = os.sep.join([self.cacheDir, ploidy, sim_name +
83 '.tar.bz2'])
84 tf = tarfile.open(tar_name)
85 tf.extractall(parDir)
86 tf.close()
87
88
89 if __name__ == '__main__':
90 cache = Cache('/home/work/werk/consolidator/sc_cache',
91 '/home/work/software/simcoal')
92 cache.run_simcoal('.', 'island_snp-50_0.0025_10_0.083_100_60.par', 102)
93