_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q7000
Logger.subscribe
train
def subscribe(self, queue=None, *levels): """ Subscribe to the aggregated log stream. On subscribe a ledis queue will be fed with all running processes logs. Always use the returned queue name from this method, even if u specified the queue name to use Note: it is legal to subscribe to ...
python
{ "resource": "" }
q7001
AggregatorManager.query
train
def query(self, key=None, **tags): """ Query zero-os aggregator for current state object of monitored metrics. Note: ID is returned as part of the key (if set) to avoid conflict with similar metrics that has same key. For example, a cpu core nr can be the id associated with 'machine.CPU...
python
{ "resource": "" }
q7002
CGroupManager.ensure
train
def ensure(self, subsystem, name): """ Creates a cgroup if it doesn't exist under the specified subsystem and the given name :param subsystem: the cgroup subsystem (currently support 'memory', and 'cpuset') :param name: name of the cgroup to delete """ args = { ...
python
{ "resource": "" }
q7003
dlmk
train
def dlmk(l,m,k,theta1): """ returns value of d^l_mk as defined in allen, ottewill 97. Called by Dlmk """ if m >= k: factor = sqrt(factorial(l-k)*factorial(l+m)/factorial(l+k)/factorial(l-m)) part2 = (cos(theta1/2))**(2*l+k-m)*(-sin(theta1/2))**(m-k)/factorial(m-k) ...
python
{ "resource": "" }
q7004
Dlmk
train
def Dlmk(l,m,k,phi1,phi2,theta1,theta2): """ returns value of D^l_mk as defined in allen, ottewill 97. """ return exp(complex(0.,-m*phi1)) * dlmk(l,m,k,theta1) * \ exp(complex(0.,-k*gamma(phi1,phi2,theta1,theta2)))
python
{ "resource": "" }
q7005
gamma
train
def gamma(phi1,phi2,theta1,theta2): """ calculate third rotation angle inputs are angles from 2 pulsars returns the angle. """ if phi1 == phi2 and theta1 == theta2: gamma = 0 else: gamma = atan( sin(theta2)*sin(phi2-phi1) / \ (cos(theta1)*sin(t...
python
{ "resource": "" }
q7006
rotated_Gamma_ml
train
def rotated_Gamma_ml(m,l,phi1,phi2,theta1,theta2,gamma_ml): """ This function takes any gamma in the computational frame and rotates it to the cosmic frame. """ rotated_gamma = 0 for ii in range(2*l+1): rotated_gamma += Dlmk(l,m,ii-l,phi1,phi2,theta1,theta2).conjugate()*g...
python
{ "resource": "" }
q7007
real_rotated_Gammas
train
def real_rotated_Gammas(m,l,phi1,phi2,theta1,theta2,gamma_ml): """ This function returns the real-valued form of the Overlap Reduction Functions, see Eqs 47 in Mingarelli et al, 2013. """ if m>0: ans=(1./sqrt(2))*(rotated_Gamma_ml(m,l,phi1,phi2,theta1,theta2,gamma_ml) + \ ...
python
{ "resource": "" }
q7008
chisq
train
def chisq(psr,formbats=False): """Return the total chisq for the current timing solution, removing noise-averaged mean residual, and ignoring deleted points.""" if formbats: psr.formbats() res, err = psr.residuals(removemean=False)[psr.deleted == 0], psr.toaerrs[psr.deleted == 0] ...
python
{ "resource": "" }
q7009
dchisq
train
def dchisq(psr,formbats=False,renormalize=True): """Return gradient of total chisq for the current timing solution, after removing noise-averaged mean residual, and ignoring deleted points.""" if formbats: psr.formbats() res, err = psr.residuals(removemean=False)[psr.deleted == 0], psr.toa...
python
{ "resource": "" }
q7010
create_fourier_design_matrix
train
def create_fourier_design_matrix(t, nmodes, freq=False, Tspan=None, logf=False, fmin=None, fmax=None): """ Construct fourier design matrix from eq 11 of Lentati et al, 2013 :param t: vector of time series in seconds :param nmodes: number of fourier coefficients to use ...
python
{ "resource": "" }
q7011
powerlaw
train
def powerlaw(f, log10_A=-16, gamma=5): """Power-law PSD. :param f: Sampling frequencies :param log10_A: log10 of red noise Amplitude [GW units] :param gamma: Spectral index of red noise process """ fyr = 1 / 3.16e7 return (10**log10_A)**2 / 12.0 / np.pi**2 * fyr**(gamma-3) * f**(-gamma)
python
{ "resource": "" }
q7012
add_gwb
train
def add_gwb(psr, dist=1, ngw=1000, seed=None, flow=1e-8, fhigh=1e-5, gwAmp=1e-20, alpha=-0.66, logspacing=True): """Add a stochastic background from inspiraling binaries, using the tempo2 code that underlies the GWbkgrd plugin. Here 'dist' is the pulsar distance [in kpc]; 'ngw' is the number of...
python
{ "resource": "" }
q7013
add_dipole_gwb
train
def add_dipole_gwb(psr, dist=1, ngw=1000, seed=None, flow=1e-8, fhigh=1e-5, gwAmp=1e-20, alpha=-0.66, logspacing=True, dipoleamps=None, dipoledir=None, dipolemag=None): """Add a stochastic background from inspiraling binaries distributed accord...
python
{ "resource": "" }
q7014
add_efac
train
def add_efac(psr, efac=1.0, flagid=None, flags=None, seed=None): """Add nominal TOA errors, multiplied by `efac` factor. Optionally take a pseudorandom-number-generator seed.""" if seed is not None: N.random.seed(seed) # default efacvec efacvec = N.ones(psr.nobs) # check that efac...
python
{ "resource": "" }
q7015
extrap1d
train
def extrap1d(interpolator): """ Function to extend an interpolation function to an extrapolation function. :param interpolator: scipy interp1d object :returns ufunclike: extension of function to extrapolation """ xs = interpolator.x ys = interpolator.y def pointwise(x): ...
python
{ "resource": "" }
q7016
computeORFMatrix
train
def computeORFMatrix(psr): """ Compute ORF matrix. :param psr: List of pulsar object instances :returns: Matrix that has the ORF values for every pulsar pair with 2 on the diagonals to account for the pulsar term. """ # begin loop over all pulsar pairs and calculat...
python
{ "resource": "" }
q7017
plotres
train
def plotres(psr,deleted=False,group=None,**kwargs): """Plot residuals, compute unweighted rms residual.""" res, t, errs = psr.residuals(), psr.toas(), psr.toaerrs if (not deleted) and N.any(psr.deleted != 0): res, t, errs = res[psr.deleted == 0], t[psr.deleted == 0], errs[psr.deleted == 0] ...
python
{ "resource": "" }
q7018
plotgwsrc
train
def plotgwsrc(gwb): """ Plot a GWB source population as a mollweide projection. """ theta, phi, omega, polarization = gwb.gw_dist() rho = phi-N.pi eta = 0.5*N.pi - theta # I don't know how to get rid of the RuntimeWarning -- RvH, Oct 10, 2014: # /Users/vhaaster/env/dev/lib/python2....
python
{ "resource": "" }
q7019
merge
train
def merge(data,skip=50,fraction=1.0): """Merge one every 'skip' clouds into a single emcee population, using the later 'fraction' of the run.""" w,s,d = data.chains.shape start = int((1.0 - fraction) * s) total = int((s - start) / skip) return data.chains[:,start::skip,:].reshape(...
python
{ "resource": "" }
q7020
cull
train
def cull(data,index,min=None,max=None): """Sieve an emcee clouds by excluding walkers with search variable 'index' smaller than 'min' or larger than 'max'.""" ret = data if min is not None: ret = ret[ret[:,index] > min,:] if max is not None: ret = ret[ret[:,index] < max,:] ...
python
{ "resource": "" }
q7021
make_ecc_interpolant
train
def make_ecc_interpolant(): """ Make interpolation function from eccentricity file to determine number of harmonics to use for a given eccentricity. :returns: interpolant """ pth = resource_filename(Requirement.parse('libstempo'), 'libstempo/ecc_vs_nharm.txt') ...
python
{ "resource": "" }
q7022
best_kmers
train
def best_kmers(dt, response, sequence, k=6, consider_shift=True, n_cores=1, seq_align="start", trim_seq_len=None): """ Find best k-mers for CONCISE initialization. Args: dt (pd.DataFrame): Table containing response variable and sequence. response (str): Name of the column use...
python
{ "resource": "" }
q7023
kmer_count
train
def kmer_count(seq_list, k): """ Generate k-mer counts from a set of sequences Args: seq_list (iterable): List of DNA sequences (with letters from {A, C, G, T}) k (int): K in k-mer. Returns: pandas.DataFrame: Count matrix for seach sequence in seq_list Example: >>> kmer...
python
{ "resource": "" }
q7024
generate_all_kmers
train
def generate_all_kmers(k): """ Generate all possible k-mers Example: >>> generate_all_kmers(2) ['AA', 'AC', 'AG', 'AT', 'CA', 'CC', 'CG', 'CT', 'GA', 'GC', 'GG', 'GT', 'TA', 'TC', 'TG', 'TT'] """ bases = ['A', 'C', 'G', 'T'] return [''.join(p) for p in itertools.product(bases, repeat=k)...
python
{ "resource": "" }
q7025
dict_to_numpy_dict
train
def dict_to_numpy_dict(obj_dict): """ Convert a dictionary of lists into a dictionary of numpy arrays """ return {key: np.asarray(value) if value is not None else None for key, value in obj_dict.items()}
python
{ "resource": "" }
q7026
rec_dict_to_numpy_dict
train
def rec_dict_to_numpy_dict(obj_dict): """ Same as dict_to_numpy_dict, but recursive """ if type(obj_dict) == dict: return {key: rec_dict_to_numpy_dict(value) if value is not None else None for key, value in obj_dict.items()} elif obj_dict is None: return None else: return...
python
{ "resource": "" }
q7027
compare_numpy_dict
train
def compare_numpy_dict(a, b, exact=True): """ Compare two recursive numpy dictionaries """ if type(a) != type(b) and type(a) != np.ndarray and type(b) != np.ndarray: return False # go through a dictionary if type(a) == dict and type(b) == dict: if not a.keys() == b.keys(): ...
python
{ "resource": "" }
q7028
BSpline.getS
train
def getS(self, add_intercept=False): """Get the penalty matrix S Returns np.array, of shape (n_bases + add_intercept, n_bases + add_intercept) """ S = self.S if add_intercept is True: # S <- cbind(0, rbind(0, S)) # in R zeros = np.zeros_like(S...
python
{ "resource": "" }
q7029
get_pwm_list
train
def get_pwm_list(motif_name_list, pseudocountProb=0.0001): """Get a list of ENCODE PWM's. # Arguments pwm_id_list: List of id's from the `PWM_id` column in `get_metadata()` table pseudocountProb: Added pseudocount probabilities to the PWM # Returns List of `concise.utils.pwm.PWM` i...
python
{ "resource": "" }
q7030
auc
train
def auc(y_true, y_pred, round=True): """Area under the ROC curve """ y_true, y_pred = _mask_value_nan(y_true, y_pred) if round: y_true = y_true.round() if len(y_true) == 0 or len(np.unique(y_true)) < 2: return np.nan return skm.roc_auc_score(y_true, y_pred)
python
{ "resource": "" }
q7031
recall_at_precision
train
def recall_at_precision(y_true, y_pred, precision): """Recall at a certain precision threshold Args: y_true: true labels y_pred: predicted labels precision: resired precision level at which where to compute the recall """ y_true, y_pred = _mask_value_nan(y_true, y_pred) precision,...
python
{ "resource": "" }
q7032
cor
train
def cor(y_true, y_pred): """Compute Pearson correlation coefficient. """ y_true, y_pred = _mask_nan(y_true, y_pred) return np.corrcoef(y_true, y_pred)[0, 1]
python
{ "resource": "" }
q7033
kendall
train
def kendall(y_true, y_pred, nb_sample=100000): """Kendall's tau coefficient, Kendall rank correlation coefficient """ y_true, y_pred = _mask_nan(y_true, y_pred) if len(y_true) > nb_sample: idx = np.arange(len(y_true)) np.random.shuffle(idx) idx = idx[:nb_sample] y_true = ...
python
{ "resource": "" }
q7034
mad
train
def mad(y_true, y_pred): """Median absolute deviation """ y_true, y_pred = _mask_nan(y_true, y_pred) return np.mean(np.abs(y_true - y_pred))
python
{ "resource": "" }
q7035
mse
train
def mse(y_true, y_pred): """Mean squared error """ y_true, y_pred = _mask_nan(y_true, y_pred) return ((y_true - y_pred) ** 2).mean(axis=None)
python
{ "resource": "" }
q7036
sample_params
train
def sample_params(params): """Randomly sample hyper-parameters stored in a dictionary on a predefined range and scale. Useful for hyper-parameter random search. Args: params (dict): hyper-parameters to sample. Dictionary value-type parsing: - :python:`[1e3, 1e7]` - uniformly ...
python
{ "resource": "" }
q7037
cat_acc
train
def cat_acc(y, z): """Classification accuracy for multi-categorical case """ weights = _cat_sample_weights(y) _acc = K.cast(K.equal(K.argmax(y, axis=-1), K.argmax(z, axis=-1)), K.floatx()) _acc = K.sum(_acc * weights) / K.sum(weights) return _acc
python
{ "resource": "" }
q7038
split_KFold_idx
train
def split_KFold_idx(train, cv_n_folds=5, stratified=False, random_state=None): """Get k-fold indices generator """ test_len(train) y = train[1] n_rows = y.shape[0] if stratified: if len(y.shape) > 1: if y.shape[1] > 1: raise ValueError("Can't use stratified K-...
python
{ "resource": "" }
q7039
prepare_data
train
def prepare_data(dt, features, response, sequence, id_column=None, seq_align="end", trim_seq_len=None): """ Prepare data for Concise.train or ConciseCV.train. Args: dt: A pandas DataFrame containing all the required data. features (List of strings): Column names of `dt` used to produce the ...
python
{ "resource": "" }
q7040
EncodeSplines.fit
train
def fit(self, x): """Calculate the knot placement from the values ranges. # Arguments x: numpy array, either N x D or N x L x D dimensional. """ assert x.ndim > 1 self.data_min_ = np.min(x, axis=tuple(range(x.ndim - 1))) self.data_max_ = np.max(x, axis=tuple(...
python
{ "resource": "" }
q7041
EncodeSplines.transform
train
def transform(self, x, warn=True): """Obtain the transformed values """ # 1. split across last dimension # 2. re-use ranges # 3. Merge array_list = [encodeSplines(x[..., i].reshape((-1, 1)), n_bases=self.n_bases, ...
python
{ "resource": "" }
q7042
InputCodon
train
def InputCodon(seq_length, ignore_stop_codons=True, name=None, **kwargs): """Input placeholder for array returned by `encodeCodon` Note: The seq_length is divided by 3 Wrapper for: `keras.layers.Input((seq_length / 3, 61 or 61), name=name, **kwargs)` """ if ignore_stop_codons: vocab = CODO...
python
{ "resource": "" }
q7043
InputAA
train
def InputAA(seq_length, name=None, **kwargs): """Input placeholder for array returned by `encodeAA` Wrapper for: `keras.layers.Input((seq_length, 22), name=name, **kwargs)` """ return Input((seq_length, len(AMINO_ACIDS)), name=name, **kwargs)
python
{ "resource": "" }
q7044
InputRNAStructure
train
def InputRNAStructure(seq_length, name=None, **kwargs): """Input placeholder for array returned by `encodeRNAStructure` Wrapper for: `keras.layers.Input((seq_length, 5), name=name, **kwargs)` """ return Input((seq_length, len(RNAplfold_PROFILES)), name=name, **kwargs)
python
{ "resource": "" }
q7045
ConvSequence._plot_weights_heatmap
train
def _plot_weights_heatmap(self, index=None, figsize=None, **kwargs): """Plot weights as a heatmap index = can be a particular index or a list of indicies **kwargs - additional arguments to concise.utils.plot.heatmap """ W = self.get_weights()[0] if index is None: ...
python
{ "resource": "" }
q7046
ConvSequence._plot_weights_motif
train
def _plot_weights_motif(self, index, plot_type="motif_raw", background_probs=DEFAULT_BASE_BACKGROUND, ncol=1, figsize=None): """Index can only be a single int """ w_all = self.get_weights() if len(w_all...
python
{ "resource": "" }
q7047
ConvSequence.plot_weights
train
def plot_weights(self, index=None, plot_type="motif_raw", figsize=None, ncol=1, **kwargs): """Plot filters as heatmap or motifs index = can be a particular index or a list of indicies **kwargs - additional arguments to concise.utils.plot.heatmap """ if "heatmap" in self.AVAILAB...
python
{ "resource": "" }
q7048
_check_pwm_list
train
def _check_pwm_list(pwm_list): """Check the input validity """ for pwm in pwm_list: if not isinstance(pwm, PWM): raise TypeError("element {0} of pwm_list is not of type PWM".format(pwm)) return True
python
{ "resource": "" }
q7049
heatmap
train
def heatmap(w, vmin=None, vmax=None, diverge_color=False, ncol=1, plot_name=None, vocab=["A", "C", "G", "T"], figsize=(6, 2)): """Plot a heatmap from weight matrix w vmin, vmax = z axis range diverge_color = Should we use diverging colors? plot_name = plot_title vocab = voca...
python
{ "resource": "" }
q7050
add_letter_to_axis
train
def add_letter_to_axis(ax, let, col, x, y, height): """Add 'let' with position x,y and height height to matplotlib axis 'ax'. """ if len(let) == 2: colors = [col, "white"] elif len(let) == 1: colors = [col] else: raise ValueError("3 or more Polygons are not supported") f...
python
{ "resource": "" }
q7051
seqlogo
train
def seqlogo(letter_heights, vocab="DNA", ax=None): """Make a logo plot # Arguments letter_heights: "motif length" x "vocabulary size" numpy array Can also contain negative values. vocab: str, Vocabulary name. Can be: DNA, RNA, AA, RNAStruct. ax: matplotlib axis """ ax = ax o...
python
{ "resource": "" }
q7052
get_cv_accuracy
train
def get_cv_accuracy(res): """ Extract the cv accuracy from the model """ ac_list = [(accuracy["train_acc_final"], accuracy["test_acc_final"] ) for accuracy, weights in res] ac = np.array(ac_list) perf = { "mean_train_acc": np.mean(ac[:, 0])...
python
{ "resource": "" }
q7053
one_hot2string
train
def one_hot2string(arr, vocab): """Convert a one-hot encoded array back to string """ tokens = one_hot2token(arr) indexToLetter = _get_index_dict(vocab) return [''.join([indexToLetter[x] for x in row]) for row in tokens]
python
{ "resource": "" }
q7054
tokenize
train
def tokenize(seq, vocab, neutral_vocab=[]): """Convert sequence to integers # Arguments seq: Sequence to encode vocab: Vocabulary to use neutral_vocab: Neutral vocabulary -> assign those values to -1 # Returns List of length `len(seq)` with integers from `-1` to `len(vocab) - 1...
python
{ "resource": "" }
q7055
encodeSequence
train
def encodeSequence(seq_vec, vocab, neutral_vocab, maxlen=None, seq_align="start", pad_value="N", encode_type="one_hot"): """Convert a list of genetic sequences into one-hot-encoded array. # Arguments seq_vec: list of strings (genetic sequences) vocab: list of chars: List of "wo...
python
{ "resource": "" }
q7056
encodeDNA
train
def encodeDNA(seq_vec, maxlen=None, seq_align="start"): """Convert the DNA sequence into 1-hot-encoding numpy array # Arguments seq_vec: list of chars List of sequences that can have different lengths maxlen: int or None, Should we trim (subset) the resulting sequence. ...
python
{ "resource": "" }
q7057
encodeRNA
train
def encodeRNA(seq_vec, maxlen=None, seq_align="start"): """Convert the RNA sequence into 1-hot-encoding numpy array as for encodeDNA """ return encodeSequence(seq_vec, vocab=RNA, neutral_vocab="N", maxlen=maxlen, ...
python
{ "resource": "" }
q7058
encodeCodon
train
def encodeCodon(seq_vec, ignore_stop_codons=True, maxlen=None, seq_align="start", encode_type="one_hot"): """Convert the Codon sequence into 1-hot-encoding numpy array # Arguments seq_vec: List of strings/DNA sequences ignore_stop_codons: boolean; if True, STOP_CODONS are omitted from one-hot e...
python
{ "resource": "" }
q7059
encodeAA
train
def encodeAA(seq_vec, maxlen=None, seq_align="start", encode_type="one_hot"): """Convert the Amino-acid sequence into 1-hot-encoding numpy array # Arguments seq_vec: List of strings/amino-acid sequences maxlen: Maximum sequence length. See `pad_sequences` for more detail seq_align: How ...
python
{ "resource": "" }
q7060
_validate_pos
train
def _validate_pos(df): """Validates the returned positional object """ assert isinstance(df, pd.DataFrame) assert ["seqname", "position", "strand"] == df.columns.tolist() assert df.position.dtype == np.dtype("int64") assert df.strand.dtype == np.dtype("O") assert df.seqname.dtype == np.dtype...
python
{ "resource": "" }
q7061
get_pwm_list
train
def get_pwm_list(pwm_id_list, pseudocountProb=0.0001): """Get a list of Attract PWM's. # Arguments pwm_id_list: List of id's from the `PWM_id` column in `get_metadata()` table pseudocountProb: Added pseudocount probabilities to the PWM # Returns List of `concise.utils.pwm.PWM` inst...
python
{ "resource": "" }
q7062
mask_loss
train
def mask_loss(loss, mask_value=MASK_VALUE): """Generates a new loss function that ignores values where `y_true == mask_value`. # Arguments loss: str; name of the keras loss function from `keras.losses` mask_value: int; which values should be masked # Returns function; Masked versio...
python
{ "resource": "" }
q7063
get_pwm_list
train
def get_pwm_list(pwm_id_list, pseudocountProb=0.0001): """Get a list of HOCOMOCO PWM's. # Arguments pwm_id_list: List of id's from the `PWM_id` column in `get_metadata()` table pseudocountProb: Added pseudocount probabilities to the PWM # Returns List of `concise.utils.pwm.PWM` ins...
python
{ "resource": "" }
q7064
Concise._var_res_to_weights
train
def _var_res_to_weights(self, var_res): """ Get model weights """ # transform the weights into our form motif_base_weights_raw = var_res["motif_base_weights"][0] motif_base_weights = np.swapaxes(motif_base_weights_raw, 0, 2) # get weights motif_weights = ...
python
{ "resource": "" }
q7065
Concise._get_var_res
train
def _get_var_res(self, graph, var, other_var): """ Get the weights from our graph """ with tf.Session(graph=graph) as sess: sess.run(other_var["init"]) # all_vars = tf.all_variables() # print("All variable names") # print([var.name for var...
python
{ "resource": "" }
q7066
Concise._convert_to_var
train
def _convert_to_var(self, graph, var_res): """ Create tf.Variables from a list of numpy arrays var_res: dictionary of numpy arrays with the key names corresponding to var """ with graph.as_default(): var = {} for key, value in var_res.items(): ...
python
{ "resource": "" }
q7067
Concise.train
train
def train(self, X_feat, X_seq, y, X_feat_valid=None, X_seq_valid=None, y_valid=None, n_cores=3): """Train the CONCISE model :py:attr:`X_feat`, :py:attr:`X_seq`, py:attr:`y` are preferrably returned by the :py:func:`concise.prepare_data` function. Args: X...
python
{ "resource": "" }
q7068
Concise._accuracy_in_session
train
def _accuracy_in_session(self, sess, other_var, X_feat, X_seq, y): """ Compute the accuracy from inside the tf session """ y_pred = self._predict_in_session(sess, other_var, X_feat, X_seq) return ce.mse(y_pred, y)
python
{ "resource": "" }
q7069
Concise._set_var_res
train
def _set_var_res(self, weights): """ Transform the weights to var_res """ if weights is None: return # layer 1 motif_base_weights_raw = np.swapaxes(weights["motif_base_weights"], 2, 0) motif_base_weights = motif_base_weights_raw[np.newaxis] mo...
python
{ "resource": "" }
q7070
ConciseCV._get_folds
train
def _get_folds(n_rows, n_folds, use_stored): """ Get the used CV folds """ # n_folds = self._n_folds # use_stored = self._use_stored_folds # n_rows = self._n_rows if use_stored is not None: # path = '~/concise/data-offline/lw-pombe/cv_folds_5.json' ...
python
{ "resource": "" }
q7071
ConciseCV.train
train
def train(self, X_feat, X_seq, y, id_vec=None, n_folds=10, use_stored_folds=None, n_cores=1, train_global_model=False): """Train the Concise model in cross-validation. Args: X_feat: See :py:func:`concise.Concise.train` X_seq: See :py:func:`concise.Concise.train` ...
python
{ "resource": "" }
q7072
ConciseCV._from_dict
train
def _from_dict(self, obj_dict): """ Initialize a model from the dictionary """ self._n_folds = obj_dict["param"]["n_folds"] self._n_rows = obj_dict["param"]["n_rows"] self._use_stored_folds = obj_dict["param"]["use_stored_folds"] self._concise_model = Concise.fro...
python
{ "resource": "" }
q7073
pwm_array2pssm_array
train
def pwm_array2pssm_array(arr, background_probs=DEFAULT_BASE_BACKGROUND): """Convert pwm array to pssm array """ b = background_probs2array(background_probs) b = b.reshape([1, 4, 1]) return np.log(arr / b).astype(arr.dtype)
python
{ "resource": "" }
q7074
pssm_array2pwm_array
train
def pssm_array2pwm_array(arr, background_probs=DEFAULT_BASE_BACKGROUND): """Convert pssm array to pwm array """ b = background_probs2array(background_probs) b = b.reshape([1, 4, 1]) return (np.exp(arr) * b).astype(arr.dtype)
python
{ "resource": "" }
q7075
load_motif_db
train
def load_motif_db(filename, skipn_matrix=0): """Read the motif file in the following format ``` >motif_name <skip n>0.1<delim>0.2<delim>0.5<delim>0.6 ... >motif_name2 .... ``` Delim can be anything supported by np.loadtxt # Arguments filename: str, file path sk...
python
{ "resource": "" }
q7076
iter_fasta
train
def iter_fasta(file_path): """Returns an iterator over the fasta file Given a fasta file. yield tuples of header, sequence Code modified from Brent Pedersen's: "Correct Way To Parse A Fasta File In Python" # Example ```python fasta = fasta_iter("hg19.fa") for hea...
python
{ "resource": "" }
q7077
write_fasta
train
def write_fasta(file_path, seq_list, name_list=None): """Write a fasta file # Arguments file_path: file path seq_list: List of strings name_list: List of names corresponding to the sequences. If not None, it should have the same length as `seq_list` """ if name_list is None: ...
python
{ "resource": "" }
q7078
read_RNAplfold
train
def read_RNAplfold(tmpdir, maxlen=None, seq_align="start", pad_with="E"): """ pad_with = with which 2ndary structure should we pad the sequence? """ assert pad_with in {"P", "H", "I", "M", "E"} def read_profile(tmpdir, P): return [values.strip().split("\t") for seq_name, val...
python
{ "resource": "" }
q7079
ism
train
def ism(model, ref, ref_rc, alt, alt_rc, mutation_positions, out_annotation_all_outputs, output_filter_mask=None, out_annotation=None, diff_type="log_odds", rc_handling="maximum"): """In-silico mutagenesis Using ISM in with diff_type 'log_odds' and rc_handling 'maximum' will produce predictions as used...
python
{ "resource": "" }
q7080
_train_and_eval_single
train
def _train_and_eval_single(train, valid, model, batch_size=32, epochs=300, use_weight=False, callbacks=[], eval_best=False, add_eval_metrics={}): """Fit and evaluate a keras model eval_best: if True, load the checkpointed model for evaluation """ de...
python
{ "resource": "" }
q7081
eval_model
train
def eval_model(model, test, add_eval_metrics={}): """Evaluate model's performance on the test-set. # Arguments model: Keras model test: test-dataset. Tuple of inputs `x` and target `y` - `(x, y)`. add_eval_metrics: Additional evaluation metrics to use. Can be a dictionary or a list of f...
python
{ "resource": "" }
q7082
get_model
train
def get_model(model_fn, train_data, param): """Feed model_fn with train_data and param """ model_param = merge_dicts({"train_data": train_data}, param["model"], param.get("shared", {})) return model_fn(**model_param)
python
{ "resource": "" }
q7083
_delete_keys
train
def _delete_keys(dct, keys): """Returns a copy of dct without `keys` keys """ c = deepcopy(dct) assert isinstance(keys, list) for k in keys: c.pop(k) return c
python
{ "resource": "" }
q7084
_mean_dict
train
def _mean_dict(dict_list): """Compute the mean value across a list of dictionaries """ return {k: np.array([d[k] for d in dict_list]).mean() for k in dict_list[0].keys()}
python
{ "resource": "" }
q7085
CMongoTrials.get_trial
train
def get_trial(self, tid): """Retrieve trial by tid """ lid = np.where(np.array(self.tids) == tid)[0][0] return self.trials[lid]
python
{ "resource": "" }
q7086
CMongoTrials.delete_running
train
def delete_running(self, timeout_last_refresh=0, dry_run=False): """Delete jobs stalled in the running state for too long timeout_last_refresh, int: number of seconds """ running_all = self.handle.jobs_running() running_timeout = [job for job in running_all ...
python
{ "resource": "" }
q7087
CMongoTrials.train_history
train
def train_history(self, tid=None): """Get train history as pd.DataFrame """ def result2history(result): if isinstance(result["history"], list): return pd.concat([pd.DataFrame(hist["loss"]).assign(fold=i) for i, hist in enumerate(resu...
python
{ "resource": "" }
q7088
CMongoTrials.as_df
train
def as_df(self, ignore_vals=["history"], separator=".", verbose=True): """Return a pd.DataFrame view of the whole experiment """ def add_eval(res): if "eval" not in res: if isinstance(res["history"], list): # take the average across all folds ...
python
{ "resource": "" }
q7089
effect_from_model
train
def effect_from_model(model, ref, ref_rc, alt, alt_rc, methods, mutation_positions, out_annotation_all_outputs, extra_args=None, **argv): """Convenience function to execute multiple effect predictions in one call # Arguments model: Keras model ref: Input sequence with the ...
python
{ "resource": "" }
q7090
trades
train
def trades(ctx, market, limit, start, stop): """ List trades in a market """ market = Market(market, bitshares_instance=ctx.bitshares) t = [["time", "quote", "base", "price"]] for trade in market.trades(limit, start=start, stop=stop): t.append( [ str(trade["time"]...
python
{ "resource": "" }
q7091
ticker
train
def ticker(ctx, market): """ Show ticker of a market """ market = Market(market, bitshares_instance=ctx.bitshares) ticker = market.ticker() t = [["key", "value"]] for key in ticker: t.append([key, str(ticker[key])]) print_table(t)
python
{ "resource": "" }
q7092
cancel
train
def cancel(ctx, orders, account): """ Cancel one or multiple orders """ print_tx(ctx.bitshares.cancel(orders, account=account))
python
{ "resource": "" }
q7093
orderbook
train
def orderbook(ctx, market): """ Show the orderbook of a particular market """ market = Market(market, bitshares_instance=ctx.bitshares) orderbook = market.orderbook() ta = {} ta["bids"] = [["quote", "sum quote", "base", "sum base", "price"]] cumsumquote = Amount(0, market["quote"]) cumsu...
python
{ "resource": "" }
q7094
buy
train
def buy(ctx, buy_amount, buy_asset, price, sell_asset, order_expiration, account): """ Buy a specific asset at a certain rate against a base asset """ amount = Amount(buy_amount, buy_asset) price = Price( price, base=sell_asset, quote=buy_asset, bitshares_instance=ctx.bitshares ) print_t...
python
{ "resource": "" }
q7095
openorders
train
def openorders(ctx, account): """ List open orders of an account """ account = Account( account or config["default_account"], bitshares_instance=ctx.bitshares ) t = [["Price", "Quote", "Base", "ID"]] for o in account.openorders: t.append( [ "{:f} {}/{}...
python
{ "resource": "" }
q7096
cancelall
train
def cancelall(ctx, market, account): """ Cancel all orders of an account in a market """ market = Market(market) ctx.bitshares.bundle = True market.cancel([x["id"] for x in market.accountopenorders(account)], account=account) print_tx(ctx.bitshares.txbuffer.broadcast())
python
{ "resource": "" }
q7097
spread
train
def spread(ctx, market, side, min, max, num, total, order_expiration, account): """ Place multiple orders \b :param str market: Market pair quote:base (e.g. USD:BTS) :param str side: ``buy`` or ``sell`` quote :param float min: minimum price to place order at :param float max...
python
{ "resource": "" }
q7098
updateratio
train
def updateratio(ctx, symbol, ratio, account): """ Update the collateral ratio of a call positions """ from bitshares.dex import Dex dex = Dex(bitshares_instance=ctx.bitshares) print_tx(dex.adjust_collateral_ratio(symbol, ratio, account=account))
python
{ "resource": "" }
q7099
bidcollateral
train
def bidcollateral( ctx, collateral_symbol, collateral_amount, debt_symbol, debt_amount, account ): """ Bid for collateral in the settlement fund """ print_tx( ctx.bitshares.bid_collateral( Amount(collateral_amount, collateral_symbol), Amount(debt_amount, debt_symbol), ...
python
{ "resource": "" }