code stringlengths 1 18.2k |
|---|
def paramsarray(self, value): """Set new `paramsarray` and update via `updateParams`.""" nparams = len(self._index_to_param) assert (isinstance(value, scipy.ndarray) and value.ndim == 1), ( "paramsarray must be 1-dim ndarray") assert len(value) == nparams, ("Assigning paramsarray to ndarray " "of the wrong length.") if... |
range(len(paramd))], dtype='float') self.updateParams(newvalues) self._paramsarray = self.paramsarray |
def dtcurrent(self, value): """Set value of `dtcurrent`, update derivatives if needed.""" assert isinstance(value, bool) if value and self.dparamscurrent: raise RuntimeError("Can't set both dparamscurrent and dtcurrent True") if value != self.dtcurrent: self._dtcurrent = value self._updateInternals() |
def t(self, value): """Set new branch lengths, update likelihood and derivatives.""" assert (isinstance(value, scipy.ndarray) and (value.dtype == 'float') and (value.shape == self.t.shape)) if (self._t != value).any(): self._t = value.copy() self._updateInternals() |
def dloglikarray(self): """Derivative of `loglik` with respect to `paramsarray`.""" assert self.dparamscurrent, "dloglikarray requires paramscurrent == True" nparams = len(self._index_to_param) dloglikarray = scipy.ndarray(shape=(nparams,), dtype='float') for (i, param) in self._index_to_param.items(): if isinstance(pa... |
def updateParams(self, newvalues): """Update model parameters and re-compute likelihoods. This method is the **only** acceptable way to update model parameters. The likelihood is re-computed as needed by this method. Args: `newvalues` (dict) A dictionary keyed by param name and with value as new value to set. Each para... |
def _updateInternals(self): """Update internal attributes related to likelihood. Should be called any time branch lengths or model parameters are changed. """ rootnode = self.nnodes - 1 if self._distributionmodel: catweights = self.model.catweights else: catweights = scipy.ones(1, dtype='float') # When there are multip... |
scipy.log(sitelik) + self.underflowlogscale self.loglik = scipy.sum(self.siteloglik) + self.model.logprior if self.dparamscurrent: self._dloglik = {} for param in self.model.freeparams: if self._distributionmodel and (param in self.model.distributionparams): name = self.model.distributedparam weighted_dk = (self.model.... |
def _M(self, k, t, tips=None, gaps=None): """Returns matrix exponential `M`.""" if self._distributionmodel: return self.model.M(k, t, tips, gaps) else: return self.model.M(t, tips, gaps) |
def _dM(self, k, t, param, M, tips=None, gaps=None): """Returns derivative of matrix exponential.""" if self._distributionmodel: return self.model.dM(k, t, param, M, tips, gaps) else: return self.model.dM(t, param, M, tips, gaps) |
def _stationarystate(self, k): """Returns the stationarystate .""" if self._distributionmodel: return self.model.stationarystate(k) else: return self.model.stationarystate |
def _dstationarystate(self, k, param): """Returns the dstationarystate .""" if self._distributionmodel: return self.model.dstationarystate(k, param) else: return self.model.dstationarystate(param) |
def _paramlist_PartialLikelihoods(self): """List of parameters looped over in `_computePartialLikelihoods`.""" if self._distributionmodel: return [param for param in self.model.freeparams + [self.model.distributedparam] if param not in self.model.distributionparams] else: return self.model.freeparams |
def _computePartialLikelihoods(self): """Update `L`, `dL`, `dL_dt`.""" for n in range(self.ntips, self.nnodes): ni = n - self.ntips # internal node number nright = self.rdescend[ni] nleft = self.ldescend[ni] if nright < self.ntips: istipr = True else: istipr = False if nleft < self.ntips: istipl = True else: istipl = F... |
(tx, Mx, nx, MLxother, istipx) in [ (tright, Mright, nright, MLleft, istipr), (tleft, Mleft, nleft, MLright, istipl)]: if istipx: tipsx = self.tips[nx] gapsx = self.gaps[nx] else: tipsx = gapsx = None dM_dt = self._dM(k, tx, 't', Mx, tipsx, gapsx) if istipx: LdM_dt = dM_dt else: LdM_dt = broadcastMatrixVectorMultiply( ... |
self.dL[param][nright][k][j]) if istipl: dMLleft = dMleft[j] MdLleft = 0 else: dMLleft = broadcastMatrixVectorMultiply( dMleft[j], self.L[nleft][k]) MdLleft = broadcastMatrixVectorMultiply( Mleft, self.dL[param][nleft][k][j]) self.dL[param][n][k][j] = ((dMLright + MdLright) * MLleft + MLright * (dMLleft + MdLleft)) if ... |
in self.dL[param]: del self.dL[param][ntodel] if self.dtcurrent: for n2 in self.dL_dt.keys(): if ntodel in self.dL_dt[n2]: del self.dL_dt[n2][ntodel] |
def _sub_index_param(self, param): """Returns list of sub-indexes for `param`. Used in computing partial likelihoods; loop over these indices.""" if self._distributionmodel and (param == self.model.distributedparam): indices = [()] else: paramvalue = getattr(self.model, param) if isinstance(paramvalue, float): indices ... |
def send_request(self, *args, **kwargs): """ Intercept connection errors which suggest that a managed host has crashed and raise an exception indicating the location of the log """ try: return super(JSHost, self).send_request(*args, **kwargs) except RequestsConnectionError as e: if ( self.manager and self.has_connected... |
def b_matching(D, k, max_iter=1000, damping=1, conv_thresh=1e-4, weighted=False, verbose=False): ''' "Belief-Propagation for Weighted b-Matchings on Arbitrary Graphs and its Relation to Linear Programs with Integer Solutions" Bayati et al. Finds the minimal weight perfect b-matching using min-sum loopy-BP. @param D pai... |
have length N' # TODO: remove these later inds = np.tile(np.arange(N), (N, 1)) backinds = inds.copy() inds = inds[mask].reshape((N, -1)) backinds = backinds.T.ravel()[:(N*(N-1))].reshape((N, -1)) # Run Belief Revision change = 1.0 B = W.copy() for n_iter in range(1, max_iter+1): oldB = B.copy() update_belief(oldB, B, W... |
else: warnings.warn("Hit iteration limit (%d) before converging" % max_iter) if verbose: # pragma: no cover if change < conv_thresh: print("Converged to stable beliefs in %d iterations" % n_iter) elif oscillation < 1: print("Stopped after reaching oscillation in %d iterations" % n_iter) print("No feasible solution foun... |
def _updateB(oldB, B, W, degrees, damping, inds, backinds): # pragma: no cover '''belief update function.''' for j,d in enumerate(degrees): kk = inds[j] bk = backinds[j] if d == 0: B[kk,bk] = -np.inf continue belief = W[kk,bk] + W[j] oldBj = oldB[j] if d == oldBj.shape[0]: bth = quickselect(-oldBj, d-1) bplus = -1 else... |
def _func_copy(f, newcode) : ''' Return a copy of function f with a different __code__ Because I can't find proper documentation on the correct signature of the types.FunctionType() constructor, I pass the minimum arguments then set the important dunder-values by direct assignment. Note you cannot assign __closure__, i... |
def bind_all(mc, builtin_only=False, stoplist=[], verbose=False): """Recursively apply constant binding to functions in a module or class. Use as the last line of the module (after everything is defined, but before test code). In modules that need modifiable globals, set builtin_only to True. """ import types try: d = ... |
def make_constants(builtin_only=False, stoplist=[], verbose=False): """ Return a decorator for optimizing global references. Verify that the first argument is a function. """ if type(builtin_only) == type(make_constants): raise ValueError("The make_constants decorator must have arguments.") return lambda f: _make_const... |
def state(): '''Get The playback state: 'playing', 'paused', or 'stopped'. If PLAYING or PAUSED, show information on current track. Calls PlaybackController.get_state(), and if state is PLAYING or PAUSED, get PlaybackController.get_current_track() and PlaybackController.get_time_position()''' server = getServer() state... |
def pause(): '''Pause playback. Calls PlaybackController.pause()''' server = getServer() server.core.playback.pause() pos = server.core.playback.get_time_position() print('Paused at {}'.format(formatTimeposition(pos))) |
def tracklist(): '''Get tracklist Calls TracklistController.get_tl_tracks() ''' _c = 0 server = getServer() _current = server.core.tracklist.index() for t in server.core.tracklist.get_tl_tracks(): logging.debug('Got tl trak: %r', t) currently = ' -- CURRENT' if t['tlid'] == _current else '' print('{}: {}{}'.format(t['t... |
def play_backend_uri(argv=None): '''Get album or track from backend uri and play all tracks found. uri is a string which represents some directory belonging to a backend. Calls LibraryController.browse(uri) to get an album and LibraryController.lookup(uri) to get track''' if argv is None: argv = sys.argv[1:] parser = a... |
hits from lookup() : %r', hits) if len(hits) == 0: print('No hits for "{}"'.format(args.uri)) else: server.core.tracklist.clear() logging.debug('got special uris: %r', [t['uri'] for t in hits]) server.core.tracklist.add(uris=[t['uri'] for t in hits]) server.core.playback.play() |
def peek(self, default=None): '''Returns `default` is there is no subsequent item''' try: result = self.pointer.next() # immediately push it back onto the front of the iterable self.pointer = itertools.chain([result], self.pointer) return result except StopIteration: # nothing to put back; iterating doesn't change anyt... |
def compute_equiv_class(atom): """(atom)->Computes a unique integer for an atom""" try: equiv_class = atom.number + \ 1000*(atom.charge+10) + \ 100000*(atom.hcount) + \ 1000000*(atom.weight) except TypeError: raise ValueError, \ "Can't compute number from atom.number %s atom.charge %s atom.hcount %s"\ " atom.weight %s"... |
def token(self): """ Token given by Transbank for payment initialization url. Will raise PaymentError when an error ocurred. """ if not self._token: self._token = self.fetch_token() logger.payment(self) return self._token |
def transaction_id(self): """ Transaction ID for Transbank, a secure random int between 0 and 999999999. """ if not self._transaction_id: self._transaction_id = random.randint(0, 10000000000 - 1) return self._transaction_id |
def _sanity_check(self): """Check if parameters are okay. Sanity check makes sure each parameter is within an allowable range. Raises: ValueError: Problem with a specific parameter. """ if any(self.m1 < 0.0): raise ValueError("Mass 1 is negative.") if any(self.m2 < 0.0): raise ValueError("Mass 2 is negative.") if any(s... |
> 1.0000001e4) or any(self.m1/self.m2 < 9.999999e-5): raise ValueError("Mass Ratio too far from unity.") return |
def _broadcast_and_set_attrs(self, local_dict): """Cast all inputs to correct dimensions. This method fixes inputs who have different lengths. Namely one input as an array and others that are scalara or of len-1. Raises: Value Error: Multiple length arrays of len>1 """ del local_dict['self'] self.remove_axis = False ma... |
for key in local_dict: try: if len(local_dict[key]) == max_length: setattr(self, key, local_dict[key]) elif len(local_dict[key]) == 1: setattr(self, key, np.full((max_length,), local_dict[key][0])) except TypeError: setattr(self, key, np.full((max_length,), local_dict[key])) return |
def _create_waveforms(self): """Create frequency domain waveforms. Method to create waveforms for PhenomDWaveforms class. It adds waveform information in the form of attributes. """ c_obj = ctypes.CDLL(self.exec_call) # prepare ctypes arrays freq_amp_cast = ctypes.c_double*self.num_points*self.length freqs = freq_amp_c... |
def _sanity_check(self): """Check if parameters are okay. Sanity check makes sure each parameter is within an allowable range. Raises: ValueError: Problem with a specific parameter. """ if any(self.m1 < 0.0): raise ValueError("Mass 1 is negative.") if any(self.m2 < 0.0): raise ValueError("Mass 2 is negative.") if any(s... |
def _convert_units(self): """Convert units to geometrized units. Change to G=c=1 (geometrized) units for ease in calculations. """ self.m1 = self.m1*M_sun*ct.G/ct.c**2 self.m2 = self.m2*M_sun*ct.G/ct.c**2 initial_cond_type_conversion = { 'time': ct.c*ct.Julian_year, 'frequency': 1./ct.c, 'separation': ct.parsec, } self... |
def _t_of_e(self, a0=None, t_start=None, f0=None, ef=None, t_obs=5.0): """Rearranged versions of Peters equations This function calculates the semi-major axis and eccentricity over time. """ if ef is None: ef = np.ones_like(self.e0)*0.0000001 beta = 64.0/5.0*self.m1*self.m2*(self.m1+self.m2) e_vals = np.asarray([np.lin... |
def _chirp_mass(self): """Chirp mass calculation """ return (self.m1*self.m2)**(3./5.)/(self.m1+self.m2)**(1./5.) |
def _g_func(self): """Eq. 20 in Peters and Mathews 1963. """ return (self.n**4./32. * ((jv(self.n-2., self.n*self.e_vals) - 2. * self.e_vals*jv(self.n-1., self.n*self.e_vals) + 2./self.n * jv(self.n, self.n*self.e_vals) + 2.*self.e_vals*jv(self.n+1., self.n*self.e_vals) - jv(self.n+2., self.n*self.e_vals))**2. + (1.-se... |
def _dEndfr(self): """Eq. 4 from Orazio and Samsing (2018) Takes f in rest frame. """ Mc = self._chirp_mass() return (np.pi**(2./3.)*Mc**(5./3.)/(3.*(1.+self.z)**(1./3.) * (self.freqs_orb/(1.+self.z))**(1./3.))*(2./self.n)**(2./3.) * self._g_func()/self._f_func()) |
def _hcn_func(self): """Eq. 56 from Barack and Cutler 2004 """ self.hc = 1./(np.pi*self.dist)*np.sqrt(2.*self._dEndfr()) return |
def _create_waveforms(self): """Create the eccentric waveforms """ # find eccentricity and semi major axis over time until e=0. e_vals, a_vals, t_vals = self._t_of_e(a0=self.a0, f0=self.f0, t_start=self.t_start, ef=None, t_obs=self.t_obs) f_mrg = 0.02/(self.m1 + self.m2) a_mrg = ((self.m1+self.m2)/f_mrg**2)**(1/3) # li... |
modes. for attr in ['e_vals', 'a_vals', 't_vals', 'freqs_orb']: arr = getattr(self, attr) new_arr = (np.flip( np.tile(arr, self.n_max).reshape(len(arr)*self.n_max, len(arr[0])), -1)) setattr(self, attr, new_arr) for attr in ['m1', 'm2', 'z', 'dist']: arr = getattr(self, attr) new_arr = np.repeat(arr, self.n_max)[:, np.... |
def pyvolvePartitions(model, divselection=None): """Get list of `pyvolve` partitions for `model`. Args: `model` (`phydmslib.models.Models` object) The model used for the simulations. Currently only certain `Models` are supported (e.g., `YNGKP`, `ExpCM`) `divselection` (`None` or 2-tuple `(divomega, divsites)`) Set this... |
for r in divsites]) partitions = [] for r in range(model.nsites): matrix = scipy.zeros((len(codons), len(codons)), dtype='float') for (xi, x) in enumerate(codons): for (yi, y) in enumerate(codons): ntdiffs = [(x[j], y[j]) for j in range(3) if x[j] != y[j]] if len(ntdiffs) == 1: (xnt, ynt) = ntdiffs[0] qxy = 1.0 if (xnt... |
/ piy) elif type(model) == phydmslib.models.YNGKP_M0: for p in range(3): qxy *= model.phi[p][NT_TO_INDEX[y[p]]] else: raise ValueError("Can't handle model type {0}".format( type(model))) matrix[xi][yi] = model.mu * qxy * fxy matrix[xi][xi] = -matrix[xi].sum() # create model in way that captures annoying print statement... |
def simulateAlignment(model, treeFile, alignmentPrefix, randomSeed=False): """ Simulate an alignment given a model and tree (units = subs/site). Simulations done using `pyvolve`. Args: `model` (`phydmslib.models.Models` object) The model used for the simulations. Only models that can be passed to `pyvolve.Partitions` a... |
+ tree.get_nonterminals(): if (node.branch_length == None) and (node == tree.root): node.branch_length = 1e-06 else: node.branch_length /= model.branchScale fd, temp_path = mkstemp() Bio.Phylo.write(tree, temp_path, 'newick') os.close(fd) pyvolve_tree = pyvolve.read_tree(file=temp_path) os.remove(temp_path) #Make the `... |
def _create_oracle(oracle_type, **kwargs): """A routine for creating a factor oracle.""" if oracle_type == 'f': return FO(**kwargs) elif oracle_type == 'a': return MO(**kwargs) else: return MO(**kwargs) |
def segment(self): """An non-overlap version Compror""" if not self.seg: j = 0 else: j = self.seg[-1][1] last_len = self.seg[-1][0] if last_len + j > self.n_states: return i = j while j < self.n_states - 1: while not (not (i < self.n_states - 1) or not (self.lrs[i + 1] >= i - j + 1)): i += 1 if i == j: i += 1 self.seg.... |
== _j: _i += 1 self.seg.append((0, _i)) else: self.seg.append((_i - _j, self.sfx[_i] - _i + _j + 1)) j = i return self.seg |
def _ir_cum2(self, alpha=1.0): code, _ = self.encode() N = self.n_states BL = np.zeros(N - 1) # BL is the block length of compror codewords h0 = np.log2(np.cumsum( [1.0 if sfx == 0 else 0.0 for sfx in self.sfx[1:]]) ) """ h1 = np.array([h if m == 0 else h+np.log2(m) for h,m in zip(h0,self.lrs[1:])]) h1 = np.array([h if... |
j = j + L h1 = h1 / BL ir = alpha * h0 - h1 ir[ir < 0] = 0 # Really a HACK here!!!!! return ir, h0, h1 |
def accept(self, context): """ Check if the context could be accepted by the oracle Args: context: s sequence same type as the oracle data Returns: bAccepted: whether the sequence is accepted or not _next: the state where the sequence is accepted """ _next = 0 for _s in context: _data = [self.data[j] for j in self.trn[... |
def add_state(self, new_data, method='inc'): """Create new state and update related links and compressed state""" self.sfx.append(0) self.rsfx.append([]) self.trn.append([]) self.lrs.append(0) # Experiment with pointer-based self.f_array.add(new_data) self.n_states += 1 i = self.n_states - 1 # assign new transition fro... |
pi_1 = k if method != 'complete': k = self.sfx[k] else: if method == 'inc': if I.shape[0] == 1: suffix_candidate = self.trn[k][I[0]] else: suffix_candidate = self.trn[k][I[np.argmin(dvec[I])]] break elif method == 'complete': suffix_candidate.append((self.trn[k][I[np.argmin(dvec[I])]], np.min(dvec))) else: suffix_candi... |
self.sfx[i] = k self.rsfx[self.sfx[i]].append(i) if self.lrs[i] > self.max_lrs[i - 1]: self.max_lrs.append(self.lrs[i]) else: self.max_lrs.append(self.max_lrs[i - 1]) self.avg_lrs.append(self.avg_lrs[i - 1] * ((i - 1.0) / (self.n_states - 1.0)) + self.lrs[i] * (1.0 / (self.n_states - 1.0))) |
def rotate(self, atom): """(atom)->start the cycle at position atom, assumes that atom is in the cycle""" try: index = self.atoms.index(atom) except ValueError: raise CycleError("atom %s not in cycle"%(atom)) self.atoms = self.atoms[index:] + self.atoms[:index] self.bonds = self.bonds[index:] + self.bonds[:index] |
def set_aromatic(self): """set the cycle to be an aromatic ring""" #XXX FIX ME # this probably shouldn't be here for atom in self.atoms: atom.aromatic = 1 for bond in self.bonds: bond.aromatic = 1 bond.bondorder = 1.5 bond.bondtype = 4 bond.symbol = ":" bond.fixed = 1 self.aromatic = 1 |
def set_debug(enabled: bool): """Enable or disable debug logs for the entire package. Parameters ---------- enabled: bool Whether debug should be enabled or not. """ global _DEBUG_ENABLED if not enabled: log('Disabling debug output...', logger_name=_LOGGER_NAME) _DEBUG_ENABLED = False else: _DEBUG_ENABLED = True log('E... |
def _create_logger(name: str, level: int) -> Generator[logging.Logger, None, None]: """Create a context-based logger. Parameters ---------- name: str Name of logger to use when logging. level: int Logging level, one of logging's levels (e.g. INFO, ERROR, etc.). Returns ------- logging.Logger Named logger that may be us... |
def log(message: str, *args: str, category: str='info', logger_name: str='pgevents'): """Log a message to the given logger. If debug has not been enabled, this method will not log a message. Parameters ---------- message: str Message, with or without formatters, to print. args: Any Arguments to use with the message. ar... |
log category "{}"'.format(category)) log_fn(message, *args) |
def sssr(molecule): """molecule -> generate the molecule.cycles that contain the smallest set of smallest rings""" results = {} lookup = {} fullSet = {} oatoms = {} # XXX FIX ME # copy atom.oatoms to atom._oatoms # atom._oatoms will be modified my the routine for atom in molecule.atoms: atom.rings = [] fullSet[atom.han... |
or (degree < minimum_degree)): minimum, minimum_degree = atom, degree if not minimum: # nothing to do! (i.e. can't have a ring) break if minimum_degree == 1: # these cannot be in rings so trim and remove # my version of trimming for oatom in oatoms[minimum.handle]: oatoms[oatom.handle].remove(minimum) oatoms[minimum.ha... |
elif minimum_degree > 2: # no N2 nodes so remove the "optimum" edge to create # N2 nodes in the next go-around. ring, bonds = getRing(minimum, fullSet, lookup, oatoms) if ring: key = ring[:] key.sort() key = tuple(key) if not results.has_key(key): results[key] = ring, bonds atoms = map(lookup.get, ring) atoms, bonds = ... |
the dictionaries used in getRing # the atoms are not in the order found # we need to topologically sort these # for the cycle atoms, bonds = toposort(atoms, bonds) potentialCycles.append((atoms, bonds)) rings = potentialCycles#checkRings(potentialCycles) molecule.rings = rings molecule.cycles = [Cycle(atoms, bonds) for... |
def toposort(initialAtoms, initialBonds): """initialAtoms, initialBonds -> atoms, bonds Given the list of atoms and bonds in a ring return the topologically sorted atoms and bonds. That is each atom is connected to the following atom and each bond is connected to the following bond in the following manner a1 - b1 - a2 ... |
# traverse to all the connected atoms for atom in next.oatoms: # both the bond and the atom have to be # in our list of atoms and bonds to use # ugg, nested if's... There has to be a # better control structure if ahash.has_key(atom.handle): bond = next.findbond(atom) assert bond # but wait! the bond has to be in our # ... |
def getRing(startAtom, atomSet, lookup, oatoms): """getRing(startAtom, atomSet, lookup, oatoms)->atoms, bonds starting at startAtom do a bfs traversal through the atoms in atomSet and return the smallest ring found returns (), () on failure note: atoms and bonds are not returned in traversal order""" path = {} bpaths =... |
atom in path[handle].keys(): if path[m].has_key(atom): intersections = intersections + 1 sharedAtom = atom if intersections == 1: del path[handle][sharedAtom] path[handle].update(path[m]) result = path[handle].keys() bond = next.findbond(current) # assert bond not in bpaths[handle] and bond not in bpaths[m] bonds = bpa... |
def checkEdges(ringSet, lookup, oatoms): """atoms, lookup -> ring atoms must be in the order of traversal around a ring! break an optimal non N2 node and return the largest ring found """ bondedAtoms = map( None, ringSet[:-1], ringSet[1:] ) bondedAtoms += [ (ringSet[-1], ringSet[0]) ] # form a lookup for the ringSet li... |
index1 = oatoms1.index(atom2) index2 = oatoms2.index(atom1) # break the bond del oatoms1[index1] del oatoms2[index2] ring1 = getRing(atom1, atomSet, lookup, oatoms) ring2 = getRing(atom2, atomSet, lookup, oatoms) # keep the larger of the two rings if len(ring1) > len(ring2): results.append((len(ring1), handle1, handle2... |
def NonNegativeInt(n): """If *n* is non-negative integer returns it, otherwise an error. >>> print("%d" % NonNegativeInt('8')) 8 >>> NonNegativeInt('8.1') Traceback (most recent call last): ... ValueError: 8.1 is not an integer >>> print("%d" % NonNegativeInt('0')) 0 >>> NonNegativeInt('-1') Traceback (most recent call... |
def IntGreaterThanZero(n): """If *n* is an integer > 0, returns it, otherwise an error.""" try: n = int(n) except: raise ValueError("%s is not an integer" % n) if n <= 0: raise ValueError("%d is not > 0" % n) else: return n |
def IntGreaterThanOne(n): """If *n* is an integer > 1, returns it, otherwise an error.""" try: n = int(n) except: raise ValueError("%s is not an integer" % n) if n <= 1: raise ValueError("%d is not > 1" % n) else: return n |
def FloatGreaterThanEqualToZero(x): """If *x* is a float >= 0, returns it, otherwise raises and error. >>> print('%.1f' % FloatGreaterThanEqualToZero('1.5')) 1.5 >>> print('%.1f' % FloatGreaterThanEqualToZero('-1.1')) Traceback (most recent call last): ... ValueError: -1.1 not float greater than or equal to zero """ tr... |
def FloatBetweenZeroAndOne(x): """Returns *x* only if *0 <= x <= 1*, otherwise raises error.""" x = float(x) if 0 <= x <= 1: return x else: raise ValueError("{0} not a float between 0 and 1.".format(x)) |
def diffPrefsPrior(priorstring): """Parses `priorstring` and returns `prior` tuple.""" assert isinstance(priorstring, str) prior = priorstring.split(',') if len(prior) == 3 and prior[0] == 'invquadratic': [c1, c2] = [float(x) for x in prior[1 : ]] assert c1 > 0 and c2 > 0, "C1 and C2 must be > 1 for invquadratic prior"... |
def ExistingFileOrNone(fname): """Like `Existingfile`, but if `fname` is string "None" then return `None`.""" if os.path.isfile(fname): return fname elif fname.lower() == 'none': return None else: raise ValueError("%s must specify a valid file name or 'None'" % fname) |
def ModelOption(model): """Returns *model* if a valid choice. Returns the string if it specifies a ``YNGKP_`` model variant. Returns *('ExpCM', prefsfile)* if it specifies an ``ExpCM_`` model. """ yngkpmatch = re.compile('^YNGKP_M[{0}]$'.format(''.join([m[1 : ] for m in yngkp_modelvariants]))) if yngkpmatch.search(mode... |
def PhyDMSPrepAlignmentParser(): """Returns *argparse.ArgumentParser* for ``phydms_prepalignment``.""" parser = ArgumentParserNoArgHelp(formatter_class=ArgumentDefaultsRawDescriptionFormatter, description='\n'.join([ "Prepare alignment of protein-coding DNA sequences.\n", "Steps:", " * Any sequences specified by '--pur... |
gaps as differences. Identity cutoff set by '--minidentity'.", " * Sequences too similar to other sequences are removed. An", " effort is made to keep one representative of sequences found", " many times in input set. Uniqueness threshold set ", " by '--minuniqueness'. You can specify sequences to not", " remove via '-... |
giving input coding sequences.") parser.add_argument('alignment', help="Name of created output FASTA alignment. PDF plot has same root, but extension '.pdf'.") parser.add_argument('refseq', help="Reference sequence in 'inseqs': specify substring found ONLY in header for that sequence.") parser.set_defaults(prealigned=F... |
purge any of these sequences for lack of identity or uniqueness. Specified in the same fashion as for '--purgeseqs'.") parser.add_argument('-v', '--version', action='version', version='%(prog)s {version}'.format(version=phydmslib.__version__)) return parser |
def PhyDMSLogoPlotParser(): """Returns `argparse.ArgumentParser` for ``phydms_logoplot``.""" parser = ArgumentParserNoArgHelp(description= "Make logo plot of preferences or differential preferences. " "Uses weblogo (http://weblogo.threeplusone.com/). " "{0} Version {1}. Full documentation at {2}".format( phydmslib.__ac... |
type=str, default='jet', help="Name of `matplotlib` color map for amino acids " "when `--mapmetric` is 'kd' or 'mw'.") parser.add_argument('--diffprefheight', type=FloatGreaterThanZero, default=1.0, help="Height of diffpref logo in each direction.") parser.add_argument('--omegabysite', help="Overlay omega on " "logo pl... |
def PhyDMSComprehensiveParser(): """Returns *argparse.ArgumentParser* for ``phdyms_comprehensive`` script.""" parser = ArgumentParserNoArgHelp(description=("Comprehensive phylogenetic " "model comparison and detection of selection informed by deep " "mutational scanning data. This program runs 'phydms' repeatedly " "to... |
(dN/dS) for each site.") parser.set_defaults(diffprefsbysite=False) parser.add_argument('--diffprefsbysite', dest='diffprefsbysite', action='store_true', help="Fit differential preferences for " "each site.") parser.set_defaults(gammaomega=False) parser.add_argument('--gammaomega', dest='gammaomega', action=\ 'store_tr... |
def PhyDMSParser(): """Returns *argparse.ArgumentParser* for ``phydms`` script.""" parser = ArgumentParserNoArgHelp(description=('Phylogenetic analysis ' 'informed by deep mutational scanning data. {0} Version {1}. Full' ' documentation at {2}').format(phydmslib.__acknowledgments__, phydmslib.__version__, phydmslib.__u... |
help="Beta for ExpCM from gamma " "distribution rather than single value.") parser.set_defaults(omegabysite=False) parser.add_argument('--omegabysite', dest='omegabysite', action='store_true', help="Fit omega (dN/dS) for each site.") parser.set_defaults(omegabysite_fixsyn=False) parser.add_argument('--omegabysite_fixsy... |
comma-delimited.")) parser.add_argument('--ncpus', default=1, type=int, help='Use this many CPUs; -1 means all available.') parser.add_argument('--fitprefsmethod', choices=[1, 2], default=2, help='Implementation to we use when fitting prefs.', type=int) parser.add_argument('--ncats', default=4, type=IntGreaterThanOne, ... |
def error(self, message): """Prints error message, then help.""" sys.stderr.write('error: %s\n\n' % message) self.print_help() sys.exit(2) |
def symmetrize(self, method=None, copy=False): '''Symmetrizes (ignores method). Returns a copy if copy=True.''' if copy: return SymmEdgePairGraph(self._pairs.copy(), num_vertices=self._num_vertices) shape = (self._num_vertices, self._num_vertices) flat_inds = np.union1d(np.ravel_multi_index(self._pairs.T, shape), np.ra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.