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 Controller import SimCoalController
15
17 - def __init__(self, data_dir, simcoal_dir):
18 """Initializes the cache.
19
20 data_dir - Where the cache can be found
21 simcoal_dir - where the binaries are
22
23 IMPORTANT: The cache only makes sense if the file name univocally
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.dataDir = data_dir
29 self.cacheDir = os.sep.join([data_dir, 'SimCoal', 'cache'])
30 self.simcoalDir = simcoal_dir
31
32
33 - def run_simcoal(self, par_file, num_sims, ploydi = '1', parDir = None):
34 if parDir == None:
35 parDir = os.sep.join([self.dataDir, 'SimCoal', 'runs'])
36 par_file_root = par_file[:-4]
37 tar_name = os.sep.join([self.cacheDir, ploydi, par_file_root +
38 '.tar.bz2'])
39 if os.access(tar_name, os.R_OK):
40 tf = tarfile.open(tar_name)
41 tar_num_sims = len(tf.getmembers()) - 3
42 else:
43 tar_num_sims = 0
44 if tar_num_sims >= num_sims:
45 tf.extractall(parDir)
46 tf.close()
47 return
48 else:
49 try:
50 tf.close()
51 except NameError:
52 pass
53 scc = SimCoalController(self.simcoalDir)
54 scc.run_simcoal(par_file, num_sims, ploydi, parDir)
55 tf = tarfile.open(tar_name, 'w:bz2')
56 tf.add(os.sep.join([parDir, par_file_root]), par_file_root)
57 tf.close()
58
60 '''
61 Lists available simulations.
62 '''
63 files = os.listdir(self.cacheDir + os.sep + ploidy)
64 sims = []
65 for file in files:
66 if file.endswith('.tar.bz2'):
67 sims.append(file[:-8])
68 return sims
69
71 '''
72 Makes available a cached simulation.
73
74 @param sim_name simulation name.
75
76 This mainly means untaring a file.
77 '''
78 if parDir == None:
79 parDir = os.sep.join([Config.dataDir, 'SimCoal', 'runs'])
80 tar_name = os.sep.join([self.cacheDir, ploidy, sim_name +
81 '.tar.bz2'])
82 tf = tarfile.open(tar_name)
83 tf.extractall(parDir)
84 tf.close()
85
86
87 if __name__ == '__main__':
88 cache = Cache('/home/work/werk/consolidator/sc_cache',
89 '/home/work/software/simcoal')
90 cache.run_simcoal('.', 'island_snp-50_0.0025_10_0.083_100_60.par', 102)
91