code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''given two tensors N x I x K and N x K x J return N dot products If either x or y is 2-dimensional, broadcast it over all N. Dot products are size N x I x J. Example: x = np.array([[[1,2], [3,4], [5,6]],[[7,8], [9,10],[11,12]]]) y = np.array([[[1,2,3], [4,5,6]],[[7,8,9],[10,11,12]]]) pri...
def dot_n(x, y)
given two tensors N x I x K and N x K x J return N dot products If either x or y is 2-dimensional, broadcast it over all N. Dot products are size N x I x J. Example: x = np.array([[[1,2], [3,4], [5,6]],[[7,8], [9,10],[11,12]]]) y = np.array([[[1,2,3], [4,5,6]],[[7,8,9],[10,11,12]]]) print dot_...
2.476165
1.555972
1.591394
'''Given a listlike, x, return all permutations of x Returns the permutations of x in the lexical order of their indices: e.g. >>> x = [ 1, 2, 3, 4 ] >>> for p in permutations(x): >>> print p [ 1, 2, 3, 4 ] [ 1, 2, 4, 3 ] [ 1, 3, 2, 4 ] [ 1, 3, 4, 2 ] [ 1, 4, 2, 3 ] [ ...
def permutations(x)
Given a listlike, x, return all permutations of x Returns the permutations of x in the lexical order of their indices: e.g. >>> x = [ 1, 2, 3, 4 ] >>> for p in permutations(x): >>> print p [ 1, 2, 3, 4 ] [ 1, 2, 4, 3 ] [ 1, 3, 2, 4 ] [ 1, 3, 4, 2 ] [ 1, 4, 2, 3 ] [ 1, 4, 3...
2.889035
2.390663
1.208466
'''Circular Hough transform of an image img - image to be transformed. radius - radius of circle nangles - # of angles to measure, e.g. nangles = 4 means accumulate at 0, 90, 180 and 270 degrees. Return the Hough transform of the image which is the accumulators for the transfor...
def circular_hough(img, radius, nangles = None, mask=None)
Circular Hough transform of an image img - image to be transformed. radius - radius of circle nangles - # of angles to measure, e.g. nangles = 4 means accumulate at 0, 90, 180 and 270 degrees. Return the Hough transform of the image which is the accumulators for the transform x + r...
2.873579
2.026479
1.418015
'''The predicted state vector for the next time point From Welch eqn 1.9 ''' if not self.has_cached_predicted_state_vec: self.p_state_vec = dot_n( self.translation_matrix, self.state_vec[:, :, np.newaxis])[:,:,0] return self.p_state_ve...
def predicted_state_vec(self)
The predicted state vector for the next time point From Welch eqn 1.9
7.76088
4.500947
1.724277
'''The predicted observation vector The observation vector for the next step in the filter. ''' if not self.has_cached_obs_vec: self.obs_vec = dot_n( self.observation_matrix, self.predicted_state_vec[:,:,np.newaxis])[:,:,0] return self...
def predicted_obs_vec(self)
The predicted observation vector The observation vector for the next step in the filter.
6.084919
4.355196
1.397163
'''Rewrite the feature indexes based on the next frame's identities old_indices - for each feature in the new frame, the index of the old feature ''' nfeatures = len(old_indices) noldfeatures = len(self.state_vec) if nfeatures > 0: self....
def map_frames(self, old_indices)
Rewrite the feature indexes based on the next frame's identities old_indices - for each feature in the new frame, the index of the old feature
4.140119
3.347994
1.236597
'''Add new features to the state kept_indices - the mapping from all indices in the state to new indices in the new version new_indices - the indices of the new features in the new version new_state_vec - the state vectors for the new indices new_state_...
def add_features(self, kept_indices, new_indices, new_state_vec, new_state_cov, new_noise_var)
Add new features to the state kept_indices - the mapping from all indices in the state to new indices in the new version new_indices - the indices of the new features in the new version new_state_vec - the state vectors for the new indices new_state_cov - the c...
1.816962
1.529093
1.188261
'''Return a deep copy of the state''' c = KalmanState(self.observation_matrix, self.translation_matrix) c.state_vec = self.state_vec.copy() c.state_cov = self.state_cov.copy() c.noise_var = self.noise_var.copy() c.state_noise = self.state_noise.copy() c.state_nois...
def deep_copy(self)
Return a deep copy of the state
2.947849
2.820705
1.045075
'''Equivalent to matlab prctile(x,p), uses linear interpolation.''' x=np.array(x).flatten() listx = np.sort(x) xpcts=[] lenlistx=len(listx) refs=[] for i in range(0,lenlistx): r=100*((.5+i)/lenlistx) #refs[i] is percentile of listx[i] in matrix x refs.append(r) rpcts=[] ...
def prcntiles(x,percents)
Equivalent to matlab prctile(x,p), uses linear interpolation.
3.443912
3.023849
1.138917
'''Tries to guess if the image contains dark objects on a bright background (1) or if the image contains bright objects on a dark background (-1), or if it contains both dark and bright objects on a gray background (0).''' pct=prcntiles(np.array(data),[1,20,80,99]) upper=pct[3]-pct[2] mi...
def automode(data)
Tries to guess if the image contains dark objects on a bright background (1) or if the image contains bright objects on a dark background (-1), or if it contains both dark and bright objects on a gray background (0).
3.221039
2.433055
1.323866
'''u is np.array''' X = np.array([(1.-u)**3 , 4-(6.*(u**2))+(3.*(u**3)) , 1.+(3.*u)+(3.*(u**2))-(3.*(u**3)) , u**3]) * (1./6) return X
def spline_factors(u)
u is np.array
6.555353
6.408518
1.022913
'''Index to first value in picklist that is larger than val. If none is larger, index=len(picklist).''' assert np.all(np.sort(picklist) == picklist), "pick list is not ordered correctly" val = np.array(val) i_pick, i_val = np.mgrid[0:len(picklist),0:len(val)] # # Mark a picklist entry as 1 ...
def pick(picklist,val)
Index to first value in picklist that is larger than val. If none is larger, index=len(picklist).
5.611813
4.546666
1.23427
'''Confine x to [low,high]. Values outside are set to low/high. See also restrict.''' y=x.copy() y[y < low] = low y[y > high] = high return y
def confine(x,low,high)
Confine x to [low,high]. Values outside are set to low/high. See also restrict.
5.294755
2.962229
1.787423
'''returns the gaussian with mean m_y and std. dev. sigma, calculated at the points of x.''' e_y = [np.exp((1.0/(2*float(sigma)**2)*-(n-m_y)**2)) for n in np.array(x)] y = [1.0/(float(sigma) * np.sqrt(2 * np.pi)) * e for e in e_y] return np.array(y)
def gauss(x,m_y,sigma)
returns the gaussian with mean m_y and std. dev. sigma, calculated at the points of x.
4.373015
3.301459
1.324571
'''returns the second derivative of the gaussian with mean m_y, and standard deviation sigma, calculated at the points of x.''' return gauss(x,m_y,sigma)*[-1/sigma**2 + (n-m_y)**2/sigma**4 for n in x]
def d2gauss(x,m_y,sigma)
returns the second derivative of the gaussian with mean m_y, and standard deviation sigma, calculated at the points of x.
6.351831
3.676574
1.72765
'''For boundary constraints, the first two and last two spline pieces are constrained to be part of the same cubic curve.''' V = np.kron(spline_matrix(x,px),spline_matrix(y,py)) lenV = len(V) if mask is not None: indices = np.nonzero(mask.T.flatten()) if len(indices)>1: ...
def spline_matrix2d(x,y,px,py,mask=None)
For boundary constraints, the first two and last two spline pieces are constrained to be part of the same cubic curve.
5.992653
3.535177
1.695149
'''Make a least squares fit of the spline (px,py,pz) to the surface (x,y,z). If mask is given, only masked points are used for the regression.''' if mask is None: V = np.array(spline_matrix2d(x, y, px, py)) a = np.array(z.T.flatten()) pz = np.linalg.lstsq(V.T, a.T)[0].T else: ...
def splinefit2d(x, y, z, px, py, mask=None)
Make a least squares fit of the spline (px,py,pz) to the surface (x,y,z). If mask is given, only masked points are used for the regression.
3.679736
2.821247
1.304294
'''Reads file, subtracts background. Returns [compensated image, background].''' from PIL import Image import pylab from matplotlib.image import pil_to_array from centrosome.filter import canny import matplotlib img = Image.open(img) if img.mode=='I;16': # 16-bit image ...
def bg_compensate(img, sigma, splinepoints, scale)
Reads file, subtracts background. Returns [compensated image, background].
3.578878
3.412389
1.04879
'''Compute the mode of an array a: an array returns a vector of values which are the most frequent (more than one if there is a tie). ''' a = np.asanyarray(a) if a.size == 0: return np.zeros(0, a.dtype) aa = a.flatten() aa.sort() indices = np.hstack([[0], np.whe...
def mode(a)
Compute the mode of an array a: an array returns a vector of values which are the most frequent (more than one if there is a tie).
3.412216
2.288921
1.490753
assert min_threshold is None or max_threshold is None or min_threshold < max_threshold def constrain(threshold): if not min_threshold is None and threshold < min_threshold: threshold = min_threshold if not max_threshold is None and threshold > max_threshold: threshol...
def otsu(data, min_threshold=None, max_threshold=None,bins=256)
Compute a threshold using Otsu's method data - an array of intensity values between zero and one min_threshold - only consider thresholds above this minimum value max_threshold - only consider thresholds below this maximum value bins - we bin the data into this many equally-sp...
2.513831
2.535352
0.991512
data = np.atleast_1d(data) data = data[~ np.isnan(data)] if len(data) == 0: return 0 elif len(data) == 1: return data[0] if bins > len(data): bins = len(data) data.sort() var = running_variance(data)+1.0/512.0 rvar = np.flipud(running_variance(np.flipud...
def entropy(data, bins=256)
Compute a threshold using Ray's entropy measurement data - an array of intensity values between zero and one bins - we bin the data into this many equally-spaced bins, then pick the bin index that optimizes the metric
2.920562
2.921957
0.999523
return 0 var = running_variance(data) rvar = np.flipud(running_variance(np.flipud(data))) if bins > len(data): bins = len(data) bin_len = int(len(data)//bins) thresholds = data[0:len(data):bin_len] score_low = (var[0:len(data):bin_len] * np.arange(0,len(data),b...
def otsu3(data, min_threshold=None, max_threshold=None,bins=128): assert min_threshold is None or max_threshold is None or min_threshold < max_threshold # # Compute the running variance and reverse running variance. # data = np.atleast_1d(data) data = data[~ np.isnan(data)] da...
Compute a threshold using a 3-category Otsu-like method data - an array of intensity values between zero and one min_threshold - only consider thresholds above this minimum value max_threshold - only consider thresholds below this maximum value bins - we bin the data into this...
2.81703
3.010319
0.935791
'''Compute entropy scores, given a variance and # of bins ''' if w is None: n = len(var) w = np.arange(0,n,n//bins) / float(n) if decimate: n = len(var) var = var[0:n:n//bins] score = w * np.log(var * w * np.sqrt(2*np.pi*np.exp(1))) score[np.isnan(score)]=np....
def entropy_score(var,bins, w=None, decimate=True)
Compute entropy scores, given a variance and # of bins
3.863257
3.410533
1.132743
'''Given a vector x, compute the variance for x[0:i] Thank you http://www.johndcook.com/standard_deviation.html S[i] = S[i-1]+(x[i]-mean[i-1])*(x[i]-mean[i]) var(i) = S[i] / (i-1) ''' n = len(x) # The mean of x[0:i] m = x.cumsum() / np.arange(1,n+1) # x[i]-mean[i-1] for i=1... ...
def running_variance(x)
Given a vector x, compute the variance for x[0:i] Thank you http://www.johndcook.com/standard_deviation.html S[i] = S[i-1]+(x[i]-mean[i-1])*(x[i]-mean[i]) var(i) = S[i] / (i-1)
3.265172
2.309819
1.413605
output = numpy.zeros(labels.shape, labels.dtype) lr_different = labels[1:,:]!=labels[:-1,:] ud_different = labels[:,1:]!=labels[:,:-1] d1_different = labels[1:,1:]!=labels[:-1,:-1] d2_different = labels[1:,:-1]!=labels[:-1,1:] different = numpy.zeros(labels.shape, bool) different[1...
def outline(labels)
Given a label matrix, return a matrix of the outlines of the labeled objects If a pixel is not zero and has at least one neighbor with a different value, then it is part of the outline.
2.039551
1.984559
1.02771
(x1, y1) = point1 (x2, y2) = point2 return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
def euclidean_dist(point1, point2)
Compute the Euclidean distance between two points. Parameters ---------- point1, point2 : 2-tuples of float The input points. Returns ------- d : float The distance between the input points. Examples -------- >>> point1 = (1.0, 2.0) >>> point2 = (4.0, 6.0) # (...
1.662145
2.290898
0.725543
labels = labels.astype(int) areas = scipy.ndimage.measurements.sum(labels != 0, labels, list(range(1, numpy.max(labels) + 1))) existing_labels = [i for (i, a) in enumerate(areas, 1) if a > 0] existing_areas = [a for a in areas if a > 0] existing_centers = scipy.ndima...
def from_labels(labels)
Creates list of cell features based on label image (1-oo pixel values) @return: list of cell features in the same order as labels
3.14085
3.104128
1.01183
traces = [] for d1n, d2n in six.iteritems(assignments): # check if the match is between existing cells if d1n < len(detections_1) and d2n < len(detections_2): traces.append(Trace(detections_1[d1n], detections_2[d2n])) return traces
def from_detections_assignment(detections_1, detections_2, assignments)
Creates traces out of given assignment and cell data.
3.512713
2.996561
1.172248
self.scale = self.parameters_tracking["avgCellDiameter"] / 35.0 detections_1 = self.derive_detections(label_image_1) detections_2 = self.derive_detections(label_image_2) # Calculate tracking based on cell features and position. traces = self.find_initials_traces(detec...
def run_tracking(self, label_image_1, label_image_2)
Tracks cells between input label images. @returns: injective function from old objects to new objects (pairs of [old, new]). Number are compatible with labels.
5.147165
5.183643
0.992963
return cell_detection.area > self.parameters_tracking["big_size"] * self.scale * self.scale
def is_cell_big(self, cell_detection)
Check if the cell is considered big. @param CellFeature cell_detection: @return:
13.602003
19.190386
0.708793
all_cells = [c for c in all_cells if c != cell] sorted_cells = sorted([(cell.distance(c), c) for c in all_cells]) return [sc[1] for sc in sorted_cells[:k] if sc[0] <= max_dist]
def find_closest_neighbours(cell, all_cells, k, max_dist)
Find k closest neighbours of the given cell. :param CellFeatures cell: cell of interest :param all_cells: cell to consider as neighbours :param int k: number of neighbours to be returned :param int max_dist: maximal distance in pixels to consider neighbours :return: k closest nei...
2.635945
3.217633
0.819219
distance = euclidean_dist(d1.center, d2.center) / self.scale area_change = 1 - min(d1.area, d2.area) / max(d1.area, d2.area) return distance + self.parameters_cost_initial["area_weight"] * area_change
def calculate_basic_cost(self, d1, d2)
Calculates assignment cost between two cells.
5.125245
4.989683
1.027168
my_nbrs_with_motion = [n for n in neighbours[d1] if n in motions] my_motion = (d1.center[0] - d2.center[0], d1.center[1] - d2.center[1]) if my_nbrs_with_motion == []: distance = euclidean_dist(d1.center, d2.center) / self.scale else: # it is not in moti...
def calculate_localised_cost(self, d1, d2, neighbours, motions)
Calculates assignment cost between two cells taking into account the movement of cells neighbours. :param CellFeatures d1: detection in first frame :param CellFeatures d2: detection in second frame
3.934789
3.72746
1.055622
global invalid_match size_sum = len(detections_1) + len(detections_2) # Cost matrix extended by matching cells with nothing # (for detection 1 it means losing cells, for detection 2 it means new cells). cost_matrix = numpy.zeros((size_sum, size_sum)) # lost ce...
def calculate_costs(self, detections_1, detections_2, calculate_match_cost, params)
Calculates assignment costs between detections and 'empty' spaces. The smaller cost the better. @param detections_1: cell list of size n in previous frame @param detections_2: cell list of size m in current frame @return: cost matrix (n+m)x(n+m) extended by cost of matching cells with emptines...
2.40426
2.355284
1.020794
if costs is None or len(costs) == 0: return dict() n = costs.shape[0] pairs = [(i, j) for i in range(0, n) for j in range(0, n) if costs[i, j] < invalid_match] costs_list = [costs[i, j] for (i, j) in pairs] assignment = lapjv.lapjv(list(zip(*pairs))[0], l...
def solve_assignement(self, costs)
Solves assignment problem using Hungarian implementation by Brian M. Clapper. @param costs: square cost matrix @return: assignment function @rtype: int->int
3.70434
3.639249
1.017886
rr = np.random.RandomState() rr.seed(0) r = rr.normal(size=image.shape) delta = pow(2.0,-bits) image_copy = np.clip(image, delta, 1) result = np.exp2(np.log2(image_copy + delta) * r + (1-r) * np.log2(image_copy)) result[result>1] = 1 result[result<0] = 0 ...
def smooth_with_noise(image, bits)
Smooth the image with a per-pixel random multiplier image - the image to perturb bits - the noise is this many bits below the pixel value The noise is random with normal distribution, so the individual pixels get either multiplied or divided by a normally distributed # of bits
3.931896
3.664364
1.073009
not_mask = np.logical_not(mask) bleed_over = function(mask.astype(float)) masked_image = np.zeros(image.shape, image.dtype) masked_image[mask] = image[mask] smoothed_image = function(masked_image) output_image = smoothed_image / (ble...
def smooth_with_function_and_mask(image, function, mask)
Smooth an image with a linear function, ignoring the contribution of masked pixels image - image to smooth function - a function that takes an image and returns a smoothed image mask - mask with 1's for significant pixels, 0 for masked pixels This function calculates the fractional contributi...
3.059757
2.965567
1.031761
i,j = np.mgrid[-radius:radius+1,-radius:radius+1].astype(float) / radius mask = i**2 + j**2 <= 1 i = i * radius / sd j = j * radius / sd kernel = np.zeros((2*radius+1,2*radius+1)) kernel[mask] = np.e ** (-(i[mask]**2+j[mask]**2) / (2 * sd **2)) # # Norma...
def circular_gaussian_kernel(sd,radius)
Create a 2-d Gaussian convolution kernel sd - standard deviation of the gaussian in pixels radius - build a circular kernel that convolves all points in the circle bounded by this radius
3.257015
3.388579
0.961174
'''Return an "image" which is a polynomial fit to the pixel data Fit the image to the polynomial Ax**2+By**2+Cxy+Dx+Ey+F pixel_data - a two-dimensional numpy array to be fitted mask - a mask of pixels whose intensities should be considered in the least squares fit ...
def fit_polynomial(pixel_data, mask, clip=True)
Return an "image" which is a polynomial fit to the pixel data Fit the image to the polynomial Ax**2+By**2+Cxy+Dx+Ey+F pixel_data - a two-dimensional numpy array to be fitted mask - a mask of pixels whose intensities should be considered in the least squares fit clip...
3.122214
1.761472
1.772502
global_threshold = get_global_threshold( threshold_method, image, mask, **kwargs) global_threshold *= threshold_correction_factor if not threshold_range_min is None: global_threshold = max(global_threshold, threshold_range_min) if not threshold_range_max is None: global_thre...
def get_threshold(threshold_method, threshold_modifier, image, mask=None, labels = None, threshold_range_min = None, threshold_range_max = None, threshold_correction_factor = 1.0, adaptive_window_size = 10, **kwargs)
Compute a threshold for an image threshold_method - one of the TM_ methods above threshold_modifier - TM_GLOBAL to calculate one threshold over entire image TM_ADAPTIVE to calculate a per-pixel threshold TM_PER_OBJECT to calculate a different threshold for ...
1.83552
1.793157
1.023624
if mask is not None and not np.any(mask): return 1 if threshold_method == TM_OTSU: fn = get_otsu_threshold elif threshold_method == TM_MOG: fn = get_mog_threshold elif threshold_method == TM_BACKGROUND: fn = get_background_threshold elif threshold_method == ...
def get_global_threshold(threshold_method, image, mask = None, **kwargs)
Compute a single threshold over the whole image
3.101054
3.124643
0.992451
# for the X and Y direction, find the # of blocks, given the # size constraints image_size = np.array(image.shape[:2],dtype=int) nblocks = image_size // adaptive_window_size # # Use a floating point block size to apportion the roundoff # roughly equally to each block # incr...
def get_adaptive_threshold(threshold_method, image, threshold, mask = None, adaptive_window_size = 10, **kwargs)
Given a global threshold, compute a threshold per pixel Break the image into blocks, computing the threshold per block. Afterwards, constrain the block threshold to .7 T < t < 1.5 T. Block sizes must be at least 50x50. Images > 500 x 500 get 10x10 blocks.
2.547292
2.491392
1.022437
if labels is None: labels = np.ones(image.shape,int) if not mask is None: labels[np.logical_not(mask)] = 0 label_extents = scipy.ndimage.find_objects(labels,np.max(labels)) local_threshold = np.ones(image.shape,image.dtype) for i, extent in enumerate(label_extents, star...
def get_per_object_threshold(method, image, threshold, mask=None, labels=None, threshold_range_min = None, threshold_range_max = None, **kwargs)
Return a matrix giving threshold per pixel calculated per-object image - image to be thresholded mask - mask out "don't care" pixels labels - a label mask indicating object boundaries threshold - the global threshold
2.630528
2.645854
0.994208
cropped_image = np.array(image.flat) if mask is None else image[mask] if np.product(cropped_image.shape)==0: return 0 img_min = np.min(cropped_image) img_max = np.max(cropped_image) if img_min == img_max: return cropped_image[0] # Only do the histogram between values a ...
def get_background_threshold(image, mask = None)
Get threshold based on the mode of the image The threshold is calculated by calculating the mode and multiplying by 2 (an arbitrary empirical factor). The user will presumably adjust the multiplication factor as needed.
3.624161
3.585111
1.010892
cropped_image = np.array(image.flat) if mask is None else image[mask] n_pixels = np.product(cropped_image.shape) if n_pixels<3: return 0 cropped_image.sort() if cropped_image[0] == cropped_image[-1]: return cropped_image[0] low_chop = int(round(n_pixels * lower_outlie...
def get_robust_background_threshold(image, mask = None, lower_outlier_fraction = 0.05, upper_outlier_fraction = 0.05, deviations_above_average = 2.0, ...
Calculate threshold based on mean & standard deviation The threshold is calculated by trimming the top and bottom 5% of pixels off the image, then calculating the mean and standard deviation of the remaining image. The threshold is then set at 2 (empirical value) standard deviations above th...
2.632797
2.569632
1.024581
'''Calculate the median absolute deviation of a sample a - a numpy array-like collection of values returns the median of the deviation of a from its median. ''' a = np.asfarray(a).flatten() return np.median(np.abs(a - np.median(a)))
def mad(a)
Calculate the median absolute deviation of a sample a - a numpy array-like collection of values returns the median of the deviation of a from its median.
4.842107
2.23916
2.162466
'''Calculate a binned mode of a sample a - array of values This routine bins the sample into np.sqrt(len(a)) bins. This is a number that is a compromise between fineness of measurement and the stochastic nature of counting which roughly scales as the square root of the sample size. ...
def binned_mode(a)
Calculate a binned mode of a sample a - array of values This routine bins the sample into np.sqrt(len(a)) bins. This is a number that is a compromise between fineness of measurement and the stochastic nature of counting which roughly scales as the square root of the sample size.
4.717057
1.920199
2.456546
cropped_image = np.array(image.flat) if mask is None else image[mask] if np.product(cropped_image.shape)<3: return 0 if np.min(cropped_image) == np.max(cropped_image): return cropped_image[0] # We want to limit the dynamic range of the image to 256. Otherwise, # an image wi...
def get_ridler_calvard_threshold(image, mask = None)
Find a threshold using the method of Ridler and Calvard The reference for this method is: "Picture Thresholding Using an Iterative Selection Method" by T. Ridler and S. Calvard, in IEEE Transactions on Systems, Man and Cybernetics, vol. 8, no. 8, August 1978.
3.805231
3.711636
1.025217
cropped_image = np.array(image.flat) if mask is None else image[mask] if np.product(cropped_image.shape)<3: return 0 if np.min(cropped_image) == np.max(cropped_image): return cropped_image[0] log_image = np.log2(smooth_with_noise(cropped_image, 8)) min_log_image = np.min(log_ima...
def get_kapur_threshold(image, mask=None)
The Kapur, Sahoo, & Wong method of thresholding, adapted to log-space.
3.131021
3.049233
1.026823
'''Return the maximum correlation threshold of the image image - image to be thresholded mask - mask of relevant pixels bins - # of value bins to use This is an implementation of the maximum correlation threshold as described in Padmanabhan, "A novel algorithm for optimal ima...
def get_maximum_correlation_threshold(image, mask = None, bins = 256)
Return the maximum correlation threshold of the image image - image to be thresholded mask - mask of relevant pixels bins - # of value bins to use This is an implementation of the maximum correlation threshold as described in Padmanabhan, "A novel algorithm for optimal image thre...
4.369818
3.227086
1.354106
if not np.any(mask): return 0 # # Clamp the dynamic range of the foreground # minval = np.max(image[mask])/256 if minval == 0: return 0 fg = np.log2(np.maximum(image[binary_image & mask], minval)) bg = np.log2(np.maximum(image[(~ binary_image) & mask], minval)) ...
def weighted_variance(image, mask, binary_image)
Compute the log-transformed variance of foreground and background image - intensity image used for thresholding mask - mask of ignored pixels binary_image - binary image marking foreground and background
2.757155
2.825775
0.975717
mask=mask.copy() mask[np.isnan(image)] = False if not np.any(mask): return 0 # # Clamp the dynamic range of the foreground # minval = np.max(image[mask])/256 if minval == 0: return 0 clamped_image = image.copy() clamped_image[clamped_image < minval] = minval ...
def sum_of_entropies(image, mask, binary_image)
Bin the foreground and background pixels and compute the entropy of the distribution of points among the bins
2.634411
2.592509
1.016163
'''Renormalize image intensities to log space Returns a tuple of transformed image and a dictionary to be passed into inverse_log_transform. The minimum and maximum from the dictionary can be applied to an image by the inverse_log_transform to convert it back to its former intensity values. ...
def log_transform(image)
Renormalize image intensities to log space Returns a tuple of transformed image and a dictionary to be passed into inverse_log_transform. The minimum and maximum from the dictionary can be applied to an image by the inverse_log_transform to convert it back to its former intensity values.
5.306401
3.023993
1.754767
'''A version of numpy.histogram that accounts for numpy's version''' args = inspect.getargs(np.histogram.__code__)[0] if args[-1] == "new": return np.histogram(a, bins, range, normed, weights, new=True) return np.histogram(a, bins, range, normed, weights)
def numpy_histogram(a, bins=10, range=None, normed=False, weights=None)
A version of numpy.histogram that accounts for numpy's version
4.495798
3.266151
1.376482
flat_image = image.ravel() sort_order = flat_image.argsort().astype(np.uint32) flat_image = flat_image[sort_order] sort_rank = np.zeros_like(sort_order) is_different = flat_image[:-1] != flat_image[1:] np.cumsum(is_different, out=sort_rank[1:]) original_values = np.zeros((sort_rank[-1]...
def rank_order(image, nbins=None)
Return an image of the same shape where each pixel has the rank-order value of the corresponding pixel in the image. The returned image's elements are of type np.uint32 which simplifies processing in C code.
3.869862
3.895051
0.993533
nobjects = labels.max() objects = np.arange(nobjects + 1) lmin, lmax = scind.extrema(image, labels, objects)[:2] # Divisor is the object's max - min, or 1 if they are the same. divisor = np.ones((nobjects + 1,)) divisor[lmax > lmin] = (lmax - lmin)[lmax > lmin] return (image - lmin[labe...
def normalized_per_object(image, labels)
Normalize the intensities of each object to the [0, 1] range.
4.219025
3.945055
1.069446
tmp = np.array(image // (1.0 / nlevels), dtype='i1') return tmp.clip(0, nlevels - 1)
def quantize(image, nlevels)
Quantize an image into integers 0, 1, ..., nlevels - 1. image -- a numpy array of type float, range [0, 1] nlevels -- an integer
5.376479
6.622518
0.811848
labels = labels.astype(int) nlevels = quantized_image.max() + 1 nobjects = labels.max() if scale_i < 0: scale_i = -scale_i scale_j = -scale_j if scale_i == 0 and scale_j > 0: image_a = quantized_image[:, :-scale_j] image_b = quantized_image[:, scale_j:] l...
def cooccurrence(quantized_image, labels, scale_i=3, scale_j=0)
Calculates co-occurrence matrices for all the objects in the image. Return an array P of shape (nobjects, nlevels, nlevels) such that P[o, :, :] is the cooccurence matrix for object o. quantized_image -- a numpy array of integer type labels -- a numpy array of integer type scale ...
2.057046
2.037417
1.009634
"Correlation." multiplied = np.dot(self.levels[:, np.newaxis] + 1, self.levels[np.newaxis] + 1) repeated = np.tile(multiplied[np.newaxis], (self.nobjects, 1, 1)) summed = (repeated * self.P).sum(2).sum(1) h3 = (summed - self.mux * self.muy) / (self.sig...
def H3(self)
Correlation.
4.326302
4.126328
1.048463
"Inverse difference moment." t = 1 + toeplitz(self.levels) ** 2 repeated = np.tile(t[np.newaxis], (self.nobjects, 1, 1)) return (1.0 / repeated * self.P).sum(2).sum(1)
def H5(self)
Inverse difference moment.
9.045368
6.529066
1.3854
"Sum average." if not hasattr(self, '_H6'): self._H6 = ((self.rlevels2 + 2) * self.p_xplusy).sum(1) return self._H6
def H6(self)
Sum average.
11.780563
8.027865
1.467459
"Sum variance (error in Haralick's original paper here)." h6 = np.tile(self.H6(), (self.rlevels2.shape[1], 1)).transpose() return (((self.rlevels2 + 2) - h6) ** 2 * self.p_xplusy).sum(1)
def H7(self)
Sum variance (error in Haralick's original paper here).
16.881134
7.26288
2.324303
"Sum entropy." return -(self.p_xplusy * np.log(self.p_xplusy + self.eps)).sum(1)
def H8(self)
Sum entropy.
11.965335
7.319232
1.63478
"Entropy." if not hasattr(self, '_H9'): self._H9 = -(self.P * np.log(self.P + self.eps)).sum(2).sum(1) return self._H9
def H9(self)
Entropy.
4.504385
4.073174
1.105866
"Difference variance." c = (self.rlevels * self.p_xminusy).sum(1) c1 = np.tile(c, (self.nlevels,1)).transpose() e = self.rlevels - c1 return (self.p_xminusy * e ** 2).sum(1)
def H10(self)
Difference variance.
8.270352
6.319516
1.3087
"Difference entropy." return -(self.p_xminusy * np.log(self.p_xminusy + self.eps)).sum(1)
def H11(self)
Difference entropy.
11.189375
7.292514
1.534364
"Information measure of correlation 1." maxima = np.vstack((self.hx, self.hy)).max(0) return (self.H9() - self.hxy1) / maxima
def H12(self)
Information measure of correlation 1.
17.561493
8.739474
2.009445
"Information measure of correlation 2." # An imaginary result has been encountered once in the Matlab # version. The reason is unclear. return np.sqrt(1 - np.exp(-2 * (self.hxy2 - self.H9())))
def H13(self)
Information measure of correlation 2.
27.028978
15.464663
1.74779
n_max = np.max(zernike_indexes[:,0]) factorial = np.ones((1 + n_max,), dtype=float) factorial[1:] = np.cumproduct(np.arange(1, 1 + n_max, dtype=float)) width = int(n_max//2 + 1) lut = np.zeros((zernike_indexes.shape[0],width), dtype=float) for idx, (n, m) in enumerate(zernike_indexes): ...
def construct_zernike_lookuptable(zernike_indexes)
Return a lookup table of the sum-of-factorial part of the radial polynomial of the zernike indexes passed zernike_indexes - an Nx2 array of the Zernike polynomials to be computed.
3.078954
3.069936
1.002938
if x.shape != y.shape: raise ValueError("X and Y must have the same shape") if mask is None: pass elif mask.shape != x.shape: raise ValueError("The mask must have the same shape as X and Y") else: x = x[mask] y = y[mask] if weight is not None: ...
def construct_zernike_polynomials(x, y, zernike_indexes, mask=None, weight=None)
Return the zerike polynomials for all objects in an image x - the X distance of a point from the center of its object y - the Y distance of a point from the center of its object zernike_indexes - an Nx2 array of the Zernike polynomials to be computed. mask - a mask with same shape as X and Y of the...
3.014352
3.031576
0.994318
if indexes is None: indexes = np.arange(1,np.max(labels)+1,dtype=np.int32) else: indexes = np.array(indexes, dtype=np.int32) radii = np.asarray(radii, dtype=float) n = radii.size k = zf.shape[2] score = np.zeros((n,k)) if n == 0: return score areas = np.squar...
def score_zernike(zf, radii, labels, indexes=None)
Score the output of construct_zernike_polynomials zf - the output of construct_zernike_polynomials which is I x J x K where K is the number of zernike polynomials computed radii - a vector of the radius of each of N labeled objects labels - a label matrix outputs a N x K matrix of the...
2.339658
2.380074
0.983019
# # "Reverse_indexes" is -1 if a label # is not to be processed. Otherwise # reverse_index[label] gives you the index into indexes of the label # and other similarly shaped vectors (like the results) # indexes = np.array(indexes,dtype=np.int32) nindexes = len(indexes) reverse_indexe...
def zernike(zernike_indexes,labels,indexes)
Compute the Zernike features for the labels with the label #s in indexes returns the score per labels and an array of one image per zernike feature
3.98122
3.888076
1.023956
def zernike_indexes_iter(n_max): for n in range(0, n_max): for m in range(n%2, n+1, 2): yield n yield m z_ind = np.fromiter(zernike_indexes_iter(limit), np.intc) z_ind = z_ind.reshape( (len(z_ind) // 2, 2) ) return z_ind
def get_zernike_indexes(limit=10)
Return a list of all Zernike indexes up to the given limit limit - return all Zernike indexes with N less than this limit returns an array of 2-tuples. Each tuple is organized as (N,M). The Zernikes are stored as complex numbers with the real part being (N,M) and the imaginary being (N,-M)
3.09361
3.34795
0.924031
if image.shape != labels.shape: raise ValueError("Image shape %s != label shape %s" % (repr(image.shape), repr(labels.shape))) if image.shape != mask.shape: raise ValueError("Image shape %s != mask shape %s" % (repr(image.shape), repr(mask.shape))) labels_out = np.zeros(labels.shape, np...
def propagate(image, labels, mask, weight)
Propagate the labels to the nearest pixels image - gives the Z height when computing distance labels - the labeled image pixels mask - only label pixels within the mask weight - the weighting of x/y distance vs z distance high numbers favor x/y, low favor z returns a label m...
2.607027
2.573641
1.012972
'''Perform the reduction transfer step from the Jonker-Volgenant algorithm The data is input in a ragged array in terms of "i" structured as a vector of values for each i,j combination where: ii - the i to be reduced j - the j-index of every entry idx - the index of the first entry for...
def slow_reduction_transfer(ii, j, idx, count, x, u, v, c)
Perform the reduction transfer step from the Jonker-Volgenant algorithm The data is input in a ragged array in terms of "i" structured as a vector of values for each i,j combination where: ii - the i to be reduced j - the j-index of every entry idx - the index of the first entry for each i...
7.326108
1.371971
5.339843
'''Perform the augmenting row reduction step from the Jonker-Volgenaut algorithm n - the number of i and j in the linear assignment problem ii - the unassigned i jj - the j-index of every entry in c idx - the index of the first entry for each i count - the number of entries for each i x...
def slow_augmenting_row_reduction(n, ii, jj, idx, count, x, y, u, v, c)
Perform the augmenting row reduction step from the Jonker-Volgenaut algorithm n - the number of i and j in the linear assignment problem ii - the unassigned i jj - the j-index of every entry in c idx - the index of the first entry for each i count - the number of entries for each i x - the ...
6.279069
4.131418
1.519834
new_records = dict() for lg_name, linkage_group in itertools.groupby( linkage_records, operator.itemgetter(0) ): new_records[lg_name] = [] for record in linkage_group: init_contig = record[-1] start = record[1] end = record[2] n...
def linkage_group_ordering(linkage_records)
Convert degenerate linkage records into ordered info_frags-like records for comparison purposes. Simple example: >>> linkage_records = [ ... ['linkage_group_1', 31842, 94039, 'sctg_207'], ... ['linkage_group_1', 95303, 95303, 'sctg_207'], ... ['linkage_group_2', 15892, 25865, '...
3.081919
2.703942
1.139788
new_scaffolds = {} with open(info_frags, "r") as info_frags_handle: current_new_contig = None for line in info_frags_handle: if line.startswith(">"): current_new_contig = str(line[1:-1]) new_scaffolds[current_new_contig] = [] elif lin...
def parse_info_frags(info_frags)
Import an info_frags.txt file and return a dictionary where each key is a newly formed scaffold and each value is the list of bins and their origin on the initial scaffolding.
2.702206
2.467373
1.095175
new_scaffolds = {} with open(bed_file) as bed_handle: for line in bed_handle: chrom, start, end, query, qual, strand = line.split()[:7] if strand == "+": ori = 1 elif strand == "-": ori = -1 else: raise...
def parse_bed(bed_file)
Import a BED file (where the data entries are analogous to what may be expected in an info_frags.txt file) and return a scaffold dictionary, similarly to parse_info_frags.
3.006172
2.890983
1.039844
new_scaffolds = {} def are_overlapping(bin1, bin2): if bin2 is None: return False init1, _, start1, end1, _ = bin1 init2, _, start2, end2, _ = bin2 if init1 != init2: return False else: return (start2 <= start1 <= end...
def correct_scaffolds(scaffolds, corrector)
Unfinished
2.272612
2.262498
1.004471
if isinstance(info_frags, dict): return info_frags else: try: scaffolds = parse_info_frags(info_frags) return scaffolds except OSError: print("Error when opening info_frags.txt") raise
def format_info_frags(info_frags)
A function to seamlessly run on either scaffold dictionaries or info_frags.txt files without having to check the input first.
3.765832
2.906075
1.295848
scaffolds = format_info_frags(scaffolds) for name, scaffold in scaffolds.items(): plt.figure() xs = range(len(scaffold)) color = [] names = {} ys = [] for my_bin in scaffold: current_color = "r" if my_bin[4] > 0 else "g" color += [cu...
def plot_info_frags(scaffolds)
A crude way to visualize new scaffolds according to their origin on the initial scaffolding. Each scaffold spawns a new plot. Orientations are represented by different colors.
3.018416
3.042775
0.991994
scaffolds = format_info_frags(scaffolds) new_scaffolds = {} for name, scaffold in scaffolds.items(): new_scaffold = [] if len(scaffold) > 2: for i in range(len(scaffold)): # First take care of edge cases: *-- or --* if i == 0: ...
def remove_spurious_insertions(scaffolds)
Remove all bins whose left and right neighbors belong to the same, different scaffold. Example with three such insertions in two different scaffolds: >>> scaffolds = { ... "scaffold1": [ ... ["contig1", 0, 0, 100, 1], ... ["contig1", 1, 100, 200, 1], ...
2.304467
2.319477
0.993529
scaffolds = format_info_frags(scaffolds) new_scaffolds = {} ordering = dict() for name, scaffold in scaffolds.items(): new_scaffold = [] ordering = dict() order = 0 my_blocks = [] for _, my_block in itertools.groupby(scaffold, operator.itemgetter(0)): ...
def rearrange_intra_scaffolds(scaffolds)
Rearranges all bins within each scaffold such that all bins belonging to the same initial contig are grouped together in the same order. When two such groups are found, the smaller one is moved to the larger one.
2.530668
2.527063
1.001427
init_genome = { record.id: record.seq for record in SeqIO.parse(init_fasta, "fasta") } my_new_records = [] with open(info_frags, "r") as info_frags_handle: current_seq = "" current_id = None previous_contig = None for line in info_frags_handle: ...
def write_fasta( init_fasta, info_frags, output=DEFAULT_NEW_GENOME_NAME, junction=False )
Convert an info_frags.txt file into a fasta file given a reference. Optionally adds junction sequences to reflect the possibly missing base pairs between two newly joined scaffolds.
2.311328
2.269135
1.018594
id_set = set((my_bin[1] for my_bin in bin_list)) start_id, end_id = min(id_set), max(id_set) return id_set == set(range(start_id, end_id + 1))
def is_block(bin_list)
Check if a bin list has exclusively consecutive bin ids.
3.265809
2.76362
1.181714
ge = np.empty_like(xi) for i, (v, bound) in enumerate(zip(xi, bounds)): a = bound[0] # minimum b = bound[1] # maximum if a == None and b == None: # No constraints ge[i] = 1.0 elif b == None: # only min ge[i] = v / np.sqrt(v ** 2 + 1) ...
def internal2external_grad(xi, bounds)
Calculate the internal to external gradiant Calculates the partial of external over internal
2.562318
2.582968
0.992005
xe = np.empty_like(xi) for i, (v, bound) in enumerate(zip(xi, bounds)): a = bound[0] # minimum b = bound[1] # maximum if a == None and b == None: # No constraints xe[i] = v elif b == None: # only min xe[i] = a - 1. + np.sqrt(v ** 2. + 1.) ...
def internal2external(xi, bounds)
Convert a series of internal variables to external variables
2.357812
2.371768
0.994116
xi = np.empty_like(xe) for i, (v, bound) in enumerate(zip(xe, bounds)): a = bound[0] # minimum b = bound[1] # maximum if a == None and b == None: # No constraints xi[i] = v elif b == None: # only min xi[i] = np.sqrt((v - a + 1.) ** 2. - 1) ...
def external2internal(xe, bounds)
Convert a series of external variables to internal variables
2.411357
2.427361
0.993407
fjac = infodic["fjac"] ipvt = infodic["ipvt"] n = len(p) # adapted from leastsq function in scipy/optimize/minpack.py perm = np.take(np.eye(n), ipvt - 1, 0) r = np.triu(np.transpose(fjac)[:n, :]) R = np.dot(r, perm) try: cov_x = np.linalg.inv(np.dot(np.transpose(R), R)) ...
def calc_cov_x(infodic, p)
Calculate cov_x from fjac, ipvt and p as is done in leastsq
3.540187
2.997216
1.181158
# check for full output if "full_output" in kw and kw["full_output"]: full = True else: full = False # convert x0 to internal variables i0 = external2internal(x0, bounds) # perfrom unconstrained optimization using internal variables r = leastsq(err, i0, args=(bounds, f...
def leastsqbound(func, x0, bounds, args=(), **kw)
Constrained multivariant Levenberg-Marquard optimization Minimize the sum of squares of a given function using the Levenberg-Marquard algorithm. Contraints on parameters are inforced using variable transformations as described in the MINUIT User's Guide by Fred James and Matthias Winkler. Parame...
4.590624
4.54418
1.010221
if self.set_status: self.github_repo.create_status( state="pending", description="Static analysis in progress.", context="inline-plz", sha=self.last_sha, )
def start_review(self)
Mark our review as started.
7.991633
7.178685
1.113245
if self.set_status: if error: self.github_repo.create_status( state="error", description="Static analysis error! inline-plz failed to run.", context="inline-plz", sha=self.last_sha, ...
def finish_review(self, success=True, error=False)
Mark our review as finished.
2.809036
2.75897
1.018146
try: latest_remote_sha = self.pr_commits(self.pull_request.refresh(True))[-1].sha print("Latest remote sha: {}".format(latest_remote_sha)) try: print("Ratelimit remaining: {}".format(self.github.ratelimit_remaining)) except Exception: ...
def out_of_date(self)
Check if our local latest sha matches the remote latest sha
4.952682
4.363266
1.135086
if not message.line_number: message.line_number = 1 for patched_file in self.patch: target = patched_file.target_file.lstrip("b/") if target == message.path: offset = 1 for hunk in patched_file: for position...
def position(self, message)
Calculate position within the PR, which is not the line number
4.637352
4.360364
1.063524
sparse_dict = dict() h = open(abs_contact_file, "r") all_lines = h.readlines() n_lines = len(all_lines) for i in range(1, n_lines): line = all_lines[i] dat = line.split() mates = [int(dat[0]), int(dat[1])] mates.sort() f1 = mates[0] - 1 f2 = mat...
def abs_contact_2_coo_file(abs_contact_file, coo_file)
Convert contact maps between old-style and new-style formats. A legacy function that converts contact maps from the older GRAAL format to the simpler instaGRAAL format. This is useful with datasets generated by Hi-C box. Parameters ---------- abs_contact_file : str, file or pathlib.Path ...
1.892261
2.000328
0.945975
sparse_dict = dict() h = open(contact_file, "r") all_lines = h.readlines() n_lines = len(all_lines) for i in range(1, n_lines): line = all_lines[i] dat = line.split() mates = [int(dat[0]), int(dat[1])] nc = int(dat[2]) mates.sort() f1 = mates[0]...
def fill_sparse_pyramid_level(pyramid_handle, level, contact_file, nfrags)
Fill a level with sparse contact map data Fill values from the simple text matrix file to the hdf5-based pyramid level with contact data. Parameters ---------- pyramid_handle : h5py.File The hdf5 file handle containing the whole dataset. level : int The level (resolution) t...
2.029
2.051959
0.988811
handle_frag_list = open(fragment_list, "r") handle_new_frag_list = open(new_frag_list, "w") handle_new_frag_list.write( "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % ( "id", "chrom", "start_pos", "end_pos", "size", "gc_...
def init_frag_list(fragment_list, new_frag_list)
Adapt the original fragment list to fit the build function requirements Parameters ---------- fragment_list : str, file or pathlib.Path The input fragment list. new_frag_list : str, file or pathlib.Path The output fragment list to be written. Returns ------- i : int ...
1.753774
1.749032
1.002712
level = curr_frag[1] frag = curr_frag[0] output = [] if level > 0: str_level = str(level) sub_low = self.spec_level[str_level]["fragments_dict"][frag][ "sub_low_index" ] sub_high = self.spec_level[str_level]["fragme...
def zoom_in_frag(self, curr_frag)
:param curr_frag:
2.879413
2.821898
1.020381
level = curr_frag[1] frag = curr_frag[0] output = [] if level > 0: str_level = str(level) high_frag = self.spec_level[str_level]["fragments_dict"][frag][ "super_index" ] new_level = level + 1 output = (h...
def zoom_out_frag(self, curr_frag)
:param curr_frag:
5.031323
4.858779
1.035512