code stringlengths 1 18.2k |
|---|
def make_plot(self): """This method creates the waterfall plot. """ # 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.") # produce fille... |
def make_plot(self): """Creates the ratio plot. """ # 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, normval) # find ... |
self.axis.contourf(self.xvals[0], self.yvals[0], loss_gain_contour, levels=[-2, -0.5, 0.5, 2], colors='none', hatches=['x', None, '+']) # make loss/gain contour outline self.axis.contour(self.xvals[0], self.yvals[0], loss_gain_contour, 3, colors='black', linewidths=2) except ValueError: pass if self.add_legend: loss_pa... |
def set_comparison(self): """Defines the comparison values for the ratio. This function is added for easier modularity. """ self.comp1 = self.zvals[0] self.comp2 = self.zvals[1] return |
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: 2-elemen... |
purposed of determining raito differences diff = self.comp1/self.comp2 # the following determines the log10 of the ratio difference. # If it is extremely small, we neglect and put it as zero # (limits chosen to resemble ratios of less than 1.05 and greater than 0.952) diff = (np.log10(diff)*(diff >= 1.05) + (-np.log10(... |
def make_plot(self): """Make the horizon plot. """ 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 else self.snr_contou... |
def ave_laplacian(self): '''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 lap.flat[::W.shape[0... |
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 vect... |
return np.diag(phi) - ((phi * P.T).T + P.T * phi)/2 |
def bandwidth(self): """Computes the 'bandwidth' of a graph.""" return np.abs(np.diff(self.pairs(), axis=1)).max() |
def profile(self): """Measure of bandedness, also known as 'envelope size'.""" leftmost_idx = np.argmax(self.matrix('dense').astype(bool), axis=0) return (np.arange(self.num_vertices()) - leftmost_idx).sum() |
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() ''' assert kind in ('vertex', 'edge'), 'Invalid kind a... |
def eccentricity(self, directed=None, weighted=None): '''Maximum distance from each vertex to any other vertex.''' sp = self.shortest_path(directed=directed, weighted=weighted) return sp.max(axis=0) |
def color_greedy(self): '''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 return coloring |
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. ''' lap = self.laplacian().astype(float) vals, vecs = eigs(lap, k=1, which='LM') vec = ve... |
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. ''' labels = np.array(partial_labels, copy=True) unlabeled = labels == -1 # compute geodesic distance... |
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: s... |
= label_dists label_dists = gram.dot(label_dists) label_dists *= clamp_weights label_dists += y_static # check convergence if np.abs(label_dists - old_label_dists).sum() <= tol: break else: warnings.warn("classify_lgc didn't converge in %d iterations" % max_iter) return classes[label_dists.argmax(axis=1)] |
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 ... |
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 20... |
tmp[y_mask] = True y_mask = tmp # mean-center known y for stability y_mean = y.mean(axis=0) y -= y_mean # use the normalized Laplacian for the smoothness matrix S = self.kernelize(kernel).laplacian(normed=True) if ss.issparse(S): S = S.tocsr() if smoothness_penalty == 0: # see Algorithm 2: Interpolated Regularization u... |
I) f = ss.linalg.lsqr(lhs, y_hat)[0] else: lhs.flat[::n+1] += I f = sl.solve(lhs, y_hat, sym_pos=True, overwrite_a=True, overwrite_b=True) # re-add the mean f += y_mean if ravel_f: return f.ravel() return f |
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`. """ assert param in par... |
else: if not isinstance(value, paramtype): raise ValueError("{0} must be a {1}, not a {2}".format( param, paramtype, type(value))) if not (lowlim <= value <= highlim): raise ValueError("{0} must be >= {1} and <= {2}, not {3}".format( param, lowlim, highlim, value)) |
def _fill_diagonals(m, diag_indices): """Fills diagonals of `nsites` matrices in `m` so rows sum to 0.""" 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 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 of gamma dis... |
catmeans = DiscreteGamma(alpha, beta, ncats) >>> scipy.allclose(catmeans.sum() / ncats, alpha / beta) True """ 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 gammain... |
{3} = {4}").format(catmeans, catmeans.sum() / ncats, alpha, beta, alpha / beta) return catmeans |
def PARAMLIMITS(self, value): """Set new `PARAMLIMITS` dictionary.""" 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 \ minimum value for {0}, ... |
def paramsReport(self): """See docs for `Model` abstract base class.""" 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): report['{0}{1}'.format(par... |
def branchScale(self): """See docs for `Model` abstract base class.""" bs = -(self.prx * scipy.diagonal(self.Prxy, axis1=1, axis2=2) ).sum() * self.mu / float(self.nsites) assert bs > 0 return bs |
def mu(self, value): """Set new `mu` value.""" _checkParam('mu', value, self.PARAMLIMITS, self.PARAMTYPES) if value != self.mu: self._cached = {} self._mu = value |
def updateParams(self, newvalues, update_all=False): """See docs for `Model` abstract base class.""" 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... |
much simpler and adds negligible cost. if update_all or (changed and changed != set(['mu'])): self._update_pi_vars() self._update_phi() self._update_prx() self._update_dprx() self._update_Qxy() self._update_Frxy() self._update_Prxy() self._update_Prxy_diag() self._update_dPrxy() self._update_B() |
def M(self, t, tips=None, gaps=None): """See docs for method in `Model` abstract base class.""" 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... |
def dM(self, t, param, Mt, tips=None, gaps=None): """See docs for method in `Model` abstract base class.""" 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 ... |
* t) expD = self._cached[('expD', t)] if ('V', t) not in self._cached: if 'Dxx_Dyy' not in self._cached: Dyy = scipy.tile(self.D, (1, N_CODON)).reshape( self.nsites, N_CODON, N_CODON) Dxx = scipy.array([Dyy[r].transpose() for r in range(self.nsites)]) self._cached['Dxx_Dyy'] = Dxx - Dyy Dxx_Dyy = self._cached['Dxx_Dyy'... |
dM_param = scipy.ndarray((paramlength, self.nsites, N_CODON, N_CODON), dtype='float') for j in range(paramlength): dM_param[j] = broadcastMatrixMultiply(self.A, broadcastMatrixMultiply(self.B[param][j] * V, self.Ainv)) else: if not paramisvec: dM_param = broadcastMatrixVectorMultiply(self.A, broadcastGetCols(broadcastM... |
def _eta_from_phi(self): """Update `eta` using current `phi`.""" 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 _update_phi(self): """Update `phi` using current `eta`.""" 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_Qxy(self): """Update `Qxy` using current `kappa` and `phi`.""" 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_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`.""" with scipy.errstate(divide='raise', under='raise', over='raise', invalid='raise'): for r in range(self.nsites): self.pi_co... |
def _update_Frxy(self): """Update `Frxy` from `piAx_piAy_beta`, `ln_piAx_piAy_beta`, `omega`, `beta`.""" 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_bet... |
def _update_Prxy(self): """Update `Prxy` using current `Frxy` and `Qxy`.""" self.Prxy = self.Frxy * self.Qxy _fill_diagonals(self.Prxy, self._diag_indices) |
def _update_Prxy_diag(self): """Update `D`, `A`, `Ainv` from `Prxy`, `prx`.""" 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()).t... |
def _update_prx(self): """Update `prx` from `phi`, `pi_codon`, and `beta`.""" 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', invalid='ra... |
def _update_dPrxy(self): """Update `dPrxy`.""" 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.Frxy_no_omega * self.Qxy, where=C... |
def _update_B(self): """Update `B`.""" 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[param], self.A)) else: assert isinstance(paramval, numpy.ndarray) and para... |
def _update_dprx(self): """Update `dprx`.""" 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, dtype='float') with scipy.errstate(divide='raise... |
def _fill_diagonals(self, m): """Fills diagonals of `nsites` matrices in `m` so rows sum to 0.""" 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 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 `omega_r` values of length `nsites` Following `Spielman and Wilke, MBE, 32:1097-1108 <... |
ExpCM `omega` value.""" 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.stationarystate[r][i] P_xy = self.Prxy[r][i][j].sum() if norm: P_xy = P_xy/self.omega Q_xy = self.Qxy[i]... |
def dlogprior(self, param): """Value of derivative of prior depends on value of `prior`.""" assert param in self.freeparams, "Invalid param: {0}".format(param) return self._dlogprior[param] |
def _update_pi_vars(self): """Update variables that depend on `pi` from `zeta`. The updated variables are: `pi`, `pi_codon`, `ln_pi_codon`, `piAx_piAy`, `piAx_piAy_beta`, `ln_piAx_piAy_beta`, and `_logprior`. If `zeta` is undefined (as it will be on the first call), then create `zeta` and `origpi` from `pi` and `origbe... |
zetari zetaprod *= zetari (minzeta, maxzeta) = self.PARAMLIMITS['zeta'] self.zeta[self.zeta < minzeta] = minzeta self.zeta[self.zeta > maxzeta] = maxzeta _checkParam('zeta', self.zeta, self.PARAMLIMITS, self.PARAMTYPES) else: # after first call, we are updating pi from zeta for r in range(self.nsites): zetaprod = 1.0 f... |
self.prior[0] == 'invquadratic': (priorstr, c1, c2) = self.prior self._dlogprior = dict([(param, 0.0) for param in self.freeparams]) self._dlogprior['zeta'] = scipy.zeros(self.zeta.shape, dtype='float') j = 0 aaindex = scipy.arange(N_AA) for r in range(self.nsites): pidiffr = self.pi[r] - self.origpi[r] rlogprior = -c2... |
def _update_dPrxy(self): """Update `dPrxy`.""" 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_CODON), dtype='float') for ... |
def _update_dprx(self): """Update `dprx`.""" 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): delta_aAx = (CODON_TO_AA == a).astype('float') self.dprx['zeta'][j][... |
def _update_dPrxy(self): """Update `dPrxy`.""" 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): zetari = self.zeta[j] self.dPrxy['zeta'][j][r] = tildeFrxyQxy[r] * (... |
def _update_phi(self): """Compute `phi`, `dphi_dbeta`, and `eta` from `g` and `frxy`.""" 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, d... |
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 curr... |
scipy.errstate(invalid='ignore'): result = scipy.optimize.root(F, self.phi[ : -1].copy(), tol=1e-8) assert result.success, "Failed: {0}".format(result) phishort = result.x return scipy.append(phishort, 1 - phishort.sum()) |
def _update_dPrxy(self): """Update `dPrxy`, accounting for dependence of `phi` on `beta`.""" 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... |
def _update_dprx(self): """Update `dprx`, accounting for dependence of `phi` on `beta`.""" 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(... |
def _update_dPrxy(self): """Update `dPrxy`, accounting for dependence of `Prxy` on `omega2`.""" 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_piA... |
def _update_Frxy(self): """Update `Frxy` from `piAx_piAy_beta`, `omega`, `omega2`, and `beta`.""" 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), whe... |
def paramsReport(self): """See docs for `Model` abstract base class.""" 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): for w in range(N_NT - 1): repor... |
def branchScale(self): """See docs for `Model` abstract base class.""" bs = -(self.Phi_x * scipy.diagonal(self.Pxy[0])).sum() * self.mu assert bs > 0 return bs |
def _calculate_correctedF3X4(self): '''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 codonFrequency = scipy.prod(codonFrequency.sum(axis=1))... |
def _calculate_Phi_x(self): """Calculate `Phi_x` (stationary state) from `phi`.""" 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 updateParams(self, newvalues, update_all=False): """See docs for `Model` abstract base class.""" 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... |
much simpler and adds negligible cost. if update_all or (changed and changed != set(['mu'])): self._update_Pxy() self._update_Pxy_diag() self._update_dPxy() self._update_B() |
def M(self, t, tips=None, gaps=None): """See docs for method in `Model` abstract base class.""" 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... |
def dM(self, t, param, Mt, tips=None, gaps=None): """See docs for method in `Model` abstract base class.""" 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 ... |
t)] = scipy.exp(self.D * self.mu * t) expD = self._cached[('expD', t)] if ('V', t) not in self._cached: if 'Dxx_Dyy' not in self._cached: Dyy = scipy.tile(self.D, (1, N_CODON)).reshape( 1, N_CODON, N_CODON) Dxx = scipy.array([Dyy[r].transpose() for r in range(1)]) self._cached['Dxx_Dyy'] = Dxx - Dyy Dxx_Dyy = self._cac... |
is None: return scipy.tile(dM_param, (self.nsites, 1, 1)) else: newdM_param = scipy.zeros((len(tips), N_CODON)) for i in range(len(tips)): newdM_param[i] =(dM_param[0][:,tips[i]]) if gaps is not None: newdM_param[gaps] = scipy.zeros(N_CODON, dtype='float') return newdM_param |
def _update_Pxy(self): """Update `Pxy` using current `omega`, `kappa`, and `Phi_x`.""" 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,... |
def _update_dPxy(self): """Update `dPxy`.""" 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_no_omega, where=CODON_NONSYN) _fill... |
def _update_Pxy_diag(self): """Update `D`, `A`, `Ainv` from `Pxy`, `Phi_x`.""" 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())... |
def _update_B(self): """Update `B`.""" 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, broadcastMatrixMultiply(self.dPxy[param], self.A)) |
def dlogprior(self, param): """Equal to value of `basemodel.dlogprior`.""" 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 M(self, k, t, tips=None, gaps=None): """See docs for `DistributionModel` abstract base class.""" assert 0 <= k < self.ncats return self._models[k].M(t, tips=tips, gaps=gaps) |
def dM(self, k, t, param, Mkt, tips=None, gaps=None): """See docs for `DistributionModel` abstract base class.""" 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, tip... |
def d_distributionparams(self): """See docs for `DistributionModel` abstract base class.""" 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.distributio... |
def updateParams(self, newvalues, update_all=False): """See docs for `Model` abstract base class.""" 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... |
# check to make sure all models have same parameter values for param in self.freeparams: if param not in self.distributionparams: pvalue = getattr(self, param) assert all([scipy.allclose(pvalue, getattr(model, param)) for model in self._models]), ("{0}\n{1}".format( pvalue, '\n'.join([str(getattr(model, param)) for mod... |
def paramsReport(self): """See docs for `Model` abstract base class.""" 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 mu(self): """See docs for `Model` abstract base class.""" mu = self._models[0].mu assert all([mu == model.mu for model in self._models]) return mu |
def mu(self, value): """Set new `mu` value.""" for k in range(self.ncats): self._models[k].updateParams({'mu':value}) |
def stationarystate(self, k): """See docs for `Model` abstract base class.""" assert 0 <= k < self.ncats return self._models[k].stationarystate |
def dstationarystate(self, k, param): """See docs for `Model` abstract base class.""" assert param not in self.distributionparams assert param in self.freeparams or param == self.distributedparam ds = self._models[k].dstationarystate(param) return ds |
def branchScale(self): """See docs for `Model` abstract base class.""" bscales = [m.branchScale for m in self._models] return (self.catweights * bscales).sum() |
def step_impl04(context): """Compare behavior of singleton vs. non-singleton. :param context: test context. """ 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(k... |
def step_impl06(context): """Prepare test for singleton property. :param context: test context. """ store = context.SingleStore context.st_1 = store() context.st_2 = store() context.st_3 = store() |
def step_impl07(context): """Test for singleton property. :param context: test context. """ assert context.st_1 is context.st_2 assert context.st_2 is context.st_3 |
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: Enco... |
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... |
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 ... |
def iter_rows(self): """Generator reading .dbf row one by one. Yields named tuple Row object. :rtype: Row """ 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_d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.