_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q17700
ParallelRunner.launch_simulation
train
def launch_simulation(self, parameter): """ Launch a single simulation, using SimulationRunner's facilities. This function is used by ParallelRunner's run_simulations to map simulation running over the parameter list. Args: parameter (dict): the parameter combinatio...
python
{ "resource": "" }
q17701
JsonHelper.stringify
train
def stringify(self, obj, beautify=False, raise_exception=False): """Alias of helper.string.serialization.json.stringify""" return self.helper.string.serialization.json.stringify( obj=obj, beautify=beautify, raise_exception=raise_exception)
python
{ "resource": "" }
q17702
JsonHelper.parse
train
def parse(self, text, encoding='utf8', raise_exception=False): """Alias of helper.string.serialization.json.parse""" return self.helper.string.serialization.json.parse( text=text, encoding=encoding, raise_exception=raise_exception)
python
{ "resource": "" }
q17703
DatabaseManager.new
train
def new(cls, script, commit, params, campaign_dir, overwrite=False): """ Initialize a new class instance with a set configuration and filename. The created database has the same name of the campaign directory. Args: script (str): the ns-3 name of the script that will be use...
python
{ "resource": "" }
q17704
DatabaseManager.load
train
def load(cls, campaign_dir): """ Initialize from an existing database. It is assumed that the database json file has the same name as its containing folder. Args: campaign_dir (str): The path to the campaign directory. """ # We only accept absolute ...
python
{ "resource": "" }
q17705
DatabaseManager.get_next_rngruns
train
def get_next_rngruns(self): """ Yield the next RngRun values that can be used in this campaign. """ available_runs = [result['params']['RngRun'] for result in self.get_results()] yield from DatabaseManager.get_next_values(available_runs)
python
{ "resource": "" }
q17706
DatabaseManager.insert_result
train
def insert_result(self, result): """ Insert a new result in the database. This function also verifies that the result dictionaries saved in the database have the following structure (with {'a': 1} representing a dictionary, 'a' a key and 1 its value):: { ...
python
{ "resource": "" }
q17707
DatabaseManager.get_results
train
def get_results(self, params=None, result_id=None): """ Return all the results available from the database that fulfill some parameter combinations. If params is None (or not specified), return all results. If params is specified, it must be a dictionary specifying the result ...
python
{ "resource": "" }
q17708
DatabaseManager.wipe_results
train
def wipe_results(self): """ Remove all results from the database. This also removes all output files, and cannot be undone. """ # Clean results table self.db.purge_table('results') # Get rid of contents of data dir map(shutil.rmtree, glob.glob(os.path.jo...
python
{ "resource": "" }
q17709
DatabaseManager.get_all_values_of_all_params
train
def get_all_values_of_all_params(self): """ Return a dictionary containing all values that are taken by all available parameters. Always returns the parameter list in alphabetical order. """ values = collections.OrderedDict([[p, []] for p in ...
python
{ "resource": "" }
q17710
SerializationHelper.serialize
train
def serialize(self, obj, method='json', beautify=False, raise_exception=False): """Alias of helper.string.serialization.serialize""" return self.helper.string.serialization.serialize( obj=obj, method=method, beautify=beautify, raise_exception=raise_exception)
python
{ "resource": "" }
q17711
SerializationHelper.deserialize
train
def deserialize(self, text, method='json', encoding='utf8', raise_exception=False): """Alias of helper.string.serialization.deserialize""" return self.helper.string.serialization.deserialize( text, method=method, encoding=encoding, raise_exception=raise_exception)
python
{ "resource": "" }
q17712
GridRunner.run_program
train
def run_program(self, command, working_directory=os.getcwd(), environment=None, cleanup_files=True, native_spec="-l cputype=intel"): """ Run a program through the grid, capturing the standard output. """ try: s = drmaa.Session() ...
python
{ "resource": "" }
q17713
adjacent
train
def adjacent(labels): '''Return a binary mask of all pixels which are adjacent to a pixel of a different label. ''' high = labels.max()+1 if high > np.iinfo(labels.dtype).max: labels = labels.astype(np.int) image_with_high_background = labels.copy() image_with_high_backgr...
python
{ "resource": "" }
q17714
binary_thin
train
def binary_thin(image, strel1, strel2): """Morphologically thin an image strel1 - the required values of the pixels in order to survive strel2 - at each pixel, the complement of strel1 if we care about the value """ hit_or_miss = scind.binary_hit_or_miss(image, strel1, strel2) return np.logical_...
python
{ "resource": "" }
q17715
strel_disk
train
def strel_disk(radius): """Create a disk structuring element for morphological operations radius - radius of the disk """ iradius = int(radius) x,y = np.mgrid[-iradius:iradius+1,-iradius:iradius+1] radius2 = radius * radius strel = np.zeros(x.shape) strel[x*x+y*y <= radius2] =...
python
{ "resource": "" }
q17716
strel_octagon
train
def strel_octagon(radius): """Create an octagonal structuring element for morphological operations radius - the distance from the origin to each edge of the octagon """ # # Inscribe a diamond in a square to get an octagon. # iradius = int(radius) i, j = np.mgrid[-iradius:(iradius + ...
python
{ "resource": "" }
q17717
strel_pair
train
def strel_pair(x, y): """Create a structing element composed of the origin and another pixel x, y - x and y offsets of the other pixel returns a structuring element """ x_center = int(np.abs(x)) y_center = int(np.abs(y)) result = np.zeros((y_center * 2 + 1, x_center * 2 + 1), bool...
python
{ "resource": "" }
q17718
cpmaximum
train
def cpmaximum(image, structure=np.ones((3,3),dtype=bool),offset=None): """Find the local maximum at each point in the image, using the given structuring element image - a 2-d array of doubles structure - a boolean structuring element indicating which local elements should be sampled ...
python
{ "resource": "" }
q17719
convex_hull_image
train
def convex_hull_image(image): '''Given a binary image, return an image of the convex hull''' labels = image.astype(int) points, counts = convex_hull(labels, np.array([1])) output = np.zeros(image.shape, int) for i in range(counts[0]): inext = (i+1) % counts[0] draw_line(output, point...
python
{ "resource": "" }
q17720
triangle_areas
train
def triangle_areas(p1,p2,p3): """Compute an array of triangle areas given three arrays of triangle pts p1,p2,p3 - three Nx2 arrays of points """ v1 = (p2 - p1).astype(np.float) v2 = (p3 - p1).astype(np.float) # Original: # cross1 = v1[:,1] * v2[:,0] # cross2 = v2[:,1] * v1[:,0] ...
python
{ "resource": "" }
q17721
minimum_distance2
train
def minimum_distance2(hull_a, center_a, hull_b, center_b): '''Return the minimum distance or 0 if overlap between 2 convex hulls hull_a - list of points in clockwise direction center_a - a point within the hull hull_b - list of points in clockwise direction center_b - a point within the hull ...
python
{ "resource": "" }
q17722
slow_minimum_distance2
train
def slow_minimum_distance2(hull_a, hull_b): '''Do the minimum distance by exhaustive examination of all points''' d2_min = np.iinfo(int).max for a in hull_a: if within_hull(a, hull_b): return 0 for b in hull_b: if within_hull(b, hull_a): return 0 for pt_a in h...
python
{ "resource": "" }
q17723
lines_intersect
train
def lines_intersect(pt1_p, pt2_p, pt1_q, pt2_q): '''Return true if two line segments intersect pt1_p, pt2_p - endpoints of first line segment pt1_q, pt2_q - endpoints of second line segment ''' # # The idea here is to do the cross-product of the vector from # point 1 to point 2 of one segmen...
python
{ "resource": "" }
q17724
find_farthest
train
def find_farthest(point, hull): '''Find the vertex in hull farthest away from a point''' d_start = np.sum((point-hull[0,:])**2) d_end = np.sum((point-hull[-1,:])**2) if d_start > d_end: # Go in the forward direction i = 1 inc = 1 term = hull.shape[0] d2_max = d_st...
python
{ "resource": "" }
q17725
find_visible
train
def find_visible(hull, observer, background): '''Given an observer location, find the first and last visible points in the hull The observer at "observer" is looking at the hull whose most distant vertex from the observer is "background. Find the vertices that are the furthest di...
python
{ "resource": "" }
q17726
distance2_to_line
train
def distance2_to_line(pt, l0, l1): '''The perpendicular distance squared from a point to a line pt - point in question l0 - one point on the line l1 - another point on the line ''' pt = np.atleast_1d(pt) l0 = np.atleast_1d(l0) l1 = np.atleast_1d(l1) reshape = pt.ndim == 1 if...
python
{ "resource": "" }
q17727
within_hull
train
def within_hull(point, hull): '''Return true if the point is within the convex hull''' h_prev_pt = hull[-1,:] for h_pt in hull: if np.cross(h_pt-h_prev_pt, point - h_pt) >= 0: return False h_prev_pt = h_pt return True
python
{ "resource": "" }
q17728
calculate_extents
train
def calculate_extents(labels, indexes): """Return the area of each object divided by the area of its bounding box""" fix = fixup_scipy_ndimage_result areas = fix(scind.sum(np.ones(labels.shape),labels,np.array(indexes, dtype=np.int32))) y,x = np.mgrid[0:labels.shape[0],0:labels.shape[1]] xmin = fix(...
python
{ "resource": "" }
q17729
calculate_perimeters
train
def calculate_perimeters(labels, indexes): """Count the distances between adjacent pixels in the perimeters of the labels""" # # Create arrays that tell whether a pixel is like its neighbors. # index = 0 is the pixel -1,-1 from the pixel of interest, 1 is -1,0, etc. # m = table_idx_from_labels(l...
python
{ "resource": "" }
q17730
calculate_solidity
train
def calculate_solidity(labels,indexes=None): """Calculate the area of each label divided by the area of its convex hull labels - a label matrix indexes - the indexes of the labels to measure """ if indexes is not None: """ Convert to compat 32bit integer """ indexes = np.array(i...
python
{ "resource": "" }
q17731
white_tophat
train
def white_tophat(image, radius=None, mask=None, footprint=None): '''White tophat filter an image using a circular structuring element image - image in question radius - radius of the circular structuring element. If no radius, use an 8-connected structuring element. mask - mask of sig...
python
{ "resource": "" }
q17732
black_tophat
train
def black_tophat(image, radius=None, mask=None, footprint=None): '''Black tophat filter an image using a circular structuring element image - image in question radius - radius of the circular structuring element. If no radius, use an 8-connected structuring element. mask - mask of sig...
python
{ "resource": "" }
q17733
grey_erosion
train
def grey_erosion(image, radius=None, mask=None, footprint=None): '''Perform a grey erosion with masking''' if footprint is None: if radius is None: footprint = np.ones((3,3),bool) radius = 1 else: footprint = strel_disk(radius)==1 else: radius = ma...
python
{ "resource": "" }
q17734
opening
train
def opening(image, radius=None, mask=None, footprint=None): '''Do a morphological opening image - pixel image to operate on radius - use a structuring element with the given radius. If no radius, use an 8-connected structuring element. mask - if present, only use unmasked pixels for op...
python
{ "resource": "" }
q17735
closing
train
def closing(image, radius=None, mask=None, footprint = None): '''Do a morphological closing image - pixel image to operate on radius - use a structuring element with the given radius. If no structuring element, use an 8-connected structuring element. mask - if present, only use unmaske...
python
{ "resource": "" }
q17736
openlines
train
def openlines(image, linelength=10, dAngle=10, mask=None): """ Do a morphological opening along lines of different angles. Return difference between max and min response to different angles for each pixel. This effectively removes dots and only keeps lines. image - pixel image to operate on le...
python
{ "resource": "" }
q17737
pattern_of
train
def pattern_of(index): '''Return the pattern represented by an index value''' return np.array([[index & 2**0,index & 2**1,index & 2**2], [index & 2**3,index & 2**4,index & 2**5], [index & 2**6,index & 2**7,index & 2**8]], bool)
python
{ "resource": "" }
q17738
index_of
train
def index_of(pattern): '''Return the index of a given pattern''' return (pattern[0,0] * 2**0 + pattern[0,1] * 2**1 + pattern[0,2] * 2**2 + pattern[1,0] * 2**3 + pattern[1,1] * 2**4 + pattern[1,2] * 2**5 + pattern[2,0] * 2**6 + pattern[2,1] * 2**7 + pattern[2,2] * 2**8)
python
{ "resource": "" }
q17739
make_table
train
def make_table(value, pattern, care=np.ones((3,3),bool)): '''Return a table suitable for table_lookup value - set all table entries matching "pattern" to "value", all others to not "value" pattern - a 3x3 boolean array with the pattern to match care - a 3x3 boolean array where each v...
python
{ "resource": "" }
q17740
branchpoints
train
def branchpoints(image, mask=None): '''Remove all pixels from an image except for branchpoints image - a skeletonized image mask - a mask of pixels excluded from consideration 1 0 1 ? 0 ? 0 1 0 -> 0 1 0 0 1 0 0 ? 0 ''' global branchpoints_table if mask is None: ...
python
{ "resource": "" }
q17741
branchings
train
def branchings(image, mask=None): '''Count the number of branches eminating from each pixel image - a binary image mask - optional mask of pixels not to consider This is the count of the number of branches that eminate from a pixel. A pixel with neighbors fore and aft has branches fore and...
python
{ "resource": "" }
q17742
bridge
train
def bridge(image, mask=None, iterations = 1): '''Fill in pixels that bridge gaps. 1 0 0 1 0 0 0 0 0 -> 0 1 0 0 0 1 0 0 1 ''' global bridge_table if mask is None: masked_image = image else: masked_image = image.astype(bool).copy() masked_image[~mask] = F...
python
{ "resource": "" }
q17743
clean
train
def clean(image, mask=None, iterations = 1): '''Remove isolated pixels 0 0 0 0 0 0 0 1 0 -> 0 0 0 0 0 0 0 0 0 Border pixels and pixels adjoining masks are removed unless one valid neighbor is true. ''' global clean_table if mask is None: masked_image = imag...
python
{ "resource": "" }
q17744
diag
train
def diag(image, mask=None, iterations=1): '''4-connect pixels that are 8-connected 0 0 0 0 0 ? 0 0 1 -> 0 1 1 0 1 0 ? 1 ? ''' global diag_table if mask is None: masked_image = image else: masked_image = image.astype(bool).copy() masked_image[~ma...
python
{ "resource": "" }
q17745
endpoints
train
def endpoints(image, mask=None): '''Remove all pixels from an image except for endpoints image - a skeletonized image mask - a mask of pixels excluded from consideration 1 0 0 ? 0 0 0 1 0 -> 0 1 0 0 0 0 0 0 0 ''' global endpoints_table if mask is None: masked...
python
{ "resource": "" }
q17746
fill
train
def fill(image, mask=None, iterations=1): '''Fill isolated black pixels 1 1 1 1 1 1 1 0 1 -> 1 1 1 1 1 1 1 1 1 ''' global fill_table if mask is None: masked_image = image else: masked_image = image.astype(bool).copy() masked_image[~mask] = True r...
python
{ "resource": "" }
q17747
fill4
train
def fill4(image, mask=None, iterations=1): '''Fill 4-connected black pixels x 1 x x 1 x 1 0 1 -> 1 1 1 x 1 x x 1 x ''' global fill4_table if mask is None: masked_image = image else: masked_image = image.astype(bool).copy() masked_image[~mask] = True ...
python
{ "resource": "" }
q17748
majority
train
def majority(image, mask=None, iterations=1): '''A pixel takes the value of the majority of its neighbors ''' global majority_table if mask is None: masked_image = image else: masked_image = image.astype(bool).copy() masked_image[~mask] = False result = table_lookup(...
python
{ "resource": "" }
q17749
remove
train
def remove(image, mask=None, iterations=1): '''Turn 1 pixels to 0 if their 4-connected neighbors are all 0 ? 1 ? ? 1 ? 1 1 1 -> 1 0 1 ? 1 ? ? 1 ? ''' global remove_table if mask is None: masked_image = image else: masked_image = image.astype(bool).copy() ...
python
{ "resource": "" }
q17750
spur
train
def spur(image, mask=None, iterations=1): '''Remove spur pixels from an image 0 0 0 0 0 0 0 1 0 -> 0 0 0 0 0 1 0 0 ? ''' global spur_table_1,spur_table_2 if mask is None: masked_image = image else: masked_image = image.astype(bool).copy() masked_image[~...
python
{ "resource": "" }
q17751
thicken
train
def thicken(image, mask=None, iterations=1): '''Thicken the objects in an image where doing so does not connect them 0 0 0 ? ? ? 0 0 0 -> ? 1 ? 0 0 1 ? ? ? 1 0 0 ? ? ? 0 0 0 -> ? 0 ? 0 0 1 ? ? ? ''' global thicken_table if mask is None: masked_image ...
python
{ "resource": "" }
q17752
distance_color_labels
train
def distance_color_labels(labels): '''Recolor a labels matrix so that adjacent labels have distant numbers ''' # # Color labels so adjacent ones are most distant # colors = color_labels(labels, True) # # Order pixels by color, then label # # rlabels = labels.ravel() orde...
python
{ "resource": "" }
q17753
skeletonize
train
def skeletonize(image, mask=None, ordering = None): '''Skeletonize the image Take the distance transform. Order the 1 points by the distance transform. Remove a point if it has more than 1 neighbor and if removing it does not change the Euler number. image - the binary image to be skel...
python
{ "resource": "" }
q17754
skeletonize_labels
train
def skeletonize_labels(labels): '''Skeletonize a labels matrix''' # # The trick here is to separate touching labels by coloring the # labels matrix and then processing each color separately # colors = color_labels(labels) max_color = np.max(colors) if max_color == 0: return label...
python
{ "resource": "" }
q17755
skeleton_length
train
def skeleton_length(labels, indices=None): '''Compute the length of all skeleton branches for labeled skeletons labels - a labels matrix indices - the indexes of the labels to be measured. Default is all returns an array of one skeleton length per label. ''' global __skel_length_table ...
python
{ "resource": "" }
q17756
distance_to_edge
train
def distance_to_edge(labels): '''Compute the distance of a pixel to the edge of its object labels - a labels matrix returns a matrix of distances ''' colors = color_labels(labels) max_color = np.max(colors) result = np.zeros(labels.shape) if max_color == 0: return resul...
python
{ "resource": "" }
q17757
is_local_maximum
train
def is_local_maximum(image, labels, footprint): '''Return a boolean array of points that are local maxima image - intensity image labels - find maxima only within labels. Zero is reserved for background. footprint - binary mask indicating the neighborhood to be examined must be a ma...
python
{ "resource": "" }
q17758
is_obtuse
train
def is_obtuse(p1, v, p2): '''Determine whether the angle, p1 - v - p2 is obtuse p1 - N x 2 array of coordinates of first point on edge v - N x 2 array of vertex coordinates p2 - N x 2 array of coordinates of second point on edge returns vector of booleans ''' p1x = p1[:,1] p1y ...
python
{ "resource": "" }
q17759
stretch
train
def stretch(image, mask=None): '''Normalize an image to make the minimum zero and maximum one image - pixel data to be normalized mask - optional mask of relevant pixels. None = don't mask returns the stretched image ''' image = np.array(image, float) if np.product(image.shape) == 0: ...
python
{ "resource": "" }
q17760
median_filter
train
def median_filter(data, mask, radius, percent=50): '''Masked median filter with octagonal shape data - array of data to be median filtered. mask - mask of significant pixels in data radius - the radius of a circle inscribed into the filtering octagon percent - conceptually, order the significant pi...
python
{ "resource": "" }
q17761
bilateral_filter
train
def bilateral_filter(image, mask, sigma_spatial, sigma_range, sampling_spatial = None, sampling_range = None): """Bilateral filter of an image image - image to be bilaterally filtered mask - mask of significant points in image sigma_spatial - standard deviation of the spatial Gaus...
python
{ "resource": "" }
q17762
laplacian_of_gaussian
train
def laplacian_of_gaussian(image, mask, size, sigma): '''Perform the Laplacian of Gaussian transform on the image image - 2-d image array mask - binary mask of significant pixels size - length of side of square kernel to use sigma - standard deviation of the Gaussian ''' half_size = size//...
python
{ "resource": "" }
q17763
roberts
train
def roberts(image, mask=None): '''Find edges using the Roberts algorithm image - the image to process mask - mask of relevant points The algorithm returns the magnitude of the output of the two Roberts convolution kernels. The following is the canonical citation for the algorithm: L. Rob...
python
{ "resource": "" }
q17764
sobel
train
def sobel(image, mask=None): '''Calculate the absolute magnitude Sobel to find the edges image - image to process mask - mask of relevant points Take the square root of the sum of the squares of the horizontal and vertical Sobels to get a magnitude that's somewhat insensitive to direction. ...
python
{ "resource": "" }
q17765
prewitt
train
def prewitt(image, mask=None): '''Find the edge magnitude using the Prewitt transform image - image to process mask - mask of relevant points Return the square root of the sum of squares of the horizontal and vertical Prewitt transforms. ''' return np.sqrt(hprewitt(image,mask)**2 + vprewi...
python
{ "resource": "" }
q17766
hprewitt
train
def hprewitt(image, mask=None): '''Find the horizontal edges of an image using the Prewitt transform image - image to process mask - mask of relevant points We use the following kernel and return the absolute value of the result at each point: 1 1 1 0 0 0 -1 -1 -1 ''' ...
python
{ "resource": "" }
q17767
gabor
train
def gabor(image, labels, frequency, theta): '''Gabor-filter the objects in an image image - 2-d grayscale image to filter labels - a similarly shaped labels matrix frequency - cycles per trip around the circle theta - angle of the filter. 0 to 2 pi Calculate the Gabor filter centered on the ce...
python
{ "resource": "" }
q17768
enhance_dark_holes
train
def enhance_dark_holes(image, min_radius, max_radius, mask=None): '''Enhance dark holes using a rolling ball filter image - grayscale 2-d image radii - a vector of radii: we enhance holes at each given radius ''' # # Do 4-connected erosion # se = np.array([[False, True, False], ...
python
{ "resource": "" }
q17769
granulometry_filter
train
def granulometry_filter(image, min_radius, max_radius, mask=None): '''Enhances bright structures within a min and max radius using a rolling ball filter image - grayscale 2-d image radii - a vector of radii: we enhance holes at each given radius ''' # # Do 4-connected erosion # se = np....
python
{ "resource": "" }
q17770
velocity_kalman_model
train
def velocity_kalman_model(): '''Return a KalmanState set up to model objects with constant velocity The observation and measurement vectors are i,j. The state vector is i,j,vi,vj ''' om = np.array([[1,0,0,0], [0, 1, 0, 0]]) tm = np.array([[1,0,1,0], [0,1,0,1], ...
python
{ "resource": "" }
q17771
reverse_velocity_kalman_model
train
def reverse_velocity_kalman_model(): '''Return a KalmanState set up to model going backwards in time''' om = np.array([[1,0,0,0], [0, 1, 0, 0]]) tm = np.array([[1,0,-1,0], [0,1,0,-1], [0,0,1,0], [0,0,0,1]]) return KalmanState(om, tm)
python
{ "resource": "" }
q17772
line_integration
train
def line_integration(image, angle, decay, sigma): '''Integrate the image along the given angle DIC images are the directional derivative of the underlying image. This filter reconstructs the original image by integrating along that direction. image - a 2-dimensional array angle - shear angle ...
python
{ "resource": "" }
q17773
variance_transform
train
def variance_transform(img, sigma, mask=None): '''Calculate a weighted variance of the image This function caluclates the variance of an image, weighting the local contributions by a Gaussian. img - image to be transformed sigma - standard deviation of the Gaussian mask - mask of relevant pixe...
python
{ "resource": "" }
q17774
inv_n
train
def inv_n(x): '''given N matrices, return N inverses''' # # The inverse of a small matrix (e.g. 3x3) is # # 1 # ----- C(j,i) # det(A) # # where C(j,i) is the cofactor of matrix A at position j,i # assert x.ndim == 3 assert x.shape[1] == x.shape[2] c = np.array([ [...
python
{ "resource": "" }
q17775
det_n
train
def det_n(x): '''given N matrices, return N determinants''' assert x.ndim == 3 assert x.shape[1] == x.shape[2] if x.shape[1] == 1: return x[:,0,0] result = np.zeros(x.shape[0]) for permutation in permutations(np.arange(x.shape[1])): sign = parity(permutation) result += np...
python
{ "resource": "" }
q17776
parity
train
def parity(x): '''The parity of a permutation The parity of a permutation is even if the permutation can be formed by an even number of transpositions and is odd otherwise. The parity of a permutation is even if there are an even number of compositions of even size and odd otherwise. A composition...
python
{ "resource": "" }
q17777
dot_n
train
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,...
python
{ "resource": "" }
q17778
permutations
train
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 ] ...
python
{ "resource": "" }
q17779
circular_hough
train
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...
python
{ "resource": "" }
q17780
poisson_equation
train
def poisson_equation(image, gradient=1, max_iter=100, convergence=.01, percentile = 90.0): '''Estimate the solution to the Poisson Equation The Poisson Equation is the solution to gradient(x) = h^2/4 and, in this context, we use a boundary condition where x is zero for background pixels. Also, we set h...
python
{ "resource": "" }
q17781
KalmanState.predicted_state_vec
train
def predicted_state_vec(self): '''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]...
python
{ "resource": "" }
q17782
KalmanState.predicted_obs_vec
train
def predicted_obs_vec(self): '''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...
python
{ "resource": "" }
q17783
KalmanState.map_frames
train
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 ''' nfeatures = len(old_indices) noldfeatures = len(self.state_vec) ...
python
{ "resource": "" }
q17784
KalmanState.add_features
train
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 t...
python
{ "resource": "" }
q17785
KalmanState.deep_copy
train
def deep_copy(self): '''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()...
python
{ "resource": "" }
q17786
spline_factors
train
def spline_factors(u): '''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
python
{ "resource": "" }
q17787
gauss
train
def gauss(x,m_y,sigma): '''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)
python
{ "resource": "" }
q17788
d2gauss
train
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.''' return gauss(x,m_y,sigma)*[-1/sigma**2 + (n-m_y)**2/sigma**4 for n in x]
python
{ "resource": "" }
q17789
spline_matrix2d
train
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.''' V = np.kron(spline_matrix(x,px),spline_matrix(y,py)) lenV = len(V) if mask is not None: indices = np.nonzero(mask.T.fla...
python
{ "resource": "" }
q17790
otsu
train
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 maxi...
python
{ "resource": "" }
q17791
entropy
train
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 """ ...
python
{ "resource": "" }
q17792
otsu3
train
def otsu3(data, min_threshold=None, max_threshold=None,bins=128): """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 thres...
python
{ "resource": "" }
q17793
outline
train
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. """ output = numpy.zeros(labels.shape, labels.dtype) lr_different = labels[1...
python
{ "resource": "" }
q17794
euclidean_dist
train
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 = ...
python
{ "resource": "" }
q17795
Trace.from_detections_assignment
train
def from_detections_assignment(detections_1, detections_2, assignments): """ Creates traces out of given assignment and cell data. """ traces = [] for d1n, d2n in six.iteritems(assignments): # check if the match is between existing cells if d1n < len(dete...
python
{ "resource": "" }
q17796
NeighbourMovementTracking.run_tracking
train
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. """ self.scale = self.parameters_tracking["avgCellDiameter"] ...
python
{ "resource": "" }
q17797
NeighbourMovementTracking.is_cell_big
train
def is_cell_big(self, cell_detection): """ Check if the cell is considered big. @param CellFeature cell_detection: @return: """ return cell_detection.area > self.parameters_tracking["big_size"] * self.scale * self.scale
python
{ "resource": "" }
q17798
NeighbourMovementTracking.calculate_basic_cost
train
def calculate_basic_cost(self, d1, d2): """ Calculates assignment cost between two cells. """ 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["are...
python
{ "resource": "" }
q17799
NeighbourMovementTracking.calculate_localised_cost
train
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 """ ...
python
{ "resource": "" }