Package Bio :: Package PopGen :: Package FDist :: Module Controller
[hide private]
[frames] | no frames]

Source Code for Module Bio.PopGen.FDist.Controller

  1  # Copyright 2007 by Tiago Antao <tiagoantao@gmail.com>.  All rights reserved. 
  2  # This code is part of the Biopython distribution and governed by its 
  3  # license.  Please see the LICENSE file that should have been included 
  4  # as part of this package. 
  5   
  6  """This module allows you to control fdist. 
  7   
  8  This will allow you to call fdist and associated programs (cplot, 
  9  datacal, pv) by Mark Beaumont. 
 10   
 11  http://www.rubic.rdg.ac.uk/~mab/software.html (old) 
 12  http://www.maths.bris.ac.uk/~mamab/ (new) 
 13  """ 
 14   
 15  import os 
 16  import subprocess 
 17  import sys 
 18  from random import randint 
 19  from time import strftime, clock 
 20  # from logging import debug 
 21   
 22   
23 -def my_float(f):
24 # Because of Jython, mostly 25 if f == "-nan": 26 f = "nan" 27 return float(f)
28 29
30 -class FDistController(object):
31 - def __init__(self, fdist_dir='', ext=None):
32 """Initializes the controller. 33 34 fdist_dir is the directory where fdist2 is. 35 ext is the extension of binaries (.exe on windows, 36 none on Unix) 37 38 """ 39 self.tmp_idx = 0 40 self.fdist_dir = fdist_dir 41 self.os_name = os.name 42 if sys.platform == 'win32': 43 py_ext = '.exe' 44 else: 45 py_ext = '' 46 if ext is None: 47 self.ext = py_ext 48 else: 49 self.ext = ext
50
51 - def _get_path(self, app):
52 """Returns the path to an fdist application. 53 54 Includes Path where fdist can be found plus executable extension. 55 """ 56 if self.fdist_dir == '': 57 return app + self.ext 58 else: 59 return os.sep.join([self.fdist_dir, app]) + self.ext
60
61 - def _get_temp_file(self):
62 """Gets a temporary file name. 63 64 Returns a temporary file name, if executing inside jython 65 tries to replace unexisting tempfile.mkstemp(). 66 """ 67 self.tmp_idx += 1 68 return strftime("%H%M%S") + str(int(clock() * 100)) + str(randint(0, 1000)) + str(self.tmp_idx)
69
70 - def run_datacal(self, data_dir='.', version=1, 71 crit_freq=0.99, p=0.5, beta=(0.25, 0.25)):
72 """Executes datacal. 73 74 data_dir - Where the data is found. 75 """ 76 if version == 1: 77 datacal_name = "datacal" 78 else: 79 datacal_name = "Ddatacal" 80 proc = subprocess.Popen([self._get_path(datacal_name)], 81 universal_newlines=True, 82 stdin=subprocess.PIPE, 83 shell=(sys.platform != "win32"), 84 stdout=subprocess.PIPE, cwd=data_dir) 85 if version == 1: 86 out, err = proc.communicate('a\n') 87 lines = out.split("\n") 88 fst_line = lines[0].rstrip().split(' ') 89 fst = my_float(fst_line[4]) 90 sample_line = lines[1].rstrip().split(' ') 91 sample = int(sample_line[9]) 92 else: 93 out, err = proc.communicate('%f\n%f\n%f %f\na\n' % ( 94 crit_freq, p, beta[0], beta[1])) 95 lines = out.split("\n") 96 l = lines[0].rstrip().split(" ") 97 loci, pops = int(l[-5]), int(l[-2]) 98 fst_line = lines[1].rstrip().split(' ') 99 fst = my_float(fst_line[4]) 100 sample_line = lines[2].rstrip().split(' ') 101 sample = int(sample_line[9]) 102 F_line = lines[3].rstrip().split(' ') 103 F, obs = my_float(F_line[5]), int(F_line[8]) 104 if version == 1: 105 return fst, sample 106 else: 107 return fst, sample, loci, pops, F, obs
108
109 - def _generate_intfile(self, data_dir):
110 """Generates an INTFILE. 111 112 Parameter: 113 data_dir - data directory 114 """ 115 inf = open(data_dir + os.sep + 'INTFILE', 'w') 116 for i in range(98): 117 inf.write(str(randint(-2 ** 31 + 1, 2 ** 31 - 1)) + '\n') 118 inf.write('8\n') 119 inf.close()
120
121 - def run_fdist(self, npops, nsamples, fst, sample_size, 122 mut=0, num_sims=50000, data_dir='.', 123 is_dominant=False, theta=0.06, beta=(0.25, 0.25), 124 max_freq=0.99):
125 """Executes (d)fdist. 126 127 Parameters: 128 129 - npops - Number of populations 130 - nsamples - Number of populations sampled 131 - fst - expected Fst 132 - sample_size - Sample size per population 133 For dfdist: if zero a sample size file has to be provided 134 - mut - 1=Stepwise, 0=Infinite allele 135 - num_sims - number of simulations 136 - data_dir - Where the data is found 137 - is_dominant - If true executes dfdist 138 - theta - Theta (=2Nmu) 139 - beta - Parameters for the beta prior 140 - max_freq - Maximum allowed frequency of the commonest allele 141 142 Returns: 143 144 - fst - Average Fst 145 146 Important Note: This can take quite a while to run! 147 """ 148 if fst >= 0.9: 149 # Lets not joke 150 fst = 0.899 151 if fst <= 0.0: 152 # 0 will make fdist run forever 153 fst = 0.001 154 if is_dominant: 155 config_name = "Dfdist_params" 156 else: 157 config_name = "fdist_params2.dat" 158 159 f = open(data_dir + os.sep + config_name, 'w') 160 f.write(str(npops) + '\n') 161 f.write(str(nsamples) + '\n') 162 f.write(str(fst) + '\n') 163 f.write(str(sample_size) + '\n') 164 if is_dominant: 165 f.write(str(theta) + '\n') 166 else: 167 f.write(str(mut) + '\n') 168 f.write(str(num_sims) + '\n') 169 if is_dominant: 170 f.write("%f %f\n" % beta) 171 f.write("%f\n" % max_freq) 172 f.close() 173 174 self._generate_intfile(data_dir) 175 176 if is_dominant: 177 bin_name = "Dfdist" 178 else: 179 bin_name = "fdist2" 180 proc = subprocess.Popen([self._get_path(bin_name)], cwd=data_dir, 181 universal_newlines=True, 182 stdin=subprocess.PIPE, stdout=subprocess.PIPE, 183 shell=(sys.platform != "win32")) 184 out, err = proc.communicate('y\n\n') 185 lines = out.split("\n") 186 for line in lines: 187 if line.startswith('average Fst'): 188 fst = my_float(line.rstrip().split(' ')[-1]) 189 return fst
190
191 - def run_fdist_force_fst(self, npops, nsamples, fst, sample_size, 192 mut=0, num_sims=50000, data_dir='.', 193 try_runs=5000, limit=0.001, is_dominant=False, 194 theta=0.06, beta=(0.25, 0.25), 195 max_freq=0.99):
196 """Executes fdist trying to force Fst. 197 198 Parameters: 199 200 - try_runs - Number of simulations on the part trying to get 201 Fst correct 202 - limit - Interval limit 203 204 Other parameters can be seen on run_fdist. 205 """ 206 max_run_fst = 1 207 min_run_fst = 0 208 current_run_fst = fst 209 while True: 210 real_fst = self.run_fdist(npops, nsamples, current_run_fst, 211 sample_size, mut, try_runs, data_dir, 212 is_dominant, theta, beta, max_freq) 213 if abs(real_fst - fst) < limit: 214 return self.run_fdist(npops, nsamples, current_run_fst, 215 sample_size, mut, num_sims, data_dir, 216 is_dominant, theta, beta, max_freq) 217 if real_fst > fst: 218 max_run_fst = current_run_fst 219 if current_run_fst < min_run_fst + limit: 220 # we can do no better 221 # debug('Lower limit is ' + str(min_run_fst)) 222 return self.run_fdist(npops, nsamples, current_run_fst, 223 sample_size, mut, num_sims, 224 data_dir) 225 current_run_fst = (min_run_fst + current_run_fst) / 2 226 else: 227 min_run_fst = current_run_fst 228 if current_run_fst > max_run_fst - limit: 229 return self.run_fdist(npops, nsamples, current_run_fst, 230 sample_size, mut, num_sims, 231 data_dir, is_dominant, theta, 232 beta, max_freq) 233 current_run_fst = (max_run_fst + current_run_fst) / 2
234
235 - def run_cplot(self, ci=0.95, data_dir='.', version=1, smooth=0.04):
236 """Executes cplot. 237 238 ci - Confidence interval. 239 data_dir - Where the data is found. 240 """ 241 242 self._generate_intfile(data_dir) 243 if version == 1: 244 cplot_name = "cplot" 245 else: 246 cplot_name = "cplot2" 247 proc = subprocess.Popen([self._get_path(cplot_name)], cwd=data_dir, 248 stdin=subprocess.PIPE, stdout=subprocess.PIPE, 249 shell=(sys.platform != "win32"), 250 universal_newlines=True) 251 if version == 1: 252 proc.communicate('out.dat out.cpl\n' + str(ci) + '\n') 253 else: 254 proc.communicate("\n".join([ 255 "data_fst_outfile out.cpl out.dat", 256 str(ci), str(smooth)])) 257 258 f = open(data_dir + os.sep + 'out.cpl') 259 conf_lines = [] 260 l = f.readline() 261 try: 262 while l != '': 263 conf_lines.append( 264 tuple(my_float(x) for x in l.rstrip().split(' '))) 265 l = f.readline() 266 except ValueError: 267 f.close() 268 return [] 269 f.close() 270 return conf_lines
271
272 - def run_pv(self, out_file='probs.dat', data_dir='.', 273 version=1, smooth=0.04):
274 """Executes pv. 275 276 out_file - Name of output file. 277 data_dir - Where the data is found. 278 """ 279 280 self._generate_intfile(data_dir) 281 282 if version == 1: 283 pv_name = "pv" 284 else: 285 pv_name = "pv2" 286 287 proc = subprocess.Popen([self._get_path(pv_name)], cwd=data_dir, 288 shell=(sys.platform != "win32"), 289 stdin=subprocess.PIPE, 290 stdout=subprocess.PIPE, 291 universal_newlines=True) 292 proc.communicate('data_fst_outfile ' + out_file + 293 ' out.dat\n' + str(smooth) + '\n') 294 pvf = open(data_dir + os.sep + out_file, 'r') 295 result = [tuple(my_float(y) for y in x.rstrip().split(' ')) for x in pvf.readlines()] 296 pvf.close() 297 return result
298