neulab/docprompting-conala huggingface dataset:
__init__(label_image=None, connectivity=1, data=None, **attr) [source]
 
Initialize a graph with edges, name, or graph attributes.  Parameters 
 
incoming_graph_datainput graph (optional, default: None) 

Data to initialize graph. If None (default) an empty graph is created. The data can be an edge list, or any NetworkX graph object. If the corresponding optional Python packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph.  
attrkeyword arguments, optional (default= no attributes) 

Attributes to add to graph as key=value pairs.      See also  
convert 
  Examples >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G = nx.Graph(name="my graph")
>>> e = [(1, 2), (2, 3), (3, 4)]  # list of edges
>>> G = nx.Graph(e)
 Arbitrary graph attribute pairs (key=value) may be assigned >>> G = nx.Graph(e, day="Friday")
>>> G.graph
{'day': 'Friday'}
skimage.future.graph.rag_boundary(labels, edge_map, connectivity=2) [source]
 
Comouter RAG based on region boundaries Given an image’s initial segmentation and its edge map this method constructs the corresponding Region Adjacency Graph (RAG). Each node in the RAG represents a set of pixels within the image with the same label in labels. The weight between two adjacent regions is the average value in edge_map along their boundary.  
labelsndarray 

The labelled image.  
edge_mapndarray 

This should have the same shape as that of labels. For all pixels along the boundary between 2 adjacent regions, the average value of the corresponding pixels in edge_map is the edge weight between them.  
connectivityint, optional 

Pixels with a squared distance less than connectivity from each other are considered adjacent. It can range from 1 to labels.ndim. Its behavior is the same as connectivity parameter in scipy.ndimage.filters.generate_binary_structure.   Examples >>> from skimage import data, segmentation, filters, color
>>> from skimage.future import graph
>>> img = data.chelsea()
>>> labels = segmentation.slic(img)
>>> edge_map = filters.sobel(color.rgb2gray(img))
>>> rag = graph.rag_boundary(labels, edge_map)
skimage.future.graph.rag_mean_color(image, labels, connectivity=2, mode='distance', sigma=255.0) [source]
 
Compute the Region Adjacency Graph using mean colors. Given an image and its initial segmentation, this method constructs the corresponding Region Adjacency Graph (RAG). Each node in the RAG represents a set of pixels within image with the same label in labels. The weight between two adjacent regions represents how similar or dissimilar two regions are depending on the mode parameter.  Parameters 
 
imagendarray, shape(M, N, […, P,] 3) 

Input image.  
labelsndarray, shape(M, N, […, P]) 

The labelled image. This should have one dimension less than image. If image has dimensions (M, N, 3) labels should have dimensions (M, N).  
connectivityint, optional 

Pixels with a squared distance less than connectivity from each other are considered adjacent. It can range from 1 to labels.ndim. Its behavior is the same as connectivity parameter in scipy.ndimage.generate_binary_structure.  
mode{‘distance’, ‘similarity’}, optional 

The strategy to assign edge weights. ‘distance’ : The weight between two adjacent regions is the \(|c_1 - c_2|\), where \(c_1\) and \(c_2\) are the mean colors of the two regions. It represents the Euclidean distance in their average color. ‘similarity’ : The weight between two adjacent is \(e^{-d^2/sigma}\) where \(d=|c_1 - c_2|\), where \(c_1\) and \(c_2\) are the mean colors of the two regions. It represents how similar two regions are.  
sigmafloat, optional 

Used for computation when mode is “similarity”. It governs how close to each other two colors should be, for their corresponding edge weight to be significant. A very large value of sigma could make any two colors behave as though they were similar.    Returns 
 
outRAG 

The region adjacency graph.     References  
1  
Alain Tremeau and Philippe Colantoni “Regions Adjacency Graph Applied To Color Image Segmentation” DOI:10.1109/83.841950   Examples >>> from skimage import data, segmentation
>>> from skimage.future import graph
>>> img = data.astronaut()
>>> labels = segmentation.slic(img)
>>> rag = graph.rag_mean_color(img, labels)
skimage.future.graph.show_rag(labels, rag, image, border_color='black', edge_width=1.5, edge_cmap='magma', img_cmap='bone', in_place=True, ax=None) [source]
 
Show a Region Adjacency Graph on an image. Given a labelled image and its corresponding RAG, show the nodes and edges of the RAG on the image with the specified colors. Edges are displayed between the centroid of the 2 adjacent regions in the image.  Parameters 
 
labelsndarray, shape (M, N) 

The labelled image.  
ragRAG 

The Region Adjacency Graph.  
imagendarray, shape (M, N[, 3]) 

Input image. If colormap is None, the image should be in RGB format.  
border_colorcolor spec, optional 

Color with which the borders between regions are drawn.  
edge_widthfloat, optional 

The thickness with which the RAG edges are drawn.  
edge_cmapmatplotlib.colors.Colormap, optional 

Any matplotlib colormap with which the edges are drawn.  
img_cmapmatplotlib.colors.Colormap, optional 

Any matplotlib colormap with which the image is draw. If set to None the image is drawn as it is.  
in_placebool, optional 

If set, the RAG is modified in place. For each node n the function will set a new attribute rag.nodes[n]['centroid'].  
axmatplotlib.axes.Axes, optional 

The axes to draw on. If not specified, new axes are created and drawn on.    Returns 
 
lcmatplotlib.collections.LineCollection 

A colection of lines that represent the edges of the graph. It can be passed to the matplotlib.figure.Figure.colorbar() function.     Examples >>> from skimage import data, segmentation
>>> from skimage.future import graph
>>> import matplotlib.pyplot as plt
>>>
>>> img = data.coffee()
>>> labels = segmentation.slic(img)
>>> g =  graph.rag_mean_color(img, labels)
>>> lc = graph.show_rag(labels, g, img)
>>> cbar = plt.colorbar(lc)
skimage.future.manual_lasso_segmentation(image, alpha=0.4, return_all=False) [source]
 
Return a label image based on freeform selections made with the mouse.  Parameters 
 
image(M, N[, 3]) array 

Grayscale or RGB image.  
alphafloat, optional 

Transparency value for polygons drawn over the image.  
return_allbool, optional 

If True, an array containing each separate polygon drawn is returned. (The polygons may overlap.) If False (default), latter polygons “overwrite” earlier ones where they overlap.    Returns 
 
labelsarray of int, shape ([Q, ]M, N) 

The segmented regions. If mode is ‘separate’, the leading dimension of the array corresponds to the number of regions that the user drew.     Notes Press and hold the left mouse button to draw around each object. Examples >>> from skimage import data, future, io
>>> camera = data.camera()
>>> mask = future.manual_lasso_segmentation(camera)  
>>> io.imshow(mask)  
>>> io.show()
skimage.future.manual_polygon_segmentation(image, alpha=0.4, return_all=False) [source]
 
Return a label image based on polygon selections made with the mouse.  Parameters 
 
image(M, N[, 3]) array 

Grayscale or RGB image.  
alphafloat, optional 

Transparency value for polygons drawn over the image.  
return_allbool, optional 

If True, an array containing each separate polygon drawn is returned. (The polygons may overlap.) If False (default), latter polygons “overwrite” earlier ones where they overlap.    Returns 
 
labelsarray of int, shape ([Q, ]M, N) 

The segmented regions. If mode is ‘separate’, the leading dimension of the array corresponds to the number of regions that the user drew.     Notes Use left click to select the vertices of the polygon and right click to confirm the selection once all vertices are selected. Examples >>> from skimage import data, future, io
>>> camera = data.camera()
>>> mask = future.manual_polygon_segmentation(camera)  
>>> io.imshow(mask)  
>>> io.show()
skimage.future.predict_segmenter(features, clf) [source]
 
Segmentation of images using a pretrained classifier.  Parameters 
 
featuresndarray 

Array of features, with the last dimension corresponding to the number of features, and the other dimensions are compatible with the shape of the image to segment, or a flattened image.  
clfclassifier object 

trained classifier object, exposing a predict method as in scikit-learn’s API, for example an instance of RandomForestClassifier or LogisticRegression classifier. The classifier must be already trained, for example with skimage.segmentation.fit_segmenter().    Returns 
 
outputndarray 

Labeled array, built from the prediction of the classifier.
class skimage.future.TrainableSegmenter(clf=None, features_func=None) [source]
 
Bases: object Estimator for classifying pixels.  Parameters 
 
clfclassifier object, optional 

classifier object, exposing a fit and a predict method as in scikit-learn’s API, for example an instance of RandomForestClassifier or LogisticRegression classifier.  
features_funcfunction, optional 

function computing features on all pixels of the image, to be passed to the classifier. The output should be of shape (m_features, *labels.shape). If None, skimage.segmentation.multiscale_basic_features() is used.     Methods  
fit(image, labels) Train classifier using partially labeled (annotated) image.  
predict(image) Segment new image using trained internal classifier.    
compute_features     
__init__(clf=None, features_func=None) [source]
 
Initialize self. See help(type(self)) for accurate signature. 
  
compute_features(image) [source]

  
fit(image, labels) [source]
 
Train classifier using partially labeled (annotated) image.  Parameters 
 
imagendarray 

Input image, which can be grayscale or multichannel, and must have a number of dimensions compatible with self.features_func.  
labelsndarray of ints 

Labeled array of shape compatible with image (same shape for a single-channel image). Labels >= 1 correspond to the training set and label 0 to unlabeled pixels to be segmented.     
  
predict(image) [source]
 
Segment new image using trained internal classifier.  Parameters 
 
imagendarray 

Input image, which can be grayscale or multichannel, and must have a number of dimensions compatible with self.features_func.    Raises 
 
NotFittedError if self.clf has not been fitted yet (use self.fit).
fit(image, labels) [source]
 
Train classifier using partially labeled (annotated) image.  Parameters 
 
imagendarray 

Input image, which can be grayscale or multichannel, and must have a number of dimensions compatible with self.features_func.  
labelsndarray of ints 

Labeled array of shape compatible with image (same shape for a single-channel image). Labels >= 1 correspond to the training set and label 0 to unlabeled pixels to be segmented.
predict(image) [source]
 
Segment new image using trained internal classifier.  Parameters 
 
imagendarray 

Input image, which can be grayscale or multichannel, and must have a number of dimensions compatible with self.features_func.    Raises 
 
NotFittedError if self.clf has not been fitted yet (use self.fit).
__init__(clf=None, features_func=None) [source]
 
Initialize self. See help(type(self)) for accurate signature.
find_costs()  
Find the minimum-cost path from the given starting points. This method finds the minimum-cost path to the specified ending indices from any one of the specified starting indices. If no end positions are given, then the minimum-cost path to every position in the costs array will be found.  Parameters 
 
startsiterable 

A list of n-d starting indices (where n is the dimension of the costs array). The minimum cost path to the closest/cheapest starting point will be found.  
endsiterable, optional 

A list of n-d ending indices.  
find_all_endsbool, optional 

If ‘True’ (default), the minimum-cost-path to every specified end-position will be found; otherwise the algorithm will stop when a a path is found to any end-position. (If no ends were specified, then this parameter has no effect.)    Returns 
 
cumulative_costsndarray 

Same shape as the costs array; this array records the minimum cost path from the nearest/cheapest starting index to each index considered. (If ends were specified, not all elements in the array will necessarily be considered: positions not evaluated will have a cumulative cost of inf. If find_all_ends is ‘False’, only one of the specified end-positions will have a finite cumulative cost.)  
tracebackndarray 

Same shape as the costs array; this array contains the offset to any given index from its predecessor index. The offset indices index into the offsets attribute, which is a array of n-d offsets. In the 2-d case, if offsets[traceback[x, y]] is (-1, -1), that means that the predecessor of [x, y] in the minimum cost path to some start position is [x+1, y+1]. Note that if the offset_index is -1, then the given index was not considered.
goal_reached()  
int goal_reached(int index, float cumcost) This method is called each iteration after popping an index from the heap, before examining the neighbours. This method can be overloaded to modify the behavior of the MCP algorithm. An example might be to stop the algorithm when a certain cumulative cost is reached, or when the front is a certain distance away from the seed point. This method should return 1 if the algorithm should not check the current point’s neighbours and 2 if the algorithm is now done.
traceback(end)  
Trace a minimum cost path through the pre-calculated traceback array. This convenience function reconstructs the the minimum cost path to a given end position from one of the starting indices provided to find_costs(), which must have been called previously. This function can be called as many times as desired after find_costs() has been run.  Parameters 
 
enditerable 

An n-d index into the costs array.    Returns 
 
tracebacklist of n-d tuples 

A list of indices into the costs array, starting with one of the start positions passed to find_costs(), and ending with the given end index. These indices specify the minimum-cost path from any given start index to the end index. (The total cost of that path can be read out from the cumulative_costs array returned by find_costs().)
__init__(costs, offsets=None, fully_connected=True, sampling=None)  
See class documentation.
class skimage.graph.MCP_Connect(costs, offsets=None, fully_connected=True)  
Bases: skimage.graph._mcp.MCP Connect source points using the distance-weighted minimum cost function. A front is grown from each seed point simultaneously, while the origin of the front is tracked as well. When two fronts meet, create_connection() is called. This method must be overloaded to deal with the found edges in a way that is appropriate for the application.  
__init__(*args, **kwargs)  
Initialize self. See help(type(self)) for accurate signature. 
  
create_connection()  
create_connection id1, id2, pos1, pos2, cost1, cost2) Overload this method to keep track of the connections that are found during MCP processing. Note that a connection with the same ids can be found multiple times (but with different positions and costs). At the time that this method is called, both points are “frozen” and will not be visited again by the MCP algorithm.  Parameters 
 
id1int 

The seed point id where the first neighbor originated from.  
id2int 

The seed point id where the second neighbor originated from.  
pos1tuple 

The index of of the first neighbour in the connection.  
pos2tuple 

The index of of the second neighbour in the connection.  
cost1float 

The cumulative cost at pos1.  
cost2float 

The cumulative costs at pos2.
create_connection()  
create_connection id1, id2, pos1, pos2, cost1, cost2) Overload this method to keep track of the connections that are found during MCP processing. Note that a connection with the same ids can be found multiple times (but with different positions and costs). At the time that this method is called, both points are “frozen” and will not be visited again by the MCP algorithm.  Parameters 
 
id1int 

The seed point id where the first neighbor originated from.  
id2int 

The seed point id where the second neighbor originated from.  
pos1tuple 

The index of of the first neighbour in the connection.  
pos2tuple 

The index of of the second neighbour in the connection.  
cost1float 

The cumulative cost at pos1.  
cost2float 

The cumulative costs at pos2.
__init__(*args, **kwargs)  
Initialize self. See help(type(self)) for accurate signature.
class skimage.graph.MCP_Flexible(costs, offsets=None, fully_connected=True)  
Bases: skimage.graph._mcp.MCP Find minimum cost paths through an N-d costs array. See the documentation for MCP for full details. This class differs from MCP in that several methods can be overloaded (from pure Python) to modify the behavior of the algorithm and/or create custom algorithms based on MCP. Note that goal_reached can also be overloaded in the MCP class.  
__init__(costs, offsets=None, fully_connected=True, sampling=None)  
See class documentation. 
  
examine_neighbor(index, new_index, offset_length)  
This method is called once for every pair of neighboring nodes, as soon as both nodes are frozen. This method can be overloaded to obtain information about neightboring nodes, and/or to modify the behavior of the MCP algorithm. One example is the MCP_Connect class, which checks for meeting fronts using this hook. 
  
travel_cost(old_cost, new_cost, offset_length)  
This method calculates the travel cost for going from the current node to the next. The default implementation returns new_cost. Overload this method to adapt the behaviour of the algorithm. 
  
update_node(index, new_index, offset_length)  
This method is called when a node is updated, right after new_index is pushed onto the heap and the traceback map is updated. This method can be overloaded to keep track of other arrays that are used by a specific implementation of the algorithm. For instance the MCP_Connect class uses it to update an id map.
examine_neighbor(index, new_index, offset_length)  
This method is called once for every pair of neighboring nodes, as soon as both nodes are frozen. This method can be overloaded to obtain information about neightboring nodes, and/or to modify the behavior of the MCP algorithm. One example is the MCP_Connect class, which checks for meeting fronts using this hook.
travel_cost(old_cost, new_cost, offset_length)  
This method calculates the travel cost for going from the current node to the next. The default implementation returns new_cost. Overload this method to adapt the behaviour of the algorithm.
update_node(index, new_index, offset_length)  
This method is called when a node is updated, right after new_index is pushed onto the heap and the traceback map is updated. This method can be overloaded to keep track of other arrays that are used by a specific implementation of the algorithm. For instance the MCP_Connect class uses it to update an id map.
class skimage.graph.MCP_Geometric(costs, offsets=None, fully_connected=True)  
Bases: skimage.graph._mcp.MCP Find distance-weighted minimum cost paths through an n-d costs array. See the documentation for MCP for full details. This class differs from MCP in that the cost of a path is not simply the sum of the costs along that path. This class instead assumes that the costs array contains at each position the “cost” of a unit distance of travel through that position. For example, a move (in 2-d) from (1, 1) to (1, 2) is assumed to originate in the center of the pixel (1, 1) and terminate in the center of (1, 2). The entire move is of distance 1, half through (1, 1) and half through (1, 2); thus the cost of that move is (1/2)*costs[1,1] + (1/2)*costs[1,2]. On the other hand, a move from (1, 1) to (2, 2) is along the diagonal and is sqrt(2) in length. Half of this move is within the pixel (1, 1) and the other half in (2, 2), so the cost of this move is calculated as (sqrt(2)/2)*costs[1,1] + (sqrt(2)/2)*costs[2,2]. These calculations don’t make a lot of sense with offsets of magnitude greater than 1. Use the sampling argument in order to deal with anisotropic data.  
__init__(costs, offsets=None, fully_connected=True, sampling=None)  
See class documentation.
skimage.graph.route_through_array(array, start, end, fully_connected=True, geometric=True) [source]
 
Simple example of how to use the MCP and MCP_Geometric classes. See the MCP and MCP_Geometric class documentation for explanation of the path-finding algorithm.  Parameters 
 
arrayndarray 

Array of costs.  
startiterable 

n-d index into array defining the starting point  
enditerable 

n-d index into array defining the end point  
fully_connectedbool (optional) 

If True, diagonal moves are permitted, if False, only axial moves.  
geometricbool (optional) 

If True, the MCP_Geometric class is used to calculate costs, if False, the MCP base class is used. See the class documentation for an explanation of the differences between MCP and MCP_Geometric.    Returns 
 
pathlist 

List of n-d index tuples defining the path from start to end.  
costfloat 

Cost of the path. If geometric is False, the cost of the path is the sum of the values of array along the path. If geometric is True, a finer computation is made (see the documentation of the MCP_Geometric class).      See also  
MCP, MCP_Geometric

  Examples >>> import numpy as np
>>> from skimage.graph import route_through_array
>>>
>>> image = np.array([[1, 3], [10, 12]])
>>> image
array([[ 1,  3],
       [10, 12]])
>>> # Forbid diagonal steps
>>> route_through_array(image, [0, 0], [1, 1], fully_connected=False)
([(0, 0), (0, 1), (1, 1)], 9.5)
>>> # Now allow diagonal steps: the path goes directly from start to end
>>> route_through_array(image, [0, 0], [1, 1])
([(0, 0), (1, 1)], 9.19238815542512)
>>> # Cost is the sum of array values along the path (16 = 1 + 3 + 12)
>>> route_through_array(image, [0, 0], [1, 1], fully_connected=False,
... geometric=False)
([(0, 0), (0, 1), (1, 1)], 16.0)
>>> # Larger array where we display the path that is selected
>>> image = np.arange((36)).reshape((6, 6))
>>> image
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23],
       [24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35]])
>>> # Find the path with lowest cost
>>> indices, weight = route_through_array(image, (0, 0), (5, 5))
>>> indices = np.stack(indices, axis=-1)
>>> path = np.zeros_like(image)
>>> path[indices[0], indices[1]] = 1
>>> path
array([[1, 1, 1, 1, 1, 0],
       [0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 1]])
skimage.graph.shortest_path(arr, reach=1, axis=-1, output_indexlist=False) [source]
 
Find the shortest path through an n-d array from one side to another.  Parameters 
 
arrndarray of float64 

reachint, optional 

By default (reach = 1), the shortest path can only move one row up or down for every step it moves forward (i.e., the path gradient is limited to 1). reach defines the number of elements that can be skipped along each non-axis dimension at each step.  
axisint, optional 

The axis along which the path must always move forward (default -1)  
output_indexlistbool, optional 

See return value p for explanation.    Returns 
 
piterable of int 

For each step along axis, the coordinate of the shortest path. If output_indexlist is True, then the path is returned as a list of n-d tuples that index into arr. If False, then the path is returned as an array listing the coordinates of the path along the non-axis dimensions for each step along the axis dimension. That is, p.shape == (arr.shape[axis], arr.ndim-1) except that p is squeezed before returning so if arr.ndim == 2, then p.shape == (arr.shape[axis],)  
costfloat 

Cost of path. This is the absolute sum of all the differences along the path.