sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def rdlevenshtein_norm(source, target):
"""Calculates the normalized restricted Damerau-Levenshtein distance
(a.k.a. the normalized optimal string alignment distance) between two
string arguments. The result will be a float in the range [0.0, 1.0], with
1.0 signifying the maximum distance between string... | Calculates the normalized restricted Damerau-Levenshtein distance
(a.k.a. the normalized optimal string alignment distance) between two
string arguments. The result will be a float in the range [0.0, 1.0], with
1.0 signifying the maximum distance between strings with these lengths | entailment |
def _levenshtein_compute(source, target, rd_flag):
"""Computes the Levenshtein
(https://en.wikipedia.org/wiki/Levenshtein_distance)
and restricted Damerau-Levenshtein
(https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)
distances between two Unicode strings with given lengths using t... | Computes the Levenshtein
(https://en.wikipedia.org/wiki/Levenshtein_distance)
and restricted Damerau-Levenshtein
(https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)
distances between two Unicode strings with given lengths using the
Wagner-Fischer algorithm
(https://en.wikipedia.... | entailment |
def main():
"""The main entry point."""
if sys.version_info < (2, 7):
sys.exit('crispy requires at least Python 2.7')
elif sys.version_info[0] == 3 and sys.version_info < (3, 4):
sys.exit('crispy requires at least Python 3.4')
kwargs = dict(
name='crispy',
version=get_ve... | The main entry point. | entailment |
def loadFromDisk(self, calculation):
"""
Read the spectra from the files generated by Quanty and store them
as a list of spectum objects.
"""
suffixes = {
'Isotropic': 'iso',
'Circular Dichroism (R-L)': 'cd',
'Right Polarized (R)': 'r',
... | Read the spectra from the files generated by Quanty and store them
as a list of spectum objects. | entailment |
def populateWidget(self):
"""
Populate the widget using data stored in the state
object. The order in which the individual widgets are populated
follows their arrangment.
The models are recreated every time the function is called.
This might seem to be an overkill, but i... | Populate the widget using data stored in the state
object. The order in which the individual widgets are populated
follows their arrangment.
The models are recreated every time the function is called.
This might seem to be an overkill, but in practice it is very fast.
Don't try ... | entailment |
def updateResultsView(self, index):
"""
Update the selection to contain only the result specified by
the index. This should be the last index of the model. Finally updade
the context menu.
The selectionChanged signal is used to trigger the update of
the Quanty dock widge... | Update the selection to contain only the result specified by
the index. This should be the last index of the model. Finally updade
the context menu.
The selectionChanged signal is used to trigger the update of
the Quanty dock widget and result details dialog.
:param index: Inde... | entailment |
def updatePlotWidget(self):
"""Updating the plotting widget should not require any information
about the current state of the widget."""
pw = self.getPlotWidget()
pw.reset()
results = self.resultsModel.getCheckedItems()
for result in results:
if isinstance(r... | Updating the plotting widget should not require any information
about the current state of the widget. | entailment |
def row(self):
"""Return the row of the child."""
if self.parent is not None:
children = self.parent.getChildren()
# The index method of the list object.
return children.index(self)
else:
return 0 | Return the row of the child. | entailment |
def index(self, row, column, parent=QModelIndex()):
"""Return the index of the item in the model specified by the
given row, column, and parent index.
"""
if parent is not None and not parent.isValid():
parentItem = self.rootItem
else:
parentItem = self.it... | Return the index of the item in the model specified by the
given row, column, and parent index. | entailment |
def parent(self, index):
"""Return the index of the parent for a given index of the
child. Unfortunately, the name of the method has to be parent,
even though a more verbose name like parentIndex, would avoid
confusion about what parent actually is - an index or an item.
"""
... | Return the index of the parent for a given index of the
child. Unfortunately, the name of the method has to be parent,
even though a more verbose name like parentIndex, would avoid
confusion about what parent actually is - an index or an item. | entailment |
def rowCount(self, parentIndex):
"""Return the number of rows under the given parent. When the
parentIndex is valid, rowCount() returns the number of children
of the parent. For this it uses item() method to extract the
parentItem from the parentIndex, and calls the childCount() of
... | Return the number of rows under the given parent. When the
parentIndex is valid, rowCount() returns the number of children
of the parent. For this it uses item() method to extract the
parentItem from the parentIndex, and calls the childCount() of
the item to get number of children. | entailment |
def data(self, index, role):
"""Return role specific data for the item referred by
index.column()."""
if not index.isValid():
return
item = self.item(index)
column = index.column()
value = item.getItemData(column)
if role == Qt.DisplayRole:
... | Return role specific data for the item referred by
index.column(). | entailment |
def setData(self, index, value, role):
"""Set the role data for the item at index to value."""
if not index.isValid():
return False
item = self.item(index)
column = index.column()
if role == Qt.EditRole:
items = list()
items.append(item)
... | Set the role data for the item at index to value. | entailment |
def flags(self, index):
"""Return the active flags for the given index. Add editable
flag to items other than the first column.
"""
activeFlags = (Qt.ItemIsEnabled | Qt.ItemIsSelectable |
Qt.ItemIsUserCheckable)
item = self.item(index)
column = ind... | Return the active flags for the given index. Add editable
flag to items other than the first column. | entailment |
def _getModelData(self, modelData, parentItem=None):
"""Return the data contained in the model."""
if parentItem is None:
parentItem = self.rootItem
for item in parentItem.getChildren():
key = item.getItemData(0)
if item.childCount():
modelDat... | Return the data contained in the model. | entailment |
def getNodesCheckState(self, parentItem=None):
"""Return the check state (disabled, tristate, enable) of all items
belonging to a parent.
"""
if parentItem is None:
parentItem = self.rootItem
checkStates = odict()
children = parentItem.getChildren()
... | Return the check state (disabled, tristate, enable) of all items
belonging to a parent. | entailment |
def calc_hexversion(major=0, minor=0, micro=0, releaselevel='dev', serial=0):
"""Calculate the hexadecimal version number from the tuple version_info:
:param major: integer
:param minor: integer
:param micro: integer
:param relev: integer or string
:param serial: integer
:return: integerm a... | Calculate the hexadecimal version number from the tuple version_info:
:param major: integer
:param minor: integer
:param micro: integer
:param relev: integer or string
:param serial: integer
:return: integerm always increasing with revision numbers | entailment |
def _contextMenu(self, pos):
"""Handle plot area customContextMenuRequested signal.
:param QPoint pos: Mouse position relative to plot area
"""
# Create the context menu.
menu = QMenu(self)
menu.addAction(self._zoomBackAction)
# Displaying the context menu at th... | Handle plot area customContextMenuRequested signal.
:param QPoint pos: Mouse position relative to plot area | entailment |
def convolve_fft(array, kernel):
"""
Convolve an array with a kernel using FFT.
Implemntation based on the convolve_fft function from astropy.
https://github.com/astropy/astropy/blob/master/astropy/convolution/convolve.py
"""
array = np.asarray(array, dtype=np.complex)
kernel = np.asarray(... | Convolve an array with a kernel using FFT.
Implemntation based on the convolve_fft function from astropy.
https://github.com/astropy/astropy/blob/master/astropy/convolution/convolve.py | entailment |
def diagonalize(self):
'''Diagonalize the tensor.'''
self.eigvals, self.eigvecs = np.linalg.eig(
(self.tensor.transpose() + self.tensor) / 2.0)
self.eigvals = np.diag(np.dot(
np.dot(self.eigvecs.transpose(), self.tensor), self.eigvecs)) | Diagonalize the tensor. | entailment |
def euler_angles_and_eigenframes(self):
'''Calculate the Euler angles only if the rotation matrix
(eigenframe) has positive determinant.'''
signs = np.array([[1, 1, 1], [-1, 1, 1], [1, -1, 1],
[1, 1, -1], [-1, -1, 1], [-1, 1, -1],
[1, -1, -1... | Calculate the Euler angles only if the rotation matrix
(eigenframe) has positive determinant. | entailment |
def _skip_lines(self, n):
'''Skip a number of lines from the output.'''
for i in range(n):
self.line = next(self.output)
return self.line | Skip a number of lines from the output. | entailment |
def _parse_tensor(self, indices=False):
'''Parse a tensor.'''
if indices:
self.line = self._skip_lines(1)
tensor = np.zeros((3, 3))
for i in range(3):
tokens = self.line.split()
if indices:
tensor[i][0] = float(tokens[1])
... | Parse a tensor. | entailment |
def parse(self):
'''Iterate over the lines and extract the required data.'''
for self.line in self.output:
# Parse general data: charge, multiplicity, coordinates, etc.
self.index = 0
if self.line[1:13] == 'Total Charge':
tokens = self.line.split()
... | Iterate over the lines and extract the required data. | entailment |
def __validate(self, target, value, oldvalue, initiator):
""" Method executed when the event 'set' is triggered.
:param target: Object triggered
:param value: New value
:param oldvalue: Previous value
:param initiator: Column modified
:return: :raise ValidateError:
... | Method executed when the event 'set' is triggered.
:param target: Object triggered
:param value: New value
:param oldvalue: Previous value
:param initiator: Column modified
:return: :raise ValidateError: | entailment |
def __create_event(self):
""" Create an SQLAlchemy event listening the 'set' in a particular column.
:rtype : object
"""
if not event.contains(self.field, 'set', self.__validate):
event.listen(self.field, 'set', self.__validate, retval=True) | Create an SQLAlchemy event listening the 'set' in a particular column.
:rtype : object | entailment |
def stop(self):
""" Remove the listener to stop the validation
"""
if event.contains(self.field, 'set', self.__validate):
event.remove(self.field, 'set', self.__validate) | Remove the listener to stop the validation | entailment |
def start(self):
""" Restart the listener
"""
if not event.contains(self.field, 'set', self.__validate):
self.__create_event() | Restart the listener | entailment |
def nhapDaiHan(self, cucSo, gioiTinh):
"""Nhap dai han
Args:
cucSo (TYPE): Description
gioiTinh (TYPE): Description
Returns:
TYPE: Description
"""
for cung in self.thapNhiCung:
khoangCach = khoangCachCung(cung.cungSo, self.cungMen... | Nhap dai han
Args:
cucSo (TYPE): Description
gioiTinh (TYPE): Description
Returns:
TYPE: Description | entailment |
def solve_gfl(data, edges=None, weights=None,
minlam=0.2, maxlam=1000.0, numlam=30,
alpha=0.2, inflate=2., converge=1e-6,
maxsteps=1000000, lam=None, verbose=0,
missing_val=None, full_path=False,
loss='normal'):
'''A very easy-to-use version of G... | A very easy-to-use version of GFL solver that just requires the data and
the edges. | entailment |
def ngayThangNam(nn, tt, nnnn, duongLich=True, timeZone=7):
"""Summary
Args:
nn (TYPE): ngay
tt (TYPE): thang
nnnn (TYPE): nam
duongLich (bool, optional): bool
timeZone (int, optional): +7 Vietnam
Returns:
TYPE: Description
Raises:
Exception: De... | Summary
Args:
nn (TYPE): ngay
tt (TYPE): thang
nnnn (TYPE): nam
duongLich (bool, optional): bool
timeZone (int, optional): +7 Vietnam
Returns:
TYPE: Description
Raises:
Exception: Description | entailment |
def canChiNgay(nn, tt, nnnn, duongLich=True, timeZone=7, thangNhuan=False):
"""Summary
Args:
nn (int): ngày
tt (int): tháng
nnnn (int): năm
duongLich (bool, optional): True nếu là dương lịch, False âm lịch
timeZone (int, optional): Múi giờ
thangNhuan (bool, optio... | Summary
Args:
nn (int): ngày
tt (int): tháng
nnnn (int): năm
duongLich (bool, optional): True nếu là dương lịch, False âm lịch
timeZone (int, optional): Múi giờ
thangNhuan (bool, optional): Có phải là tháng nhuận không?
Returns:
TYPE: Description | entailment |
def ngayThangNamCanChi(nn, tt, nnnn, duongLich=True, timeZone=7):
"""chuyển đổi năm, tháng âm/dương lịch sang Can, Chi trong tiếng Việt.
Không tính đến can ngày vì phải chuyển đổi qua lịch Julius.
Hàm tìm can ngày là hàm canChiNgay(nn, tt, nnnn, duongLich=True,\
timeZone... | chuyển đổi năm, tháng âm/dương lịch sang Can, Chi trong tiếng Việt.
Không tính đến can ngày vì phải chuyển đổi qua lịch Julius.
Hàm tìm can ngày là hàm canChiNgay(nn, tt, nnnn, duongLich=True,\
timeZone=7, thangNhuan=False)
Args:
nn (int): Ngày
tt (int):... | entailment |
def nguHanh(tenHanh):
"""
Args:
tenHanh (string): Tên Hành trong ngũ hành, Kim hoặc K, Moc hoặc M,
Thuy hoặc T, Hoa hoặc H, Tho hoặc O
Returns:
Dictionary: ID của Hành, tên đầy đủ của Hành, số Cục của Hành
Raises:
Exception: Description
"""
if tenHanh in ["Kim",... | Args:
tenHanh (string): Tên Hành trong ngũ hành, Kim hoặc K, Moc hoặc M,
Thuy hoặc T, Hoa hoặc H, Tho hoặc O
Returns:
Dictionary: ID của Hành, tên đầy đủ của Hành, số Cục của Hành
Raises:
Exception: Description | entailment |
def nguHanhNapAm(diaChi, thienCan, xuatBanMenh=False):
"""Sử dụng Ngũ Hành nạp âm để tính Hành của năm.
Args:
diaChi (integer): Số thứ tự của địa chi (Tý=1, Sửu=2,...)
thienCan (integer): Số thứ tự của thiên can (Giáp=1, Ất=2,...)
Returns:
Trả về chữ viết tắt Hành của năm (K, T, H,... | Sử dụng Ngũ Hành nạp âm để tính Hành của năm.
Args:
diaChi (integer): Số thứ tự của địa chi (Tý=1, Sửu=2,...)
thienCan (integer): Số thứ tự của thiên can (Giáp=1, Ất=2,...)
Returns:
Trả về chữ viết tắt Hành của năm (K, T, H, O, M) | entailment |
def timTuVi(cuc, ngaySinhAmLich):
"""Tìm vị trí của sao Tử vi
Args:
cuc (TYPE): Description
ngaySinhAmLich (TYPE): Description
Returns:
TYPE: Description
Raises:
Exception: Description
"""
cungDan = 3 # Vị trí cung Dần ban đầu là 3
cucBanDau = cuc
if c... | Tìm vị trí của sao Tử vi
Args:
cuc (TYPE): Description
ngaySinhAmLich (TYPE): Description
Returns:
TYPE: Description
Raises:
Exception: Description | entailment |
def nt2aa(ntseq):
"""Translate a nucleotide sequence into an amino acid sequence.
Parameters
----------
ntseq : str
Nucleotide sequence composed of A, C, G, or T (uppercase or lowercase)
Returns
-------
aaseq : str
Amino acid sequence
Example
--------
>>> n... | Translate a nucleotide sequence into an amino acid sequence.
Parameters
----------
ntseq : str
Nucleotide sequence composed of A, C, G, or T (uppercase or lowercase)
Returns
-------
aaseq : str
Amino acid sequence
Example
--------
>>> nt2aa('TGTGCCTGGAGTGTAGCTC... | entailment |
def nt2codon_rep(ntseq):
"""Represent nucleotide sequence by sequence of codon symbols.
'Translates' the nucleotide sequence into a symbolic representation of
'amino acids' where each codon gets its own unique character symbol. These
characters should be reserved only for representing the 64 individua... | Represent nucleotide sequence by sequence of codon symbols.
'Translates' the nucleotide sequence into a symbolic representation of
'amino acids' where each codon gets its own unique character symbol. These
characters should be reserved only for representing the 64 individual
codons --- note that this... | entailment |
def cutR_seq(seq, cutR, max_palindrome):
"""Cut genomic sequence from the right.
Parameters
----------
seq : str
Nucleotide sequence to be cut from the right
cutR : int
cutR - max_palindrome = how many nucleotides to cut from the right.
Negative cutR implies complementary pa... | Cut genomic sequence from the right.
Parameters
----------
seq : str
Nucleotide sequence to be cut from the right
cutR : int
cutR - max_palindrome = how many nucleotides to cut from the right.
Negative cutR implies complementary palindromic insertions.
max_palindrome : int
... | entailment |
def cutL_seq(seq, cutL, max_palindrome):
"""Cut genomic sequence from the left.
Parameters
----------
seq : str
Nucleotide sequence to be cut from the right
cutL : int
cutL - max_palindrome = how many nucleotides to cut from the left.
Negative cutL implies complementary pali... | Cut genomic sequence from the left.
Parameters
----------
seq : str
Nucleotide sequence to be cut from the right
cutL : int
cutL - max_palindrome = how many nucleotides to cut from the left.
Negative cutL implies complementary palindromic insertions.
max_palindrome : int
... | entailment |
def construct_codons_dict(alphabet_file = None):
"""Generate the sub_codons_right dictionary of codon suffixes.
syntax of custom alphabet_files:
char: list,of,amino,acids,or,codons,separated,by,commas
Parameters
----------
alphabet_file : str
File name for a custom al... | Generate the sub_codons_right dictionary of codon suffixes.
syntax of custom alphabet_files:
char: list,of,amino,acids,or,codons,separated,by,commas
Parameters
----------
alphabet_file : str
File name for a custom alphabet definition. If no file is provided, the
... | entailment |
def generate_sub_codons_left(codons_dict):
"""Generate the sub_codons_left dictionary of codon prefixes.
Parameters
----------
codons_dict : dict
Dictionary, keyed by the allowed 'amino acid' symbols with the values
being lists of codons corresponding to the symbol.
Returns
--... | Generate the sub_codons_left dictionary of codon prefixes.
Parameters
----------
codons_dict : dict
Dictionary, keyed by the allowed 'amino acid' symbols with the values
being lists of codons corresponding to the symbol.
Returns
-------
sub_codons_left : dict
Dictionar... | entailment |
def generate_sub_codons_right(codons_dict):
"""Generate the sub_codons_right dictionary of codon suffixes.
Parameters
----------
codons_dict : dict
Dictionary, keyed by the allowed 'amino acid' symbols with the values
being lists of codons corresponding to the symbol.
Returns
... | Generate the sub_codons_right dictionary of codon suffixes.
Parameters
----------
codons_dict : dict
Dictionary, keyed by the allowed 'amino acid' symbols with the values
being lists of codons corresponding to the symbol.
Returns
-------
sub_codons_right : dict
Diction... | entailment |
def determine_seq_type(seq, aa_alphabet):
"""Determine the type of a sequence.
Parameters
----------
seq : str
Sequence to be typed.
aa_alphabet : str
String of all characters recoginized as 'amino acids'. (i.e. the keys
of codons_dict: aa_alphabet = ''.join(codons_dict... | Determine the type of a sequence.
Parameters
----------
seq : str
Sequence to be typed.
aa_alphabet : str
String of all characters recoginized as 'amino acids'. (i.e. the keys
of codons_dict: aa_alphabet = ''.join(codons_dict.keys()) )
Returns
-------
seq_type... | entailment |
def calc_steady_state_dist(R):
"""Calculate the steady state dist of a 4 state markov transition matrix.
Parameters
----------
R : ndarray
Markov transition matrix
Returns
-------
p_ss : ndarray
Steady state probability distribution
"""
#Calc steady state d... | Calculate the steady state dist of a 4 state markov transition matrix.
Parameters
----------
R : ndarray
Markov transition matrix
Returns
-------
p_ss : ndarray
Steady state probability distribution | entailment |
def rnd_ins_seq(ins_len, C_R, CP_first_nt):
"""Generate a random insertion nucleotide sequence of length ins_len.
Draws the sequence identity (for a set length) from the distribution
defined by the dinucleotide markov model of transition matrix R.
Parameters
----------
ins_len : int
Le... | Generate a random insertion nucleotide sequence of length ins_len.
Draws the sequence identity (for a set length) from the distribution
defined by the dinucleotide markov model of transition matrix R.
Parameters
----------
ins_len : int
Length of nucleotide sequence to be inserted.
C_R... | entailment |
def gen_rnd_prod_CDR3(self, conserved_J_residues = 'FVW'):
"""Generate a productive CDR3 seq from a Monte Carlo draw of the model.
Parameters
----------
conserved_J_residues : str, optional
Conserved amino acid residues defining the CDR3 on the J side (normally
F... | Generate a productive CDR3 seq from a Monte Carlo draw of the model.
Parameters
----------
conserved_J_residues : str, optional
Conserved amino acid residues defining the CDR3 on the J side (normally
F, V, and/or W)
Returns
-------
ntseq : str
... | entailment |
def choose_random_recomb_events(self):
"""Sample the genomic model for VDJ recombination events.
Returns
-------
recomb_events : dict
Dictionary of the VDJ recombination events. These are
integers determining gene choice, deletions, and number of insertions.
... | Sample the genomic model for VDJ recombination events.
Returns
-------
recomb_events : dict
Dictionary of the VDJ recombination events. These are
integers determining gene choice, deletions, and number of insertions.
Example
--------
>>> sequence... | entailment |
def gen_rnd_prod_CDR3(self, conserved_J_residues = 'FVW'):
"""Generate a productive CDR3 seq from a Monte Carlo draw of the model.
Parameters
----------
conserved_J_residues : str, optional
Conserved amino acid residues defining the CDR3 on the J side (normally
F... | Generate a productive CDR3 seq from a Monte Carlo draw of the model.
Parameters
----------
conserved_J_residues : str, optional
Conserved amino acid residues defining the CDR3 on the J side (normally
F, V, and/or W)
Returns
-------
ntseq : str
... | entailment |
def choose_random_recomb_events(self):
"""Sample the genomic model for VDJ recombination events.
Returns
-------
recomb_events : dict
Dictionary of the VDJ recombination events. These are
integers determining gene choice, deletions, and number of insertions.
... | Sample the genomic model for VDJ recombination events.
Returns
-------
recomb_events : dict
Dictionary of the VDJ recombination events. These are
integers determining gene choice, deletions, and number of insertions.
Example
--------
>>> sequence... | entailment |
def update_rates(self):
"""
Creates or updates rates for a source
"""
source, created = RateSource.objects.get_or_create(name=self.get_source_name())
source.base_currency = self.get_base_currency()
source.save()
for currency, value in six.iteritems(self.get_rates... | Creates or updates rates for a source | entailment |
def sample_gtf(data, D, k, likelihood='gaussian', prior='laplace',
lambda_hyperparams=None, lam_walk_stdev=0.01, lam0=1.,
dp_hyperparameter=None, w_hyperparameters=None,
iterations=7000, burn=2000, thin=10,
robus... | Generate samples from the generalized graph trend filtering distribution via a modified Swendsen-Wang slice sampling algorithm.
Options for likelihood: gaussian, binomial, poisson. Options for prior: laplace, doublepareto. | entailment |
def compute_regex_CDR3_template_pgen(self, regex_seq, V_usage_mask_in = None, J_usage_mask_in = None, print_warnings = True, raise_overload_warning = True):
"""Compute Pgen for all seqs consistent with regular expression regex_seq.
Computes Pgen for a (limited vocabulary) regular expression of CDR3... | Compute Pgen for all seqs consistent with regular expression regex_seq.
Computes Pgen for a (limited vocabulary) regular expression of CDR3
amino acid sequences, conditioned on the V genes/alleles indicated in
V_usage_mask_in and the J genes/alleles in J_usage_mask_in. Please note
... | entailment |
def compute_aa_CDR3_pgen(self, CDR3_seq, V_usage_mask_in = None, J_usage_mask_in = None, print_warnings = True):
"""Compute Pgen for the amino acid sequence CDR3_seq.
Conditioned on the V genes/alleles indicated in V_usage_mask_in and the
J genes/alleles in J_usage_mask_in. (Examples are T... | Compute Pgen for the amino acid sequence CDR3_seq.
Conditioned on the V genes/alleles indicated in V_usage_mask_in and the
J genes/alleles in J_usage_mask_in. (Examples are TCRB sequences/model)
Parameters
----------
CDR3_seq : str
CDR3 sequence composed of... | entailment |
def compute_hamming_dist_1_pgen(self, CDR3_seq, V_usage_mask_in = None, J_usage_mask_in = None, print_warnings = True):
"""Compute Pgen of all seqs hamming dist 1 (in amino acids) from CDR3_seq.
Please note that this function will list out all the
sequences that are hamming distance 1 from... | Compute Pgen of all seqs hamming dist 1 (in amino acids) from CDR3_seq.
Please note that this function will list out all the
sequences that are hamming distance 1 from the base sequence and then
calculate the Pgen of each sequence in succession. THIS CAN BE SLOW
as it computes Pg... | entailment |
def compute_nt_CDR3_pgen(self, CDR3_ntseq, V_usage_mask_in = None, J_usage_mask_in = None, print_warnings = True):
"""Compute Pgen for the inframe nucleotide sequence CDR3_ntseq.
Conditioned on the V genes/alleles indicated in V_usage_mask_in and the
J genes/alleles in J_usage_mask_in. (Ex... | Compute Pgen for the inframe nucleotide sequence CDR3_ntseq.
Conditioned on the V genes/alleles indicated in V_usage_mask_in and the
J genes/alleles in J_usage_mask_in. (Examples are TCRB sequences/model)
Parameters
----------
CDR3_ntseq : str
Inframe nucle... | entailment |
def format_usage_masks(self, V_usage_mask_in, J_usage_mask_in, print_warnings = True):
"""Format raw usage masks into lists of indices.
Usage masks allows the Pgen computation to be conditioned on the V and J
gene/allele identities. The inputted masks are lists of strings, or a
si... | Format raw usage masks into lists of indices.
Usage masks allows the Pgen computation to be conditioned on the V and J
gene/allele identities. The inputted masks are lists of strings, or a
single string, of the names of the genes or alleles to be conditioned on.
The default mask ... | entailment |
def list_seqs_from_regex(self, regex_seq, print_warnings = True, raise_overload_warning = True):
"""List sequences that match regular expression template.
This function parses a limited regular expression vocabulary, and
lists all the sequences consistent with the regular expression. Suppo... | List sequences that match regular expression template.
This function parses a limited regular expression vocabulary, and
lists all the sequences consistent with the regular expression. Supported
regex syntax: [] and {}. Cannot have two {} in a row. Note we can't use
Kline star (*... | entailment |
def max_nt_to_aa_alignment_left(self, CDR3_seq, ntseq):
"""Find maximum match between CDR3_seq and ntseq from the left.
This function returns the length of the maximum length nucleotide
subsequence of ntseq contiguous from the left (or 5' end) that is
consistent with the 'amino... | Find maximum match between CDR3_seq and ntseq from the left.
This function returns the length of the maximum length nucleotide
subsequence of ntseq contiguous from the left (or 5' end) that is
consistent with the 'amino acid' sequence CDR3_seq.
Parameters
----------
... | entailment |
def max_nt_to_aa_alignment_right(self, CDR3_seq, ntseq):
"""Find maximum match between CDR3_seq and ntseq from the right.
This function returns the length of the maximum length nucleotide
subsequence of ntseq contiguous from the right (or 3' end) that is
consistent with the 'amino ... | Find maximum match between CDR3_seq and ntseq from the right.
This function returns the length of the maximum length nucleotide
subsequence of ntseq contiguous from the right (or 3' end) that is
consistent with the 'amino acid' sequence CDR3_seq
Parameters
----------
... | entailment |
def compute_CDR3_pgen(self, CDR3_seq, V_usage_mask, J_usage_mask):
"""Compute Pgen for CDR3 'amino acid' sequence CDR3_seq from VDJ model.
Conditioned on the already formatted V genes/alleles indicated in
V_usage_mask and the J genes/alleles in J_usage_mask.
(Examples are TCRB seq... | Compute Pgen for CDR3 'amino acid' sequence CDR3_seq from VDJ model.
Conditioned on the already formatted V genes/alleles indicated in
V_usage_mask and the J genes/alleles in J_usage_mask.
(Examples are TCRB sequences/model)
Parameters
----------
CDR3_seq : st... | entailment |
def compute_Pi_V(self, CDR3_seq, V_usage_mask):
"""Compute Pi_V.
This function returns the Pi array from the model factors of the V genomic
contributions, P(V)*P(delV|V). This corresponds to V_{x_1}.
For clarity in parsing the algorithm implementation, we include which
... | Compute Pi_V.
This function returns the Pi array from the model factors of the V genomic
contributions, P(V)*P(delV|V). This corresponds to V_{x_1}.
For clarity in parsing the algorithm implementation, we include which
instance attributes are used in the method as 'param... | entailment |
def compute_Pi_L(self, CDR3_seq, Pi_V, max_V_align):
"""Compute Pi_L.
This function returns the Pi array from the model factors of the V genomic
contributions, P(V)*P(delV|V), and the VD (N1) insertions,
first_nt_bias_insVD(m_1)PinsVD(\ell_{VD})\prod_{i=2}^{\ell_{VD}}Rvd(m_i|m_{i-1... | Compute Pi_L.
This function returns the Pi array from the model factors of the V genomic
contributions, P(V)*P(delV|V), and the VD (N1) insertions,
first_nt_bias_insVD(m_1)PinsVD(\ell_{VD})\prod_{i=2}^{\ell_{VD}}Rvd(m_i|m_{i-1}).
This corresponds to V_{x_1}{M^{x_1}}_{x_2}.
... | entailment |
def compute_Pi_J_given_D(self, CDR3_seq, J_usage_mask):
"""Compute Pi_J conditioned on D.
This function returns the Pi array from the model factors of the D and J
genomic contributions, P(D, J)*P(delJ|J) = P(D|J)P(J)P(delJ|J). This
corresponds to J(D)^{x_4}.
For c... | Compute Pi_J conditioned on D.
This function returns the Pi array from the model factors of the D and J
genomic contributions, P(D, J)*P(delJ|J) = P(D|J)P(J)P(delJ|J). This
corresponds to J(D)^{x_4}.
For clarity in parsing the algorithm implementation, we include which
... | entailment |
def compute_Pi_JinsDJ_given_D(self, CDR3_seq, Pi_J_given_D, max_J_align):
"""Compute Pi_JinsDJ conditioned on D.
This function returns the Pi array from the model factors of the J genomic
contributions, P(D,J)*P(delJ|J), and the DJ (N2) insertions,
first_nt_bias_insDJ(n_1)PinsDJ(\e... | Compute Pi_JinsDJ conditioned on D.
This function returns the Pi array from the model factors of the J genomic
contributions, P(D,J)*P(delJ|J), and the DJ (N2) insertions,
first_nt_bias_insDJ(n_1)PinsDJ(\ell_{DJ})\prod_{i=2}^{\ell_{DJ}}Rdj(n_i|n_{i-1})
conditioned on D identity. T... | entailment |
def compute_Pi_R(self, CDR3_seq, Pi_JinsDJ_given_D):
"""Compute Pi_R.
This function returns the Pi array from the model factors of the D and J
genomic contributions, P(D, J)*P(delJ|J)P(delDl, delDr |D) and
the DJ (N2) insertions,
first_nt_bias_insDJ(n_1)PinsDJ(\ell_{DJ})\pr... | Compute Pi_R.
This function returns the Pi array from the model factors of the D and J
genomic contributions, P(D, J)*P(delJ|J)P(delDl, delDr |D) and
the DJ (N2) insertions,
first_nt_bias_insDJ(n_1)PinsDJ(\ell_{DJ})\prod_{i=2}^{\ell_{DJ}}Rdj(n_i|n_{i-1}).
This corresponds t... | entailment |
def compute_CDR3_pgen(self, CDR3_seq, V_usage_mask, J_usage_mask):
"""Compute Pgen for CDR3 'amino acid' sequence CDR3_seq from VJ model.
Conditioned on the already formatted V genes/alleles indicated in
V_usage_mask and the J genes/alleles in J_usage_mask.
Parameters
... | Compute Pgen for CDR3 'amino acid' sequence CDR3_seq from VJ model.
Conditioned on the already formatted V genes/alleles indicated in
V_usage_mask and the J genes/alleles in J_usage_mask.
Parameters
----------
CDR3_seq : str
CDR3 sequence composed of 'amino... | entailment |
def compute_Pi_V_given_J(self, CDR3_seq, V_usage_mask, J_usage_mask):
"""Compute Pi_V conditioned on J.
This function returns the Pi array from the model factors of the V genomic
contributions, P(V, J)*P(delV|V). This corresponds to V(J)_{x_1}.
For clarity in parsing the a... | Compute Pi_V conditioned on J.
This function returns the Pi array from the model factors of the V genomic
contributions, P(V, J)*P(delV|V). This corresponds to V(J)_{x_1}.
For clarity in parsing the algorithm implementation, we include which
instance attributes are used i... | entailment |
def compute_Pi_V_insVJ_given_J(self, CDR3_seq, Pi_V_given_J, max_V_align):
"""Compute Pi_V_insVJ conditioned on J.
This function returns the Pi array from the model factors of the V genomic
contributions, P(V, J)*P(delV|V), and the VJ (N) insertions,
first_nt_bias_insVJ(m_1)PinsVJ(... | Compute Pi_V_insVJ conditioned on J.
This function returns the Pi array from the model factors of the V genomic
contributions, P(V, J)*P(delV|V), and the VJ (N) insertions,
first_nt_bias_insVJ(m_1)PinsVJ(\ell_{VJ})\prod_{i=2}^{\ell_{VJ}}Rvj(m_i|m_{i-1}).
This corresponds to V(J)_{... | entailment |
def compute_Pi_J(self, CDR3_seq, J_usage_mask):
"""Compute Pi_J.
This function returns the Pi array from the model factors of the J genomic
contributions, P(delJ|J). This corresponds to J(D)^{x_4}.
For clarity in parsing the algorithm implementation, we include which
... | Compute Pi_J.
This function returns the Pi array from the model factors of the J genomic
contributions, P(delJ|J). This corresponds to J(D)^{x_4}.
For clarity in parsing the algorithm implementation, we include which
instance attributes are used in the method as 'paramete... | entailment |
def solve(self, lam):
'''Solves the GFL for a fixed value of lambda.'''
s = weighted_graphtf(self.nnodes, self.y, self.weights, lam,
self.Dk.shape[0], self.Dk.shape[1], self.Dk.nnz,
self.Dk.row.astype('int32'), self.Dk.col.astype('int32'), self.D... | Solves the GFL for a fixed value of lambda. | entailment |
def solution_path(self, min_lambda, max_lambda, lambda_bins, verbose=0):
'''Follows the solution path to find the best lambda value.'''
self.u = np.zeros(self.Dk.shape[0], dtype='double')
lambda_grid = np.exp(np.linspace(np.log(max_lambda), np.log(min_lambda), lambda_bins))
aic_trace = n... | Follows the solution path to find the best lambda value. | entailment |
def solve(self, lam):
'''Solves the GFL for a fixed value of lambda.'''
s = weighted_graphtf_logit(self.nnodes, self.trials, self.successes, lam,
self.Dk.shape[0], self.Dk.shape[1], self.Dk.nnz,
self.Dk.row.astype('int32'), self.Dk.col.as... | Solves the GFL for a fixed value of lambda. | entailment |
def solve(self, lam):
'''Solves the GFL for a fixed value of lambda.'''
s = weighted_graphtf_poisson(self.nnodes, self.obs, lam,
self.Dk.shape[0], self.Dk.shape[1], self.Dk.nnz,
self.Dk.row.astype('int32'), self.Dk.col.astype('int32'), se... | Solves the GFL for a fixed value of lambda. | entailment |
def make_V_and_J_mask_mapping(self, genV, genJ):
"""Constructs the V and J mask mapping dictionaries.
Parameters
----------
genV : list
List of genomic V information.
genJ : list
List of genomic J information.
"""
... | Constructs the V and J mask mapping dictionaries.
Parameters
----------
genV : list
List of genomic V information.
genJ : list
List of genomic J information. | entailment |
def preprocess_D_segs(self, generative_model, genomic_data):
"""Process P(delDl, delDr|D) into Pi arrays.
Sets the attributes PD_nt_pos_vec, PD_2nd_nt_pos_per_aa_vec,
min_delDl_given_DdelDr, max_delDl_given_DdelDr, and zeroD_given_D.
Parameters
----------
g... | Process P(delDl, delDr|D) into Pi arrays.
Sets the attributes PD_nt_pos_vec, PD_2nd_nt_pos_per_aa_vec,
min_delDl_given_DdelDr, max_delDl_given_DdelDr, and zeroD_given_D.
Parameters
----------
generative_model : GenerativeModelVDJ
VDJ generative model cl... | entailment |
def generate_PJdelJ_nt_pos_vecs(self, generative_model, genomic_data):
"""Process P(J)*P(delJ|J) into Pi arrays.
Sets the attributes PJdelJ_nt_pos_vec and PJdelJ_2nd_nt_pos_per_aa_vec.
Parameters
----------
generative_model : GenerativeModelVDJ
VDJ gener... | Process P(J)*P(delJ|J) into Pi arrays.
Sets the attributes PJdelJ_nt_pos_vec and PJdelJ_2nd_nt_pos_per_aa_vec.
Parameters
----------
generative_model : GenerativeModelVDJ
VDJ generative model class containing the model parameters.
genomic_dat... | entailment |
def generate_VD_junction_transfer_matrices(self):
"""Compute the transfer matrices for the VD junction.
Sets the attributes Tvd, Svd, Dvd, lTvd, and lDvd.
"""
nt2num = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
#Compute Tvd
Tvd ... | Compute the transfer matrices for the VD junction.
Sets the attributes Tvd, Svd, Dvd, lTvd, and lDvd. | entailment |
def generate_DJ_junction_transfer_matrices(self):
"""Compute the transfer matrices for the VD junction.
Sets the attributes Tdj, Sdj, Ddj, rTdj, and rDdj.
"""
nt2num = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
#Compute Tdj
Tdj = {}
for aa... | Compute the transfer matrices for the VD junction.
Sets the attributes Tdj, Sdj, Ddj, rTdj, and rDdj. | entailment |
def generate_PVdelV_nt_pos_vecs(self, generative_model, genomic_data):
"""Process P(delV|V) into Pi arrays.
Set the attributes PVdelV_nt_pos_vec and PVdelV_2nd_nt_pos_per_aa_vec.
Parameters
----------
generative_model : GenerativeModelVJ
VJ generative mo... | Process P(delV|V) into Pi arrays.
Set the attributes PVdelV_nt_pos_vec and PVdelV_2nd_nt_pos_per_aa_vec.
Parameters
----------
generative_model : GenerativeModelVJ
VJ generative model class containing the model parameters.
genomic_data : Geno... | entailment |
def generate_PJdelJ_nt_pos_vecs(self, generative_model, genomic_data):
"""Process P(delJ|J) into Pi arrays.
Set the attributes PJdelJ_nt_pos_vec and PJdelJ_2nd_nt_pos_per_aa_vec.
Parameters
----------
generative_model : GenerativeModelVJ
VJ generative mo... | Process P(delJ|J) into Pi arrays.
Set the attributes PJdelJ_nt_pos_vec and PJdelJ_2nd_nt_pos_per_aa_vec.
Parameters
----------
generative_model : GenerativeModelVJ
VJ generative model class containing the model parameters.
genomic_data : Geno... | entailment |
def generate_VJ_junction_transfer_matrices(self):
"""Compute the transfer matrices for the VJ junction.
Sets the attributes Tvj, Svj, Dvj, lTvj, and lDvj.
"""
nt2num = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
#Compute Tvj
Tv... | Compute the transfer matrices for the VJ junction.
Sets the attributes Tvj, Svj, Dvj, lTvj, and lDvj. | entailment |
def showDosHeaderData(peInstance):
""" Prints IMAGE_DOS_HEADER fields. """
dosFields = peInstance.dosHeader.getFields()
print "[+] IMAGE_DOS_HEADER values:\n"
for field in dosFields:
if isinstance(dosFields[field], datatypes.Array):
print "--> %s - Array of length %d" % (field,... | Prints IMAGE_DOS_HEADER fields. | entailment |
def showFileHeaderData(peInstance):
""" Prints IMAGE_FILE_HEADER fields. """
fileHeaderFields = peInstance.ntHeaders.fileHeader.getFields()
print "[+] IMAGE_FILE_HEADER values:\n"
for field in fileHeaderFields:
print "--> %s = 0x%08x" % (field, fileHeaderFields[field].value) | Prints IMAGE_FILE_HEADER fields. | entailment |
def showOptionalHeaderData(peInstance):
""" Prints IMAGE_OPTIONAL_HEADER fields. """
print "[+] IMAGE_OPTIONAL_HEADER:\n"
ohFields = peInstance.ntHeaders.optionalHeader.getFields()
for field in ohFields:
if not isinstance(ohFields[field], datadirs.DataDirectory):
print "--> %s ... | Prints IMAGE_OPTIONAL_HEADER fields. | entailment |
def showDataDirectoriesData(peInstance):
""" Prints the DATA_DIRECTORY fields. """
print "[+] Data directories:\n"
dirs = peInstance.ntHeaders.optionalHeader.dataDirectory
counter = 1
for dir in dirs:
print "[%d] --> Name: %s -- RVA: 0x%08x -- SIZE: 0x%08x" % (counter, dir.name.value, ... | Prints the DATA_DIRECTORY fields. | entailment |
def showSectionsHeaders(peInstance):
""" Prints IMAGE_SECTION_HEADER for every section present in the file. """
print "[+] Sections information:\n"
print "--> NumberOfSections: %d\n" % peInstance.ntHeaders.fileHeader.numberOfSections.value
for section in peInstance.sectionHeaders:
fields = ... | Prints IMAGE_SECTION_HEADER for every section present in the file. | entailment |
def showImports(peInstance):
""" Shows imports information. """
iidEntries = peInstance.ntHeaders.optionalHeader.dataDirectory[consts.IMPORT_DIRECTORY].info
if iidEntries:
for iidEntry in iidEntries:
fields = iidEntry.getFields()
print "module: %s" % iidEntry.metaData.mo... | Shows imports information. | entailment |
def showExports(peInstance):
""" Show exports information """
exports = peInstance.ntHeaders.optionalHeader.dataDirectory[consts.EXPORT_DIRECTORY].info
if exports:
exp_fields = exports.getFields()
for field in exp_fields:
print "%s -> %x" % (field, exp_fields[field].value)
... | Show exports information | entailment |
def getFields(self):
"""
Returns all the class attributues.
@rtype: dict
@return: A dictionary containing all the class attributes.
"""
d = {}
for i in self._attrsList:
key = i
value = getattr(self, i)
d[key] = value
... | Returns all the class attributues.
@rtype: dict
@return: A dictionary containing all the class attributes. | entailment |
def parse(readDataInstance, arrayType, arrayLength):
"""
Returns a new L{Array} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: The L{ReadData} object containing the array data.
@type arrayType: int
@param arrayType: The type of L{... | Returns a new L{Array} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: The L{ReadData} object containing the array data.
@type arrayType: int
@param arrayType: The type of L{Array} to be built.
@type arrayLength: int
@param ... | entailment |
def calc_euler_tour(g, start, end):
'''Calculates an Euler tour over the graph g from vertex start to vertex end.
Assumes start and end are odd-degree vertices and that there are no other odd-degree
vertices.'''
even_g = nx.subgraph(g, g.nodes()).copy()
if end in even_g.neighbors(start):
# I... | Calculates an Euler tour over the graph g from vertex start to vertex end.
Assumes start and end are odd-degree vertices and that there are no other odd-degree
vertices. | entailment |
def greedy_trails(subg, odds, verbose):
'''Greedily select trails by making the longest you can until the end'''
if verbose:
print('\tCreating edge map')
edges = defaultdict(list)
for x,y in subg.edges():
edges[x].append(y)
edges[y].append(x)
if verbose:
print('\tS... | Greedily select trails by making the longest you can until the end | entailment |
def decompose_graph(g, heuristic='tour', max_odds=20, verbose=0):
'''Decompose a graph into a set of non-overlapping trails.'''
# Get the connected subgraphs
subgraphs = [nx.subgraph(g, x).copy() for x in nx.connected_components(g)]
chains = []
num_subgraphs = len(subgraphs)
step = 0
while ... | Decompose a graph into a set of non-overlapping trails. | entailment |
def plus(self, a):
""" Add. """
return Vector(self.x+a.x, self.y+a.y, self.z+a.z) | Add. | entailment |
def minus(self, a):
""" Subtract. """
return Vector(self.x-a.x, self.y-a.y, self.z-a.z) | Subtract. | entailment |
def times(self, a):
""" Multiply. """
return Vector(self.x*a, self.y*a, self.z*a) | Multiply. | entailment |
def dividedBy(self, a):
""" Divide. """
return Vector(self.x/a, self.y/a, self.z/a) | Divide. | entailment |
def lerp(self, a, t):
""" Lerp. Linear interpolation from self to a"""
return self.plus(a.minus(self).times(t)); | Lerp. Linear interpolation from self to a | entailment |
def interpolate(self, other, t):
"""
Create a new vertex between this vertex and `other` by linearly
interpolating all properties using a parameter of `t`. Subclasses should
override this to interpolate additional properties.
"""
return Vertex(self.pos.lerp(other.pos, t),... | Create a new vertex between this vertex and `other` by linearly
interpolating all properties using a parameter of `t`. Subclasses should
override this to interpolate additional properties. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.