code stringlengths 57 46.3k | quality_prob float64 0.7 0.99 | learning_prob float64 0.5 1 |
|---|---|---|
def calculate_desired_noise_rms(clean_rms, snr):
"""
Given the Root Mean Square (RMS) of a clean sound and a desired signal-to-noise ratio (SNR),
calculate the desired RMS of a noise sound to be mixed in.
Based on https://github.com/Sato-Kunihiko/audio-SNR/blob/8d2c933b6c0afe6f1203251f4877e7a1068a6130/... | 0.930253 | 0.753603 |
def is_waveform_multichannel(samples):
"""
Return bool that answers the question: Is the given ndarray a multichannel waveform or not?
:param samples: numpy ndarray
:return:
"""
return len(samples.shape) > 1 | 0.772101 | 0.565959 |
def is_spectrogram_multichannel(spectrogram):
"""
Return bool that answers the question: Is the given ndarray a multichannel spectrogram?
:param samples: numpy ndarray
:return:
"""
return len(spectrogram.shape) > 2 and spectrogram.shape[-1] > 1 | 0.823577 | 0.777215 |
def normalize_timestamp(timestamp):
"""
Format a timestamp (string or numeric) into a standardized
xxxxxxxxxx.xxxxx (10.5) format.
Note that timestamps using values greater than or equal to November 20th,
2286 at 17:46 UTC will use 11 digits to represent the number of
seconds.
:param times... | 0.860472 | 0.780662 |
def unpack_str(byteseq):
"""Unpack a byte sequence into a string."""
return byteseq.decode() | 0.721743 | 0.609408 |
def num_model_detection_error(ground_truth_vps, detected_vps):
"""Measures error in the number of detected vanishing points.
Returns:
Integer, positive when there are too many VPs, negative
when there are too few.
"""
return len(detected_vps) - len(ground_truth_vps) | 0.785679 | 0.801237 |
def binary_search_iterative(array, item):
"""Time Complexity: O(log*n) because you are constantly dividing the length of array by 2 until array length is 1
Space Complexity: O(1) """
left, right = 0, len(array) - 1
if len(array) == 0:
return None
while left <= right:
middle = ... | 0.755997 | 0.620765 |
import torch
def smooth_l1_loss(pred, target, beta=1.0):
"""Smooth l1 loss.
:param pred: predict
:param target: target
:param beta: beta
:return: loss
"""
assert beta > 0
assert pred.size() == target.size() and target.numel() > 0
diff = torch.abs(pred - target)
loss = torch.whe... | 0.768907 | 0.611295 |
import torch
def _expand_binary_labels(labels, label_weights, label_channels):
"""Expand binary labels.
:param labels: labels
:param label_weights: label weights
:param label_channels: label channels
:return: binary label and label weights
"""
bin_labels = labels.new_full((labels.size(0), ... | 0.779154 | 0.550547 |
def normalize_pack_version(version):
"""
Normalize old, pre StackStorm v2.1 non valid semver version string (e.g. 0.2) to a valid
semver version string (0.2.0).
:rtype: ``str``
"""
version = str(version)
version_seperator_count = version.count('.')
if version_seperator_count == 1:
... | 0.719482 | 0.505249 |
def roundup_to_integer_multiple(x, factor):
"""Round up integer x to the nearest integer multiple of integer factor.
Returns x if factor is set to -1. Both x and factor must otherwise be
positive."""
# ensure integers
assert int(x) == x, "The input x is not an integer."
assert int(factor) == fac... | 0.886039 | 0.563828 |
def calculate_matvec_accumulator_range(matrix, vec_dt):
"""Calculate the minimum and maximum possible result (accumulator) values
for a dot product x * A, given matrix A of dims (MW, MH), and vector (1, MW)
with datatype vec_dt. Returns (acc_min, acc_max).
"""
min_weight = matrix.min()
max_weigh... | 0.871146 | 0.762114 |
import torch
def cam2pixel(cam_coords, proj_c2p_rot, proj_c2p_tr, padding_mode):
"""Transform coordinates in the camera frame to the pixel frame.
Args:
cam_coords: pixel coordinates defined in the first camera coordinates system -- [B, 4, H, W]
proj_c2p_rot: rotation matrix of cameras -- [B, 3,... | 0.805058 | 0.637045 |
import torch
def euler2mat(angle):
"""Convert euler angles to rotation matrix.
Reference: https://github.com/pulkitag/pycaffe-utils/blob/master/rot_utils.py#L174
Args:
angle: rotation angle along 3 axis (in radians) -- size = [B, 3]
Returns:
Rotation matrix corresponding to the euler... | 0.950353 | 0.861538 |
import torch
def quat2mat(quat):
"""Convert quaternion coefficients to rotation matrix.
Args:
quat: first three coeff of quaternion of rotation. fourht is then computed to have a norm of 1 -- size = [B, 3]
Returns:
Rotation matrix corresponding to the quaternion -- size = [B, 3, 3]
"""... | 0.914558 | 0.940024 |
def elemwise_mul(a, b):
"""
a: A theano matrix
b: A theano matrix
Returns the elementwise product of a and b
"""
return a * b | 0.713531 | 0.629276 |
import torch
def l2_norm(input, axis=1):
"""l2 normalization.
Args:
input (torch.Tensor): The input tensor.
axis (int, optional): Specifies which axis of input to calculate the
norm across. Defaults to 1.
Returns:
Tensor: Tensor after L2 normalization per-instance.
... | 0.818193 | 0.500122 |
def rectangle_centroid(rectangle):
"""
get the centroid of the rectangle
Keyword arguments:
rectangle -- polygon geojson object
return centroid
"""
bbox = rectangle['coordinates'][0]
xmin = bbox[0][0]
ymin = bbox[0][1]
xmax = bbox[2][0]
ymax = bbox[2][1]
xwidth = xmax ... | 0.817684 | 0.666021 |
def fixed_time_horizon(df, column='close', lookback=20):
"""
Fixed-time Horizon
As it relates to finance, virtually all ML papers label observations using the fixed-time horizon method.
Fixed-time horizon is presented as one of the main procedures to label data when it comes to processing
financial... | 0.937002 | 0.756942 |
def _make_cache_key(times, targets):
"""
Make a unique key to reference this combination of ``times`` and ``targets``.
Often, we wish to store expensive calculations for a combination of
``targets`` and ``times`` in a cache on an ``observer``` object. This
routine will provide an appropriate, hasha... | 0.903967 | 0.904693 |
def min_best_rescale(vals, min_val, max_val, less_than_min=1):
"""
rescales an input array ``vals`` to be a score (between zero and one),
where the ``min_val`` goes to one, and the ``max_val`` goes to zero.
Parameters
----------
vals : array-like
the values that need to be rescaled to b... | 0.937947 | 0.981095 |
def max_best_rescale(vals, min_val, max_val, greater_than_max=1):
"""
rescales an input array ``vals`` to be a score (between zero and one),
where the ``max_val`` goes to one, and the ``min_val`` goes to zero.
Parameters
----------
vals : array-like
the values that need to be rescaled t... | 0.942354 | 0.984796 |
def convert_qkv_weight(cfg, value):
"""
Convert qkv.weight to be compatible with LiBai transformer layer
Args:
cfg: config file
value: qkv.weight in the loaded checkpoint
"""
num_heads = cfg.model.num_heads
hidden_size = cfg.model.embed_dim
head_size = int(hidden_size / num_... | 0.88136 | 0.689458 |
def convert_qkv_bias(cfg, value):
"""
Convert qkv.bias to be compatible with LiBai transformer layer
Args:
cfg: config file
value: qkv.bias in the loaded checkpoint
"""
num_heads = cfg.model.num_heads
hidden_size = cfg.model.embed_dim
head_size = int(hidden_size / num_heads)... | 0.914901 | 0.817137 |
def get_supported_schedulers():
"""
Return a tuple of the scheduler supported by parallelcluster.
:return: a tuple of strings of the supported scheduler
"""
return "sge", "torque", "slurm", "awsbatch" | 0.744006 | 0.517937 |
def textBoxSize(txt, transformation=None, figure=None):
"""Get the width and height of a text object's bounding box transformed to the desired coordinates. Defaults to
figure coordinates if transformation is None."""
fig= txt.get_figure() if figure is None else figure
if transformation is None:
... | 0.802517 | 0.693596 |
def pretty_date(ago):
""" Process a timedelta object.
From https://stackoverflow.com/questions/1551382/user-friendly-time-format-in-python
"""
second_diff = ago.seconds
day_diff = ago.days
if day_diff < 0:
return ''
if day_diff == 0:
if second_diff < 10:
return ... | 0.736401 | 0.514217 |
def combine_dict(d1,d2):
"""Creates a dictionary which has entries from both of them.
:param d1: dictionary 1
:param d2: dictionary 2
:return: resulting dictionary
"""
d = d1.copy()
d.update(d2)
return d | 0.723993 | 0.975414 |
def lift_to_dimension(A, dim):
"""Creates a view of A of dimension dim (by adding dummy dimensions if necessary).
:param A: numpy array
:param dim: desired dimension of view
:return: returns view of A of appropriate dimension
"""
current_dim = len(A.shape)
if current_dim > dim:
rai... | 0.769514 | 0.587647 |
def get_dim_of_affine_transform(Ab):
"""Returns the number of dimensions corresponding to an affine transformation of the
form y=Ax+b stored in a column vector. For A =[a1,a2,a3], the parameter vector is simply
[a1;a2;a3;b], i.e., all columns stacked on top of each other.
:param Ab: parameter vector
... | 0.795975 | 0.727129 |
def t2np(v):
"""
Takes a torch array and returns it as a numpy array on the cpu
:param v: torch array
:return: numpy array
"""
return (v.detach()).cpu().numpy() | 0.77518 | 0.791821 |
def cxyz_to_xyzc( v ):
"""
Takes a torch array and returns it as a numpy array on the cpu
:param v: torch array
:return: numpy array
"""
dim = len(v.shape)-2
if dim ==2:
v = v.permute(0,2,3,1)
if dim ==3:
v = v.permute(0,2,3,4,1)
return v | 0.725357 | 0.735642 |
def best_scale(number):
"""Scale and units for a number with proper prefix."""
absnr = abs(number)
if absnr == 0:
return 1, ' '
if absnr < 0.99999999e-9:
return 1e12, 'p'
if absnr < 0.99999999e-6:
return 1e9, 'n'
if absnr < 0.99999999e-3:
return 1e6, 'µ'
if a... | 0.702326 | 0.625495 |
def crop_img(img, relative_corners):
""" relative_corners are floats between 0 and 1 designating where the corners of a crop box
should be ([[top_left_x, top_left_y], [bottom_right_x, bottom_right_y]]).
e.g. [[0, 0], [1, 1]] would be the full image, [[0.5, 0.5], [1, 1]] would be bottom right."""
rc = r... | 0.809765 | 0.708015 |
def loss(y_pred, y_true, metric):
"""Compute loss function between prediction and ground truth.
Loss function given by a Riemannian metric,
expressed as the squared geodesic distance between the prediction
and the ground truth.
Parameters
----------
y_pred
y_true
metric
Return... | 0.947884 | 0.811265 |
def kl_to_prior(means, log_stds, stds):
"""
KL between a Gaussian and a standard Gaussian.
https://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians
"""
return 0.5 * (
- 2 * log_stds # log std_prior = 0
- 1 # d = 1
+ stds ... | 0.72952 | 0.557243 |
def getConflictingAssignments(schedule):
""" Get list of assignments which exceeded rotation capacity
Parameters:
schedule (dict): overall assignments
Returns:
confictingAssignmentsByRotation (dict): overall schedule with conflicting assignments
"""
return {} | 0.777131 | 0.615203 |
def quadratic_formula(polynomial):
"""
input is single-variable polynomial of degree 2
returns zeros
"""
if len(polynomial.term_matrix) == 3:
if polynomial.term_matrix[2][1] == 1:
a, b = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0]
return 0, -b/a
... | 0.739234 | 0.795221 |
def generate_coordinates(coords):
"""
A function that returns all possible triples of coords
Parameters:
coords: a numpy array of coordinates
Returns:
x: the first coordinate of possible triples
y: the second coordinate of possible triples
z the third coordinate of possible triples
... | 0.914827 | 0.929824 |
def midpoint_rule(f, M=100000):
"""Integrate f(x) over [0,1] using M intervals."""
from numpy import sum, linspace
dx = 1.0/M # interval length
x = linspace(dx/2, 1-dx/2, M) # integration points
return dx*sum(f(x)) | 0.700895 | 0.504639 |
def dollar(amount):
""" Given an amount as a number
Return a string formatted as a dollar amount
"""
amount = round(amount, 2)
return '${0:0.2f}'.format(amount) | 0.778986 | 0.924688 |
def dataqc_condcompress(p_orig, p_new, c_orig, cpcor=-9.57e-8):
"""
Description:
Implementation of the Sea-Bird conductivity compressibility correction,
scaling the input conductivity based on ratio of the original pressure
and the updated pressure.
Implemented by:
2013-04... | 0.825906 | 0.751785 |
def delta(a, b):
"""
Return change in percent (or None if undefined).
The delta in percent is rounded to one decimal.
"""
if a is None or b is None:
return None
if a == 0.0 and b == 0.0:
return 0.0
assert a != 0.0 and b != 0.0
return round((b - a) * 1000.0 / a) / 10.0 | 0.741393 | 0.654322 |
def adjust_contrast(image, contrast_level):
"""Return the image scaled to a certain contrast level in [0, 1].
parameters:
- image: a numpy.ndarray
- contrast_level: a scalar in [0, 1]; with 1 -> full contrast
"""
assert(contrast_level >= 0.0), "contrast_level too low."
assert(contrast_lev... | 0.89753 | 0.78964 |
def to_list(data_in):
"""Convert the data into a list. Does not pack lists into a new one.
If your input is, for example, a string or a list of strings, or a
tuple filled with strings, you have, in general, a problem:
- just iterate through the object will fail because it iterates through the
ch... | 0.814754 | 0.701317 |
def dot(a, b, out=None):
"""Returns a dot product of two arrays.
For arrays with more than one axis, it computes the dot product along the
last axis of ``a`` and the second-to-last axis of ``b``. This is just a
matrix product if the both arrays are 2-D. For 1-D arrays, it uses their
unique axis as ... | 0.814422 | 0.750736 |
def coord_to_index(coord, sl):
"""
Takes a 3D coordinate in a cube and the cube side length.
Returns index in flattened 3D array.
"""
return coord[0] * sl * sl + coord[1] * sl + coord[2] | 0.749546 | 0.992327 |
def index_to_coord(index, sl):
"""
Takes an index into a flattened 3D array and its side length.
Returns the coordinate in the cube.
"""
coord = []
two_d_slice_size = sl * sl
coord.append(index // two_d_slice_size)
remaining = index % two_d_slice_size
coord.append(remaining // sl)
... | 0.748076 | 0.868102 |
def use_node_def_or_str(given_value, default_func):
"""Transform a value of type (None, str, Callable) to a node annotation function."""
# Default: use pre-defined function from this module
if given_value is None:
func = default_func
# Transform: value to function that returns the value
elif... | 0.745306 | 0.540378 |
def use_node_def_or_num(given_value, default_func):
"""Transform a value of type (None, int, float, Callable) to a node annotation function."""
# Default: use pre-defined function from this module
if given_value is None:
func = default_func
# Transform: value to function that returns the value
... | 0.737725 | 0.556882 |
def use_edge_def_or_str(given_value, default_func):
"""Transform a value of type (None, str, Callable) to an edge annotation function."""
# Default: use pre-defined function from this module
if given_value is None:
func = default_func
# Transform: value to function that returns the value
eli... | 0.752559 | 0.546436 |
def use_edge_def_or_num(given_value, default_func):
"""Transform a value of type (None, int, float, Callable) to an edge annotation function."""
# Default: use pre-defined function from this module
if given_value is None:
func = default_func
# Transform: value to function that returns the value
... | 0.761361 | 0.562177 |
import torch
def gnmt_length_penalty(lengths, alpha=0.8):
"""Calculate a length penalty from https://arxiv.org/pdf/1609.08144.pdf
The paper states the penalty as (5 + |Y|)^a / (5 + 1)^a. This is implemented
as ((5 + |Y|) / 6)^a for a (very) tiny performance boost
:param lengths: `torch.LongTensor`: [... | 0.913342 | 0.563798 |
def repeat_batch(t, K, dim=0):
"""Repeat a tensor while keeping the concept of a batch.
:param t: `torch.Tensor`: The tensor to repeat.
:param K: `int`: The number of times to repeat the tensor.
:param dim: `int`: The dimension to repeat in. This should be the
batch dimension.
:returns: `t... | 0.946076 | 0.911928 |
import torch
def bilinear_interpolate_torch(im, x, y):
"""
Args:
im: (H, W, C) [y, x]
x: (N)
y: (N)
Returns:
"""
x0 = torch.floor(x).long()
x1 = x0 + 1
y0 = torch.floor(y).long()
y1 = y0 + 1
x0 = torch.clamp(x0, 0, im.shape[1] - 1)
x1 = torch.clamp(x1, ... | 0.806396 | 0.580798 |
def int_parameter(level, maxval):
"""Helper function to scale `val` between 0 and maxval .
Args:
level: Level of the operation that will be between [0, `PARAMETER_MAX`].
maxval: Maximum value that the operation can have. This will be scaled to
level/PARAMETER_MAX.
Returns:
An int that resu... | 0.768386 | 0.610802 |
def float_parameter(level, maxval):
"""Helper function to scale `val` between 0 and maxval.
Args:
level: Level of the operation that will be between [0, `PARAMETER_MAX`].
maxval: Maximum value that the operation can have. This will be scaled to
level/PARAMETER_MAX.
Returns:
A float that re... | 0.862207 | 0.820397 |
def normalize(image):
"""Normalize input image channel-wise to zero mean and unit variance."""
return image - 127 | 0.792223 | 0.963746 |
def MakeMetadataLine(label, value, indent=1):
"""Returns a string with a vertically aligned label and value.
Labels of the same indentation level will start at the same column. Values
will all start at the same column (unless the combined left-indent and
label length is excessively long). If a value spans mult... | 0.90532 | 0.670947 |
def to_label(name, capitalize=True):
"""Converts `name` into label by replacing underscores by spaces. If
`capitalize` is ``True`` (default) then the first letter of the label is
capitalized."""
label = name.replace("_", " ")
if capitalize:
label = label.capitalize()
return label | 0.731538 | 0.581273 |
def closest_ref_length(ref_lens, hyp_len):
"""
This function finds the reference that is the closest length to the
hypothesis. The closest reference length is referred to as *r* variable
from the brevity penalty formula in Papineni et. al. (2002)
:param references: A list of reference translations.... | 0.776708 | 0.756897 |
def firing_rate(spike_train, duration):
"""Calculate firing rate for a spike train.
If either temporal bound is not specified, the first and last spike time are used by default.
Inputs:
-------
spike_train : array of spike times (in seconds)
duration : length of recording (in seconds)
Out... | 0.788176 | 0.967132 |
def get_unit_pcs(these_pc_features, index_mask, channel_mask):
""" Use the index_mask and channel_mask to return PC features for one unit
Inputs:
-------
these_pc_features : numpy.ndarray (float)
Array of pre-computed PC features (num_spikes x num_PCs x num_channels)
index_mask : numpy.ndar... | 0.794863 | 0.76291 |
def capitalize(text):
"""capitalizes a word, for use in rendering template
Args:
text (str): word to capitalize
Returns:
capitalized (str): capitalized word
"""
return text[0].upper() + text[1:] | 0.821116 | 0.759839 |
def rule_separation(value: float, layer1: str, layer2: str):
"""Min space between different layers"""
error = f"min {layer1} {layer2} separation {value}um"
return f"{layer1}.separation({layer2}, {value})" f".output('{error}', '{error}')" | 0.76454 | 0.723187 |
def remove_alpha(pic):
"""
Removes the alpha channel from an image, if it exists. Necessary for OCR.
Args:
pic: PIL.Image object to convert.
Returns:
The PIL.Image object in RGB format.
"""
return pic.convert("RGB") | 0.805288 | 0.673809 |
def is_array(signature):
"""Return True if this argument is an array. A dictionary is considered an array."""
return signature[0] == "a" | 0.758332 | 0.624007 |
def to_row_vec(col_vec):
"""
:param col_vec: 2d np array
:return:
"""
return col_vec.reshape(1, -1) | 0.758689 | 0.970688 |
def concatenate_rounds(rounds_1, rounds_2):
"""
:param rounds_1: list - first rounds played.
:param rounds_2: list - second set of rounds played.
:return: list - all rounds played.
"""
return rounds_1 + rounds_2 | 0.799403 | 0.693077 |
def list_contains_round(rounds, number):
"""
:param rounds: list - rounds played.
:param number: int - round number.
:return: bool - was the round played?
"""
return number in rounds | 0.702836 | 0.50116 |
def card_average(hand):
"""
:param hand: list - cards in hand.
:return: float - average value of the cards in the hand.
"""
return sum(hand) / len(hand) | 0.702938 | 0.841044 |
def split_num(line, chars=' ', maxsplits=1, empty=''):
"""/lazy/ wrapper, to stop us having to bounds-check when splitting.
Arguments:
line -- line to split
chars -- character(s) to split line on
maxsplits -- how many split items are returned
empty -- character to put in place of nothing
R... | 0.756178 | 0.555797 |
def const_rate(n, p1=0.0, p2=1.0, p3=1.0):
"""
Constant rate function.
:param n: int - allele number (unused)
:param p1: float - constant parameter
:param p2: float - linear parameter (unused)
:param p3: float - additional parameter (unused)
:return: float - p1
"""
return p1 | 0.76708 | 0.553143 |
def linear_rate(n, p1=0.0, p2=1.0, p3=1.0):
"""
Linear rate function.
:param n: int - allele number
:param p1: float - constant parameter
:param p2: float - linear parameter
:param p3: float - additional parameter (unused)
:return: float - p1 + p2 * n
"""
return p1 + p2 * n | 0.821939 | 0.580293 |
def n2_rate(n, p1=0.0, p2=1.0, p3=1.0):
"""
Quadratic rate function.
:param n: int - allele number
:param p1: float - constant parameter
:param p2: float - linear parameter
:param p3: float - quadratic parameter
:return: float - p1 + p2 * n + p3 * n * n
"""
return p1 + p2 * n + p3 * ... | 0.752104 | 0.734881 |
def set_axis(ax, x, y, letter=None):
"""
Formats the plot's caption.
Parameters
----------
ax: Axes object.
x: float
X-position of caption.
y: float
Y-position of caption.
letter: string
Caption of the plot.
Default: None.
Returns
-------
ax:... | 0.923394 | 0.536374 |
def _airtovac(w):
"""Convert air wavelengths to vacuum wavelengths. Don't convert less than 2000 Å.
Parameters
----------
w : :class:`float`
Wavelength [Å] of the line in air.
Returns
-------
:class:`float`
Wavelength [Å] of the line in vacuum.
"""
if w < 2000.0:
... | 0.943796 | 0.520862 |
def dict_zero(first_level_keys):
"""Initialise a dictionary with one level
Parameters
----------
first_level_keys : list
First level data
Returns
-------
one_level_dict : dict
dictionary
"""
one_level_dict = dict.fromkeys(first_level_keys, 0) # set zero as argument... | 0.761184 | 0.743215 |
import torch
def get_dihedral_torch(c1, c2, c3, c4):
""" Returns the dihedral angle in radians.
Will use atan2 formula from:
https://en.wikipedia.org/wiki/Dihedral_angle#In_polymer_physics
Can't use torch.dot bc it does not broadcast
Inputs:
* c1: (batch, 3) or (3,)
... | 0.86852 | 0.701728 |
import torch
def distmat_loss_torch(X=None, Y=None, X_mat=None, Y_mat=None, p=2, q=2, custom=None, distmat_mask=None):
""" Calculates a loss on the distance matrix - no need to align structs.
Inputs:
* X: (N, d) tensor. the predicted structure. One of (X, X_mat) is needed.
* X_mat: (N, N) ... | 0.859752 | 0.665988 |
def Kabsch(A, B):
""" Returns Kabsch-rotated matrices resulting
from aligning A into B.
Adapted from: https://github.com/charnley/rmsd/
* Inputs:
* A,B are (3 x N)
* backend: one of ["numpy", "torch", "auto"] for backend choice
* Outputs: tensor/array of shap... | 0.735167 | 0.770249 |
def RMSD(A, B):
""" Returns RMSD score as defined here (lower is better):
https://en.wikipedia.org/wiki/
Root-mean-square_deviation_of_atomic_positions
* Inputs:
* A,B are (B x 3 x N) or (3 x N)
* backend: one of ["numpy", "torch", "auto"] for backend choice
... | 0.820073 | 0.903081 |
def TMscore(A, B):
""" Returns TMscore as defined here (higher is better):
>0.5 (likely) >0.6 (highly likely) same folding.
= 0.2. https://en.wikipedia.org/wiki/Template_modeling_score
Warning! It's not exactly the code in:
https://zhanglab.ccmb.med.umich.edu/TM-score/TMscore.cpp
... | 0.788827 | 0.580352 |
def get_square(tracks, position):
"""Get square from tracks with position."""
row, col = position
return tracks[row][col] | 0.707203 | 0.526404 |
def split_history_and_current(windowed_ts):
"""
Returns the first n-1 columns as X, and the last column as y. Useful mainly for forecasting scenarios
:param windowed_ts: a pd.DataFrame with a date index and a column per timestamp. see get_windowed_ts
:return:
"""
X = windowed_ts.iloc[:, :-1].val... | 0.744099 | 0.775009 |
def calc_accuracy(pred, real):
"""
A function to calculate the accuracy of a CNN when given a list of predicted classes and a list of the real classes
Param:
- pred, a numpy array of predicted classes
- real, a numpy array of the real classes
Return:
- Accuracy as a de... | 0.753104 | 0.988313 |
def convert_to_physical(a_coeffs, b_coeffs, logic_x, logic_y):
"""
Convert to physical coordinates from logical coordinates.
Parameters
----------
a_coeffs : array
Perspective transformation coefficients for alpha.
b_coeffs : array
Perspective transformation coefficients for bet... | 0.926877 | 0.884888 |
def drop_disregard(df):
"""
If one token in a note is marked 'disregard', remove the whole note from df.
Parameters
----------
df: DataFrame
parsed token-level annotations df (created by `parse_annotations.py`)
Returns
-------
DataFrame
df without 'disregard' notes
... | 0.802517 | 0.611527 |
def fix_week_14(df):
"""
For annotations from week 14:
- Replace MBW values with `False`
- Replace MBW-lvl values with NaN
We remove this domain from week 14 since the guidelines for it were changed after this week.
Parameters
----------
df: DataFrame
parsed token-level annotati... | 0.868576 | 0.586079 |
def gaussian_product_center(alpha1,A,alpha2,B):
"""
The center of the Gaussian resulting from the product of two Gaussians:
>>> gaussian_product_center(1,array((0,0,0),'d'),1,array((0,0,0),'d'))
array([ 0., 0., 0.])
"""
return (alpha1*A+alpha2*B)/(alpha1+alpha2) | 0.734501 | 0.534005 |
def smoothing_error(x, x_a, A):
"""Return the smoothing error through the averaging kernel.
Parameters:
x (ndarray): Atmospherice profile.
x_a (ndarray): A priori profile.
A (ndarray): Averaging kernel matrix.
Returns:
ndarray: Smoothing error due to correlation between lay... | 0.917935 | 0.960584 |
def get_f_min(f_max, cents_per_value, v_min, v_max):
"""
This function takes in a y value max and min, a maximum frequency and a y scale parameter in units of cents/y value, and returns the minimum frequency that fits to such a scale.
Cents are a logarithmic unit of tone intervals (https://en.wikipedia.org/... | 0.937168 | 0.675141 |
def get_f_max(f_min, cents_per_value, v_min, v_max):
"""
This function takes in a y value max and min, a minimum frequency and a y scale parameter in units of cents/y value, and returns the maximum frequency that fits to such a scale.
Cents are a logarithmic unit of tone intervals (https://en.wikipedia.org/... | 0.934189 | 0.710622 |
def flatten(tensor):
"""Flattens a given tensor such that the channel axis is first.
The shapes are transformed as follows:
(N, C, D, H, W) -> (C, N * D * H * W)
"""
# number of channels
C = tensor.size(1)
# new axis order
axis_order = (1, 0) + tuple(range(2, tensor.dim()))
# Tran... | 0.85741 | 0.681264 |
import torch
def expand_as_one_hot(input, C, ignore_index=None):
"""
Converts NxHxW label image to NxCxDxHxW, where each label gets converted to its corresponding one-hot vector
:param input: 4D input image (NxDxHxW)
:param C: number of channels/labels
:param ignore_index: ignore index to be kept d... | 0.766992 | 0.659302 |
def batch_quat_to_rotmat(q, out=None):
"""
quaternion a + bi + cj + dk should be given in the form [a,b,c,d]
:param q:
:param out:
:return:
"""
import torch
batchsize = q.size(0)
if out is None:
out = q.new_empty(batchsize, 3, 3)
# 2 / squared quaternion 2-norm
s ... | 0.855127 | 0.810216 |
import torch
def cosine_distance(memory_matrix, cos_keys):
"""
compute the cosine similarity between keys to each of the
memory slot.
Parameters:
----------
memory_matrix: Tensor (batch_size, mem_slot, mem_size)
the memory matrix to lookup in
keys: Tensor (batch_size, mem_size, nu... | 0.803174 | 0.748168 |
def center_to_corner(boxes):
""" Convert bounding boxes from center format (cx, cy, width, height) to corner format (xmin, ymin, xmax, ymax)
Args:
- boxes: numpy array of tensor containing all the boxes to be converted
Returns:
- A numpy array or tensor of converted boxes
"""
temp ... | 0.908541 | 0.767123 |
def exact_match(gt_s, gt_e, pr_s, pr_e):
"""
Evaluate exact match of a predicted span over a ground truth span.
Args:
gt_s: index of the ground truth start position
gt_e: index of the ground truth end position
pr_s: index of the predicted start position
pr_e: index of the pre... | 0.779741 | 0.658424 |
def Pluralize(num, word, plural=None):
"""Pluralize word based on num.
Args:
num: int, the number of objects to count.
word: str, the word to pluralize.
plural: str, the plural form of word if not "add s"
Returns:
str: the plural or singular form of word in accord with num.
"""
if num == 1:
... | 0.708213 | 0.614539 |
End of preview. Expand in Data Studio
- Downloads last month
- 26