hexsha stringlengths 40 40 | repo stringlengths 7 114 | path stringlengths 4 124 | license listlengths 1 9 | language stringclasses 1
value | identifier stringlengths 1 71 | return_type stringlengths 1 749 ⌀ | original_string stringlengths 76 22.7k | original_docstring stringlengths 16 7.61k | docstring stringlengths 16 2.47k | docstring_tokens listlengths 6 477 | code stringlengths 14 10.2k | code_tokens listlengths 6 996 | short_docstring stringlengths 2 644 | short_docstring_tokens listlengths 1 116 | comment listlengths 1 89 | parameters listlengths 0 64 | docstring_params dict |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bffcd526ad60c791e2f78156c586adc7f8e59d3e | rcasero/cytometer | cytometer/data.py | [
"Apache-2.0"
] | Python | load_watershed_seg_and_compute_dmap | <not_specific> | def load_watershed_seg_and_compute_dmap(seg_file_list, background_label=1):
"""
Loads a list of segmentation files and computes distance maps to the objects boundaries/background.
The segmentation file is assumed to have one integer label (2, 3, 4, ...) per object. The background has label 1.
The bound... |
Loads a list of segmentation files and computes distance maps to the objects boundaries/background.
The segmentation file is assumed to have one integer label (2, 3, 4, ...) per object. The background has label 1.
The boundaries between objects have label 0 (if boundaries exist).
Those boundaries==0 ... | Loads a list of segmentation files and computes distance maps to the objects boundaries/background.
The segmentation file is assumed to have one integer label (2, 3, 4, ...) per object. The background has label 1.
The boundaries between objects have label 0 (if boundaries exist).
Those boundaries==0 are important for ... | [
"Loads",
"a",
"list",
"of",
"segmentation",
"files",
"and",
"computes",
"distance",
"maps",
"to",
"the",
"objects",
"boundaries",
"/",
"background",
".",
"The",
"segmentation",
"file",
"is",
"assumed",
"to",
"have",
"one",
"integer",
"label",
"(",
"2",
"3",
... | def load_watershed_seg_and_compute_dmap(seg_file_list, background_label=1):
if not isinstance(seg_file_list, list):
raise ValueError('seg_file_list must be a list')
if len(seg_file_list) == 0:
return np.empty((1, 0)), np.empty((1, 0)), np.empty((1, 0))
seg0 = Image.open(seg_file_list[0])
... | [
"def",
"load_watershed_seg_and_compute_dmap",
"(",
"seg_file_list",
",",
"background_label",
"=",
"1",
")",
":",
"if",
"not",
"isinstance",
"(",
"seg_file_list",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"'seg_file_list must be a list'",
")",
"if",
"len",
... | Loads a list of segmentation files and computes distance maps to the objects boundaries/background. | [
"Loads",
"a",
"list",
"of",
"segmentation",
"files",
"and",
"computes",
"distance",
"maps",
"to",
"the",
"objects",
"boundaries",
"/",
"background",
"."
] | [
"\"\"\"\n Loads a list of segmentation files and computes distance maps to the objects boundaries/background.\n\n The segmentation file is assumed to have one integer label (2, 3, 4, ...) per object. The background has label 1.\n The boundaries between objects have label 0 (if boundaries exist).\n\n Tho... | [
{
"param": "seg_file_list",
"type": null
},
{
"param": "background_label",
"type": null
}
] | {
"returns": [
{
"docstring": "(dmap, mask, seg)\ndmap: np.array with one distance map per segmentation file. It provides the Euclidean distance of each pixel\nto the closest background/boundary pixel.\nmask: np.array with one segmentation mask per file. Background pixels = 0. Foreground/boundary pixels = 1... |
bffcd526ad60c791e2f78156c586adc7f8e59d3e | rcasero/cytometer | cytometer/data.py | [
"Apache-2.0"
] | Python | read_paths_from_svg_file | <not_specific> | def read_paths_from_svg_file(file, tag='Cell', add_offset_from_filename=False, minimum_npoints=3):
"""
Read a SVG file produced by Gimp that contains paths (contours), and return a list of paths, where each path
is a list of (X,Y) point coordinates.
Only paths that have a label that starts with the cho... |
Read a SVG file produced by Gimp that contains paths (contours), and return a list of paths, where each path
is a list of (X,Y) point coordinates.
Only paths that have a label that starts with the chosen tag are read. This allows having different types of
objects in the SVG file (e.g. cells, edge cell... | Read a SVG file produced by Gimp that contains paths (contours), and return a list of paths, where each path
is a list of (X,Y) point coordinates.
Only paths that have a label that starts with the chosen tag are read. This allows having different types of
objects in the SVG file , but only read one type of objects. | [
"Read",
"a",
"SVG",
"file",
"produced",
"by",
"Gimp",
"that",
"contains",
"paths",
"(",
"contours",
")",
"and",
"return",
"a",
"list",
"of",
"paths",
"where",
"each",
"path",
"is",
"a",
"list",
"of",
"(",
"X",
"Y",
")",
"point",
"coordinates",
".",
"... | def read_paths_from_svg_file(file, tag='Cell', add_offset_from_filename=False, minimum_npoints=3):
tag = tag.lower()
def extract_contour(path, x_offset=0, y_offset=0):
contour = []
for pt in path:
contour.append((np.real(pt.start) + x_offset, np.imag(pt.start) + y_offset))
... | [
"def",
"read_paths_from_svg_file",
"(",
"file",
",",
"tag",
"=",
"'Cell'",
",",
"add_offset_from_filename",
"=",
"False",
",",
"minimum_npoints",
"=",
"3",
")",
":",
"tag",
"=",
"tag",
".",
"lower",
"(",
")",
"def",
"extract_contour",
"(",
"path",
",",
"x_... | Read a SVG file produced by Gimp that contains paths (contours), and return a list of paths, where each path
is a list of (X,Y) point coordinates. | [
"Read",
"a",
"SVG",
"file",
"produced",
"by",
"Gimp",
"that",
"contains",
"paths",
"(",
"contours",
")",
"and",
"return",
"a",
"list",
"of",
"paths",
"where",
"each",
"path",
"is",
"a",
"list",
"of",
"(",
"X",
"Y",
")",
"point",
"coordinates",
"."
] | [
"\"\"\"\n Read a SVG file produced by Gimp that contains paths (contours), and return a list of paths, where each path\n is a list of (X,Y) point coordinates.\n\n Only paths that have a label that starts with the chosen tag are read. This allows having different types of\n objects in the SVG file (e.g. ... | [
{
"param": "file",
"type": null
},
{
"param": "tag",
"type": null
},
{
"param": "add_offset_from_filename",
"type": null
},
{
"param": "minimum_npoints",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "file",
"type": null,
"docstring": "path and name of SVG file.",
"docstring_tokens": [
"path",
"and"... |
bffcd526ad60c791e2f78156c586adc7f8e59d3e | rcasero/cytometer | cytometer/data.py | [
"Apache-2.0"
] | Python | area2quantile | <not_specific> | def area2quantile(areas, quantiles=np.linspace(0.0, 1.0, 101)):
"""
Return function to map from cell areas to quantiles.
:param areas: Vector with random sample that is representative of area values in the population. The probability
distribution and quantiles are computed from this random sample.
... |
Return function to map from cell areas to quantiles.
:param areas: Vector with random sample that is representative of area values in the population. The probability
distribution and quantiles are computed from this random sample.
:param quantiles: (def np.linspace(0.0, 1.0, 101)) Quantiles values in ... | Return function to map from cell areas to quantiles. | [
"Return",
"function",
"to",
"map",
"from",
"cell",
"areas",
"to",
"quantiles",
"."
] | def area2quantile(areas, quantiles=np.linspace(0.0, 1.0, 101)):
areas_by_quantiles = scipy.stats.mstats.hdquantiles(areas, prob=quantiles)
f_area2quantile = scipy.interpolate.interp1d(areas_by_quantiles.data, quantiles, bounds_error=False,
fill_value=(0.0, 1.0))
... | [
"def",
"area2quantile",
"(",
"areas",
",",
"quantiles",
"=",
"np",
".",
"linspace",
"(",
"0.0",
",",
"1.0",
",",
"101",
")",
")",
":",
"areas_by_quantiles",
"=",
"scipy",
".",
"stats",
".",
"mstats",
".",
"hdquantiles",
"(",
"areas",
",",
"prob",
"=",
... | Return function to map from cell areas to quantiles. | [
"Return",
"function",
"to",
"map",
"from",
"cell",
"areas",
"to",
"quantiles",
"."
] | [
"\"\"\"\n Return function to map from cell areas to quantiles.\n\n :param areas: Vector with random sample that is representative of area values in the population. The probability\n distribution and quantiles are computed from this random sample.\n :param quantiles: (def np.linspace(0.0, 1.0, 101)) Quan... | [
{
"param": "areas",
"type": null
},
{
"param": "quantiles",
"type": null
}
] | {
"returns": [
{
"docstring": "scipy.interpolate.interpolate.interp1d interpolation function that maps areas values to [0.0, 1.0]. Area values\noutside the range are mapped to 0.0 (smaller) or 1.0 (larger).",
"docstring_tokens": [
"scipy",
".",
"interpolate",
".",
... |
bffcd526ad60c791e2f78156c586adc7f8e59d3e | rcasero/cytometer | cytometer/data.py | [
"Apache-2.0"
] | Python | aida_colourmap | <not_specific> | def aida_colourmap():
"""
Create a colourmap that replicates in plt.imshow() the colours that we obtain in AIDA. This colormap is called
'quantiles_aida'.
This colourmap is meant to map area quantiles [0.0, 1.0] to a pastel yellow-green-purple colour scale.
This function can be combined with area2... |
Create a colourmap that replicates in plt.imshow() the colours that we obtain in AIDA. This colormap is called
'quantiles_aida'.
This colourmap is meant to map area quantiles [0.0, 1.0] to a pastel yellow-green-purple colour scale.
This function can be combined with area2quantile() to map areas to co... | Create a colourmap that replicates in plt.imshow() the colours that we obtain in AIDA. This colormap is called
'quantiles_aida'.
This colourmap is meant to map area quantiles [0.0, 1.0] to a pastel yellow-green-purple colour scale.
This function can be combined with area2quantile() to map areas to colours.
import cy... | [
"Create",
"a",
"colourmap",
"that",
"replicates",
"in",
"plt",
".",
"imshow",
"()",
"the",
"colours",
"that",
"we",
"obtain",
"in",
"AIDA",
".",
"This",
"colormap",
"is",
"called",
"'",
"quantiles_aida",
"'",
".",
"This",
"colourmap",
"is",
"meant",
"to",
... | def aida_colourmap():
hue = np.linspace(0, 315 / 360, 101)
lightness = 0.69
saturation = 0.44
alpha = 1
cm = [colorsys.hls_to_rgb(h=h, l=lightness, s=saturation) + (alpha,) for h in hue]
return ListedColormap(cm, name='quantiles_aida') | [
"def",
"aida_colourmap",
"(",
")",
":",
"hue",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"315",
"/",
"360",
",",
"101",
")",
"lightness",
"=",
"0.69",
"saturation",
"=",
"0.44",
"alpha",
"=",
"1",
"cm",
"=",
"[",
"colorsys",
".",
"hls_to_rgb",
"("... | Create a colourmap that replicates in plt.imshow() the colours that we obtain in AIDA. | [
"Create",
"a",
"colourmap",
"that",
"replicates",
"in",
"plt",
".",
"imshow",
"()",
"the",
"colours",
"that",
"we",
"obtain",
"in",
"AIDA",
"."
] | [
"\"\"\"\n Create a colourmap that replicates in plt.imshow() the colours that we obtain in AIDA. This colormap is called\n 'quantiles_aida'.\n\n This colourmap is meant to map area quantiles [0.0, 1.0] to a pastel yellow-green-purple colour scale.\n\n This function can be combined with area2quantile() t... | [] | {
"returns": [
{
"docstring": "matplotlib.colors.ListedColormap with 101 colours.",
"docstring_tokens": [
"matplotlib",
".",
"colors",
".",
"ListedColormap",
"with",
"101",
"colours",
"."
],
"type": null
}
],
"... |
bffcd526ad60c791e2f78156c586adc7f8e59d3e | rcasero/cytometer | cytometer/data.py | [
"Apache-2.0"
] | Python | aida_contour_items | <not_specific> | def aida_contour_items(contours, f_area2quantile, cm='quantiles_aida', xres=1.0, yres=1.0, cell_prob=None):
"""
Create list of contour items for AIDA.
This function computes the area of each contour, it's quantile, and maps it to a colour.
:param contours: List [contour_0, contour_1...], where contour... |
Create list of contour items for AIDA.
This function computes the area of each contour, it's quantile, and maps it to a colour.
:param contours: List [contour_0, contour_1...], where contour_i is an (Ni, 2)-np.array with Ni 2D points.
:param f_area2quantile: Function to map areas to quantiles. Comput... | Create list of contour items for AIDA.
This function computes the area of each contour, it's quantile, and maps it to a colour. | [
"Create",
"list",
"of",
"contour",
"items",
"for",
"AIDA",
".",
"This",
"function",
"computes",
"the",
"area",
"of",
"each",
"contour",
"it",
"'",
"s",
"quantile",
"and",
"maps",
"it",
"to",
"a",
"colour",
"."
] | def aida_contour_items(contours, f_area2quantile, cm='quantiles_aida', xres=1.0, yres=1.0, cell_prob=None):
def aida_contour_item(contour, rgb_colour, cell_prob=None):
if type(contour) != 'numpy.ndarray':
contour = list(contour)
hls_colour = colorsys.rgb_to_hls(rgb_colour[0], rgb_colour[... | [
"def",
"aida_contour_items",
"(",
"contours",
",",
"f_area2quantile",
",",
"cm",
"=",
"'quantiles_aida'",
",",
"xres",
"=",
"1.0",
",",
"yres",
"=",
"1.0",
",",
"cell_prob",
"=",
"None",
")",
":",
"def",
"aida_contour_item",
"(",
"contour",
",",
"rgb_colour"... | Create list of contour items for AIDA. | [
"Create",
"list",
"of",
"contour",
"items",
"for",
"AIDA",
"."
] | [
"\"\"\"\n Create list of contour items for AIDA.\n\n This function computes the area of each contour, it's quantile, and maps it to a colour.\n\n :param contours: List [contour_0, contour_1...], where contour_i is an (Ni, 2)-np.array with Ni 2D points.\n :param f_area2quantile: Function to map areas to ... | [
{
"param": "contours",
"type": null
},
{
"param": "f_area2quantile",
"type": null
},
{
"param": "cm",
"type": null
},
{
"param": "xres",
"type": null
},
{
"param": "yres",
"type": null
},
{
"param": "cell_prob",
"type": null
}
] | {
"returns": [
{
"docstring": "List of dictionaries, each one with the structure of a contour object.",
"docstring_tokens": [
"List",
"of",
"dictionaries",
"each",
"one",
"with",
"the",
"structure",
"of",
"a",
"con... |
bffcd526ad60c791e2f78156c586adc7f8e59d3e | rcasero/cytometer | cytometer/data.py | [
"Apache-2.0"
] | Python | aida_contour_item | <not_specific> | def aida_contour_item(contour, rgb_colour, cell_prob=None):
"""
Create an object that describes a closed contour in AIDA. The user provides the coordinates of the contour
points and the colour for the contour.
:param contour: np.array or list of points of a contour: [[x0, y0], [x1, y1],... |
Create an object that describes a closed contour in AIDA. The user provides the coordinates of the contour
points and the colour for the contour.
:param contour: np.array or list of points of a contour: [[x0, y0], [x1, y1], ...]
:param rgb_colour: (r, g, b) or (r, g, b, alpha). RGB col... | Create an object that describes a closed contour in AIDA. The user provides the coordinates of the contour
points and the colour for the contour. | [
"Create",
"an",
"object",
"that",
"describes",
"a",
"closed",
"contour",
"in",
"AIDA",
".",
"The",
"user",
"provides",
"the",
"coordinates",
"of",
"the",
"contour",
"points",
"and",
"the",
"colour",
"for",
"the",
"contour",
"."
] | def aida_contour_item(contour, rgb_colour, cell_prob=None):
if type(contour) != 'numpy.ndarray':
contour = list(contour)
hls_colour = colorsys.rgb_to_hls(rgb_colour[0], rgb_colour[1], rgb_colour[2])
item = {
'class': '',
'type': 'path',
'color': {
... | [
"def",
"aida_contour_item",
"(",
"contour",
",",
"rgb_colour",
",",
"cell_prob",
"=",
"None",
")",
":",
"if",
"type",
"(",
"contour",
")",
"!=",
"'numpy.ndarray'",
":",
"contour",
"=",
"list",
"(",
"contour",
")",
"hls_colour",
"=",
"colorsys",
".",
"rgb_t... | Create an object that describes a closed contour in AIDA. | [
"Create",
"an",
"object",
"that",
"describes",
"a",
"closed",
"contour",
"in",
"AIDA",
"."
] | [
"\"\"\"\n Create an object that describes a closed contour in AIDA. The user provides the coordinates of the contour\n points and the colour for the contour.\n\n :param contour: np.array or list of points of a contour: [[x0, y0], [x1, y1], ...]\n :param rgb_colour: (r, g, b) or (r, g, b,... | [
{
"param": "contour",
"type": null
},
{
"param": "rgb_colour",
"type": null
},
{
"param": "cell_prob",
"type": null
}
] | {
"returns": [
{
"docstring": "dictionary with the structure of the contour object.",
"docstring_tokens": [
"dictionary",
"with",
"the",
"structure",
"of",
"the",
"contour",
"object",
"."
],
"type": null
}
],
"... |
bffcd526ad60c791e2f78156c586adc7f8e59d3e | rcasero/cytometer | cytometer/data.py | [
"Apache-2.0"
] | Python | aida_rectangle_items | <not_specific> | def aida_rectangle_items(rectangles):
"""
Create list of rectangle items for AIDA.
:param rectangles: List [rectangle_0, rectangle_1...], where rectangle_i is a tuple (x0, y0, width, height).
:return: List of dictionaries, each one with the structure of a rectangle object.
"""
def aida_rectan... |
Create list of rectangle items for AIDA.
:param rectangles: List [rectangle_0, rectangle_1...], where rectangle_i is a tuple (x0, y0, width, height).
:return: List of dictionaries, each one with the structure of a rectangle object.
| Create list of rectangle items for AIDA. | [
"Create",
"list",
"of",
"rectangle",
"items",
"for",
"AIDA",
"."
] | def aida_rectangle_items(rectangles):
def aida_rectangle_item(rectangle):
(x0, y0, width, height) = rectangle
hls_colour_black = colorsys.rgb_to_hls(0, 0, 0)
hls_colour_white = colorsys.rgb_to_hls(1, 1, 1)
item = {
'type': 'rectangle',
'class': '',
... | [
"def",
"aida_rectangle_items",
"(",
"rectangles",
")",
":",
"def",
"aida_rectangle_item",
"(",
"rectangle",
")",
":",
"\"\"\"\n Create an object that describes a rectangle in AIDA.\n\n :param rectangle: (x0, y0, width, height).\n :return: item: dictionary with the struct... | Create list of rectangle items for AIDA. | [
"Create",
"list",
"of",
"rectangle",
"items",
"for",
"AIDA",
"."
] | [
"\"\"\"\n Create list of rectangle items for AIDA.\n\n :param rectangles: List [rectangle_0, rectangle_1...], where rectangle_i is a tuple (x0, y0, width, height).\n :return: List of dictionaries, each one with the structure of a rectangle object.\n \"\"\"",
"\"\"\"\n Create an object that desc... | [
{
"param": "rectangles",
"type": null
}
] | {
"returns": [
{
"docstring": "List of dictionaries, each one with the structure of a rectangle object.",
"docstring_tokens": [
"List",
"of",
"dictionaries",
"each",
"one",
"with",
"the",
"structure",
"of",
"a",
"r... |
bffcd526ad60c791e2f78156c586adc7f8e59d3e | rcasero/cytometer | cytometer/data.py | [
"Apache-2.0"
] | Python | aida_rectangle_item | <not_specific> | def aida_rectangle_item(rectangle):
"""
Create an object that describes a rectangle in AIDA.
:param rectangle: (x0, y0, width, height).
:return: item: dictionary with the structure of the rectangle object.
"""
# extract rectangle parameters
(x0, y0, width, heigh... |
Create an object that describes a rectangle in AIDA.
:param rectangle: (x0, y0, width, height).
:return: item: dictionary with the structure of the rectangle object.
| Create an object that describes a rectangle in AIDA. | [
"Create",
"an",
"object",
"that",
"describes",
"a",
"rectangle",
"in",
"AIDA",
"."
] | def aida_rectangle_item(rectangle):
(x0, y0, width, height) = rectangle
hls_colour_black = colorsys.rgb_to_hls(0, 0, 0)
hls_colour_white = colorsys.rgb_to_hls(1, 1, 1)
item = {
'type': 'rectangle',
'class': '',
'color': {
'fill': {
... | [
"def",
"aida_rectangle_item",
"(",
"rectangle",
")",
":",
"(",
"x0",
",",
"y0",
",",
"width",
",",
"height",
")",
"=",
"rectangle",
"hls_colour_black",
"=",
"colorsys",
".",
"rgb_to_hls",
"(",
"0",
",",
"0",
",",
"0",
")",
"hls_colour_white",
"=",
"color... | Create an object that describes a rectangle in AIDA. | [
"Create",
"an",
"object",
"that",
"describes",
"a",
"rectangle",
"in",
"AIDA",
"."
] | [
"\"\"\"\n Create an object that describes a rectangle in AIDA.\n\n :param rectangle: (x0, y0, width, height).\n :return: item: dictionary with the structure of the rectangle object.\n \"\"\"",
"# extract rectangle parameters",
"# convert RGB to HSL"
] | [
{
"param": "rectangle",
"type": null
}
] | {
"returns": [
{
"docstring": "dictionary with the structure of the rectangle object.",
"docstring_tokens": [
"dictionary",
"with",
"the",
"structure",
"of",
"the",
"rectangle",
"object",
"."
],
"type": null
}
],... |
bffcd526ad60c791e2f78156c586adc7f8e59d3e | rcasero/cytometer | cytometer/data.py | [
"Apache-2.0"
] | Python | aida_write_new_items | null | def aida_write_new_items(filename, items, mode='append_to_last_layer', indent=0, ensure_ascii=False,
double_precision=10, number_of_attempts=1):
"""
Create a new or update existing AIDA annotations file, adding new items.
:param filename: String with path to .json annotations file.
... |
Create a new or update existing AIDA annotations file, adding new items.
:param filename: String with path to .json annotations file.
:param items: List of items, obtained e.g. with aida_contour_items() or aida_rectangle_items().
:param mode:
- 'append_to_last_layer': (def) Append items to the ... | Create a new or update existing AIDA annotations file, adding new items. | [
"Create",
"a",
"new",
"or",
"update",
"existing",
"AIDA",
"annotations",
"file",
"adding",
"new",
"items",
"."
] | def aida_write_new_items(filename, items, mode='append_to_last_layer', indent=0, ensure_ascii=False,
double_precision=10, number_of_attempts=1):
if type(items) != list:
raise SyntaxError('items must be a list, but is type: ' + type(items))
item_type = items[0]['type']
if ite... | [
"def",
"aida_write_new_items",
"(",
"filename",
",",
"items",
",",
"mode",
"=",
"'append_to_last_layer'",
",",
"indent",
"=",
"0",
",",
"ensure_ascii",
"=",
"False",
",",
"double_precision",
"=",
"10",
",",
"number_of_attempts",
"=",
"1",
")",
":",
"if",
"ty... | Create a new or update existing AIDA annotations file, adding new items. | [
"Create",
"a",
"new",
"or",
"update",
"existing",
"AIDA",
"annotations",
"file",
"adding",
"new",
"items",
"."
] | [
"\"\"\"\n Create a new or update existing AIDA annotations file, adding new items.\n :param filename: String with path to .json annotations file.\n :param items: List of items, obtained e.g. with aida_contour_items() or aida_rectangle_items().\n :param mode:\n - 'append_to_last_layer': (def) Appe... | [
{
"param": "filename",
"type": null
},
{
"param": "items",
"type": null
},
{
"param": "mode",
"type": null
},
{
"param": "indent",
"type": null
},
{
"param": "ensure_ascii",
"type": null
},
{
"param": "double_precision",
"type": null
},
{
"... | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "filename",
"type": null,
"docstring": "String with path to .json annotations file.",
"docstring_tokens": [
... |
bffcd526ad60c791e2f78156c586adc7f8e59d3e | rcasero/cytometer | cytometer/data.py | [
"Apache-2.0"
] | Python | aida_get_contours | <not_specific> | def aida_get_contours(annotations, layer_name='.*', return_props=False):
"""
Concatenate items as contours in an AIDA annotations file or dict. Only 'path' and 'rectangle' types implemented.
:param annotations: filename or dict with AIDA annotations.
:param layer_name: (def '.*', which matches any name... |
Concatenate items as contours in an AIDA annotations file or dict. Only 'path' and 'rectangle' types implemented.
:param annotations: filename or dict with AIDA annotations.
:param layer_name: (def '.*', which matches any name). Regular expression (see help for re module) that will be used
as the patt... | Concatenate items as contours in an AIDA annotations file or dict. Only 'path' and 'rectangle' types implemented. | [
"Concatenate",
"items",
"as",
"contours",
"in",
"an",
"AIDA",
"annotations",
"file",
"or",
"dict",
".",
"Only",
"'",
"path",
"'",
"and",
"'",
"rectangle",
"'",
"types",
"implemented",
"."
] | def aida_get_contours(annotations, layer_name='.*', return_props=False):
if isinstance(annotations, six.string_types):
with open(annotations) as fp:
annotations = ujson.load(fp)
if type(annotations) != dict:
raise TypeError('annotations must be type dict')
items = []
if retur... | [
"def",
"aida_get_contours",
"(",
"annotations",
",",
"layer_name",
"=",
"'.*'",
",",
"return_props",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"annotations",
",",
"six",
".",
"string_types",
")",
":",
"with",
"open",
"(",
"annotations",
")",
"as",
"... | Concatenate items as contours in an AIDA annotations file or dict. | [
"Concatenate",
"items",
"as",
"contours",
"in",
"an",
"AIDA",
"annotations",
"file",
"or",
"dict",
"."
] | [
"\"\"\"\n Concatenate items as contours in an AIDA annotations file or dict. Only 'path' and 'rectangle' types implemented.\n\n :param annotations: filename or dict with AIDA annotations.\n :param layer_name: (def '.*', which matches any name). Regular expression (see help for re module) that will be used\... | [
{
"param": "annotations",
"type": null
},
{
"param": "layer_name",
"type": null
},
{
"param": "return_props",
"type": null
}
] | {
"returns": [
{
"docstring": "list of concatenated contours from selected layers.",
"docstring_tokens": [
"list",
"of",
"concatenated",
"contours",
"from",
"selected",
"layers",
"."
],
"type": null
}
],
"raises": [],
... |
bffcd526ad60c791e2f78156c586adc7f8e59d3e | rcasero/cytometer | cytometer/data.py | [
"Apache-2.0"
] | Python | write_path_to_aida_json_file | <not_specific> | def write_path_to_aida_json_file(fp, x, hue=170, pretty_print=False):
"""
DEPRECATED: Use aida_write_new_items() instead.
Write single contour to a JSON file in AIDA's annotation format.
(This function only writes the XML code only for the contour, not a full JSON file).
:param fp: file pointer to... |
DEPRECATED: Use aida_write_new_items() instead.
Write single contour to a JSON file in AIDA's annotation format.
(This function only writes the XML code only for the contour, not a full JSON file).
:param fp: file pointer to text file that is open for writing/appending.
:param x: numpy.ndarray wi... |
(This function only writes the XML code only for the contour, not a full JSON file). | [
"(",
"This",
"function",
"only",
"writes",
"the",
"XML",
"code",
"only",
"for",
"the",
"contour",
"not",
"a",
"full",
"JSON",
"file",
")",
"."
] | def write_path_to_aida_json_file(fp, x, hue=170, pretty_print=False):
warnings.warn('Use aida_write_new_items() instead', DeprecationWarning)
if pretty_print:
fp.write(' {\n')
fp.write(' "class": "",\n')
fp.write(' "type": "path",\n')
fp.write(' ... | [
"def",
"write_path_to_aida_json_file",
"(",
"fp",
",",
"x",
",",
"hue",
"=",
"170",
",",
"pretty_print",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"'Use aida_write_new_items() instead'",
",",
"DeprecationWarning",
")",
"if",
"pretty_print",
":",
"fp"... | DEPRECATED: Use aida_write_new_items() instead. | [
"DEPRECATED",
":",
"Use",
"aida_write_new_items",
"()",
"instead",
"."
] | [
"\"\"\"\n DEPRECATED: Use aida_write_new_items() instead.\n Write single contour to a JSON file in AIDA's annotation format.\n\n (This function only writes the XML code only for the contour, not a full JSON file).\n\n :param fp: file pointer to text file that is open for writing/appending.\n :param x... | [
{
"param": "fp",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "hue",
"type": null
},
{
"param": "pretty_print",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "fp",
"type": null,
"docstring": "file pointer to text file that is open for writing/appending.",
"docstring_tokens"... |
bffcd526ad60c791e2f78156c586adc7f8e59d3e | rcasero/cytometer | cytometer/data.py | [
"Apache-2.0"
] | Python | seek_character | <not_specific> | def seek_character(fp, target):
"""
Read file backwards until finding target character.
:param fp: File pointer.
:param target: Character that we are looking for.
:return:
c: Found character.
"""
while fp.tell() > 0:
c = fp.read(1)
... |
Read file backwards until finding target character.
:param fp: File pointer.
:param target: Character that we are looking for.
:return:
c: Found character.
| Read file backwards until finding target character. | [
"Read",
"file",
"backwards",
"until",
"finding",
"target",
"character",
"."
] | def seek_character(fp, target):
while fp.tell() > 0:
c = fp.read(1)
if c == target:
break
else:
fp.seek(fp.tell() - 2)
if fp.tell() == 0:
raise IOError('Beginning of file reached before finding "}"')
return c | [
"def",
"seek_character",
"(",
"fp",
",",
"target",
")",
":",
"while",
"fp",
".",
"tell",
"(",
")",
">",
"0",
":",
"c",
"=",
"fp",
".",
"read",
"(",
"1",
")",
"if",
"c",
"==",
"target",
":",
"break",
"else",
":",
"fp",
".",
"seek",
"(",
"fp",
... | Read file backwards until finding target character. | [
"Read",
"file",
"backwards",
"until",
"finding",
"target",
"character",
"."
] | [
"\"\"\"\n Read file backwards until finding target character.\n :param fp: File pointer.\n :param target: Character that we are looking for.\n :return:\n c: Found character.\n \"\"\""
] | [
{
"param": "fp",
"type": null
},
{
"param": "target",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "fp",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"i... |
bffcd526ad60c791e2f78156c586adc7f8e59d3e | rcasero/cytometer | cytometer/data.py | [
"Apache-2.0"
] | Python | zeiss_to_deepzoom | <not_specific> | def zeiss_to_deepzoom(histo_list, dzi_dir=None, overwrite=False, extra_tif=False, tif_dir=None):
"""
Convert microscopy files from Zeiss .czi format to DeepZoom .dzi format. It can also create a TIFF version of the
file that can be read by OpenSlide and probably most libraries.
.dzi is a format that ca... |
Convert microscopy files from Zeiss .czi format to DeepZoom .dzi format. It can also create a TIFF version of the
file that can be read by OpenSlide and probably most libraries.
.dzi is a format that can be used by AIDA to display and navigate large microscopy images.
:param histo_list: path and file... | Convert microscopy files from Zeiss .czi format to DeepZoom .dzi format. It can also create a TIFF version of the
file that can be read by OpenSlide and probably most libraries.
.dzi is a format that can be used by AIDA to display and navigate large microscopy images. | [
"Convert",
"microscopy",
"files",
"from",
"Zeiss",
".",
"czi",
"format",
"to",
"DeepZoom",
".",
"dzi",
"format",
".",
"It",
"can",
"also",
"create",
"a",
"TIFF",
"version",
"of",
"the",
"file",
"that",
"can",
"be",
"read",
"by",
"OpenSlide",
"and",
"prob... | def zeiss_to_deepzoom(histo_list, dzi_dir=None, overwrite=False, extra_tif=False, tif_dir=None):
if type(histo_list) is not list:
histo_list = [histo_list,]
for histo_file in histo_list:
filename_noext = os.path.basename(histo_file)
filename_noext = os.path.splitext(filename_noext)[0]
... | [
"def",
"zeiss_to_deepzoom",
"(",
"histo_list",
",",
"dzi_dir",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"extra_tif",
"=",
"False",
",",
"tif_dir",
"=",
"None",
")",
":",
"if",
"type",
"(",
"histo_list",
")",
"is",
"not",
"list",
":",
"histo_list... | Convert microscopy files from Zeiss .czi format to DeepZoom .dzi format. | [
"Convert",
"microscopy",
"files",
"from",
"Zeiss",
".",
"czi",
"format",
"to",
"DeepZoom",
".",
"dzi",
"format",
"."
] | [
"\"\"\"\n Convert microscopy files from Zeiss .czi format to DeepZoom .dzi format. It can also create a TIFF version of the\n file that can be read by OpenSlide and probably most libraries.\n\n .dzi is a format that can be used by AIDA to display and navigate large microscopy images.\n\n :param histo_li... | [
{
"param": "histo_list",
"type": null
},
{
"param": "dzi_dir",
"type": null
},
{
"param": "overwrite",
"type": null
},
{
"param": "extra_tif",
"type": null
},
{
"param": "tif_dir",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "histo_list",
"type": null,
"docstring": "path and filename, or list of paths and filenames of Zeiss .czi files.",
"... |
cde60914f621fed9ac23c393258ba25451d0eec9 | rcasero/cytometer | scripts/fus_delta_exp_0002_annotations_postprocessing.py | [
"Apache-2.0"
] | Python | process_annotations | null | def process_annotations(annotation_files_list, overwrite_aggregated_annotation_file=False, create_symlink=False):
"""
Helper function to process a list of JSON files with annotations.
:param annotation_files_list: list of JSON filenames containing annotations.
:return:
"""
for annotation_file i... |
Helper function to process a list of JSON files with annotations.
:param annotation_files_list: list of JSON filenames containing annotations.
:return:
| Helper function to process a list of JSON files with annotations. | [
"Helper",
"function",
"to",
"process",
"a",
"list",
"of",
"JSON",
"files",
"with",
"annotations",
"."
] | def process_annotations(annotation_files_list, overwrite_aggregated_annotation_file=False, create_symlink=False):
for annotation_file in annotation_files_list:
print('File: ' + os.path.basename(annotation_file))
aggregated_annotation_file = annotation_file.replace('.json', '_aggregated.json')
... | [
"def",
"process_annotations",
"(",
"annotation_files_list",
",",
"overwrite_aggregated_annotation_file",
"=",
"False",
",",
"create_symlink",
"=",
"False",
")",
":",
"for",
"annotation_file",
"in",
"annotation_files_list",
":",
"print",
"(",
"'File: '",
"+",
"os",
"."... | Helper function to process a list of JSON files with annotations. | [
"Helper",
"function",
"to",
"process",
"a",
"list",
"of",
"JSON",
"files",
"with",
"annotations",
"."
] | [
"\"\"\"\n Helper function to process a list of JSON files with annotations.\n :param annotation_files_list: list of JSON filenames containing annotations.\n :return:\n \"\"\"",
"# name of the file that we are going to save the aggregated annotations to",
"# name of the original .ndpi file",
"# agg... | [
{
"param": "annotation_files_list",
"type": null
},
{
"param": "overwrite_aggregated_annotation_file",
"type": null
},
{
"param": "create_symlink",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "annotation_files_list",
"type": null,
"docstring": "list of JSON filenames containing annotations.",
"docstring_tok... |
9e939e8d907acbaa50fb781bacfe750a4544930a | rcasero/cytometer | scripts/rreb1_tm1b_exp_0008_zeiss_annotations_postprocessing_v8_no_correction.py | [
"Apache-2.0"
] | Python | process_annotations | <not_specific> | def process_annotations(annotation_files_list, overwrite_aggregated_annotation_file=False, create_symlink=False):
"""
Helper function to process a list of JSON files with annotations.
:param annotation_files_list: list of JSON filenames containing annotations.
:return:
"""
for annotation_file i... |
Helper function to process a list of JSON files with annotations.
:param annotation_files_list: list of JSON filenames containing annotations.
:return:
| Helper function to process a list of JSON files with annotations. | [
"Helper",
"function",
"to",
"process",
"a",
"list",
"of",
"JSON",
"files",
"with",
"annotations",
"."
] | def process_annotations(annotation_files_list, overwrite_aggregated_annotation_file=False, create_symlink=False):
for annotation_file in annotation_files_list:
print('File: ' + os.path.basename(annotation_file))
aggregated_annotation_file = annotation_file.replace('.json', '_aggregated.json')
... | [
"def",
"process_annotations",
"(",
"annotation_files_list",
",",
"overwrite_aggregated_annotation_file",
"=",
"False",
",",
"create_symlink",
"=",
"False",
")",
":",
"for",
"annotation_file",
"in",
"annotation_files_list",
":",
"print",
"(",
"'File: '",
"+",
"os",
"."... | Helper function to process a list of JSON files with annotations. | [
"Helper",
"function",
"to",
"process",
"a",
"list",
"of",
"JSON",
"files",
"with",
"annotations",
"."
] | [
"\"\"\"\n Helper function to process a list of JSON files with annotations.\n :param annotation_files_list: list of JSON filenames containing annotations.\n :return:\n \"\"\"",
"# name of the file that we are going to save the aggregated annotations to",
"# name of the original histo file",
"# um"... | [
{
"param": "annotation_files_list",
"type": null
},
{
"param": "overwrite_aggregated_annotation_file",
"type": null
},
{
"param": "create_symlink",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "annotation_files_list",
"type": null,
"docstring": "list of JSON filenames containing annotations.",
"docstring_tok... |
8089896b39d1604b48fa650f650b914fe222df45 | rcasero/cytometer | cytometer/stats.py | [
"Apache-2.0"
] | Python | models_coeff_ci_pval | <not_specific> | def models_coeff_ci_pval(models, extra_hypotheses=None, model_names=None):
"""
For convenience, extract betas (coefficients), confidence intervals and p-values from a statsmodels model. Each one
corresponds to one t-test of a hypothesis (where the hypothesis is that the coefficient ~= 0).
This function ... |
For convenience, extract betas (coefficients), confidence intervals and p-values from a statsmodels model. Each one
corresponds to one t-test of a hypothesis (where the hypothesis is that the coefficient ~= 0).
This function also allows to add extra hypotheses (contrasts) to the model. For example, that th... | For convenience, extract betas (coefficients), confidence intervals and p-values from a statsmodels model. Each one
corresponds to one t-test of a hypothesis (where the hypothesis is that the coefficient ~= 0).
This function also allows to add extra hypotheses (contrasts) to the model. For example, that the sum of two ... | [
"For",
"convenience",
"extract",
"betas",
"(",
"coefficients",
")",
"confidence",
"intervals",
"and",
"p",
"-",
"values",
"from",
"a",
"statsmodels",
"model",
".",
"Each",
"one",
"corresponds",
"to",
"one",
"t",
"-",
"test",
"of",
"a",
"hypothesis",
"(",
"... | def models_coeff_ci_pval(models, extra_hypotheses=None, model_names=None):
if extra_hypotheses is not None:
hypotheses_labels = extra_hypotheses.replace(' ', '').split(',')
df_coeff_tot = pd.DataFrame()
df_ci_lo_tot = pd.DataFrame()
df_ci_hi_tot = pd.DataFrame()
df_pval_tot = pd.DataFrame()
... | [
"def",
"models_coeff_ci_pval",
"(",
"models",
",",
"extra_hypotheses",
"=",
"None",
",",
"model_names",
"=",
"None",
")",
":",
"if",
"extra_hypotheses",
"is",
"not",
"None",
":",
"hypotheses_labels",
"=",
"extra_hypotheses",
".",
"replace",
"(",
"' '",
",",
"'... | For convenience, extract betas (coefficients), confidence intervals and p-values from a statsmodels model. | [
"For",
"convenience",
"extract",
"betas",
"(",
"coefficients",
")",
"confidence",
"intervals",
"and",
"p",
"-",
"values",
"from",
"a",
"statsmodels",
"model",
"."
] | [
"\"\"\"\n For convenience, extract betas (coefficients), confidence intervals and p-values from a statsmodels model. Each one\n corresponds to one t-test of a hypothesis (where the hypothesis is that the coefficient ~= 0).\n This function also allows to add extra hypotheses (contrasts) to the model. For ex... | [
{
"param": "models",
"type": null
},
{
"param": "extra_hypotheses",
"type": null
},
{
"param": "model_names",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "models",
"type": null,
"docstring": "List of statsmodels models .",
"docstring_tokens": [
"List",
"... |
8089896b39d1604b48fa650f650b914fe222df45 | rcasero/cytometer | cytometer/stats.py | [
"Apache-2.0"
] | Python | plot_linear_regression | <not_specific> | def plot_linear_regression(model, df, ind_var, other_vars={}, dep_var=None, sx=1.0, tx = 0.0, sy=1.0, ty=0.0,
c='C0', marker='x', line_label=''):
"""
Auxiliary function to make it easier to plot linear regression models. Optionally, also the scatter plot of points
that the model w... |
Auxiliary function to make it easier to plot linear regression models. Optionally, also the scatter plot of points
that the model was computed from.
We expect a pandas.DataFrame with a column for the independent variable ind_var used to create the model.
Also, the linear statsmodel model computed from... | Auxiliary function to make it easier to plot linear regression models. Optionally, also the scatter plot of points
that the model was computed from.
We expect a pandas.DataFrame with a column for the independent variable ind_var used to create the model.
Also, the linear statsmodel model computed from the data. Both i... | [
"Auxiliary",
"function",
"to",
"make",
"it",
"easier",
"to",
"plot",
"linear",
"regression",
"models",
".",
"Optionally",
"also",
"the",
"scatter",
"plot",
"of",
"points",
"that",
"the",
"model",
"was",
"computed",
"from",
".",
"We",
"expect",
"a",
"pandas",... | def plot_linear_regression(model, df, ind_var, other_vars={}, dep_var=None, sx=1.0, tx = 0.0, sy=1.0, ty=0.0,
c='C0', marker='x', line_label=''):
ind_var_lim = np.array([df[ind_var].min(), df[ind_var].max()])
vars = {ind_var: ind_var_lim}
for key in other_vars.keys():
othe... | [
"def",
"plot_linear_regression",
"(",
"model",
",",
"df",
",",
"ind_var",
",",
"other_vars",
"=",
"{",
"}",
",",
"dep_var",
"=",
"None",
",",
"sx",
"=",
"1.0",
",",
"tx",
"=",
"0.0",
",",
"sy",
"=",
"1.0",
",",
"ty",
"=",
"0.0",
",",
"c",
"=",
... | Auxiliary function to make it easier to plot linear regression models. | [
"Auxiliary",
"function",
"to",
"make",
"it",
"easier",
"to",
"plot",
"linear",
"regression",
"models",
"."
] | [
"\"\"\"\n Auxiliary function to make it easier to plot linear regression models. Optionally, also the scatter plot of points\n that the model was computed from.\n\n We expect a pandas.DataFrame with a column for the independent variable ind_var used to create the model.\n Also, the linear statsmodel mod... | [
{
"param": "model",
"type": null
},
{
"param": "df",
"type": null
},
{
"param": "ind_var",
"type": null
},
{
"param": "other_vars",
"type": null
},
{
"param": "dep_var",
"type": null
},
{
"param": "sx",
"type": null
},
{
"param": "tx",
... | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "model",
"type": null,
"docstring": "statsmodels linear model.",
"docstring_tokens": [
"statsmodels",
... |
8089896b39d1604b48fa650f650b914fe222df45 | rcasero/cytometer | cytometer/stats.py | [
"Apache-2.0"
] | Python | _hdsd_1D | <not_specific> | def _hdsd_1D(data, prob):
"Computes the std error for 1D arrays."
xsorted = np.sort(data.compressed())
n = len(xsorted)
hdsd = np.empty(len(prob), float_)
if n < 2:
hdsd.flat = np.nan
vv = np.arange(n) / float(n-1)
betacdf = beta.cdf
for (i,... | Computes the std error for 1D arrays. | Computes the std error for 1D arrays. | [
"Computes",
"the",
"std",
"error",
"for",
"1D",
"arrays",
"."
] | def _hdsd_1D(data, prob):
xsorted = np.sort(data.compressed())
n = len(xsorted)
hdsd = np.empty(len(prob), float_)
if n < 2:
hdsd.flat = np.nan
vv = np.arange(n) / float(n-1)
betacdf = beta.cdf
for (i,p) in enumerate(prob):
_w = betacdf(vv,... | [
"def",
"_hdsd_1D",
"(",
"data",
",",
"prob",
")",
":",
"xsorted",
"=",
"np",
".",
"sort",
"(",
"data",
".",
"compressed",
"(",
")",
")",
"n",
"=",
"len",
"(",
"xsorted",
")",
"hdsd",
"=",
"np",
".",
"empty",
"(",
"len",
"(",
"prob",
")",
",",
... | Computes the std error for 1D arrays. | [
"Computes",
"the",
"std",
"error",
"for",
"1D",
"arrays",
"."
] | [
"\"Computes the std error for 1D arrays.\""
] | [
{
"param": "data",
"type": null
},
{
"param": "prob",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "prob",
"type": null,
"docstring": null,
"docstring_tokens": [... |
6c7e6bc41255ed605cc4f12d0260c0c23a965839 | rcasero/cytometer | cytometer/deepcell.py | [
"Apache-2.0"
] | Python | step | null | def step(self):
"""Perform a single step of the morphological Chan-Vese evolution."""
# Assign attributes to local variables for convenience.
u = self._u
if u is None:
raise ValueError("the levelset function is not set (use set_levelset)")
data = self.data
# Create mask to separate objects
lab... | Perform a single step of the morphological Chan-Vese evolution. | Perform a single step of the morphological Chan-Vese evolution. | [
"Perform",
"a",
"single",
"step",
"of",
"the",
"morphological",
"Chan",
"-",
"Vese",
"evolution",
"."
] | def step(self):
u = self._u
if u is None:
raise ValueError("the levelset function is not set (use set_levelset)")
data = self.data
labeled, nr_objects = mh.label(u)
mask = mh.segmentation.gvoronoi(labeled)
mask = 1-find_boundaries(mask)
self.mask = np.float32(mask)/np.float32(mask).max()
inside = u>0... | [
"def",
"step",
"(",
"self",
")",
":",
"u",
"=",
"self",
".",
"_u",
"if",
"u",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"the levelset function is not set (use set_levelset)\"",
")",
"data",
"=",
"self",
".",
"data",
"labeled",
",",
"nr_objects",
"=",
... | Perform a single step of the morphological Chan-Vese evolution. | [
"Perform",
"a",
"single",
"step",
"of",
"the",
"morphological",
"Chan",
"-",
"Vese",
"evolution",
"."
] | [
"\"\"\"Perform a single step of the morphological Chan-Vese evolution.\"\"\"",
"# Assign attributes to local variables for convenience.",
"# Create mask to separate objects",
"# Determine c0 and c1.",
"# Image attachment.",
"# Smoothing.",
"# Apply mask"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
4a157a82091931dbe7ffc1289ac736172f4e6b40 | rcasero/cytometer | scripts/primes_scratch.py | [
"Apache-2.0"
] | Python | pixel_connectivity | <not_specific> | def pixel_connectivity(is_prime_square, x_square):
"""
Count the number of pixels adjacent to each labelled pixel, split into two types of connectivity:
diagonally and 4-neighbourhood (laterally).
:param is_prime_square:
:param x_square:
:return:
* pandas.DataFrame
"""
def is_neigh(... |
Count the number of pixels adjacent to each labelled pixel, split into two types of connectivity:
diagonally and 4-neighbourhood (laterally).
:param is_prime_square:
:param x_square:
:return:
* pandas.DataFrame
| Count the number of pixels adjacent to each labelled pixel, split into two types of connectivity:
diagonally and 4-neighbourhood (laterally). | [
"Count",
"the",
"number",
"of",
"pixels",
"adjacent",
"to",
"each",
"labelled",
"pixel",
"split",
"into",
"two",
"types",
"of",
"connectivity",
":",
"diagonally",
"and",
"4",
"-",
"neighbourhood",
"(",
"laterally",
")",
"."
] | def pixel_connectivity(is_prime_square, x_square):
def is_neigh(is_prime_square, i, j):
nrow = is_prime_square.shape[0]
ncol = is_prime_square.shape[1]
if i < 0 or j < 0 or i >= nrow or j >= ncol:
return 0
else:
return int(is_prime_square[i, j])
out_num = ... | [
"def",
"pixel_connectivity",
"(",
"is_prime_square",
",",
"x_square",
")",
":",
"def",
"is_neigh",
"(",
"is_prime_square",
",",
"i",
",",
"j",
")",
":",
"nrow",
"=",
"is_prime_square",
".",
"shape",
"[",
"0",
"]",
"ncol",
"=",
"is_prime_square",
".",
"shap... | Count the number of pixels adjacent to each labelled pixel, split into two types of connectivity:
diagonally and 4-neighbourhood (laterally). | [
"Count",
"the",
"number",
"of",
"pixels",
"adjacent",
"to",
"each",
"labelled",
"pixel",
"split",
"into",
"two",
"types",
"of",
"connectivity",
":",
"diagonally",
"and",
"4",
"-",
"neighbourhood",
"(",
"laterally",
")",
"."
] | [
"\"\"\"\n Count the number of pixels adjacent to each labelled pixel, split into two types of connectivity:\n diagonally and 4-neighbourhood (laterally).\n :param is_prime_square:\n :param x_square:\n :return:\n * pandas.DataFrame\n \"\"\"",
"# init outputs",
"# loop pixels that correspond ... | [
{
"param": "is_prime_square",
"type": null
},
{
"param": "x_square",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "is_prime_square",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": n... |
4a157a82091931dbe7ffc1289ac736172f4e6b40 | rcasero/cytometer | scripts/primes_scratch.py | [
"Apache-2.0"
] | Python | prop_primes | <not_specific> | def prop_primes(x):
"""
Compute proportion of prime numbers in each row/column (even length squares) or diagonal/antidiagonal (odd length
squares).
:param x:
:return:
"""
# length of square length
n = x.shape[0]
if n % 2 == 1: # odd length square
prop_fw = []
for... |
Compute proportion of prime numbers in each row/column (even length squares) or diagonal/antidiagonal (odd length
squares).
:param x:
:return:
| Compute proportion of prime numbers in each row/column (even length squares) or diagonal/antidiagonal (odd length
squares). | [
"Compute",
"proportion",
"of",
"prime",
"numbers",
"in",
"each",
"row",
"/",
"column",
"(",
"even",
"length",
"squares",
")",
"or",
"diagonal",
"/",
"antidiagonal",
"(",
"odd",
"length",
"squares",
")",
"."
] | def prop_primes(x):
n = x.shape[0]
if n % 2 == 1:
prop_fw = []
for k in range(n - 1, -n, -1):
diag = np.diagonal(x, k)
prop_fw.append(np.count_nonzero(diag) / len(diag))
x = np.fliplr(x)
prop_bk = []
for k in range(n - 1, -n, -1):
dia... | [
"def",
"prop_primes",
"(",
"x",
")",
":",
"n",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
"if",
"n",
"%",
"2",
"==",
"1",
":",
"prop_fw",
"=",
"[",
"]",
"for",
"k",
"in",
"range",
"(",
"n",
"-",
"1",
",",
"-",
"n",
",",
"-",
"1",
")",
":",
... | Compute proportion of prime numbers in each row/column (even length squares) or diagonal/antidiagonal (odd length
squares). | [
"Compute",
"proportion",
"of",
"prime",
"numbers",
"in",
"each",
"row",
"/",
"column",
"(",
"even",
"length",
"squares",
")",
"or",
"diagonal",
"/",
"antidiagonal",
"(",
"odd",
"length",
"squares",
")",
"."
] | [
"\"\"\"\n Compute proportion of prime numbers in each row/column (even length squares) or diagonal/antidiagonal (odd length\n squares).\n\n :param x:\n :return:\n \"\"\"",
"# length of square length",
"# odd length square",
"# even length square",
"# rows",
"# columns",
"# odd length squa... | [
{
"param": "x",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is... |
155644feb418a5fd293a091909a904c952f55d3b | rcasero/cytometer | scripts/rreb1_tm1b_exp_0004_pilot_annotations_postprocessing_v8_no_correction.py | [
"Apache-2.0"
] | Python | process_annotations | <not_specific> | def process_annotations(annotation_files_list, overwrite_aggregated_annotation_file=False, create_symlink=False):
"""
Helper function to process a list of JSON files with annotations.
:param annotation_files_list: list of JSON filenames containing annotations.
:return:
"""
for annotation_file i... |
Helper function to process a list of JSON files with annotations.
:param annotation_files_list: list of JSON filenames containing annotations.
:return:
| Helper function to process a list of JSON files with annotations. | [
"Helper",
"function",
"to",
"process",
"a",
"list",
"of",
"JSON",
"files",
"with",
"annotations",
"."
] | def process_annotations(annotation_files_list, overwrite_aggregated_annotation_file=False, create_symlink=False):
for annotation_file in annotation_files_list:
print('File: ' + os.path.basename(annotation_file))
aggregated_annotation_file = annotation_file.replace('.json', '_aggregated.json')
... | [
"def",
"process_annotations",
"(",
"annotation_files_list",
",",
"overwrite_aggregated_annotation_file",
"=",
"False",
",",
"create_symlink",
"=",
"False",
")",
":",
"for",
"annotation_file",
"in",
"annotation_files_list",
":",
"print",
"(",
"'File: '",
"+",
"os",
"."... | Helper function to process a list of JSON files with annotations. | [
"Helper",
"function",
"to",
"process",
"a",
"list",
"of",
"JSON",
"files",
"with",
"annotations",
"."
] | [
"\"\"\"\n Helper function to process a list of JSON files with annotations.\n :param annotation_files_list: list of JSON filenames containing annotations.\n :return:\n \"\"\"",
"# name of the file that we are going to save the aggregated annotations to",
"# name of the original .ndpi file",
"# agg... | [
{
"param": "annotation_files_list",
"type": null
},
{
"param": "overwrite_aggregated_annotation_file",
"type": null
},
{
"param": "create_symlink",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "annotation_files_list",
"type": null,
"docstring": "list of JSON filenames containing annotations.",
"docstring_tok... |
c85206d6c39b14afcc05aca0f48bd97316cec8ea | rcasero/cytometer | scripts/gtex_exp_0001_annotations_postprocessing.py | [
"Apache-2.0"
] | Python | process_annotations | null | def process_annotations(annotation_files_list, overwrite_aggregated_annotation_file=False, create_symlink=False):
"""
Helper function to process a list of JSON files with annotations.
:param annotation_files_list: list of JSON filenames containing annotations.
:return:
"""
for annotation_file i... |
Helper function to process a list of JSON files with annotations.
:param annotation_files_list: list of JSON filenames containing annotations.
:return:
| Helper function to process a list of JSON files with annotations. | [
"Helper",
"function",
"to",
"process",
"a",
"list",
"of",
"JSON",
"files",
"with",
"annotations",
"."
] | def process_annotations(annotation_files_list, overwrite_aggregated_annotation_file=False, create_symlink=False):
for annotation_file in annotation_files_list:
print('File: ' + os.path.basename(annotation_file))
aggregated_annotation_file = annotation_file.replace('.json', '_aggregated.json')
... | [
"def",
"process_annotations",
"(",
"annotation_files_list",
",",
"overwrite_aggregated_annotation_file",
"=",
"False",
",",
"create_symlink",
"=",
"False",
")",
":",
"for",
"annotation_file",
"in",
"annotation_files_list",
":",
"print",
"(",
"'File: '",
"+",
"os",
"."... | Helper function to process a list of JSON files with annotations. | [
"Helper",
"function",
"to",
"process",
"a",
"list",
"of",
"JSON",
"files",
"with",
"annotations",
"."
] | [
"\"\"\"\n Helper function to process a list of JSON files with annotations.\n :param annotation_files_list: list of JSON filenames containing annotations.\n :return:\n \"\"\"",
"# name of the file that we are going to save the aggregated annotations to",
"# name of the original histo file",
"# um/... | [
{
"param": "annotation_files_list",
"type": null
},
{
"param": "overwrite_aggregated_annotation_file",
"type": null
},
{
"param": "create_symlink",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "annotation_files_list",
"type": null,
"docstring": "list of JSON filenames containing annotations.",
"docstring_tok... |
7e2bede03831cff7c69ba12618a32aeb293a9f82 | rcasero/cytometer | cytometer/models.py | [
"Apache-2.0"
] | Python | load_model_with_retries | <not_specific> | def load_model_with_retries(model, number_of_attempts=1, time_between_attempts=5):
"""
Wrap keras.models.load_model in a loop so that if the loading fails due to some network filesystem errors, we wait a
few seconds and then retry to load the model.
:param model: string with filename containing a keras ... |
Wrap keras.models.load_model in a loop so that if the loading fails due to some network filesystem errors, we wait a
few seconds and then retry to load the model.
:param model: string with filename containing a keras model.
:param number_of_attempts: (def 1) Number of times we try to load the model bef... | Wrap keras.models.load_model in a loop so that if the loading fails due to some network filesystem errors, we wait a
few seconds and then retry to load the model. | [
"Wrap",
"keras",
".",
"models",
".",
"load_model",
"in",
"a",
"loop",
"so",
"that",
"if",
"the",
"loading",
"fails",
"due",
"to",
"some",
"network",
"filesystem",
"errors",
"we",
"wait",
"a",
"few",
"seconds",
"and",
"then",
"retry",
"to",
"load",
"the",... | def load_model_with_retries(model, number_of_attempts=1, time_between_attempts=5):
for attempt in range(number_of_attempts):
try:
model = keras.models.load_model(model)
break
except ConnectionResetError:
print(
'# ======> ConnectionResetError. Atte... | [
"def",
"load_model_with_retries",
"(",
"model",
",",
"number_of_attempts",
"=",
"1",
",",
"time_between_attempts",
"=",
"5",
")",
":",
"for",
"attempt",
"in",
"range",
"(",
"number_of_attempts",
")",
":",
"try",
":",
"model",
"=",
"keras",
".",
"models",
"."... | Wrap keras.models.load_model in a loop so that if the loading fails due to some network filesystem errors, we wait a
few seconds and then retry to load the model. | [
"Wrap",
"keras",
".",
"models",
".",
"load_model",
"in",
"a",
"loop",
"so",
"that",
"if",
"the",
"loading",
"fails",
"due",
"to",
"some",
"network",
"filesystem",
"errors",
"we",
"wait",
"a",
"few",
"seconds",
"and",
"then",
"retry",
"to",
"load",
"the",... | [
"\"\"\"\n Wrap keras.models.load_model in a loop so that if the loading fails due to some network filesystem errors, we wait a\n few seconds and then retry to load the model.\n :param model: string with filename containing a keras model.\n :param number_of_attempts: (def 1) Number of times we try to loa... | [
{
"param": "model",
"type": null
},
{
"param": "number_of_attempts",
"type": null
},
{
"param": "time_between_attempts",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "model",
"type": null,
"docstring": "string with filename containing a keras model.",
"docstring_tokens": [
... |
7e2bede03831cff7c69ba12618a32aeb293a9f82 | rcasero/cytometer | cytometer/models.py | [
"Apache-2.0"
] | Python | change_input_size | <not_specific> | def change_input_size(model, batch_shape):
"""
Change the expected shape of the model's input tensor.
This function works by creating a new model with the same structure, and then copying the weights from the original
model onto the new model. It follows the solution by Christos Kyrkou
(https://med... |
Change the expected shape of the model's input tensor.
This function works by creating a new model with the same structure, and then copying the weights from the original
model onto the new model. It follows the solution by Christos Kyrkou
(https://medium.com/@ckyrkou/changing-input-size-of-pre-traine... | Change the expected shape of the model's input tensor.
This function works by creating a new model with the same structure, and then copying the weights from the original
model onto the new model. It follows the solution by Christos Kyrkou
. | [
"Change",
"the",
"expected",
"shape",
"of",
"the",
"model",
"'",
"s",
"input",
"tensor",
".",
"This",
"function",
"works",
"by",
"creating",
"a",
"new",
"model",
"with",
"the",
"same",
"structure",
"and",
"then",
"copying",
"the",
"weights",
"from",
"the",... | def change_input_size(model, batch_shape):
model._layers[0].batch_input_shape = batch_shape
model_out = keras.models.model_from_json(model.to_json())
for layer in model_out.layers:
try:
layer.set_weights(model.get_layer(name=layer.name).get_weights())
except:
pass
... | [
"def",
"change_input_size",
"(",
"model",
",",
"batch_shape",
")",
":",
"model",
".",
"_layers",
"[",
"0",
"]",
".",
"batch_input_shape",
"=",
"batch_shape",
"model_out",
"=",
"keras",
".",
"models",
".",
"model_from_json",
"(",
"model",
".",
"to_json",
"(",... | Change the expected shape of the model's input tensor. | [
"Change",
"the",
"expected",
"shape",
"of",
"the",
"model",
"'",
"s",
"input",
"tensor",
"."
] | [
"\"\"\"\n Change the expected shape of the model's input tensor.\n\n This function works by creating a new model with the same structure, and then copying the weights from the original\n model onto the new model. It follows the solution by Christos Kyrkou\n (https://medium.com/@ckyrkou/changing-input-si... | [
{
"param": "model",
"type": null
},
{
"param": "batch_shape",
"type": null
}
] | {
"returns": [
{
"docstring": "Keras model with modified input layer.",
"docstring_tokens": [
"Keras",
"model",
"with",
"modified",
"input",
"layer",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier... |
7e2bede03831cff7c69ba12618a32aeb293a9f82 | rcasero/cytometer | cytometer/models.py | [
"Apache-2.0"
] | Python | check_model | <not_specific> | def check_model(model):
"""
Check the layers with weights for NaNs.
:param model: Keras model.
:return: list with the names of layers with NaNs. If no weights contain NaNs, the list is empty.
"""
# loop layers
layers_with_nans = []
for layer in model.layers:
# get the weights in... |
Check the layers with weights for NaNs.
:param model: Keras model.
:return: list with the names of layers with NaNs. If no weights contain NaNs, the list is empty.
| Check the layers with weights for NaNs. | [
"Check",
"the",
"layers",
"with",
"weights",
"for",
"NaNs",
"."
] | def check_model(model):
layers_with_nans = []
for layer in model.layers:
weights_list = layer.get_weights()
if not isinstance(weights_list, list):
continue
for weights in weights_list:
if not isinstance(weights, np.ndarray):
continue
if... | [
"def",
"check_model",
"(",
"model",
")",
":",
"layers_with_nans",
"=",
"[",
"]",
"for",
"layer",
"in",
"model",
".",
"layers",
":",
"weights_list",
"=",
"layer",
".",
"get_weights",
"(",
")",
"if",
"not",
"isinstance",
"(",
"weights_list",
",",
"list",
"... | Check the layers with weights for NaNs. | [
"Check",
"the",
"layers",
"with",
"weights",
"for",
"NaNs",
"."
] | [
"\"\"\"\n Check the layers with weights for NaNs.\n :param model: Keras model.\n :return: list with the names of layers with NaNs. If no weights contain NaNs, the list is empty.\n \"\"\"",
"# loop layers",
"# get the weights in the layer",
"# print('Checking layer ' + layer.name)",
"# print('Lay... | [
{
"param": "model",
"type": null
}
] | {
"returns": [
{
"docstring": "list with the names of layers with NaNs. If no weights contain NaNs, the list is empty.",
"docstring_tokens": [
"list",
"with",
"the",
"names",
"of",
"layers",
"with",
"NaNs",
".",
"If",
... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | resize | <not_specific> | def resize(x, size, resample=Image.NEAREST):
"""
Resize an image in numpy.ndarray format. PIL is used internally for the resizing.
:param x: numpy.ndarray (row, col) or (row, col, chan) for colour images.
:param size: (row, col)-tuple with the output size.
:param resample: (def Image.NEAREST) An op... |
Resize an image in numpy.ndarray format. PIL is used internally for the resizing.
:param x: numpy.ndarray (row, col) or (row, col, chan) for colour images.
:param size: (row, col)-tuple with the output size.
:param resample: (def Image.NEAREST) An optional resampling filter. This can be one of PIL.Ima... | Resize an image in numpy.ndarray format. PIL is used internally for the resizing. | [
"Resize",
"an",
"image",
"in",
"numpy",
".",
"ndarray",
"format",
".",
"PIL",
"is",
"used",
"internally",
"for",
"the",
"resizing",
"."
] | def resize(x, size, resample=Image.NEAREST):
if x.ndim < 2 or x.ndim > 3:
raise ValueError('x.ndims must be 2 or 3')
if x.ndim == 2:
x = Image.fromarray(x)
x = np.array(x.resize(size, resample=resample))
else:
y = np.zeros(shape=size + (x.shape[2],), dtype=x.dtype)
fo... | [
"def",
"resize",
"(",
"x",
",",
"size",
",",
"resample",
"=",
"Image",
".",
"NEAREST",
")",
":",
"if",
"x",
".",
"ndim",
"<",
"2",
"or",
"x",
".",
"ndim",
">",
"3",
":",
"raise",
"ValueError",
"(",
"'x.ndims must be 2 or 3'",
")",
"if",
"x",
".",
... | Resize an image in numpy.ndarray format. | [
"Resize",
"an",
"image",
"in",
"numpy",
".",
"ndarray",
"format",
"."
] | [
"\"\"\"\n Resize an image in numpy.ndarray format. PIL is used internally for the resizing.\n\n :param x: numpy.ndarray (row, col) or (row, col, chan) for colour images.\n :param size: (row, col)-tuple with the output size.\n :param resample: (def Image.NEAREST) An optional resampling filter. This can b... | [
{
"param": "x",
"type": null
},
{
"param": "size",
"type": null
},
{
"param": "resample",
"type": null
}
] | {
"returns": [
{
"docstring": "numpy.ndarray with the resized image.",
"docstring_tokens": [
"numpy",
".",
"ndarray",
"with",
"the",
"resized",
"image",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | clear_mem | <not_specific> | def clear_mem():
"""GPU garbage collection in Keras with TensorFlow.
From Otto Stegmaier and Jeremy Howard.
https://forums.fast.ai/t/gpu-garbage-collection/1976/5
"""
K.get_session().close()
sess = K.get_session()
sess.close()
# limit mem
cfg = tf.ConfigProto()
cfg.gpu_options.... | GPU garbage collection in Keras with TensorFlow.
From Otto Stegmaier and Jeremy Howard.
https://forums.fast.ai/t/gpu-garbage-collection/1976/5
| GPU garbage collection in Keras with TensorFlow.
From Otto Stegmaier and Jeremy Howard. | [
"GPU",
"garbage",
"collection",
"in",
"Keras",
"with",
"TensorFlow",
".",
"From",
"Otto",
"Stegmaier",
"and",
"Jeremy",
"Howard",
"."
] | def clear_mem():
K.get_session().close()
sess = K.get_session()
sess.close()
cfg = tf.ConfigProto()
cfg.gpu_options.allow_growth = True
K.set_session(tf.Session(config=cfg))
return | [
"def",
"clear_mem",
"(",
")",
":",
"K",
".",
"get_session",
"(",
")",
".",
"close",
"(",
")",
"sess",
"=",
"K",
".",
"get_session",
"(",
")",
"sess",
".",
"close",
"(",
")",
"cfg",
"=",
"tf",
".",
"ConfigProto",
"(",
")",
"cfg",
".",
"gpu_options... | GPU garbage collection in Keras with TensorFlow. | [
"GPU",
"garbage",
"collection",
"in",
"Keras",
"with",
"TensorFlow",
"."
] | [
"\"\"\"GPU garbage collection in Keras with TensorFlow.\n\n From Otto Stegmaier and Jeremy Howard.\n https://forums.fast.ai/t/gpu-garbage-collection/1976/5\n \"\"\"",
"# limit mem"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | paint_labels | <not_specific> | def paint_labels(labels, paint_labs, paint_values):
"""
Assign values to pixels in image according to their labels. E.g.
labels = [2, 2, 2, 3, 0] paint_labs = [0, 1, 2, 3] paint_values = [.3, .5., .9, .7]
[2, 2, 0, 3, 1]
[2, 2, 0, 0, 3]
out = paint_labels(labels, paint_la... |
Assign values to pixels in image according to their labels. E.g.
labels = [2, 2, 2, 3, 0] paint_labs = [0, 1, 2, 3] paint_values = [.3, .5., .9, .7]
[2, 2, 0, 3, 1]
[2, 2, 0, 0, 3]
out = paint_labels(labels, paint_labs, paint_values)
out = [.9, .9, .9, .7, .3]
... | Assign values to pixels in image according to their labels.
| [
"Assign",
"values",
"to",
"pixels",
"in",
"image",
"according",
"to",
"their",
"labels",
"."
] | def paint_labels(labels, paint_labs, paint_values):
max_lab = np.max([np.max(paint_labs), np.max(labels)])
lut = np.zeros(shape=(max_lab + 1,), dtype=paint_values.dtype)
lut.fill(np.nan)
lut[paint_labs] = paint_values
return lut[labels] | [
"def",
"paint_labels",
"(",
"labels",
",",
"paint_labs",
",",
"paint_values",
")",
":",
"max_lab",
"=",
"np",
".",
"max",
"(",
"[",
"np",
".",
"max",
"(",
"paint_labs",
")",
",",
"np",
".",
"max",
"(",
"labels",
")",
"]",
")",
"lut",
"=",
"np",
"... | Assign values to pixels in image according to their labels. | [
"Assign",
"values",
"to",
"pixels",
"in",
"image",
"according",
"to",
"their",
"labels",
"."
] | [
"\"\"\"\n Assign values to pixels in image according to their labels. E.g.\n\n labels = [2, 2, 2, 3, 0] paint_labs = [0, 1, 2, 3] paint_values = [.3, .5., .9, .7]\n [2, 2, 0, 3, 1]\n [2, 2, 0, 0, 3]\n\n out = paint_labels(labels, paint_labs, paint_values)\n\n out = [.9, .9, .... | [
{
"param": "labels",
"type": null
},
{
"param": "paint_labs",
"type": null
},
{
"param": "paint_values",
"type": null
}
] | {
"returns": [
{
"docstring": "numpy.ndarray of the same size as labels, where labels have been replaced by their corresponding values.",
"docstring_tokens": [
"numpy",
".",
"ndarray",
"of",
"the",
"same",
"size",
"as",
"labels",
... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | rough_foreground_mask | <not_specific> | def rough_foreground_mask(filename, downsample_factor=8.0, dilation_size=25,
component_size_threshold=1e6, hole_size_treshold=8000, std_k=1.0,
return_im=False, enhance_contrast=None, clear_border=[0, 0, 0, 0],
ignore_white_threshold=None, ign... |
Rough segmentation of large segmentation objects in a microscope image with a format that can be read
by OpenSlice. The objects are darker than the background.
The function works by first estimating the colour of the background as the mode of all colours. This assumes
that background pixels are the mo... | Rough segmentation of large segmentation objects in a microscope image with a format that can be read
by OpenSlice. The objects are darker than the background.
The function works by first estimating the colour of the background as the mode of all colours. This assumes
that background pixels are the most numerous and r... | [
"Rough",
"segmentation",
"of",
"large",
"segmentation",
"objects",
"in",
"a",
"microscope",
"image",
"with",
"a",
"format",
"that",
"can",
"be",
"read",
"by",
"OpenSlice",
".",
"The",
"objects",
"are",
"darker",
"than",
"the",
"background",
".",
"The",
"func... | def rough_foreground_mask(filename, downsample_factor=8.0, dilation_size=25,
component_size_threshold=1e6, hole_size_treshold=8000, std_k=1.0,
return_im=False, enhance_contrast=None, clear_border=[0, 0, 0, 0],
ignore_white_threshold=None, ign... | [
"def",
"rough_foreground_mask",
"(",
"filename",
",",
"downsample_factor",
"=",
"8.0",
",",
"dilation_size",
"=",
"25",
",",
"component_size_threshold",
"=",
"1e6",
",",
"hole_size_treshold",
"=",
"8000",
",",
"std_k",
"=",
"1.0",
",",
"return_im",
"=",
"False",... | Rough segmentation of large segmentation objects in a microscope image with a format that can be read
by OpenSlice. | [
"Rough",
"segmentation",
"of",
"large",
"segmentation",
"objects",
"in",
"a",
"microscope",
"image",
"with",
"a",
"format",
"that",
"can",
"be",
"read",
"by",
"OpenSlice",
"."
] | [
"\"\"\"\n Rough segmentation of large segmentation objects in a microscope image with a format that can be read\n by OpenSlice. The objects are darker than the background.\n\n The function works by first estimating the colour of the background as the mode of all colours. This assumes\n that background p... | [
{
"param": "filename",
"type": null
},
{
"param": "downsample_factor",
"type": null
},
{
"param": "dilation_size",
"type": null
},
{
"param": "component_size_threshold",
"type": null
},
{
"param": "hole_size_treshold",
"type": null
},
{
"param": "std_k... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "filename",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "downsample_factor",
"type": null,
"docstring": null,
"doc... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | principal_curvatures_range_image | <not_specific> | def principal_curvatures_range_image(img, sigma=10):
"""
Compute Gaussian, Mean and principal curvatures of an image with depth values. Examples of such images
are topographic maps, range images, depth maps or distance transformations.
Any of this images can be projected as a Monge patch, a 2D surface ... |
Compute Gaussian, Mean and principal curvatures of an image with depth values. Examples of such images
are topographic maps, range images, depth maps or distance transformations.
Any of this images can be projected as a Monge patch, a 2D surface embedded in 3D space, f:U->R^3,
f(x,y) = (x, y, img(x, y... | Compute Gaussian, Mean and principal curvatures of an image with depth values. Examples of such images
are topographic maps, range images, depth maps or distance transformations.
Any of this images can be projected as a Monge patch, a 2D surface embedded in 3D space, f:U->R^3,
f(x,y) = (x, y, img(x, y)).
We use a cub... | [
"Compute",
"Gaussian",
"Mean",
"and",
"principal",
"curvatures",
"of",
"an",
"image",
"with",
"depth",
"values",
".",
"Examples",
"of",
"such",
"images",
"are",
"topographic",
"maps",
"range",
"images",
"depth",
"maps",
"or",
"distance",
"transformations",
".",
... | def principal_curvatures_range_image(img, sigma=10):
img = gaussian_filter(img, sigma=sigma)
sp = RectBivariateSpline(range(img.shape[0]), range(img.shape[1]), img, kx=3, ky=3, s=0)
hx = sp(range(img.shape[0]), range(img.shape[1]), dx=1, grid=True)
hy = sp(range(img.shape[0]), range(img.shape[1]), dy=1,... | [
"def",
"principal_curvatures_range_image",
"(",
"img",
",",
"sigma",
"=",
"10",
")",
":",
"img",
"=",
"gaussian_filter",
"(",
"img",
",",
"sigma",
"=",
"sigma",
")",
"sp",
"=",
"RectBivariateSpline",
"(",
"range",
"(",
"img",
".",
"shape",
"[",
"0",
"]",... | Compute Gaussian, Mean and principal curvatures of an image with depth values. | [
"Compute",
"Gaussian",
"Mean",
"and",
"principal",
"curvatures",
"of",
"an",
"image",
"with",
"depth",
"values",
"."
] | [
"\"\"\"\n Compute Gaussian, Mean and principal curvatures of an image with depth values. Examples of such images\n are topographic maps, range images, depth maps or distance transformations.\n\n Any of this images can be projected as a Monge patch, a 2D surface embedded in 3D space, f:U->R^3,\n f(x,y) =... | [
{
"param": "img",
"type": null
},
{
"param": "sigma",
"type": null
}
] | {
"returns": [
{
"docstring": "K, H, k1, k2 = Gaussian curvature, Mean curvature, principal curvature 1, principal\ncurvature 2. Each output is an array of the same size as img, with a curvature value per pixel.",
"docstring_tokens": [
"K",
"H",
"k1",
"k2",
"=",... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | segment_dmap_contour | <not_specific> | def segment_dmap_contour(dmap, contour=None,
sigma=10, min_seed_object_size=50, border_dilation=0, boundary_threshold=0.1,
median_size=11, closing_size=11, contour_seed_threshold=0,
version=2):
"""
Segment cells from a distance transform... |
Segment cells from a distance transformation image, and optionally, a contour estimate image.
This function computes the normal curvature of the dmap seen as a Monge patch. The "valleys" in
the dmap (the cell contours) correspond to higher normal curvature values.
If provided, the normal curvature is... | Segment cells from a distance transformation image, and optionally, a contour estimate image.
This function computes the normal curvature of the dmap seen as a Monge patch. The "valleys" in
the dmap (the cell contours) correspond to higher normal curvature values.
If provided, the normal curvature is element-wise mult... | [
"Segment",
"cells",
"from",
"a",
"distance",
"transformation",
"image",
"and",
"optionally",
"a",
"contour",
"estimate",
"image",
".",
"This",
"function",
"computes",
"the",
"normal",
"curvature",
"of",
"the",
"dmap",
"seen",
"as",
"a",
"Monge",
"patch",
".",
... | def segment_dmap_contour(dmap, contour=None,
sigma=10, min_seed_object_size=50, border_dilation=0, boundary_threshold=0.1,
median_size=11, closing_size=11, contour_seed_threshold=0,
version=2):
For the purpose of this function, the details ... | [
"def",
"segment_dmap_contour",
"(",
"dmap",
",",
"contour",
"=",
"None",
",",
"sigma",
"=",
"10",
",",
"min_seed_object_size",
"=",
"50",
",",
"border_dilation",
"=",
"0",
",",
"boundary_threshold",
"=",
"0.1",
",",
"median_size",
"=",
"11",
",",
"closing_si... | Segment cells from a distance transformation image, and optionally, a contour estimate image. | [
"Segment",
"cells",
"from",
"a",
"distance",
"transformation",
"image",
"and",
"optionally",
"a",
"contour",
"estimate",
"image",
"."
] | [
"\"\"\"\n Segment cells from a distance transformation image, and optionally, a contour estimate image.\n\n This function computes the normal curvature of the dmap seen as a Monge patch. The \"valleys\" in\n the dmap (the cell contours) correspond to higher normal curvature values.\n\n If provided, the ... | [
{
"param": "dmap",
"type": null
},
{
"param": "contour",
"type": null
},
{
"param": "sigma",
"type": null
},
{
"param": "min_seed_object_size",
"type": null
},
{
"param": "border_dilation",
"type": null
},
{
"param": "boundary_threshold",
"type": n... | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "dmap",
"type": null,
"docstring": "numpy.ndarray matrix with distance transformation, distance range image,\ntopographic ... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | match_overlapping_labels | <not_specific> | def match_overlapping_labels(labels_ref, labels_test, allow_repeat_ref=False):
"""
Match estimated segmentations to ground truth segmentations and compute Dice coefficients.
This function takes two segmentations, reference and test, and computes how good each test
label segmentation is, based on how it... |
Match estimated segmentations to ground truth segmentations and compute Dice coefficients.
This function takes two segmentations, reference and test, and computes how good each test
label segmentation is, based on how it overlaps the reference segmentation. In a nutshell,
we find the reference label b... | Match estimated segmentations to ground truth segmentations and compute Dice coefficients.
This function takes two segmentations, reference and test, and computes how good each test
label segmentation is, based on how it overlaps the reference segmentation. In a nutshell,
we find the reference label best aligned to eac... | [
"Match",
"estimated",
"segmentations",
"to",
"ground",
"truth",
"segmentations",
"and",
"compute",
"Dice",
"coefficients",
".",
"This",
"function",
"takes",
"two",
"segmentations",
"reference",
"and",
"test",
"and",
"computes",
"how",
"good",
"each",
"test",
"labe... | def match_overlapping_labels(labels_ref, labels_test, allow_repeat_ref=False):
test = 0
ref = 1
labels_test_unique, labels_test_unique_count = np.unique(labels_test, return_counts=True)
labels_ref_unique, labels_ref_unique_count = np.unique(labels_ref, return_counts=True)
idx = labels_test_unique !=... | [
"def",
"match_overlapping_labels",
"(",
"labels_ref",
",",
"labels_test",
",",
"allow_repeat_ref",
"=",
"False",
")",
":",
"test",
"=",
"0",
"ref",
"=",
"1",
"labels_test_unique",
",",
"labels_test_unique_count",
"=",
"np",
".",
"unique",
"(",
"labels_test",
","... | Match estimated segmentations to ground truth segmentations and compute Dice coefficients. | [
"Match",
"estimated",
"segmentations",
"to",
"ground",
"truth",
"segmentations",
"and",
"compute",
"Dice",
"coefficients",
"."
] | [
"\"\"\"\n Match estimated segmentations to ground truth segmentations and compute Dice coefficients.\n\n This function takes two segmentations, reference and test, and computes how good each test\n label segmentation is, based on how it overlaps the reference segmentation. In a nutshell,\n we find the r... | [
{
"param": "labels_ref",
"type": null
},
{
"param": "labels_test",
"type": null
},
{
"param": "allow_repeat_ref",
"type": null
}
] | {
"returns": [
{
"docstring": "structured array out:\nout['lab_test']: (N,) np.ndarray with unique list of labels in the test image.\nout['lab_ref']: (N,) np.ndarray with labels that best align with the test labels.\nout['area_test']: (N,) np.ndarray with area of test label in pixels.\nout['area_ref']: (N,)... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | prop_of_pixels_in_label | <not_specific> | def prop_of_pixels_in_label(lab, mask):
"""
Proportion of pixels in each label that belong to a mask.
For example, if label "7" contains a total of 20 pixels, and 5 of those pixels have mask != 0, then the proportion
is 5/20 = 0.25.
:param lab: (row, col) np.ndarray with a label segmentation (all ... |
Proportion of pixels in each label that belong to a mask.
For example, if label "7" contains a total of 20 pixels, and 5 of those pixels have mask != 0, then the proportion
is 5/20 = 0.25.
:param lab: (row, col) np.ndarray with a label segmentation (all pixels with the same integer value belong to th... | Proportion of pixels in each label that belong to a mask.
For example, if label "7" contains a total of 20 pixels, and 5 of those pixels have mask != 0, then the proportion
is 5/20 = 0.25. | [
"Proportion",
"of",
"pixels",
"in",
"each",
"label",
"that",
"belong",
"to",
"a",
"mask",
".",
"For",
"example",
"if",
"label",
"\"",
"7",
"\"",
"contains",
"a",
"total",
"of",
"20",
"pixels",
"and",
"5",
"of",
"those",
"pixels",
"have",
"mask",
"!",
... | def prop_of_pixels_in_label(lab, mask):
lut = np.zeros(shape=(np.max(lab)+1,), dtype=np.float32)
lut_masked = np.zeros(shape=(np.max(lab)+1,), dtype=np.float32)
seg_labs, seg_labs_counts = np.unique(lab * (mask != 0), return_counts=True)
lut_masked[seg_labs] = seg_labs_counts
seg_labs, seg_labs_coun... | [
"def",
"prop_of_pixels_in_label",
"(",
"lab",
",",
"mask",
")",
":",
"lut",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"(",
"np",
".",
"max",
"(",
"lab",
")",
"+",
"1",
",",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"lut_masked",
"=",
... | Proportion of pixels in each label that belong to a mask. | [
"Proportion",
"of",
"pixels",
"in",
"each",
"label",
"that",
"belong",
"to",
"a",
"mask",
"."
] | [
"\"\"\"\n Proportion of pixels in each label that belong to a mask.\n\n For example, if label \"7\" contains a total of 20 pixels, and 5 of those pixels have mask != 0, then the proportion\n is 5/20 = 0.25.\n\n :param lab: (row, col) np.ndarray with a label segmentation (all pixels with the same integer... | [
{
"param": "lab",
"type": null
},
{
"param": "mask",
"type": null
}
] | {
"returns": [
{
"docstring": "Vector with the list of unique labels in lab.\nseg_prop: Vector with the proportion of masked pixels in each label.",
"docstring_tokens": [
"Vector",
"with",
"the",
"list",
"of",
"unique",
"labels",
"in",
... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | bounding_box_with_margin | <not_specific> | def bounding_box_with_margin(label, inc=0.0, coordinates='xy'):
"""
Create a square bounding box around a segmentation mask, with optional enlargement/reduction.
The output is given as (x0, y0, xend, yend) for plotting or (r0, c0, rend, cend) for indexing arrays.
Note that because we need integers for ... |
Create a square bounding box around a segmentation mask, with optional enlargement/reduction.
The output is given as (x0, y0, xend, yend) for plotting or (r0, c0, rend, cend) for indexing arrays.
Note that because we need integers for indexing, the bounding box may not be completely centered on the segmen... | Create a square bounding box around a segmentation mask, with optional enlargement/reduction.
The output is given as (x0, y0, xend, yend) for plotting or (r0, c0, rend, cend) for indexing arrays.
Note that because we need integers for indexing, the bounding box may not be completely centered on the segmentation
mask.
... | [
"Create",
"a",
"square",
"bounding",
"box",
"around",
"a",
"segmentation",
"mask",
"with",
"optional",
"enlargement",
"/",
"reduction",
".",
"The",
"output",
"is",
"given",
"as",
"(",
"x0",
"y0",
"xend",
"yend",
")",
"for",
"plotting",
"or",
"(",
"r0",
"... | def bounding_box_with_margin(label, inc=0.0, coordinates='xy'):
props = regionprops((label != 0).astype(np.uint8), coordinates='rc')
assert (len(props) == 1)
bbox = props[0]['bbox']
(bbox_r0, bbox_c0, bbox_rend, bbox_cend) = bbox
bbox_r_len = bbox_rend - bbox_r0
bbox_c_len = bbox_cend - bbox_c0
... | [
"def",
"bounding_box_with_margin",
"(",
"label",
",",
"inc",
"=",
"0.0",
",",
"coordinates",
"=",
"'xy'",
")",
":",
"props",
"=",
"regionprops",
"(",
"(",
"label",
"!=",
"0",
")",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
",",
"coordinates",
"=",
... | Create a square bounding box around a segmentation mask, with optional enlargement/reduction. | [
"Create",
"a",
"square",
"bounding",
"box",
"around",
"a",
"segmentation",
"mask",
"with",
"optional",
"enlargement",
"/",
"reduction",
"."
] | [
"\"\"\"\n Create a square bounding box around a segmentation mask, with optional enlargement/reduction.\n The output is given as (x0, y0, xend, yend) for plotting or (r0, c0, rend, cend) for indexing arrays.\n\n Note that because we need integers for indexing, the bounding box may not be completely centere... | [
{
"param": "label",
"type": null
},
{
"param": "inc",
"type": null
},
{
"param": "coordinates",
"type": null
}
] | {
"returns": [
{
"docstring": "Coordinates of the bottom left and top right corners of the box.\nIf coordinates=='xy': (x0, y0, xend, yend): These are the true coordinates of the box corners, and these values\ncan be directly used for plotting.\nIf coordinates=='rc': (r0, c0, rend, cend): These are rounded ... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | extract_bbox | <not_specific> | def extract_bbox(im, bbox):
"""
Crop bounding box from an image. Note that bounding boxes that go beyond the image boundaries are allowed. In that
case, external pixels will be set to zero.
:param im: (row, col) or (row, col, channels) np.ndarray image.
:param bbox: (r0, c0, rend, cend)-tuple with ... |
Crop bounding box from an image. Note that bounding boxes that go beyond the image boundaries are allowed. In that
case, external pixels will be set to zero.
:param im: (row, col) or (row, col, channels) np.ndarray image.
:param bbox: (r0, c0, rend, cend)-tuple with bottom left and top right vertices ... | Crop bounding box from an image. Note that bounding boxes that go beyond the image boundaries are allowed. In that
case, external pixels will be set to zero. | [
"Crop",
"bounding",
"box",
"from",
"an",
"image",
".",
"Note",
"that",
"bounding",
"boxes",
"that",
"go",
"beyond",
"the",
"image",
"boundaries",
"are",
"allowed",
".",
"In",
"that",
"case",
"external",
"pixels",
"will",
"be",
"set",
"to",
"zero",
"."
] | def extract_bbox(im, bbox):
if im.ndim < 2 or im.ndim > 3:
raise ValueError('im must be a (row, col) or (row, col, channel) array')
elif im.ndim == 2:
DIM2 = True
im = np.expand_dims(im, axis=2)
else:
DIM2 = False
r0, c0, rend, cend = bbox
out = np.zeros(shape=(rend -... | [
"def",
"extract_bbox",
"(",
"im",
",",
"bbox",
")",
":",
"if",
"im",
".",
"ndim",
"<",
"2",
"or",
"im",
".",
"ndim",
">",
"3",
":",
"raise",
"ValueError",
"(",
"'im must be a (row, col) or (row, col, channel) array'",
")",
"elif",
"im",
".",
"ndim",
"==",
... | Crop bounding box from an image. | [
"Crop",
"bounding",
"box",
"from",
"an",
"image",
"."
] | [
"\"\"\"\n Crop bounding box from an image. Note that bounding boxes that go beyond the image boundaries are allowed. In that\n case, external pixels will be set to zero.\n\n :param im: (row, col) or (row, col, channels) np.ndarray image.\n :param bbox: (r0, c0, rend, cend)-tuple with bottom left and top... | [
{
"param": "im",
"type": null
},
{
"param": "bbox",
"type": null
}
] | {
"returns": [
{
"docstring": "Cropping of the image, as numpy.ndarray with the same number of channels as im.",
"docstring_tokens": [
"Cropping",
"of",
"the",
"image",
"as",
"numpy",
".",
"ndarray",
"with",
"the",
... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | one_image_per_label_v2 | <not_specific> | def one_image_per_label_v2(vols, resize_to=None, resample=None, bbox_inc=1.0, only_central_label=False,
return_bbox=False):
"""
Crop a squared bounding box around each label in a segmentation array. Optionally, more volumes of the same size
can be provided and they will be cropped... |
Crop a squared bounding box around each label in a segmentation array. Optionally, more volumes of the same size
can be provided and they will be cropped according to the same labels (this is useful if e.g. you want to also crop
the image the segmentation was computed on).
Also optionally:
* ... | Crop a squared bounding box around each label in a segmentation array. Optionally, more volumes of the same size
can be provided and they will be cropped according to the same labels (this is useful if e.g. you want to also crop
the image the segmentation was computed on).
Also optionally.
The crops can all be scaled... | [
"Crop",
"a",
"squared",
"bounding",
"box",
"around",
"each",
"label",
"in",
"a",
"segmentation",
"array",
".",
"Optionally",
"more",
"volumes",
"of",
"the",
"same",
"size",
"can",
"be",
"provided",
"and",
"they",
"will",
"be",
"cropped",
"according",
"to",
... | def one_image_per_label_v2(vols, resize_to=None, resample=None, bbox_inc=1.0, only_central_label=False,
return_bbox=False):
if type(vols) == tuple:
vols = list(vols)
vols_islist = type(vols) == list
if not vols_islist:
vols = [vols]
labels = vols[0]
i... | [
"def",
"one_image_per_label_v2",
"(",
"vols",
",",
"resize_to",
"=",
"None",
",",
"resample",
"=",
"None",
",",
"bbox_inc",
"=",
"1.0",
",",
"only_central_label",
"=",
"False",
",",
"return_bbox",
"=",
"False",
")",
":",
"if",
"type",
"(",
"vols",
")",
"... | Crop a squared bounding box around each label in a segmentation array. | [
"Crop",
"a",
"squared",
"bounding",
"box",
"around",
"each",
"label",
"in",
"a",
"segmentation",
"array",
"."
] | [
"\"\"\"\n Crop a squared bounding box around each label in a segmentation array. Optionally, more volumes of the same size\n can be provided and they will be cropped according to the same labels (this is useful if e.g. you want to also crop\n the image the segmentation was computed on).\n\n Also optiona... | [
{
"param": "vols",
"type": null
},
{
"param": "resize_to",
"type": null
},
{
"param": "resample",
"type": null
},
{
"param": "bbox_inc",
"type": null
},
{
"param": "only_central_label",
"type": null
},
{
"param": "return_bbox",
"type": null
}
] | {
"returns": [
{
"docstring": "tuple with the cropped windows, e.g.\n\nIf resize_to had some value, e.g. (401, 401), each list has been collapsed into an array, e.g.\n\n\n\n\n\nList of tuples (i, lab), where i is the image index, and lab is the segmentation label of each\ncrop. If input return_bbox=True, th... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | edge_labels | <not_specific> | def edge_labels(labels):
"""
Find which labels touch the borders of the image. The background label (0) will be ignored.
:param labels: 2D numpy.ndarray with segmentation labels.
:return:
edge_labels: numpy.ndarray with list of labels.
"""
if labels.ndim != 2:
raise ValueError('lab... |
Find which labels touch the borders of the image. The background label (0) will be ignored.
:param labels: 2D numpy.ndarray with segmentation labels.
:return:
edge_labels: numpy.ndarray with list of labels.
| Find which labels touch the borders of the image. The background label (0) will be ignored. | [
"Find",
"which",
"labels",
"touch",
"the",
"borders",
"of",
"the",
"image",
".",
"The",
"background",
"label",
"(",
"0",
")",
"will",
"be",
"ignored",
"."
] | def edge_labels(labels):
if labels.ndim != 2:
raise ValueError('labels must be a 2D array')
edge_labels = np.unique(labels[0, :])
edge_labels = np.unique(np.concatenate((edge_labels, labels[:, 0].flat)))
edge_labels = np.unique(np.concatenate((edge_labels, labels[:, -1].flat)))
edge_labels =... | [
"def",
"edge_labels",
"(",
"labels",
")",
":",
"if",
"labels",
".",
"ndim",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'labels must be a 2D array'",
")",
"edge_labels",
"=",
"np",
".",
"unique",
"(",
"labels",
"[",
"0",
",",
":",
"]",
")",
"edge_labels... | Find which labels touch the borders of the image. | [
"Find",
"which",
"labels",
"touch",
"the",
"borders",
"of",
"the",
"image",
"."
] | [
"\"\"\"\n Find which labels touch the borders of the image. The background label (0) will be ignored.\n\n :param labels: 2D numpy.ndarray with segmentation labels.\n :return:\n edge_labels: numpy.ndarray with list of labels.\n \"\"\"",
"# labels that touch the top edge of the image",
"# labels th... | [
{
"param": "labels",
"type": null
}
] | {
"returns": [
{
"docstring": "numpy.ndarray with list of labels.",
"docstring_tokens": [
"numpy",
".",
"ndarray",
"with",
"list",
"of",
"labels",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"ident... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | clean_segmentation | <not_specific> | def clean_segmentation(labels,
min_cell_area=0, max_cell_area=np.inf,
remove_edge_labels=False,
mask=None, min_mask_overlap=0.8,
phagocytosis=False,
labels_class=None, min_class_prop=1.0):
"""
The ... |
The function packs several methods to remove unwanted labels from a segmentation:
* Remove labels that are smaller than a certain size.
* Remove labels that don't overlap enough with a binary mask.
* Remove labels that don't contain enough pixels of class 1.
* Merge labels that are complete... | The function packs several methods to remove unwanted labels from a segmentation:
Remove labels that are smaller than a certain size.
Remove labels that don't overlap enough with a binary mask.
Remove labels that don't contain enough pixels of class 1.
Merge labels that are completely surrounded by another label into t... | [
"The",
"function",
"packs",
"several",
"methods",
"to",
"remove",
"unwanted",
"labels",
"from",
"a",
"segmentation",
":",
"Remove",
"labels",
"that",
"are",
"smaller",
"than",
"a",
"certain",
"size",
".",
"Remove",
"labels",
"that",
"don",
"'",
"t",
"overlap... | def clean_segmentation(labels,
min_cell_area=0, max_cell_area=np.inf,
remove_edge_labels=False,
mask=None, min_mask_overlap=0.8,
phagocytosis=False,
labels_class=None, min_class_prop=1.0):
if mask is n... | [
"def",
"clean_segmentation",
"(",
"labels",
",",
"min_cell_area",
"=",
"0",
",",
"max_cell_area",
"=",
"np",
".",
"inf",
",",
"remove_edge_labels",
"=",
"False",
",",
"mask",
"=",
"None",
",",
"min_mask_overlap",
"=",
"0.8",
",",
"phagocytosis",
"=",
"False"... | The function packs several methods to remove unwanted labels from a segmentation:
Remove labels that are smaller than a certain size. | [
"The",
"function",
"packs",
"several",
"methods",
"to",
"remove",
"unwanted",
"labels",
"from",
"a",
"segmentation",
":",
"Remove",
"labels",
"that",
"are",
"smaller",
"than",
"a",
"certain",
"size",
"."
] | [
"\"\"\"\n The function packs several methods to remove unwanted labels from a segmentation:\n * Remove labels that are smaller than a certain size.\n * Remove labels that don't overlap enough with a binary mask.\n * Remove labels that don't contain enough pixels of class 1.\n * Merge labels t... | [
{
"param": "labels",
"type": null
},
{
"param": "min_cell_area",
"type": null
},
{
"param": "max_cell_area",
"type": null
},
{
"param": "remove_edge_labels",
"type": null
},
{
"param": "mask",
"type": null
},
{
"param": "min_mask_overlap",
"type": ... | {
"returns": [
{
"docstring": "(row, col) or (n, row, col) np.ndarray with removed labels as requested.\nis_removed_edge_label: (row, col) or (n, row, col) boolean np.ndarray. True pixels belong to edge labels that were\nremoved.",
"docstring_tokens": [
"(",
"row",
"col",
... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | correct_segmentation | <not_specific> | def correct_segmentation(im, seg, correction_model, model_type='-1_1', smoothing=11, batch_size=16):
"""
Correct histology segmentation using a fully convolutional neural network.
This methods follows the following steps:
* Use keras model to estimate which pixels have been underestimated/overestim... |
Correct histology segmentation using a fully convolutional neural network.
This methods follows the following steps:
* Use keras model to estimate which pixels have been underestimated/overestimated in the segmentation, and
correct segmentation accordingly.
* Fill holes.
* Ke... | Correct histology segmentation using a fully convolutional neural network.
This methods follows the following steps:
Use keras model to estimate which pixels have been underestimated/overestimated in the segmentation, and
correct segmentation accordingly.
Fill holes.
Keep only the largest component in each segmentation... | [
"Correct",
"histology",
"segmentation",
"using",
"a",
"fully",
"convolutional",
"neural",
"network",
".",
"This",
"methods",
"follows",
"the",
"following",
"steps",
":",
"Use",
"keras",
"model",
"to",
"estimate",
"which",
"pixels",
"have",
"been",
"underestimated"... | def correct_segmentation(im, seg, correction_model, model_type='-1_1', smoothing=11, batch_size=16):
if isinstance(correction_model, six.string_types):
correction_model = keras.models.load_model(correction_model)
correction_model = change_input_size(correction_model, batch_shape=im.shape)
seg_out = ... | [
"def",
"correct_segmentation",
"(",
"im",
",",
"seg",
",",
"correction_model",
",",
"model_type",
"=",
"'-1_1'",
",",
"smoothing",
"=",
"11",
",",
"batch_size",
"=",
"16",
")",
":",
"if",
"isinstance",
"(",
"correction_model",
",",
"six",
".",
"string_types"... | Correct histology segmentation using a fully convolutional neural network. | [
"Correct",
"histology",
"segmentation",
"using",
"a",
"fully",
"convolutional",
"neural",
"network",
"."
] | [
"\"\"\"\n Correct histology segmentation using a fully convolutional neural network.\n\n This methods follows the following steps:\n * Use keras model to estimate which pixels have been underestimated/overestimated in the segmentation, and\n correct segmentation accordingly.\n * Fill ho... | [
{
"param": "im",
"type": null
},
{
"param": "seg",
"type": null
},
{
"param": "correction_model",
"type": null
},
{
"param": "model_type",
"type": null
},
{
"param": "smoothing",
"type": null
},
{
"param": "batch_size",
"type": null
}
] | {
"returns": [
{
"docstring": "(n, row, col) Corrected segmentations.",
"docstring_tokens": [
"(",
"n",
"row",
"col",
")",
"Corrected",
"segmentations",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | segmentation_pipeline | <not_specific> | def segmentation_pipeline(im, contour_model, dmap_model, quality_model,
quality_model_type='0_1', quality_model_preprocessing=None,
mask=None, smallest_cell_area=804):
"""
Instance segmentation of cells using the contour + distance transformation pipeline.
... |
Instance segmentation of cells using the contour + distance transformation pipeline.
DEPRECATED by segmentation_pipeline2(). Kept for historical comparisons.
:param im: numpy.ndarray (image, row, col, channel) with RGB histology images.
:param contour_model: filename or keras model for the contour de... | Instance segmentation of cells using the contour + distance transformation pipeline. | [
"Instance",
"segmentation",
"of",
"cells",
"using",
"the",
"contour",
"+",
"distance",
"transformation",
"pipeline",
"."
] | def segmentation_pipeline(im, contour_model, dmap_model, quality_model,
quality_model_type='0_1', quality_model_preprocessing=None,
mask=None, smallest_cell_area=804):
if isinstance(contour_model, six.string_types):
contour_model = keras.models.load_model(... | [
"def",
"segmentation_pipeline",
"(",
"im",
",",
"contour_model",
",",
"dmap_model",
",",
"quality_model",
",",
"quality_model_type",
"=",
"'0_1'",
",",
"quality_model_preprocessing",
"=",
"None",
",",
"mask",
"=",
"None",
",",
"smallest_cell_area",
"=",
"804",
")"... | Instance segmentation of cells using the contour + distance transformation pipeline. | [
"Instance",
"segmentation",
"of",
"cells",
"using",
"the",
"contour",
"+",
"distance",
"transformation",
"pipeline",
"."
] | [
"\"\"\"\n Instance segmentation of cells using the contour + distance transformation pipeline.\n\n DEPRECATED by segmentation_pipeline2(). Kept for historical comparisons.\n\n :param im: numpy.ndarray (image, row, col, channel) with RGB histology images.\n :param contour_model: filename or keras model f... | [
{
"param": "im",
"type": null
},
{
"param": "contour_model",
"type": null
},
{
"param": "dmap_model",
"type": null
},
{
"param": "quality_model",
"type": null
},
{
"param": "quality_model_type",
"type": null
},
{
"param": "quality_model_preprocessing",... | {
"returns": [
{
"docstring": "labels, labels_info\nlabels: numpy.ndarray of size (image, row, col, 1). Instance segmentation of im. Each label segments a different\ncell.\n\nnumpy structured array. One element per cell.\nlabels_info['im']: Each element is the index of the image the cell belongs to.\nlabels... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | labels2contours | <not_specific> | def labels2contours(window_labels, offset_xy=None, scaling_factor_xy=None):
"""
Extract contours from labels.
Each label is assumed to be a polygon. The polygon border is extracted as a list of (x, y)-points using marching
cubes (http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure... |
Extract contours from labels.
Each label is assumed to be a polygon. The polygon border is extracted as a list of (x, y)-points using marching
cubes (http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.find_contours).
The contour points assume that pixel size is (1, 1).
:pa... | Extract contours from labels.
Each label is assumed to be a polygon. The polygon border is extracted as a list of (x, y)-points using marching
cubes .
The contour points assume that pixel size is (1, 1). | [
"Extract",
"contours",
"from",
"labels",
".",
"Each",
"label",
"is",
"assumed",
"to",
"be",
"a",
"polygon",
".",
"The",
"polygon",
"border",
"is",
"extracted",
"as",
"a",
"list",
"of",
"(",
"x",
"y",
")",
"-",
"points",
"using",
"marching",
"cubes",
".... | def labels2contours(window_labels, offset_xy=None, scaling_factor_xy=None):
if len(window_labels) == 0:
return []
if offset_xy is not None:
if window_labels.shape[0] != offset_xy.shape[0] or offset_xy.shape[1] != 2:
raise ValueError('offset must have shape (n, 2) if window_labels has... | [
"def",
"labels2contours",
"(",
"window_labels",
",",
"offset_xy",
"=",
"None",
",",
"scaling_factor_xy",
"=",
"None",
")",
":",
"if",
"len",
"(",
"window_labels",
")",
"==",
"0",
":",
"return",
"[",
"]",
"if",
"offset_xy",
"is",
"not",
"None",
":",
"if",... | Extract contours from labels. | [
"Extract",
"contours",
"from",
"labels",
"."
] | [
"\"\"\"\n Extract contours from labels.\n\n Each label is assumed to be a polygon. The polygon border is extracted as a list of (x, y)-points using marching\n cubes (http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.find_contours).\n\n The contour points assume that pixel size is... | [
{
"param": "window_labels",
"type": null
},
{
"param": "offset_xy",
"type": null
},
{
"param": "scaling_factor_xy",
"type": null
}
] | {
"returns": [
{
"docstring": "List of np.array (m_i, x, y). Each np.array contains the points of a contour.",
"docstring_tokens": [
"List",
"of",
"np",
".",
"array",
"(",
"m_i",
"x",
"y",
")",
".",
"Each",... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | colour_labels_with_receptive_field | <not_specific> | def colour_labels_with_receptive_field(labels, receptive_field):
"""
Take a segmentation where each object has a different label, and colour them with a distance constraint:
Let c(i) be the center of mass of label i that we have assigned colour k. If we draw a rectangle of size
receptive_field around c... |
Take a segmentation where each object has a different label, and colour them with a distance constraint:
Let c(i) be the center of mass of label i that we have assigned colour k. If we draw a rectangle of size
receptive_field around c(i), the only object with colour k within the rectangle is i.
:para... | Take a segmentation where each object has a different label, and colour them with a distance constraint:
Let c(i) be the center of mass of label i that we have assigned colour k. If we draw a rectangle of size
receptive_field around c(i), the only object with colour k within the rectangle is i. | [
"Take",
"a",
"segmentation",
"where",
"each",
"object",
"has",
"a",
"different",
"label",
"and",
"colour",
"them",
"with",
"a",
"distance",
"constraint",
":",
"Let",
"c",
"(",
"i",
")",
"be",
"the",
"center",
"of",
"mass",
"of",
"label",
"i",
"that",
"... | def colour_labels_with_receptive_field(labels, receptive_field):
if np.isscalar(receptive_field):
receptive_field = (receptive_field, receptive_field)
if not isinstance(receptive_field, tuple):
raise TypeError('receptive_field must be a scalar or a tuple')
no_colour = 0
background = 0
... | [
"def",
"colour_labels_with_receptive_field",
"(",
"labels",
",",
"receptive_field",
")",
":",
"if",
"np",
".",
"isscalar",
"(",
"receptive_field",
")",
":",
"receptive_field",
"=",
"(",
"receptive_field",
",",
"receptive_field",
")",
"if",
"not",
"isinstance",
"("... | Take a segmentation where each object has a different label, and colour them with a distance constraint:
Let c(i) be the center of mass of label i that we have assigned colour k. If we draw a rectangle of size
receptive_field around c(i), the only object with colour k within the rectangle is i. | [
"Take",
"a",
"segmentation",
"where",
"each",
"object",
"has",
"a",
"different",
"label",
"and",
"colour",
"them",
"with",
"a",
"distance",
"constraint",
":",
"Let",
"c",
"(",
"i",
")",
"be",
"the",
"center",
"of",
"mass",
"of",
"label",
"i",
"that",
"... | [
"\"\"\"\n Take a segmentation where each object has a different label, and colour them with a distance constraint:\n\n Let c(i) be the center of mass of label i that we have assigned colour k. If we draw a rectangle of size\n receptive_field around c(i), the only object with colour k within the rectangle i... | [
{
"param": "labels",
"type": null
},
{
"param": "receptive_field",
"type": null
}
] | {
"returns": [
{
"docstring": "colours, coloured_labels:\ncolours is a dictionary with pairs {label: colour}.\ncoloured_labels: np.ndarray of the same size as labels, with the labels replaced by colours.",
"docstring_tokens": [
"colours",
"coloured_labels",
":",
"colour... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | keras2skimage_transform | <not_specific> | def keras2skimage_transform(keras_transform, input_shape, output_shape='same'):
"""
Convert an affine transform from keras to skimage format. This can then be used to apply a
transformation to an image (transform_im) or point set (transform_coords).
Note: Currently, the implemented parameters are:
... |
Convert an affine transform from keras to skimage format. This can then be used to apply a
transformation to an image (transform_im) or point set (transform_coords).
Note: Currently, the implemented parameters are:
* scaling ('zx', 'zy')
* rotation ('theta')
* translation ('tx', 'ty')
... | Convert an affine transform from keras to skimage format. This can then be used to apply a
transformation to an image (transform_im) or point set (transform_coords).
Note 2: Rotations in keras are referred to the centre of the image.
Rotations in skimage are referred to the origin of coordinates (x, y)=(0, 0). | [
"Convert",
"an",
"affine",
"transform",
"from",
"keras",
"to",
"skimage",
"format",
".",
"This",
"can",
"then",
"be",
"used",
"to",
"apply",
"a",
"transformation",
"to",
"an",
"image",
"(",
"transform_im",
")",
"or",
"point",
"set",
"(",
"transform_coords",
... | def keras2skimage_transform(keras_transform, input_shape, output_shape='same'):
im_centre = np.array([(input_shape[1] - 1) / 2, (input_shape[0] - 1) / 2])
transform_skimage_center = EuclideanTransform(translation=-im_centre)
transform_skimage_affine = AffineTransform(matrix=None, scale=(keras_transform['z... | [
"def",
"keras2skimage_transform",
"(",
"keras_transform",
",",
"input_shape",
",",
"output_shape",
"=",
"'same'",
")",
":",
"im_centre",
"=",
"np",
".",
"array",
"(",
"[",
"(",
"input_shape",
"[",
"1",
"]",
"-",
"1",
")",
"/",
"2",
",",
"(",
"input_shape... | Convert an affine transform from keras to skimage format. | [
"Convert",
"an",
"affine",
"transform",
"from",
"keras",
"to",
"skimage",
"format",
"."
] | [
"\"\"\"\n Convert an affine transform from keras to skimage format. This can then be used to apply a\n transformation to an image (transform_im) or point set (transform_coords).\n\n Note: Currently, the implemented parameters are:\n * scaling ('zx', 'zy')\n * rotation ('theta')\n * translati... | [
{
"param": "keras_transform",
"type": null
},
{
"param": "input_shape",
"type": null
},
{
"param": "output_shape",
"type": null
}
] | {
"returns": [
{
"docstring": "skimage.transform._geometric.ProjectiveTransform with same affine\ntransform.\noutput_shape: (height, width)",
"docstring_tokens": [
"skimage",
".",
"transform",
".",
"_geometric",
".",
"ProjectiveTransform",
... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | transform_coords | <not_specific> | def transform_coords(coords, transform_skimage):
"""
Apply a scikit.image transformation to a set of point coordinates.
The transformations applied to point coordinates in this function are consistent to transformations applied to
an image with transform_im().
:param coords: (P, 2) np.array, each ... |
Apply a scikit.image transformation to a set of point coordinates.
The transformations applied to point coordinates in this function are consistent to transformations applied to
an image with transform_im().
:param coords: (P, 2) np.array, each row has the (x, y) coordinates of a point.
... | Apply a scikit.image transformation to a set of point coordinates.
The transformations applied to point coordinates in this function are consistent to transformations applied to
an image with transform_im(). | [
"Apply",
"a",
"scikit",
".",
"image",
"transformation",
"to",
"a",
"set",
"of",
"point",
"coordinates",
".",
"The",
"transformations",
"applied",
"to",
"point",
"coordinates",
"in",
"this",
"function",
"are",
"consistent",
"to",
"transformations",
"applied",
"to... | def transform_coords(coords, transform_skimage):
is_list = type(coords) == list
if is_list:
coords = np.vstack(coords)
coords_out = matrix_transform(coords, transform_skimage.params)
if is_list:
coords_out = [tuple(x) for x in coords_out]
return coords_out | [
"def",
"transform_coords",
"(",
"coords",
",",
"transform_skimage",
")",
":",
"is_list",
"=",
"type",
"(",
"coords",
")",
"==",
"list",
"if",
"is_list",
":",
"coords",
"=",
"np",
".",
"vstack",
"(",
"coords",
")",
"coords_out",
"=",
"matrix_transform",
"("... | Apply a scikit.image transformation to a set of point coordinates. | [
"Apply",
"a",
"scikit",
".",
"image",
"transformation",
"to",
"a",
"set",
"of",
"point",
"coordinates",
"."
] | [
"\"\"\"\n Apply a scikit.image transformation to a set of point coordinates.\n\n The transformations applied to point coordinates in this function are consistent to transformations applied to\n an image with transform_im().\n\n :param coords: (P, 2) np.array, each row has the (x, y) coordinates of a poi... | [
{
"param": "coords",
"type": null
},
{
"param": "transform_skimage",
"type": null
}
] | {
"returns": [
{
"docstring": "(P, 2) np.array or list of (x, y) coordinates of the transformed points.",
"docstring_tokens": [
"(",
"P",
"2",
")",
"np",
".",
"array",
"or",
"list",
"of",
"(",
"x",
... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | transform_im | <not_specific> | def transform_im(im, transform_skimage, output_shape=None, order=1):
"""
Apply a scikit.image transformation to an image.
The motivation for this function is that keras apply_transform() doesn't enable nearest neighbour
interpolation. Thus, when applied to label or segmentation images, its bi-linear in... |
Apply a scikit.image transformation to an image.
The motivation for this function is that keras apply_transform() doesn't enable nearest neighbour
interpolation. Thus, when applied to label or segmentation images, its bi-linear interpolation
creates bogus labels.
:param im: (row, col, channel) or... | Apply a scikit.image transformation to an image.
The motivation for this function is that keras apply_transform() doesn't enable nearest neighbour
interpolation. Thus, when applied to label or segmentation images, its bi-linear interpolation
creates bogus labels. | [
"Apply",
"a",
"scikit",
".",
"image",
"transformation",
"to",
"an",
"image",
".",
"The",
"motivation",
"for",
"this",
"function",
"is",
"that",
"keras",
"apply_transform",
"()",
"doesn",
"'",
"t",
"enable",
"nearest",
"neighbour",
"interpolation",
".",
"Thus",... | def transform_im(im, transform_skimage, output_shape=None, order=1):
im_out = warp(im, transform_skimage.inverse, order=order, preserve_range=True, output_shape=output_shape)
im_out = im_out.astype(im.dtype)
return im_out | [
"def",
"transform_im",
"(",
"im",
",",
"transform_skimage",
",",
"output_shape",
"=",
"None",
",",
"order",
"=",
"1",
")",
":",
"im_out",
"=",
"warp",
"(",
"im",
",",
"transform_skimage",
".",
"inverse",
",",
"order",
"=",
"order",
",",
"preserve_range",
... | Apply a scikit.image transformation to an image. | [
"Apply",
"a",
"scikit",
".",
"image",
"transformation",
"to",
"an",
"image",
"."
] | [
"\"\"\"\n Apply a scikit.image transformation to an image.\n\n The motivation for this function is that keras apply_transform() doesn't enable nearest neighbour\n interpolation. Thus, when applied to label or segmentation images, its bi-linear interpolation\n creates bogus labels.\n\n :param im: (row... | [
{
"param": "im",
"type": null
},
{
"param": "transform_skimage",
"type": null
},
{
"param": "output_shape",
"type": null
},
{
"param": "order",
"type": null
}
] | {
"returns": [
{
"docstring": "np.array with the same shape and dtype as im.",
"docstring_tokens": [
"np",
".",
"array",
"with",
"the",
"same",
"shape",
"and",
"dtype",
"as",
"im",
"."
],
"type"... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | rescale_intensity | <not_specific> | def rescale_intensity(im, ignore_value=None):
"""
Stretch the pixel intensities of a batch of images to cover the whole dynamic range of the dtype,
excluding the black background pixels.
The scaling is performed on the H-channel of the HSV transform of the RGB image.
:param im: np.ndarray (batch, ... |
Stretch the pixel intensities of a batch of images to cover the whole dynamic range of the dtype,
excluding the black background pixels.
The scaling is performed on the H-channel of the HSV transform of the RGB image.
:param im: np.ndarray (batch, rows, cols, channel) RGB images.
:param ignore_va... | Stretch the pixel intensities of a batch of images to cover the whole dynamic range of the dtype,
excluding the black background pixels.
The scaling is performed on the H-channel of the HSV transform of the RGB image. | [
"Stretch",
"the",
"pixel",
"intensities",
"of",
"a",
"batch",
"of",
"images",
"to",
"cover",
"the",
"whole",
"dynamic",
"range",
"of",
"the",
"dtype",
"excluding",
"the",
"black",
"background",
"pixels",
".",
"The",
"scaling",
"is",
"performed",
"on",
"the",... | def rescale_intensity(im, ignore_value=None):
V = 2
for i in range(im.shape[0]):
if DEBUG:
plt.clf()
plt.imshow(im[i, :, :, :])
im_hsv = rgb2hsv(im[i, :, :, :])
im_v = im_hsv[:, :, V]
if ignore_value is None:
im_v = minmax_scale(im_v, feature_r... | [
"def",
"rescale_intensity",
"(",
"im",
",",
"ignore_value",
"=",
"None",
")",
":",
"V",
"=",
"2",
"for",
"i",
"in",
"range",
"(",
"im",
".",
"shape",
"[",
"0",
"]",
")",
":",
"if",
"DEBUG",
":",
"plt",
".",
"clf",
"(",
")",
"plt",
".",
"imshow"... | Stretch the pixel intensities of a batch of images to cover the whole dynamic range of the dtype,
excluding the black background pixels. | [
"Stretch",
"the",
"pixel",
"intensities",
"of",
"a",
"batch",
"of",
"images",
"to",
"cover",
"the",
"whole",
"dynamic",
"range",
"of",
"the",
"dtype",
"excluding",
"the",
"black",
"background",
"pixels",
"."
] | [
"\"\"\"\n Stretch the pixel intensities of a batch of images to cover the whole dynamic range of the dtype,\n excluding the black background pixels.\n\n The scaling is performed on the H-channel of the HSV transform of the RGB image.\n\n :param im: np.ndarray (batch, rows, cols, channel) RGB images.\n ... | [
{
"param": "im",
"type": null
},
{
"param": "ignore_value",
"type": null
}
] | {
"returns": [
{
"docstring": "Array with the same size as im.",
"docstring_tokens": [
"Array",
"with",
"the",
"same",
"size",
"as",
"im",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": ... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | ecdf_confidence | <not_specific> | def ecdf_confidence(data, num_quantiles=101, equispace='quantiles', confidence=0.95, estimator_name='beta'):
"""
Compute empirical ECDF with confidence intervals/bands.
The ECDF is a function that maps quantiles = ECDF(data). The user can choose whether the output is
equispaced on the data axis or the ... |
Compute empirical ECDF with confidence intervals/bands.
The ECDF is a function that maps quantiles = ECDF(data). The user can choose whether the output is
equispaced on the data axis or the quantiles axis.
Derived from plot_CDF_confidence (https://github.com/wfbradley/CDF-confidence/blob/master/CDF_c... | Compute empirical ECDF with confidence intervals/bands.
The ECDF is a function that maps quantiles = ECDF(data). The user can choose whether the output is
equispaced on the data axis or the quantiles axis.
Derived from plot_CDF_confidence . | [
"Compute",
"empirical",
"ECDF",
"with",
"confidence",
"intervals",
"/",
"bands",
".",
"The",
"ECDF",
"is",
"a",
"function",
"that",
"maps",
"quantiles",
"=",
"ECDF",
"(",
"data",
")",
".",
"The",
"user",
"can",
"choose",
"whether",
"the",
"output",
"is",
... | def ecdf_confidence(data, num_quantiles=101, equispace='quantiles', confidence=0.95, estimator_name='beta'):
if len(np.shape(data)) != 1:
raise NameError('Data must be 1 dimensional')
if num_quantiles > len(data) + 1:
num_quantiles = len(data) + 1
if len(data) < 2:
raise NameError('N... | [
"def",
"ecdf_confidence",
"(",
"data",
",",
"num_quantiles",
"=",
"101",
",",
"equispace",
"=",
"'quantiles'",
",",
"confidence",
"=",
"0.95",
",",
"estimator_name",
"=",
"'beta'",
")",
":",
"if",
"len",
"(",
"np",
".",
"shape",
"(",
"data",
")",
")",
... | Compute empirical ECDF with confidence intervals/bands. | [
"Compute",
"empirical",
"ECDF",
"with",
"confidence",
"intervals",
"/",
"bands",
"."
] | [
"\"\"\"\n Compute empirical ECDF with confidence intervals/bands.\n\n The ECDF is a function that maps quantiles = ECDF(data). The user can choose whether the output is\n equispaced on the data axis or the quantiles axis.\n\n Derived from plot_CDF_confidence (https://github.com/wfbradley/CDF-confidence/... | [
{
"param": "data",
"type": null
},
{
"param": "num_quantiles",
"type": null
},
{
"param": "equispace",
"type": null
},
{
"param": "confidence",
"type": null
},
{
"param": "estimator_name",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": "numpy.array with the 1D data to compute the ECDF for.",
"docstring_tokens": [
... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | compare_ecdfs | <not_specific> | def compare_ecdfs(x, y, alpha=0.05, num_quantiles=101, num_perms=1000, rng_seed=0,
resampling_method='bootstrap', multitest_method=None):
"""
Compute p-values for the difference between each percentile point of the empirical cumulative distribution
functions (ECDFs) of two samples x, y.
... |
Compute p-values for the difference between each percentile point of the empirical cumulative distribution
functions (ECDFs) of two samples x, y.
This function allows multiple test adjustment of p-values using statsmodels.stats.multitest.multipletests.
This function is basically an implementation of ... | Compute p-values for the difference between each percentile point of the empirical cumulative distribution
functions (ECDFs) of two samples x, y.
This function allows multiple test adjustment of p-values using statsmodels.stats.multitest.multipletests.
For example, if the median(x)=10, median(y)=7, this function co... | [
"Compute",
"p",
"-",
"values",
"for",
"the",
"difference",
"between",
"each",
"percentile",
"point",
"of",
"the",
"empirical",
"cumulative",
"distribution",
"functions",
"(",
"ECDFs",
")",
"of",
"two",
"samples",
"x",
"y",
".",
"This",
"function",
"allows",
... | def compare_ecdfs(x, y, alpha=0.05, num_quantiles=101, num_perms=1000, rng_seed=0,
resampling_method='bootstrap', multitest_method=None):
def compute_test_statistics(x, y, quantiles):
x_ecdf_func = ECDF(x)
y_ecdf_func = ECDF(y)
xu = np.unique(x)
yu = np.unique(y)
... | [
"def",
"compare_ecdfs",
"(",
"x",
",",
"y",
",",
"alpha",
"=",
"0.05",
",",
"num_quantiles",
"=",
"101",
",",
"num_perms",
"=",
"1000",
",",
"rng_seed",
"=",
"0",
",",
"resampling_method",
"=",
"'bootstrap'",
",",
"multitest_method",
"=",
"None",
")",
":... | Compute p-values for the difference between each percentile point of the empirical cumulative distribution
functions (ECDFs) of two samples x, y. | [
"Compute",
"p",
"-",
"values",
"for",
"the",
"difference",
"between",
"each",
"percentile",
"point",
"of",
"the",
"empirical",
"cumulative",
"distribution",
"functions",
"(",
"ECDFs",
")",
"of",
"two",
"samples",
"x",
"y",
"."
] | [
"\"\"\"\n Compute p-values for the difference between each percentile point of the empirical cumulative distribution\n functions (ECDFs) of two samples x, y.\n\n This function allows multiple test adjustment of p-values using statsmodels.stats.multitest.multipletests.\n\n This function is basically an i... | [
{
"param": "x",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "alpha",
"type": null
},
{
"param": "num_quantiles",
"type": null
},
{
"param": "num_perms",
"type": null
},
{
"param": "rng_seed",
"type": null
},
{
"param": "resam... | {
"returns": [
{
"docstring": "numpy.ndarray vector with quantile values in [0.0, 1.0].\npval: corresponding p-values for each quantile, whether adjusted or not.\nreject_h0: boolean vector, whether the null-hypothesis is rejected for each percentile, i.e. there's a significant\neffect, pval < alpha_c (where... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | bspline_resample | <not_specific> | def bspline_resample(xy, factor=1.0, min_n=0, k=1, is_closed=True):
"""
Resample a 2D curve using B-spline interpolation.
Note that repeated consecutive points will be removed, because otherwise splprep() raises an exception.
:param xy: (N, 2)-np.ndarray with (x,y)=coordinates
:param factor: (def ... |
Resample a 2D curve using B-spline interpolation.
Note that repeated consecutive points will be removed, because otherwise splprep() raises an exception.
:param xy: (N, 2)-np.ndarray with (x,y)=coordinates
:param factor: (def 1.0) The number of output points is computed as round(N*factor).
:param... | Resample a 2D curve using B-spline interpolation.
Note that repeated consecutive points will be removed, because otherwise splprep() raises an exception. | [
"Resample",
"a",
"2D",
"curve",
"using",
"B",
"-",
"spline",
"interpolation",
".",
"Note",
"that",
"repeated",
"consecutive",
"points",
"will",
"be",
"removed",
"because",
"otherwise",
"splprep",
"()",
"raises",
"an",
"exception",
"."
] | def bspline_resample(xy, factor=1.0, min_n=0, k=1, is_closed=True):
if type(xy) != np.ndarray or xy.shape[1] != 2:
raise ValueError('xy must be a 2-column np.ndarray')
idx = np.logical_or(np.diff(xy[:, 0]) != 0, np.diff(xy[:, 1]) != 0)
if is_closed:
idx = np.concatenate(([np.any(xy[0, :] - x... | [
"def",
"bspline_resample",
"(",
"xy",
",",
"factor",
"=",
"1.0",
",",
"min_n",
"=",
"0",
",",
"k",
"=",
"1",
",",
"is_closed",
"=",
"True",
")",
":",
"if",
"type",
"(",
"xy",
")",
"!=",
"np",
".",
"ndarray",
"or",
"xy",
".",
"shape",
"[",
"1",
... | Resample a 2D curve using B-spline interpolation. | [
"Resample",
"a",
"2D",
"curve",
"using",
"B",
"-",
"spline",
"interpolation",
"."
] | [
"\"\"\"\n Resample a 2D curve using B-spline interpolation.\n\n Note that repeated consecutive points will be removed, because otherwise splprep() raises an exception.\n\n :param xy: (N, 2)-np.ndarray with (x,y)=coordinates\n :param factor: (def 1.0) The number of output points is computed as round(N*fa... | [
{
"param": "xy",
"type": null
},
{
"param": "factor",
"type": null
},
{
"param": "min_n",
"type": null
},
{
"param": "k",
"type": null
},
{
"param": "is_closed",
"type": null
}
] | {
"returns": [
{
"docstring": "(M, 2)-np.ndarray with coordinates of the resampled curve.",
"docstring_tokens": [
"(",
"M",
"2",
")",
"-",
"np",
".",
"ndarray",
"with",
"coordinates",
"of",
"the",
"... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | plot_confusion_matrix | <not_specific> | def plot_confusion_matrix(y_true, y_pred,
normalize=False,
title=None,
xlabel=None,
ylabel=None,
cmap=plt.cm.Blues,
colorbar=True):
"""
This function prints... |
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
Copied from https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py
on 27 Mar 2019. Small modi... | This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
| [
"This",
"function",
"prints",
"and",
"plots",
"the",
"confusion",
"matrix",
".",
"Normalization",
"can",
"be",
"applied",
"by",
"setting",
"`",
"normalize",
"=",
"True",
"`",
"."
] | def plot_confusion_matrix(y_true, y_pred,
normalize=False,
title=None,
xlabel=None,
ylabel=None,
cmap=plt.cm.Blues,
colorbar=True):
if not title:
if nor... | [
"def",
"plot_confusion_matrix",
"(",
"y_true",
",",
"y_pred",
",",
"normalize",
"=",
"False",
",",
"title",
"=",
"None",
",",
"xlabel",
"=",
"None",
",",
"ylabel",
"=",
"None",
",",
"cmap",
"=",
"plt",
".",
"cm",
".",
"Blues",
",",
"colorbar",
"=",
"... | This function prints and plots the confusion matrix. | [
"This",
"function",
"prints",
"and",
"plots",
"the",
"confusion",
"matrix",
"."
] | [
"\"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n\n Copied from https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py\n on 27 Mar ... | [
{
"param": "y_true",
"type": null
},
{
"param": "y_pred",
"type": null
},
{
"param": "normalize",
"type": null
},
{
"param": "title",
"type": null
},
{
"param": "xlabel",
"type": null
},
{
"param": "ylabel",
"type": null
},
{
"param": "cmap... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "y_true",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "y_pred",
"type": null,
"docstring": null,
"docstring_tokens... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | boxplot_poi | <not_specific> | def boxplot_poi(bp):
"""
Extract points of interest (quartiles and whiskers) from box and whisker plot.
:param bp: plt.boxplot object. This is returned by matplotlib.pyplot.boxplot(). It is assumed that the boxes are
plotted vertically.
:return:
* poi: (n, 5) np.array. Each row contains the 5 p... |
Extract points of interest (quartiles and whiskers) from box and whisker plot.
:param bp: plt.boxplot object. This is returned by matplotlib.pyplot.boxplot(). It is assumed that the boxes are
plotted vertically.
:return:
* poi: (n, 5) np.array. Each row contains the 5 points of interest in one box... | Extract points of interest (quartiles and whiskers) from box and whisker plot. | [
"Extract",
"points",
"of",
"interest",
"(",
"quartiles",
"and",
"whiskers",
")",
"from",
"box",
"and",
"whisker",
"plot",
"."
] | def boxplot_poi(bp):
n = len(bp['boxes'])
poi = []
for idx in range(n):
bp_w0 = bp['whiskers'][2*idx].get_data()[1][1]
bp_q1 = bp['boxes'][idx].get_data()[1][1]
bp_q2 = bp['medians'][idx].get_data()[1][0]
bp_q3 = bp['boxes'][idx].get_data()[1][5]
bp_wend = bp['whisker... | [
"def",
"boxplot_poi",
"(",
"bp",
")",
":",
"n",
"=",
"len",
"(",
"bp",
"[",
"'boxes'",
"]",
")",
"poi",
"=",
"[",
"]",
"for",
"idx",
"in",
"range",
"(",
"n",
")",
":",
"bp_w0",
"=",
"bp",
"[",
"'whiskers'",
"]",
"[",
"2",
"*",
"idx",
"]",
"... | Extract points of interest (quartiles and whiskers) from box and whisker plot. | [
"Extract",
"points",
"of",
"interest",
"(",
"quartiles",
"and",
"whiskers",
")",
"from",
"box",
"and",
"whisker",
"plot",
"."
] | [
"\"\"\"\n Extract points of interest (quartiles and whiskers) from box and whisker plot.\n\n :param bp: plt.boxplot object. This is returned by matplotlib.pyplot.boxplot(). It is assumed that the boxes are\n plotted vertically.\n :return:\n * poi: (n, 5) np.array. Each row contains the 5 points of in... | [
{
"param": "bp",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "bp",
"type": null,
"docstring": "plt.boxplot object. This is returned by matplotlib.pyplot.boxplot(). It is assumed that ... |
a8591a7000948cf4e9457dbb8e3c657f85037779 | rcasero/cytometer | cytometer/utils.py | [
"Apache-2.0"
] | Python | sphericity | <not_specific> | def sphericity(poly):
"""
Sphericity measure of a polygon, or degree to which an object approximates a sphere.
Sphericity = R_inscribed / R_circumscribing
where R_incribed, R_circumscribing are the minimum and maximum distances, respectively, from polygon vertices to the
polygon's centroid... |
Sphericity measure of a polygon, or degree to which an object approximates a sphere.
Sphericity = R_inscribed / R_circumscribing
where R_incribed, R_circumscribing are the minimum and maximum distances, respectively, from polygon vertices to the
polygon's centroid. Sphericity \in [0, 1], and ... | Sphericity measure of a polygon, or degree to which an object approximates a sphere.
Note that the centroid could be outside a polygon, and the sphericity measure wouldn't make much sense, but we are
not checking for those cases. | [
"Sphericity",
"measure",
"of",
"a",
"polygon",
"or",
"degree",
"to",
"which",
"an",
"object",
"approximates",
"a",
"sphere",
".",
"Note",
"that",
"the",
"centroid",
"could",
"be",
"outside",
"a",
"polygon",
"and",
"the",
"sphericity",
"measure",
"wouldn",
"'... | def sphericity(poly):
if type(poly) != shapely.geometry.polygon.Polygon:
raise TypeError('poly must be a shapely.geometry.polygon.Polygon')
d = np.array([shapely.geometry.Point(p).distance(poly.centroid) for p in list(poly.exterior.coords[:-1])])
return d.min() / d.max() | [
"def",
"sphericity",
"(",
"poly",
")",
":",
"if",
"type",
"(",
"poly",
")",
"!=",
"shapely",
".",
"geometry",
".",
"polygon",
".",
"Polygon",
":",
"raise",
"TypeError",
"(",
"'poly must be a shapely.geometry.polygon.Polygon'",
")",
"d",
"=",
"np",
".",
"arra... | Sphericity measure of a polygon, or degree to which an object approximates a sphere. | [
"Sphericity",
"measure",
"of",
"a",
"polygon",
"or",
"degree",
"to",
"which",
"an",
"object",
"approximates",
"a",
"sphere",
"."
] | [
"\"\"\"\n Sphericity measure of a polygon, or degree to which an object approximates a sphere.\n\n Sphericity = R_inscribed / R_circumscribing\n\n where R_incribed, R_circumscribing are the minimum and maximum distances, respectively, from polygon vertices to the\n polygon's centroid. Sphericity... | [
{
"param": "poly",
"type": null
}
] | {
"returns": [
{
"docstring": "float scalar with the sphericity measure for the polygon.",
"docstring_tokens": [
"float",
"scalar",
"with",
"the",
"sphericity",
"measure",
"for",
"the",
"polygon",
"."
],
"type"... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | following_schedule | <not_specific> | def following_schedule(self, dttm):
"""
Calculates the following schedule for this dag in UTC.
:param dttm: utc datetime
:return: utc datetime
"""
warnings.warn(
"`DAG.following_schedule()` is deprecated. Use `DAG.next_dagrun_info(restricted=False)` instead."... |
Calculates the following schedule for this dag in UTC.
:param dttm: utc datetime
:return: utc datetime
| Calculates the following schedule for this dag in UTC. | [
"Calculates",
"the",
"following",
"schedule",
"for",
"this",
"dag",
"in",
"UTC",
"."
] | def following_schedule(self, dttm):
warnings.warn(
"`DAG.following_schedule()` is deprecated. Use `DAG.next_dagrun_info(restricted=False)` instead.",
category=DeprecationWarning,
stacklevel=2,
)
data_interval = self.infer_automated_data_interval(timezone.coerc... | [
"def",
"following_schedule",
"(",
"self",
",",
"dttm",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`DAG.following_schedule()` is deprecated. Use `DAG.next_dagrun_info(restricted=False)` instead.\"",
",",
"category",
"=",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
","... | Calculates the following schedule for this dag in UTC. | [
"Calculates",
"the",
"following",
"schedule",
"for",
"this",
"dag",
"in",
"UTC",
"."
] | [
"\"\"\"\n Calculates the following schedule for this dag in UTC.\n\n :param dttm: utc datetime\n :return: utc datetime\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "dttm",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | infer_automated_data_interval | DataInterval | def infer_automated_data_interval(self, logical_date: datetime) -> DataInterval:
"""Infer a data interval for a run against this DAG.
This method is used to bridge runs created prior to AIP-39
implementation, which do not have an explicit data interval. Therefore,
this method only consi... | Infer a data interval for a run against this DAG.
This method is used to bridge runs created prior to AIP-39
implementation, which do not have an explicit data interval. Therefore,
this method only considers ``schedule_interval`` values valid prior to
Airflow 2.2.
DO NOT use th... | Infer a data interval for a run against this DAG.
This method is used to bridge runs created prior to AIP-39
implementation, which do not have an explicit data interval. Therefore,
this method only considers ``schedule_interval`` values valid prior to
Airflow 2.2.
DO NOT use this method is there is a known data interv... | [
"Infer",
"a",
"data",
"interval",
"for",
"a",
"run",
"against",
"this",
"DAG",
".",
"This",
"method",
"is",
"used",
"to",
"bridge",
"runs",
"created",
"prior",
"to",
"AIP",
"-",
"39",
"implementation",
"which",
"do",
"not",
"have",
"an",
"explicit",
"dat... | def infer_automated_data_interval(self, logical_date: datetime) -> DataInterval:
timetable_type = type(self.timetable)
if issubclass(timetable_type, (NullTimetable, OnceTimetable)):
return DataInterval.exact(timezone.coerce_datetime(logical_date))
start = timezone.coerce_datetime(log... | [
"def",
"infer_automated_data_interval",
"(",
"self",
",",
"logical_date",
":",
"datetime",
")",
"->",
"DataInterval",
":",
"timetable_type",
"=",
"type",
"(",
"self",
".",
"timetable",
")",
"if",
"issubclass",
"(",
"timetable_type",
",",
"(",
"NullTimetable",
",... | Infer a data interval for a run against this DAG. | [
"Infer",
"a",
"data",
"interval",
"for",
"a",
"run",
"against",
"this",
"DAG",
"."
] | [
"\"\"\"Infer a data interval for a run against this DAG.\n\n This method is used to bridge runs created prior to AIP-39\n implementation, which do not have an explicit data interval. Therefore,\n this method only considers ``schedule_interval`` values valid prior to\n Airflow 2.2.\n\n ... | [
{
"param": "self",
"type": null
},
{
"param": "logical_date",
"type": "datetime"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "logical_date",
"type": "datetime",
"docstring": null,
"docstr... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | next_dagrun_info | Optional[DagRunInfo] | def next_dagrun_info(
self,
last_automated_dagrun: Union[None, datetime, DataInterval],
*,
restricted: bool = True,
) -> Optional[DagRunInfo]:
"""Get information about the next DagRun of this dag after ``date_last_automated_dagrun``.
This calculates what time interva... | Get information about the next DagRun of this dag after ``date_last_automated_dagrun``.
This calculates what time interval the next DagRun should operate on
(its execution date), and when it can be scheduled, , according to the
dag's timetable, start_date, end_date, etc. This doesn't check max
... | Get information about the next DagRun of this dag after ``date_last_automated_dagrun``.
This calculates what time interval the next DagRun should operate on
(its execution date), and when it can be scheduled, , according to the
dag's timetable, start_date, end_date, etc. This doesn't check max
active run or any other "... | [
"Get",
"information",
"about",
"the",
"next",
"DagRun",
"of",
"this",
"dag",
"after",
"`",
"`",
"date_last_automated_dagrun",
"`",
"`",
".",
"This",
"calculates",
"what",
"time",
"interval",
"the",
"next",
"DagRun",
"should",
"operate",
"on",
"(",
"its",
"ex... | def next_dagrun_info(
self,
last_automated_dagrun: Union[None, datetime, DataInterval],
*,
restricted: bool = True,
) -> Optional[DagRunInfo]:
if self.is_subdag:
return None
if isinstance(last_automated_dagrun, datetime):
warnings.warn(
... | [
"def",
"next_dagrun_info",
"(",
"self",
",",
"last_automated_dagrun",
":",
"Union",
"[",
"None",
",",
"datetime",
",",
"DataInterval",
"]",
",",
"*",
",",
"restricted",
":",
"bool",
"=",
"True",
",",
")",
"->",
"Optional",
"[",
"DagRunInfo",
"]",
":",
"i... | Get information about the next DagRun of this dag after ``date_last_automated_dagrun``. | [
"Get",
"information",
"about",
"the",
"next",
"DagRun",
"of",
"this",
"dag",
"after",
"`",
"`",
"date_last_automated_dagrun",
"`",
"`",
"."
] | [
"\"\"\"Get information about the next DagRun of this dag after ``date_last_automated_dagrun``.\n\n This calculates what time interval the next DagRun should operate on\n (its execution date), and when it can be scheduled, , according to the\n dag's timetable, start_date, end_date, etc. This doe... | [
{
"param": "self",
"type": null
},
{
"param": "last_automated_dagrun",
"type": "Union[None, datetime, DataInterval]"
},
{
"param": "restricted",
"type": "bool"
}
] | {
"returns": [
{
"docstring": "DagRunInfo of the next dagrun, or None if a dagrun is not\ngoing to be scheduled.",
"docstring_tokens": [
"DagRunInfo",
"of",
"the",
"next",
"dagrun",
"or",
"None",
"if",
"a",
"dagrun",
... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | param | DagParam | def param(self, name: str, default=None) -> DagParam:
"""
Return a DagParam object for current dag.
:param name: dag parameter name.
:param default: fallback value for dag parameter.
:return: DagParam instance for specified name and current dag.
"""
return DagPar... |
Return a DagParam object for current dag.
:param name: dag parameter name.
:param default: fallback value for dag parameter.
:return: DagParam instance for specified name and current dag.
| Return a DagParam object for current dag. | [
"Return",
"a",
"DagParam",
"object",
"for",
"current",
"dag",
"."
] | def param(self, name: str, default=None) -> DagParam:
return DagParam(current_dag=self, name=name, default=default) | [
"def",
"param",
"(",
"self",
",",
"name",
":",
"str",
",",
"default",
"=",
"None",
")",
"->",
"DagParam",
":",
"return",
"DagParam",
"(",
"current_dag",
"=",
"self",
",",
"name",
"=",
"name",
",",
"default",
"=",
"default",
")"
] | Return a DagParam object for current dag. | [
"Return",
"a",
"DagParam",
"object",
"for",
"current",
"dag",
"."
] | [
"\"\"\"\n Return a DagParam object for current dag.\n\n :param name: dag parameter name.\n :param default: fallback value for dag parameter.\n :return: DagParam instance for specified name and current dag.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "name",
"type": "str"
},
{
"param": "default",
"type": null
}
] | {
"returns": [
{
"docstring": "DagParam instance for specified name and current dag.",
"docstring_tokens": [
"DagParam",
"instance",
"for",
"specified",
"name",
"and",
"current",
"dag",
"."
],
"type": null
}
],
... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | relative_fileloc | pathlib.Path | def relative_fileloc(self) -> pathlib.Path:
"""File location of the importable dag 'file' relative to the configured DAGs folder."""
path = pathlib.Path(self.fileloc)
try:
return path.relative_to(settings.DAGS_FOLDER)
except ValueError:
# Not relative to DAGS_FOLD... | File location of the importable dag 'file' relative to the configured DAGs folder. | File location of the importable dag 'file' relative to the configured DAGs folder. | [
"File",
"location",
"of",
"the",
"importable",
"dag",
"'",
"file",
"'",
"relative",
"to",
"the",
"configured",
"DAGs",
"folder",
"."
] | def relative_fileloc(self) -> pathlib.Path:
path = pathlib.Path(self.fileloc)
try:
return path.relative_to(settings.DAGS_FOLDER)
except ValueError:
return path | [
"def",
"relative_fileloc",
"(",
"self",
")",
"->",
"pathlib",
".",
"Path",
":",
"path",
"=",
"pathlib",
".",
"Path",
"(",
"self",
".",
"fileloc",
")",
"try",
":",
"return",
"path",
".",
"relative_to",
"(",
"settings",
".",
"DAGS_FOLDER",
")",
"except",
... | File location of the importable dag 'file' relative to the configured DAGs folder. | [
"File",
"location",
"of",
"the",
"importable",
"dag",
"'",
"file",
"'",
"relative",
"to",
"the",
"configured",
"DAGs",
"folder",
"."
] | [
"\"\"\"File location of the importable dag 'file' relative to the configured DAGs folder.\"\"\"",
"# Not relative to DAGS_FOLDER."
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | owner | str | def owner(self) -> str:
"""
Return list of all owners found in DAG tasks.
:return: Comma separated list of owners in DAG tasks
:rtype: str
"""
return ", ".join({t.owner for t in self.tasks}) |
Return list of all owners found in DAG tasks.
:return: Comma separated list of owners in DAG tasks
:rtype: str
| Return list of all owners found in DAG tasks. | [
"Return",
"list",
"of",
"all",
"owners",
"found",
"in",
"DAG",
"tasks",
"."
] | def owner(self) -> str:
return ", ".join({t.owner for t in self.tasks}) | [
"def",
"owner",
"(",
"self",
")",
"->",
"str",
":",
"return",
"\", \"",
".",
"join",
"(",
"{",
"t",
".",
"owner",
"for",
"t",
"in",
"self",
".",
"tasks",
"}",
")"
] | Return list of all owners found in DAG tasks. | [
"Return",
"list",
"of",
"all",
"owners",
"found",
"in",
"DAG",
"tasks",
"."
] | [
"\"\"\"\n Return list of all owners found in DAG tasks.\n\n :return: Comma separated list of owners in DAG tasks\n :rtype: str\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": "Comma separated list of owners in DAG tasks",
"docstring_tokens": [
"Comma",
"separated",
"list",
"of",
"owners",
"in",
"DAG",
"tasks"
],
"type": "str"
}
],
"raises": [],
"params": [
... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | handle_callback | null | def handle_callback(self, dagrun, success=True, reason=None, session=None):
"""
Triggers the appropriate callback depending on the value of success, namely the
on_failure_callback or on_success_callback. This method gets the context of a
single TaskInstance part of this DagRun and passes... |
Triggers the appropriate callback depending on the value of success, namely the
on_failure_callback or on_success_callback. This method gets the context of a
single TaskInstance part of this DagRun and passes that to the callable along
with a 'reason', primarily to differentiate DagRun ... | Triggers the appropriate callback depending on the value of success, namely the
on_failure_callback or on_success_callback. This method gets the context of a
single TaskInstance part of this DagRun and passes that to the callable along
with a 'reason', primarily to differentiate DagRun failures.
| [
"Triggers",
"the",
"appropriate",
"callback",
"depending",
"on",
"the",
"value",
"of",
"success",
"namely",
"the",
"on_failure_callback",
"or",
"on_success_callback",
".",
"This",
"method",
"gets",
"the",
"context",
"of",
"a",
"single",
"TaskInstance",
"part",
"of... | def handle_callback(self, dagrun, success=True, reason=None, session=None):
callback = self.on_success_callback if success else self.on_failure_callback
if callback:
self.log.info('Executing dag callback function: %s', callback)
tis = dagrun.get_task_instances(session=session)
... | [
"def",
"handle_callback",
"(",
"self",
",",
"dagrun",
",",
"success",
"=",
"True",
",",
"reason",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"callback",
"=",
"self",
".",
"on_success_callback",
"if",
"success",
"else",
"self",
".",
"on_failure_cal... | Triggers the appropriate callback depending on the value of success, namely the
on_failure_callback or on_success_callback. | [
"Triggers",
"the",
"appropriate",
"callback",
"depending",
"on",
"the",
"value",
"of",
"success",
"namely",
"the",
"on_failure_callback",
"or",
"on_success_callback",
"."
] | [
"\"\"\"\n Triggers the appropriate callback depending on the value of success, namely the\n on_failure_callback or on_success_callback. This method gets the context of a\n single TaskInstance part of this DagRun and passes that to the callable along\n with a 'reason', primarily to differ... | [
{
"param": "self",
"type": null
},
{
"param": "dagrun",
"type": null
},
{
"param": "success",
"type": null
},
{
"param": "reason",
"type": null
},
{
"param": "session",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dagrun",
"type": null,
"docstring": null,
"docstring_tokens":... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | subdags | <not_specific> | def subdags(self):
"""Returns a list of the subdag objects associated to this DAG"""
# Check SubDag for class but don't check class directly
from airflow.operators.subdag import SubDagOperator
subdag_lst = []
for task in self.tasks:
if (
isinstance(ta... | Returns a list of the subdag objects associated to this DAG | Returns a list of the subdag objects associated to this DAG | [
"Returns",
"a",
"list",
"of",
"the",
"subdag",
"objects",
"associated",
"to",
"this",
"DAG"
] | def subdags(self):
from airflow.operators.subdag import SubDagOperator
subdag_lst = []
for task in self.tasks:
if (
isinstance(task, SubDagOperator)
or
type(task).__name__ == 'SubDagOperator'
or task.task_type == 'SubDag... | [
"def",
"subdags",
"(",
"self",
")",
":",
"from",
"airflow",
".",
"operators",
".",
"subdag",
"import",
"SubDagOperator",
"subdag_lst",
"=",
"[",
"]",
"for",
"task",
"in",
"self",
".",
"tasks",
":",
"if",
"(",
"isinstance",
"(",
"task",
",",
"SubDagOperat... | Returns a list of the subdag objects associated to this DAG | [
"Returns",
"a",
"list",
"of",
"the",
"subdag",
"objects",
"associated",
"to",
"this",
"DAG"
] | [
"\"\"\"Returns a list of the subdag objects associated to this DAG\"\"\"",
"# Check SubDag for class but don't check class directly",
"# TODO remove in Airflow 2.0"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | topological_sort | <not_specific> | def topological_sort(self, include_subdag_tasks: bool = False):
"""
Sorts tasks in topographical order, such that a task comes after any of its
upstream dependencies.
Heavily inspired by:
http://blog.jupo.org/2012/04/06/topological-sorting-acyclic-directed-graphs/
:para... |
Sorts tasks in topographical order, such that a task comes after any of its
upstream dependencies.
Heavily inspired by:
http://blog.jupo.org/2012/04/06/topological-sorting-acyclic-directed-graphs/
:param include_subdag_tasks: whether to include tasks in subdags, default to Fal... | Sorts tasks in topographical order, such that a task comes after any of its
upstream dependencies.
| [
"Sorts",
"tasks",
"in",
"topographical",
"order",
"such",
"that",
"a",
"task",
"comes",
"after",
"any",
"of",
"its",
"upstream",
"dependencies",
"."
] | def topological_sort(self, include_subdag_tasks: bool = False):
from airflow.operators.subdag import SubDagOperator
graph_unsorted = OrderedDict((task.task_id, task) for task in self.tasks)
graph_sorted = []
if len(self.tasks) == 0:
return tuple(graph_sorted)
whil... | [
"def",
"topological_sort",
"(",
"self",
",",
"include_subdag_tasks",
":",
"bool",
"=",
"False",
")",
":",
"from",
"airflow",
".",
"operators",
".",
"subdag",
"import",
"SubDagOperator",
"graph_unsorted",
"=",
"OrderedDict",
"(",
"(",
"task",
".",
"task_id",
",... | Sorts tasks in topographical order, such that a task comes after any of its
upstream dependencies. | [
"Sorts",
"tasks",
"in",
"topographical",
"order",
"such",
"that",
"a",
"task",
"comes",
"after",
"any",
"of",
"its",
"upstream",
"dependencies",
"."
] | [
"\"\"\"\n Sorts tasks in topographical order, such that a task comes after any of its\n upstream dependencies.\n\n Heavily inspired by:\n http://blog.jupo.org/2012/04/06/topological-sorting-acyclic-directed-graphs/\n\n :param include_subdag_tasks: whether to include tasks in subda... | [
{
"param": "self",
"type": null
},
{
"param": "include_subdag_tasks",
"type": "bool"
}
] | {
"returns": [
{
"docstring": "list of tasks in topological order",
"docstring_tokens": [
"list",
"of",
"tasks",
"in",
"topological",
"order"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"ty... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | clear | <not_specific> | def clear(
self,
task_ids=None,
start_date=None,
end_date=None,
only_failed=False,
only_running=False,
confirm_prompt=False,
include_subdags=True,
include_parentdag=True,
dag_run_state: DagRunState = DagRunState.QUEUED,
dry_run=Fals... |
Clears a set of task instances associated with the current dag for
a specified date range.
:param task_ids: List of task ids to clear
:type task_ids: List[str]
:param start_date: The minimum execution_date to clear
:type start_date: datetime.datetime or None
:pa... | Clears a set of task instances associated with the current dag for
a specified date range. | [
"Clears",
"a",
"set",
"of",
"task",
"instances",
"associated",
"with",
"the",
"current",
"dag",
"for",
"a",
"specified",
"date",
"range",
"."
] | def clear(
self,
task_ids=None,
start_date=None,
end_date=None,
only_failed=False,
only_running=False,
confirm_prompt=False,
include_subdags=True,
include_parentdag=True,
dag_run_state: DagRunState = DagRunState.QUEUED,
dry_run=Fals... | [
"def",
"clear",
"(",
"self",
",",
"task_ids",
"=",
"None",
",",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
",",
"only_failed",
"=",
"False",
",",
"only_running",
"=",
"False",
",",
"confirm_prompt",
"=",
"False",
",",
"include_subdags",
"=",
... | Clears a set of task instances associated with the current dag for
a specified date range. | [
"Clears",
"a",
"set",
"of",
"task",
"instances",
"associated",
"with",
"the",
"current",
"dag",
"for",
"a",
"specified",
"date",
"range",
"."
] | [
"\"\"\"\n Clears a set of task instances associated with the current dag for\n a specified date range.\n\n :param task_ids: List of task ids to clear\n :type task_ids: List[str]\n :param start_date: The minimum execution_date to clear\n :type start_date: datetime.datetime o... | [
{
"param": "self",
"type": null
},
{
"param": "task_ids",
"type": null
},
{
"param": "start_date",
"type": null
},
{
"param": "end_date",
"type": null
},
{
"param": "only_failed",
"type": null
},
{
"param": "only_running",
"type": null
},
{
... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "task_ids",
"type": null,
"docstring": "List of task ids to clear",
... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | sub_dag | <not_specific> | def sub_dag(self, *args, **kwargs):
"""This method is deprecated in favor of partial_subset"""
warnings.warn(
"This method is deprecated and will be removed in a future version. Please use partial_subset",
DeprecationWarning,
stacklevel=2,
)
return sel... | This method is deprecated in favor of partial_subset | This method is deprecated in favor of partial_subset | [
"This",
"method",
"is",
"deprecated",
"in",
"favor",
"of",
"partial_subset"
] | def sub_dag(self, *args, **kwargs):
warnings.warn(
"This method is deprecated and will be removed in a future version. Please use partial_subset",
DeprecationWarning,
stacklevel=2,
)
return self.partial_subset(*args, **kwargs) | [
"def",
"sub_dag",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"This method is deprecated and will be removed in a future version. Please use partial_subset\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
",",... | This method is deprecated in favor of partial_subset | [
"This",
"method",
"is",
"deprecated",
"in",
"favor",
"of",
"partial_subset"
] | [
"\"\"\"This method is deprecated in favor of partial_subset\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | partial_subset | <not_specific> | def partial_subset(
self,
task_ids_or_regex: Union[str, RePatternType, Iterable[str]],
include_downstream=False,
include_upstream=True,
include_direct_upstream=False,
):
"""
Returns a subset of the current dag as a deep copy of the current dag
based on... |
Returns a subset of the current dag as a deep copy of the current dag
based on a regex that should match one or many tasks, and includes
upstream and downstream neighbours based on the flag passed.
:param task_ids_or_regex: Either a list of task_ids, or a regex to
match aga... | Returns a subset of the current dag as a deep copy of the current dag
based on a regex that should match one or many tasks, and includes
upstream and downstream neighbours based on the flag passed. | [
"Returns",
"a",
"subset",
"of",
"the",
"current",
"dag",
"as",
"a",
"deep",
"copy",
"of",
"the",
"current",
"dag",
"based",
"on",
"a",
"regex",
"that",
"should",
"match",
"one",
"or",
"many",
"tasks",
"and",
"includes",
"upstream",
"and",
"downstream",
"... | def partial_subset(
self,
task_ids_or_regex: Union[str, RePatternType, Iterable[str]],
include_downstream=False,
include_upstream=True,
include_direct_upstream=False,
):
memo = {id(self.task_dict): None, id(self._task_group): None}
dag = copy.deepcopy(self, me... | [
"def",
"partial_subset",
"(",
"self",
",",
"task_ids_or_regex",
":",
"Union",
"[",
"str",
",",
"RePatternType",
",",
"Iterable",
"[",
"str",
"]",
"]",
",",
"include_downstream",
"=",
"False",
",",
"include_upstream",
"=",
"True",
",",
"include_direct_upstream",
... | Returns a subset of the current dag as a deep copy of the current dag
based on a regex that should match one or many tasks, and includes
upstream and downstream neighbours based on the flag passed. | [
"Returns",
"a",
"subset",
"of",
"the",
"current",
"dag",
"as",
"a",
"deep",
"copy",
"of",
"the",
"current",
"dag",
"based",
"on",
"a",
"regex",
"that",
"should",
"match",
"one",
"or",
"many",
"tasks",
"and",
"includes",
"upstream",
"and",
"downstream",
"... | [
"\"\"\"\n Returns a subset of the current dag as a deep copy of the current dag\n based on a regex that should match one or many tasks, and includes\n upstream and downstream neighbours based on the flag passed.\n\n :param task_ids_or_regex: Either a list of task_ids, or a regex to\n ... | [
{
"param": "self",
"type": null
},
{
"param": "task_ids_or_regex",
"type": "Union[str, RePatternType, Iterable[str]]"
},
{
"param": "include_downstream",
"type": null
},
{
"param": "include_upstream",
"type": null
},
{
"param": "include_direct_upstream",
"type... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "task_ids_or_regex",
"type": "Union[str, RePatternType, Iterable[str]]",
... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | filter_task_group | <not_specific> | def filter_task_group(group, parent_group):
"""Exclude tasks not included in the subdag from the given TaskGroup."""
copied = copy.copy(group)
copied.used_group_ids = set(copied.used_group_ids)
copied._parent_group = parent_group
copied.children = {}
... | Exclude tasks not included in the subdag from the given TaskGroup. | Exclude tasks not included in the subdag from the given TaskGroup. | [
"Exclude",
"tasks",
"not",
"included",
"in",
"the",
"subdag",
"from",
"the",
"given",
"TaskGroup",
"."
] | def filter_task_group(group, parent_group):
copied = copy.copy(group)
copied.used_group_ids = set(copied.used_group_ids)
copied._parent_group = parent_group
copied.children = {}
for child in group.children.values():
if isinstance(child, BaseOpe... | [
"def",
"filter_task_group",
"(",
"group",
",",
"parent_group",
")",
":",
"copied",
"=",
"copy",
".",
"copy",
"(",
"group",
")",
"copied",
".",
"used_group_ids",
"=",
"set",
"(",
"copied",
".",
"used_group_ids",
")",
"copied",
".",
"_parent_group",
"=",
"pa... | Exclude tasks not included in the subdag from the given TaskGroup. | [
"Exclude",
"tasks",
"not",
"included",
"in",
"the",
"subdag",
"from",
"the",
"given",
"TaskGroup",
"."
] | [
"\"\"\"Exclude tasks not included in the subdag from the given TaskGroup.\"\"\"",
"# Only include this child TaskGroup if it is non-empty."
] | [
{
"param": "group",
"type": null
},
{
"param": "parent_group",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "group",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "parent_group",
"type": null,
"docstring": null,
"docstring_t... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | tree_view | None | def tree_view(self) -> None:
"""Print an ASCII tree representation of the DAG."""
def get_downstream(task, level=0):
print((" " * level * 4) + str(task))
level += 1
for t in task.downstream_list:
get_downstream(t, level)
for t in self.roots:
... | Print an ASCII tree representation of the DAG. | Print an ASCII tree representation of the DAG. | [
"Print",
"an",
"ASCII",
"tree",
"representation",
"of",
"the",
"DAG",
"."
] | def tree_view(self) -> None:
def get_downstream(task, level=0):
print((" " * level * 4) + str(task))
level += 1
for t in task.downstream_list:
get_downstream(t, level)
for t in self.roots:
get_downstream(t) | [
"def",
"tree_view",
"(",
"self",
")",
"->",
"None",
":",
"def",
"get_downstream",
"(",
"task",
",",
"level",
"=",
"0",
")",
":",
"print",
"(",
"(",
"\" \"",
"*",
"level",
"*",
"4",
")",
"+",
"str",
"(",
"task",
")",
")",
"level",
"+=",
"1",
"fo... | Print an ASCII tree representation of the DAG. | [
"Print",
"an",
"ASCII",
"tree",
"representation",
"of",
"the",
"DAG",
"."
] | [
"\"\"\"Print an ASCII tree representation of the DAG.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | add_task | null | def add_task(self, task):
"""
Add a task to the DAG
:param task: the task you want to add
:type task: task
"""
if not self.start_date and not task.start_date:
raise AirflowException("Task is missing the start_date parameter")
# if the task has no star... |
Add a task to the DAG
:param task: the task you want to add
:type task: task
| Add a task to the DAG | [
"Add",
"a",
"task",
"to",
"the",
"DAG"
] | def add_task(self, task):
if not self.start_date and not task.start_date:
raise AirflowException("Task is missing the start_date parameter")
elif not task.start_date:
task.start_date = self.start_date
elif self.start_date:
task.start_date = max(task.start_date... | [
"def",
"add_task",
"(",
"self",
",",
"task",
")",
":",
"if",
"not",
"self",
".",
"start_date",
"and",
"not",
"task",
".",
"start_date",
":",
"raise",
"AirflowException",
"(",
"\"Task is missing the start_date parameter\"",
")",
"elif",
"not",
"task",
".",
"sta... | Add a task to the DAG | [
"Add",
"a",
"task",
"to",
"the",
"DAG"
] | [
"\"\"\"\n Add a task to the DAG\n\n :param task: the task you want to add\n :type task: task\n \"\"\"",
"# if the task has no start date, assign it the same as the DAG",
"# otherwise, the task will start on the later of its own start date and",
"# the DAG's start date",
"# if the... | [
{
"param": "self",
"type": null
},
{
"param": "task",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "task",
"type": null,
"docstring": "the task you want to add",
... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | cli | null | def cli(self):
"""Exposes a CLI specific to this DAG"""
check_cycle(self)
from airflow.cli import cli_parser
parser = cli_parser.get_parser(dag_parser=True)
args = parser.parse_args()
args.func(args, self) | Exposes a CLI specific to this DAG | Exposes a CLI specific to this DAG | [
"Exposes",
"a",
"CLI",
"specific",
"to",
"this",
"DAG"
] | def cli(self):
check_cycle(self)
from airflow.cli import cli_parser
parser = cli_parser.get_parser(dag_parser=True)
args = parser.parse_args()
args.func(args, self) | [
"def",
"cli",
"(",
"self",
")",
":",
"check_cycle",
"(",
"self",
")",
"from",
"airflow",
".",
"cli",
"import",
"cli_parser",
"parser",
"=",
"cli_parser",
".",
"get_parser",
"(",
"dag_parser",
"=",
"True",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(... | Exposes a CLI specific to this DAG | [
"Exposes",
"a",
"CLI",
"specific",
"to",
"this",
"DAG"
] | [
"\"\"\"Exposes a CLI specific to this DAG\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | create_dagrun | <not_specific> | def create_dagrun(
self,
state: DagRunState,
execution_date: Optional[datetime] = None,
run_id: Optional[str] = None,
start_date: Optional[datetime] = None,
external_trigger: Optional[bool] = False,
conf: Optional[dict] = None,
run_type: Optional[DagRunTyp... |
Creates a dag run from this dag including the tasks associated with this dag.
Returns the dag run.
:param run_id: defines the run id for this dag run
:type run_id: str
:param run_type: type of DagRun
:type run_type: airflow.utils.types.DagRunType
:param executio... | Creates a dag run from this dag including the tasks associated with this dag.
Returns the dag run. | [
"Creates",
"a",
"dag",
"run",
"from",
"this",
"dag",
"including",
"the",
"tasks",
"associated",
"with",
"this",
"dag",
".",
"Returns",
"the",
"dag",
"run",
"."
] | def create_dagrun(
self,
state: DagRunState,
execution_date: Optional[datetime] = None,
run_id: Optional[str] = None,
start_date: Optional[datetime] = None,
external_trigger: Optional[bool] = False,
conf: Optional[dict] = None,
run_type: Optional[DagRunTyp... | [
"def",
"create_dagrun",
"(",
"self",
",",
"state",
":",
"DagRunState",
",",
"execution_date",
":",
"Optional",
"[",
"datetime",
"]",
"=",
"None",
",",
"run_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"start_date",
":",
"Optional",
"[",
"date... | Creates a dag run from this dag including the tasks associated with this dag. | [
"Creates",
"a",
"dag",
"run",
"from",
"this",
"dag",
"including",
"the",
"tasks",
"associated",
"with",
"this",
"dag",
"."
] | [
"\"\"\"\n Creates a dag run from this dag including the tasks associated with this dag.\n Returns the dag run.\n\n :param run_id: defines the run id for this dag run\n :type run_id: str\n :param run_type: type of DagRun\n :type run_type: airflow.utils.types.DagRunType\n ... | [
{
"param": "self",
"type": null
},
{
"param": "state",
"type": "DagRunState"
},
{
"param": "execution_date",
"type": "Optional[datetime]"
},
{
"param": "run_id",
"type": "Optional[str]"
},
{
"param": "start_date",
"type": "Optional[datetime]"
},
{
"par... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "state",
"type": "DagRunState",
"docstring": "the state of the dag r... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | bulk_sync_to_db | <not_specific> | def bulk_sync_to_db(cls, dags: Collection["DAG"], session=None):
"""This method is deprecated in favor of bulk_write_to_db"""
warnings.warn(
"This method is deprecated and will be removed in a future version. Please use bulk_write_to_db",
DeprecationWarning,
stackleve... | This method is deprecated in favor of bulk_write_to_db | This method is deprecated in favor of bulk_write_to_db | [
"This",
"method",
"is",
"deprecated",
"in",
"favor",
"of",
"bulk_write_to_db"
] | def bulk_sync_to_db(cls, dags: Collection["DAG"], session=None):
warnings.warn(
"This method is deprecated and will be removed in a future version. Please use bulk_write_to_db",
DeprecationWarning,
stacklevel=2,
)
return cls.bulk_write_to_db(dags, session) | [
"def",
"bulk_sync_to_db",
"(",
"cls",
",",
"dags",
":",
"Collection",
"[",
"\"DAG\"",
"]",
",",
"session",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"This method is deprecated and will be removed in a future version. Please use bulk_write_to_db\"",
",",
"De... | This method is deprecated in favor of bulk_write_to_db | [
"This",
"method",
"is",
"deprecated",
"in",
"favor",
"of",
"bulk_write_to_db"
] | [
"\"\"\"This method is deprecated in favor of bulk_write_to_db\"\"\""
] | [
{
"param": "cls",
"type": null
},
{
"param": "dags",
"type": "Collection[\"DAG\"]"
},
{
"param": "session",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dags",
"type": "Collection[\"DAG\"]",
"docstring": null,
"docs... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | bulk_write_to_db | <not_specific> | def bulk_write_to_db(cls, dags: Collection["DAG"], session=None):
"""
Ensure the DagModel rows for the given dags are up-to-date in the dag table in the DB, including
calculated fields.
Note that this method can be called for both DAGs and SubDAGs. A SubDag is actually a SubDagOperator.... |
Ensure the DagModel rows for the given dags are up-to-date in the dag table in the DB, including
calculated fields.
Note that this method can be called for both DAGs and SubDAGs. A SubDag is actually a SubDagOperator.
:param dags: the DAG objects to save to the DB
:type dags: ... | Ensure the DagModel rows for the given dags are up-to-date in the dag table in the DB, including
calculated fields.
Note that this method can be called for both DAGs and SubDAGs. | [
"Ensure",
"the",
"DagModel",
"rows",
"for",
"the",
"given",
"dags",
"are",
"up",
"-",
"to",
"-",
"date",
"in",
"the",
"dag",
"table",
"in",
"the",
"DB",
"including",
"calculated",
"fields",
".",
"Note",
"that",
"this",
"method",
"can",
"be",
"called",
... | def bulk_write_to_db(cls, dags: Collection["DAG"], session=None):
if not dags:
return
log.info("Sync %s DAGs", len(dags))
dag_by_ids = {dag.dag_id: dag for dag in dags}
dag_ids = set(dag_by_ids.keys())
query = (
session.query(DagModel)
.options... | [
"def",
"bulk_write_to_db",
"(",
"cls",
",",
"dags",
":",
"Collection",
"[",
"\"DAG\"",
"]",
",",
"session",
"=",
"None",
")",
":",
"if",
"not",
"dags",
":",
"return",
"log",
".",
"info",
"(",
"\"Sync %s DAGs\"",
",",
"len",
"(",
"dags",
")",
")",
"da... | Ensure the DagModel rows for the given dags are up-to-date in the dag table in the DB, including
calculated fields. | [
"Ensure",
"the",
"DagModel",
"rows",
"for",
"the",
"given",
"dags",
"are",
"up",
"-",
"to",
"-",
"date",
"in",
"the",
"dag",
"table",
"in",
"the",
"DB",
"including",
"calculated",
"fields",
"."
] | [
"\"\"\"\n Ensure the DagModel rows for the given dags are up-to-date in the dag table in the DB, including\n calculated fields.\n\n Note that this method can be called for both DAGs and SubDAGs. A SubDag is actually a SubDagOperator.\n\n :param dags: the DAG objects to save to the DB\n ... | [
{
"param": "cls",
"type": null
},
{
"param": "dags",
"type": "Collection[\"DAG\"]"
},
{
"param": "session",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | sync_to_db | null | def sync_to_db(self, session=None):
"""
Save attributes about this DAG to the DB. Note that this method
can be called for both DAGs and SubDAGs. A SubDag is actually a
SubDagOperator.
:return: None
"""
self.bulk_write_to_db([self], session) |
Save attributes about this DAG to the DB. Note that this method
can be called for both DAGs and SubDAGs. A SubDag is actually a
SubDagOperator.
:return: None
| Save attributes about this DAG to the DB. Note that this method
can be called for both DAGs and SubDAGs. | [
"Save",
"attributes",
"about",
"this",
"DAG",
"to",
"the",
"DB",
".",
"Note",
"that",
"this",
"method",
"can",
"be",
"called",
"for",
"both",
"DAGs",
"and",
"SubDAGs",
"."
] | def sync_to_db(self, session=None):
self.bulk_write_to_db([self], session) | [
"def",
"sync_to_db",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"self",
".",
"bulk_write_to_db",
"(",
"[",
"self",
"]",
",",
"session",
")"
] | Save attributes about this DAG to the DB. | [
"Save",
"attributes",
"about",
"this",
"DAG",
"to",
"the",
"DB",
"."
] | [
"\"\"\"\n Save attributes about this DAG to the DB. Note that this method\n can be called for both DAGs and SubDAGs. A SubDag is actually a\n SubDagOperator.\n\n :return: None\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "session",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | deactivate_unknown_dags | <not_specific> | def deactivate_unknown_dags(active_dag_ids, session=None):
"""
Given a list of known DAGs, deactivate any other DAGs that are
marked as active in the ORM
:param active_dag_ids: list of DAG IDs that are active
:type active_dag_ids: list[unicode]
:return: None
"""
... |
Given a list of known DAGs, deactivate any other DAGs that are
marked as active in the ORM
:param active_dag_ids: list of DAG IDs that are active
:type active_dag_ids: list[unicode]
:return: None
| Given a list of known DAGs, deactivate any other DAGs that are
marked as active in the ORM | [
"Given",
"a",
"list",
"of",
"known",
"DAGs",
"deactivate",
"any",
"other",
"DAGs",
"that",
"are",
"marked",
"as",
"active",
"in",
"the",
"ORM"
] | def deactivate_unknown_dags(active_dag_ids, session=None):
if len(active_dag_ids) == 0:
return
for dag in session.query(DagModel).filter(~DagModel.dag_id.in_(active_dag_ids)).all():
dag.is_active = False
session.merge(dag)
session.commit() | [
"def",
"deactivate_unknown_dags",
"(",
"active_dag_ids",
",",
"session",
"=",
"None",
")",
":",
"if",
"len",
"(",
"active_dag_ids",
")",
"==",
"0",
":",
"return",
"for",
"dag",
"in",
"session",
".",
"query",
"(",
"DagModel",
")",
".",
"filter",
"(",
"~",... | Given a list of known DAGs, deactivate any other DAGs that are
marked as active in the ORM | [
"Given",
"a",
"list",
"of",
"known",
"DAGs",
"deactivate",
"any",
"other",
"DAGs",
"that",
"are",
"marked",
"as",
"active",
"in",
"the",
"ORM"
] | [
"\"\"\"\n Given a list of known DAGs, deactivate any other DAGs that are\n marked as active in the ORM\n\n :param active_dag_ids: list of DAG IDs that are active\n :type active_dag_ids: list[unicode]\n :return: None\n \"\"\""
] | [
{
"param": "active_dag_ids",
"type": null
},
{
"param": "session",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "active_dag_ids",
"type": null,
"docstring": "list of DAG IDs that are active",
"docstring_tokens": [
"list"... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | deactivate_stale_dags | null | def deactivate_stale_dags(expiration_date, session=None):
"""
Deactivate any DAGs that were last touched by the scheduler before
the expiration date. These DAGs were likely deleted.
:param expiration_date: set inactive DAGs that were touched before this
time
:type ex... |
Deactivate any DAGs that were last touched by the scheduler before
the expiration date. These DAGs were likely deleted.
:param expiration_date: set inactive DAGs that were touched before this
time
:type expiration_date: datetime
:return: None
| Deactivate any DAGs that were last touched by the scheduler before
the expiration date. These DAGs were likely deleted. | [
"Deactivate",
"any",
"DAGs",
"that",
"were",
"last",
"touched",
"by",
"the",
"scheduler",
"before",
"the",
"expiration",
"date",
".",
"These",
"DAGs",
"were",
"likely",
"deleted",
"."
] | def deactivate_stale_dags(expiration_date, session=None):
for dag in (
session.query(DagModel)
.filter(DagModel.last_parsed_time < expiration_date, DagModel.is_active)
.all()
):
log.info(
"Deactivating DAG ID %s since it was last touched by... | [
"def",
"deactivate_stale_dags",
"(",
"expiration_date",
",",
"session",
"=",
"None",
")",
":",
"for",
"dag",
"in",
"(",
"session",
".",
"query",
"(",
"DagModel",
")",
".",
"filter",
"(",
"DagModel",
".",
"last_parsed_time",
"<",
"expiration_date",
",",
"DagM... | Deactivate any DAGs that were last touched by the scheduler before
the expiration date. | [
"Deactivate",
"any",
"DAGs",
"that",
"were",
"last",
"touched",
"by",
"the",
"scheduler",
"before",
"the",
"expiration",
"date",
"."
] | [
"\"\"\"\n Deactivate any DAGs that were last touched by the scheduler before\n the expiration date. These DAGs were likely deleted.\n\n :param expiration_date: set inactive DAGs that were touched before this\n time\n :type expiration_date: datetime\n :return: None\n ... | [
{
"param": "expiration_date",
"type": null
},
{
"param": "session",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "expiration_date",
"type": null,
"docstring": "set inactive DAGs that were touched before this\ntime",
"docstring_to... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | validate_schedule_and_params | <not_specific> | def validate_schedule_and_params(self):
"""
Validates & raise exception if there are any Params in the DAG which neither have a default value nor
have the null in schema['type'] list, but the DAG have a schedule_interval which is not None.
"""
if not self.timetable.can_run:
... |
Validates & raise exception if there are any Params in the DAG which neither have a default value nor
have the null in schema['type'] list, but the DAG have a schedule_interval which is not None.
| Validates & raise exception if there are any Params in the DAG which neither have a default value nor
have the null in schema['type'] list, but the DAG have a schedule_interval which is not None. | [
"Validates",
"&",
"raise",
"exception",
"if",
"there",
"are",
"any",
"Params",
"in",
"the",
"DAG",
"which",
"neither",
"have",
"a",
"default",
"value",
"nor",
"have",
"the",
"null",
"in",
"schema",
"[",
"'",
"type",
"'",
"]",
"list",
"but",
"the",
"DAG... | def validate_schedule_and_params(self):
if not self.timetable.can_run:
return
for k, v in self.params.items():
if not v.has_value and ("type" not in v.schema or "null" not in v.schema["type"]):
raise AirflowException(
"DAG Schedule must be None... | [
"def",
"validate_schedule_and_params",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"timetable",
".",
"can_run",
":",
"return",
"for",
"k",
",",
"v",
"in",
"self",
".",
"params",
".",
"items",
"(",
")",
":",
"if",
"not",
"v",
".",
"has_value",
"a... | Validates & raise exception if there are any Params in the DAG which neither have a default value nor
have the null in schema['type'] list, but the DAG have a schedule_interval which is not None. | [
"Validates",
"&",
"raise",
"exception",
"if",
"there",
"are",
"any",
"Params",
"in",
"the",
"DAG",
"which",
"neither",
"have",
"a",
"default",
"value",
"nor",
"have",
"the",
"null",
"in",
"schema",
"[",
"'",
"type",
"'",
"]",
"list",
"but",
"the",
"DAG... | [
"\"\"\"\n Validates & raise exception if there are any Params in the DAG which neither have a default value nor\n have the null in schema['type'] list, but the DAG have a schedule_interval which is not None.\n \"\"\"",
"# As type can be an array, we would check if `null` is an allowed type or... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | relative_fileloc | Optional[pathlib.Path] | def relative_fileloc(self) -> Optional[pathlib.Path]:
"""File location of the importable dag 'file' relative to the configured DAGs folder."""
if self.fileloc is None:
return None
path = pathlib.Path(self.fileloc)
try:
return path.relative_to(settings.DAGS_FOLDER)... | File location of the importable dag 'file' relative to the configured DAGs folder. | File location of the importable dag 'file' relative to the configured DAGs folder. | [
"File",
"location",
"of",
"the",
"importable",
"dag",
"'",
"file",
"'",
"relative",
"to",
"the",
"configured",
"DAGs",
"folder",
"."
] | def relative_fileloc(self) -> Optional[pathlib.Path]:
if self.fileloc is None:
return None
path = pathlib.Path(self.fileloc)
try:
return path.relative_to(settings.DAGS_FOLDER)
except ValueError:
return path | [
"def",
"relative_fileloc",
"(",
"self",
")",
"->",
"Optional",
"[",
"pathlib",
".",
"Path",
"]",
":",
"if",
"self",
".",
"fileloc",
"is",
"None",
":",
"return",
"None",
"path",
"=",
"pathlib",
".",
"Path",
"(",
"self",
".",
"fileloc",
")",
"try",
":"... | File location of the importable dag 'file' relative to the configured DAGs folder. | [
"File",
"location",
"of",
"the",
"importable",
"dag",
"'",
"file",
"'",
"relative",
"to",
"the",
"configured",
"DAGs",
"folder",
"."
] | [
"\"\"\"File location of the importable dag 'file' relative to the configured DAGs folder.\"\"\"",
"# Not relative to DAGS_FOLDER."
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | dags_needing_dagruns | <not_specific> | def dags_needing_dagruns(cls, session: Session):
"""
Return (and lock) a list of Dag objects that are due to create a new DagRun.
This will return a resultset of rows that is row-level-locked with a "SELECT ... FOR UPDATE" query,
you should ensure that any scheduling decisions are made... |
Return (and lock) a list of Dag objects that are due to create a new DagRun.
This will return a resultset of rows that is row-level-locked with a "SELECT ... FOR UPDATE" query,
you should ensure that any scheduling decisions are made in a single transaction -- as soon as the
transacti... | Return (and lock) a list of Dag objects that are due to create a new DagRun.
This will return a resultset of rows that is row-level-locked with a "SELECT ... FOR UPDATE" query,
you should ensure that any scheduling decisions are made in a single transaction -- as soon as the
transaction is committed it will be unlocke... | [
"Return",
"(",
"and",
"lock",
")",
"a",
"list",
"of",
"Dag",
"objects",
"that",
"are",
"due",
"to",
"create",
"a",
"new",
"DagRun",
".",
"This",
"will",
"return",
"a",
"resultset",
"of",
"rows",
"that",
"is",
"row",
"-",
"level",
"-",
"locked",
"with... | def dags_needing_dagruns(cls, session: Session):
query = (
session.query(cls)
.filter(
cls.is_paused == expression.false(),
cls.is_active == expression.true(),
cls.next_dagrun_create_after <= func.now(),
)
.order_by(... | [
"def",
"dags_needing_dagruns",
"(",
"cls",
",",
"session",
":",
"Session",
")",
":",
"query",
"=",
"(",
"session",
".",
"query",
"(",
"cls",
")",
".",
"filter",
"(",
"cls",
".",
"is_paused",
"==",
"expression",
".",
"false",
"(",
")",
",",
"cls",
"."... | Return (and lock) a list of Dag objects that are due to create a new DagRun. | [
"Return",
"(",
"and",
"lock",
")",
"a",
"list",
"of",
"Dag",
"objects",
"that",
"are",
"due",
"to",
"create",
"a",
"new",
"DagRun",
"."
] | [
"\"\"\"\n Return (and lock) a list of Dag objects that are due to create a new DagRun.\n\n This will return a resultset of rows that is row-level-locked with a \"SELECT ... FOR UPDATE\" query,\n you should ensure that any scheduling decisions are made in a single transaction -- as soon as the\... | [
{
"param": "cls",
"type": null
},
{
"param": "session",
"type": "Session"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "session",
"type": "Session",
"docstring": null,
"docstring_tok... |
149606b992a1275e8e50ce3b2cd7902ec0f4677f | Harisonm/airflow | airflow/models/dag.py | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | Python | dag | <not_specific> | def dag(*dag_args, **dag_kwargs):
"""
Python dag decorator. Wraps a function into an Airflow DAG.
Accepts kwargs for operator kwarg. Can be used to parametrize DAGs.
:param dag_args: Arguments for DAG object
:type dag_args: Any
:param dag_kwargs: Kwargs for DAG object.
:type dag_kwargs: Any... |
Python dag decorator. Wraps a function into an Airflow DAG.
Accepts kwargs for operator kwarg. Can be used to parametrize DAGs.
:param dag_args: Arguments for DAG object
:type dag_args: Any
:param dag_kwargs: Kwargs for DAG object.
:type dag_kwargs: Any
| Python dag decorator. Wraps a function into an Airflow DAG.
Accepts kwargs for operator kwarg. Can be used to parametrize DAGs. | [
"Python",
"dag",
"decorator",
".",
"Wraps",
"a",
"function",
"into",
"an",
"Airflow",
"DAG",
".",
"Accepts",
"kwargs",
"for",
"operator",
"kwarg",
".",
"Can",
"be",
"used",
"to",
"parametrize",
"DAGs",
"."
] | def dag(*dag_args, **dag_kwargs):
def wrapper(f: Callable):
dag_sig = signature(DAG.__init__)
dag_bound_args = dag_sig.bind_partial(*dag_args, **dag_kwargs)
@functools.wraps(f)
def factory(*args, **kwargs):
f_sig = signature(f).bind(*args, **kwargs)
f_sig.appl... | [
"def",
"dag",
"(",
"*",
"dag_args",
",",
"**",
"dag_kwargs",
")",
":",
"def",
"wrapper",
"(",
"f",
":",
"Callable",
")",
":",
"dag_sig",
"=",
"signature",
"(",
"DAG",
".",
"__init__",
")",
"dag_bound_args",
"=",
"dag_sig",
".",
"bind_partial",
"(",
"*"... | Python dag decorator. | [
"Python",
"dag",
"decorator",
"."
] | [
"\"\"\"\n Python dag decorator. Wraps a function into an Airflow DAG.\n Accepts kwargs for operator kwarg. Can be used to parametrize DAGs.\n\n :param dag_args: Arguments for DAG object\n :type dag_args: Any\n :param dag_kwargs: Kwargs for DAG object.\n :type dag_kwargs: Any\n \"\"\"",
"# Get... | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "dag_args",
"type": null,
"docstring": "Arguments for DAG object",
"docstring_tokens": [
"Arguments",
"for",
"DAG",
"object"
],
"default": null,
"is_opti... |
b16cfaacc203ff66da925d50b924d32db2c4fa96 | tusharsadhwani/emojy | src/emojy/__init__.py | [
"MIT"
] | Python | de_emojify | str | def de_emojify(emoji_code: str) -> str:
"""Convert emojified Python into regular Python"""
converted_tokens: List[tokenize_rt.Token] = []
unresolved_text = ""
for token in tokenize_rt.src_to_tokens(emoji_code):
if token.name == "STRING":
converted_tokens.append(token)
co... | Convert emojified Python into regular Python | Convert emojified Python into regular Python | [
"Convert",
"emojified",
"Python",
"into",
"regular",
"Python"
] | def de_emojify(emoji_code: str) -> str:
converted_tokens: List[tokenize_rt.Token] = []
unresolved_text = ""
for token in tokenize_rt.src_to_tokens(emoji_code):
if token.name == "STRING":
converted_tokens.append(token)
continue
src_list: List[str] = []
text = t... | [
"def",
"de_emojify",
"(",
"emoji_code",
":",
"str",
")",
"->",
"str",
":",
"converted_tokens",
":",
"List",
"[",
"tokenize_rt",
".",
"Token",
"]",
"=",
"[",
"]",
"unresolved_text",
"=",
"\"\"",
"for",
"token",
"in",
"tokenize_rt",
".",
"src_to_tokens",
"("... | Convert emojified Python into regular Python | [
"Convert",
"emojified",
"Python",
"into",
"regular",
"Python"
] | [
"\"\"\"Convert emojified Python into regular Python\"\"\"",
"# TODO: we need to check if the current text could be the part of an emoji sequence.",
"# if yes, we add it to unresolved_text, and keep getting more tokens as long as",
"# any of the existing tokens start with unresolved_text.",
"# if we find a m... | [
{
"param": "emoji_code",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "emoji_code",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
91117268afc30261a2a6f47dd05d4ae45695f863 | nickblum/regression | regression/linear_regression.py | [
"MIT"
] | Python | find_curve | null | def find_curve(X=0,y=0,alpha=100):
"""
NOTE TO SELF: USE numpy -- it's written in C and a zillion times faster than python functions for arrays and such
Need to include docstring here. A brief explanation of the function
X: A brief explanation of this variable
y: A brief ex... |
NOTE TO SELF: USE numpy -- it's written in C and a zillion times faster than python functions for arrays and such
Need to include docstring here. A brief explanation of the function
X: A brief explanation of this variable
y: A brief explanation of this variable
alpha: ... | NOTE TO SELF: USE numpy -- it's written in C and a zillion times faster than python functions for arrays and such
Need to include docstring here. A brief explanation of the function
A brief explanation of this variable
y: A brief explanation of this variable
alpha: This one too | [
"NOTE",
"TO",
"SELF",
":",
"USE",
"numpy",
"--",
"it",
"'",
"s",
"written",
"in",
"C",
"and",
"a",
"zillion",
"times",
"faster",
"than",
"python",
"functions",
"for",
"arrays",
"and",
"such",
"Need",
"to",
"include",
"docstring",
"here",
".",
"A",
"bri... | def find_curve(X=0,y=0,alpha=100):
print('Finding curve') | [
"def",
"find_curve",
"(",
"X",
"=",
"0",
",",
"y",
"=",
"0",
",",
"alpha",
"=",
"100",
")",
":",
"print",
"(",
"'Finding curve'",
")"
] | NOTE TO SELF: USE numpy -- it's written in C and a zillion times faster than python functions for arrays and such
Need to include docstring here. | [
"NOTE",
"TO",
"SELF",
":",
"USE",
"numpy",
"--",
"it",
"'",
"s",
"written",
"in",
"C",
"and",
"a",
"zillion",
"times",
"faster",
"than",
"python",
"functions",
"for",
"arrays",
"and",
"such",
"Need",
"to",
"include",
"docstring",
"here",
"."
] | [
"\"\"\"\n NOTE TO SELF: USE numpy -- it's written in C and a zillion times faster than python functions for arrays and such\n \n Need to include docstring here. A brief explanation of the function\n\n X: A brief explanation of this variable\n y: A brief explanation of this variabl... | [
{
"param": "X",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "alpha",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "X",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "y",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
fd5c0a4105269a7d3321041bb25d2c6e884f9134 | gitter-badger/aroma-1 | aroma/utils.py | [
"Apache-2.0"
] | Python | runICA | null | def runICA(fsl_dir, in_file, out_dir, mel_dir_in, mask, dim, TR):
"""Run MELODIC and merge the thresholded ICs into a single 4D nifti file.
Parameters
----------
fsl_dir : str
Full path of the bin-directory of FSL
in_file : str
Full path to the fMRI data file (nii.gz) on which MELOD... | Run MELODIC and merge the thresholded ICs into a single 4D nifti file.
Parameters
----------
fsl_dir : str
Full path of the bin-directory of FSL
in_file : str
Full path to the fMRI data file (nii.gz) on which MELODIC
should be run
out_dir : str
Full path of the outpu... | Run MELODIC and merge the thresholded ICs into a single 4D nifti file.
Parameters
fsl_dir : str
Full path of the bin-directory of FSL
in_file : str
Full path to the fMRI data file (nii.gz) on which MELODIC
should be run
out_dir : str
Full path of the output directory
mel_dir_in : str or None
Full path of the MELODIC d... | [
"Run",
"MELODIC",
"and",
"merge",
"the",
"thresholded",
"ICs",
"into",
"a",
"single",
"4D",
"nifti",
"file",
".",
"Parameters",
"fsl_dir",
":",
"str",
"Full",
"path",
"of",
"the",
"bin",
"-",
"directory",
"of",
"FSL",
"in_file",
":",
"str",
"Full",
"path... | def runICA(fsl_dir, in_file, out_dir, mel_dir_in, mask, dim, TR):
mel_dir = op.join(out_dir, "melodic.ica")
mel_IC = op.join(mel_dir, "melodic_IC.nii.gz")
mel_IC_mix = op.join(mel_dir, "melodic_mix")
mel_IC_thr = op.join(out_dir, "melodic_IC_thr.nii.gz")
if (
mel_dir_in
and op.isfile... | [
"def",
"runICA",
"(",
"fsl_dir",
",",
"in_file",
",",
"out_dir",
",",
"mel_dir_in",
",",
"mask",
",",
"dim",
",",
"TR",
")",
":",
"mel_dir",
"=",
"op",
".",
"join",
"(",
"out_dir",
",",
"\"melodic.ica\"",
")",
"mel_IC",
"=",
"op",
".",
"join",
"(",
... | Run MELODIC and merge the thresholded ICs into a single 4D nifti file. | [
"Run",
"MELODIC",
"and",
"merge",
"the",
"thresholded",
"ICs",
"into",
"a",
"single",
"4D",
"nifti",
"file",
"."
] | [
"\"\"\"Run MELODIC and merge the thresholded ICs into a single 4D nifti file.\n\n Parameters\n ----------\n fsl_dir : str\n Full path of the bin-directory of FSL\n in_file : str\n Full path to the fMRI data file (nii.gz) on which MELODIC\n should be run\n out_dir : str\n F... | [
{
"param": "fsl_dir",
"type": null
},
{
"param": "in_file",
"type": null
},
{
"param": "out_dir",
"type": null
},
{
"param": "mel_dir_in",
"type": null
},
{
"param": "mask",
"type": null
},
{
"param": "dim",
"type": null
},
{
"param": "TR",... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "fsl_dir",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "in_file",
"type": null,
"docstring": null,
"docstring_toke... |
fd5c0a4105269a7d3321041bb25d2c6e884f9134 | gitter-badger/aroma-1 | aroma/utils.py | [
"Apache-2.0"
] | Python | register2MNI | null | def register2MNI(fsl_dir, in_file, out_file, affmat, warp):
"""Register an image (or time-series of images) to MNI152 T1 2mm.
If no affmat is defined, it only warps (i.e. it assumes that the data has
been registered to the structural scan associated with the warp-file
already). If no warp is defined ei... | Register an image (or time-series of images) to MNI152 T1 2mm.
If no affmat is defined, it only warps (i.e. it assumes that the data has
been registered to the structural scan associated with the warp-file
already). If no warp is defined either, it only resamples the data to 2mm
isotropic if needed (i.... | Register an image (or time-series of images) to MNI152 T1 2mm.
If no affmat is defined, it only warps . If no warp is defined either, it only resamples the data to 2mm
isotropic if needed . In case only an affmat file is defined, it assumes that
the data has to be linearly registered to MNI152 .
Parameters
Output
... | [
"Register",
"an",
"image",
"(",
"or",
"time",
"-",
"series",
"of",
"images",
")",
"to",
"MNI152",
"T1",
"2mm",
".",
"If",
"no",
"affmat",
"is",
"defined",
"it",
"only",
"warps",
".",
"If",
"no",
"warp",
"is",
"defined",
"either",
"it",
"only",
"resam... | def register2MNI(fsl_dir, in_file, out_file, affmat, warp):
fslnobin = fsl_dir.rsplit("/", 2)[0]
ref = op.join(fslnobin, "data", "standard", "MNI152_T1_2mm_brain.nii.gz")
if not affmat and not warp:
in_img = nib.load(in_file)
pixdim1, pixdim2, pixdim3 = in_img.header.get_zooms()[:3]
... | [
"def",
"register2MNI",
"(",
"fsl_dir",
",",
"in_file",
",",
"out_file",
",",
"affmat",
",",
"warp",
")",
":",
"fslnobin",
"=",
"fsl_dir",
".",
"rsplit",
"(",
"\"/\"",
",",
"2",
")",
"[",
"0",
"]",
"ref",
"=",
"op",
".",
"join",
"(",
"fslnobin",
","... | Register an image (or time-series of images) to MNI152 T1 2mm. | [
"Register",
"an",
"image",
"(",
"or",
"time",
"-",
"series",
"of",
"images",
")",
"to",
"MNI152",
"T1",
"2mm",
"."
] | [
"\"\"\"Register an image (or time-series of images) to MNI152 T1 2mm.\n\n If no affmat is defined, it only warps (i.e. it assumes that the data has\n been registered to the structural scan associated with the warp-file\n already). If no warp is defined either, it only resamples the data to 2mm\n isotrop... | [
{
"param": "fsl_dir",
"type": null
},
{
"param": "in_file",
"type": null
},
{
"param": "out_file",
"type": null
},
{
"param": "affmat",
"type": null
},
{
"param": "warp",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "fsl_dir",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "in_file",
"type": null,
"docstring": null,
"docstring_toke... |
177d2a8d43f9df27b52462867dbb85d9efe08de4 | ashihito/nose-selecttests | noseselecttests/__init__.py | [
"BSD-3-Clause"
] | Python | _is_selected | <not_specific> | def _is_selected(self, test_obj):
"""Return True if a test object should be selected based on criteria pattern."""
if not test_obj:
return
if isinstance(test_obj, six.string_types):
name = test_obj
else:
name = objname(test_obj)
#log.debug('obj... | Return True if a test object should be selected based on criteria pattern. | Return True if a test object should be selected based on criteria pattern. | [
"Return",
"True",
"if",
"a",
"test",
"object",
"should",
"be",
"selected",
"based",
"on",
"criteria",
"pattern",
"."
] | def _is_selected(self, test_obj):
if not test_obj:
return
if isinstance(test_obj, six.string_types):
name = test_obj
else:
name = objname(test_obj)
if name:
name = name.lower()
selected = any(fnmatch(name, pat) for pat in self.s... | [
"def",
"_is_selected",
"(",
"self",
",",
"test_obj",
")",
":",
"if",
"not",
"test_obj",
":",
"return",
"if",
"isinstance",
"(",
"test_obj",
",",
"six",
".",
"string_types",
")",
":",
"name",
"=",
"test_obj",
"else",
":",
"name",
"=",
"objname",
"(",
"t... | Return True if a test object should be selected based on criteria pattern. | [
"Return",
"True",
"if",
"a",
"test",
"object",
"should",
"be",
"selected",
"based",
"on",
"criteria",
"pattern",
"."
] | [
"\"\"\"Return True if a test object should be selected based on criteria pattern.\"\"\"",
"#log.debug('object name: %r' % name)",
"#log.debug('selected:%r name: %r' % (selected, name,))"
] | [
{
"param": "self",
"type": null
},
{
"param": "test_obj",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "test_obj",
"type": null,
"docstring": null,
"docstring_tokens... |
177d2a8d43f9df27b52462867dbb85d9efe08de4 | ashihito/nose-selecttests | noseselecttests/__init__.py | [
"BSD-3-Clause"
] | Python | objname | <not_specific> | def objname(obj):
'''Return the context qualified name of a function, method or class obj'''
if hasattr(obj, 'name'):
return obj.name
# name proper
if hasattr(obj, '__name__'):
names = [obj.__name__]
else:
#this is a class?
names = [obj.__class__.__name__]
# pare... | Return the context qualified name of a function, method or class obj | Return the context qualified name of a function, method or class obj | [
"Return",
"the",
"context",
"qualified",
"name",
"of",
"a",
"function",
"method",
"or",
"class",
"obj"
] | def objname(obj):
if hasattr(obj, 'name'):
return obj.name
if hasattr(obj, '__name__'):
names = [obj.__name__]
else:
names = [obj.__class__.__name__]
cls = None
if six.PY2:
if hasattr(obj, 'im_class'):
cls = obj.im_class
else:
if getattr(obj, '... | [
"def",
"objname",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'name'",
")",
":",
"return",
"obj",
".",
"name",
"if",
"hasattr",
"(",
"obj",
",",
"'__name__'",
")",
":",
"names",
"=",
"[",
"obj",
".",
"__name__",
"]",
"else",
":",
"na... | Return the context qualified name of a function, method or class obj | [
"Return",
"the",
"context",
"qualified",
"name",
"of",
"a",
"function",
"method",
"or",
"class",
"obj"
] | [
"'''Return the context qualified name of a function, method or class obj'''",
"# name proper",
"#this is a class?",
"# parent class if unbound method",
"# this is a method",
"# parent class if bound method",
"# module, but ignore __main__ module"
] | [
{
"param": "obj",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "obj",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
f87412ea51ffec142c3a2f06f489d605e0f5e819 | hirp7/sana | math_functions.py | [
"MIT"
] | Python | fourier_expansion | <not_specific> | def fourier_expansion(fun,L,n):
"""
fun:a periodic function
L:interval length
n:the number of harmonics
"""
#tol = 1e-6
x = np.linspace(-L,L,100)
a0 = 1/L/2 * integrate.quad(fun,-L,L)[0]
an = 1/L * np.array([integrate.quad(lambda x:fun(x)*cos(i*x*pi/L),-L,L)[0]... |
fun:a periodic function
L:interval length
n:the number of harmonics
| a periodic function
L:interval length
n:the number of harmonics | [
"a",
"periodic",
"function",
"L",
":",
"interval",
"length",
"n",
":",
"the",
"number",
"of",
"harmonics"
] | def fourier_expansion(fun,L,n):
x = np.linspace(-L,L,100)
a0 = 1/L/2 * integrate.quad(fun,-L,L)[0]
an = 1/L * np.array([integrate.quad(lambda x:fun(x)*cos(i*x*pi/L),-L,L)[0] for i in np.arange(n)+1])
bn = 1/L * np.array([integrate.quad(lambda x:fun(x)*sin(i*x*pi/L),-L,L)[0] for i in np.arange(n)+1])
... | [
"def",
"fourier_expansion",
"(",
"fun",
",",
"L",
",",
"n",
")",
":",
"x",
"=",
"np",
".",
"linspace",
"(",
"-",
"L",
",",
"L",
",",
"100",
")",
"a0",
"=",
"1",
"/",
"L",
"/",
"2",
"*",
"integrate",
".",
"quad",
"(",
"fun",
",",
"-",
"L",
... | fun:a periodic function
L:interval length
n:the number of harmonics | [
"fun",
":",
"a",
"periodic",
"function",
"L",
":",
"interval",
"length",
"n",
":",
"the",
"number",
"of",
"harmonics"
] | [
"\"\"\"\r\n fun:a periodic function\r\n L:interval length\r\n n:the number of harmonics\r\n \"\"\"",
"#tol = 1e-6\r",
"\"\"\"\r\n c0 = 1/L/2 * integrate.quad(fun,-a,a)[0]\r\n\r\n cn = np.array([1/(L)*(integrate.quad(lambda x:fun(x)*cos(i*x*pi/L),-L,L)[0] - 1j* \\\r\n ... | [
{
"param": "fun",
"type": null
},
{
"param": "L",
"type": null
},
{
"param": "n",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "fun",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "L",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
1d34ef1b3380c39a27bddb1f881df2eec1d98522 | Vixx-X/handTracking | HandTrackingModule.py | [
"MIT"
] | Python | findHands | <not_specific> | def findHands(self, img, draw=True):
"""
Given a Image, process landmark tracking and optionally draw a skelleton
"""
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
self.results = self.hands.process(imgRGB)
if self.results.multi_hand_landmarks:
for handLms in ... |
Given a Image, process landmark tracking and optionally draw a skelleton
| Given a Image, process landmark tracking and optionally draw a skelleton | [
"Given",
"a",
"Image",
"process",
"landmark",
"tracking",
"and",
"optionally",
"draw",
"a",
"skelleton"
] | def findHands(self, img, draw=True):
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
self.results = self.hands.process(imgRGB)
if self.results.multi_hand_landmarks:
for handLms in self.results.multi_hand_landmarks:
if draw:
self.mpDraw.draw_landmarks... | [
"def",
"findHands",
"(",
"self",
",",
"img",
",",
"draw",
"=",
"True",
")",
":",
"imgRGB",
"=",
"cv2",
".",
"cvtColor",
"(",
"img",
",",
"cv2",
".",
"COLOR_BGR2RGB",
")",
"self",
".",
"results",
"=",
"self",
".",
"hands",
".",
"process",
"(",
"imgR... | Given a Image, process landmark tracking and optionally draw a skelleton | [
"Given",
"a",
"Image",
"process",
"landmark",
"tracking",
"and",
"optionally",
"draw",
"a",
"skelleton"
] | [
"\"\"\"\n Given a Image, process landmark tracking and optionally draw a skelleton\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "img",
"type": null
},
{
"param": "draw",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "img",
"type": null,
"docstring": null,
"docstring_tokens": []... |
1d34ef1b3380c39a27bddb1f881df2eec1d98522 | Vixx-X/handTracking | HandTrackingModule.py | [
"MIT"
] | Python | findPosition | <not_specific> | def findPosition(self, img, handNo=0, draw=True):
"""
Get landmarks positions (from previus findHands) and optionally redraw on landmark
"""
xList, yList, bbox = [], [], []
self.lmList = []
if self.results.multi_hand_landmarks:
myHand = self.results.multi_hand... |
Get landmarks positions (from previus findHands) and optionally redraw on landmark
| Get landmarks positions (from previus findHands) and optionally redraw on landmark | [
"Get",
"landmarks",
"positions",
"(",
"from",
"previus",
"findHands",
")",
"and",
"optionally",
"redraw",
"on",
"landmark"
] | def findPosition(self, img, handNo=0, draw=True):
xList, yList, bbox = [], [], []
self.lmList = []
if self.results.multi_hand_landmarks:
myHand = self.results.multi_hand_landmarks[handNo]
for id, lm in enumerate(myHand.landmark):
h, w, _ = img.shape
... | [
"def",
"findPosition",
"(",
"self",
",",
"img",
",",
"handNo",
"=",
"0",
",",
"draw",
"=",
"True",
")",
":",
"xList",
",",
"yList",
",",
"bbox",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"self",
".",
"lmList",
"=",
"[",
"]",
"if",
"self",
... | Get landmarks positions (from previus findHands) and optionally redraw on landmark | [
"Get",
"landmarks",
"positions",
"(",
"from",
"previus",
"findHands",
")",
"and",
"optionally",
"redraw",
"on",
"landmark"
] | [
"\"\"\"\n Get landmarks positions (from previus findHands) and optionally redraw on landmark\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "img",
"type": null
},
{
"param": "handNo",
"type": null
},
{
"param": "draw",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "img",
"type": null,
"docstring": null,
"docstring_tokens": []... |
1d34ef1b3380c39a27bddb1f881df2eec1d98522 | Vixx-X/handTracking | HandTrackingModule.py | [
"MIT"
] | Python | fingersUp | <not_specific> | def fingersUp(self):
"""
Return bool[5] weather each tip finger is on top of its pip articulation
"""
fingers = []
# Thumb
if self.lmList[self.tipIds[0]][1] < self.lmList[self.tipIds[0] - 1][1]:
fingers.append(1)
else:
fingers.append(0)
... |
Return bool[5] weather each tip finger is on top of its pip articulation
| Return bool[5] weather each tip finger is on top of its pip articulation | [
"Return",
"bool",
"[",
"5",
"]",
"weather",
"each",
"tip",
"finger",
"is",
"on",
"top",
"of",
"its",
"pip",
"articulation"
] | def fingersUp(self):
fingers = []
if self.lmList[self.tipIds[0]][1] < self.lmList[self.tipIds[0] - 1][1]:
fingers.append(1)
else:
fingers.append(0)
for id in range(1, 5):
if self.lmList[self.tipIds[id]][2] < self.lmList[self.tipIds[id] - 2][2]:
... | [
"def",
"fingersUp",
"(",
"self",
")",
":",
"fingers",
"=",
"[",
"]",
"if",
"self",
".",
"lmList",
"[",
"self",
".",
"tipIds",
"[",
"0",
"]",
"]",
"[",
"1",
"]",
"<",
"self",
".",
"lmList",
"[",
"self",
".",
"tipIds",
"[",
"0",
"]",
"-",
"1",
... | Return bool[5] weather each tip finger is on top of its pip articulation | [
"Return",
"bool",
"[",
"5",
"]",
"weather",
"each",
"tip",
"finger",
"is",
"on",
"top",
"of",
"its",
"pip",
"articulation"
] | [
"\"\"\"\n Return bool[5] weather each tip finger is on top of its pip articulation\n \"\"\"",
"# Thumb",
"# Fingers"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
1d34ef1b3380c39a27bddb1f881df2eec1d98522 | Vixx-X/handTracking | HandTrackingModule.py | [
"MIT"
] | Python | findDistance | <not_specific> | def findDistance(self, p1, p2, img, draw=True, r=15, t=3):
"""
Find distance between two tip fingers
"""
x1, y1 = self.lmList[p1][1:]
x2, y2 = self.lmList[p2][1:]
cx, cy = (x1 + x2) // 2, (y1 + y2) // 2
if draw:
cv2.line(img, (x1, y1), (x2, y2), (255... |
Find distance between two tip fingers
| Find distance between two tip fingers | [
"Find",
"distance",
"between",
"two",
"tip",
"fingers"
] | def findDistance(self, p1, p2, img, draw=True, r=15, t=3):
x1, y1 = self.lmList[p1][1:]
x2, y2 = self.lmList[p2][1:]
cx, cy = (x1 + x2) // 2, (y1 + y2) // 2
if draw:
cv2.line(img, (x1, y1), (x2, y2), (255, 0, 255), t)
cv2.circle(img, (x1, y1), r, (255, 0, 255), cv... | [
"def",
"findDistance",
"(",
"self",
",",
"p1",
",",
"p2",
",",
"img",
",",
"draw",
"=",
"True",
",",
"r",
"=",
"15",
",",
"t",
"=",
"3",
")",
":",
"x1",
",",
"y1",
"=",
"self",
".",
"lmList",
"[",
"p1",
"]",
"[",
"1",
":",
"]",
"x2",
",",... | Find distance between two tip fingers | [
"Find",
"distance",
"between",
"two",
"tip",
"fingers"
] | [
"\"\"\"\n Find distance between two tip fingers\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "p1",
"type": null
},
{
"param": "p2",
"type": null
},
{
"param": "img",
"type": null
},
{
"param": "draw",
"type": null
},
{
"param": "r",
"type": null
},
{
"param": "t",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "p1",
"type": null,
"docstring": null,
"docstring_tokens": [],... |
5dcbfa6c61cfc50797f0b8d79391fad7decc5c29 | tianyikillua/ratpmetro | ratpmetro/main.py | [
"MIT"
] | Python | load | null | def load(
self, line, number_of_tweets=3200, folder_tweets="tweets", force_download=False
):
"""
Download the tweets from the official RATP Twitter account.
Some code is adapted from https://github.com/gitlaura/get_tweets
Args:
line (int or str): RATP metro line... |
Download the tweets from the official RATP Twitter account.
Some code is adapted from https://github.com/gitlaura/get_tweets
Args:
line (int or str): RATP metro line number (1 to 14), or ``"A"``, ``"B"`` for RER lines
number_of_tweets (int): Number of tweets to downloa... | Download the tweets from the official RATP Twitter account. | [
"Download",
"the",
"tweets",
"from",
"the",
"official",
"RATP",
"Twitter",
"account",
"."
] | def load(
self, line, number_of_tweets=3200, folder_tweets="tweets", force_download=False
):
import os
username = self._twitter_account(line)
outfile = os.path.join(folder_tweets, username + ".csv")
if not os.path.isfile(outfile) or force_download:
os.makedirs(os.... | [
"def",
"load",
"(",
"self",
",",
"line",
",",
"number_of_tweets",
"=",
"3200",
",",
"folder_tweets",
"=",
"\"tweets\"",
",",
"force_download",
"=",
"False",
")",
":",
"import",
"os",
"username",
"=",
"self",
".",
"_twitter_account",
"(",
"line",
")",
"outf... | Download the tweets from the official RATP Twitter account. | [
"Download",
"the",
"tweets",
"from",
"the",
"official",
"RATP",
"Twitter",
"account",
"."
] | [
"\"\"\"\n Download the tweets from the official RATP Twitter account.\n\n Some code is adapted from https://github.com/gitlaura/get_tweets\n\n Args:\n line (int or str): RATP metro line number (1 to 14), or ``\"A\"``, ``\"B\"`` for RER lines\n number_of_tweets (int): Numbe... | [
{
"param": "self",
"type": null
},
{
"param": "line",
"type": null
},
{
"param": "number_of_tweets",
"type": null
},
{
"param": "folder_tweets",
"type": null
},
{
"param": "force_download",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "line",
"type": null,
"docstring": "RATP metro line number (1 to 14)... |
5dcbfa6c61cfc50797f0b8d79391fad7decc5c29 | tianyikillua/ratpmetro | ratpmetro/main.py | [
"MIT"
] | Python | process | null | def process(self):
"""
Process the downloaded raw data frame (using Paris time zone, identifying incidents, resampling...)
"""
assert self.df is not None
# Convert to Paris time
self.df["time"] = pd.DatetimeIndex(pd.to_datetime(self.df["time"]))
self.df = self.df... |
Process the downloaded raw data frame (using Paris time zone, identifying incidents, resampling...)
| Process the downloaded raw data frame (using Paris time zone, identifying incidents, resampling...) | [
"Process",
"the",
"downloaded",
"raw",
"data",
"frame",
"(",
"using",
"Paris",
"time",
"zone",
"identifying",
"incidents",
"resampling",
"...",
")"
] | def process(self):
assert self.df is not None
self.df["time"] = pd.DatetimeIndex(pd.to_datetime(self.df["time"]))
self.df = self.df.set_index("time")
self.df = self.df.tz_convert("Europe/Paris")
self.df = self.df.sort_index()
self.df[["is_incident", "incident_cause"]] = s... | [
"def",
"process",
"(",
"self",
")",
":",
"assert",
"self",
".",
"df",
"is",
"not",
"None",
"self",
".",
"df",
"[",
"\"time\"",
"]",
"=",
"pd",
".",
"DatetimeIndex",
"(",
"pd",
".",
"to_datetime",
"(",
"self",
".",
"df",
"[",
"\"time\"",
"]",
")",
... | Process the downloaded raw data frame (using Paris time zone, identifying incidents, resampling...) | [
"Process",
"the",
"downloaded",
"raw",
"data",
"frame",
"(",
"using",
"Paris",
"time",
"zone",
"identifying",
"incidents",
"resampling",
"...",
")"
] | [
"\"\"\"\n Process the downloaded raw data frame (using Paris time zone, identifying incidents, resampling...)\n \"\"\"",
"# Convert to Paris time",
"# Detect incidents from tweets",
"# Uniformly resample timestamps every hour and extract time information"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
5dcbfa6c61cfc50797f0b8d79391fad7decc5c29 | tianyikillua/ratpmetro | ratpmetro/main.py | [
"MIT"
] | Python | incident_prob | <not_specific> | def incident_prob(self, year=None, loc=None):
"""
Return the mean probability of incidents
Args:
year (int): If ``year`` is given then only tweets within this specific year are used, else then all downloaded tweets are used
loc (list of str): Time period from ``loc[0]`` ... |
Return the mean probability of incidents
Args:
year (int): If ``year`` is given then only tweets within this specific year are used, else then all downloaded tweets are used
loc (list of str): Time period from ``loc[0]`` to ``loc[1]``
| Return the mean probability of incidents | [
"Return",
"the",
"mean",
"probability",
"of",
"incidents"
] | def incident_prob(self, year=None, loc=None):
df = self._df_processed_loc(year=year, loc=loc)
return df["is_incident"].mean() | [
"def",
"incident_prob",
"(",
"self",
",",
"year",
"=",
"None",
",",
"loc",
"=",
"None",
")",
":",
"df",
"=",
"self",
".",
"_df_processed_loc",
"(",
"year",
"=",
"year",
",",
"loc",
"=",
"loc",
")",
"return",
"df",
"[",
"\"is_incident\"",
"]",
".",
... | Return the mean probability of incidents | [
"Return",
"the",
"mean",
"probability",
"of",
"incidents"
] | [
"\"\"\"\n Return the mean probability of incidents\n\n Args:\n year (int): If ``year`` is given then only tweets within this specific year are used, else then all downloaded tweets are used\n loc (list of str): Time period from ``loc[0]`` to ``loc[1]``\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "year",
"type": null
},
{
"param": "loc",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "year",
"type": null,
"docstring": "If ``year`` is given then only t... |
5dcbfa6c61cfc50797f0b8d79391fad7decc5c29 | tianyikillua/ratpmetro | ratpmetro/main.py | [
"MIT"
] | Python | plot_incident_cause | <not_specific> | def plot_incident_cause(self, year=None, loc=None):
"""
Plot frequencies of the main cause of incidents
Args:
year (int): If ``year`` is given then only tweets within this specific year are used, else then all downloaded tweets are used
loc (list of str): Time period fro... |
Plot frequencies of the main cause of incidents
Args:
year (int): If ``year`` is given then only tweets within this specific year are used, else then all downloaded tweets are used
loc (list of str): Time period from ``loc[0]`` to ``loc[1]``
| Plot frequencies of the main cause of incidents | [
"Plot",
"frequencies",
"of",
"the",
"main",
"cause",
"of",
"incidents"
] | def plot_incident_cause(self, year=None, loc=None):
df = self._df_processed_loc(year=year, loc=loc)
incident_cause = df["incident_cause"].value_counts().drop(["N/A"])
incident_cause.plot(kind="pie", autopct="%.0f%%")
plt.ylabel("")
return incident_cause.index, incident_cause.valu... | [
"def",
"plot_incident_cause",
"(",
"self",
",",
"year",
"=",
"None",
",",
"loc",
"=",
"None",
")",
":",
"df",
"=",
"self",
".",
"_df_processed_loc",
"(",
"year",
"=",
"year",
",",
"loc",
"=",
"loc",
")",
"incident_cause",
"=",
"df",
"[",
"\"incident_ca... | Plot frequencies of the main cause of incidents | [
"Plot",
"frequencies",
"of",
"the",
"main",
"cause",
"of",
"incidents"
] | [
"\"\"\"\n Plot frequencies of the main cause of incidents\n\n Args:\n year (int): If ``year`` is given then only tweets within this specific year are used, else then all downloaded tweets are used\n loc (list of str): Time period from ``loc[0]`` to ``loc[1]``\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "year",
"type": null
},
{
"param": "loc",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "year",
"type": null,
"docstring": "If ``year`` is given then only t... |
5dcbfa6c61cfc50797f0b8d79391fad7decc5c29 | tianyikillua/ratpmetro | ratpmetro/main.py | [
"MIT"
] | Python | plot_incident_prob | <not_specific> | def plot_incident_prob(self, by="hour", year=None, loc=None, **kwargs):
"""
Plot (marginal) probability of operational incidents
Args:
by (str): Can be "year", "month", "day", "weekday", "hour", or any two of them connected by a "-", like "hour-weekday"
year (int): If ``... |
Plot (marginal) probability of operational incidents
Args:
by (str): Can be "year", "month", "day", "weekday", "hour", or any two of them connected by a "-", like "hour-weekday"
year (int): If ``year`` is given then only tweets within this specific year are used, else then all ... | Plot (marginal) probability of operational incidents | [
"Plot",
"(",
"marginal",
")",
"probability",
"of",
"operational",
"incidents"
] | def plot_incident_prob(self, by="hour", year=None, loc=None, **kwargs):
if "year" in by:
year = None
df = self._df_processed_loc(year=year, loc=loc)
if "-" in by:
by_x, by_y = by.split("-")
assert by_x in df
assert by_y in df
else:
... | [
"def",
"plot_incident_prob",
"(",
"self",
",",
"by",
"=",
"\"hour\"",
",",
"year",
"=",
"None",
",",
"loc",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"\"year\"",
"in",
"by",
":",
"year",
"=",
"None",
"df",
"=",
"self",
".",
"_df_processed_loc... | Plot (marginal) probability of operational incidents | [
"Plot",
"(",
"marginal",
")",
"probability",
"of",
"operational",
"incidents"
] | [
"\"\"\"\n Plot (marginal) probability of operational incidents\n\n Args:\n by (str): Can be \"year\", \"month\", \"day\", \"weekday\", \"hour\", or any two of them connected by a \"-\", like \"hour-weekday\"\n year (int): If ``year`` is given then only tweets within this specific... | [
{
"param": "self",
"type": null
},
{
"param": "by",
"type": null
},
{
"param": "year",
"type": null
},
{
"param": "loc",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "by",
"type": null,
"docstring": "Can be \"year\", \"month\", \"day\... |
5dcbfa6c61cfc50797f0b8d79391fad7decc5c29 | tianyikillua/ratpmetro | ratpmetro/main.py | [
"MIT"
] | Python | _twitter_account | <not_specific> | def _twitter_account(self, line):
"""
Return the official RATP twitter account
"""
# Metro
try:
line_int = int(line)
assert 1 <= line_int <= 14
return f"Ligne{line_int:d}_RATP"
except ValueError:
# RER A or B
if ... |
Return the official RATP twitter account
| Return the official RATP twitter account | [
"Return",
"the",
"official",
"RATP",
"twitter",
"account"
] | def _twitter_account(self, line):
try:
line_int = int(line)
assert 1 <= line_int <= 14
return f"Ligne{line_int:d}_RATP"
except ValueError:
if line == "A":
return "RER_A"
elif line == "B":
return "RER_B"
... | [
"def",
"_twitter_account",
"(",
"self",
",",
"line",
")",
":",
"try",
":",
"line_int",
"=",
"int",
"(",
"line",
")",
"assert",
"1",
"<=",
"line_int",
"<=",
"14",
"return",
"f\"Ligne{line_int:d}_RATP\"",
"except",
"ValueError",
":",
"if",
"line",
"==",
"\"A... | Return the official RATP twitter account | [
"Return",
"the",
"official",
"RATP",
"twitter",
"account"
] | [
"\"\"\"\n Return the official RATP twitter account\n \"\"\"",
"# Metro",
"# RER A or B"
] | [
{
"param": "self",
"type": null
},
{
"param": "line",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "line",
"type": null,
"docstring": null,
"docstring_tokens": [... |
5dcbfa6c61cfc50797f0b8d79391fad7decc5c29 | tianyikillua/ratpmetro | ratpmetro/main.py | [
"MIT"
] | Python | _classify_incident_cause | <not_specific> | def _classify_incident_cause(self, tweet):
"""
Classify the cause of operational incident
"""
tweet = tweet.lower().strip()
for main_cause, keywords in self.incident_causes.items():
for keyword in keywords:
if keyword in tweet:
retu... |
Classify the cause of operational incident
| Classify the cause of operational incident | [
"Classify",
"the",
"cause",
"of",
"operational",
"incident"
] | def _classify_incident_cause(self, tweet):
tweet = tweet.lower().strip()
for main_cause, keywords in self.incident_causes.items():
for keyword in keywords:
if keyword in tweet:
return main_cause
else:
return self.incident_cause_other | [
"def",
"_classify_incident_cause",
"(",
"self",
",",
"tweet",
")",
":",
"tweet",
"=",
"tweet",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"for",
"main_cause",
",",
"keywords",
"in",
"self",
".",
"incident_causes",
".",
"items",
"(",
")",
":",
"for... | Classify the cause of operational incident | [
"Classify",
"the",
"cause",
"of",
"operational",
"incident"
] | [
"\"\"\"\n Classify the cause of operational incident\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "tweet",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "tweet",
"type": null,
"docstring": null,
"docstring_tokens": ... |
5dcbfa6c61cfc50797f0b8d79391fad7decc5c29 | tianyikillua/ratpmetro | ratpmetro/main.py | [
"MIT"
] | Python | _agg_incident_cause | <not_specific> | def _agg_incident_cause(self, cause):
"""
Given a list of causes found by self._classify_incident_cause,
return the most common cause (useful when resampling)
"""
cause = list(filter(("N/A").__ne__, cause)) # remove N/A
if len(cause) > 0:
return max(set(cause... |
Given a list of causes found by self._classify_incident_cause,
return the most common cause (useful when resampling)
| Given a list of causes found by self._classify_incident_cause,
return the most common cause (useful when resampling) | [
"Given",
"a",
"list",
"of",
"causes",
"found",
"by",
"self",
".",
"_classify_incident_cause",
"return",
"the",
"most",
"common",
"cause",
"(",
"useful",
"when",
"resampling",
")"
] | def _agg_incident_cause(self, cause):
cause = list(filter(("N/A").__ne__, cause))
if len(cause) > 0:
return max(set(cause), key=cause.count)
else:
return "N/A" | [
"def",
"_agg_incident_cause",
"(",
"self",
",",
"cause",
")",
":",
"cause",
"=",
"list",
"(",
"filter",
"(",
"(",
"\"N/A\"",
")",
".",
"__ne__",
",",
"cause",
")",
")",
"if",
"len",
"(",
"cause",
")",
">",
"0",
":",
"return",
"max",
"(",
"set",
"... | Given a list of causes found by self._classify_incident_cause,
return the most common cause (useful when resampling) | [
"Given",
"a",
"list",
"of",
"causes",
"found",
"by",
"self",
".",
"_classify_incident_cause",
"return",
"the",
"most",
"common",
"cause",
"(",
"useful",
"when",
"resampling",
")"
] | [
"\"\"\"\n Given a list of causes found by self._classify_incident_cause,\n return the most common cause (useful when resampling)\n \"\"\"",
"# remove N/A"
] | [
{
"param": "self",
"type": null
},
{
"param": "cause",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "cause",
"type": null,
"docstring": null,
"docstring_tokens": ... |
5dcbfa6c61cfc50797f0b8d79391fad7decc5c29 | tianyikillua/ratpmetro | ratpmetro/main.py | [
"MIT"
] | Python | _df_processed_loc | <not_specific> | def _df_processed_loc(self, year=None, loc=None):
"""
Return self.df_processed within the given year or time period
"""
assert self.df is not None
if self.df_processed is None:
self.process()
# Focus on a specific year or time period
if year is not No... |
Return self.df_processed within the given year or time period
| Return self.df_processed within the given year or time period | [
"Return",
"self",
".",
"df_processed",
"within",
"the",
"given",
"year",
"or",
"time",
"period"
] | def _df_processed_loc(self, year=None, loc=None):
assert self.df is not None
if self.df_processed is None:
self.process()
if year is not None:
df = self.df_processed.loc[f"{year}-01-01":f"{year}-12-31"]
elif loc is not None:
df = self.df_processed.loc[... | [
"def",
"_df_processed_loc",
"(",
"self",
",",
"year",
"=",
"None",
",",
"loc",
"=",
"None",
")",
":",
"assert",
"self",
".",
"df",
"is",
"not",
"None",
"if",
"self",
".",
"df_processed",
"is",
"None",
":",
"self",
".",
"process",
"(",
")",
"if",
"y... | Return self.df_processed within the given year or time period | [
"Return",
"self",
".",
"df_processed",
"within",
"the",
"given",
"year",
"or",
"time",
"period"
] | [
"\"\"\"\n Return self.df_processed within the given year or time period\n \"\"\"",
"# Focus on a specific year or time period"
] | [
{
"param": "self",
"type": null
},
{
"param": "year",
"type": null
},
{
"param": "loc",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "year",
"type": null,
"docstring": null,
"docstring_tokens": [... |
5dcbfa6c61cfc50797f0b8d79391fad7decc5c29 | tianyikillua/ratpmetro | ratpmetro/main.py | [
"MIT"
] | Python | _detect_incident | <not_specific> | def _detect_incident(self, tweet):
"""
Read a tweet message from the RATP official accounts and detect if it announces
some operational incidents
Returns:
bool: Whether the tweet corresponds to an incident
str: Cause of the incident if applicable, otherwise retur... |
Read a tweet message from the RATP official accounts and detect if it announces
some operational incidents
Returns:
bool: Whether the tweet corresponds to an incident
str: Cause of the incident if applicable, otherwise returns ``N/A``
| Read a tweet message from the RATP official accounts and detect if it announces
some operational incidents | [
"Read",
"a",
"tweet",
"message",
"from",
"the",
"RATP",
"official",
"accounts",
"and",
"detect",
"if",
"it",
"announces",
"some",
"operational",
"incidents"
] | def _detect_incident(self, tweet):
if tweet.startswith("RT"):
return pd.Series(
[False, "N/A"]
)
tweet = tweet.lower()
for word in self.incident_words:
negative_word = "n'est pas " + word
if word in tweet and negative_word not in ... | [
"def",
"_detect_incident",
"(",
"self",
",",
"tweet",
")",
":",
"if",
"tweet",
".",
"startswith",
"(",
"\"RT\"",
")",
":",
"return",
"pd",
".",
"Series",
"(",
"[",
"False",
",",
"\"N/A\"",
"]",
")",
"tweet",
"=",
"tweet",
".",
"lower",
"(",
")",
"f... | Read a tweet message from the RATP official accounts and detect if it announces
some operational incidents | [
"Read",
"a",
"tweet",
"message",
"from",
"the",
"RATP",
"official",
"accounts",
"and",
"detect",
"if",
"it",
"announces",
"some",
"operational",
"incidents"
] | [
"\"\"\"\n Read a tweet message from the RATP official accounts and detect if it announces\n some operational incidents\n\n Returns:\n bool: Whether the tweet corresponds to an incident\n str: Cause of the incident if applicable, otherwise returns ``N/A``\n \"\"\"",
... | [
{
"param": "self",
"type": null
},
{
"param": "tweet",
"type": null
}
] | {
"returns": [
{
"docstring": "Whether the tweet corresponds to an incident\nstr: Cause of the incident if applicable, otherwise returns ``N/A``",
"docstring_tokens": [
"Whether",
"the",
"tweet",
"corresponds",
"to",
"an",
"incident",
"st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.