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 import os
10 import tarfile
11 from Controller import SimCoalController
12
13
15 - def __init__(self, data_dir, simcoal_dir):
16 """Initializes the cache.
17
18 data_dir - Where the cache can be found
19 simcoal_dir - where the binaries are
20
21 IMPORTANT: The cache only makes sense if the file name univocally
22 identifies the model.
23 For now use use the model name as key,
24 and it will probably stay like that.
25 """
26 self.dataDir = data_dir
27 self.cacheDir = os.sep.join([data_dir, 'SimCoal', 'cache'])
28 self.simcoalDir = simcoal_dir
29
30 - def run_simcoal(self, par_file, num_sims, ploydi = '1', parDir = None):
31 if parDir is None:
32 parDir = os.sep.join([self.dataDir, 'SimCoal', 'runs'])
33 par_file_root = par_file[:-4]
34 tar_name = os.sep.join([self.cacheDir, ploydi, par_file_root +
35 '.tar.bz2'])
36 if os.access(tar_name, os.R_OK):
37 tf = tarfile.open(tar_name)
38 tar_num_sims = len(tf.getmembers()) - 3
39 else:
40 tar_num_sims = 0
41 if tar_num_sims >= num_sims:
42 tf.extractall(parDir)
43 tf.close()
44 return
45 else:
46 try:
47 tf.close()
48 except NameError:
49 pass
50 scc = SimCoalController(self.simcoalDir)
51 scc.run_simcoal(par_file, num_sims, ploydi, parDir)
52 tf = tarfile.open(tar_name, 'w:bz2')
53 tf.add(os.sep.join([parDir, par_file_root]), par_file_root)
54 tf.close()
55
57 '''
58 Lists available simulations.
59 '''
60 files = os.listdir(self.cacheDir + os.sep + ploidy)
61 sims = []
62 for file in files:
63 if file.endswith('.tar.bz2'):
64 sims.append(file[:-8])
65 return sims
66
68 '''
69 Makes available a cached simulation.
70
71 @param sim_name simulation name.
72
73 This mainly means untaring a file.
74 '''
75 if parDir is None:
76 parDir = os.sep.join([self.dataDir, 'SimCoal', 'runs'])
77 tar_name = os.sep.join([self.cacheDir, ploidy, sim_name +
78 '.tar.bz2'])
79 tf = tarfile.open(tar_name)
80 tf.extractall(parDir)
81 tf.close()
82
83
84
85
86
87
88