code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if prune: prune_list = range(i % prune, oracle.n_states - 1, prune) trn_link = [s + 1 for s in oracle.latent[oracle.data[i]] if (oracle.lrs[s] >= lrs and (s + 1) < oracle.n_states) and s in prune_list] else: trn_link = [s...
def improvise_step(oracle, i, lrs=0, weight=None, prune=False)
Given the current time step, improvise (generate) the next time step based on the oracle structure. :param oracle: an indexed vmo object :param i: current improvisation time step :param lrs: the length of minimum longest repeated suffixes allowed to jump :param weight: if None, jump to possible candida...
2.788802
2.66142
1.047863
s = [] if k + continuity < oracle.n_states - 1: s.extend(range(k, k + continuity)) k = s[-1] seq_len -= continuity while seq_len > 0: s.append(improvise_step(oracle, k, LRS, weight)) k = s[-1] if k + 1 < oracle.n_states - 1: k += 1 e...
def improvise(oracle, seq_len, k=1, LRS=0, weight=None, continuity=1)
Given an oracle and length, generate an improvised sequence of the given length. :param oracle: an indexed vmo object :param seq_len: the length of the returned improvisation sequence :param k: the starting improvisation time step in oracle :param LRS: the length of minimum longest repeated suffixes al...
2.510534
2.345361
1.070425
trn = oracle.trn[:] sfx = oracle.sfx[:] lrs = oracle.lrs[:] rsfx = oracle.rsfx[:] s = [] ktrace = [1] for _i in range(seq_len): # generate each state if sfx[k] != 0 and sfx[k] is not None: if (random.random() < p): # copy forward according ...
def generate(oracle, seq_len, p=0.5, k=1, LRS=0, weight=None)
Generate a sequence based on traversing an oracle. :param oracle: a indexed vmo object :param seq_len: the length of the returned improvisation sequence :param p: a float between (0,1) representing the probability using the forward links. :param k: the starting improvisation time step in oracle :pa...
2.898773
2.695482
1.075419
k_vec.sort() if 0 in k_vec: return k_vec else: if sfx[k] not in k_vec: k_vec.append(sfx[k]) for i in range(len(rsfx[k])): if rsfx[k][i] not in k_vec: k_vec.append(rsfx[k][i]) for i in range(len(k_vec)): k_vec = _find_li...
def _find_links(k_vec, sfx, rsfx, k)
Find sfx/rsfx recursively.
1.866952
1.732528
1.077588
if mono: win = np.hanning(n) + 0.00001 else: win = np.array([np.hanning(n) + 0.00001, np.hanning(n) + 0.00001]) win = np.transpose(win) return win
def _make_win(n, mono=False)
Generate a window for a given length. :param n: an integer for the length of the window. :param mono: True for a mono window, False for a stereo window. :return: an numpy array containing the window value.
2.271675
2.271006
1.000295
if wrapped not in _INSTANCES: _INSTANCES[wrapped] = wrapped(*args, **kwargs) return _INSTANCES[wrapped]
def singleton(wrapped, _, args, kwargs)
Return the single instance of wrapped. :param wrapped: the wrapped class. :param _: unused :param args: optional arguments for wrapped object. :param kwargs: optional arguments for wrapped object.
2.21788
2.806401
0.790293
if not isinstance(node, Node): raise TypeError('not a node') for child in node: if condition(child): yield child for subchild in self.filter(child, condition): yield subchild
def filter(self, node, condition)
This method accepts a node and the condition function; a generator will be returned to yield the nodes that got matched by the condition.
3.126753
2.797004
1.117894
for child in self.filter(node, condition): if not skip: return child skip -= 1 raise TypeError('no match found')
def extract(self, node, condition, skip=0)
Extract a single node that matches the provided condition, otherwise a TypeError is raised. An optional skip parameter can be provided to specify how many matching nodes are to be skipped over.
6.407203
4.402642
1.455309
if not depth: return '<%s ...>' % node.__class__.__name__ attrs = [] children = node.children() ids = {id(child) for child in children} indentation = ' ' * (indent * (_level + 1)) header = '\n' + indentation if indent else '' joiner = ',\n'...
def walk( self, node, omit=( 'lexpos', 'lineno', 'colno', 'rowno'), indent=0, depth=-1, pos=False, _level=0)
Accepts the standard node argument, along with an optional omit flag - it should be an iterable that lists out all attributes that should be omitted from the repr output.
2.446274
2.437797
1.003477
'''Directed graph construction alg. from Johns & Mahadevan, ICML '07. trajectories: list of NxD arrays of ordered states ''' X = np.vstack(trajectories) G = neighbor_graph(X, k=k) if pruning_thresh > 0: traj_len = map(len, trajectories) G = _prune_edges(G, X, traj_len, pruning_thresh, verbose=verbos...
def directed_graph(trajectories, k=5, verbose=False, pruning_thresh=0, return_coords=False)
Directed graph construction alg. from Johns & Mahadevan, ICML '07. trajectories: list of NxD arrays of ordered states
5.76534
2.913329
1.978953
'''Prune edges in graph G via cosine distance with trajectory edges.''' W = G.matrix('dense', copy=True) degree = G.degree(kind='out', weighted=False) i = 0 num_bad = 0 for n in traj_lengths: s, t = np.nonzero(W[i:i+n-1]) graph_edges = X[t] - X[s+i] traj_edges = np.diff(X[i:i+n], axis=0) tra...
def _prune_edges(G, X, traj_lengths, pruning_thresh=0.1, verbose=False)
Prune edges in graph G via cosine distance with trajectory edges.
3.872017
3.36819
1.149584
# sets levels of main contour plot colors1 = ['None', 'darkblue', 'blue', 'deepskyblue', 'aqua', 'greenyellow', 'orange', 'red', 'darkred'] if len(self.contour_vals) > len(colors1) + 1: raise AttributeError("Reduce number of contours.") # produc...
def make_plot(self)
This method creates the waterfall plot.
4.713766
4.621302
1.020008
# sets colormap for ratio comparison plot cmap = getattr(cm, self.colormap) # set values of ratio comparison contour normval = 2.0 num_contours = 40 # must be even levels = np.linspace(-normval, normval, num_contours) norm = colors.Normalize(-normval, n...
def make_plot(self)
Creates the ratio plot.
4.029511
3.952746
1.019421
self.comp1 = self.zvals[0] self.comp2 = self.zvals[1] return
def set_comparison(self)
Defines the comparison values for the ratio. This function is added for easier modularity.
5.360289
4.681825
1.144914
# set contour to test and control contour self.ratio_comp_value = (self.comparison_value if self.ratio_comp_value is None else self.ratio_comp_value) # indices of loss,gained. inds_gained = np.where((self.comp1 >= self.comparison_value) ...
def find_difference_contour(self)
Find the ratio and loss/gain contours. This method finds the ratio contour and the Loss/Gain contour values. Its inputs are the two datasets for comparison where the second is the control to compare against the first. The input data sets need to be the same shape. Returns: ...
3.986998
3.724384
1.070512
self.get_contour_values() # sets levels of main contour plot colors1 = ['blue', 'green', 'red', 'purple', 'orange', 'gold', 'magenta'] # set contour value. Default is SNR_CUT. self.snr_contour_value = (self.SNR_CUT if self.snr_contour_value is None ...
def make_plot(self)
Make the horizon plot.
4.30765
4.199387
1.025781
'''Another kind of laplacian normalization, used in the matlab PVF code. Uses the formula: L = I - D^{-1} * W''' W = self.matrix('dense') # calculate -inv(D) Dinv = W.sum(axis=0) mask = Dinv!=0 Dinv[mask] = -1./Dinv[mask] # calculate -inv(D) * W lap = (Dinv * W.T).T # add I l...
def ave_laplacian(self)
Another kind of laplacian normalization, used in the matlab PVF code. Uses the formula: L = I - D^{-1} * W
6.598341
3.744429
1.762176
'''Computes the directed combinatorial graph laplacian. http://www-all.cs.umass.edu/pubs/2007/johns_m_ICML07.pdf D: (optional) N-array of degrees eta: probability of not teleporting (see the paper) tol, max_iter: convergence params for Perron vector calculation ''' W = self.matrix('dense') ...
def directed_laplacian(self, D=None, eta=0.99, tol=1e-12, max_iter=500)
Computes the directed combinatorial graph laplacian. http://www-all.cs.umass.edu/pubs/2007/johns_m_ICML07.pdf D: (optional) N-array of degrees eta: probability of not teleporting (see the paper) tol, max_iter: convergence params for Perron vector calculation
5.215761
2.970161
1.756054
return np.abs(np.diff(self.pairs(), axis=1)).max()
def bandwidth(self)
Computes the 'bandwidth' of a graph.
12.624692
9.978014
1.265251
leftmost_idx = np.argmax(self.matrix('dense').astype(bool), axis=0) return (np.arange(self.num_vertices()) - leftmost_idx).sum()
def profile(self)
Measure of bandedness, also known as 'envelope size'.
11.692813
9.235118
1.266125
'''Computes the betweenness centrality of a graph. kind : string, either 'vertex' (default) or 'edge' directed : bool, defaults to self.is_directed() weighted : bool, defaults to self.is_weighted() ''' assert kind in ('vertex', 'edge'), 'Invalid kind argument: ' + kind weighted = weighted is...
def betweenness(self, kind='vertex', directed=None, weighted=None)
Computes the betweenness centrality of a graph. kind : string, either 'vertex' (default) or 'edge' directed : bool, defaults to self.is_directed() weighted : bool, defaults to self.is_weighted()
3.456041
2.881729
1.199294
'''Maximum distance from each vertex to any other vertex.''' sp = self.shortest_path(directed=directed, weighted=weighted) return sp.max(axis=0)
def eccentricity(self, directed=None, weighted=None)
Maximum distance from each vertex to any other vertex.
5.648238
4.608706
1.225558
'''Returns a greedy vertex coloring as an array of ints.''' n = self.num_vertices() coloring = np.zeros(n, dtype=int) for i, nbrs in enumerate(self.adj_list()): nbr_colors = set(coloring[nbrs]) for c in count(1): if c not in nbr_colors: coloring[i] = c break r...
def color_greedy(self)
Returns a greedy vertex coloring as an array of ints.
3.27298
2.610242
1.253899
'''Returns an approximate 2-coloring as an array of booleans. From "A Multiscale Pyramid Transform for Graph Signals" by Shuman et al. Note: Assumes a single connected component, and may fail otherwise. ''' lap = self.laplacian().astype(float) vals, vecs = eigs(lap, k=1, which='LM') vec = v...
def bicolor_spectral(self)
Returns an approximate 2-coloring as an array of booleans. From "A Multiscale Pyramid Transform for Graph Signals" by Shuman et al. Note: Assumes a single connected component, and may fail otherwise.
8.388179
2.372597
3.535443
'''Simple semi-supervised classification, by assigning unlabeled vertices the label of nearest labeled vertex. partial_labels: (n,) array of integer labels, -1 for unlabeled. ''' labels = np.array(partial_labels, copy=True) unlabeled = labels == -1 # compute geodesic distances from unlabele...
def classify_nearest(self, partial_labels)
Simple semi-supervised classification, by assigning unlabeled vertices the label of nearest labeled vertex. partial_labels: (n,) array of integer labels, -1 for unlabeled.
4.74012
2.969867
1.596072
'''Iterative label spreading for semi-supervised classification. partial_labels: (n,) array of integer labels, -1 for unlabeled. kernel: one of {'none', 'rbf', 'binary'}, for reweighting edges. alpha: scalar, clamping factor. tol: scalar, convergence tolerance. max_iter: integer, cap on the num...
def classify_lgc(self, partial_labels, kernel='rbf', alpha=0.2, tol=1e-3, max_iter=30)
Iterative label spreading for semi-supervised classification. partial_labels: (n,) array of integer labels, -1 for unlabeled. kernel: one of {'none', 'rbf', 'binary'}, for reweighting edges. alpha: scalar, clamping factor. tol: scalar, convergence tolerance. max_iter: integer, cap on the number of ...
4.814764
2.680595
1.796155
'''Harmonic function method for semi-supervised classification, also known as the Gaussian Mean Fields algorithm. partial_labels: (n,) array of integer labels, -1 for unlabeled. use_CMN : when True, apply Class Mass Normalization From "Semi-Supervised Learning Using Gaussian Fields and Harmonic Fu...
def classify_harmonic(self, partial_labels, use_CMN=True)
Harmonic function method for semi-supervised classification, also known as the Gaussian Mean Fields algorithm. partial_labels: (n,) array of integer labels, -1 for unlabeled. use_CMN : when True, apply Class Mass Normalization From "Semi-Supervised Learning Using Gaussian Fields and Harmonic Functions...
5.874132
2.654603
2.21281
'''Perform vertex-valued regression, given partial labels. y : (n,d) array of known labels y_mask : index object such that all_labels[y_mask] == y From "Regularization and Semi-supervised Learning on Large Graphs" by Belkin, Matveeva, and Niyogi in 2004. Doesn't support multiple labels per ve...
def regression(self, y, y_mask, smoothness_penalty=0, kernel='rbf')
Perform vertex-valued regression, given partial labels. y : (n,d) array of known labels y_mask : index object such that all_labels[y_mask] == y From "Regularization and Semi-supervised Learning on Large Graphs" by Belkin, Matveeva, and Niyogi in 2004. Doesn't support multiple labels per vertex, u...
3.776615
2.497836
1.511954
assert param in paramlimits, "Invalid param: {0}".format(param) (lowlim, highlim) = paramlimits[param] paramtype = paramtypes[param] if isinstance(paramtype, tuple): (paramtype, paramshape) = paramtype if not (isinstance(value, paramtype)): raise ValueError("{0} must be ...
def _checkParam(param, value, paramlimits, paramtypes)
Checks if `value` is allowable value for `param`. Raises except if `value` is not acceptable, otherwise returns `None` if value is acceptable. `paramlimits` and `paramtypes` are the `PARAMLIMITS` and `PARAMTYPES` attributes of a `Model`.
1.70242
1.789181
0.951508
assert m.ndim == 3, "M must have 3 dimensions" assert m.shape[1] == m.shape[2], "M must contain square matrices" for r in range(m.shape[0]): scipy.fill_diagonal(m[r], 0) m[r][diag_indices] -= scipy.sum(m[r], axis=1)
def _fill_diagonals(m, diag_indices)
Fills diagonals of `nsites` matrices in `m` so rows sum to 0.
3.256113
2.949283
1.104036
alpha = float(alpha) beta = float(beta) assert alpha > 0 assert beta > 0 assert ncats > 1 scale = 1.0 / beta catmeans = scipy.ndarray(ncats, dtype='float') for k in range(ncats): if k == 0: lower = 0.0 gammainc_lower = 0.0 else: lo...
def DiscreteGamma(alpha, beta, ncats)
Returns category means for discretized gamma distribution. The distribution is evenly divided into categories, and the mean of each category is returned. Args: `alpha` (`float` > 0) Shape parameter of gamma distribution. `beta` (`float` > 0) Inverse scale parameter ...
2.680523
2.517267
1.064855
assert set(value.keys()) == set(self.PARAMLIMITS.keys()), "The \ new parameter limits are not defined for the same set \ of parameters as before." for param in value.keys(): assert value[param][0] < value[param][1], "The new \ mini...
def PARAMLIMITS(self, value)
Set new `PARAMLIMITS` dictionary.
3.576797
3.288172
1.087776
report = {} for param in self._REPORTPARAMS: pvalue = getattr(self, param) if isinstance(pvalue, float): report[param] = pvalue elif isinstance(pvalue, scipy.ndarray) and pvalue.shape == (N_NT,): for w in range(N_NT - 1): ...
def paramsReport(self)
See docs for `Model` abstract base class.
2.945251
2.887415
1.02003
bs = -(self.prx * scipy.diagonal(self.Prxy, axis1=1, axis2=2) ).sum() * self.mu / float(self.nsites) assert bs > 0 return bs
def branchScale(self)
See docs for `Model` abstract base class.
12.850585
11.585449
1.1092
_checkParam('mu', value, self.PARAMLIMITS, self.PARAMTYPES) if value != self.mu: self._cached = {} self._mu = value
def mu(self, value)
Set new `mu` value.
9.896331
8.832108
1.120495
assert all(map(lambda x: x in self.freeparams, newvalues.keys())),\ "Invalid entry in newvalues: {0}\nfreeparams: {1}".format( ', '.join(newvalues.keys()), ', '.join(self.freeparams)) changed = set([]) # contains string names of changed params for (name, ...
def updateParams(self, newvalues, update_all=False)
See docs for `Model` abstract base class.
4.663049
4.579833
1.01817
assert isinstance(t, float) and t > 0, "Invalid t: {0}".format(t) with scipy.errstate(under='ignore'): # don't worry if some values 0 if ('expD', t) not in self._cached: self._cached[('expD', t)] = scipy.exp(self.D * self.mu * t) expD = self._cached[('exp...
def M(self, t, tips=None, gaps=None)
See docs for method in `Model` abstract base class.
4.977471
4.942503
1.007075
self.eta = scipy.ndarray(N_NT - 1, dtype='float') etaprod = 1.0 for w in range(N_NT - 1): self.eta[w] = 1.0 - self.phi[w] / etaprod etaprod *= self.eta[w] _checkParam('eta', self.eta, self.PARAMLIMITS, self.PARAMTYPES)
def _eta_from_phi(self)
Update `eta` using current `phi`.
5.524714
5.241376
1.054058
etaprod = 1.0 for w in range(N_NT - 1): self.phi[w] = etaprod * (1 - self.eta[w]) etaprod *= self.eta[w] self.phi[N_NT - 1] = etaprod
def _update_phi(self)
Update `phi` using current `eta`.
4.311593
3.583941
1.203031
for w in range(N_NT): scipy.copyto(self.Qxy, self.phi[w], where=CODON_NT_MUT[w]) self.Qxy[CODON_TRANSITION] *= self.kappa
def _update_Qxy(self)
Update `Qxy` using current `kappa` and `phi`.
14.492208
11.918139
1.215979
with scipy.errstate(divide='raise', under='raise', over='raise', invalid='raise'): for r in range(self.nsites): self.pi_codon[r] = self.pi[r][CODON_TO_AA] pim = scipy.tile(self.pi_codon[r], (N_CODON, 1)) # [x][y] is piAy self.p...
def _update_pi_vars(self)
Update variables that depend on `pi`. These are `pi_codon`, `ln_pi_codon`, `piAx_piAy`, `piAx_piAy_beta`, `ln_piAx_piAy_beta`. Update using current `pi` and `beta`.
4.399625
3.114015
1.412847
self.Frxy.fill(1.0) self.Frxy_no_omega.fill(1.0) with scipy.errstate(divide='raise', under='raise', over='raise', invalid='ignore'): scipy.copyto(self.Frxy_no_omega, -self.ln_piAx_piAy_beta / (1 - self.piAx_piAy_beta), where=scipy....
def _update_Frxy(self)
Update `Frxy` from `piAx_piAy_beta`, `ln_piAx_piAy_beta`, `omega`, `beta`.
5.906225
3.798489
1.554888
self.Prxy = self.Frxy * self.Qxy _fill_diagonals(self.Prxy, self._diag_indices)
def _update_Prxy(self)
Update `Prxy` using current `Frxy` and `Qxy`.
9.347778
4.382334
2.133059
for r in range(self.nsites): pr_half = self.prx[r]**0.5 pr_neghalf = self.prx[r]**-0.5 #symm_pr = scipy.dot(scipy.diag(pr_half), scipy.dot(self.Prxy[r], scipy.diag(pr_neghalf))) symm_pr = (pr_half * (self.Prxy[r] * pr_neghalf).transpose()).transpose() ...
def _update_Prxy_diag(self)
Update `D`, `A`, `Ainv` from `Prxy`, `prx`.
2.774632
2.477267
1.120038
qx = scipy.ones(N_CODON, dtype='float') for j in range(3): for w in range(N_NT): qx[CODON_NT[j][w]] *= self.phi[w] frx = self.pi_codon**self.beta self.prx = frx * qx with scipy.errstate(divide='raise', under='raise', over='raise', ...
def _update_prx(self)
Update `prx` from `phi`, `pi_codon`, and `beta`.
5.922139
4.398389
1.346434
if 'kappa' in self.freeparams: scipy.copyto(self.dPrxy['kappa'], self.Prxy / self.kappa, where=CODON_TRANSITION) _fill_diagonals(self.dPrxy['kappa'], self._diag_indices) if 'omega' in self.freeparams: scipy.copyto(self.dPrxy['omega'], self...
def _update_dPrxy(self)
Update `dPrxy`.
3.264923
3.240592
1.007508
for param in self.freeparams: if param == 'mu': continue paramval = getattr(self, param) if isinstance(paramval, float): self.B[param] = broadcastMatrixMultiply(self.Ainv, broadcastMatrixMultiply(self.dPrxy[para...
def _update_B(self)
Update `B`.
3.273204
3.177435
1.03014
if 'beta' in self.freeparams: for r in range(self.nsites): self.dprx['beta'][r] = self.prx[r] * (self.ln_pi_codon[r] - scipy.dot(self.ln_pi_codon[r], self.prx[r])) if 'eta' in self.freeparams: boolterm = scipy.ndarray(N_CODON, dtyp...
def _update_dprx(self)
Update `dprx`.
4.009345
3.939283
1.017785
assert m.shape == (self.nsites, N_CODON, N_CODON) for r in range(self.nsites): scipy.fill_diagonal(m[r], 0) m[r][self._diag_indices] -= scipy.sum(m[r], axis=1)
def _fill_diagonals(self, m)
Fills diagonals of `nsites` matrices in `m` so rows sum to 0.
5.582402
4.452756
1.253696
wr = [] for r in range(self.nsites): num = 0 den = 0 for i in range(N_CODON): j = scipy.intersect1d(scipy.where(CODON_SINGLEMUT[i]==True)[0], scipy.where(CODON_NONSYN[i]==True)[0]) p_i = self.stationary...
def spielman_wr(self, norm=True)
Returns a list of site-specific omega values calculated from the `ExpCM`. Args: `norm` (bool) If `True`, normalize the `omega_r` values by the ExpCM gene-wide `omega`. Returns: `wr` (list) list of `omeg...
4.882211
3.719087
1.312745
assert param in self.freeparams, "Invalid param: {0}".format(param) return self._dlogprior[param]
def dlogprior(self, param)
Value of derivative of prior depends on value of `prior`.
5.305007
5.690083
0.932325
super(ExpCM_fitprefs, self)._update_dPrxy() if 'zeta' in self.freeparams: tildeFrxyQxy = self.tildeFrxy * self.Qxy j = 0 zetaxterm = scipy.ndarray((self.nsites, N_CODON, N_CODON), dtype='float') zetayterm = scipy.ndarray((self.nsites, N_CODON, N_...
def _update_dPrxy(self)
Update `dPrxy`.
3.51171
3.493115
1.005323
super(ExpCM_fitprefs, self)._update_dprx() j = 0 if 'zeta' in self.freeparams: self.dprx['zeta'].fill(0) for r in range(self.nsites): for i in range(N_AA - 1): zetari = self.zeta[j] for a in range(i, N_AA): ...
def _update_dprx(self)
Update `dprx`.
6.620523
6.481158
1.021503
super(ExpCM_fitprefs, self)._update_dPrxy() if 'zeta' in self.freeparams: self.dPrxy['zeta'].fill(0.0) tildeFrxyQxy = self.tildeFrxy * self.Qxy j = 0 for r in range(self.nsites): for i in range(N_AA - 1): zetar...
def _update_dPrxy(self)
Update `dPrxy`.
5.325308
5.243214
1.015657
self.phi = self._compute_empirical_phi(self.beta) _checkParam('phi', self.phi, self.PARAMLIMITS, self.PARAMTYPES) self._eta_from_phi() dbeta = 1.0e-3 self.dphi_dbeta = scipy.misc.derivative(self._compute_empirical_phi, self.beta, dx=dbeta, n=1, order=5) ...
def _update_phi(self)
Compute `phi`, `dphi_dbeta`, and `eta` from `g` and `frxy`.
4.071672
3.74515
1.087185
def F(phishort): phifull = scipy.append(phishort, 1 - phishort.sum()) phiprod = scipy.ones(N_CODON, dtype='float') for w in range(N_NT): phiprod *= phifull[w]**CODON_NT_COUNT[w] frx_phiprod = frx * phiprod frx_phi...
def _compute_empirical_phi(self, beta)
Returns empirical `phi` at the given value of `beta`. Does **not** set `phi` attribute, simply returns what should be value of `phi` given the current `g` and `pi_codon` attributes, plus the passed value of `beta`. Note that it uses the passed value of `beta`, **not** the curren...
4.919244
4.531471
1.085573
super(ExpCM_empirical_phi, self)._update_dPrxy() if 'beta' in self.freeparams: self.dQxy_dbeta = scipy.zeros((N_CODON, N_CODON), dtype='float') for w in range(N_NT): scipy.copyto(self.dQxy_dbeta, self.dphi_dbeta[w], where=CODON_NT_...
def _update_dPrxy(self)
Update `dPrxy`, accounting for dependence of `phi` on `beta`.
7.018762
6.793334
1.033184
super(ExpCM_empirical_phi, self)._update_dprx() if 'beta' in self.freeparams: dphi_over_phi = scipy.zeros(N_CODON, dtype='float') for j in range(3): dphi_over_phi += (self.dphi_dbeta / self.phi)[CODON_NT_INDEX[j]] for r in range(self.nsites): ...
def _update_dprx(self)
Update `dprx`, accounting for dependence of `phi` on `beta`.
6.453314
5.716825
1.128828
super(ExpCM_empirical_phi_divpressure, self)._update_dPrxy() if 'omega2' in self.freeparams: with scipy.errstate(divide='raise', under='raise', over='raise', invalid='ignore'): scipy.copyto(self.dPrxy['omega2'], -self.ln_piAx_piAy_beta ...
def _update_dPrxy(self)
Update `dPrxy`, accounting for dependence of `Prxy` on `omega2`.
7.473454
7.189078
1.039557
self.Frxy.fill(1.0) self.Frxy_no_omega.fill(1.0) with scipy.errstate(divide='raise', under='raise', over='raise', invalid='ignore'): scipy.copyto(self.Frxy_no_omega, -self.ln_piAx_piAy_beta / (1 - self.piAx_piAy_beta), where=scipy.logical_...
def _update_Frxy(self)
Update `Frxy` from `piAx_piAy_beta`, `omega`, `omega2`, and `beta`.
4.781484
3.646208
1.311358
report = {} for param in self._REPORTPARAMS: pvalue = getattr(self, param) if isinstance(pvalue, float): report[param] = pvalue elif isinstance(pvalue, scipy.ndarray) and pvalue.shape == (3, N_NT): for p in range(3): ...
def paramsReport(self)
See docs for `Model` abstract base class.
3.835555
3.753266
1.021925
bs = -(self.Phi_x * scipy.diagonal(self.Pxy[0])).sum() * self.mu assert bs > 0 return bs
def branchScale(self)
See docs for `Model` abstract base class.
22.806469
19.520908
1.16831
'''Calculate `phi` based on the empirical `e_pw` values''' def F(phi): phi_reshape = phi.reshape((3, N_NT)) functionList = [] stop_frequency = [] for x in range(N_STOP): codonFrequency = STOP_CODON_TO_NT_INDICES[x] * phi_reshape ...
def _calculate_correctedF3X4(self)
Calculate `phi` based on the empirical `e_pw` values
4.727909
4.059426
1.164674
self.Phi_x = scipy.ones(N_CODON, dtype='float') for codon in range(N_CODON): for pos in range(3): self.Phi_x[codon] *= self.phi[pos][CODON_NT_INDEX[pos][codon]] self.Phi_x /= self.Phi_x.sum()
def _calculate_Phi_x(self)
Calculate `Phi_x` (stationary state) from `phi`.
3.855999
3.575764
1.078371
assert all(map(lambda x: x in self.freeparams, newvalues.keys())),\ "Invalid entry in newvalues: {0}\nfreeparams: {1}".format( ', '.join(newvalues.keys()), ', '.join(self.freeparams)) changed = set([]) # contains string names of changed params for (name, ...
def updateParams(self, newvalues, update_all=False)
See docs for `Model` abstract base class.
4.910668
4.816086
1.019639
assert isinstance(t, float) and t > 0, "Invalid t: {0}".format(t) with scipy.errstate(under='ignore'): # don't worry if some values 0 if ('expD', t) not in self._cached: self._cached[('expD', t)] = scipy.exp(self.D * self.mu * t) expD = self._cached[('exp...
def M(self, t, tips=None, gaps=None)
See docs for method in `Model` abstract base class.
4.812164
4.734671
1.016367
assert isinstance(t, float) and t > 0, "Invalid t: {0}".format(t) assert (param == 't') or (param in self.freeparams), ( "Invalid param: {0}".format(param)) if Mt is None: Mt = self.M(t, tips=tips, gaps=gaps) if (param == 'mu') or (param == 't'): ...
def dM(self, t, param, Mt, tips=None, gaps=None)
See docs for method in `Model` abstract base class.
2.826635
2.825167
1.00052
scipy.copyto(self.Pxy_no_omega, self.Phi_x.transpose(), where=CODON_SINGLEMUT) self.Pxy_no_omega[0][CODON_TRANSITION] *= self.kappa self.Pxy = self.Pxy_no_omega.copy() self.Pxy[0][CODON_NONSYN] *= self.omega _fill_diagonals(self.Pxy, self._diag_indices)
def _update_Pxy(self)
Update `Pxy` using current `omega`, `kappa`, and `Phi_x`.
8.292956
6.676919
1.242033
if 'kappa' in self.freeparams: scipy.copyto(self.dPxy['kappa'], self.Pxy / self.kappa, where=CODON_TRANSITION) _fill_diagonals(self.dPxy['kappa'], self._diag_indices) if 'omega' in self.freeparams: scipy.copyto(self.dPxy['omega'], self.Pxy...
def _update_dPxy(self)
Update `dPxy`.
4.766986
4.684466
1.017616
for r in range(1): Phi_x_half = self.Phi_x**0.5 Phi_x_neghalf = self.Phi_x**-0.5 #symm_p = scipy.dot(scipy.diag(Phi_x_half), scipy.dot(self.Pxy[r], scipy.diag(Phi_x_neghalf))) symm_p = (Phi_x_half * (self.Pxy[r] * Phi_x_neghalf).transpose()).transpose() ...
def _update_Pxy_diag(self)
Update `D`, `A`, `Ainv` from `Pxy`, `Phi_x`.
2.798949
2.490946
1.123649
for param in self.freeparams: if param == 'mu': continue paramval = getattr(self, param) assert isinstance(paramval, float), "Paramvalues must be floats" self.B[param] = broadcastMatrixMultiply(self.Ainv, broadcastMatri...
def _update_B(self)
Update `B`.
7.563998
7.232119
1.04589
assert param in self.freeparams, "Invalid param: {0}".format(param) if param in self.distributionparams: return 0.0 else: return self._models[0].dlogprior(param)
def dlogprior(self, param)
Equal to value of `basemodel.dlogprior`.
4.87646
4.574659
1.065972
assert 0 <= k < self.ncats return self._models[k].M(t, tips=tips, gaps=gaps)
def M(self, k, t, tips=None, gaps=None)
See docs for `DistributionModel` abstract base class.
5.015613
4.544467
1.103675
assert 0 <= k < self.ncats assert ((param in self.freeparams) or (param == 't') or ( param == self.distributedparam)) assert param not in self.distributionparams return self._models[k].dM(t, param, Mkt, tips=tips, gaps=gaps)
def dM(self, k, t, param, Mkt, tips=None, gaps=None)
See docs for `DistributionModel` abstract base class.
6.523619
6.023912
1.082954
if not self._d_distributionparams: dx = 1.0e-3 def f_alpha(alpha): return DiscreteGamma(alpha, self.beta_lambda, self.ncats) def f_beta(beta): return DiscreteGamma(self.alpha_lambda, beta, self.ncats) assert set(self.distri...
def d_distributionparams(self)
See docs for `DistributionModel` abstract base class.
3.383861
3.367783
1.004774
assert all(map(lambda x: x in self.freeparams, newvalues.keys())),\ "Invalid entry in newvalues: {0}\nfreeparams: {1}".format( ', '.join(newvalues.keys()), ', '.join(self.freeparams)) newvalues_list = [{} for k in range(self.ncats)] if update_all or any...
def updateParams(self, newvalues, update_all=False)
See docs for `Model` abstract base class.
2.876494
2.850009
1.009293
report = self._models[0].paramsReport del report[self.distributedparam] for param in self.distributionparams: new_name = "_".join([param.split("_")[0], self.distributedparam]) report[new_name] = getattr(self, param) return report
def paramsReport(self)
See docs for `Model` abstract base class.
6.410553
5.597929
1.145165
mu = self._models[0].mu assert all([mu == model.mu for model in self._models]) return mu
def mu(self)
See docs for `Model` abstract base class.
6.25283
4.339
1.441076
for k in range(self.ncats): self._models[k].updateParams({'mu':value})
def mu(self, value)
Set new `mu` value.
12.284216
10.245941
1.198935
assert 0 <= k < self.ncats return self._models[k].stationarystate
def stationarystate(self, k)
See docs for `Model` abstract base class.
10.637594
9.439428
1.126932
assert param not in self.distributionparams assert param in self.freeparams or param == self.distributedparam ds = self._models[k].dstationarystate(param) return ds
def dstationarystate(self, k, param)
See docs for `Model` abstract base class.
10.347535
9.03665
1.145063
bscales = [m.branchScale for m in self._models] return (self.catweights * bscales).sum()
def branchScale(self)
See docs for `Model` abstract base class.
13.97406
10.069257
1.387795
single = context.singleStore general = context.generalStore key = 13 item = 42 assert single.request(key) == general.request(key) single.add_item(key, item) general.add_item(key, item) assert single.request(key) == general.request(key)
def step_impl04(context)
Compare behavior of singleton vs. non-singleton. :param context: test context.
4.549838
4.114458
1.105817
store = context.SingleStore context.st_1 = store() context.st_2 = store() context.st_3 = store()
def step_impl06(context)
Prepare test for singleton property. :param context: test context.
7.353022
6.840377
1.074944
assert context.st_1 is context.st_2 assert context.st_2 is context.st_3
def step_impl07(context)
Test for singleton property. :param context: test context.
4.853228
5.387072
0.900903
kwargs = dict( encoding=encoding, fieldnames_lower=fieldnames_lower, case_sensitive=case_sensitive, ) if zipped: with Dbf.open_zip(db, zipped, **kwargs) as dbf: yield dbf else: with Dbf.open(db, **kwargs) as dbf: yield dbf
def open_db(db, zipped=None, encoding=None, fieldnames_lower=True, case_sensitive=True)
Context manager. Allows reading DBF file (maybe even from zip). :param str|unicode|file db: .dbf file name or a file-like object. :param str|unicode zipped: .zip file path or a file-like object. :param str|unicode encoding: Encoding used by DB. This will be used if there's no encoding information...
2.125629
2.469338
0.860809
if not case_sensitive: if isinstance(dbfile, string_types): dbfile = pick_name(dbfile, listdir(path.dirname(dbfile))) with open(dbfile, 'rb') as f: yield cls(f, encoding=encoding, fieldnames_lower=fieldnames_lower)
def open(cls, dbfile, encoding=None, fieldnames_lower=True, case_sensitive=True)
Context manager. Allows opening a .dbf file. .. code-block:: with Dbf.open('some.dbf') as dbf: ... :param str|unicode|file dbfile: .dbf filepath or a file-like object. :param str|unicode encoding: Encoding used by DB. This will be used if there's no en...
3.576848
4.527484
0.79003
with ZipFile(zipped, 'r') as zip_: if not case_sensitive: dbname = pick_name(dbname, zip_.namelist()) with zip_.open(dbname) as f: yield cls(f, encoding=encoding, fieldnames_lower=fieldnames_lower)
def open_zip(cls, dbname, zipped, encoding=None, fieldnames_lower=True, case_sensitive=True)
Context manager. Allows opening a .dbf file from zip archive. .. code-block:: with Dbf.open_zip('some.dbf', 'myarch.zip') as dbf: ... :param str|unicode dbname: .dbf file name :param str|unicode|file zipped: .zip file path or a file-like object. :param st...
3.311428
4.150405
0.797857
fileobj = self._fileobj cls_row = self.cls_row fields = self.fields for idx in range(self.prolog.records_count): data = fileobj.read(1) marker = struct.unpack('<1s', data)[0] is_deleted = marker == b'*' if is_deleted: ...
def iter_rows(self)
Generator reading .dbf row one by one. Yields named tuple Row object. :rtype: Row
4.381472
4.39482
0.996963
if self.tick_label_fontsize is not None: self.x_tick_label_fontsize = self.tick_label_fontsize self.y_tick_label_fontsize = self.tick_label_fontsize # setup xticks and yticks and limits # if logspaced, the log values are used. xticks = np.arange(float(se...
def setup_plot(self)
Set up limits and labels. For all plot types, this method is used to setup the basic features of each plot.
1.811976
1.811741
1.00013
self.fig.colorbar(plot_call_sign, cax=self.cbar_ax, ticks=self.cbar_ticks, orientation=self.cbar_orientation) # setup colorbar ticks (getattr(self.cbar_ax, 'set_' + self.cbar_var + 'ticklabels') (self.cbar_tick_labels, fontsize=self.cbar_ticks_fonts...
def setup_colorbars(self, plot_call_sign)
Setup colorbars for each type of plot. Take all of the optional performed during ``__init__`` method and makes the colorbar. Args: plot_call_sign (obj): Plot instance of ax.contourf with colormapping to add as a colorbar.
2.569185
2.569284
0.999962
if 'application/json' in response.headers['content-type']: body = response.json() status = response.status_code if body.get('error'): return self._simple_response_to_error_adapter(status, body) raise UnknownHttpError(response)
def _adapt_response(self, response)
Convert error responses to standardized ErrorDetails.
5.328553
4.693133
1.135394
meta = original_body.get('error') e = [] if 'error_detail' in original_body: errors = original_body.get('error_detail') for error in errors: if type(error) == dict: for parameter, title in error.iteritems(): ...
def _simple_response_to_error_adapter(self, status, original_body)
Convert a single error response.
3.574291
3.448632
1.036437
# sys is global to avoid undefined local global sys, current_settings, execute_from_command_line, ROOT ROOT = os.path.dirname(os.path.abspath(manage_file)) # Adjust the python path and put local packages in front. prev_sys_path = list(sys.path) # Make root application importable without ...
def setup_environ(manage_file, settings=None, more_pythonic=False)
Sets up a Django app within a manage.py file. Keyword Arguments **settings** An imported settings module. Without this, playdoh tries to import these modules (in order): DJANGO_SETTINGS_MODULE, settings **more_pythonic** When True, does not do any path hackery besides adding the v...
3.773596
3.713408
1.016208
from django.core.exceptions import ImproperlyConfigured if settings.SECRET_KEY == '': msg = 'settings.SECRET_KEY cannot be blank! Check your local settings' if not settings.DEBUG: raise ImproperlyConfigured(msg) if getattr(settings, 'SESSION_COOKIE_SECURE', None) is None: ...
def validate_settings(settings)
Raise an error in prod if we see any insecure settings. This used to warn during development but that was changed in 71718bec324c2561da6cc3990c927ee87362f0f7
2.902063
2.840609
1.021634
_cache_attr_name = '_cache_'+method.__name__ _bool_attr_name = '_cached_'+method.__name__ def method_wrapper(self,*args,**kwargs): is_cached = getattr(self,_bool_attr_name) if not is_cached: result = method(self, *args, **kwargs) setattr(self, _cache_attr_name, ...
def cached(method)
this function is used as a decorator for caching
2.204611
2.230593
0.988352
def method_wrapper(self,*args,**kwargs): tail = '_'.join(str(idx) for idx in args) _cache_attr_name = '_cache_'+method.__name__+'_'+tail _bool_attr_name = '_cached_'+method.__name__+'_'+tail is_cached = getattr(self,_bool_attr_name) if not is_cached: result ...
def cached_idxs(method)
this function is used as a decorator for caching
2.381779
2.370468
1.004772
'''See neighbor_graph.''' assert ((k is not None) or (epsilon is not None) ), "Must provide `k` or `epsilon`" assert (_issequence(k) ^ _issequence(epsilon) ), "Exactly one of `k` or `epsilon` must be a sequence." assert weighting in ('binary','none'), "Invalid weighting param: " + weighting ...
def incremental_neighbor_graph(X, precomputed=False, k=None, epsilon=None, weighting='none')
See neighbor_graph.
3.421013
3.379919
1.012158
s = [\ 'Version information:', '\tTime and date: %s' % time.asctime(), '\tPlatform: %s' % platform.platform(), '\tPython version: %s' % sys.version.replace('\n', ' '), '\tphydms version: %s' % phydmslib.__version__, ] for modname in ['...
def Versions()
Returns a string with version information. You would call this function if you want a string giving detailed information on the version of ``phydms`` and the associated packages that it uses.
3.953902
3.41443
1.157998
charmatch = re.compile('^PI_([A-z\*\-]+)$') if isinstance(f, str): f = open(f) lines = f.readlines() f.close() else: lines = f.readlines() characters = [] sites = [] wts = {} pi_means = {} pi_95credint = {} h = {} for line in lines: if...
def readPrefs_dms_tools_format(f)
Reads the amino-acid preferences written by `dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_. This is an exact copy of the same code from `dms_tools.file_io.ReadPreferences`. It is copied because `dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_ is currently only compatible with `python2`,...
3.102167
2.711392
1.144123