code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
available_runs = [result['params']['RngRun'] for result in
self.get_results()]
yield from DatabaseManager.get_next_values(available_runs) | def get_next_rngruns(self) | Yield the next RngRun values that can be used in this campaign. | 17.547707 | 11.422522 | 1.536238 |
# This dictionary serves as a model for how the keys in the newly
# inserted result should be structured.
example_result = {
'params': {k: ['...'] for k in self.get_params() + ['RngRun']},
'meta': {k: ['...'] for k in ['elapsed_time', 'id']},
}
... | 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)::
{
'params': {
'param1'... | 6.822059 | 4.806293 | 1.419401 |
# In this case, return all results
# A cast to dict is necessary, since self.db.table() contains TinyDB's
# Document object (which is simply a wrapper for a dictionary, thus the
# simple cast).
if result_id is not None:
return [dict(i) for i in self.db.table... | 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
values we are interested in, with multiple values specified as li... | 4.389269 | 4.348163 | 1.009454 |
if isinstance(result, dict):
result_id = result['meta']['id']
else: # Should already be a string containing the id
result_id = result
result_data_dir = os.path.join(self.get_data_dir(), result_id)
filenames = next(os.walk(result_data_dir))[2]
... | def get_result_files(self, result) | Return a dictionary containing filename: filepath values for each
output file associated with an id.
Result can be either a result dictionary (e.g., obtained with the
get_results() method) or a result id. | 2.913197 | 2.571922 | 1.132693 |
if result_id is not None:
results = deepcopy(self.get_results(result_id=result_id))
else:
results = deepcopy(self.get_results(params))
for r in results:
r['output'] = {}
available_files = self.get_result_files(r['meta']['id'])
... | def get_complete_results(self, params=None, result_id=None) | Return available results, analogously to what get_results does, but
also read the corresponding output files for each result, and
incorporate them in the result dictionary under the output key, as a
dictionary of filename: file_contents.
Args:
params (dict): parameter specific... | 2.791218 | 2.402437 | 1.161828 |
# Clean results table
self.db.purge_table('results')
# Get rid of contents of data dir
map(shutil.rmtree, glob.glob(os.path.join(self.get_data_dir(), '*.*'))) | def wipe_results(self) | Remove all results from the database.
This also removes all output files, and cannot be undone. | 6.951356 | 6.563885 | 1.059031 |
# Keys of this level are the same
if set(d1.keys()) != set(d2.keys()):
return False
# Check nested dictionaries
for k1, k2 in zip(sorted(d1.keys()), sorted(d2.keys())):
# If one of the values is a dictionary and the other is not
if isinstance... | def have_same_structure(d1, d2) | Given two dictionaries (possibly with other nested dictionaries as
values), this function checks whether they have the same key structure.
>>> from sem import DatabaseManager
>>> d1 = {'a': 1, 'b': 2}
>>> d2 = {'a': [], 'b': 3}
>>> d3 = {'a': 4, 'c': 5}
>>> DatabaseManag... | 2.367429 | 2.342058 | 1.010832 |
values = collections.OrderedDict([[p, []] for p in
sorted(self.get_params())])
for result in self.get_results():
for param in self.get_params():
values[param] += [result['params'][param]]
sorted_values = collection... | 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. | 3.021084 | 3.035003 | 0.995414 |
return self.helper.string.serialization.serialize(
obj=obj, method=method, beautify=beautify, raise_exception=raise_exception) | def serialize(self, obj, method='json', beautify=False, raise_exception=False) | Alias of helper.string.serialization.serialize | 4.098084 | 2.050485 | 1.998593 |
return self.helper.string.serialization.deserialize(
text, method=method, encoding=encoding, raise_exception=raise_exception) | def deserialize(self, text, method='json', encoding='utf8', raise_exception=False) | Alias of helper.string.serialization.deserialize | 5.09929 | 2.269831 | 2.24655 |
# Open up a session
s = drmaa.Session()
s.initialize()
# Create a job template for each parameter combination
jobs = {}
for parameter in parameter_list:
# Initialize result
current_result = {
'params': {},
... | def run_simulations(self, parameter_list, data_folder) | This function runs multiple simulations in parallel. | 3.354481 | 3.392533 | 0.988783 |
# At the moment, we rely on regex to extract the list of available
# parameters. A tighter integration with waf would allow for a more
# natural extraction of the information.
stdout = self.run_program("%s %s" % (self.script_executable,
... | def get_available_parameters(self) | Return a list of the parameters made available by the script. | 10.118304 | 9.825874 | 1.029761 |
try:
s = drmaa.Session()
s.initialize()
jt = s.createJobTemplate()
jt.remoteCommand = os.path.dirname(
os.path.abspath(__file__)) + '/run_program.sh'
jt.args = [command]
if environment is not None:
... | 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. | 2.846341 | 2.817943 | 1.010077 |
'''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_background[labels == 0] = hi... | def adjacent(labels) | Return a binary mask of all pixels which are adjacent to a pixel of
a different label. | 3.272564 | 2.608837 | 1.254415 |
hit_or_miss = scind.binary_hit_or_miss(image, strel1, strel2)
return np.logical_and(image,np.logical_not(hit_or_miss)) | 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 | 3.594012 | 4.170188 | 0.861835 |
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] = 1
return strel | def strel_disk(radius) | Create a disk structuring element for morphological operations
radius - radius of the disk | 2.419426 | 2.610682 | 0.926741 |
iradius = int(radius)
i, j = np.mgrid[-iradius:(iradius + 1), -iradius:(iradius+1)]
strel = (((i+j) <= radius) & ((i+j) >= -radius) &
((i-j) <= radius) & ((i-j) >= -radius))
return strel | def strel_diamond(radius) | Create a diamond structuring element for morphological operations
radius - the offset of the corners of the diamond from the origin
rounded down (e.g. r=2: (0, 2), (2, 0), (0, -2), (-2, 0))
returns a two-dimensional binary array | 2.817836 | 3.020271 | 0.932975 |
angle = float(angle) * np.pi / 180.
x_off = int(np.finfo(float).eps + np.cos(angle) * length / 2)
# Y is flipped here because "up" is negative
y_off = -int(np.finfo(float).eps + np.sin(angle) * length / 2)
x_center = abs(x_off)
y_center = abs(y_off)
strel = np.zeros((y_center * 2 + 1,
... | def strel_line(length, angle) | Create a line structuring element for morphological operations
length - distance between first and last pixels of the line, rounded down
angle - angle from the horizontal, counter-clockwise in degrees.
Note: uses draw_line's Bresenham algorithm to select points. | 2.507609 | 2.503838 | 1.001506 |
#
# Inscribe a diamond in a square to get an octagon.
#
iradius = int(radius)
i, j = np.mgrid[-iradius:(iradius + 1), -iradius:(iradius+1)]
#
# The distance to the diagonal side is also iradius:
#
# iradius ** 2 = i**2 + j**2 and i = j
# iradius ** 2 = 2 * i ** 2
# i = i... | def strel_octagon(radius) | Create an octagonal structuring element for morphological operations
radius - the distance from the origin to each edge of the octagon | 3.797353 | 3.918345 | 0.969122 |
x_center = int(np.abs(x))
y_center = int(np.abs(y))
result = np.zeros((y_center * 2 + 1, x_center * 2 + 1), bool)
result[y_center, x_center] = True
result[y_center + int(y), x_center + int(x)] = True
return result | 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 | 2.380865 | 2.352432 | 1.012087 |
xoff, yoff, n = [int(t) for t in (xoff, yoff, n)]
center_x, center_y = abs(n * xoff), abs(n * yoff)
result = np.zeros((center_y * 2 + 1, center_x * 2 + 1), bool)
k = np.arange(-n, n+1)
result[center_y + yoff * k, center_x + xoff * k] = True
return result | def strel_periodicline(xoff, yoff, n) | Create a structuring element composed of a line of evenly-spaced points
xoff, yoff - the line goes through the origin and this point
n - the line is composed of the origin and n points on either side of the
origin for a total of 2*n + 1 points
The structuring element is composed of... | 2.535343 | 2.541145 | 0.997717 |
return np.ones([int((hw - 1) // 2) * 2 + 1 for hw in (height, width)], bool) | def strel_rectangle(width, height) | Create a rectangular structuring element
width - the width of the structuring element (in the j direction). The
width will be rounded down to the nearest multiple of 2*n+1
height = the height of the structuring element (in the i direction). The
height will be rounded do... | 6.871542 | 6.758088 | 1.016788 |
center = np.array(structure.shape) // 2
if offset is None:
offset = center
origin = np.array(offset) - center
return scind.maximum_filter(image, footprint=structure, origin=origin,
mode='constant', cval=np.min(image)) | 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
offset - the offset to the center of the structuring element | 3.254833 | 4.324656 | 0.752622 |
#
# Build a label table that converts an old label # into
# labels using the new numbering scheme
#
unique_labels = np.unique(image[image!=0])
if len(unique_labels) == 0:
return (image,0)
consecutive_labels = np.arange(len(unique_labels))+1
label_table = np.zeros(unique_labe... | def relabel(image) | Given a labeled image, relabel each of the objects consecutively
image - a labeled 2-d integer array
returns - (labeled image, object count) | 3.505965 | 3.402454 | 1.030423 |
'''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, points[i,1:], points[inext,1:],1)
... | def convex_hull_image(image) | Given a binary image, return an image of the convex hull | 4.320349 | 4.374887 | 0.987534 |
if indexes is None:
indexes = np.unique(labels)
indexes.sort()
indexes=indexes[indexes!=0]
else:
indexes=np.array(indexes)
if len(indexes) == 0:
return np.zeros((0,2),int),np.zeros((0,),int)
#
# Reduce the # of points to consider
#
outlines = outl... | def convex_hull(labels, indexes=None, fast=True) | Given a labeled image, return a list of points per object ordered by
angle from an interior point, representing the convex hull.s
labels - the label matrix
indexes - an array of label #s to be processed, defaults to all non-zero
labels
Returns a matrix and a vector. The matrix co... | 3.781507 | 3.645708 | 1.037249 |
v1 = (p2 - p1).astype(np.float)
v2 = (p3 - p1).astype(np.float)
# Original:
# cross1 = v1[:,1] * v2[:,0]
# cross2 = v2[:,1] * v1[:,0]
# a = (cross1-cross2) / 2
# Memory reduced:
cross1 = v1[:, 1]
cross1 *= v2[:, 0]
cross2 = v2[:, 1]
cross2 *= v1[:, 0]
a = cross... | 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 | 3.43481 | 3.469392 | 0.990032 |
y0,x0 = pt0
y1,x1 = pt1
diff_y = abs(y1-y0)
diff_x = abs(x1-x0)
x = x0
y = y0
labels[y,x]=value
step_x = (x1 > x0 and 1) or -1
step_y = (y1 > y0 and 1) or -1
if diff_y > diff_x:
# Y varies fastest, do x before y
remainder = diff_x*2 - diff_y
while y !... | def draw_line(labels,pt0,pt1,value=1) | Draw a line between two points
pt0, pt1 are in i,j format which is the reverse of x,y format
Uses the Bresenham algorithm
Some code transcribed from http://www.cs.unc.edu/~mcmillan/comp136/Lecture6/Lines.html | 2.105663 | 1.995505 | 1.055203 |
if getattr(whatever_it_returned,"__getitem__",False):
return np.array(whatever_it_returned)
else:
return np.array([whatever_it_returned]) | def fixup_scipy_ndimage_result(whatever_it_returned) | Convert a result from scipy.ndimage to a numpy array
scipy.ndimage has the annoying habit of returning a single, bare
value instead of an array if the indexes passed in are of length 1.
For instance:
scind.maximum(image, labels, [1]) returns a float
but
scind.maximum(image, labels, [1,2]) r... | 2.595665 | 2.973917 | 0.87281 |
'''Return the i,j coordinates of the centers of a labels matrix
The result returned is an 2 x n numpy array where n is the number
of the label minus one, result[0,x] is the i coordinate of the center
and result[x,1] is the j coordinate of the center.
You can unpack the result as "i,j = centers_... | def centers_of_labels(labels) | Return the i,j coordinates of the centers of a labels matrix
The result returned is an 2 x n numpy array where n is the number
of the label minus one, result[0,x] is the i coordinate of the center
and result[x,1] is the j coordinate of the center.
You can unpack the result as "i,j = centers_of_labe... | 4.465417 | 1.994051 | 2.239369 |
'''Return the i,j coordinates of the maximum value within each object
image - measure the maximum within this image
labels - use the objects within this labels matrix
indices - label #s to measure
The result returned is an 2 x n numpy array where n is the number
of the label minus one,... | def maximum_position_of_labels(image, labels, indices) | Return the i,j coordinates of the maximum value within each object
image - measure the maximum within this image
labels - use the objects within this labels matrix
indices - label #s to measure
The result returned is an 2 x n numpy array where n is the number
of the label minus one, result... | 6.02579 | 1.911704 | 3.152051 |
'''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
'''
if hull_a.shape[0] < 3 or hull_b.shape[0] < 3:
... | 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 | 2.726506 | 1.783581 | 1.528669 |
'''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 hull_a:
for pt_b in hull_b:
... | def slow_minimum_distance2(hull_a, hull_b) | Do the minimum distance by exhaustive examination of all points | 2.781738 | 2.566301 | 1.083948 |
'''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 segment against the cross products from
# both poi... | 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 | 2.579469 | 2.506892 | 1.028951 |
'''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_start
else:
# Go in th... | def find_farthest(point, hull) | Find the vertex in hull farthest away from a point | 2.514901 | 2.39667 | 1.049331 |
'''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 distance from the line between observer and back... | 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 distance from the line between observer and background.... | 3.484785 | 1.844533 | 1.88925 |
'''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 reshape:
pt.shape = l0.sha... | 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 | 2.447439 | 2.070063 | 1.182302 |
'''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 | def within_hull(point, hull) | Return true if the point is within the convex hull | 3.104686 | 3.127426 | 0.992729 |
'''Find which vectors have all-true elements
Given an array, "a" and indexes into the first elements of vectors
within that array, return an array where each element is true if
all elements of the corresponding vector are true.
Example: a = [ 1,1,0,1,1,1,1], indexes=[0,3]
vect... | def all_true(a, indexes) | Find which vectors have all-true elements
Given an array, "a" and indexes into the first elements of vectors
within that array, return an array where each element is true if
all elements of the corresponding vector are true.
Example: a = [ 1,1,0,1,1,1,1], indexes=[0,3]
vectors = [... | 3.683472 | 2.003498 | 1.83852 |
if len(indexes) == 0:
return (np.zeros((0,2)), np.zeros((0,)), np.zeros((0,)),
np.zeros((0,)),np.zeros((0,)))
i,j = np.argwhere(labels != 0).transpose()
return ellipse_from_second_moments_ijv(i,j,image[i,j], labels[i,j], indexes, wants_compactness) | def ellipse_from_second_moments(image, labels, indexes, wants_compactness = False) | Calculate measurements of ellipses equivalent to the second moments of labels
image - the intensity at each point
labels - for each labeled object, derive an ellipse
indexes - sequence of indexes to process
returns the following arrays:
coordinates of the center of the ellipse
e... | 2.811697 | 2.913486 | 0.965063 |
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(scind.minimum(x, labels, indexes))
xmax = fix(scind.maximum(x, labels, indexes))
ymin = fix(scind.minimum(y,... | def calculate_extents(labels, indexes) | Return the area of each object divided by the area of its bounding box | 2.84906 | 2.7343 | 1.04197 |
#
# 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(labels)
pixel_score = __perimeter_scoring[m]
return fixup_scipy_ndimage_result(scind.sum(pixel_score, labels, np.arra... | def calculate_perimeters(labels, indexes) | Count the distances between adjacent pixels in the perimeters of the labels | 12.68632 | 12.316647 | 1.030014 |
'''Return an array of indexes into a morphology lookup table
labels - a labels matrix
returns a matrix of values between 0 and 511 of indices appropriate
for table_lookup where a pixel's index is determined based on whether
or not the pixel has the same label as its neighbors (and is labeled)
... | def table_idx_from_labels(labels) | Return an array of indexes into a morphology lookup table
labels - a labels matrix
returns a matrix of values between 0 and 511 of indices appropriate
for table_lookup where a pixel's index is determined based on whether
or not the pixel has the same label as its neighbors (and is labeled) | 4.181766 | 2.385289 | 1.753149 |
if indexes is not None:
indexes = np.array(indexes,dtype=np.int32)
areas = scind.sum(np.ones(labels.shape),labels,indexes)
convex_hull_areas = calculate_convex_hull_areas(labels, indexes)
return areas / convex_hull_areas | 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 | 4.202816 | 3.761574 | 1.117303 |
shape = np.array(shape)
block_shape = np.array(block_shape)
i,j = np.mgrid[0:shape[0],0:shape[1]]
ijmax = (shape.astype(float)/block_shape.astype(float)).astype(int)
ijmax = np.maximum(ijmax, 1)
multiplier = ijmax.astype(float) / shape.astype(float)
i = (i * multiplier[0]).astype(int)
... | def block(shape, block_shape) | Create a labels image that divides the image into blocks
shape - the shape of the image to be blocked
block_shape - the shape of one block
returns a labels matrix and the indexes of all labels generated
The idea here is to block-process an image by using SciPy label
routines. This rou... | 2.553919 | 2.594615 | 0.984315 |
'''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 significant pixels in the image. Points outside of
the m... | 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 significant pixels in the image. Points outside of
the mask wil... | 5.432225 | 2.664855 | 2.038469 |
'''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 significant pixels in the image. Points outside of
the m... | 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 significant pixels in the image. Points outside of
the mask wil... | 6.362772 | 3.157264 | 2.015281 |
'''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 = max(1, np.max(np.array(footprint.shape) // 2))
iradius = int(np... | def grey_erosion(image, radius=None, mask=None, footprint=None) | Perform a grey erosion with masking | 2.69004 | 2.708525 | 0.993175 |
'''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 operations
'''
eroded_image = grey_erosion(image, radi... | 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 operations | 4.927049 | 2.168481 | 2.27212 |
'''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 unmasked pixels for operations
'''
dilated_image = grey_dilat... | 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 unmasked pixels for operations | 5.259422 | 2.080625 | 2.527809 |
nAngles = 180//dAngle
openingstack = np.zeros((nAngles,image.shape[0],image.shape[1]),image.dtype)
for iAngle in range(nAngles):
angle = dAngle * iAngle
se = strel_line(linelength,angle)
openingstack[iAngle,:,:] = opening(image, mask=mask, footprint=se)
imLines = np.max(op... | 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
length - length of the structural element
angluar_resolution - angle ... | 3.414423 | 3.67617 | 0.928799 |
'''Perform a morphological transform on an image, directed by its neighbors
image - a binary image
table - a 512-element table giving the transform of each pixel given
the values of that pixel and its 8-connected neighbors.
border_value - the value of pixels beyond the border of the ima... | def table_lookup(image, table, border_value, iterations = None) | Perform a morphological transform on an image, directed by its neighbors
image - a binary image
table - a 512-element table giving the transform of each pixel given
the values of that pixel and its 8-connected neighbors.
border_value - the value of pixels beyond the border of the image.
... | 3.491475 | 2.496384 | 1.398613 |
'''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) | def pattern_of(index) | Return the pattern represented by an index value | 2.547508 | 2.253209 | 1.130613 |
'''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) | def index_of(pattern) | Return the index of a given pattern | 1.823087 | 1.794459 | 1.015954 |
'''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 value is true if the pattern
must match at th... | 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 value is true if the pattern
must match at that posi... | 3.881137 | 2.19147 | 1.77102 |
'''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:
masked_image = image
else:
... | 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 | 4.886368 | 2.321281 | 2.105031 |
'''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 aft = 2. An endpoint
has one ... | 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 aft = 2. An endpoint
has one branch.... | 6.124542 | 2.373902 | 2.579948 |
'''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] = False
result = table_lookup(masked_image, b... | 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 | 3.867439 | 2.375436 | 1.628097 |
'''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 = image
else:
masked_image = image.asty... | 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. | 4.965124 | 2.491963 | 1.992454 |
'''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[~mask] = False
result = table_lookup(mask... | 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 ? | 4.561491 | 2.535667 | 1.798931 |
'''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_image = image
else:
... | 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 | 4.627199 | 2.252181 | 2.054541 |
'''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
result = table_lookup(masked_image, fill_ta... | 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 | 3.415129 | 2.507438 | 1.361999 |
'''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
result = table_lookup(masked_image, fil... | 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 | 3.895884 | 2.50944 | 1.552491 |
'''Remove horizontal breaks
1 1 1 1 1 1
0 1 0 -> 0 0 0 (this case only)
1 1 1 1 1 1
'''
global hbreak_table
if mask is None:
masked_image = image
else:
masked_image = image.astype(bool).copy()
masked_image[~mask] = False
result = table_lookup(mas... | def hbreak(image, mask=None, iterations=1) | Remove horizontal breaks
1 1 1 1 1 1
0 1 0 -> 0 0 0 (this case only)
1 1 1 1 1 1 | 3.744528 | 2.405768 | 1.556479 |
'''Remove horizontal breaks
1 1 1 1 1 1
0 1 0 -> 0 0 0 (this case only)
1 1 1 1 1 1
'''
global vbreak_table
if mask is None:
masked_image = image
else:
masked_image = image.astype(bool).copy()
masked_image[~mask] = False
result = table_lookup(mas... | def vbreak(image, mask=None, iterations=1) | Remove horizontal breaks
1 1 1 1 1 1
0 1 0 -> 0 0 0 (this case only)
1 1 1 1 1 1 | 3.890568 | 2.448033 | 1.589263 |
'''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(masked_image, majority_table, False, iteration... | def majority(image, mask=None, iterations=1) | A pixel takes the value of the majority of its neighbors | 3.961994 | 3.473124 | 1.140758 |
'''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()
masked_image[~mask] = False
result ... | 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 ? | 5.005267 | 2.614547 | 1.914392 |
'''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[~mask] = False
index_i, index_j, masked... | 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 ? | 3.069102 | 2.578575 | 1.190232 |
'''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 = image
else:
masked_image = imag... | 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 ? ? ? | 3.710635 | 2.063251 | 1.798441 |
'''Thin an image to lines, preserving Euler number
Implements thinning as described in algorithm # 1 from
Guo, "Parallel Thinning with Two Subiteration Algorithms",
Communications of the ACM, Vol 32 #3 page 359.
'''
global thin_table, eight_connect
if thin_table is None:
thin_ta... | def thin(image, mask=None, iterations=1) | Thin an image to lines, preserving Euler number
Implements thinning as described in algorithm # 1 from
Guo, "Parallel Thinning with Two Subiteration Algorithms",
Communications of the ACM, Vol 32 #3 page 359. | 3.378658 | 2.611367 | 1.293827 |
'''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()
order = np.lexsort((rlabels, colors.rav... | def distance_color_labels(labels) | Recolor a labels matrix so that adjacent labels have distant numbers | 7.142723 | 6.363606 | 1.122433 |
'''Color a labels matrix so that no adjacent labels have the same color
distance_transform - if true, distance transform the labels to find out
which objects are closest to each other.
Create a label coloring matrix which assigns a color (1-n) to each pixel
in the labels matrix s... | def color_labels(labels, distance_transform = False) | Color a labels matrix so that no adjacent labels have the same color
distance_transform - if true, distance transform the labels to find out
which objects are closest to each other.
Create a label coloring matrix which assigns a color (1-n) to each pixel
in the labels matrix such tha... | 5.445582 | 3.451466 | 1.577759 |
'''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 skeletonized
mask - only skeletonize pixels wit... | 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 skeletonized
mask - only skeletonize pixels within the... | 4.907971 | 3.70509 | 1.324657 |
'''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 labels
result = np.zeros(labels.s... | def skeletonize_labels(labels) | Skeletonize a labels matrix | 4.244234 | 4.399155 | 0.964784 |
'''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
if __skel_length_table is None:
... | 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. | 3.715226 | 3.083791 | 1.204759 |
'''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 result
for i in range(1, m... | 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 | 3.798887 | 2.645179 | 1.436155 |
'''Associate each label in i with a component #
This function finds all connected components given an array of
associations between labels i and j using a depth-first search.
i & j give the edges of the graph. The first step of the algorithm makes
bidirectional edges, (i->j and j<-i), so i... | def all_connected_components(i,j) | Associate each label in i with a component #
This function finds all connected components given an array of
associations between labels i and j using a depth-first search.
i & j give the edges of the graph. The first step of the algorithm makes
bidirectional edges, (i->j and j<-i), so it's bes... | 5.352625 | 2.280618 | 2.347006 |
'''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 matrix with odd dimensions, center is taken to
... | 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 matrix with odd dimensions, center is taken to
... | 2.970374 | 2.54538 | 1.166967 |
'''For each object in labels, compute the angular distribution
around the centers of mass. Returns an i x j matrix, where i is
the number of objects in the label matrix, and j is the resolution
of the distribution (default 100), mapped from -pi to pi.
Optionally, the distributions can be weighted ... | def angular_distribution(labels, resolution=100, weights=None) | For each object in labels, compute the angular distribution
around the centers of mass. Returns an i x j matrix, where i is
the number of objects in the label matrix, and j is the resolution
of the distribution (default 100), mapped from -pi to pi.
Optionally, the distributions can be weighted by pixe... | 4.160002 | 2.330529 | 1.785003 |
'''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 = p1[:,0]
p2x = p2[:,1... | 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 | 2.676318 | 1.764568 | 1.516698 |
(M,N) = x.shape
Mean = x.mean(0)
y = x - Mean
cov = numpy.dot(y.transpose(),y) / (M-1)
(V,PC) = numpy.linalg.eig(cov)
order = (-V).argsort()
coeff = PC[:,order]
return coeff | def princomp(x) | Determine the principal components of a vector of measurements
Determine the principal components of a vector of measurements
x should be a M x N numpy array composed of M observations of n variables
The output is:
coeffs - the NxN correlation matrix that can be used to transform x into its compone... | 3.837716 | 3.608865 | 1.063414 |
'''Return an (n*(n - 1)) x 2 array of all non-identity pairs of n things
n - # of things
The array is (cleverly) ordered so that the first m * (m - 1) elements
can be used for m < n things:
n = 3
[[0, 1], # n = 2
[1, 0], # n = 2
[0, 2],
[1, 2],
[2, 0],
[2,... | def all_pairs(n) | Return an (n*(n - 1)) x 2 array of all non-identity pairs of n things
n - # of things
The array is (cleverly) ordered so that the first m * (m - 1) elements
can be used for m < n things:
n = 3
[[0, 1], # n = 2
[1, 0], # n = 2
[0, 2],
[1, 2],
[2, 0],
[2, 1]] | 5.289998 | 2.349223 | 2.251807 |
'''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:
return image
if mask is... | 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 | 2.493174 | 1.856108 | 1.343227 |
'''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 pixels in the octagon,
count them and c... | 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 pixels in the octagon,
count them and choose t... | 5.285609 | 2.182629 | 2.421671 |
'''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//2
i,j = np.mgrid[-half_size:half_size+1,
... | 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 | 4.337165 | 3.763666 | 1.152378 |
'''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. Roberts Machine Perception of 3-D ... | 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. Roberts Machine Perception of 3-D Solids,... | 5.143636 | 2.770459 | 1.8566 |
'''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.
Note that scipy's Sobel ret... | 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.
Note that scipy's Sobel returns a ... | 8.476197 | 1.683072 | 5.036147 |
'''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 + vprewitt(image,mask)**2) | 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. | 5.998957 | 2.026275 | 2.960583 |
'''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
'''
if mask is None:
mas... | 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 | 3.884563 | 2.117502 | 1.834503 |
'''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 centroids of each object
in the image. Sum... | 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 centroids of each object
in the image. Summing th... | 3.745717 | 2.728782 | 1.37267 |
'''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],
[True, True, True],
[False, True, Fa... | 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 | 3.493456 | 2.777637 | 1.257708 |
'''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.array([[False, True, False],
[True, True, True],... | 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 | 4.597618 | 3.139588 | 1.464402 |
'''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],
[0,0,1,0],
... | 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 | 4.780557 | 2.086572 | 2.291106 |
'''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) | def reverse_velocity_kalman_model() | Return a KalmanState set up to model going backwards in time | 3.95774 | 2.571224 | 1.539243 |
'''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 in radians. We integrate perpendicular to this ang... | 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 in radians. We integrate perpendicular to this angle
... | 3.388121 | 2.422561 | 1.39857 |
'''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 pixels in the image
'''
if mask is None:
... | 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 pixels in the image | 3.841584 | 2.57962 | 1.489205 |
'''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([ [cofactor_n(x, ... | def inv_n(x) | given N matrices, return N inverses | 4.200914 | 3.978336 | 1.055948 |
'''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.prod([x[:, i,... | def det_n(x) | given N matrices, return N determinants | 3.018605 | 2.833926 | 1.065167 |
'''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 is a cycle:
... | 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 is a cycle:
for i... | 4.86463 | 1.815182 | 2.679968 |
'''Return the cofactor of n matrices x[n,i,j] at position i,j
The cofactor is the determinant of the matrix formed by removing
row i and column j.
'''
m = x.shape[1]
mr = np.arange(m)
i_idx = mr[mr != i]
j_idx = mr[mr != j]
return det_n(x[:, i_idx[:, np.newaxis],
... | def cofactor_n(x, i, j) | Return the cofactor of n matrices x[n,i,j] at position i,j
The cofactor is the determinant of the matrix formed by removing
row i and column j. | 3.986803 | 2.498512 | 1.595671 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.