repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
limix/limix-core
limix_core/util/preprocess.py
toRanks
def toRanks(A): """ converts the columns of A to ranks """ AA=sp.zeros_like(A) for i in range(A.shape[1]): AA[:,i] = st.rankdata(A[:,i]) AA=sp.array(sp.around(AA),dtype="int")-1 return AA
python
def toRanks(A): """ converts the columns of A to ranks """ AA=sp.zeros_like(A) for i in range(A.shape[1]): AA[:,i] = st.rankdata(A[:,i]) AA=sp.array(sp.around(AA),dtype="int")-1 return AA
[ "def", "toRanks", "(", "A", ")", ":", "AA", "=", "sp", ".", "zeros_like", "(", "A", ")", "for", "i", "in", "range", "(", "A", ".", "shape", "[", "1", "]", ")", ":", "AA", "[", ":", ",", "i", "]", "=", "st", ".", "rankdata", "(", "A", "[",...
converts the columns of A to ranks
[ "converts", "the", "columns", "of", "A", "to", "ranks" ]
train
https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/util/preprocess.py#L54-L62
limix/limix-core
limix_core/util/preprocess.py
gaussianize
def gaussianize(Y): """ Gaussianize X: [samples x phenotypes] - each phentoype is converted to ranks and transformed back to normal using the inverse CDF """ N,P = Y.shape YY=toRanks(Y) quantiles=(sp.arange(N)+0.5)/N gauss = st.norm.isf(quantiles) Y_gauss=sp.zeros((N,P)) for i in range(P): Y_gauss[:,i] = gauss[YY[:,i]] Y_gauss *= -1 return Y_gauss
python
def gaussianize(Y): """ Gaussianize X: [samples x phenotypes] - each phentoype is converted to ranks and transformed back to normal using the inverse CDF """ N,P = Y.shape YY=toRanks(Y) quantiles=(sp.arange(N)+0.5)/N gauss = st.norm.isf(quantiles) Y_gauss=sp.zeros((N,P)) for i in range(P): Y_gauss[:,i] = gauss[YY[:,i]] Y_gauss *= -1 return Y_gauss
[ "def", "gaussianize", "(", "Y", ")", ":", "N", ",", "P", "=", "Y", ".", "shape", "YY", "=", "toRanks", "(", "Y", ")", "quantiles", "=", "(", "sp", ".", "arange", "(", "N", ")", "+", "0.5", ")", "/", "N", "gauss", "=", "st", ".", "norm", "."...
Gaussianize X: [samples x phenotypes] - each phentoype is converted to ranks and transformed back to normal using the inverse CDF
[ "Gaussianize", "X", ":", "[", "samples", "x", "phenotypes", "]", "-", "each", "phentoype", "is", "converted", "to", "ranks", "and", "transformed", "back", "to", "normal", "using", "the", "inverse", "CDF" ]
train
https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/util/preprocess.py#L64-L78
limix/limix-core
limix_core/util/preprocess.py
regressOut
def regressOut(Y, X, return_b=False): """ regresses out X from Y """ Xd = la.pinv(X) b = Xd.dot(Y) Y_out = Y-X.dot(b) if return_b: return Y_out, b else: return Y_out
python
def regressOut(Y, X, return_b=False): """ regresses out X from Y """ Xd = la.pinv(X) b = Xd.dot(Y) Y_out = Y-X.dot(b) if return_b: return Y_out, b else: return Y_out
[ "def", "regressOut", "(", "Y", ",", "X", ",", "return_b", "=", "False", ")", ":", "Xd", "=", "la", ".", "pinv", "(", "X", ")", "b", "=", "Xd", ".", "dot", "(", "Y", ")", "Y_out", "=", "Y", "-", "X", ".", "dot", "(", "b", ")", "if", "retur...
regresses out X from Y
[ "regresses", "out", "X", "from", "Y" ]
train
https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/util/preprocess.py#L87-L97
limix/limix-core
limix_core/util/preprocess.py
remove_dependent_cols
def remove_dependent_cols(M, tol=1e-6, display=False): """ Returns a matrix where dependent columsn have been removed """ R = la.qr(M, mode='r')[0][:M.shape[1], :] I = (abs(R.diagonal())>tol) if sp.any(~I) and display: print(('cols ' + str(sp.where(~I)[0]) + ' have been removed because linearly dependent on the others')) R = M[:,I] else: R = M.copy() return R
python
def remove_dependent_cols(M, tol=1e-6, display=False): """ Returns a matrix where dependent columsn have been removed """ R = la.qr(M, mode='r')[0][:M.shape[1], :] I = (abs(R.diagonal())>tol) if sp.any(~I) and display: print(('cols ' + str(sp.where(~I)[0]) + ' have been removed because linearly dependent on the others')) R = M[:,I] else: R = M.copy() return R
[ "def", "remove_dependent_cols", "(", "M", ",", "tol", "=", "1e-6", ",", "display", "=", "False", ")", ":", "R", "=", "la", ".", "qr", "(", "M", ",", "mode", "=", "'r'", ")", "[", "0", "]", "[", ":", "M", ".", "shape", "[", "1", "]", ",", ":...
Returns a matrix where dependent columsn have been removed
[ "Returns", "a", "matrix", "where", "dependent", "columsn", "have", "been", "removed" ]
train
https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/util/preprocess.py#L99-L111
limix/limix-core
limix_core/util/preprocess.py
boxcox
def boxcox(X): """ Gaussianize X using the Box-Cox transformation: [samples x phenotypes] - each phentoype is brought to a positive schale, by first subtracting the minimum value and adding 1. - Then each phenotype transformed by the boxcox transformation """ X_transformed = sp.zeros_like(X) maxlog = sp.zeros(X.shape[1]) for i in range(X.shape[1]): i_nan = sp.isnan(X[:,i]) values = X[~i_nan,i] X_transformed[i_nan,i] = X[i_nan,i] X_transformed[~i_nan,i], maxlog[i] = st.boxcox(values-values.min()+1.0) return X_transformed, maxlog
python
def boxcox(X): """ Gaussianize X using the Box-Cox transformation: [samples x phenotypes] - each phentoype is brought to a positive schale, by first subtracting the minimum value and adding 1. - Then each phenotype transformed by the boxcox transformation """ X_transformed = sp.zeros_like(X) maxlog = sp.zeros(X.shape[1]) for i in range(X.shape[1]): i_nan = sp.isnan(X[:,i]) values = X[~i_nan,i] X_transformed[i_nan,i] = X[i_nan,i] X_transformed[~i_nan,i], maxlog[i] = st.boxcox(values-values.min()+1.0) return X_transformed, maxlog
[ "def", "boxcox", "(", "X", ")", ":", "X_transformed", "=", "sp", ".", "zeros_like", "(", "X", ")", "maxlog", "=", "sp", ".", "zeros", "(", "X", ".", "shape", "[", "1", "]", ")", "for", "i", "in", "range", "(", "X", ".", "shape", "[", "1", "]"...
Gaussianize X using the Box-Cox transformation: [samples x phenotypes] - each phentoype is brought to a positive schale, by first subtracting the minimum value and adding 1. - Then each phenotype transformed by the boxcox transformation
[ "Gaussianize", "X", "using", "the", "Box", "-", "Cox", "transformation", ":", "[", "samples", "x", "phenotypes", "]" ]
train
https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/util/preprocess.py#L113-L127
limix/limix-core
limix_core/covar/freeform.py
FreeFormCov.setCovariance
def setCovariance(self,cov): """ set hyperparameters from given covariance """ chol = LA.cholesky(cov,lower=True) params = chol[sp.tril_indices(self.dim)] self.setParams(params)
python
def setCovariance(self,cov): """ set hyperparameters from given covariance """ chol = LA.cholesky(cov,lower=True) params = chol[sp.tril_indices(self.dim)] self.setParams(params)
[ "def", "setCovariance", "(", "self", ",", "cov", ")", ":", "chol", "=", "LA", ".", "cholesky", "(", "cov", ",", "lower", "=", "True", ")", "params", "=", "chol", "[", "sp", ".", "tril_indices", "(", "self", ".", "dim", ")", "]", "self", ".", "set...
set hyperparameters from given covariance
[ "set", "hyperparameters", "from", "given", "covariance" ]
train
https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/covar/freeform.py#L123-L127
jesford/cluster-lensing
clusterlensing/halobias.py
bias
def bias(mass, z, h=h, Om_M=Om_M, Om_L=Om_L): """Calculate halo bias, from Seljak & Warren 2004. Parameters ---------- mass : ndarray or float Halo mass to calculate bias for. z : ndarray or float Halo z, same type and size as mass. h : float, optional Hubble parameter, defaults to astropy.cosmology.Planck13.h Om_M : float, optional Fractional matter density, defaults to astropy.cosmology.Planck13.Om0 Om_L : float, optional Fractional dark energy density, defaults to 1-Om_M. Returns ---------- ndarray or float Returns the halo bias, of same type and size as input mass_halo and z_halo. Calculated according to Seljak & Warren 2004 for z = 0. For halo z > 0, the non-linear mass is adjusted using the input cosmological parameters. References ---------- Based on fitting formula derived from simulations in: U. Seljak and M.S. Warren, "Large-scale bias and stochasticity of haloes and dark matter," Monthly Notices of the Royal Astronomical Society, Volume 355, Issue 1, pp. 129-136 (2004). """ M_nl_0 = (8.73 / h) * (10. ** 12.) # nonlinear mass today [M_sun] M_nl = M_nl_0 * (Om_M + Om_L / ((1. + z) ** 3.)) # scaled to z_lens x = mass / M_nl b = 0.53 + 0.39 * (x ** 0.45) + 0.13 / (40. * x + 1.) + (5.e-4) * (x ** 1.5) return b
python
def bias(mass, z, h=h, Om_M=Om_M, Om_L=Om_L): """Calculate halo bias, from Seljak & Warren 2004. Parameters ---------- mass : ndarray or float Halo mass to calculate bias for. z : ndarray or float Halo z, same type and size as mass. h : float, optional Hubble parameter, defaults to astropy.cosmology.Planck13.h Om_M : float, optional Fractional matter density, defaults to astropy.cosmology.Planck13.Om0 Om_L : float, optional Fractional dark energy density, defaults to 1-Om_M. Returns ---------- ndarray or float Returns the halo bias, of same type and size as input mass_halo and z_halo. Calculated according to Seljak & Warren 2004 for z = 0. For halo z > 0, the non-linear mass is adjusted using the input cosmological parameters. References ---------- Based on fitting formula derived from simulations in: U. Seljak and M.S. Warren, "Large-scale bias and stochasticity of haloes and dark matter," Monthly Notices of the Royal Astronomical Society, Volume 355, Issue 1, pp. 129-136 (2004). """ M_nl_0 = (8.73 / h) * (10. ** 12.) # nonlinear mass today [M_sun] M_nl = M_nl_0 * (Om_M + Om_L / ((1. + z) ** 3.)) # scaled to z_lens x = mass / M_nl b = 0.53 + 0.39 * (x ** 0.45) + 0.13 / (40. * x + 1.) + (5.e-4) * (x ** 1.5) return b
[ "def", "bias", "(", "mass", ",", "z", ",", "h", "=", "h", ",", "Om_M", "=", "Om_M", ",", "Om_L", "=", "Om_L", ")", ":", "M_nl_0", "=", "(", "8.73", "/", "h", ")", "*", "(", "10.", "**", "12.", ")", "# nonlinear mass today [M_sun]", "M_nl", "=", ...
Calculate halo bias, from Seljak & Warren 2004. Parameters ---------- mass : ndarray or float Halo mass to calculate bias for. z : ndarray or float Halo z, same type and size as mass. h : float, optional Hubble parameter, defaults to astropy.cosmology.Planck13.h Om_M : float, optional Fractional matter density, defaults to astropy.cosmology.Planck13.Om0 Om_L : float, optional Fractional dark energy density, defaults to 1-Om_M. Returns ---------- ndarray or float Returns the halo bias, of same type and size as input mass_halo and z_halo. Calculated according to Seljak & Warren 2004 for z = 0. For halo z > 0, the non-linear mass is adjusted using the input cosmological parameters. References ---------- Based on fitting formula derived from simulations in: U. Seljak and M.S. Warren, "Large-scale bias and stochasticity of haloes and dark matter," Monthly Notices of the Royal Astronomical Society, Volume 355, Issue 1, pp. 129-136 (2004).
[ "Calculate", "halo", "bias", "from", "Seljak", "&", "Warren", "2004", "." ]
train
https://github.com/jesford/cluster-lensing/blob/2815c1bb07d904ca91a80dae3f52090016768072/clusterlensing/halobias.py#L9-L47
pyroscope/pyrobase
src/pyrobase/logutil.py
shorten
def shorten(text): """ Reduce text length for displaying / logging purposes. """ if len(text) >= MAX_DISPLAY_LEN: text = text[:MAX_DISPLAY_LEN//2]+"..."+text[-MAX_DISPLAY_LEN//2:] return text
python
def shorten(text): """ Reduce text length for displaying / logging purposes. """ if len(text) >= MAX_DISPLAY_LEN: text = text[:MAX_DISPLAY_LEN//2]+"..."+text[-MAX_DISPLAY_LEN//2:] return text
[ "def", "shorten", "(", "text", ")", ":", "if", "len", "(", "text", ")", ">=", "MAX_DISPLAY_LEN", ":", "text", "=", "text", "[", ":", "MAX_DISPLAY_LEN", "//", "2", "]", "+", "\"...\"", "+", "text", "[", "-", "MAX_DISPLAY_LEN", "//", "2", ":", "]", "...
Reduce text length for displaying / logging purposes.
[ "Reduce", "text", "length", "for", "displaying", "/", "logging", "purposes", "." ]
train
https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/logutil.py#L25-L30
pyroscope/pyrobase
src/pyrobase/logutil.py
get_logfile
def get_logfile(logger=None): """ Return log file of first file handler associated with the (root) logger. None if no such handler is found. """ logger = logger or logging.getLogger() handlers = [i for i in logger.handlers if isinstance(i, logging.FileHandler)] return handlers[0].baseFilename if handlers else None
python
def get_logfile(logger=None): """ Return log file of first file handler associated with the (root) logger. None if no such handler is found. """ logger = logger or logging.getLogger() handlers = [i for i in logger.handlers if isinstance(i, logging.FileHandler)] return handlers[0].baseFilename if handlers else None
[ "def", "get_logfile", "(", "logger", "=", "None", ")", ":", "logger", "=", "logger", "or", "logging", ".", "getLogger", "(", ")", "handlers", "=", "[", "i", "for", "i", "in", "logger", ".", "handlers", "if", "isinstance", "(", "i", ",", "logging", "....
Return log file of first file handler associated with the (root) logger. None if no such handler is found.
[ "Return", "log", "file", "of", "first", "file", "handler", "associated", "with", "the", "(", "root", ")", "logger", ".", "None", "if", "no", "such", "handler", "is", "found", "." ]
train
https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/logutil.py#L33-L39
pedroburon/tbk
tbk/webpay/confirmation.py
ConfirmationPayload.paid_at
def paid_at(self): '''Localized at America/Santiago datetime of ``TBK_FECHA_TRANSACCION``. ''' fecha_transaccion = self.data['TBK_FECHA_TRANSACCION'] hora_transaccion = self.data['TBK_HORA_TRANSACCION'] m = int(fecha_transaccion[:2]) d = int(fecha_transaccion[2:]) h = int(hora_transaccion[:2]) i = int(hora_transaccion[2:4]) s = int(hora_transaccion[4:]) santiago = pytz.timezone('America/Santiago') today = santiago.localize(datetime.datetime.today()) santiago_dt = santiago.localize( datetime.datetime(today.year, m, d, h, i, s)) return santiago_dt
python
def paid_at(self): '''Localized at America/Santiago datetime of ``TBK_FECHA_TRANSACCION``. ''' fecha_transaccion = self.data['TBK_FECHA_TRANSACCION'] hora_transaccion = self.data['TBK_HORA_TRANSACCION'] m = int(fecha_transaccion[:2]) d = int(fecha_transaccion[2:]) h = int(hora_transaccion[:2]) i = int(hora_transaccion[2:4]) s = int(hora_transaccion[4:]) santiago = pytz.timezone('America/Santiago') today = santiago.localize(datetime.datetime.today()) santiago_dt = santiago.localize( datetime.datetime(today.year, m, d, h, i, s)) return santiago_dt
[ "def", "paid_at", "(", "self", ")", ":", "fecha_transaccion", "=", "self", ".", "data", "[", "'TBK_FECHA_TRANSACCION'", "]", "hora_transaccion", "=", "self", ".", "data", "[", "'TBK_HORA_TRANSACCION'", "]", "m", "=", "int", "(", "fecha_transaccion", "[", ":", ...
Localized at America/Santiago datetime of ``TBK_FECHA_TRANSACCION``.
[ "Localized", "at", "America", "/", "Santiago", "datetime", "of", "TBK_FECHA_TRANSACCION", "." ]
train
https://github.com/pedroburon/tbk/blob/ecd6741e0bae06269eb4ac885c3ffcb7902ee40e/tbk/webpay/confirmation.py#L43-L59
pedroburon/tbk
tbk/webpay/confirmation.py
ConfirmationPayload.accountable_date
def accountable_date(self): '''Accountable date of transaction, localized as America/Santiago ''' fecha_transaccion = self.data['TBK_FECHA_CONTABLE'] m = int(fecha_transaccion[:2]) d = int(fecha_transaccion[2:]) santiago = pytz.timezone('America/Santiago') today = santiago.localize(datetime.datetime.today()) year = today.year if self.paid_at.month == 12 and m == 1: year += 1 santiago_dt = santiago.localize(datetime.datetime(year, m, d)) return santiago_dt
python
def accountable_date(self): '''Accountable date of transaction, localized as America/Santiago ''' fecha_transaccion = self.data['TBK_FECHA_CONTABLE'] m = int(fecha_transaccion[:2]) d = int(fecha_transaccion[2:]) santiago = pytz.timezone('America/Santiago') today = santiago.localize(datetime.datetime.today()) year = today.year if self.paid_at.month == 12 and m == 1: year += 1 santiago_dt = santiago.localize(datetime.datetime(year, m, d)) return santiago_dt
[ "def", "accountable_date", "(", "self", ")", ":", "fecha_transaccion", "=", "self", ".", "data", "[", "'TBK_FECHA_CONTABLE'", "]", "m", "=", "int", "(", "fecha_transaccion", "[", ":", "2", "]", ")", "d", "=", "int", "(", "fecha_transaccion", "[", "2", ":...
Accountable date of transaction, localized as America/Santiago
[ "Accountable", "date", "of", "transaction", "localized", "as", "America", "/", "Santiago" ]
train
https://github.com/pedroburon/tbk/blob/ecd6741e0bae06269eb4ac885c3ffcb7902ee40e/tbk/webpay/confirmation.py#L110-L122
pedroburon/tbk
tbk/webpay/confirmation.py
Confirmation.is_success
def is_success(self, check_timeout=True): ''' Check if Webpay response ``TBK_RESPUESTA`` is equal to ``0`` and if the lapse between initialization and this call is less than ``self.timeout`` when ``check_timeout`` is ``True`` (default). :param check_timeout: When ``True``, check time between initialization and call. ''' if check_timeout and self.is_timeout(): return False return self.payload.response == self.payload.SUCCESS_RESPONSE_CODE
python
def is_success(self, check_timeout=True): ''' Check if Webpay response ``TBK_RESPUESTA`` is equal to ``0`` and if the lapse between initialization and this call is less than ``self.timeout`` when ``check_timeout`` is ``True`` (default). :param check_timeout: When ``True``, check time between initialization and call. ''' if check_timeout and self.is_timeout(): return False return self.payload.response == self.payload.SUCCESS_RESPONSE_CODE
[ "def", "is_success", "(", "self", ",", "check_timeout", "=", "True", ")", ":", "if", "check_timeout", "and", "self", ".", "is_timeout", "(", ")", ":", "return", "False", "return", "self", ".", "payload", ".", "response", "==", "self", ".", "payload", "."...
Check if Webpay response ``TBK_RESPUESTA`` is equal to ``0`` and if the lapse between initialization and this call is less than ``self.timeout`` when ``check_timeout`` is ``True`` (default). :param check_timeout: When ``True``, check time between initialization and call.
[ "Check", "if", "Webpay", "response", "TBK_RESPUESTA", "is", "equal", "to", "0", "and", "if", "the", "lapse", "between", "initialization", "and", "this", "call", "is", "less", "than", "self", ".", "timeout", "when", "check_timeout", "is", "True", "(", "defaul...
train
https://github.com/pedroburon/tbk/blob/ecd6741e0bae06269eb4ac885c3ffcb7902ee40e/tbk/webpay/confirmation.py#L183-L192
pedroburon/tbk
tbk/webpay/confirmation.py
Confirmation.is_timeout
def is_timeout(self): ''' Check if the lapse between initialization and now is more than ``self.timeout``. ''' lapse = datetime.datetime.now() - self.init_time return lapse > datetime.timedelta(seconds=self.timeout)
python
def is_timeout(self): ''' Check if the lapse between initialization and now is more than ``self.timeout``. ''' lapse = datetime.datetime.now() - self.init_time return lapse > datetime.timedelta(seconds=self.timeout)
[ "def", "is_timeout", "(", "self", ")", ":", "lapse", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "self", ".", "init_time", "return", "lapse", ">", "datetime", ".", "timedelta", "(", "seconds", "=", "self", ".", "timeout", ")" ]
Check if the lapse between initialization and now is more than ``self.timeout``.
[ "Check", "if", "the", "lapse", "between", "initialization", "and", "now", "is", "more", "than", "self", ".", "timeout", "." ]
train
https://github.com/pedroburon/tbk/blob/ecd6741e0bae06269eb4ac885c3ffcb7902ee40e/tbk/webpay/confirmation.py#L194-L199
inveniosoftware/invenio-config
invenio_config/folder.py
InvenioConfigInstanceFolder.init_app
def init_app(self, app): """Initialize Flask application.""" app.config.from_pyfile('{0}.cfg'.format(app.name), silent=True)
python
def init_app(self, app): """Initialize Flask application.""" app.config.from_pyfile('{0}.cfg'.format(app.name), silent=True)
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "app", ".", "config", ".", "from_pyfile", "(", "'{0}.cfg'", ".", "format", "(", "app", ".", "name", ")", ",", "silent", "=", "True", ")" ]
Initialize Flask application.
[ "Initialize", "Flask", "application", "." ]
train
https://github.com/inveniosoftware/invenio-config/blob/8d1e63ac045cd9c58a3399c6b58845e6daa06102/invenio_config/folder.py#L32-L34
wangsix/vmo
vmo/generate.py
improvise_step
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 candidate time step uniformly, if "lrs", the probability is proportional to the LRS of each candidate time step :param prune: whether to prune improvisation steps based on regular beat structure or not :return: the next time step """ 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 + 1 for s in oracle.latent[oracle.data[i]] if (oracle.lrs[s] >= lrs and (s + 1) < oracle.n_states)] if not trn_link: if i == oracle.n_states - 1: n = 1 else: n = i + 1 else: if weight == 'lrs': lrs_link = [oracle.lrs[s] for s in oracle.latent[oracle.data[i]] if (oracle.lrs[s] >= lrs and (s + 1) < oracle.n_states)] lrs_pop = list(itertools.chain.from_iterable(itertools.chain.from_iterable( [[[i] * _x for (i, _x) in zip(trn_link, lrs_link)]]))) n = np.random.choice(lrs_pop) else: n = trn_link[int(np.floor(random.random() * len(trn_link)))] return n
python
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 candidate time step uniformly, if "lrs", the probability is proportional to the LRS of each candidate time step :param prune: whether to prune improvisation steps based on regular beat structure or not :return: the next time step """ 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 + 1 for s in oracle.latent[oracle.data[i]] if (oracle.lrs[s] >= lrs and (s + 1) < oracle.n_states)] if not trn_link: if i == oracle.n_states - 1: n = 1 else: n = i + 1 else: if weight == 'lrs': lrs_link = [oracle.lrs[s] for s in oracle.latent[oracle.data[i]] if (oracle.lrs[s] >= lrs and (s + 1) < oracle.n_states)] lrs_pop = list(itertools.chain.from_iterable(itertools.chain.from_iterable( [[[i] * _x for (i, _x) in zip(trn_link, lrs_link)]]))) n = np.random.choice(lrs_pop) else: n = trn_link[int(np.floor(random.random() * len(trn_link)))] return n
[ "def", "improvise_step", "(", "oracle", ",", "i", ",", "lrs", "=", "0", ",", "weight", "=", "None", ",", "prune", "=", "False", ")", ":", "if", "prune", ":", "prune_list", "=", "range", "(", "i", "%", "prune", ",", "oracle", ".", "n_states", "-", ...
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 candidate time step uniformly, if "lrs", the probability is proportional to the LRS of each candidate time step :param prune: whether to prune improvisation steps based on regular beat structure or not :return: the next time step
[ "Given", "the", "current", "time", "step", "improvise", "(", "generate", ")", "the", "next", "time", "step", "based", "on", "the", "oracle", "structure", "." ]
train
https://github.com/wangsix/vmo/blob/bb1cc4cf1f33f0bb49e38c91126c1be1a0cdd09d/vmo/generate.py#L28-L64
wangsix/vmo
vmo/generate.py
improvise
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 allowed to jump :param weight: if None, jump to possible candidate time step uniformly, if "lrs", the probability is proportional to the LRS of each candidate time step :param continuity: the number of time steps guaranteed to continue before next jump is executed :return: the improvised sequence """ 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 else: k = 1 if k + continuity < oracle.n_states - 1: s.extend(range(k, k + continuity)) seq_len -= continuity k = s[-1] seq_len -= 1 return s
python
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 allowed to jump :param weight: if None, jump to possible candidate time step uniformly, if "lrs", the probability is proportional to the LRS of each candidate time step :param continuity: the number of time steps guaranteed to continue before next jump is executed :return: the improvised sequence """ 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 else: k = 1 if k + continuity < oracle.n_states - 1: s.extend(range(k, k + continuity)) seq_len -= continuity k = s[-1] seq_len -= 1 return s
[ "def", "improvise", "(", "oracle", ",", "seq_len", ",", "k", "=", "1", ",", "LRS", "=", "0", ",", "weight", "=", "None", ",", "continuity", "=", "1", ")", ":", "s", "=", "[", "]", "if", "k", "+", "continuity", "<", "oracle", ".", "n_states", "-...
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 allowed to jump :param weight: if None, jump to possible candidate time step uniformly, if "lrs", the probability is proportional to the LRS of each candidate time step :param continuity: the number of time steps guaranteed to continue before next jump is executed :return: the improvised sequence
[ "Given", "an", "oracle", "and", "length", "generate", "an", "improvised", "sequence", "of", "the", "given", "length", "." ]
train
https://github.com/wangsix/vmo/blob/bb1cc4cf1f33f0bb49e38c91126c1be1a0cdd09d/vmo/generate.py#L67-L99
wangsix/vmo
vmo/generate.py
generate
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 :param LRS: the length of minimum longest repeated suffixes allowed to jump :param weight: None: choose uniformly among all the possible sfx/rsfx given current state. "max": always choose the sfx/rsfx having the longest LRS. "weight": choose sfx/rsfx in a way that favors longer ones than shorter ones. :return: s: a list containing the sequence generated, each element represents a state. kend: the ending state. ktrace: """ 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 to transitions I = trn[k] if len(I) == 0: # if last state, choose a suffix k = sfx[k] ktrace.append(k) I = trn[k] sym = I[int(np.floor(random.random() * len(I)))] s.append(sym) # Why (sym-1) before? k = sym ktrace.append(k) else: # copy any of the next symbols ktrace.append(k) _k = k k_vec = [] k_vec = _find_links(k_vec, sfx, rsfx, _k) k_vec = [_i for _i in k_vec if lrs[_i] >= LRS] lrs_vec = [lrs[_i] for _i in k_vec] if len(k_vec) > 0: # if a possibility found, len(I) if weight == 'weight': max_lrs = np.amax(lrs_vec) query_lrs = max_lrs - np.floor(random.expovariate(1)) if query_lrs in lrs_vec: _tmp = np.where(lrs_vec == query_lrs)[0] _tmp = _tmp[int( np.floor(random.random() * len(_tmp)))] sym = k_vec[_tmp] else: _tmp = np.argmin(abs( np.subtract(lrs_vec, query_lrs))) sym = k_vec[_tmp] elif weight == 'max': sym = k_vec[np.argmax([lrs[_i] for _i in k_vec])] else: sym = k_vec[int(np.floor(random.random() * len(k_vec)))] if sym == len(sfx) - 1: sym = sfx[sym] + 1 else: s.append(sym + 1) k = sym + 1 ktrace.append(k) else: # otherwise continue if k < len(sfx) - 1: sym = k + 1 else: sym = sfx[k] + 1 s.append(sym) k = sym ktrace.append(k) else: if k < len(sfx) - 1: s.append(k + 1) k += 1 ktrace.append(k) else: sym = sfx[k] + 1 s.append(sym) k = sym ktrace.append(k) if k >= len(sfx) - 1: k = 0 kend = k return s, kend, ktrace
python
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 :param LRS: the length of minimum longest repeated suffixes allowed to jump :param weight: None: choose uniformly among all the possible sfx/rsfx given current state. "max": always choose the sfx/rsfx having the longest LRS. "weight": choose sfx/rsfx in a way that favors longer ones than shorter ones. :return: s: a list containing the sequence generated, each element represents a state. kend: the ending state. ktrace: """ 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 to transitions I = trn[k] if len(I) == 0: # if last state, choose a suffix k = sfx[k] ktrace.append(k) I = trn[k] sym = I[int(np.floor(random.random() * len(I)))] s.append(sym) # Why (sym-1) before? k = sym ktrace.append(k) else: # copy any of the next symbols ktrace.append(k) _k = k k_vec = [] k_vec = _find_links(k_vec, sfx, rsfx, _k) k_vec = [_i for _i in k_vec if lrs[_i] >= LRS] lrs_vec = [lrs[_i] for _i in k_vec] if len(k_vec) > 0: # if a possibility found, len(I) if weight == 'weight': max_lrs = np.amax(lrs_vec) query_lrs = max_lrs - np.floor(random.expovariate(1)) if query_lrs in lrs_vec: _tmp = np.where(lrs_vec == query_lrs)[0] _tmp = _tmp[int( np.floor(random.random() * len(_tmp)))] sym = k_vec[_tmp] else: _tmp = np.argmin(abs( np.subtract(lrs_vec, query_lrs))) sym = k_vec[_tmp] elif weight == 'max': sym = k_vec[np.argmax([lrs[_i] for _i in k_vec])] else: sym = k_vec[int(np.floor(random.random() * len(k_vec)))] if sym == len(sfx) - 1: sym = sfx[sym] + 1 else: s.append(sym + 1) k = sym + 1 ktrace.append(k) else: # otherwise continue if k < len(sfx) - 1: sym = k + 1 else: sym = sfx[k] + 1 s.append(sym) k = sym ktrace.append(k) else: if k < len(sfx) - 1: s.append(k + 1) k += 1 ktrace.append(k) else: sym = sfx[k] + 1 s.append(sym) k = sym ktrace.append(k) if k >= len(sfx) - 1: k = 0 kend = k return s, kend, ktrace
[ "def", "generate", "(", "oracle", ",", "seq_len", ",", "p", "=", "0.5", ",", "k", "=", "1", ",", "LRS", "=", "0", ",", "weight", "=", "None", ")", ":", "trn", "=", "oracle", ".", "trn", "[", ":", "]", "sfx", "=", "oracle", ".", "sfx", "[", ...
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 :param LRS: the length of minimum longest repeated suffixes allowed to jump :param weight: None: choose uniformly among all the possible sfx/rsfx given current state. "max": always choose the sfx/rsfx having the longest LRS. "weight": choose sfx/rsfx in a way that favors longer ones than shorter ones. :return: s: a list containing the sequence generated, each element represents a state. kend: the ending state. ktrace:
[ "Generate", "a", "sequence", "based", "on", "traversing", "an", "oracle", "." ]
train
https://github.com/wangsix/vmo/blob/bb1cc4cf1f33f0bb49e38c91126c1be1a0cdd09d/vmo/generate.py#L106-L204
wangsix/vmo
vmo/generate.py
_find_links
def _find_links(k_vec, sfx, rsfx, k): """Find sfx/rsfx recursively.""" 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_links(k_vec, sfx, rsfx, k_vec[i]) if 0 in k_vec: break return k_vec
python
def _find_links(k_vec, sfx, rsfx, k): """Find sfx/rsfx recursively.""" 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_links(k_vec, sfx, rsfx, k_vec[i]) if 0 in k_vec: break return k_vec
[ "def", "_find_links", "(", "k_vec", ",", "sfx", ",", "rsfx", ",", "k", ")", ":", "k_vec", ".", "sort", "(", ")", "if", "0", "in", "k_vec", ":", "return", "k_vec", "else", ":", "if", "sfx", "[", "k", "]", "not", "in", "k_vec", ":", "k_vec", ".",...
Find sfx/rsfx recursively.
[ "Find", "sfx", "/", "rsfx", "recursively", "." ]
train
https://github.com/wangsix/vmo/blob/bb1cc4cf1f33f0bb49e38c91126c1be1a0cdd09d/vmo/generate.py#L207-L222
wangsix/vmo
vmo/generate.py
_make_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. """ 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
python
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. """ 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", ")", ":", "if", "mono", ":", "win", "=", "np", ".", "hanning", "(", "n", ")", "+", "0.00001", "else", ":", "win", "=", "np", ".", "array", "(", "[", "np", ".", "hanning", "(", "n", ")",...
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.
[ "Generate", "a", "window", "for", "a", "given", "length", "." ]
train
https://github.com/wangsix/vmo/blob/bb1cc4cf1f33f0bb49e38c91126c1be1a0cdd09d/vmo/generate.py#L225-L238
stbraun/fuzzing
gp_decorators/singleton.py
singleton
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. """ if wrapped not in _INSTANCES: _INSTANCES[wrapped] = wrapped(*args, **kwargs) return _INSTANCES[wrapped]
python
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. """ if wrapped not in _INSTANCES: _INSTANCES[wrapped] = wrapped(*args, **kwargs) return _INSTANCES[wrapped]
[ "def", "singleton", "(", "wrapped", ",", "_", ",", "args", ",", "kwargs", ")", ":", "if", "wrapped", "not", "in", "_INSTANCES", ":", "_INSTANCES", "[", "wrapped", "]", "=", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "_INSTAN...
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.
[ "Return", "the", "single", "instance", "of", "wrapped", ".", ":", "param", "wrapped", ":", "the", "wrapped", "class", ".", ":", "param", "_", ":", "unused", ":", "param", "args", ":", "optional", "arguments", "for", "wrapped", "object", ".", ":", "param"...
train
https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/gp_decorators/singleton.py#L11-L20
calmjs/calmjs.parse
src/calmjs/parse/walkers.py
Walker.filter
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. """ 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
python
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. """ 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", ")", ":", "if", "not", "isinstance", "(", "node", ",", "Node", ")", ":", "raise", "TypeError", "(", "'not a node'", ")", "for", "child", "in", "node", ":", "if", "condition", "(", "child", ...
This method accepts a node and the condition function; a generator will be returned to yield the nodes that got matched by the 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", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/walkers.py#L78-L92
calmjs/calmjs.parse
src/calmjs/parse/walkers.py
Walker.extract
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. """ for child in self.filter(node, condition): if not skip: return child skip -= 1 raise TypeError('no match found')
python
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. """ 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", ")", ":", "for", "child", "in", "self", ".", "filter", "(", "node", ",", "condition", ")", ":", "if", "not", "skip", ":", "return", "child", "skip", "-=", "1", "...
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.
[ "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",...
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/walkers.py#L94-L106
calmjs/calmjs.parse
src/calmjs/parse/walkers.py
ReprWalker.walk
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. """ 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' + indentation if indent else ', ' tailer = '\n' + ' ' * (indent * _level) if indent else '' for k, v in vars(node).items(): if k.startswith('_'): continue if id(v) in ids: ids.remove(id(v)) if isinstance(v, Node): attrs.append((k, self.walk( v, omit, indent, depth - 1, pos, _level))) elif isinstance(v, list): items = [] for i in v: if id(i) in ids: ids.remove(id(i)) items.append(self.walk( i, omit, indent, depth - 1, pos, _level + 1)) attrs.append( (k, '[' + header + joiner.join(items) + tailer + ']')) else: attrs.append((k, repr_compat(v))) if ids: # for unnamed child nodes. attrs.append(('?children', '[' + header + joiner.join( self.walk(child, omit, indent, depth - 1, pos, _level + 1) for child in children if id(child) in ids) + tailer + ']')) position = ('@%s:%s ' % ( '?' if node.lineno is None else node.lineno, '?' if node.colno is None else node.colno, ) if pos else '') omit_keys = () if not omit else set(omit) return '<%s %s%s>' % (node.__class__.__name__, position, ', '.join( '%s=%s' % (k, v) for k, v in sorted(attrs) if k not in omit_keys ))
python
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. """ 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' + indentation if indent else ', ' tailer = '\n' + ' ' * (indent * _level) if indent else '' for k, v in vars(node).items(): if k.startswith('_'): continue if id(v) in ids: ids.remove(id(v)) if isinstance(v, Node): attrs.append((k, self.walk( v, omit, indent, depth - 1, pos, _level))) elif isinstance(v, list): items = [] for i in v: if id(i) in ids: ids.remove(id(i)) items.append(self.walk( i, omit, indent, depth - 1, pos, _level + 1)) attrs.append( (k, '[' + header + joiner.join(items) + tailer + ']')) else: attrs.append((k, repr_compat(v))) if ids: # for unnamed child nodes. attrs.append(('?children', '[' + header + joiner.join( self.walk(child, omit, indent, depth - 1, pos, _level + 1) for child in children if id(child) in ids) + tailer + ']')) position = ('@%s:%s ' % ( '?' if node.lineno is None else node.lineno, '?' if node.colno is None else node.colno, ) if pos else '') omit_keys = () if not omit else set(omit) return '<%s %s%s>' % (node.__class__.__name__, position, ', '.join( '%s=%s' % (k, v) for k, v in sorted(attrs) if k not in omit_keys ))
[ "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.
[ "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",...
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/walkers.py#L137-L198
all-umass/graphs
graphs/construction/directed.py
directed_graph
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 ''' 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=verbose) if return_coords: return G, X return G
python
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 ''' 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=verbose) if return_coords: return G, X return G
[ "def", "directed_graph", "(", "trajectories", ",", "k", "=", "5", ",", "verbose", "=", "False", ",", "pruning_thresh", "=", "0", ",", "return_coords", "=", "False", ")", ":", "X", "=", "np", ".", "vstack", "(", "trajectories", ")", "G", "=", "neighbor_...
Directed graph construction alg. from Johns & Mahadevan, ICML '07. trajectories: list of NxD arrays of ordered states
[ "Directed", "graph", "construction", "alg", ".", "from", "Johns", "&", "Mahadevan", "ICML", "07", ".", "trajectories", ":", "list", "of", "NxD", "arrays", "of", "ordered", "states" ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/construction/directed.py#L11-L23
all-umass/graphs
graphs/construction/directed.py
_prune_edges
def _prune_edges(G, X, traj_lengths, pruning_thresh=0.1, verbose=False): '''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) traj_edges = np.repeat(traj_edges, degree[i:i+n-1], axis=0) theta = paired_distances(graph_edges, traj_edges, 'cosine') bad_edges = theta > pruning_thresh s, t = s[bad_edges], t[bad_edges] if verbose: # pragma: no cover num_bad += np.count_nonzero(W[s,t]) W[s,t] = 0 i += n if verbose: # pragma: no cover print('removed %d bad edges' % num_bad) return Graph.from_adj_matrix(W)
python
def _prune_edges(G, X, traj_lengths, pruning_thresh=0.1, verbose=False): '''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) traj_edges = np.repeat(traj_edges, degree[i:i+n-1], axis=0) theta = paired_distances(graph_edges, traj_edges, 'cosine') bad_edges = theta > pruning_thresh s, t = s[bad_edges], t[bad_edges] if verbose: # pragma: no cover num_bad += np.count_nonzero(W[s,t]) W[s,t] = 0 i += n if verbose: # pragma: no cover print('removed %d bad edges' % num_bad) return Graph.from_adj_matrix(W)
[ "def", "_prune_edges", "(", "G", ",", "X", ",", "traj_lengths", ",", "pruning_thresh", "=", "0.1", ",", "verbose", "=", "False", ")", ":", "W", "=", "G", ".", "matrix", "(", "'dense'", ",", "copy", "=", "True", ")", "degree", "=", "G", ".", "degree...
Prune edges in graph G via cosine distance with trajectory edges.
[ "Prune", "edges", "in", "graph", "G", "via", "cosine", "distance", "with", "trajectory", "edges", "." ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/construction/directed.py#L26-L46
mikekatz04/BOWIE
bowie/plotutils/plottypes.py
Waterfall.make_plot
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 filled contour of SNR sc = self.axis.contourf(self.xvals[0], self.yvals[0], self.zvals[0], levels=np.asarray(self.contour_vals), colors=colors1) self.colorbar.setup_colorbars(sc) # check for user desire to show separate contour line if self.snr_contour_value is not None: self.axis.contour(self.xvals[0], self.yvals[0], self.zvals[0], np.array([self.snr_contour_value]), colors='white', linewidths=1.5, linestyles='dashed') return
python
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 filled contour of SNR sc = self.axis.contourf(self.xvals[0], self.yvals[0], self.zvals[0], levels=np.asarray(self.contour_vals), colors=colors1) self.colorbar.setup_colorbars(sc) # check for user desire to show separate contour line if self.snr_contour_value is not None: self.axis.contour(self.xvals[0], self.yvals[0], self.zvals[0], np.array([self.snr_contour_value]), colors='white', linewidths=1.5, linestyles='dashed') return
[ "def", "make_plot", "(", "self", ")", ":", "# sets levels of main contour plot", "colors1", "=", "[", "'None'", ",", "'darkblue'", ",", "'blue'", ",", "'deepskyblue'", ",", "'aqua'", ",", "'greenyellow'", ",", "'orange'", ",", "'red'", ",", "'darkred'", "]", "...
This method creates the waterfall plot.
[ "This", "method", "creates", "the", "waterfall", "plot", "." ]
train
https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/bowie/plotutils/plottypes.py#L26-L50
mikekatz04/BOWIE
bowie/plotutils/plottypes.py
Ratio.make_plot
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 Loss/Gain contour and Ratio contour self.set_comparison() diff_out, loss_gain_contour = self.find_difference_contour() cmap.set_bad(color='white', alpha=0.001) # plot ratio contours sc = self.axis.contourf(self.xvals[0], self.yvals[0], diff_out, levels=levels, norm=norm, extend='both', cmap=cmap) self.colorbar.setup_colorbars(sc) # toggle line contours of orders of magnitude of ratio comparisons if self.order_contour_lines: self.axis.contour(self.xvals[0], self.yvals[0], diff_out, np.array( [-2.0, -1.0, 1.0, 2.0]), colors='black', linewidths=1.0) # plot loss gain contour if self.loss_gain_status is True: # if there is no loss/gain contours, this will produce an error, # so we catch the exception. try: # make hatching cs = 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_patch = Patch(fill=None, label='Loss', hatch='x', linestyle='--', linewidth=2) gain_patch = Patch(fill=None, label='Gain', hatch='+', linestyle='-', linewidth=2) legend = self.axis.legend(handles=[loss_patch, gain_patch], **self.legend_kwargs) return
python
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 Loss/Gain contour and Ratio contour self.set_comparison() diff_out, loss_gain_contour = self.find_difference_contour() cmap.set_bad(color='white', alpha=0.001) # plot ratio contours sc = self.axis.contourf(self.xvals[0], self.yvals[0], diff_out, levels=levels, norm=norm, extend='both', cmap=cmap) self.colorbar.setup_colorbars(sc) # toggle line contours of orders of magnitude of ratio comparisons if self.order_contour_lines: self.axis.contour(self.xvals[0], self.yvals[0], diff_out, np.array( [-2.0, -1.0, 1.0, 2.0]), colors='black', linewidths=1.0) # plot loss gain contour if self.loss_gain_status is True: # if there is no loss/gain contours, this will produce an error, # so we catch the exception. try: # make hatching cs = 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_patch = Patch(fill=None, label='Loss', hatch='x', linestyle='--', linewidth=2) gain_patch = Patch(fill=None, label='Gain', hatch='+', linestyle='-', linewidth=2) legend = self.axis.legend(handles=[loss_patch, gain_patch], **self.legend_kwargs) return
[ "def", "make_plot", "(", "self", ")", ":", "# 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"...
Creates the ratio plot.
[ "Creates", "the", "ratio", "plot", "." ]
train
https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/bowie/plotutils/plottypes.py#L71-L123
mikekatz04/BOWIE
bowie/plotutils/plottypes.py
Ratio.set_comparison
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
python
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", "set_comparison", "(", "self", ")", ":", "self", ".", "comp1", "=", "self", ".", "zvals", "[", "0", "]", "self", ".", "comp2", "=", "self", ".", "zvals", "[", "1", "]", "return" ]
Defines the comparison values for the ratio. This function is added for easier modularity.
[ "Defines", "the", "comparison", "values", "for", "the", "ratio", "." ]
train
https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/bowie/plotutils/plottypes.py#L125-L133
mikekatz04/BOWIE
bowie/plotutils/plottypes.py
Ratio.find_difference_contour
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-element tuple containing - **diff** (*2D array of floats*): Ratio contour values. - **loss_gain_contour** (*2D array of floats*): loss/gain contour values. """ # 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) & (self.comp2 < self.comparison_value)) inds_lost = np.where((self.comp1 < self.comparison_value) & (self.comp2 >= self.comparison_value)) self.comp1 = np.ma.masked_where(self.comp1 < self.ratio_comp_value, self.comp1) self.comp2 = np.ma.masked_where(self.comp2 < self.ratio_comp_value, self.comp2) # set diff to ratio for 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(1.0/diff)) * (diff <= 0.952) + 0.0*((diff < 1.05) & (diff > 0.952))) # initialize loss/gain loss_gain_contour = np.zeros(np.shape(self.comp1)) # fill out loss/gain loss_gain_contour[inds_lost] = -1 loss_gain_contour[inds_gained] = 1 return diff, loss_gain_contour
python
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-element tuple containing - **diff** (*2D array of floats*): Ratio contour values. - **loss_gain_contour** (*2D array of floats*): loss/gain contour values. """ # 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) & (self.comp2 < self.comparison_value)) inds_lost = np.where((self.comp1 < self.comparison_value) & (self.comp2 >= self.comparison_value)) self.comp1 = np.ma.masked_where(self.comp1 < self.ratio_comp_value, self.comp1) self.comp2 = np.ma.masked_where(self.comp2 < self.ratio_comp_value, self.comp2) # set diff to ratio for 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(1.0/diff)) * (diff <= 0.952) + 0.0*((diff < 1.05) & (diff > 0.952))) # initialize loss/gain loss_gain_contour = np.zeros(np.shape(self.comp1)) # fill out loss/gain loss_gain_contour[inds_lost] = -1 loss_gain_contour[inds_gained] = 1 return diff, loss_gain_contour
[ "def", "find_difference_contour", "(", "self", ")", ":", "# 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_valu...
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-element tuple containing - **diff** (*2D array of floats*): Ratio contour values. - **loss_gain_contour** (*2D array of floats*): loss/gain contour values.
[ "Find", "the", "ratio", "and", "loss", "/", "gain", "contours", "." ]
train
https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/bowie/plotutils/plottypes.py#L135-L180
mikekatz04/BOWIE
bowie/plotutils/plottypes.py
Horizon.make_plot
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_contour_value) # plot contours for j in range(len(self.zvals)): hz = self.axis.contour(self.xvals[j], self.yvals[j], self.zvals[j], np.array([self.snr_contour_value]), colors=colors1[j], linewidths=1., linestyles='solid') # plot invisible lines for purpose of creating a legend if self.legend_labels != []: # plot a curve off of the grid with same color for legend label. self.axis.plot([0.1, 0.2], [0.1, 0.2], color=colors1[j], label=self.legend_labels[j]) if self.add_legend: self.axis.legend(**self.legend_kwargs) return
python
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_contour_value) # plot contours for j in range(len(self.zvals)): hz = self.axis.contour(self.xvals[j], self.yvals[j], self.zvals[j], np.array([self.snr_contour_value]), colors=colors1[j], linewidths=1., linestyles='solid') # plot invisible lines for purpose of creating a legend if self.legend_labels != []: # plot a curve off of the grid with same color for legend label. self.axis.plot([0.1, 0.2], [0.1, 0.2], color=colors1[j], label=self.legend_labels[j]) if self.add_legend: self.axis.legend(**self.legend_kwargs) return
[ "def", "make_plot", "(", "self", ")", ":", "self", ".", "get_contour_values", "(", ")", "# sets levels of main contour plot", "colors1", "=", "[", "'blue'", ",", "'green'", ",", "'red'", ",", "'purple'", ",", "'orange'", ",", "'gold'", ",", "'magenta'", "]", ...
Make the horizon plot.
[ "Make", "the", "horizon", "plot", "." ]
train
https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/bowie/plotutils/plottypes.py#L194-L223
all-umass/graphs
graphs/mixins/analysis.py
AnalysisMixin.ave_laplacian
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]+1] += 1 # symmetrize return (lap + lap.T) / 2.0
python
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]+1] += 1 # symmetrize return (lap + lap.T) / 2.0
[ "def", "ave_laplacian", "(", "self", ")", ":", "W", "=", "self", ".", "matrix", "(", "'dense'", ")", "# calculate -inv(D)", "Dinv", "=", "W", ".", "sum", "(", "axis", "=", "0", ")", "mask", "=", "Dinv", "!=", "0", "Dinv", "[", "mask", "]", "=", "...
Another kind of laplacian normalization, used in the matlab PVF code. Uses the formula: L = I - D^{-1} * W
[ "Another", "kind", "of", "laplacian", "normalization", "used", "in", "the", "matlab", "PVF", "code", ".", "Uses", "the", "formula", ":", "L", "=", "I", "-", "D^", "{", "-", "1", "}", "*", "W" ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/analysis.py#L46-L59
all-umass/graphs
graphs/mixins/analysis.py
AnalysisMixin.directed_laplacian
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 ''' W = self.matrix('dense') n = W.shape[0] if D is None: D = W.sum(axis=1) # compute probability transition matrix with np.errstate(invalid='ignore', divide='ignore'): P = W.astype(float) / D[:,None] P[D==0] = 0 # start at the uniform distribution Perron vector (phi) old_phi = np.ones(n) / n # iterate to the fixed point (teleporting random walk) for _ in range(max_iter): phi = eta * old_phi.dot(P) + (1-eta)/n if np.abs(phi - old_phi).max() < tol: break old_phi = phi else: warnings.warn("phi failed to converge after %d iterations" % max_iter) # L = Phi - (Phi P + P' Phi)/2 return np.diag(phi) - ((phi * P.T).T + P.T * phi)/2
python
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 ''' W = self.matrix('dense') n = W.shape[0] if D is None: D = W.sum(axis=1) # compute probability transition matrix with np.errstate(invalid='ignore', divide='ignore'): P = W.astype(float) / D[:,None] P[D==0] = 0 # start at the uniform distribution Perron vector (phi) old_phi = np.ones(n) / n # iterate to the fixed point (teleporting random walk) for _ in range(max_iter): phi = eta * old_phi.dot(P) + (1-eta)/n if np.abs(phi - old_phi).max() < tol: break old_phi = phi else: warnings.warn("phi failed to converge after %d iterations" % max_iter) # L = Phi - (Phi P + P' Phi)/2 return np.diag(phi) - ((phi * P.T).T + P.T * phi)/2
[ "def", "directed_laplacian", "(", "self", ",", "D", "=", "None", ",", "eta", "=", "0.99", ",", "tol", "=", "1e-12", ",", "max_iter", "=", "500", ")", ":", "W", "=", "self", ".", "matrix", "(", "'dense'", ")", "n", "=", "W", ".", "shape", "[", "...
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
[ "Computes", "the", "directed", "combinatorial", "graph", "laplacian", ".", "http", ":", "//", "www", "-", "all", ".", "cs", ".", "umass", ".", "edu", "/", "pubs", "/", "2007", "/", "johns_m_ICML07", ".", "pdf" ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/analysis.py#L61-L88
all-umass/graphs
graphs/mixins/analysis.py
AnalysisMixin.bandwidth
def bandwidth(self): """Computes the 'bandwidth' of a graph.""" return np.abs(np.diff(self.pairs(), axis=1)).max()
python
def bandwidth(self): """Computes the 'bandwidth' of a graph.""" return np.abs(np.diff(self.pairs(), axis=1)).max()
[ "def", "bandwidth", "(", "self", ")", ":", "return", "np", ".", "abs", "(", "np", ".", "diff", "(", "self", ".", "pairs", "(", ")", ",", "axis", "=", "1", ")", ")", ".", "max", "(", ")" ]
Computes the 'bandwidth' of a graph.
[ "Computes", "the", "bandwidth", "of", "a", "graph", "." ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/analysis.py#L90-L92
all-umass/graphs
graphs/mixins/analysis.py
AnalysisMixin.profile
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()
python
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", "profile", "(", "self", ")", ":", "leftmost_idx", "=", "np", ".", "argmax", "(", "self", ".", "matrix", "(", "'dense'", ")", ".", "astype", "(", "bool", ")", ",", "axis", "=", "0", ")", "return", "(", "np", ".", "arange", "(", "self", ".",...
Measure of bandedness, also known as 'envelope size'.
[ "Measure", "of", "bandedness", "also", "known", "as", "envelope", "size", "." ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/analysis.py#L94-L97
all-umass/graphs
graphs/mixins/analysis.py
AnalysisMixin.betweenness
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 argument: ' + kind weighted = weighted is not False and self.is_weighted() directed = directed if directed is not None else self.is_directed() adj = self.matrix('csr') btw = betweenness(adj, weighted, kind=='vertex') # normalize if undirected if not directed: btw /= 2. return btw
python
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 argument: ' + kind weighted = weighted is not False and self.is_weighted() directed = directed if directed is not None else self.is_directed() adj = self.matrix('csr') btw = betweenness(adj, weighted, kind=='vertex') # normalize if undirected if not directed: btw /= 2. return btw
[ "def", "betweenness", "(", "self", ",", "kind", "=", "'vertex'", ",", "directed", "=", "None", ",", "weighted", "=", "None", ")", ":", "assert", "kind", "in", "(", "'vertex'", ",", "'edge'", ")", ",", "'Invalid kind argument: '", "+", "kind", "weighted", ...
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()
[ "Computes", "the", "betweenness", "centrality", "of", "a", "graph", ".", "kind", ":", "string", "either", "vertex", "(", "default", ")", "or", "edge", "directed", ":", "bool", "defaults", "to", "self", ".", "is_directed", "()", "weighted", ":", "bool", "de...
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/analysis.py#L99-L113
all-umass/graphs
graphs/mixins/analysis.py
AnalysisMixin.eccentricity
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)
python
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", "eccentricity", "(", "self", ",", "directed", "=", "None", ",", "weighted", "=", "None", ")", ":", "sp", "=", "self", ".", "shortest_path", "(", "directed", "=", "directed", ",", "weighted", "=", "weighted", ")", "return", "sp", ".", "max", "(",...
Maximum distance from each vertex to any other vertex.
[ "Maximum", "distance", "from", "each", "vertex", "to", "any", "other", "vertex", "." ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/analysis.py#L115-L118
all-umass/graphs
graphs/mixins/label.py
LabelMixin.color_greedy
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
python
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", "color_greedy", "(", "self", ")", ":", "n", "=", "self", ".", "num_vertices", "(", ")", "coloring", "=", "np", ".", "zeros", "(", "n", ",", "dtype", "=", "int", ")", "for", "i", ",", "nbrs", "in", "enumerate", "(", "self", ".", "adj_list", ...
Returns a greedy vertex coloring as an array of ints.
[ "Returns", "a", "greedy", "vertex", "coloring", "as", "an", "array", "of", "ints", "." ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/label.py#L15-L25
all-umass/graphs
graphs/mixins/label.py
LabelMixin.bicolor_spectral
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 = vecs[:,0].real return vec > 0 if vec[0] > 0 else vec < 0
python
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 = vecs[:,0].real return vec > 0 if vec[0] > 0 else vec < 0
[ "def", "bicolor_spectral", "(", "self", ")", ":", "lap", "=", "self", ".", "laplacian", "(", ")", ".", "astype", "(", "float", ")", "vals", ",", "vecs", "=", "eigs", "(", "lap", ",", "k", "=", "1", ",", "which", "=", "'LM'", ")", "vec", "=", "v...
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.
[ "Returns", "an", "approximate", "2", "-", "coloring", "as", "an", "array", "of", "booleans", "." ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/label.py#L27-L36
all-umass/graphs
graphs/mixins/label.py
LabelMixin.classify_nearest
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 distances from unlabeled vertices D_unlabeled = self.shortest_path(weighted=True)[unlabeled] # set distances to other unlabeled vertices to infinity D_unlabeled[:,unlabeled] = np.inf # find shortest distances to labeled vertices idx = D_unlabeled.argmin(axis=1) # apply the label of the closest vertex labels[unlabeled] = labels[idx] return labels
python
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 distances from unlabeled vertices D_unlabeled = self.shortest_path(weighted=True)[unlabeled] # set distances to other unlabeled vertices to infinity D_unlabeled[:,unlabeled] = np.inf # find shortest distances to labeled vertices idx = D_unlabeled.argmin(axis=1) # apply the label of the closest vertex labels[unlabeled] = labels[idx] return labels
[ "def", "classify_nearest", "(", "self", ",", "partial_labels", ")", ":", "labels", "=", "np", ".", "array", "(", "partial_labels", ",", "copy", "=", "True", ")", "unlabeled", "=", "labels", "==", "-", "1", "# compute geodesic distances from unlabeled vertices", ...
Simple semi-supervised classification, by assigning unlabeled vertices the label of nearest labeled vertex. partial_labels: (n,) array of integer labels, -1 for unlabeled.
[ "Simple", "semi", "-", "supervised", "classification", "by", "assigning", "unlabeled", "vertices", "the", "label", "of", "nearest", "labeled", "vertex", "." ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/label.py#L42-L58
all-umass/graphs
graphs/mixins/label.py
LabelMixin.classify_lgc
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 iterations performed. From "Learning with local and global consistency" by Zhou et al. in 2004. Based on the LabelSpreading implementation in scikit-learn. ''' # compute the gram matrix gram = -self.kernelize(kernel).laplacian(normed=True) if ss.issparse(gram): gram.data[gram.row == gram.col] = 0 else: np.fill_diagonal(gram, 0) # initialize label distributions partial_labels = np.asarray(partial_labels) unlabeled = partial_labels == -1 label_dists, classes = _onehot(partial_labels, mask=~unlabeled) # initialize clamping terms clamp_weights = np.where(unlabeled, alpha, 1)[:,None] y_static = label_dists * min(1 - alpha, 1) # iterate for it in range(max_iter): old_label_dists = 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)]
python
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 iterations performed. From "Learning with local and global consistency" by Zhou et al. in 2004. Based on the LabelSpreading implementation in scikit-learn. ''' # compute the gram matrix gram = -self.kernelize(kernel).laplacian(normed=True) if ss.issparse(gram): gram.data[gram.row == gram.col] = 0 else: np.fill_diagonal(gram, 0) # initialize label distributions partial_labels = np.asarray(partial_labels) unlabeled = partial_labels == -1 label_dists, classes = _onehot(partial_labels, mask=~unlabeled) # initialize clamping terms clamp_weights = np.where(unlabeled, alpha, 1)[:,None] y_static = label_dists * min(1 - alpha, 1) # iterate for it in range(max_iter): old_label_dists = 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_lgc", "(", "self", ",", "partial_labels", ",", "kernel", "=", "'rbf'", ",", "alpha", "=", "0.2", ",", "tol", "=", "1e-3", ",", "max_iter", "=", "30", ")", ":", "# compute the gram matrix", "gram", "=", "-", "self", ".", "kernelize", "(",...
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 iterations performed. From "Learning with local and global consistency" by Zhou et al. in 2004. Based on the LabelSpreading implementation in scikit-learn.
[ "Iterative", "label", "spreading", "for", "semi", "-", "supervised", "classification", "." ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/label.py#L60-L103
all-umass/graphs
graphs/mixins/label.py
LabelMixin.classify_harmonic
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" by Zhu, Ghahramani, and Lafferty in 2003. Based on the matlab code at: http://pages.cs.wisc.edu/~jerryzhu/pub/harmonic_function.m ''' # prepare labels labels = np.array(partial_labels, copy=True) unlabeled = labels == -1 # convert known labels to one-hot encoding fl, classes = _onehot(labels[~unlabeled]) L = self.laplacian(normed=False) if ss.issparse(L): L = L.tocsr()[unlabeled].toarray() else: L = L[unlabeled] Lul = L[:,~unlabeled] Luu = L[:,unlabeled] fu = -np.linalg.solve(Luu, Lul.dot(fl)) if use_CMN: scale = (1 + fl.sum(axis=0)) / fu.sum(axis=0) fu *= scale # assign new labels labels[unlabeled] = classes[fu.argmax(axis=1)] return labels
python
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" by Zhu, Ghahramani, and Lafferty in 2003. Based on the matlab code at: http://pages.cs.wisc.edu/~jerryzhu/pub/harmonic_function.m ''' # prepare labels labels = np.array(partial_labels, copy=True) unlabeled = labels == -1 # convert known labels to one-hot encoding fl, classes = _onehot(labels[~unlabeled]) L = self.laplacian(normed=False) if ss.issparse(L): L = L.tocsr()[unlabeled].toarray() else: L = L[unlabeled] Lul = L[:,~unlabeled] Luu = L[:,unlabeled] fu = -np.linalg.solve(Luu, Lul.dot(fl)) if use_CMN: scale = (1 + fl.sum(axis=0)) / fu.sum(axis=0) fu *= scale # assign new labels labels[unlabeled] = classes[fu.argmax(axis=1)] return labels
[ "def", "classify_harmonic", "(", "self", ",", "partial_labels", ",", "use_CMN", "=", "True", ")", ":", "# prepare labels", "labels", "=", "np", ".", "array", "(", "partial_labels", ",", "copy", "=", "True", ")", "unlabeled", "=", "labels", "==", "-", "1", ...
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" by Zhu, Ghahramani, and Lafferty in 2003. Based on the matlab code at: http://pages.cs.wisc.edu/~jerryzhu/pub/harmonic_function.m
[ "Harmonic", "function", "method", "for", "semi", "-", "supervised", "classification", "also", "known", "as", "the", "Gaussian", "Mean", "Fields", "algorithm", "." ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/label.py#L115-L151
all-umass/graphs
graphs/mixins/label.py
LabelMixin.regression
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, unlike the paper's algorithm. To allow provided y values to change, use a (small) smoothness_penalty. ''' n = self.num_vertices() # input validation for y y = np.array(y, copy=True) ravel_f = False if y.ndim == 1: y = y[:,None] ravel_f = True if y.ndim != 2 or y.size == 0: raise ValueError('Invalid shape of y array: %s' % (y.shape,)) k, d = y.shape # input validation for y_mask if not hasattr(y_mask, 'dtype') or y_mask.dtype != 'bool': tmp = np.zeros(n, dtype=bool) 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 unlabeled_mask = ~y_mask S_23 = S[unlabeled_mask, :] S_3 = S_23[:, unlabeled_mask] rhs = S_23[:, y_mask].dot(y) if ss.issparse(S): f_unlabeled = ss.linalg.spsolve(S_3, rhs) if f_unlabeled.ndim == 1: f_unlabeled = f_unlabeled[:,None] else: f_unlabeled = sl.solve(S_3, rhs, sym_pos=True, overwrite_a=True, overwrite_b=True) f = np.zeros((n, d)) f[y_mask] = y f[unlabeled_mask] = -f_unlabeled else: # see Algorithm 1: Tikhonov Regularization in the paper y_hat = np.zeros((n, d)) y_hat[y_mask] = y I = y_mask.astype(float) # only one label per vertex lhs = k * smoothness_penalty * S if ss.issparse(lhs): lhs.setdiag(lhs.diagonal() + 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
python
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, unlike the paper's algorithm. To allow provided y values to change, use a (small) smoothness_penalty. ''' n = self.num_vertices() # input validation for y y = np.array(y, copy=True) ravel_f = False if y.ndim == 1: y = y[:,None] ravel_f = True if y.ndim != 2 or y.size == 0: raise ValueError('Invalid shape of y array: %s' % (y.shape,)) k, d = y.shape # input validation for y_mask if not hasattr(y_mask, 'dtype') or y_mask.dtype != 'bool': tmp = np.zeros(n, dtype=bool) 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 unlabeled_mask = ~y_mask S_23 = S[unlabeled_mask, :] S_3 = S_23[:, unlabeled_mask] rhs = S_23[:, y_mask].dot(y) if ss.issparse(S): f_unlabeled = ss.linalg.spsolve(S_3, rhs) if f_unlabeled.ndim == 1: f_unlabeled = f_unlabeled[:,None] else: f_unlabeled = sl.solve(S_3, rhs, sym_pos=True, overwrite_a=True, overwrite_b=True) f = np.zeros((n, d)) f[y_mask] = y f[unlabeled_mask] = -f_unlabeled else: # see Algorithm 1: Tikhonov Regularization in the paper y_hat = np.zeros((n, d)) y_hat[y_mask] = y I = y_mask.astype(float) # only one label per vertex lhs = k * smoothness_penalty * S if ss.issparse(lhs): lhs.setdiag(lhs.diagonal() + 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", "regression", "(", "self", ",", "y", ",", "y_mask", ",", "smoothness_penalty", "=", "0", ",", "kernel", "=", "'rbf'", ")", ":", "n", "=", "self", ".", "num_vertices", "(", ")", "# input validation for y", "y", "=", "np", ".", "array", "(", "y", ...
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, unlike the paper's algorithm. To allow provided y values to change, use a (small) smoothness_penalty.
[ "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" ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/label.py#L153-L224
jbloomlab/phydms
phydmslib/models.py
_checkParam
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 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 {1}, not {2}".format( param, paramtype, type(param))) if value.shape != paramshape: raise ValueError("{0} must have shape {1}, not {2}".format( param, paramshape, value.shape)) if value.dtype != 'float': raise ValueError("{0} must have dtype float, not {1}".format( param, value.dtype)) if not ((lowlim <= value).all() and (value <= highlim).all()): raise ValueError("{0} must be >= {1} and <= {2}, not {3}".format( param, lowlim, highlim, value)) 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))
python
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 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 {1}, not {2}".format( param, paramtype, type(param))) if value.shape != paramshape: raise ValueError("{0} must have shape {1}, not {2}".format( param, paramshape, value.shape)) if value.dtype != 'float': raise ValueError("{0} must have dtype float, not {1}".format( param, value.dtype)) if not ((lowlim <= value).all() and (value <= highlim).all()): raise ValueError("{0} must be >= {1} and <= {2}, not {3}".format( param, lowlim, highlim, value)) 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", "_checkParam", "(", "param", ",", "value", ",", "paramlimits", ",", "paramtypes", ")", ":", "assert", "param", "in", "paramlimits", ",", "\"Invalid param: {0}\"", ".", "format", "(", "param", ")", "(", "lowlim", ",", "highlim", ")", "=", "paramlimits"...
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`.
[ "Checks", "if", "value", "is", "allowable", "value", "for", "param", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2232-L2264
jbloomlab/phydms
phydmslib/models.py
_fill_diagonals
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)
python
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", "_fill_diagonals", "(", "m", ",", "diag_indices", ")", ":", "assert", "m", ".", "ndim", "==", "3", ",", "\"M must have 3 dimensions\"", "assert", "m", ".", "shape", "[", "1", "]", "==", "m", ".", "shape", "[", "2", "]", ",", "\"M must contain squa...
Fills diagonals of `nsites` matrices in `m` so rows sum to 0.
[ "Fills", "diagonals", "of", "nsites", "matrices", "in", "m", "so", "rows", "sum", "to", "0", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2267-L2273
jbloomlab/phydms
phydmslib/models.py
DiscreteGamma
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 distribution. `ncats` (`int` > 1) Number of categories in discretized gamma distribution. Returns: `catmeans` (`scipy.ndarray` of `float`, shape `(ncats,)`) `catmeans[k]` is the mean of category `k` where `0 <= k < ncats`. Check that we get values in Figure 1 of Yang, J Mol Evol, 39:306-314 >>> catmeans = DiscreteGamma(0.5, 0.5, 4) >>> scipy.allclose(catmeans, scipy.array([0.0334, 0.2519, 0.8203, 2.8944]), atol=1e-4) True Make sure we get expected mean of alpha / beta >>> alpha = 0.6 >>> beta = 0.8 >>> ncats = 6 >>> 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 gammainc_lower = 0.0 else: lower = upper gammainc_lower = gammainc_upper if k == ncats - 1: upper = float('inf') gammainc_upper = 1.0 else: upper = scipy.stats.gamma.ppf((k + 1) / float(ncats), alpha, scale=scale) gammainc_upper = scipy.special.gammainc(alpha + 1, upper * beta) catmeans[k] = alpha * ncats * (gammainc_upper - gammainc_lower) / beta assert scipy.allclose(catmeans.sum() / ncats, alpha / beta), ( "catmeans is {0}, mean of catmeans is {1}, expected mean " "alpha / beta = {2} / {3} = {4}").format(catmeans, catmeans.sum() / ncats, alpha, beta, alpha / beta) return catmeans
python
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 distribution. `ncats` (`int` > 1) Number of categories in discretized gamma distribution. Returns: `catmeans` (`scipy.ndarray` of `float`, shape `(ncats,)`) `catmeans[k]` is the mean of category `k` where `0 <= k < ncats`. Check that we get values in Figure 1 of Yang, J Mol Evol, 39:306-314 >>> catmeans = DiscreteGamma(0.5, 0.5, 4) >>> scipy.allclose(catmeans, scipy.array([0.0334, 0.2519, 0.8203, 2.8944]), atol=1e-4) True Make sure we get expected mean of alpha / beta >>> alpha = 0.6 >>> beta = 0.8 >>> ncats = 6 >>> 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 gammainc_lower = 0.0 else: lower = upper gammainc_lower = gammainc_upper if k == ncats - 1: upper = float('inf') gammainc_upper = 1.0 else: upper = scipy.stats.gamma.ppf((k + 1) / float(ncats), alpha, scale=scale) gammainc_upper = scipy.special.gammainc(alpha + 1, upper * beta) catmeans[k] = alpha * ncats * (gammainc_upper - gammainc_lower) / beta assert scipy.allclose(catmeans.sum() / ncats, alpha / beta), ( "catmeans is {0}, mean of catmeans is {1}, expected mean " "alpha / beta = {2} / {3} = {4}").format(catmeans, catmeans.sum() / ncats, alpha, beta, alpha / beta) return catmeans
[ "def", "DiscreteGamma", "(", "alpha", ",", "beta", ",", "ncats", ")", ":", "alpha", "=", "float", "(", "alpha", ")", "beta", "=", "float", "(", "beta", ")", "assert", "alpha", ">", "0", "assert", "beta", ">", "0", "assert", "ncats", ">", "1", "scal...
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 distribution. `ncats` (`int` > 1) Number of categories in discretized gamma distribution. Returns: `catmeans` (`scipy.ndarray` of `float`, shape `(ncats,)`) `catmeans[k]` is the mean of category `k` where `0 <= k < ncats`. Check that we get values in Figure 1 of Yang, J Mol Evol, 39:306-314 >>> catmeans = DiscreteGamma(0.5, 0.5, 4) >>> scipy.allclose(catmeans, scipy.array([0.0334, 0.2519, 0.8203, 2.8944]), atol=1e-4) True Make sure we get expected mean of alpha / beta >>> alpha = 0.6 >>> beta = 0.8 >>> ncats = 6 >>> catmeans = DiscreteGamma(alpha, beta, ncats) >>> scipy.allclose(catmeans.sum() / ncats, alpha / beta) True
[ "Returns", "category", "means", "for", "discretized", "gamma", "distribution", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2276-L2334
jbloomlab/phydms
phydmslib/models.py
ExpCM.PARAMLIMITS
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}, {1}, is equal to or \ larger than the new maximum value, {2}"\ .format(param, value[param][0], value[param][1]) self._PARAMLIMITS = value.copy()
python
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}, {1}, is equal to or \ larger than the new maximum value, {2}"\ .format(param, value[param][0], value[param][1]) self._PARAMLIMITS = value.copy()
[ "def", "PARAMLIMITS", "(", "self", ",", "value", ")", ":", "assert", "set", "(", "value", ".", "keys", "(", ")", ")", "==", "set", "(", "self", ".", "PARAMLIMITS", ".", "keys", "(", ")", ")", ",", "\"The \\\n new parameter limits are not defin...
Set new `PARAMLIMITS` dictionary.
[ "Set", "new", "PARAMLIMITS", "dictionary", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L319-L329
jbloomlab/phydms
phydmslib/models.py
ExpCM.paramsReport
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(param, INDEX_TO_NT[w])] = pvalue[w] elif isinstance(pvalue, scipy.ndarray) and (pvalue.shape == (self.nsites, N_AA)): for r in range(self.nsites): for a in range(N_AA): report['{0}{1}{2}'.format(param, r + 1, INDEX_TO_AA[a]) ] = pvalue[r][a] else: raise ValueError("Unexpected param: {0}".format(param)) return report
python
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(param, INDEX_TO_NT[w])] = pvalue[w] elif isinstance(pvalue, scipy.ndarray) and (pvalue.shape == (self.nsites, N_AA)): for r in range(self.nsites): for a in range(N_AA): report['{0}{1}{2}'.format(param, r + 1, INDEX_TO_AA[a]) ] = pvalue[r][a] else: raise ValueError("Unexpected param: {0}".format(param)) return report
[ "def", "paramsReport", "(", "self", ")", ":", "report", "=", "{", "}", "for", "param", "in", "self", ".", "_REPORTPARAMS", ":", "pvalue", "=", "getattr", "(", "self", ",", "param", ")", "if", "isinstance", "(", "pvalue", ",", "float", ")", ":", "repo...
See docs for `Model` abstract base class.
[ "See", "docs", "for", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L456-L474
jbloomlab/phydms
phydmslib/models.py
ExpCM.branchScale
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
python
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", "branchScale", "(", "self", ")", ":", "bs", "=", "-", "(", "self", ".", "prx", "*", "scipy", ".", "diagonal", "(", "self", ".", "Prxy", ",", "axis1", "=", "1", ",", "axis2", "=", "2", ")", ")", ".", "sum", "(", ")", "*", "self", ".", ...
See docs for `Model` abstract base class.
[ "See", "docs", "for", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L477-L482
jbloomlab/phydms
phydmslib/models.py
ExpCM.mu
def mu(self, value): """Set new `mu` value.""" _checkParam('mu', value, self.PARAMLIMITS, self.PARAMTYPES) if value != self.mu: self._cached = {} self._mu = value
python
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", "mu", "(", "self", ",", "value", ")", ":", "_checkParam", "(", "'mu'", ",", "value", ",", "self", ".", "PARAMLIMITS", ",", "self", ".", "PARAMTYPES", ")", "if", "value", "!=", "self", ".", "mu", ":", "self", ".", "_cached", "=", "{", "}", ...
Set new `mu` value.
[ "Set", "new", "mu", "value", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L500-L505
jbloomlab/phydms
phydmslib/models.py
ExpCM.updateParams
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 names of changed params for (name, value) in newvalues.items(): _checkParam(name, value, self.PARAMLIMITS, self.PARAMTYPES) if isinstance(value, scipy.ndarray): if (value != getattr(self, name)).any(): changed.add(name) setattr(self, name, value.copy()) else: if value != getattr(self, name): changed.add(name) setattr(self, name, copy.copy(value)) if update_all or changed: self._cached = {} # The order of the updating below is important. # If you change it, you may break either this class # **or** classes that inherit from it. # Note also that not all attributes need to be updated # for all possible parameter changes, but just doing it # this way is 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()
python
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 names of changed params for (name, value) in newvalues.items(): _checkParam(name, value, self.PARAMLIMITS, self.PARAMTYPES) if isinstance(value, scipy.ndarray): if (value != getattr(self, name)).any(): changed.add(name) setattr(self, name, value.copy()) else: if value != getattr(self, name): changed.add(name) setattr(self, name, copy.copy(value)) if update_all or changed: self._cached = {} # The order of the updating below is important. # If you change it, you may break either this class # **or** classes that inherit from it. # Note also that not all attributes need to be updated # for all possible parameter changes, but just doing it # this way is 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", "updateParams", "(", "self", ",", "newvalues", ",", "update_all", "=", "False", ")", ":", "assert", "all", "(", "map", "(", "lambda", "x", ":", "x", "in", "self", ".", "freeparams", ",", "newvalues", ".", "keys", "(", ")", ")", ")", ",", "\"...
See docs for `Model` abstract base class.
[ "See", "docs", "for", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L507-L543
jbloomlab/phydms
phydmslib/models.py
ExpCM.M
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 * t) expD = self._cached[('expD', t)] if tips is None: # swap axes to broadcast multiply D as diagonal matrix M = broadcastMatrixMultiply((self.A.swapaxes(0, 1) * expD).swapaxes(1, 0), self.Ainv) else: M = broadcastMatrixVectorMultiply((self.A.swapaxes(0, 1) * expD).swapaxes(1, 0), broadcastGetCols( self.Ainv, tips)) if gaps is not None: M[gaps] = scipy.ones(N_CODON, dtype='float') #if M.min() < -0.01: # warnings.warn("Large negative value in M(t) being set to 0. " # "Value is {0}, t is {1}".format(M.min(), t)) M[M < 0] = 0.0 return M
python
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 * t) expD = self._cached[('expD', t)] if tips is None: # swap axes to broadcast multiply D as diagonal matrix M = broadcastMatrixMultiply((self.A.swapaxes(0, 1) * expD).swapaxes(1, 0), self.Ainv) else: M = broadcastMatrixVectorMultiply((self.A.swapaxes(0, 1) * expD).swapaxes(1, 0), broadcastGetCols( self.Ainv, tips)) if gaps is not None: M[gaps] = scipy.ones(N_CODON, dtype='float') #if M.min() < -0.01: # warnings.warn("Large negative value in M(t) being set to 0. " # "Value is {0}, t is {1}".format(M.min(), t)) M[M < 0] = 0.0 return M
[ "def", "M", "(", "self", ",", "t", ",", "tips", "=", "None", ",", "gaps", "=", "None", ")", ":", "assert", "isinstance", "(", "t", ",", "float", ")", "and", "t", ">", "0", ",", "\"Invalid t: {0}\"", ".", "format", "(", "t", ")", "with", "scipy", ...
See docs for method in `Model` abstract base class.
[ "See", "docs", "for", "method", "in", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L545-L566
jbloomlab/phydms
phydmslib/models.py
ExpCM.dM
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 (param == 'mu') or (param == 't'): if param == 'mu': alpha = t else: alpha = self.mu if tips is None: dM_param = broadcastMatrixMultiply(self.Prxy, Mt, alpha=alpha) else: dM_param = broadcastMatrixVectorMultiply(self.Prxy, Mt, alpha=alpha) if gaps is not None: dM_param[gaps] = scipy.zeros(N_CODON, dtype='float') return dM_param paramval = getattr(self, param) if isinstance(paramval, float): paramisvec = False else: assert isinstance(paramval, numpy.ndarray) and paramval.ndim == 1 paramisvec = True paramlength = paramval.shape[0] if ('expD', t) not in self._cached: self._cached[('expD', 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( 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'] if 'Dxx_Dyy_lt_ALMOST_ZERO' not in self._cached: self._cached['Dxx_Dyy_lt_ALMOST_ZERO'] = scipy.fabs( Dxx_Dyy) < ALMOST_ZERO Dxx_Dyy_lt_ALMOST_ZERO = self._cached['Dxx_Dyy_lt_ALMOST_ZERO'] with scipy.errstate(divide='raise', under='ignore', over='raise', invalid='ignore'): expDyy = scipy.tile(expD,(1, N_CODON)).reshape( self.nsites, N_CODON, N_CODON) expDxx = scipy.array([expDyy[r].transpose() for r in range(self.nsites)]) V = (expDxx - expDyy) / Dxx_Dyy with scipy.errstate(under='ignore'): # OK if some values 0 scipy.copyto(V, self.mu * t * expDxx, where= Dxx_Dyy_lt_ALMOST_ZERO) self._cached[('V', t)] = V V = self._cached[('V', t)] with scipy.errstate(under='ignore'): # don't worry if some values 0 if tips is None: if not paramisvec: dM_param = broadcastMatrixMultiply(self.A, broadcastMatrixMultiply(self.B[param] * V, self.Ainv)) else: 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(broadcastMatrixMultiply( self.B[param] * V, self.Ainv), tips)) else: dM_param = scipy.ndarray((paramlength, self.nsites, N_CODON), dtype='float') for j in range(paramlength): dM_param[j] = broadcastMatrixVectorMultiply(self.A, broadcastGetCols(broadcastMatrixMultiply( self.B[param][j] * V, self.Ainv), tips)) if gaps is not None: if not paramisvec: dM_param[gaps] = scipy.zeros(N_CODON, dtype='float') else: dM_param[:, gaps] = scipy.zeros(N_CODON, dtype='float') return dM_param
python
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 (param == 'mu') or (param == 't'): if param == 'mu': alpha = t else: alpha = self.mu if tips is None: dM_param = broadcastMatrixMultiply(self.Prxy, Mt, alpha=alpha) else: dM_param = broadcastMatrixVectorMultiply(self.Prxy, Mt, alpha=alpha) if gaps is not None: dM_param[gaps] = scipy.zeros(N_CODON, dtype='float') return dM_param paramval = getattr(self, param) if isinstance(paramval, float): paramisvec = False else: assert isinstance(paramval, numpy.ndarray) and paramval.ndim == 1 paramisvec = True paramlength = paramval.shape[0] if ('expD', t) not in self._cached: self._cached[('expD', 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( 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'] if 'Dxx_Dyy_lt_ALMOST_ZERO' not in self._cached: self._cached['Dxx_Dyy_lt_ALMOST_ZERO'] = scipy.fabs( Dxx_Dyy) < ALMOST_ZERO Dxx_Dyy_lt_ALMOST_ZERO = self._cached['Dxx_Dyy_lt_ALMOST_ZERO'] with scipy.errstate(divide='raise', under='ignore', over='raise', invalid='ignore'): expDyy = scipy.tile(expD,(1, N_CODON)).reshape( self.nsites, N_CODON, N_CODON) expDxx = scipy.array([expDyy[r].transpose() for r in range(self.nsites)]) V = (expDxx - expDyy) / Dxx_Dyy with scipy.errstate(under='ignore'): # OK if some values 0 scipy.copyto(V, self.mu * t * expDxx, where= Dxx_Dyy_lt_ALMOST_ZERO) self._cached[('V', t)] = V V = self._cached[('V', t)] with scipy.errstate(under='ignore'): # don't worry if some values 0 if tips is None: if not paramisvec: dM_param = broadcastMatrixMultiply(self.A, broadcastMatrixMultiply(self.B[param] * V, self.Ainv)) else: 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(broadcastMatrixMultiply( self.B[param] * V, self.Ainv), tips)) else: dM_param = scipy.ndarray((paramlength, self.nsites, N_CODON), dtype='float') for j in range(paramlength): dM_param[j] = broadcastMatrixVectorMultiply(self.A, broadcastGetCols(broadcastMatrixMultiply( self.B[param][j] * V, self.Ainv), tips)) if gaps is not None: if not paramisvec: dM_param[gaps] = scipy.zeros(N_CODON, dtype='float') else: dM_param[:, gaps] = scipy.zeros(N_CODON, dtype='float') return dM_param
[ "def", "dM", "(", "self", ",", "t", ",", "param", ",", "Mt", ",", "tips", "=", "None", ",", "gaps", "=", "None", ")", ":", "assert", "isinstance", "(", "t", ",", "float", ")", "and", "t", ">", "0", ",", "\"Invalid t: {0}\"", ".", "format", "(", ...
See docs for method in `Model` abstract base class.
[ "See", "docs", "for", "method", "in", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L568-L657
jbloomlab/phydms
phydmslib/models.py
ExpCM._eta_from_phi
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)
python
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", "_eta_from_phi", "(", "self", ")", ":", "self", ".", "eta", "=", "scipy", ".", "ndarray", "(", "N_NT", "-", "1", ",", "dtype", "=", "'float'", ")", "etaprod", "=", "1.0", "for", "w", "in", "range", "(", "N_NT", "-", "1", ")", ":", "self", ...
Update `eta` using current `phi`.
[ "Update", "eta", "using", "current", "phi", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L659-L666
jbloomlab/phydms
phydmslib/models.py
ExpCM._update_phi
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
python
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_phi", "(", "self", ")", ":", "etaprod", "=", "1.0", "for", "w", "in", "range", "(", "N_NT", "-", "1", ")", ":", "self", ".", "phi", "[", "w", "]", "=", "etaprod", "*", "(", "1", "-", "self", ".", "eta", "[", "w", "]", ")", "...
Update `phi` using current `eta`.
[ "Update", "phi", "using", "current", "eta", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L668-L674
jbloomlab/phydms
phydmslib/models.py
ExpCM._update_Qxy
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
python
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_Qxy", "(", "self", ")", ":", "for", "w", "in", "range", "(", "N_NT", ")", ":", "scipy", ".", "copyto", "(", "self", ".", "Qxy", ",", "self", ".", "phi", "[", "w", "]", ",", "where", "=", "CODON_NT_MUT", "[", "w", "]", ")", "self...
Update `Qxy` using current `kappa` and `phi`.
[ "Update", "Qxy", "using", "current", "kappa", "and", "phi", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L676-L680
jbloomlab/phydms
phydmslib/models.py
ExpCM._update_pi_vars
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_codon[r] = self.pi[r][CODON_TO_AA] pim = scipy.tile(self.pi_codon[r], (N_CODON, 1)) # [x][y] is piAy self.piAx_piAy[r] = pim.transpose() / pim self.ln_pi_codon = scipy.log(self.pi_codon) self.piAx_piAy_beta = self.piAx_piAy**self.beta self.ln_piAx_piAy_beta = scipy.log(self.piAx_piAy_beta)
python
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_codon[r] = self.pi[r][CODON_TO_AA] pim = scipy.tile(self.pi_codon[r], (N_CODON, 1)) # [x][y] is piAy self.piAx_piAy[r] = pim.transpose() / pim self.ln_pi_codon = scipy.log(self.pi_codon) self.piAx_piAy_beta = self.piAx_piAy**self.beta self.ln_piAx_piAy_beta = scipy.log(self.piAx_piAy_beta)
[ "def", "_update_pi_vars", "(", "self", ")", ":", "with", "scipy", ".", "errstate", "(", "divide", "=", "'raise'", ",", "under", "=", "'raise'", ",", "over", "=", "'raise'", ",", "invalid", "=", "'raise'", ")", ":", "for", "r", "in", "range", "(", "se...
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`.
[ "Update", "variables", "that", "depend", "on", "pi", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L682-L697
jbloomlab/phydms
phydmslib/models.py
ExpCM._update_Frxy
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_beta), where=scipy.logical_and( CODON_NONSYN, scipy.fabs(1 - self.piAx_piAy_beta) > ALMOST_ZERO)) scipy.copyto(self.Frxy, self.Frxy_no_omega * self.omega, where=CODON_NONSYN)
python
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_beta), where=scipy.logical_and( CODON_NONSYN, scipy.fabs(1 - self.piAx_piAy_beta) > ALMOST_ZERO)) scipy.copyto(self.Frxy, self.Frxy_no_omega * self.omega, where=CODON_NONSYN)
[ "def", "_update_Frxy", "(", "self", ")", ":", "self", ".", "Frxy", ".", "fill", "(", "1.0", ")", "self", ".", "Frxy_no_omega", ".", "fill", "(", "1.0", ")", "with", "scipy", ".", "errstate", "(", "divide", "=", "'raise'", ",", "under", "=", "'raise'"...
Update `Frxy` from `piAx_piAy_beta`, `ln_piAx_piAy_beta`, `omega`, `beta`.
[ "Update", "Frxy", "from", "piAx_piAy_beta", "ln_piAx_piAy_beta", "omega", "beta", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L699-L709
jbloomlab/phydms
phydmslib/models.py
ExpCM._update_Prxy
def _update_Prxy(self): """Update `Prxy` using current `Frxy` and `Qxy`.""" self.Prxy = self.Frxy * self.Qxy _fill_diagonals(self.Prxy, self._diag_indices)
python
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", "(", "self", ")", ":", "self", ".", "Prxy", "=", "self", ".", "Frxy", "*", "self", ".", "Qxy", "_fill_diagonals", "(", "self", ".", "Prxy", ",", "self", ".", "_diag_indices", ")" ]
Update `Prxy` using current `Frxy` and `Qxy`.
[ "Update", "Prxy", "using", "current", "Frxy", "and", "Qxy", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L711-L714
jbloomlab/phydms
phydmslib/models.py
ExpCM._update_Prxy_diag
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()).transpose() # assert scipy.allclose(symm_pr, symm_pr.transpose()) (evals, evecs) = scipy.linalg.eigh(symm_pr) # assert scipy.allclose(scipy.linalg.inv(evecs), evecs.transpose()) # assert scipy.allclose(symm_pr, scipy.dot(evecs, scipy.dot(scipy.diag(evals), evecs.transpose()))) self.D[r] = evals self.Ainv[r] = evecs.transpose() * pr_half self.A[r] = (pr_neghalf * evecs.transpose()).transpose()
python
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()).transpose() # assert scipy.allclose(symm_pr, symm_pr.transpose()) (evals, evecs) = scipy.linalg.eigh(symm_pr) # assert scipy.allclose(scipy.linalg.inv(evecs), evecs.transpose()) # assert scipy.allclose(symm_pr, scipy.dot(evecs, scipy.dot(scipy.diag(evals), evecs.transpose()))) self.D[r] = evals self.Ainv[r] = evecs.transpose() * pr_half self.A[r] = (pr_neghalf * evecs.transpose()).transpose()
[ "def", "_update_Prxy_diag", "(", "self", ")", ":", "for", "r", "in", "range", "(", "self", ".", "nsites", ")", ":", "pr_half", "=", "self", ".", "prx", "[", "r", "]", "**", "0.5", "pr_neghalf", "=", "self", ".", "prx", "[", "r", "]", "**", "-", ...
Update `D`, `A`, `Ainv` from `Prxy`, `prx`.
[ "Update", "D", "A", "Ainv", "from", "Prxy", "prx", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L716-L729
jbloomlab/phydms
phydmslib/models.py
ExpCM._update_prx
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='raise'): for r in range(self.nsites): self.prx[r] /= self.prx[r].sum()
python
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='raise'): for r in range(self.nsites): self.prx[r] /= self.prx[r].sum()
[ "def", "_update_prx", "(", "self", ")", ":", "qx", "=", "scipy", ".", "ones", "(", "N_CODON", ",", "dtype", "=", "'float'", ")", "for", "j", "in", "range", "(", "3", ")", ":", "for", "w", "in", "range", "(", "N_NT", ")", ":", "qx", "[", "CODON_...
Update `prx` from `phi`, `pi_codon`, and `beta`.
[ "Update", "prx", "from", "phi", "pi_codon", "and", "beta", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L731-L742
jbloomlab/phydms
phydmslib/models.py
ExpCM._update_dPrxy
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=CODON_NONSYN) _fill_diagonals(self.dPrxy['omega'], self._diag_indices) if 'beta' in self.freeparams: self.dPrxy['beta'].fill(0) with scipy.errstate(divide='raise', under='raise', over='raise', invalid='ignore'): scipy.copyto(self.dPrxy['beta'], self.Prxy * (1 / self.beta + (self.piAx_piAy_beta * (self.ln_piAx_piAy_beta / self.beta) / (1 - self.piAx_piAy_beta))), where=CODON_NONSYN) scipy.copyto(self.dPrxy['beta'], self.Prxy/self.beta * (1 - self.piAx_piAy_beta), where=scipy.logical_and( CODON_NONSYN, scipy.fabs(1 - self.piAx_piAy_beta) < ALMOST_ZERO)) _fill_diagonals(self.dPrxy['beta'], self._diag_indices) if 'eta' in self.freeparams: for i in range(N_NT - 1): for w in range(i, N_NT): scipy.copyto(self.dPrxy['eta'][i], self.Prxy / (self.eta[i] - int(i == w)), where=CODON_NT_MUT[w]) _fill_diagonals(self.dPrxy['eta'][i], self._diag_indices)
python
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=CODON_NONSYN) _fill_diagonals(self.dPrxy['omega'], self._diag_indices) if 'beta' in self.freeparams: self.dPrxy['beta'].fill(0) with scipy.errstate(divide='raise', under='raise', over='raise', invalid='ignore'): scipy.copyto(self.dPrxy['beta'], self.Prxy * (1 / self.beta + (self.piAx_piAy_beta * (self.ln_piAx_piAy_beta / self.beta) / (1 - self.piAx_piAy_beta))), where=CODON_NONSYN) scipy.copyto(self.dPrxy['beta'], self.Prxy/self.beta * (1 - self.piAx_piAy_beta), where=scipy.logical_and( CODON_NONSYN, scipy.fabs(1 - self.piAx_piAy_beta) < ALMOST_ZERO)) _fill_diagonals(self.dPrxy['beta'], self._diag_indices) if 'eta' in self.freeparams: for i in range(N_NT - 1): for w in range(i, N_NT): scipy.copyto(self.dPrxy['eta'][i], self.Prxy / (self.eta[i] - int(i == w)), where=CODON_NT_MUT[w]) _fill_diagonals(self.dPrxy['eta'][i], self._diag_indices)
[ "def", "_update_dPrxy", "(", "self", ")", ":", "if", "'kappa'", "in", "self", ".", "freeparams", ":", "scipy", ".", "copyto", "(", "self", ".", "dPrxy", "[", "'kappa'", "]", ",", "self", ".", "Prxy", "/", "self", ".", "kappa", ",", "where", "=", "C...
Update `dPrxy`.
[ "Update", "dPrxy", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L744-L772
jbloomlab/phydms
phydmslib/models.py
ExpCM._update_B
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 paramval.ndim == 1 for j in range(paramval.shape[0]): self.B[param][j] = broadcastMatrixMultiply(self.Ainv, broadcastMatrixMultiply(self.dPrxy[param][j], self.A))
python
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 paramval.ndim == 1 for j in range(paramval.shape[0]): self.B[param][j] = broadcastMatrixMultiply(self.Ainv, broadcastMatrixMultiply(self.dPrxy[param][j], self.A))
[ "def", "_update_B", "(", "self", ")", ":", "for", "param", "in", "self", ".", "freeparams", ":", "if", "param", "==", "'mu'", ":", "continue", "paramval", "=", "getattr", "(", "self", ",", "param", ")", "if", "isinstance", "(", "paramval", ",", "float"...
Update `B`.
[ "Update", "B", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L774-L788
jbloomlab/phydms
phydmslib/models.py
ExpCM._update_dprx
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', under='raise', over='raise', invalid='raise'): for i in range(N_NT - 1): boolterm.fill(0) for j in range(3): boolterm += ((i <= CODON_NT_INDEX[j]).astype('float') / (self.eta[i] - (i == CODON_NT_INDEX[j]).astype( 'float'))) for r in range(self.nsites): self.dprx['eta'][i][r] = self.prx[r] * (boolterm - scipy.dot(boolterm, self.prx[r]) / self.prx[r].sum())
python
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', under='raise', over='raise', invalid='raise'): for i in range(N_NT - 1): boolterm.fill(0) for j in range(3): boolterm += ((i <= CODON_NT_INDEX[j]).astype('float') / (self.eta[i] - (i == CODON_NT_INDEX[j]).astype( 'float'))) for r in range(self.nsites): self.dprx['eta'][i][r] = self.prx[r] * (boolterm - scipy.dot(boolterm, self.prx[r]) / self.prx[r].sum())
[ "def", "_update_dprx", "(", "self", ")", ":", "if", "'beta'", "in", "self", ".", "freeparams", ":", "for", "r", "in", "range", "(", "self", ".", "nsites", ")", ":", "self", ".", "dprx", "[", "'beta'", "]", "[", "r", "]", "=", "self", ".", "prx", ...
Update `dprx`.
[ "Update", "dprx", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L790-L808
jbloomlab/phydms
phydmslib/models.py
ExpCM._fill_diagonals
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)
python
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", "_fill_diagonals", "(", "self", ",", "m", ")", ":", "assert", "m", ".", "shape", "==", "(", "self", ".", "nsites", ",", "N_CODON", ",", "N_CODON", ")", "for", "r", "in", "range", "(", "self", ".", "nsites", ")", ":", "scipy", ".", "fill_diag...
Fills diagonals of `nsites` matrices in `m` so rows sum to 0.
[ "Fills", "diagonals", "of", "nsites", "matrices", "in", "m", "so", "rows", "sum", "to", "0", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L810-L815
jbloomlab/phydms
phydmslib/models.py
ExpCM.spielman_wr
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 <https://doi.org/10.1093/molbev/msv003>`_, we can predict the `dN/dS` value for each site `r`, :math:`\\rm{spielman}\\omega_r`, from the `ExpCM`. When `norm` is `False`, the `omega_r` values are defined as :math:`\\rm{spielman}\\omega_r = \\frac{\\sum_x \\sum_{y \\in N_x}p_{r,x}\ P_{r,xy}}{\\sum_x \\sum_{y \\in Nx}p_{r,x}Q_{xy}}`, where `r,x,y`, :math:`p_{r,x}`, :math:`P_{r,xy}`, and :math:`Q_{x,y}` have the same definitions as in the main `ExpCM` doc string and :math:`N_{x}` is the set of codons which are non-synonymous to codon `x` and differ from `x` by one nucleotide. When `norm` is `True`, the `omega_r` values above are divided by the 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][j].sum() num += (p_i * P_xy) den += (p_i * Q_xy) result = num/den wr.append(result) return wr
python
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 <https://doi.org/10.1093/molbev/msv003>`_, we can predict the `dN/dS` value for each site `r`, :math:`\\rm{spielman}\\omega_r`, from the `ExpCM`. When `norm` is `False`, the `omega_r` values are defined as :math:`\\rm{spielman}\\omega_r = \\frac{\\sum_x \\sum_{y \\in N_x}p_{r,x}\ P_{r,xy}}{\\sum_x \\sum_{y \\in Nx}p_{r,x}Q_{xy}}`, where `r,x,y`, :math:`p_{r,x}`, :math:`P_{r,xy}`, and :math:`Q_{x,y}` have the same definitions as in the main `ExpCM` doc string and :math:`N_{x}` is the set of codons which are non-synonymous to codon `x` and differ from `x` by one nucleotide. When `norm` is `True`, the `omega_r` values above are divided by the 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][j].sum() num += (p_i * P_xy) den += (p_i * Q_xy) result = num/den wr.append(result) return wr
[ "def", "spielman_wr", "(", "self", ",", "norm", "=", "True", ")", ":", "wr", "=", "[", "]", "for", "r", "in", "range", "(", "self", ".", "nsites", ")", ":", "num", "=", "0", "den", "=", "0", "for", "i", "in", "range", "(", "N_CODON", ")", ":"...
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 <https://doi.org/10.1093/molbev/msv003>`_, we can predict the `dN/dS` value for each site `r`, :math:`\\rm{spielman}\\omega_r`, from the `ExpCM`. When `norm` is `False`, the `omega_r` values are defined as :math:`\\rm{spielman}\\omega_r = \\frac{\\sum_x \\sum_{y \\in N_x}p_{r,x}\ P_{r,xy}}{\\sum_x \\sum_{y \\in Nx}p_{r,x}Q_{xy}}`, where `r,x,y`, :math:`p_{r,x}`, :math:`P_{r,xy}`, and :math:`Q_{x,y}` have the same definitions as in the main `ExpCM` doc string and :math:`N_{x}` is the set of codons which are non-synonymous to codon `x` and differ from `x` by one nucleotide. When `norm` is `True`, the `omega_r` values above are divided by the ExpCM `omega` value.
[ "Returns", "a", "list", "of", "site", "-", "specific", "omega", "values", "calculated", "from", "the", "ExpCM", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L818-L862
jbloomlab/phydms
phydmslib/models.py
ExpCM_fitprefs.dlogprior
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]
python
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", "dlogprior", "(", "self", ",", "param", ")", ":", "assert", "param", "in", "self", ".", "freeparams", ",", "\"Invalid param: {0}\"", ".", "format", "(", "param", ")", "return", "self", ".", "_dlogprior", "[", "param", "]" ]
Value of derivative of prior depends on value of `prior`.
[ "Value", "of", "derivative", "of", "prior", "depends", "on", "value", "of", "prior", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L984-L987
jbloomlab/phydms
phydmslib/models.py
ExpCM_fitprefs._update_pi_vars
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 `origbeta`.""" minpi = self.PARAMLIMITS['pi'][0] if not hasattr(self, 'zeta'): # should only execute on first call to initialize zeta assert not hasattr(self, 'origpi') self.origpi = self.pi**self._origbeta for r in range(self.nsites): self.origpi[r] /= self.origpi[r].sum() self.origpi[r][self.origpi[r] < 2 * minpi] = 2 * minpi self.origpi[r] /= self.origpi[r].sum() self.pi = self.origpi.copy() self.zeta = scipy.ndarray(self.nsites * (N_AA - 1), dtype='float') self.tildeFrxy = scipy.zeros((self.nsites, N_CODON, N_CODON), dtype='float') for r in range(self.nsites): zetaprod = 1.0 for i in range(N_AA - 1): zetari = 1.0 - self.pi[r][i] / zetaprod self.zeta.reshape(self.nsites, N_AA - 1)[r][i] = 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 for i in range(N_AA - 1): zetari = self.zeta.reshape(self.nsites, N_AA - 1)[r][i] self.pi[r][i] = zetaprod * (1 - zetari) zetaprod *= zetari self.pi[r][N_AA - 1] = zetaprod self.pi[r][self.pi[r] < minpi] = minpi self.pi[r] /= self.pi[r].sum() super(ExpCM_fitprefs, self)._update_pi_vars() with scipy.errstate(divide='raise', under='raise', over='raise', invalid='ignore'): scipy.copyto(self.tildeFrxy, self.omega * self.beta * (self.piAx_piAy_beta * (self.ln_piAx_piAy_beta - 1) + 1) / (1 - self.piAx_piAy_beta)**2, where=CODON_NONSYN) scipy.copyto(self.tildeFrxy, self.omega * self.beta / 2.0, where=scipy.logical_and(CODON_NONSYN, scipy.fabs(1 - self.piAx_piAy_beta) < ALMOST_ZERO)) self._logprior = 0.0 self._dlogprior = dict([(param, 0.0) for param in self.freeparams]) if self.prior is None: pass elif 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 * scipy.log(1 + c1 * pidiffr**2).sum() self._logprior += rlogprior for i in range(N_AA - 1): zetari = self.zeta[j] self._dlogprior['zeta'][j] = -2 * c1 * c2 * ( pidiffr[i : ] / (1 + c1 * pidiffr[i : ]**2) * self.pi[r][i : ] / (zetari - (aaindex == i).astype( 'float')[i : ])).sum() j += 1 else: raise ValueError("Invalid prior: {0}".format(self.prior))
python
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 `origbeta`.""" minpi = self.PARAMLIMITS['pi'][0] if not hasattr(self, 'zeta'): # should only execute on first call to initialize zeta assert not hasattr(self, 'origpi') self.origpi = self.pi**self._origbeta for r in range(self.nsites): self.origpi[r] /= self.origpi[r].sum() self.origpi[r][self.origpi[r] < 2 * minpi] = 2 * minpi self.origpi[r] /= self.origpi[r].sum() self.pi = self.origpi.copy() self.zeta = scipy.ndarray(self.nsites * (N_AA - 1), dtype='float') self.tildeFrxy = scipy.zeros((self.nsites, N_CODON, N_CODON), dtype='float') for r in range(self.nsites): zetaprod = 1.0 for i in range(N_AA - 1): zetari = 1.0 - self.pi[r][i] / zetaprod self.zeta.reshape(self.nsites, N_AA - 1)[r][i] = 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 for i in range(N_AA - 1): zetari = self.zeta.reshape(self.nsites, N_AA - 1)[r][i] self.pi[r][i] = zetaprod * (1 - zetari) zetaprod *= zetari self.pi[r][N_AA - 1] = zetaprod self.pi[r][self.pi[r] < minpi] = minpi self.pi[r] /= self.pi[r].sum() super(ExpCM_fitprefs, self)._update_pi_vars() with scipy.errstate(divide='raise', under='raise', over='raise', invalid='ignore'): scipy.copyto(self.tildeFrxy, self.omega * self.beta * (self.piAx_piAy_beta * (self.ln_piAx_piAy_beta - 1) + 1) / (1 - self.piAx_piAy_beta)**2, where=CODON_NONSYN) scipy.copyto(self.tildeFrxy, self.omega * self.beta / 2.0, where=scipy.logical_and(CODON_NONSYN, scipy.fabs(1 - self.piAx_piAy_beta) < ALMOST_ZERO)) self._logprior = 0.0 self._dlogprior = dict([(param, 0.0) for param in self.freeparams]) if self.prior is None: pass elif 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 * scipy.log(1 + c1 * pidiffr**2).sum() self._logprior += rlogprior for i in range(N_AA - 1): zetari = self.zeta[j] self._dlogprior['zeta'][j] = -2 * c1 * c2 * ( pidiffr[i : ] / (1 + c1 * pidiffr[i : ]**2) * self.pi[r][i : ] / (zetari - (aaindex == i).astype( 'float')[i : ])).sum() j += 1 else: raise ValueError("Invalid prior: {0}".format(self.prior))
[ "def", "_update_pi_vars", "(", "self", ")", ":", "minpi", "=", "self", ".", "PARAMLIMITS", "[", "'pi'", "]", "[", "0", "]", "if", "not", "hasattr", "(", "self", ",", "'zeta'", ")", ":", "# should only execute on first call to initialize zeta", "assert", "not",...
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 `origbeta`.
[ "Update", "variables", "that", "depend", "on", "pi", "from", "zeta", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L989-L1066
jbloomlab/phydms
phydmslib/models.py
ExpCM_fitprefs._update_dPrxy
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 r in range(self.nsites): for i in range(N_AA - 1): zetari = self.zeta[j] zetaxterm.fill(0) zetayterm.fill(0) zetaxterm[r][self._aa_for_x > i] = -1.0 / zetari zetaxterm[r][self._aa_for_x == i] = -1.0 / (zetari - 1.0) zetayterm[r][self._aa_for_y > i] = 1.0 / zetari zetayterm[r][self._aa_for_y == i] = 1.0 / (zetari - 1.0) self.dPrxy['zeta'][j] = tildeFrxyQxy * (zetayterm + zetaxterm) _fill_diagonals(self.dPrxy['zeta'][j], self._diag_indices) j += 1
python
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 r in range(self.nsites): for i in range(N_AA - 1): zetari = self.zeta[j] zetaxterm.fill(0) zetayterm.fill(0) zetaxterm[r][self._aa_for_x > i] = -1.0 / zetari zetaxterm[r][self._aa_for_x == i] = -1.0 / (zetari - 1.0) zetayterm[r][self._aa_for_y > i] = 1.0 / zetari zetayterm[r][self._aa_for_y == i] = 1.0 / (zetari - 1.0) self.dPrxy['zeta'][j] = tildeFrxyQxy * (zetayterm + zetaxterm) _fill_diagonals(self.dPrxy['zeta'][j], self._diag_indices) j += 1
[ "def", "_update_dPrxy", "(", "self", ")", ":", "super", "(", "ExpCM_fitprefs", ",", "self", ")", ".", "_update_dPrxy", "(", ")", "if", "'zeta'", "in", "self", ".", "freeparams", ":", "tildeFrxyQxy", "=", "self", ".", "tildeFrxy", "*", "self", ".", "Qxy",...
Update `dPrxy`.
[ "Update", "dPrxy", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1068-L1088
jbloomlab/phydms
phydmslib/models.py
ExpCM_fitprefs._update_dprx
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][r] += (delta_aAx - (delta_aAx * self.prx[r]).sum())/ (zetari - int(i == a)) self.dprx['zeta'][j] *= self.prx[r] j += 1
python
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][r] += (delta_aAx - (delta_aAx * self.prx[r]).sum())/ (zetari - int(i == a)) self.dprx['zeta'][j] *= self.prx[r] j += 1
[ "def", "_update_dprx", "(", "self", ")", ":", "super", "(", "ExpCM_fitprefs", ",", "self", ")", ".", "_update_dprx", "(", ")", "j", "=", "0", "if", "'zeta'", "in", "self", ".", "freeparams", ":", "self", ".", "dprx", "[", "'zeta'", "]", ".", "fill", ...
Update `dprx`.
[ "Update", "dprx", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1090-L1104
jbloomlab/phydms
phydmslib/models.py
ExpCM_fitprefs2._update_dPrxy
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] * ( ((i == self._aa_for_y).astype('float') - (i == self._aa_for_x).astype('float')) / zetari) j += 1 for j in range(self.dPrxy['zeta'].shape[0]): _fill_diagonals(self.dPrxy['zeta'][j], self._diag_indices)
python
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] * ( ((i == self._aa_for_y).astype('float') - (i == self._aa_for_x).astype('float')) / zetari) j += 1 for j in range(self.dPrxy['zeta'].shape[0]): _fill_diagonals(self.dPrxy['zeta'][j], self._diag_indices)
[ "def", "_update_dPrxy", "(", "self", ")", ":", "super", "(", "ExpCM_fitprefs", ",", "self", ")", ".", "_update_dPrxy", "(", ")", "if", "'zeta'", "in", "self", ".", "freeparams", ":", "self", ".", "dPrxy", "[", "'zeta'", "]", ".", "fill", "(", "0.0", ...
Update `dPrxy`.
[ "Update", "dPrxy", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1196-L1212
jbloomlab/phydms
phydmslib/models.py
ExpCM_empirical_phi._update_phi
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, dx=dbeta, n=1, order=5) dphi_dbeta_halfdx = scipy.misc.derivative(self._compute_empirical_phi, self.beta, dx=dbeta / 2, n=1, order=5) assert scipy.allclose(self.dphi_dbeta, dphi_dbeta_halfdx, atol=1e-5, rtol=1e-4), ("The numerical derivative dphi_dbeta differs " "considerably in value for step dbeta = {0} and a step " "half that size, giving values of {1} and {2}.").format( dbeta, self.dphi_dbeta, dphi_dbeta_halfdx)
python
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, dx=dbeta, n=1, order=5) dphi_dbeta_halfdx = scipy.misc.derivative(self._compute_empirical_phi, self.beta, dx=dbeta / 2, n=1, order=5) assert scipy.allclose(self.dphi_dbeta, dphi_dbeta_halfdx, atol=1e-5, rtol=1e-4), ("The numerical derivative dphi_dbeta differs " "considerably in value for step dbeta = {0} and a step " "half that size, giving values of {1} and {2}.").format( dbeta, self.dphi_dbeta, dphi_dbeta_halfdx)
[ "def", "_update_phi", "(", "self", ")", ":", "self", ".", "phi", "=", "self", ".", "_compute_empirical_phi", "(", "self", ".", "beta", ")", "_checkParam", "(", "'phi'", ",", "self", ".", "phi", ",", "self", ".", "PARAMLIMITS", ",", "self", ".", "PARAMT...
Compute `phi`, `dphi_dbeta`, and `eta` from `g` and `frxy`.
[ "Compute", "phi", "dphi_dbeta", "and", "eta", "from", "g", "and", "frxy", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1281-L1295
jbloomlab/phydms
phydmslib/models.py
ExpCM_empirical_phi._compute_empirical_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 current `beta` attribute. Initial guess is current value of `phi` attribute.""" def F(phishort): """Difference between `g` and expected `g` given `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_phiprod_codonsum = frx_phiprod.sum(axis=1) gexpect = [] for w in range(N_NT - 1): gexpect.append( ((CODON_NT_COUNT[w] * frx_phiprod).sum(axis=1) / frx_phiprod_codonsum).sum() / (3 * self.nsites)) gexpect = scipy.array(gexpect, dtype='float') return self.g[ : -1] - gexpect frx = self.pi_codon**beta with 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())
python
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 current `beta` attribute. Initial guess is current value of `phi` attribute.""" def F(phishort): """Difference between `g` and expected `g` given `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_phiprod_codonsum = frx_phiprod.sum(axis=1) gexpect = [] for w in range(N_NT - 1): gexpect.append( ((CODON_NT_COUNT[w] * frx_phiprod).sum(axis=1) / frx_phiprod_codonsum).sum() / (3 * self.nsites)) gexpect = scipy.array(gexpect, dtype='float') return self.g[ : -1] - gexpect frx = self.pi_codon**beta with 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", "_compute_empirical_phi", "(", "self", ",", "beta", ")", ":", "def", "F", "(", "phishort", ")", ":", "\"\"\"Difference between `g` and expected `g` given `phishort`.\"\"\"", "phifull", "=", "scipy", ".", "append", "(", "phishort", ",", "1", "-", "phishort", ...
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 current `beta` attribute. Initial guess is current value of `phi` attribute.
[ "Returns", "empirical", "phi", "at", "the", "given", "value", "of", "beta", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1297-L1330
jbloomlab/phydms
phydmslib/models.py
ExpCM_empirical_phi._update_dPrxy
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_NT_MUT[w]) self.dQxy_dbeta[CODON_TRANSITION] *= self.kappa self.dPrxy['beta'] += self.Frxy * self.dQxy_dbeta _fill_diagonals(self.dPrxy['beta'], self._diag_indices)
python
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_NT_MUT[w]) self.dQxy_dbeta[CODON_TRANSITION] *= self.kappa self.dPrxy['beta'] += self.Frxy * self.dQxy_dbeta _fill_diagonals(self.dPrxy['beta'], self._diag_indices)
[ "def", "_update_dPrxy", "(", "self", ")", ":", "super", "(", "ExpCM_empirical_phi", ",", "self", ")", ".", "_update_dPrxy", "(", ")", "if", "'beta'", "in", "self", ".", "freeparams", ":", "self", ".", "dQxy_dbeta", "=", "scipy", ".", "zeros", "(", "(", ...
Update `dPrxy`, accounting for dependence of `phi` on `beta`.
[ "Update", "dPrxy", "accounting", "for", "dependence", "of", "phi", "on", "beta", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1332-L1342
jbloomlab/phydms
phydmslib/models.py
ExpCM_empirical_phi._update_dprx
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(self.nsites): self.dprx['beta'][r] += self.prx[r] * (dphi_over_phi - scipy.dot(dphi_over_phi, self.prx[r]))
python
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(self.nsites): self.dprx['beta'][r] += self.prx[r] * (dphi_over_phi - scipy.dot(dphi_over_phi, self.prx[r]))
[ "def", "_update_dprx", "(", "self", ")", ":", "super", "(", "ExpCM_empirical_phi", ",", "self", ")", ".", "_update_dprx", "(", ")", "if", "'beta'", "in", "self", ".", "freeparams", ":", "dphi_over_phi", "=", "scipy", ".", "zeros", "(", "N_CODON", ",", "d...
Update `dprx`, accounting for dependence of `phi` on `beta`.
[ "Update", "dprx", "accounting", "for", "dependence", "of", "phi", "on", "beta", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1344-L1353
jbloomlab/phydms
phydmslib/models.py
ExpCM_empirical_phi_divpressure._update_dPrxy
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_piAx_piAy_beta * self.Qxy * self.omega / (1 - self.piAx_piAy_beta), where=CODON_NONSYN) scipy.copyto(self.dPrxy['omega2'], self.Qxy * self.omega, where=scipy.logical_and(CODON_NONSYN, scipy.fabs(1 - self.piAx_piAy_beta) < ALMOST_ZERO)) for r in range(self.nsites): self.dPrxy['omega2'][r] *= self.deltar[r] _fill_diagonals(self.dPrxy['omega2'], self._diag_indices)
python
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_piAx_piAy_beta * self.Qxy * self.omega / (1 - self.piAx_piAy_beta), where=CODON_NONSYN) scipy.copyto(self.dPrxy['omega2'], self.Qxy * self.omega, where=scipy.logical_and(CODON_NONSYN, scipy.fabs(1 - self.piAx_piAy_beta) < ALMOST_ZERO)) for r in range(self.nsites): self.dPrxy['omega2'][r] *= self.deltar[r] _fill_diagonals(self.dPrxy['omega2'], self._diag_indices)
[ "def", "_update_dPrxy", "(", "self", ")", ":", "super", "(", "ExpCM_empirical_phi_divpressure", ",", "self", ")", ".", "_update_dPrxy", "(", ")", "if", "'omega2'", "in", "self", ".", "freeparams", ":", "with", "scipy", ".", "errstate", "(", "divide", "=", ...
Update `dPrxy`, accounting for dependence of `Prxy` on `omega2`.
[ "Update", "dPrxy", "accounting", "for", "dependence", "of", "Prxy", "on", "omega2", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1407-L1421
jbloomlab/phydms
phydmslib/models.py
ExpCM_empirical_phi_divpressure._update_Frxy
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), where=scipy.logical_and( CODON_NONSYN, scipy.fabs(1 - self.piAx_piAy_beta) > ALMOST_ZERO)) for r in range(self.nsites): scipy.copyto(self.Frxy_no_omega[r], self.Frxy_no_omega[r] * (1 + self.omega2 * self.deltar[r]), where=CODON_NONSYN) scipy.copyto(self.Frxy, self.Frxy_no_omega * self.omega, where=CODON_NONSYN)
python
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), where=scipy.logical_and( CODON_NONSYN, scipy.fabs(1 - self.piAx_piAy_beta) > ALMOST_ZERO)) for r in range(self.nsites): scipy.copyto(self.Frxy_no_omega[r], self.Frxy_no_omega[r] * (1 + self.omega2 * self.deltar[r]), where=CODON_NONSYN) scipy.copyto(self.Frxy, self.Frxy_no_omega * self.omega, where=CODON_NONSYN)
[ "def", "_update_Frxy", "(", "self", ")", ":", "self", ".", "Frxy", ".", "fill", "(", "1.0", ")", "self", ".", "Frxy_no_omega", ".", "fill", "(", "1.0", ")", "with", "scipy", ".", "errstate", "(", "divide", "=", "'raise'", ",", "under", "=", "'raise'"...
Update `Frxy` from `piAx_piAy_beta`, `omega`, `omega2`, and `beta`.
[ "Update", "Frxy", "from", "piAx_piAy_beta", "omega", "omega2", "and", "beta", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1423-L1437
jbloomlab/phydms
phydmslib/models.py
YNGKP_M0.paramsReport
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): report['{0}{1}{2}'.format(param, p, INDEX_TO_NT[w])] =\ pvalue[p][w] else: raise ValueError("Unexpected param: {0}".format(param)) return report
python
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): report['{0}{1}{2}'.format(param, p, INDEX_TO_NT[w])] =\ pvalue[p][w] else: raise ValueError("Unexpected param: {0}".format(param)) return report
[ "def", "paramsReport", "(", "self", ")", ":", "report", "=", "{", "}", "for", "param", "in", "self", ".", "_REPORTPARAMS", ":", "pvalue", "=", "getattr", "(", "self", ",", "param", ")", "if", "isinstance", "(", "pvalue", ",", "float", ")", ":", "repo...
See docs for `Model` abstract base class.
[ "See", "docs", "for", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1589-L1603
jbloomlab/phydms
phydmslib/models.py
YNGKP_M0.branchScale
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
python
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", "branchScale", "(", "self", ")", ":", "bs", "=", "-", "(", "self", ".", "Phi_x", "*", "scipy", ".", "diagonal", "(", "self", ".", "Pxy", "[", "0", "]", ")", ")", ".", "sum", "(", ")", "*", "self", ".", "mu", "assert", "bs", ">", "0", ...
See docs for `Model` abstract base class.
[ "See", "docs", "for", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1606-L1610
jbloomlab/phydms
phydmslib/models.py
YNGKP_M0._calculate_correctedF3X4
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)) stop_frequency.append(codonFrequency) C = scipy.sum(stop_frequency) for p in range(3): for w in range(N_NT): s = 0 for x in range(N_STOP): if STOP_CODON_TO_NT_INDICES[x][p][w] == 1: s += stop_frequency[x] functionList.append((phi_reshape[p][w] - s)/(1 - C) - self.e_pw[p][w]) return functionList phi = self.e_pw.copy().flatten() with scipy.errstate(invalid='ignore'): result = scipy.optimize.root(F, phi, tol=1e-8) assert result.success, "Failed: {0}".format(result) return result.x.reshape((3, N_NT))
python
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)) stop_frequency.append(codonFrequency) C = scipy.sum(stop_frequency) for p in range(3): for w in range(N_NT): s = 0 for x in range(N_STOP): if STOP_CODON_TO_NT_INDICES[x][p][w] == 1: s += stop_frequency[x] functionList.append((phi_reshape[p][w] - s)/(1 - C) - self.e_pw[p][w]) return functionList phi = self.e_pw.copy().flatten() with scipy.errstate(invalid='ignore'): result = scipy.optimize.root(F, phi, tol=1e-8) assert result.success, "Failed: {0}".format(result) return result.x.reshape((3, N_NT))
[ "def", "_calculate_correctedF3X4", "(", "self", ")", ":", "def", "F", "(", "phi", ")", ":", "phi_reshape", "=", "phi", ".", "reshape", "(", "(", "3", ",", "N_NT", ")", ")", "functionList", "=", "[", "]", "stop_frequency", "=", "[", "]", "for", "x", ...
Calculate `phi` based on the empirical `e_pw` values
[ "Calculate", "phi", "based", "on", "the", "empirical", "e_pw", "values" ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1632-L1660
jbloomlab/phydms
phydmslib/models.py
YNGKP_M0._calculate_Phi_x
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()
python
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", "_calculate_Phi_x", "(", "self", ")", ":", "self", ".", "Phi_x", "=", "scipy", ".", "ones", "(", "N_CODON", ",", "dtype", "=", "'float'", ")", "for", "codon", "in", "range", "(", "N_CODON", ")", ":", "for", "pos", "in", "range", "(", "3", ")...
Calculate `Phi_x` (stationary state) from `phi`.
[ "Calculate", "Phi_x", "(", "stationary", "state", ")", "from", "phi", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1662-L1668
jbloomlab/phydms
phydmslib/models.py
YNGKP_M0.updateParams
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 names of changed params for (name, value) in newvalues.items(): _checkParam(name, value, self.PARAMLIMITS, self.PARAMTYPES) if isinstance(value, scipy.ndarray): if (value != getattr(self, name)).any(): changed.add(name) setattr(self, name, value.copy()) else: if value != getattr(self, name): changed.add(name) setattr(self, name, copy.copy(value)) if update_all or changed: self._cached = {} # The order of the updating below is important. # If you change it, you may break either this class # **or** classes that inherit from it. # Note also that not all attributes need to be updated # for all possible parameter changes, but just doing it # this way is 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()
python
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 names of changed params for (name, value) in newvalues.items(): _checkParam(name, value, self.PARAMLIMITS, self.PARAMTYPES) if isinstance(value, scipy.ndarray): if (value != getattr(self, name)).any(): changed.add(name) setattr(self, name, value.copy()) else: if value != getattr(self, name): changed.add(name) setattr(self, name, copy.copy(value)) if update_all or changed: self._cached = {} # The order of the updating below is important. # If you change it, you may break either this class # **or** classes that inherit from it. # Note also that not all attributes need to be updated # for all possible parameter changes, but just doing it # this way is 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", "updateParams", "(", "self", ",", "newvalues", ",", "update_all", "=", "False", ")", ":", "assert", "all", "(", "map", "(", "lambda", "x", ":", "x", "in", "self", ".", "freeparams", ",", "newvalues", ".", "keys", "(", ")", ")", ")", ",", "\"...
See docs for `Model` abstract base class.
[ "See", "docs", "for", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1670-L1700
jbloomlab/phydms
phydmslib/models.py
YNGKP_M0.M
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 * t) expD = self._cached[('expD', t)] # swap axes to broadcast multiply D as diagonal matrix temp = scipy.ascontiguousarray((self.A.swapaxes(0, 1) * expD).swapaxes(1, 0), dtype=float) M = broadcastMatrixMultiply(temp, self.Ainv) assert M.min() > -1e-3, "Overly negative M: {0}".format(M.min()) M[M < 0] = 0.0 if tips is None: return scipy.tile(M, (self.nsites, 1, 1)) else: newM = scipy.zeros((len(tips), N_CODON)) for i in range(len(tips)): newM[i] =(M[0][:,tips[i]]) if gaps is not None: newM[gaps] = scipy.ones(N_CODON, dtype='float') return newM
python
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 * t) expD = self._cached[('expD', t)] # swap axes to broadcast multiply D as diagonal matrix temp = scipy.ascontiguousarray((self.A.swapaxes(0, 1) * expD).swapaxes(1, 0), dtype=float) M = broadcastMatrixMultiply(temp, self.Ainv) assert M.min() > -1e-3, "Overly negative M: {0}".format(M.min()) M[M < 0] = 0.0 if tips is None: return scipy.tile(M, (self.nsites, 1, 1)) else: newM = scipy.zeros((len(tips), N_CODON)) for i in range(len(tips)): newM[i] =(M[0][:,tips[i]]) if gaps is not None: newM[gaps] = scipy.ones(N_CODON, dtype='float') return newM
[ "def", "M", "(", "self", ",", "t", ",", "tips", "=", "None", ",", "gaps", "=", "None", ")", ":", "assert", "isinstance", "(", "t", ",", "float", ")", "and", "t", ">", "0", ",", "\"Invalid t: {0}\"", ".", "format", "(", "t", ")", "with", "scipy", ...
See docs for method in `Model` abstract base class.
[ "See", "docs", "for", "method", "in", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1702-L1723
jbloomlab/phydms
phydmslib/models.py
YNGKP_M0.dM
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 (param == 'mu') or (param == 't'): if param == 'mu': alpha = t else: alpha = self.mu if tips is None: dM_param = scipy.tile(broadcastMatrixMultiply(self.Pxy, scipy.tile(Mt[0], (1, 1, 1)), alpha=alpha), (self.nsites, 1, 1)) else: #Pxy is tiled over the number of sites dM_param = broadcastMatrixVectorMultiply(scipy.tile(self.Pxy[0], (self.nsites, 1, 1)), Mt, alpha=alpha) if gaps is not None: dM_param[gaps] = scipy.zeros(N_CODON, dtype='float') return dM_param paramval = getattr(self, param) assert isinstance(paramval, float), "All params should be floats" if ('expD', t) not in self._cached: self._cached[('expD', 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._cached['Dxx_Dyy'] if 'Dxx_Dyy_lt_ALMOST_ZERO' not in self._cached: self._cached['Dxx_Dyy_lt_ALMOST_ZERO'] = scipy.fabs( Dxx_Dyy) < ALMOST_ZERO Dxx_Dyy_lt_ALMOST_ZERO = self._cached['Dxx_Dyy_lt_ALMOST_ZERO'] with scipy.errstate(divide='raise', under='ignore', over='raise', invalid='ignore'): expDyy = scipy.tile(expD, (1, N_CODON)).reshape( 1, N_CODON, N_CODON) expDxx = scipy.array([expDyy[r].transpose() for r in range(1)]) V = (expDxx - expDyy) / Dxx_Dyy with scipy.errstate(under='ignore'): # OK if some values 0 scipy.copyto(V, self.mu * t * expDxx, where= Dxx_Dyy_lt_ALMOST_ZERO) self._cached[('V', t)] = V V = self._cached[('V', t)] with scipy.errstate(under='ignore'): # don't worry if some values 0 dM_param = broadcastMatrixMultiply(self.A, broadcastMatrixMultiply(self.B[param] * V, self.Ainv)) if tips 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
python
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 (param == 'mu') or (param == 't'): if param == 'mu': alpha = t else: alpha = self.mu if tips is None: dM_param = scipy.tile(broadcastMatrixMultiply(self.Pxy, scipy.tile(Mt[0], (1, 1, 1)), alpha=alpha), (self.nsites, 1, 1)) else: #Pxy is tiled over the number of sites dM_param = broadcastMatrixVectorMultiply(scipy.tile(self.Pxy[0], (self.nsites, 1, 1)), Mt, alpha=alpha) if gaps is not None: dM_param[gaps] = scipy.zeros(N_CODON, dtype='float') return dM_param paramval = getattr(self, param) assert isinstance(paramval, float), "All params should be floats" if ('expD', t) not in self._cached: self._cached[('expD', 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._cached['Dxx_Dyy'] if 'Dxx_Dyy_lt_ALMOST_ZERO' not in self._cached: self._cached['Dxx_Dyy_lt_ALMOST_ZERO'] = scipy.fabs( Dxx_Dyy) < ALMOST_ZERO Dxx_Dyy_lt_ALMOST_ZERO = self._cached['Dxx_Dyy_lt_ALMOST_ZERO'] with scipy.errstate(divide='raise', under='ignore', over='raise', invalid='ignore'): expDyy = scipy.tile(expD, (1, N_CODON)).reshape( 1, N_CODON, N_CODON) expDxx = scipy.array([expDyy[r].transpose() for r in range(1)]) V = (expDxx - expDyy) / Dxx_Dyy with scipy.errstate(under='ignore'): # OK if some values 0 scipy.copyto(V, self.mu * t * expDxx, where= Dxx_Dyy_lt_ALMOST_ZERO) self._cached[('V', t)] = V V = self._cached[('V', t)] with scipy.errstate(under='ignore'): # don't worry if some values 0 dM_param = broadcastMatrixMultiply(self.A, broadcastMatrixMultiply(self.B[param] * V, self.Ainv)) if tips 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", "dM", "(", "self", ",", "t", ",", "param", ",", "Mt", ",", "tips", "=", "None", ",", "gaps", "=", "None", ")", ":", "assert", "isinstance", "(", "t", ",", "float", ")", "and", "t", ">", "0", ",", "\"Invalid t: {0}\"", ".", "format", "(", ...
See docs for method in `Model` abstract base class.
[ "See", "docs", "for", "method", "in", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1725-L1795
jbloomlab/phydms
phydmslib/models.py
YNGKP_M0._update_Pxy
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, self._diag_indices)
python
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, self._diag_indices)
[ "def", "_update_Pxy", "(", "self", ")", ":", "scipy", ".", "copyto", "(", "self", ".", "Pxy_no_omega", ",", "self", ".", "Phi_x", ".", "transpose", "(", ")", ",", "where", "=", "CODON_SINGLEMUT", ")", "self", ".", "Pxy_no_omega", "[", "0", "]", "[", ...
Update `Pxy` using current `omega`, `kappa`, and `Phi_x`.
[ "Update", "Pxy", "using", "current", "omega", "kappa", "and", "Phi_x", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1797-L1804
jbloomlab/phydms
phydmslib/models.py
YNGKP_M0._update_dPxy
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_diagonals(self.dPxy['omega'], self._diag_indices)
python
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_diagonals(self.dPxy['omega'], self._diag_indices)
[ "def", "_update_dPxy", "(", "self", ")", ":", "if", "'kappa'", "in", "self", ".", "freeparams", ":", "scipy", ".", "copyto", "(", "self", ".", "dPxy", "[", "'kappa'", "]", ",", "self", ".", "Pxy", "/", "self", ".", "kappa", ",", "where", "=", "CODO...
Update `dPxy`.
[ "Update", "dPxy", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1806-L1815
jbloomlab/phydms
phydmslib/models.py
YNGKP_M0._update_Pxy_diag
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()).transpose() #assert scipy.allclose(symm_p, symm_p.transpose()) (evals, evecs) = scipy.linalg.eigh(symm_p) #assert scipy.allclose(scipy.linalg.inv(evecs), evecs.transpose()) #assert scipy.allclose(symm_pr, scipy.dot(evecs, scipy.dot(scipy.diag(evals), evecs.transpose()))) self.D[r] = evals self.Ainv[r] = evecs.transpose() * Phi_x_half self.A[r] = (Phi_x_neghalf * evecs.transpose()).transpose()
python
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()).transpose() #assert scipy.allclose(symm_p, symm_p.transpose()) (evals, evecs) = scipy.linalg.eigh(symm_p) #assert scipy.allclose(scipy.linalg.inv(evecs), evecs.transpose()) #assert scipy.allclose(symm_pr, scipy.dot(evecs, scipy.dot(scipy.diag(evals), evecs.transpose()))) self.D[r] = evals self.Ainv[r] = evecs.transpose() * Phi_x_half self.A[r] = (Phi_x_neghalf * evecs.transpose()).transpose()
[ "def", "_update_Pxy_diag", "(", "self", ")", ":", "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), ...
Update `D`, `A`, `Ainv` from `Pxy`, `Phi_x`.
[ "Update", "D", "A", "Ainv", "from", "Pxy", "Phi_x", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1817-L1830
jbloomlab/phydms
phydmslib/models.py
YNGKP_M0._update_B
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))
python
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", "_update_B", "(", "self", ")", ":", "for", "param", "in", "self", ".", "freeparams", ":", "if", "param", "==", "'mu'", ":", "continue", "paramval", "=", "getattr", "(", "self", ",", "param", ")", "assert", "isinstance", "(", "paramval", ",", "fl...
Update `B`.
[ "Update", "B", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1832-L1840
jbloomlab/phydms
phydmslib/models.py
GammaDistributedModel.dlogprior
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)
python
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", "dlogprior", "(", "self", ",", "param", ")", ":", "assert", "param", "in", "self", ".", "freeparams", ",", "\"Invalid param: {0}\"", ".", "format", "(", "param", ")", "if", "param", "in", "self", ".", "distributionparams", ":", "return", "0.0", "els...
Equal to value of `basemodel.dlogprior`.
[ "Equal", "to", "value", "of", "basemodel", ".", "dlogprior", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2011-L2017
jbloomlab/phydms
phydmslib/models.py
GammaDistributedModel.M
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)
python
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", "M", "(", "self", ",", "k", ",", "t", ",", "tips", "=", "None", ",", "gaps", "=", "None", ")", ":", "assert", "0", "<=", "k", "<", "self", ".", "ncats", "return", "self", ".", "_models", "[", "k", "]", ".", "M", "(", "t", ",", "tips"...
See docs for `DistributionModel` abstract base class.
[ "See", "docs", "for", "DistributionModel", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2082-L2085
jbloomlab/phydms
phydmslib/models.py
GammaDistributedModel.dM
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, tips=tips, gaps=gaps)
python
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, tips=tips, gaps=gaps)
[ "def", "dM", "(", "self", ",", "k", ",", "t", ",", "param", ",", "Mkt", ",", "tips", "=", "None", ",", "gaps", "=", "None", ")", ":", "assert", "0", "<=", "k", "<", "self", ".", "ncats", "assert", "(", "(", "param", "in", "self", ".", "freepa...
See docs for `DistributionModel` abstract base class.
[ "See", "docs", "for", "DistributionModel", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2087-L2093
jbloomlab/phydms
phydmslib/models.py
GammaDistributedModel.d_distributionparams
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.distributionparams) == {'alpha_lambda', 'beta_lambda'} for (param, f) in [('alpha_lambda', f_alpha), ('beta_lambda', f_beta)]: pvalue = getattr(self, param) dparam = scipy.misc.derivative(f, pvalue, dx, n=1, order=5) assert dparam.shape == (self.ncats,) for stepchange in [0.5, 2]: # make sure robust to step size dparam2 = scipy.misc.derivative(f, pvalue, stepchange * dx, n=1, order=5) assert scipy.allclose(dparam, dparam2, atol=1e-5, rtol=1e-4), ( "Numerical derivative of {0} at {1} " "differs for step {2} and {3}: {4} and {5}" ", respectively.").format(param, pvalue, dx, dx * stepchange, dparam, dparam2) self._d_distributionparams[param] = dparam return self._d_distributionparams
python
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.distributionparams) == {'alpha_lambda', 'beta_lambda'} for (param, f) in [('alpha_lambda', f_alpha), ('beta_lambda', f_beta)]: pvalue = getattr(self, param) dparam = scipy.misc.derivative(f, pvalue, dx, n=1, order=5) assert dparam.shape == (self.ncats,) for stepchange in [0.5, 2]: # make sure robust to step size dparam2 = scipy.misc.derivative(f, pvalue, stepchange * dx, n=1, order=5) assert scipy.allclose(dparam, dparam2, atol=1e-5, rtol=1e-4), ( "Numerical derivative of {0} at {1} " "differs for step {2} and {3}: {4} and {5}" ", respectively.").format(param, pvalue, dx, dx * stepchange, dparam, dparam2) self._d_distributionparams[param] = dparam return self._d_distributionparams
[ "def", "d_distributionparams", "(", "self", ")", ":", "if", "not", "self", ".", "_d_distributionparams", ":", "dx", "=", "1.0e-3", "def", "f_alpha", "(", "alpha", ")", ":", "return", "DiscreteGamma", "(", "alpha", ",", "self", ".", "beta_lambda", ",", "sel...
See docs for `DistributionModel` abstract base class.
[ "See", "docs", "for", "DistributionModel", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2096-L2118
jbloomlab/phydms
phydmslib/models.py
GammaDistributedModel.updateParams
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(self.ncats)] if update_all or any([param in self.distributionparams for param in newvalues.keys()]): self._d_distributionparams = {} for param in self.distributionparams: if param in newvalues: _checkParam(param, newvalues[param], self.PARAMLIMITS, self.PARAMTYPES) setattr(self, param, copy.copy(newvalues[param])) self._lambdas = DiscreteGamma(self.alpha_lambda, self.beta_lambda, self.ncats) for (k, l) in enumerate(self._lambdas): newvalues_list[k][self.distributedparam] = l for name in self.freeparams: if name not in self.distributionparams: if name in newvalues: value = newvalues[name] _checkParam(name, value, self.PARAMLIMITS, self.PARAMTYPES) setattr(self, name, copy.copy(value)) for k in range(self.ncats): newvalues_list[k][name] = value elif update_all: for k in range(self.ncats): newvalues_list[k][name] = getattr(self, name) assert len(newvalues_list) == len(self._models) == self.ncats for (k, newvalues_k) in enumerate(newvalues_list): self._models[k].updateParams(newvalues_k) # 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 model in self._models])))
python
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(self.ncats)] if update_all or any([param in self.distributionparams for param in newvalues.keys()]): self._d_distributionparams = {} for param in self.distributionparams: if param in newvalues: _checkParam(param, newvalues[param], self.PARAMLIMITS, self.PARAMTYPES) setattr(self, param, copy.copy(newvalues[param])) self._lambdas = DiscreteGamma(self.alpha_lambda, self.beta_lambda, self.ncats) for (k, l) in enumerate(self._lambdas): newvalues_list[k][self.distributedparam] = l for name in self.freeparams: if name not in self.distributionparams: if name in newvalues: value = newvalues[name] _checkParam(name, value, self.PARAMLIMITS, self.PARAMTYPES) setattr(self, name, copy.copy(value)) for k in range(self.ncats): newvalues_list[k][name] = value elif update_all: for k in range(self.ncats): newvalues_list[k][name] = getattr(self, name) assert len(newvalues_list) == len(self._models) == self.ncats for (k, newvalues_k) in enumerate(newvalues_list): self._models[k].updateParams(newvalues_k) # 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 model in self._models])))
[ "def", "updateParams", "(", "self", ",", "newvalues", ",", "update_all", "=", "False", ")", ":", "assert", "all", "(", "map", "(", "lambda", "x", ":", "x", "in", "self", ".", "freeparams", ",", "newvalues", ".", "keys", "(", ")", ")", ")", ",", "\"...
See docs for `Model` abstract base class.
[ "See", "docs", "for", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2120-L2163
jbloomlab/phydms
phydmslib/models.py
GammaDistributedModel.paramsReport
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
python
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", "paramsReport", "(", "self", ")", ":", "report", "=", "self", ".", "_models", "[", "0", "]", ".", "paramsReport", "del", "report", "[", "self", ".", "distributedparam", "]", "for", "param", "in", "self", ".", "distributionparams", ":", "new_name", ...
See docs for `Model` abstract base class.
[ "See", "docs", "for", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2166-L2173
jbloomlab/phydms
phydmslib/models.py
GammaDistributedModel.mu
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
python
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", ")", ":", "mu", "=", "self", ".", "_models", "[", "0", "]", ".", "mu", "assert", "all", "(", "[", "mu", "==", "model", ".", "mu", "for", "model", "in", "self", ".", "_models", "]", ")", "return", "mu" ]
See docs for `Model` abstract base class.
[ "See", "docs", "for", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2201-L2205
jbloomlab/phydms
phydmslib/models.py
GammaDistributedModel.mu
def mu(self, value): """Set new `mu` value.""" for k in range(self.ncats): self._models[k].updateParams({'mu':value})
python
def mu(self, value): """Set new `mu` value.""" for k in range(self.ncats): self._models[k].updateParams({'mu':value})
[ "def", "mu", "(", "self", ",", "value", ")", ":", "for", "k", "in", "range", "(", "self", ".", "ncats", ")", ":", "self", ".", "_models", "[", "k", "]", ".", "updateParams", "(", "{", "'mu'", ":", "value", "}", ")" ]
Set new `mu` value.
[ "Set", "new", "mu", "value", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2208-L2211
jbloomlab/phydms
phydmslib/models.py
GammaDistributedModel.stationarystate
def stationarystate(self, k): """See docs for `Model` abstract base class.""" assert 0 <= k < self.ncats return self._models[k].stationarystate
python
def stationarystate(self, k): """See docs for `Model` abstract base class.""" assert 0 <= k < self.ncats return self._models[k].stationarystate
[ "def", "stationarystate", "(", "self", ",", "k", ")", ":", "assert", "0", "<=", "k", "<", "self", ".", "ncats", "return", "self", ".", "_models", "[", "k", "]", ".", "stationarystate" ]
See docs for `Model` abstract base class.
[ "See", "docs", "for", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2213-L2216
jbloomlab/phydms
phydmslib/models.py
GammaDistributedModel.dstationarystate
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
python
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", "dstationarystate", "(", "self", ",", "k", ",", "param", ")", ":", "assert", "param", "not", "in", "self", ".", "distributionparams", "assert", "param", "in", "self", ".", "freeparams", "or", "param", "==", "self", ".", "distributedparam", "ds", "="...
See docs for `Model` abstract base class.
[ "See", "docs", "for", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2218-L2223
jbloomlab/phydms
phydmslib/models.py
GammaDistributedModel.branchScale
def branchScale(self): """See docs for `Model` abstract base class.""" bscales = [m.branchScale for m in self._models] return (self.catweights * bscales).sum()
python
def branchScale(self): """See docs for `Model` abstract base class.""" bscales = [m.branchScale for m in self._models] return (self.catweights * bscales).sum()
[ "def", "branchScale", "(", "self", ")", ":", "bscales", "=", "[", "m", ".", "branchScale", "for", "m", "in", "self", ".", "_models", "]", "return", "(", "self", ".", "catweights", "*", "bscales", ")", ".", "sum", "(", ")" ]
See docs for `Model` abstract base class.
[ "See", "docs", "for", "Model", "abstract", "base", "class", "." ]
train
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2226-L2229
stbraun/fuzzing
features/steps/ft_singleton.py
step_impl04
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(key) == general.request(key)
python
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(key) == general.request(key)
[ "def", "step_impl04", "(", "context", ")", ":", "single", "=", "context", ".", "singleStore", "general", "=", "context", ".", "generalStore", "key", "=", "13", "item", "=", "42", "assert", "single", ".", "request", "(", "key", ")", "==", "general", ".", ...
Compare behavior of singleton vs. non-singleton. :param context: test context.
[ "Compare", "behavior", "of", "singleton", "vs", ".", "non", "-", "singleton", "." ]
train
https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_singleton.py#L37-L49
stbraun/fuzzing
features/steps/ft_singleton.py
step_impl06
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()
python
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_impl06", "(", "context", ")", ":", "store", "=", "context", ".", "SingleStore", "context", ".", "st_1", "=", "store", "(", ")", "context", ".", "st_2", "=", "store", "(", ")", "context", ".", "st_3", "=", "store", "(", ")" ]
Prepare test for singleton property. :param context: test context.
[ "Prepare", "test", "for", "singleton", "property", "." ]
train
https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_singleton.py#L62-L70