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_documentation_string stringlengths 1 47.2k | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|
gagneurlab/concise | concise/utils/plot.py | add_letter_to_axis | 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 | 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... | Add 'let' with position x,y and height height to matplotlib axis 'ax'. | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/utils/plot.py#L174-L192 |
gagneurlab/concise | concise/utils/plot.py | seqlogo | 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 | 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... | 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 | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/utils/plot.py#L196-L234 |
gagneurlab/concise | concise/legacy/analyze.py | get_cv_accuracy | 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 | 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])... | Extract the cv accuracy from the model | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/analyze.py#L9-L26 |
gagneurlab/concise | concise/preprocessing/sequence.py | one_hot2string | 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 | 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] | Convert a one-hot encoded array back to string | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/preprocessing/sequence.py#L32-L38 |
gagneurlab/concise | concise/preprocessing/sequence.py | tokenize | 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 | 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... | 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` | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/preprocessing/sequence.py#L41-L66 |
gagneurlab/concise | concise/preprocessing/sequence.py | token2one_hot | def token2one_hot(tvec, vocab_size):
"""
Note: everything out of the vucabulary is transformed into `np.zeros(vocab_size)`
"""
arr = np.zeros((len(tvec), vocab_size))
tvec_range = np.arange(len(tvec))
tvec = np.asarray(tvec)
arr[tvec_range[tvec >= 0], tvec[tvec >= 0]] = 1
return arr | python | def token2one_hot(tvec, vocab_size):
"""
Note: everything out of the vucabulary is transformed into `np.zeros(vocab_size)`
"""
arr = np.zeros((len(tvec), vocab_size))
tvec_range = np.arange(len(tvec))
tvec = np.asarray(tvec)
arr[tvec_range[tvec >= 0], tvec[tvec >= 0]] = 1
return arr | Note: everything out of the vucabulary is transformed into `np.zeros(vocab_size)` | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/preprocessing/sequence.py#L82-L91 |
gagneurlab/concise | concise/preprocessing/sequence.py | encodeSequence | 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 | 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... | 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 "words" to use as the vocabulary. Can be strings of length>0,
but all need to have the same length. For DNA, this is: ["A", "C", "G", "T"]... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/preprocessing/sequence.py#L94-L141 |
gagneurlab/concise | concise/preprocessing/sequence.py | encodeDNA | 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 | 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. ... | 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. If None don't trim.
Note that trims wrt the align p... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/preprocessing/sequence.py#L144-L196 |
gagneurlab/concise | concise/preprocessing/sequence.py | encodeRNA | 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 | 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,
... | Convert the RNA sequence into 1-hot-encoding numpy array as for encodeDNA | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/preprocessing/sequence.py#L199-L208 |
gagneurlab/concise | concise/preprocessing/sequence.py | encodeCodon | 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 | 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... | 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 encoding.
maxlen: Maximum sequence length. See `pad_sequences` for more detail
seq_align: How to a... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/preprocessing/sequence.py#L211-L240 |
gagneurlab/concise | concise/preprocessing/sequence.py | encodeAA | 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 | 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 ... | 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 to align the sequences of variable lengths. See `pad_sequences` for more detail
... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/preprocessing/sequence.py#L243-L261 |
gagneurlab/concise | concise/preprocessing/sequence.py | pad_sequences | def pad_sequences(sequence_vec, maxlen=None, align="end", value="N"):
"""Pad and/or trim a list of sequences to have common length. Procedure:
1. Pad the sequence with N's or any other string or list element (`value`)
2. Subset the sequence
# Note
See also: https://keras.io/preprocessi... | python | def pad_sequences(sequence_vec, maxlen=None, align="end", value="N"):
"""Pad and/or trim a list of sequences to have common length. Procedure:
1. Pad the sequence with N's or any other string or list element (`value`)
2. Subset the sequence
# Note
See also: https://keras.io/preprocessi... | Pad and/or trim a list of sequences to have common length. Procedure:
1. Pad the sequence with N's or any other string or list element (`value`)
2. Subset the sequence
# Note
See also: https://keras.io/preprocessing/sequence/
Aplicable also for lists of characters
# Arguments
... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/preprocessing/sequence.py#L264-L365 |
gagneurlab/concise | concise/utils/position.py | extract_landmarks | def extract_landmarks(gtf, landmarks=ALL_LANDMARKS):
"""Given an gene annotation GFF/GTF file,
# Arguments
gtf: File path or a loaded `pd.DataFrame` with columns:
seqname, feature, start, end, strand
landmarks: list or a dictionary of landmark extractors (function or name)
# Note
... | python | def extract_landmarks(gtf, landmarks=ALL_LANDMARKS):
"""Given an gene annotation GFF/GTF file,
# Arguments
gtf: File path or a loaded `pd.DataFrame` with columns:
seqname, feature, start, end, strand
landmarks: list or a dictionary of landmark extractors (function or name)
# Note
... | Given an gene annotation GFF/GTF file,
# Arguments
gtf: File path or a loaded `pd.DataFrame` with columns:
seqname, feature, start, end, strand
landmarks: list or a dictionary of landmark extractors (function or name)
# Note
When landmark extractor names are used, they have to be i... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/utils/position.py#L16-L48 |
gagneurlab/concise | concise/utils/position.py | _validate_pos | 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 | 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... | Validates the returned positional object | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/utils/position.py#L131-L139 |
gagneurlab/concise | concise/utils/tf_helper.py | huber_loss | def huber_loss(tensor, k=1, scope=None):
"""Define a huber loss https://en.wikipedia.org/wiki/Huber_loss
tensor: tensor to regularize.
k: value of k in the huber loss
scope: Optional scope for op_scope.
Huber loss:
f(x) = if |x| <= k:
0.5 * x^2
else:
... | python | def huber_loss(tensor, k=1, scope=None):
"""Define a huber loss https://en.wikipedia.org/wiki/Huber_loss
tensor: tensor to regularize.
k: value of k in the huber loss
scope: Optional scope for op_scope.
Huber loss:
f(x) = if |x| <= k:
0.5 * x^2
else:
... | Define a huber loss https://en.wikipedia.org/wiki/Huber_loss
tensor: tensor to regularize.
k: value of k in the huber loss
scope: Optional scope for op_scope.
Huber loss:
f(x) = if |x| <= k:
0.5 * x^2
else:
k * |x| - 0.5 * k^2
Returns:
the L... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/utils/tf_helper.py#L26-L47 |
gagneurlab/concise | concise/data/attract.py | get_metadata | def get_metadata():
"""
Get pandas.DataFrame with metadata about the Attract PWM's. Columns:
- PWM_id (id of the PWM - pass to get_pwm_list() for getting the pwm
- Gene_name
- Gene_id
- Mutated (if the target gene is mutated)
- Organism
- Motif (concsensus motif)
- Len (lenght o... | python | def get_metadata():
"""
Get pandas.DataFrame with metadata about the Attract PWM's. Columns:
- PWM_id (id of the PWM - pass to get_pwm_list() for getting the pwm
- Gene_name
- Gene_id
- Mutated (if the target gene is mutated)
- Organism
- Motif (concsensus motif)
- Len (lenght o... | Get pandas.DataFrame with metadata about the Attract PWM's. Columns:
- PWM_id (id of the PWM - pass to get_pwm_list() for getting the pwm
- Gene_name
- Gene_id
- Mutated (if the target gene is mutated)
- Organism
- Motif (concsensus motif)
- Len (lenght of the motif)
- Experiment_de... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/data/attract.py#L11-L35 |
gagneurlab/concise | concise/data/attract.py | get_pwm_list | 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 | 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... | 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` instances. | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/data/attract.py#L38-L51 |
gagneurlab/concise | concise/losses.py | mask_loss | 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 | 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... | 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 version of the `loss`
# Example
```python
... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/losses.py#L9-L36 |
gagneurlab/concise | concise/effects/gradient.py | gradient_pred | def gradient_pred(model, ref, ref_rc, alt, alt_rc, mutation_positions, out_annotation_all_outputs,
output_filter_mask=None, out_annotation=None):
"""Gradient-based (saliency) variant effect prediction
Based on the idea of [saliency maps](https://arxiv.org/pdf/1312.6034.pdf) the gradient-based... | python | def gradient_pred(model, ref, ref_rc, alt, alt_rc, mutation_positions, out_annotation_all_outputs,
output_filter_mask=None, out_annotation=None):
"""Gradient-based (saliency) variant effect prediction
Based on the idea of [saliency maps](https://arxiv.org/pdf/1312.6034.pdf) the gradient-based... | Gradient-based (saliency) variant effect prediction
Based on the idea of [saliency maps](https://arxiv.org/pdf/1312.6034.pdf) the gradient-based prediction of
variant effects uses the `gradient` function of the Keras backend to estimate the importance of a variant
for a given output. This value is then mul... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/effects/gradient.py#L230-L319 |
gagneurlab/concise | concise/data/hocomoco.py | get_pwm_list | 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 | 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... | 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` instances. | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/data/hocomoco.py#L43-L56 |
gagneurlab/concise | concise/legacy/concise.py | Concise.get_weights | def get_weights(self):
"""
Returns:
dict: Model's trained weights.
"""
if self.is_trained() is False:
# print("Model not fitted yet. Use object.fit() to fit the model.")
return None
var_res = self._var_res
weights = self._var_res_to_we... | python | def get_weights(self):
"""
Returns:
dict: Model's trained weights.
"""
if self.is_trained() is False:
# print("Model not fitted yet. Use object.fit() to fit the model.")
return None
var_res = self._var_res
weights = self._var_res_to_we... | Returns:
dict: Model's trained weights. | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L412-L427 |
gagneurlab/concise | concise/legacy/concise.py | Concise._var_res_to_weights | 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 | 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 = ... | Get model weights | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L436-L472 |
gagneurlab/concise | concise/legacy/concise.py | Concise._get_var_res | 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 | 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... | Get the weights from our graph | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L519-L532 |
gagneurlab/concise | concise/legacy/concise.py | Concise._convert_to_var | 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 | 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():
... | Create tf.Variables from a list of numpy arrays
var_res: dictionary of numpy arrays with the key names corresponding to var | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L534-L547 |
gagneurlab/concise | concise/legacy/concise.py | Concise.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 | 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... | 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_feat: Numpy (float) array of shape :code:`(N, D)`. Feature design matrix storing :code:`N` training samples and :code:`D` features
... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L554-L640 |
gagneurlab/concise | concise/legacy/concise.py | Concise._predict_in_session | def _predict_in_session(self, sess, other_var, X_feat, X_seq, variable="y_pred"):
"""
Predict y (or any other variable) from inside the tf session. Variable has to be in other_var
"""
# other_var["tf_X_seq"]: X_seq, tf_y: y,
feed_dict = {other_var["tf_X_feat"]: X_feat,
... | python | def _predict_in_session(self, sess, other_var, X_feat, X_seq, variable="y_pred"):
"""
Predict y (or any other variable) from inside the tf session. Variable has to be in other_var
"""
# other_var["tf_X_seq"]: X_seq, tf_y: y,
feed_dict = {other_var["tf_X_feat"]: X_feat,
... | Predict y (or any other variable) from inside the tf session. Variable has to be in other_var | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L642-L651 |
gagneurlab/concise | concise/legacy/concise.py | Concise._accuracy_in_session | 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 | 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) | Compute the accuracy from inside the tf session | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L653-L658 |
gagneurlab/concise | concise/legacy/concise.py | Concise._train_lbfgs | def _train_lbfgs(self, X_feat_train, X_seq_train, y_train,
X_feat_valid, X_seq_valid, y_valid,
graph, var, other_var,
early_stop_patience=None,
n_cores=3):
"""
Train the model actual model
Updates weights / vari... | python | def _train_lbfgs(self, X_feat_train, X_seq_train, y_train,
X_feat_valid, X_seq_valid, y_valid,
graph, var, other_var,
early_stop_patience=None,
n_cores=3):
"""
Train the model actual model
Updates weights / vari... | Train the model actual model
Updates weights / variables, computes and returns the training and validation accuracy | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L660-L782 |
gagneurlab/concise | concise/legacy/concise.py | Concise.predict | def predict(self, X_feat, X_seq):
"""
Predict the response variable :py:attr:`y` for new input data (:py:attr:`X_feat`, :py:attr:`X_seq`).
Args:
X_feat: Feature design matrix. Same format as :py:attr:`X_feat` in :py:meth:`train`
X_seq: Sequenc design matrix. Same format... | python | def predict(self, X_feat, X_seq):
"""
Predict the response variable :py:attr:`y` for new input data (:py:attr:`X_feat`, :py:attr:`X_seq`).
Args:
X_feat: Feature design matrix. Same format as :py:attr:`X_feat` in :py:meth:`train`
X_seq: Sequenc design matrix. Same format... | Predict the response variable :py:attr:`y` for new input data (:py:attr:`X_feat`, :py:attr:`X_seq`).
Args:
X_feat: Feature design matrix. Same format as :py:attr:`X_feat` in :py:meth:`train`
X_seq: Sequenc design matrix. Same format as :py:attr:`X_seq` in :py:meth:`train` | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L922-L934 |
gagneurlab/concise | concise/legacy/concise.py | Concise._get_other_var | def _get_other_var(self, X_feat, X_seq, variable="y_pred"):
"""
Get the value of a variable from other_vars (from a tf-graph)
"""
if self.is_trained() is False:
print("Model not fitted yet. Use object.fit() to fit the model.")
return
# input check:
... | python | def _get_other_var(self, X_feat, X_seq, variable="y_pred"):
"""
Get the value of a variable from other_vars (from a tf-graph)
"""
if self.is_trained() is False:
print("Model not fitted yet. Use object.fit() to fit the model.")
return
# input check:
... | Get the value of a variable from other_vars (from a tf-graph) | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L936-L961 |
gagneurlab/concise | concise/legacy/concise.py | Concise.to_dict | def to_dict(self):
"""
Returns:
dict: Concise represented as a dictionary.
"""
final_res = {
"param": self._param,
"unused_param": self.unused_param,
"execution_time": self._exec_time,
"output": {"accuracy": self.get_accuracy(),... | python | def to_dict(self):
"""
Returns:
dict: Concise represented as a dictionary.
"""
final_res = {
"param": self._param,
"unused_param": self.unused_param,
"execution_time": self._exec_time,
"output": {"accuracy": self.get_accuracy(),... | Returns:
dict: Concise represented as a dictionary. | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L1003-L1017 |
gagneurlab/concise | concise/legacy/concise.py | Concise._set_var_res | 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 | 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... | Transform the weights to var_res | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L1028-L1059 |
gagneurlab/concise | concise/legacy/concise.py | Concise.from_dict | def from_dict(cls, obj_dict):
"""
Load the object from a dictionary (produced with :py:func:`Concise.to_dict`)
Returns:
Concise: Loaded Concise object.
"""
# convert the output into a proper form
obj_dict['output'] = helper.rec_dict_to_numpy_dict(obj_dict["o... | python | def from_dict(cls, obj_dict):
"""
Load the object from a dictionary (produced with :py:func:`Concise.to_dict`)
Returns:
Concise: Loaded Concise object.
"""
# convert the output into a proper form
obj_dict['output'] = helper.rec_dict_to_numpy_dict(obj_dict["o... | Load the object from a dictionary (produced with :py:func:`Concise.to_dict`)
Returns:
Concise: Loaded Concise object. | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L1062-L1098 |
gagneurlab/concise | concise/legacy/concise.py | Concise.load | def load(cls, file_path):
"""
Load the object from a JSON file (saved with :py:func:`Concise.save`).
Returns:
Concise: Loaded Concise object.
"""
# convert back to numpy
data = helper.read_json(file_path)
return Concise.from_dict(data) | python | def load(cls, file_path):
"""
Load the object from a JSON file (saved with :py:func:`Concise.save`).
Returns:
Concise: Loaded Concise object.
"""
# convert back to numpy
data = helper.read_json(file_path)
return Concise.from_dict(data) | Load the object from a JSON file (saved with :py:func:`Concise.save`).
Returns:
Concise: Loaded Concise object. | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L1101-L1111 |
gagneurlab/concise | concise/legacy/concise.py | ConciseCV._get_folds | 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 | 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'
... | Get the used CV folds | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L1149-L1180 |
gagneurlab/concise | concise/legacy/concise.py | ConciseCV.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 | 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`
... | Train the Concise model in cross-validation.
Args:
X_feat: See :py:func:`concise.Concise.train`
X_seq: See :py:func:`concise.Concise.train`
y: See :py:func:`concise.Concise.train`
id_vec: List of character id's used to differentiate the trainig samples. Returned ... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L1193-L1265 |
gagneurlab/concise | concise/legacy/concise.py | ConciseCV.get_CV_prediction | def get_CV_prediction(self):
"""
Returns:
np.ndarray: Predictions on the hold-out folds (unseen data, corresponds to :py:attr:`y`).
"""
# TODO: get it from the test_prediction ...
# test_id, prediction
# sort by test_id
predict_vec = np.zeros((self._n_... | python | def get_CV_prediction(self):
"""
Returns:
np.ndarray: Predictions on the hold-out folds (unseen data, corresponds to :py:attr:`y`).
"""
# TODO: get it from the test_prediction ...
# test_id, prediction
# sort by test_id
predict_vec = np.zeros((self._n_... | Returns:
np.ndarray: Predictions on the hold-out folds (unseen data, corresponds to :py:attr:`y`). | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L1267-L1279 |
gagneurlab/concise | concise/legacy/concise.py | ConciseCV.get_CV_accuracy | def get_CV_accuracy(self):
"""
Returns:
float: Prediction accuracy in CV.
"""
accuracy = {}
for fold, train, test in self._kf:
acc = self._cv_model[fold].get_accuracy()
accuracy[fold] = acc["test_acc_final"]
return accuracy | python | def get_CV_accuracy(self):
"""
Returns:
float: Prediction accuracy in CV.
"""
accuracy = {}
for fold, train, test in self._kf:
acc = self._cv_model[fold].get_accuracy()
accuracy[fold] = acc["test_acc_final"]
return accuracy | Returns:
float: Prediction accuracy in CV. | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L1281-L1290 |
gagneurlab/concise | concise/legacy/concise.py | ConciseCV.to_dict | def to_dict(self):
"""
Returns:
dict: ConciseCV represented as a dictionary.
"""
param = {
"n_folds": self._n_folds,
"n_rows": self._n_rows,
"use_stored_folds": self._use_stored_folds
}
if self._concise_global_model is None... | python | def to_dict(self):
"""
Returns:
dict: ConciseCV represented as a dictionary.
"""
param = {
"n_folds": self._n_folds,
"n_rows": self._n_rows,
"use_stored_folds": self._use_stored_folds
}
if self._concise_global_model is None... | Returns:
dict: ConciseCV represented as a dictionary. | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L1306-L1328 |
gagneurlab/concise | concise/legacy/concise.py | ConciseCV.from_dict | def from_dict(cls, obj_dict):
"""
Load the object from a dictionary (produced with :py:func:`ConciseCV.to_dict`)
Returns:
ConciseCV: Loaded ConciseCV object.
"""
default_model = Concise()
cvdc = ConciseCV(default_model)
cvdc._from_dict(obj_dict)
... | python | def from_dict(cls, obj_dict):
"""
Load the object from a dictionary (produced with :py:func:`ConciseCV.to_dict`)
Returns:
ConciseCV: Loaded ConciseCV object.
"""
default_model = Concise()
cvdc = ConciseCV(default_model)
cvdc._from_dict(obj_dict)
... | Load the object from a dictionary (produced with :py:func:`ConciseCV.to_dict`)
Returns:
ConciseCV: Loaded ConciseCV object. | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L1331-L1340 |
gagneurlab/concise | concise/legacy/concise.py | ConciseCV._from_dict | 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 | 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... | Initialize a model from the dictionary | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L1342-L1358 |
gagneurlab/concise | concise/legacy/concise.py | ConciseCV.load | def load(cls, file_path):
"""
Load the object from a JSON file (saved with :py:func:`ConciseCV.save`)
Returns:
ConciseCV: Loaded ConciseCV object.
"""
data = helper.read_json(file_path)
return ConciseCV.from_dict(data) | python | def load(cls, file_path):
"""
Load the object from a JSON file (saved with :py:func:`ConciseCV.save`)
Returns:
ConciseCV: Loaded ConciseCV object.
"""
data = helper.read_json(file_path)
return ConciseCV.from_dict(data) | Load the object from a JSON file (saved with :py:func:`ConciseCV.save`)
Returns:
ConciseCV: Loaded ConciseCV object. | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L1370-L1378 |
gagneurlab/concise | concise/utils/pwm.py | pwm_array2pssm_array | 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 | 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) | Convert pwm array to pssm array | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/utils/pwm.py#L239-L244 |
gagneurlab/concise | concise/utils/pwm.py | pssm_array2pwm_array | 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 | 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) | Convert pssm array to pwm array | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/utils/pwm.py#L247-L252 |
gagneurlab/concise | concise/utils/pwm.py | load_motif_db | 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 | 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... | 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
skipn_matrix: integer, number of characters to skip wh... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/utils/pwm.py#L255-L306 |
gagneurlab/concise | concise/effects/dropout.py | dropout_pred | def dropout_pred(model, ref, ref_rc, alt, alt_rc, mutation_positions, out_annotation_all_outputs,
output_filter_mask=None, out_annotation=None, dropout_iterations=30):
"""Dropout-based variant effect prediction
This method is based on the ideas in [Gal et al.](https://arxiv.org/pdf/1506.02... | python | def dropout_pred(model, ref, ref_rc, alt, alt_rc, mutation_positions, out_annotation_all_outputs,
output_filter_mask=None, out_annotation=None, dropout_iterations=30):
"""Dropout-based variant effect prediction
This method is based on the ideas in [Gal et al.](https://arxiv.org/pdf/1506.02... | Dropout-based variant effect prediction
This method is based on the ideas in [Gal et al.](https://arxiv.org/pdf/1506.02142.pdf) where dropout
layers are also actived in the model prediction phase in order to estimate model uncertainty. The
advantage of this method is that instead of a point est... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/effects/dropout.py#L164-L287 |
gagneurlab/concise | concise/utils/fasta.py | iter_fasta | 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 | 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... | 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 header, seq in fasta:
... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/utils/fasta.py#L11-L39 |
gagneurlab/concise | concise/utils/fasta.py | write_fasta | 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 | 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:
... | 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` | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/utils/fasta.py#L42-L57 |
gagneurlab/concise | concise/preprocessing/structure.py | run_RNAplfold | def run_RNAplfold(input_fasta, tmpdir, W=240, L=160, U=1):
"""
Arguments:
W, Int: span - window length
L, Int, maxiumm span
U, Int, size of unpaired region
"""
profiles = RNAplfold_PROFILES_EXECUTE
for i, P in enumerate(profiles):
print("running {P}_RNAplfold... ({i}/{N... | python | def run_RNAplfold(input_fasta, tmpdir, W=240, L=160, U=1):
"""
Arguments:
W, Int: span - window length
L, Int, maxiumm span
U, Int, size of unpaired region
"""
profiles = RNAplfold_PROFILES_EXECUTE
for i, P in enumerate(profiles):
print("running {P}_RNAplfold... ({i}/{N... | Arguments:
W, Int: span - window length
L, Int, maxiumm span
U, Int, size of unpaired region | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/preprocessing/structure.py#L18-L39 |
gagneurlab/concise | concise/preprocessing/structure.py | read_RNAplfold | 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 | 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... | pad_with = with which 2ndary structure should we pad the sequence? | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/preprocessing/structure.py#L42-L69 |
gagneurlab/concise | concise/preprocessing/structure.py | encodeRNAStructure | def encodeRNAStructure(seq_vec, maxlen=None, seq_align="start",
W=240, L=160, U=1,
tmpdir="/tmp/RNAplfold/"):
"""Compute RNA secondary structure with RNAplfold implemented in
Kazan et al 2010, [doi](https://doi.org/10.1371/journal.pcbi.1000832).
# Note
... | python | def encodeRNAStructure(seq_vec, maxlen=None, seq_align="start",
W=240, L=160, U=1,
tmpdir="/tmp/RNAplfold/"):
"""Compute RNA secondary structure with RNAplfold implemented in
Kazan et al 2010, [doi](https://doi.org/10.1371/journal.pcbi.1000832).
# Note
... | Compute RNA secondary structure with RNAplfold implemented in
Kazan et al 2010, [doi](https://doi.org/10.1371/journal.pcbi.1000832).
# Note
Secondary structure is represented as the probability
to be in the following states:
- `["Pairedness", "Hairpin loop", "Internal loop", "Multi loop... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/preprocessing/structure.py#L92-L138 |
gagneurlab/concise | concise/effects/ism.py | ism | 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 | 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... | In-silico mutagenesis
Using ISM in with diff_type 'log_odds' and rc_handling 'maximum' will produce predictions as used
in [DeepSEA](http://www.nature.com/nmeth/journal/v12/n10/full/nmeth.3547.html). ISM offers two ways to
calculate the difference between the outputs created by reference and alternative se... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/effects/ism.py#L9-L84 |
gagneurlab/concise | concise/hyopt.py | _train_and_eval_single | 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 | 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... | Fit and evaluate a keras model
eval_best: if True, load the checkpointed model for evaluation | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/hyopt.py#L315-L351 |
gagneurlab/concise | concise/hyopt.py | eval_model | 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 | 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... | 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 functions
accepting arguments: `y_true`, `y_predicted`... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/hyopt.py#L354-L389 |
gagneurlab/concise | concise/hyopt.py | get_model | 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 | 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) | Feed model_fn with train_data and param | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/hyopt.py#L392-L396 |
gagneurlab/concise | concise/hyopt.py | _delete_keys | 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 | 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 | Returns a copy of dct without `keys` keys | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/hyopt.py#L701-L708 |
gagneurlab/concise | concise/hyopt.py | _mean_dict | 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 | 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()} | Compute the mean value across a list of dictionaries | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/hyopt.py#L711-L715 |
gagneurlab/concise | concise/hyopt.py | CMongoTrials.get_trial | def get_trial(self, tid):
"""Retrieve trial by tid
"""
lid = np.where(np.array(self.tids) == tid)[0][0]
return self.trials[lid] | python | def get_trial(self, tid):
"""Retrieve trial by tid
"""
lid = np.where(np.array(self.tids) == tid)[0][0]
return self.trials[lid] | Retrieve trial by tid | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/hyopt.py#L116-L120 |
gagneurlab/concise | concise/hyopt.py | CMongoTrials.count_by_state_unsynced | def count_by_state_unsynced(self, arg):
"""Extends the original object in order to inject checking
for stalled jobs and killing them if they are running for too long
"""
if self.kill_timeout is not None:
self.delete_running(self.kill_timeout)
return super(CMongoTrials... | python | def count_by_state_unsynced(self, arg):
"""Extends the original object in order to inject checking
for stalled jobs and killing them if they are running for too long
"""
if self.kill_timeout is not None:
self.delete_running(self.kill_timeout)
return super(CMongoTrials... | Extends the original object in order to inject checking
for stalled jobs and killing them if they are running for too long | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/hyopt.py#L166-L172 |
gagneurlab/concise | concise/hyopt.py | CMongoTrials.delete_running | 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 | 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
... | Delete jobs stalled in the running state for too long
timeout_last_refresh, int: number of seconds | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/hyopt.py#L174-L205 |
gagneurlab/concise | concise/hyopt.py | CMongoTrials.train_history | 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 | 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... | Get train history as pd.DataFrame | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/hyopt.py#L216-L238 |
gagneurlab/concise | concise/hyopt.py | CMongoTrials.as_df | 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 | 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
... | Return a pd.DataFrame view of the whole experiment | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/hyopt.py#L283-L311 |
gagneurlab/concise | concise/effects/snp_effects.py | effect_from_model | 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 | 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 ... | Convenience function to execute multiple effect predictions in one call
# Arguments
model: Keras model
ref: Input sequence with the reference genotype in the mutation position
ref_rc: Reverse complement of the 'ref' argument
alt: Input sequence with the alternative genotype in the m... | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/effects/snp_effects.py#L5-L53 |
bitshares/uptick | uptick/markets.py | trades | 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 | 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"]... | List trades in a market | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/markets.py#L31-L49 |
bitshares/uptick | uptick/markets.py | ticker | 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 | 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) | Show ticker of a market | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/markets.py#L56-L64 |
bitshares/uptick | uptick/markets.py | cancel | def cancel(ctx, orders, account):
""" Cancel one or multiple orders
"""
print_tx(ctx.bitshares.cancel(orders, account=account)) | python | def cancel(ctx, orders, account):
""" Cancel one or multiple orders
"""
print_tx(ctx.bitshares.cancel(orders, account=account)) | Cancel one or multiple orders | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/markets.py#L78-L81 |
bitshares/uptick | uptick/markets.py | orderbook | 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 | 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... | Show the orderbook of a particular market | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/markets.py#L88-L135 |
bitshares/uptick | uptick/markets.py | buy | 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 | 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... | Buy a specific asset at a certain rate against a base asset | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/markets.py#L153-L162 |
bitshares/uptick | uptick/markets.py | openorders | 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 | 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} {}/{}... | List open orders of an account | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/markets.py#L196-L216 |
bitshares/uptick | uptick/markets.py | cancelall | 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 | 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()) | Cancel all orders of an account in a market | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/markets.py#L225-L231 |
bitshares/uptick | uptick/markets.py | spread | 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 | 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... | 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: maximum price to place order at
:param int num: Number of orders to place
... | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/markets.py#L246-L273 |
bitshares/uptick | uptick/markets.py | borrow | def borrow(ctx, amount, symbol, ratio, account):
""" Borrow a bitasset/market-pegged asset
"""
from bitshares.dex import Dex
dex = Dex(bitshares_instance=ctx.bitshares)
print_tx(
dex.borrow(Amount(amount, symbol), collateral_ratio=ratio, account=account)
) | python | def borrow(ctx, amount, symbol, ratio, account):
""" Borrow a bitasset/market-pegged asset
"""
from bitshares.dex import Dex
dex = Dex(bitshares_instance=ctx.bitshares)
print_tx(
dex.borrow(Amount(amount, symbol), collateral_ratio=ratio, account=account)
) | Borrow a bitasset/market-pegged asset | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/markets.py#L289-L297 |
bitshares/uptick | uptick/markets.py | updateratio | 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 | 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)) | Update the collateral ratio of a call positions | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/markets.py#L312-L318 |
bitshares/uptick | uptick/markets.py | fundfeepool | def fundfeepool(ctx, symbol, amount, account):
""" Fund the fee pool of an asset
"""
print_tx(ctx.bitshares.fund_fee_pool(symbol, amount, account=account)) | python | def fundfeepool(ctx, symbol, amount, account):
""" Fund the fee pool of an asset
"""
print_tx(ctx.bitshares.fund_fee_pool(symbol, amount, account=account)) | Fund the fee pool of an asset | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/markets.py#L333-L336 |
bitshares/uptick | uptick/markets.py | bidcollateral | 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 | 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),
... | Bid for collateral in the settlement fund | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/markets.py#L353-L364 |
bitshares/uptick | uptick/markets.py | settle | def settle(ctx, symbol, amount, account):
""" Fund the fee pool of an asset
"""
print_tx(ctx.bitshares.asset_settle(Amount(amount, symbol), account=account)) | python | def settle(ctx, symbol, amount, account):
""" Fund the fee pool of an asset
"""
print_tx(ctx.bitshares.asset_settle(Amount(amount, symbol), account=account)) | Fund the fee pool of an asset | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/markets.py#L379-L382 |
bitshares/uptick | uptick/votes.py | votes | def votes(ctx, account, type):
""" List accounts vesting balances
"""
if not isinstance(type, (list, tuple)):
type = [type]
account = Account(account, full=True)
ret = {key: list() for key in Vote.types()}
for vote in account["votes"]:
t = Vote.vote_type_from_id(vote["id"])
... | python | def votes(ctx, account, type):
""" List accounts vesting balances
"""
if not isinstance(type, (list, tuple)):
type = [type]
account = Account(account, full=True)
ret = {key: list() for key in Vote.types()}
for vote in account["votes"]:
t = Vote.vote_type_from_id(vote["id"])
... | List accounts vesting balances | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/votes.py#L34-L107 |
bitshares/uptick | uptick/info.py | info | def info(ctx, objects):
""" Obtain all kinds of information
"""
if not objects:
t = [["Key", "Value"]]
info = ctx.bitshares.rpc.get_dynamic_global_properties()
for key in info:
t.append([key, info[key]])
print_table(t)
for obj in objects:
# Block
... | python | def info(ctx, objects):
""" Obtain all kinds of information
"""
if not objects:
t = [["Key", "Value"]]
info = ctx.bitshares.rpc.get_dynamic_global_properties()
for key in info:
t.append([key, info[key]])
print_table(t)
for obj in objects:
# Block
... | Obtain all kinds of information | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/info.py#L19-L103 |
bitshares/uptick | uptick/info.py | fees | def fees(ctx, currency):
""" List fees
"""
from bitsharesbase.operationids import getOperationNameForId
from bitshares.market import Market
market = Market("%s:%s" % (currency, "BTS"))
ticker = market.ticker()
if "quoteSettlement_price" in ticker:
price = ticker.get("quoteSettlement... | python | def fees(ctx, currency):
""" List fees
"""
from bitsharesbase.operationids import getOperationNameForId
from bitshares.market import Market
market = Market("%s:%s" % (currency, "BTS"))
ticker = market.ticker()
if "quoteSettlement_price" in ticker:
price = ticker.get("quoteSettlement... | List fees | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/info.py#L110-L147 |
bitshares/uptick | uptick/htlc.py | create | def create(ctx, to, amount, symbol, secret, hash, account, expiration):
""" Create an HTLC contract
"""
ctx.blockchain.blocking = True
tx = ctx.blockchain.htlc_create(
Amount(amount, symbol),
to,
secret,
hash_type=hash,
expiration=expiration,
account=accou... | python | def create(ctx, to, amount, symbol, secret, hash, account, expiration):
""" Create an HTLC contract
"""
ctx.blockchain.blocking = True
tx = ctx.blockchain.htlc_create(
Amount(amount, symbol),
to,
secret,
hash_type=hash,
expiration=expiration,
account=accou... | Create an HTLC contract | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/htlc.py#L28-L45 |
bitshares/uptick | uptick/htlc.py | redeem | def redeem(ctx, htlc_id, secret, account):
""" Redeem an HTLC contract
"""
print_tx(ctx.blockchain.htlc_redeem(htlc_id, secret, account=account)) | python | def redeem(ctx, htlc_id, secret, account):
""" Redeem an HTLC contract
"""
print_tx(ctx.blockchain.htlc_redeem(htlc_id, secret, account=account)) | Redeem an HTLC contract | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/htlc.py#L57-L60 |
pasztorpisti/py-flags | src/flags.py | unique | def unique(flags_class):
""" A decorator for flags classes to forbid flag aliases. """
if not is_flags_class_final(flags_class):
raise TypeError('unique check can be applied only to flags classes that have members')
if not flags_class.__member_aliases__:
return flags_class
aliases = ', '... | python | def unique(flags_class):
""" A decorator for flags classes to forbid flag aliases. """
if not is_flags_class_final(flags_class):
raise TypeError('unique check can be applied only to flags classes that have members')
if not flags_class.__member_aliases__:
return flags_class
aliases = ', '... | A decorator for flags classes to forbid flag aliases. | https://github.com/pasztorpisti/py-flags/blob/bc48adb5edd7340ea1a686622d7993b4bcf4bfc2/src/flags.py#L26-L33 |
pasztorpisti/py-flags | src/flags.py | unique_bits | def unique_bits(flags_class):
""" A decorator for flags classes to forbid declaring flags with overlapping bits. """
flags_class = unique(flags_class)
other_bits = 0
for name, member in flags_class.__members_without_aliases__.items():
bits = int(member)
if other_bits & bits:
... | python | def unique_bits(flags_class):
""" A decorator for flags classes to forbid declaring flags with overlapping bits. """
flags_class = unique(flags_class)
other_bits = 0
for name, member in flags_class.__members_without_aliases__.items():
bits = int(member)
if other_bits & bits:
... | A decorator for flags classes to forbid declaring flags with overlapping bits. | https://github.com/pasztorpisti/py-flags/blob/bc48adb5edd7340ea1a686622d7993b4bcf4bfc2/src/flags.py#L36-L47 |
pasztorpisti/py-flags | src/flags.py | process_inline_members_definition | def process_inline_members_definition(members):
"""
:param members: this can be any of the following:
- a string containing a space and/or comma separated list of names: e.g.:
"item1 item2 item3" OR "item1,item2,item3" OR "item1, item2, item3"
- tuple/list/Set of strings (names)
- Mapping of (... | python | def process_inline_members_definition(members):
"""
:param members: this can be any of the following:
- a string containing a space and/or comma separated list of names: e.g.:
"item1 item2 item3" OR "item1,item2,item3" OR "item1, item2, item3"
- tuple/list/Set of strings (names)
- Mapping of (... | :param members: this can be any of the following:
- a string containing a space and/or comma separated list of names: e.g.:
"item1 item2 item3" OR "item1,item2,item3" OR "item1, item2, item3"
- tuple/list/Set of strings (names)
- Mapping of (name, data) pairs
- any kind of iterable that yields (na... | https://github.com/pasztorpisti/py-flags/blob/bc48adb5edd7340ea1a686622d7993b4bcf4bfc2/src/flags.py#L95-L112 |
pasztorpisti/py-flags | src/flags.py | FlagsMeta.process_member_definitions | def process_member_definitions(cls, member_definitions):
"""
The incoming member_definitions contains the class attributes (with their values) that are
used to define the flag members. This method can do anything to the incoming list and has to
return a final set of flag definitions that... | python | def process_member_definitions(cls, member_definitions):
"""
The incoming member_definitions contains the class attributes (with their values) that are
used to define the flag members. This method can do anything to the incoming list and has to
return a final set of flag definitions that... | The incoming member_definitions contains the class attributes (with their values) that are
used to define the flag members. This method can do anything to the incoming list and has to
return a final set of flag definitions that assigns bits to the members. The returned member
definitions can be ... | https://github.com/pasztorpisti/py-flags/blob/bc48adb5edd7340ea1a686622d7993b4bcf4bfc2/src/flags.py#L426-L458 |
pasztorpisti/py-flags | src/flags.py | Flags.from_simple_str | def from_simple_str(cls, s):
""" Accepts only the output of to_simple_str(). The output of __str__() is invalid as input. """
if not isinstance(s, str):
raise TypeError("Expected an str instance, received %r" % (s,))
return cls(cls.bits_from_simple_str(s)) | python | def from_simple_str(cls, s):
""" Accepts only the output of to_simple_str(). The output of __str__() is invalid as input. """
if not isinstance(s, str):
raise TypeError("Expected an str instance, received %r" % (s,))
return cls(cls.bits_from_simple_str(s)) | Accepts only the output of to_simple_str(). The output of __str__() is invalid as input. | https://github.com/pasztorpisti/py-flags/blob/bc48adb5edd7340ea1a686622d7993b4bcf4bfc2/src/flags.py#L663-L667 |
pasztorpisti/py-flags | src/flags.py | Flags.from_str | def from_str(cls, s):
""" Accepts both the output of to_simple_str() and __str__(). """
if not isinstance(s, str):
raise TypeError("Expected an str instance, received %r" % (s,))
return cls(cls.bits_from_str(s)) | python | def from_str(cls, s):
""" Accepts both the output of to_simple_str() and __str__(). """
if not isinstance(s, str):
raise TypeError("Expected an str instance, received %r" % (s,))
return cls(cls.bits_from_str(s)) | Accepts both the output of to_simple_str() and __str__(). | https://github.com/pasztorpisti/py-flags/blob/bc48adb5edd7340ea1a686622d7993b4bcf4bfc2/src/flags.py#L670-L674 |
pasztorpisti/py-flags | src/flags.py | Flags.bits_from_str | def bits_from_str(cls, s):
""" Converts the output of __str__ into an integer. """
try:
if len(s) <= len(cls.__name__) or not s.startswith(cls.__name__):
return cls.bits_from_simple_str(s)
c = s[len(cls.__name__)]
if c == '(':
if not s.... | python | def bits_from_str(cls, s):
""" Converts the output of __str__ into an integer. """
try:
if len(s) <= len(cls.__name__) or not s.startswith(cls.__name__):
return cls.bits_from_simple_str(s)
c = s[len(cls.__name__)]
if c == '(':
if not s.... | Converts the output of __str__ into an integer. | https://github.com/pasztorpisti/py-flags/blob/bc48adb5edd7340ea1a686622d7993b4bcf4bfc2/src/flags.py#L689-L710 |
bitshares/uptick | uptick/feed.py | newfeed | def newfeed(ctx, symbol, price, market, cer, mssr, mcr, account):
""" Publish a price feed!
Examples:
\b
uptick newfeed USD 0.01 USD/BTS
uptick newfeed USD 100 BTS/USD
Core Exchange Rate (CER)
\b
If no CER is provided, the cer will be the same a... | python | def newfeed(ctx, symbol, price, market, cer, mssr, mcr, account):
""" Publish a price feed!
Examples:
\b
uptick newfeed USD 0.01 USD/BTS
uptick newfeed USD 100 BTS/USD
Core Exchange Rate (CER)
\b
If no CER is provided, the cer will be the same a... | Publish a price feed!
Examples:
\b
uptick newfeed USD 0.01 USD/BTS
uptick newfeed USD 100 BTS/USD
Core Exchange Rate (CER)
\b
If no CER is provided, the cer will be the same as the settlement price
with a 5% premium (Only if the 'market' is ... | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/feed.py#L42-L67 |
bitshares/uptick | uptick/feed.py | feeds | def feeds(ctx, assets, pricethreshold, maxage):
""" Price Feed Overview
"""
import builtins
witnesses = Witnesses(bitshares_instance=ctx.bitshares)
def test_price(p, ref):
if math.fabs(float(p / ref) - 1.0) > pricethreshold / 100.0:
return click.style(str(p), fg="red")
... | python | def feeds(ctx, assets, pricethreshold, maxage):
""" Price Feed Overview
"""
import builtins
witnesses = Witnesses(bitshares_instance=ctx.bitshares)
def test_price(p, ref):
if math.fabs(float(p / ref) - 1.0) > pricethreshold / 100.0:
return click.style(str(p), fg="red")
... | Price Feed Overview | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/feed.py#L78-L179 |
bitshares/uptick | uptick/ui.py | print_table | def print_table(*args, **kwargs):
"""
if csv:
import csv
t = csv.writer(sys.stdout, delimiter=";")
t.writerow(header)
else:
t = PrettyTable(header)
t.align = "r"
t.align["details"] = "l"
"""
t = format_table(*args, **kwargs)
click.echo(t) | python | def print_table(*args, **kwargs):
"""
if csv:
import csv
t = csv.writer(sys.stdout, delimiter=";")
t.writerow(header)
else:
t = PrettyTable(header)
t.align = "r"
t.align["details"] = "l"
"""
t = format_table(*args, **kwargs)
click.echo(t) | if csv:
import csv
t = csv.writer(sys.stdout, delimiter=";")
t.writerow(header)
else:
t = PrettyTable(header)
t.align = "r"
t.align["details"] = "l" | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/ui.py#L125-L137 |
bitshares/uptick | uptick/rpc.py | rpc | def rpc(ctx, call, arguments, api):
""" Construct RPC call directly
\b
You can specify which API to send the call to:
uptick rpc --api assets
You can also specify lists using
uptick rpc get_objects "['2.0.0', '2.1.0']"
"""
try:
data = list(eval(d) ... | python | def rpc(ctx, call, arguments, api):
""" Construct RPC call directly
\b
You can specify which API to send the call to:
uptick rpc --api assets
You can also specify lists using
uptick rpc get_objects "['2.0.0', '2.1.0']"
"""
try:
data = list(eval(d) ... | Construct RPC call directly
\b
You can specify which API to send the call to:
uptick rpc --api assets
You can also specify lists using
uptick rpc get_objects "['2.0.0', '2.1.0']" | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/rpc.py#L16-L33 |
bitshares/uptick | uptick/committee.py | approvecommittee | def approvecommittee(ctx, members, account):
""" Approve committee member(s)
"""
print_tx(ctx.bitshares.approvecommittee(members, account=account)) | python | def approvecommittee(ctx, members, account):
""" Approve committee member(s)
"""
print_tx(ctx.bitshares.approvecommittee(members, account=account)) | Approve committee member(s) | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/committee.py#L18-L21 |
bitshares/uptick | uptick/committee.py | disapprovecommittee | def disapprovecommittee(ctx, members, account):
""" Disapprove committee member(s)
"""
print_tx(ctx.bitshares.disapprovecommittee(members, account=account)) | python | def disapprovecommittee(ctx, members, account):
""" Disapprove committee member(s)
"""
print_tx(ctx.bitshares.disapprovecommittee(members, account=account)) | Disapprove committee member(s) | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/committee.py#L35-L38 |
bitshares/uptick | uptick/committee.py | createcommittee | def createcommittee(ctx, url, account):
""" Setup a committee account for your account
"""
print_tx(ctx.bitshares.create_committee_member(url, account=account)) | python | def createcommittee(ctx, url, account):
""" Setup a committee account for your account
"""
print_tx(ctx.bitshares.create_committee_member(url, account=account)) | Setup a committee account for your account | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/committee.py#L52-L55 |
bitshares/uptick | uptick/cli.py | set | def set(ctx, key, value):
""" Set configuration parameters
"""
if key == "default_account" and value[0] == "@":
value = value[1:]
ctx.bitshares.config[key] = value | python | def set(ctx, key, value):
""" Set configuration parameters
"""
if key == "default_account" and value[0] == "@":
value = value[1:]
ctx.bitshares.config[key] = value | Set configuration parameters | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/cli.py#L40-L45 |
bitshares/uptick | uptick/cli.py | configuration | def configuration(ctx):
""" Show configuration variables
"""
t = [["Key", "Value"]]
for key in ctx.bitshares.config:
t.append([key, ctx.bitshares.config[key]])
print_table(t) | python | def configuration(ctx):
""" Show configuration variables
"""
t = [["Key", "Value"]]
for key in ctx.bitshares.config:
t.append([key, ctx.bitshares.config[key]])
print_table(t) | Show configuration variables | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/cli.py#L51-L57 |
bitshares/uptick | uptick/cli.py | sign | def sign(ctx, filename):
""" Sign a json-formatted transaction
"""
if filename:
tx = filename.read()
else:
tx = sys.stdin.read()
tx = TransactionBuilder(eval(tx), bitshares_instance=ctx.bitshares)
tx.appendMissingSignatures()
tx.sign()
print_tx(tx.json()) | python | def sign(ctx, filename):
""" Sign a json-formatted transaction
"""
if filename:
tx = filename.read()
else:
tx = sys.stdin.read()
tx = TransactionBuilder(eval(tx), bitshares_instance=ctx.bitshares)
tx.appendMissingSignatures()
tx.sign()
print_tx(tx.json()) | Sign a json-formatted transaction | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/cli.py#L65-L75 |
bitshares/uptick | uptick/cli.py | randomwif | def randomwif(prefix, num):
""" Obtain a random private/public key pair
"""
from bitsharesbase.account import PrivateKey
t = [["wif", "pubkey"]]
for n in range(0, num):
wif = PrivateKey()
t.append([str(wif), format(wif.pubkey, prefix)])
print_table(t) | python | def randomwif(prefix, num):
""" Obtain a random private/public key pair
"""
from bitsharesbase.account import PrivateKey
t = [["wif", "pubkey"]]
for n in range(0, num):
wif = PrivateKey()
t.append([str(wif), format(wif.pubkey, prefix)])
print_table(t) | Obtain a random private/public key pair | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/cli.py#L97-L106 |
bitshares/uptick | uptick/witness.py | approvewitness | def approvewitness(ctx, witnesses, account):
""" Approve witness(es)
"""
print_tx(ctx.bitshares.approvewitness(witnesses, account=account)) | python | def approvewitness(ctx, witnesses, account):
""" Approve witness(es)
"""
print_tx(ctx.bitshares.approvewitness(witnesses, account=account)) | Approve witness(es) | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/witness.py#L20-L23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.