repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
vtkiorg/vtki | vtki/pointset.py | UnstructuredGrid.extract_cells | def extract_cells(self, ind):
"""
Returns a subset of the grid
Parameters
----------
ind : np.ndarray
Numpy array of cell indices to be extracted.
Returns
-------
subgrid : vtki.UnstructuredGrid
Subselected grid
"""
if not isinstance(ind, np.ndarray):
ind = np.array(ind, np.ndarray)
if ind.dtype == np.bool:
ind = ind.nonzero()[0].astype(vtki.ID_TYPE)
if ind.dtype != vtki.ID_TYPE:
ind = ind.astype(vtki.ID_TYPE)
if not ind.flags.c_contiguous:
ind = np.ascontiguousarray(ind)
vtk_ind = numpy_to_vtkIdTypeArray(ind, deep=False)
# Create selection objects
selectionNode = vtk.vtkSelectionNode()
selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
selectionNode.SetSelectionList(vtk_ind)
selection = vtk.vtkSelection()
selection.AddNode(selectionNode)
# extract
extract_sel = vtk.vtkExtractSelection()
extract_sel.SetInputData(0, self)
extract_sel.SetInputData(1, selection)
extract_sel.Update()
subgrid = _get_output(extract_sel)
# extracts only in float32
if self.points.dtype is not np.dtype('float32'):
ind = subgrid.point_arrays['vtkOriginalPointIds']
subgrid.points = self.points[ind]
return subgrid | python | def extract_cells(self, ind):
"""
Returns a subset of the grid
Parameters
----------
ind : np.ndarray
Numpy array of cell indices to be extracted.
Returns
-------
subgrid : vtki.UnstructuredGrid
Subselected grid
"""
if not isinstance(ind, np.ndarray):
ind = np.array(ind, np.ndarray)
if ind.dtype == np.bool:
ind = ind.nonzero()[0].astype(vtki.ID_TYPE)
if ind.dtype != vtki.ID_TYPE:
ind = ind.astype(vtki.ID_TYPE)
if not ind.flags.c_contiguous:
ind = np.ascontiguousarray(ind)
vtk_ind = numpy_to_vtkIdTypeArray(ind, deep=False)
# Create selection objects
selectionNode = vtk.vtkSelectionNode()
selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
selectionNode.SetSelectionList(vtk_ind)
selection = vtk.vtkSelection()
selection.AddNode(selectionNode)
# extract
extract_sel = vtk.vtkExtractSelection()
extract_sel.SetInputData(0, self)
extract_sel.SetInputData(1, selection)
extract_sel.Update()
subgrid = _get_output(extract_sel)
# extracts only in float32
if self.points.dtype is not np.dtype('float32'):
ind = subgrid.point_arrays['vtkOriginalPointIds']
subgrid.points = self.points[ind]
return subgrid | [
"def",
"extract_cells",
"(",
"self",
",",
"ind",
")",
":",
"if",
"not",
"isinstance",
"(",
"ind",
",",
"np",
".",
"ndarray",
")",
":",
"ind",
"=",
"np",
".",
"array",
"(",
"ind",
",",
"np",
".",
"ndarray",
")",
"if",
"ind",
".",
"dtype",
"==",
... | Returns a subset of the grid
Parameters
----------
ind : np.ndarray
Numpy array of cell indices to be extracted.
Returns
-------
subgrid : vtki.UnstructuredGrid
Subselected grid | [
"Returns",
"a",
"subset",
"of",
"the",
"grid"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L2087-L2137 | train | 217,600 |
vtkiorg/vtki | vtki/pointset.py | UnstructuredGrid.merge | def merge(self, grid=None, merge_points=True, inplace=False,
main_has_priority=True):
"""
Join one or many other grids to this grid. Grid is updated
in-place by default.
Can be used to merge points of adjcent cells when no grids
are input.
Parameters
----------
grid : vtk.UnstructuredGrid or list of vtk.UnstructuredGrids
Grids to merge to this grid.
merge_points : bool, optional
Points in exactly the same location will be merged between
the two meshes.
inplace : bool, optional
Updates grid inplace when True.
main_has_priority : bool, optional
When this parameter is true and merge_points is true,
the scalar arrays of the merging grids will be overwritten
by the original main mesh.
Returns
-------
merged_grid : vtk.UnstructuredGrid
Merged grid. Returned when inplace is False.
Notes
-----
When two or more grids are joined, the type and name of each
scalar array must match or the arrays will be ignored and not
included in the final merged mesh.
"""
append_filter = vtk.vtkAppendFilter()
append_filter.SetMergePoints(merge_points)
if not main_has_priority:
append_filter.AddInputData(self)
if isinstance(grid, vtki.UnstructuredGrid):
append_filter.AddInputData(grid)
elif isinstance(grid, list):
grids = grid
for grid in grids:
append_filter.AddInputData(grid)
if main_has_priority:
append_filter.AddInputData(self)
append_filter.Update()
merged = _get_output(append_filter)
if inplace:
self.DeepCopy(merged)
else:
return merged | python | def merge(self, grid=None, merge_points=True, inplace=False,
main_has_priority=True):
"""
Join one or many other grids to this grid. Grid is updated
in-place by default.
Can be used to merge points of adjcent cells when no grids
are input.
Parameters
----------
grid : vtk.UnstructuredGrid or list of vtk.UnstructuredGrids
Grids to merge to this grid.
merge_points : bool, optional
Points in exactly the same location will be merged between
the two meshes.
inplace : bool, optional
Updates grid inplace when True.
main_has_priority : bool, optional
When this parameter is true and merge_points is true,
the scalar arrays of the merging grids will be overwritten
by the original main mesh.
Returns
-------
merged_grid : vtk.UnstructuredGrid
Merged grid. Returned when inplace is False.
Notes
-----
When two or more grids are joined, the type and name of each
scalar array must match or the arrays will be ignored and not
included in the final merged mesh.
"""
append_filter = vtk.vtkAppendFilter()
append_filter.SetMergePoints(merge_points)
if not main_has_priority:
append_filter.AddInputData(self)
if isinstance(grid, vtki.UnstructuredGrid):
append_filter.AddInputData(grid)
elif isinstance(grid, list):
grids = grid
for grid in grids:
append_filter.AddInputData(grid)
if main_has_priority:
append_filter.AddInputData(self)
append_filter.Update()
merged = _get_output(append_filter)
if inplace:
self.DeepCopy(merged)
else:
return merged | [
"def",
"merge",
"(",
"self",
",",
"grid",
"=",
"None",
",",
"merge_points",
"=",
"True",
",",
"inplace",
"=",
"False",
",",
"main_has_priority",
"=",
"True",
")",
":",
"append_filter",
"=",
"vtk",
".",
"vtkAppendFilter",
"(",
")",
"append_filter",
".",
"... | Join one or many other grids to this grid. Grid is updated
in-place by default.
Can be used to merge points of adjcent cells when no grids
are input.
Parameters
----------
grid : vtk.UnstructuredGrid or list of vtk.UnstructuredGrids
Grids to merge to this grid.
merge_points : bool, optional
Points in exactly the same location will be merged between
the two meshes.
inplace : bool, optional
Updates grid inplace when True.
main_has_priority : bool, optional
When this parameter is true and merge_points is true,
the scalar arrays of the merging grids will be overwritten
by the original main mesh.
Returns
-------
merged_grid : vtk.UnstructuredGrid
Merged grid. Returned when inplace is False.
Notes
-----
When two or more grids are joined, the type and name of each
scalar array must match or the arrays will be ignored and not
included in the final merged mesh. | [
"Join",
"one",
"or",
"many",
"other",
"grids",
"to",
"this",
"grid",
".",
"Grid",
"is",
"updated",
"in",
"-",
"place",
"by",
"default",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L2175-L2233 | train | 217,601 |
vtkiorg/vtki | vtki/pointset.py | UnstructuredGrid.delaunay_2d | def delaunay_2d(self, tol=1e-05, alpha=0.0, offset=1.0, bound=False):
"""Apply a delaunay 2D filter along the best fitting plane. This
extracts the grid's points and perfoms the triangulation on those alone.
"""
return PolyData(self.points).delaunay_2d(tol=tol, alpha=alpha, offset=offset, bound=bound) | python | def delaunay_2d(self, tol=1e-05, alpha=0.0, offset=1.0, bound=False):
"""Apply a delaunay 2D filter along the best fitting plane. This
extracts the grid's points and perfoms the triangulation on those alone.
"""
return PolyData(self.points).delaunay_2d(tol=tol, alpha=alpha, offset=offset, bound=bound) | [
"def",
"delaunay_2d",
"(",
"self",
",",
"tol",
"=",
"1e-05",
",",
"alpha",
"=",
"0.0",
",",
"offset",
"=",
"1.0",
",",
"bound",
"=",
"False",
")",
":",
"return",
"PolyData",
"(",
"self",
".",
"points",
")",
".",
"delaunay_2d",
"(",
"tol",
"=",
"tol... | Apply a delaunay 2D filter along the best fitting plane. This
extracts the grid's points and perfoms the triangulation on those alone. | [
"Apply",
"a",
"delaunay",
"2D",
"filter",
"along",
"the",
"best",
"fitting",
"plane",
".",
"This",
"extracts",
"the",
"grid",
"s",
"points",
"and",
"perfoms",
"the",
"triangulation",
"on",
"those",
"alone",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L2235-L2239 | train | 217,602 |
vtkiorg/vtki | vtki/pointset.py | StructuredGrid._from_arrays | def _from_arrays(self, x, y, z):
"""
Create VTK structured grid directly from numpy arrays.
Parameters
----------
x : np.ndarray
Position of the points in x direction.
y : np.ndarray
Position of the points in y direction.
z : np.ndarray
Position of the points in z direction.
"""
if not(x.shape == y.shape == z.shape):
raise Exception('Input point array shapes must match exactly')
# make the output points the same precision as the input arrays
points = np.empty((x.size, 3), x.dtype)
points[:, 0] = x.ravel('F')
points[:, 1] = y.ravel('F')
points[:, 2] = z.ravel('F')
# ensure that the inputs are 3D
dim = list(x.shape)
while len(dim) < 3:
dim.append(1)
# Create structured grid
self.SetDimensions(dim)
self.SetPoints(vtki.vtk_points(points)) | python | def _from_arrays(self, x, y, z):
"""
Create VTK structured grid directly from numpy arrays.
Parameters
----------
x : np.ndarray
Position of the points in x direction.
y : np.ndarray
Position of the points in y direction.
z : np.ndarray
Position of the points in z direction.
"""
if not(x.shape == y.shape == z.shape):
raise Exception('Input point array shapes must match exactly')
# make the output points the same precision as the input arrays
points = np.empty((x.size, 3), x.dtype)
points[:, 0] = x.ravel('F')
points[:, 1] = y.ravel('F')
points[:, 2] = z.ravel('F')
# ensure that the inputs are 3D
dim = list(x.shape)
while len(dim) < 3:
dim.append(1)
# Create structured grid
self.SetDimensions(dim)
self.SetPoints(vtki.vtk_points(points)) | [
"def",
"_from_arrays",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
")",
":",
"if",
"not",
"(",
"x",
".",
"shape",
"==",
"y",
".",
"shape",
"==",
"z",
".",
"shape",
")",
":",
"raise",
"Exception",
"(",
"'Input point array shapes must match exactly'",
")"... | Create VTK structured grid directly from numpy arrays.
Parameters
----------
x : np.ndarray
Position of the points in x direction.
y : np.ndarray
Position of the points in y direction.
z : np.ndarray
Position of the points in z direction. | [
"Create",
"VTK",
"structured",
"grid",
"directly",
"from",
"numpy",
"arrays",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L2303-L2334 | train | 217,603 |
vtkiorg/vtki | vtki/pointset.py | StructuredGrid.save | def save(self, filename, binary=True):
"""
Writes a structured grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
".vts" will select the VTK XML writer.
binary : bool, optional
Writes as a binary file by default. Set to False to write ASCII.
Notes
-----
Binary files write much faster than ASCII, but binary files written on
one system may not be readable on other systems. Binary can be used
only with the legacy writer.
"""
filename = os.path.abspath(os.path.expanduser(filename))
# Use legacy writer if vtk is in filename
if '.vtk' in filename:
writer = vtk.vtkStructuredGridWriter()
if binary:
writer.SetFileTypeToBinary()
else:
writer.SetFileTypeToASCII()
elif '.vts' in filename:
writer = vtk.vtkXMLStructuredGridWriter()
if binary:
writer.SetDataModeToBinary()
else:
writer.SetDataModeToAscii()
else:
raise Exception('Extension should be either ".vts" (xml) or' +
'".vtk" (legacy)')
# Write
writer.SetFileName(filename)
writer.SetInputData(self)
writer.Write() | python | def save(self, filename, binary=True):
"""
Writes a structured grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
".vts" will select the VTK XML writer.
binary : bool, optional
Writes as a binary file by default. Set to False to write ASCII.
Notes
-----
Binary files write much faster than ASCII, but binary files written on
one system may not be readable on other systems. Binary can be used
only with the legacy writer.
"""
filename = os.path.abspath(os.path.expanduser(filename))
# Use legacy writer if vtk is in filename
if '.vtk' in filename:
writer = vtk.vtkStructuredGridWriter()
if binary:
writer.SetFileTypeToBinary()
else:
writer.SetFileTypeToASCII()
elif '.vts' in filename:
writer = vtk.vtkXMLStructuredGridWriter()
if binary:
writer.SetDataModeToBinary()
else:
writer.SetDataModeToAscii()
else:
raise Exception('Extension should be either ".vts" (xml) or' +
'".vtk" (legacy)')
# Write
writer.SetFileName(filename)
writer.SetInputData(self)
writer.Write() | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"binary",
"=",
"True",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
")",
"# Use legacy writer if vtk is in filename",
"if",
... | Writes a structured grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
".vts" will select the VTK XML writer.
binary : bool, optional
Writes as a binary file by default. Set to False to write ASCII.
Notes
-----
Binary files write much faster than ASCII, but binary files written on
one system may not be readable on other systems. Binary can be used
only with the legacy writer. | [
"Writes",
"a",
"structured",
"grid",
"to",
"disk",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L2376-L2418 | train | 217,604 |
vtkiorg/vtki | vtki/pointset.py | StructuredGrid.dimensions | def dimensions(self, dims):
"""Sets the dataset dimensions. Pass a length three tuple of integers"""
nx, ny, nz = dims[0], dims[1], dims[2]
self.SetDimensions(nx, ny, nz)
self.Modified() | python | def dimensions(self, dims):
"""Sets the dataset dimensions. Pass a length three tuple of integers"""
nx, ny, nz = dims[0], dims[1], dims[2]
self.SetDimensions(nx, ny, nz)
self.Modified() | [
"def",
"dimensions",
"(",
"self",
",",
"dims",
")",
":",
"nx",
",",
"ny",
",",
"nz",
"=",
"dims",
"[",
"0",
"]",
",",
"dims",
"[",
"1",
"]",
",",
"dims",
"[",
"2",
"]",
"self",
".",
"SetDimensions",
"(",
"nx",
",",
"ny",
",",
"nz",
")",
"se... | Sets the dataset dimensions. Pass a length three tuple of integers | [
"Sets",
"the",
"dataset",
"dimensions",
".",
"Pass",
"a",
"length",
"three",
"tuple",
"of",
"integers"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L2426-L2430 | train | 217,605 |
vtkiorg/vtki | vtki/grid.py | RectilinearGrid._from_arrays | def _from_arrays(self, x, y, z):
"""
Create VTK rectilinear grid directly from numpy arrays. Each array
gives the uniques coordinates of the mesh along each axial direction.
To help ensure you are using this correctly, we take the unique values
of each argument.
Parameters
----------
x : np.ndarray
Coordinates of the nodes in x direction.
y : np.ndarray
Coordinates of the nodes in y direction.
z : np.ndarray
Coordinates of the nodes in z direction.
"""
x = np.unique(x.ravel())
y = np.unique(y.ravel())
z = np.unique(z.ravel())
# Set the cell spacings and dimensions of the grid
self.SetDimensions(len(x), len(y), len(z))
self.SetXCoordinates(numpy_to_vtk(x))
self.SetYCoordinates(numpy_to_vtk(y))
self.SetZCoordinates(numpy_to_vtk(z)) | python | def _from_arrays(self, x, y, z):
"""
Create VTK rectilinear grid directly from numpy arrays. Each array
gives the uniques coordinates of the mesh along each axial direction.
To help ensure you are using this correctly, we take the unique values
of each argument.
Parameters
----------
x : np.ndarray
Coordinates of the nodes in x direction.
y : np.ndarray
Coordinates of the nodes in y direction.
z : np.ndarray
Coordinates of the nodes in z direction.
"""
x = np.unique(x.ravel())
y = np.unique(y.ravel())
z = np.unique(z.ravel())
# Set the cell spacings and dimensions of the grid
self.SetDimensions(len(x), len(y), len(z))
self.SetXCoordinates(numpy_to_vtk(x))
self.SetYCoordinates(numpy_to_vtk(y))
self.SetZCoordinates(numpy_to_vtk(z)) | [
"def",
"_from_arrays",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
")",
":",
"x",
"=",
"np",
".",
"unique",
"(",
"x",
".",
"ravel",
"(",
")",
")",
"y",
"=",
"np",
".",
"unique",
"(",
"y",
".",
"ravel",
"(",
")",
")",
"z",
"=",
"np",
".",
... | Create VTK rectilinear grid directly from numpy arrays. Each array
gives the uniques coordinates of the mesh along each axial direction.
To help ensure you are using this correctly, we take the unique values
of each argument.
Parameters
----------
x : np.ndarray
Coordinates of the nodes in x direction.
y : np.ndarray
Coordinates of the nodes in y direction.
z : np.ndarray
Coordinates of the nodes in z direction. | [
"Create",
"VTK",
"rectilinear",
"grid",
"directly",
"from",
"numpy",
"arrays",
".",
"Each",
"array",
"gives",
"the",
"uniques",
"coordinates",
"of",
"the",
"mesh",
"along",
"each",
"axial",
"direction",
".",
"To",
"help",
"ensure",
"you",
"are",
"using",
"th... | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/grid.py#L108-L133 | train | 217,606 |
vtkiorg/vtki | vtki/grid.py | RectilinearGrid._load_file | def _load_file(self, filename):
"""
Load a rectilinear grid from a file.
The file extension will select the type of reader to use. A .vtk
extension will use the legacy reader, while .vtr will select the VTK
XML reader.
Parameters
----------
filename : str
Filename of grid to be loaded.
"""
filename = os.path.abspath(os.path.expanduser(filename))
# check file exists
if not os.path.isfile(filename):
raise Exception('{} does not exist'.format(filename))
# Check file extention
if '.vtr' in filename:
legacy_writer = False
elif '.vtk' in filename:
legacy_writer = True
else:
raise Exception(
'Extension should be either ".vtr" (xml) or ".vtk" (legacy)')
# Create reader
if legacy_writer:
reader = vtk.vtkRectilinearGridReader()
else:
reader = vtk.vtkXMLRectilinearGridReader()
# load file to self
reader.SetFileName(filename)
reader.Update()
grid = reader.GetOutput()
self.ShallowCopy(grid) | python | def _load_file(self, filename):
"""
Load a rectilinear grid from a file.
The file extension will select the type of reader to use. A .vtk
extension will use the legacy reader, while .vtr will select the VTK
XML reader.
Parameters
----------
filename : str
Filename of grid to be loaded.
"""
filename = os.path.abspath(os.path.expanduser(filename))
# check file exists
if not os.path.isfile(filename):
raise Exception('{} does not exist'.format(filename))
# Check file extention
if '.vtr' in filename:
legacy_writer = False
elif '.vtk' in filename:
legacy_writer = True
else:
raise Exception(
'Extension should be either ".vtr" (xml) or ".vtk" (legacy)')
# Create reader
if legacy_writer:
reader = vtk.vtkRectilinearGridReader()
else:
reader = vtk.vtkXMLRectilinearGridReader()
# load file to self
reader.SetFileName(filename)
reader.Update()
grid = reader.GetOutput()
self.ShallowCopy(grid) | [
"def",
"_load_file",
"(",
"self",
",",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
")",
"# check file exists",
"if",
"not",
"os",
".",
"path",
".",
"isfile",... | Load a rectilinear grid from a file.
The file extension will select the type of reader to use. A .vtk
extension will use the legacy reader, while .vtr will select the VTK
XML reader.
Parameters
----------
filename : str
Filename of grid to be loaded. | [
"Load",
"a",
"rectilinear",
"grid",
"from",
"a",
"file",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/grid.py#L160-L198 | train | 217,607 |
vtkiorg/vtki | vtki/grid.py | RectilinearGrid.save | def save(self, filename, binary=True):
"""
Writes a rectilinear grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
".vtr" will select the VTK XML writer.
binary : bool, optional
Writes as a binary file by default. Set to False to write ASCII.
Notes
-----
Binary files write much faster than ASCII, but binary files written on
one system may not be readable on other systems. Binary can be used
only with the legacy writer.
"""
filename = os.path.abspath(os.path.expanduser(filename))
# Use legacy writer if vtk is in filename
if '.vtk' in filename:
writer = vtk.vtkRectilinearGridWriter()
legacy = True
elif '.vtr' in filename:
writer = vtk.vtkXMLRectilinearGridWriter()
legacy = False
else:
raise Exception('Extension should be either ".vtr" (xml) or' +
'".vtk" (legacy)')
# Write
writer.SetFileName(filename)
writer.SetInputData(self)
if binary and legacy:
writer.SetFileTypeToBinary()
writer.Write() | python | def save(self, filename, binary=True):
"""
Writes a rectilinear grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
".vtr" will select the VTK XML writer.
binary : bool, optional
Writes as a binary file by default. Set to False to write ASCII.
Notes
-----
Binary files write much faster than ASCII, but binary files written on
one system may not be readable on other systems. Binary can be used
only with the legacy writer.
"""
filename = os.path.abspath(os.path.expanduser(filename))
# Use legacy writer if vtk is in filename
if '.vtk' in filename:
writer = vtk.vtkRectilinearGridWriter()
legacy = True
elif '.vtr' in filename:
writer = vtk.vtkXMLRectilinearGridWriter()
legacy = False
else:
raise Exception('Extension should be either ".vtr" (xml) or' +
'".vtk" (legacy)')
# Write
writer.SetFileName(filename)
writer.SetInputData(self)
if binary and legacy:
writer.SetFileTypeToBinary()
writer.Write() | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"binary",
"=",
"True",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
")",
"# Use legacy writer if vtk is in filename",
"if",
... | Writes a rectilinear grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
".vtr" will select the VTK XML writer.
binary : bool, optional
Writes as a binary file by default. Set to False to write ASCII.
Notes
-----
Binary files write much faster than ASCII, but binary files written on
one system may not be readable on other systems. Binary can be used
only with the legacy writer. | [
"Writes",
"a",
"rectilinear",
"grid",
"to",
"disk",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/grid.py#L200-L238 | train | 217,608 |
vtkiorg/vtki | vtki/grid.py | UniformGrid.origin | def origin(self, origin):
"""Set the origin. Pass a length three tuple of floats"""
ox, oy, oz = origin[0], origin[1], origin[2]
self.SetOrigin(ox, oy, oz)
self.Modified() | python | def origin(self, origin):
"""Set the origin. Pass a length three tuple of floats"""
ox, oy, oz = origin[0], origin[1], origin[2]
self.SetOrigin(ox, oy, oz)
self.Modified() | [
"def",
"origin",
"(",
"self",
",",
"origin",
")",
":",
"ox",
",",
"oy",
",",
"oz",
"=",
"origin",
"[",
"0",
"]",
",",
"origin",
"[",
"1",
"]",
",",
"origin",
"[",
"2",
"]",
"self",
".",
"SetOrigin",
"(",
"ox",
",",
"oy",
",",
"oz",
")",
"se... | Set the origin. Pass a length three tuple of floats | [
"Set",
"the",
"origin",
".",
"Pass",
"a",
"length",
"three",
"tuple",
"of",
"floats"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/grid.py#L533-L537 | train | 217,609 |
vtkiorg/vtki | vtki/grid.py | UniformGrid.spacing | def spacing(self, spacing):
"""Set the spacing in each axial direction. Pass a length three tuple of
floats"""
dx, dy, dz = spacing[0], spacing[1], spacing[2]
self.SetSpacing(dx, dy, dz)
self.Modified() | python | def spacing(self, spacing):
"""Set the spacing in each axial direction. Pass a length three tuple of
floats"""
dx, dy, dz = spacing[0], spacing[1], spacing[2]
self.SetSpacing(dx, dy, dz)
self.Modified() | [
"def",
"spacing",
"(",
"self",
",",
"spacing",
")",
":",
"dx",
",",
"dy",
",",
"dz",
"=",
"spacing",
"[",
"0",
"]",
",",
"spacing",
"[",
"1",
"]",
",",
"spacing",
"[",
"2",
"]",
"self",
".",
"SetSpacing",
"(",
"dx",
",",
"dy",
",",
"dz",
")",... | Set the spacing in each axial direction. Pass a length three tuple of
floats | [
"Set",
"the",
"spacing",
"in",
"each",
"axial",
"direction",
".",
"Pass",
"a",
"length",
"three",
"tuple",
"of",
"floats"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/grid.py#L545-L550 | train | 217,610 |
vtkiorg/vtki | vtki/qt_plotting.py | resample_image | def resample_image(arr, max_size=400):
"""Resamples a square image to an image of max_size"""
dim = np.max(arr.shape[0:2])
if dim < max_size:
max_size = dim
x, y, _ = arr.shape
sx = int(np.ceil(x / max_size))
sy = int(np.ceil(y / max_size))
img = np.zeros((max_size, max_size, 3), dtype=arr.dtype)
arr = arr[0:-1:sx, 0:-1:sy, :]
xl = (max_size - arr.shape[0]) // 2
yl = (max_size - arr.shape[1]) // 2
img[xl:arr.shape[0]+xl, yl:arr.shape[1]+yl, :] = arr
return img | python | def resample_image(arr, max_size=400):
"""Resamples a square image to an image of max_size"""
dim = np.max(arr.shape[0:2])
if dim < max_size:
max_size = dim
x, y, _ = arr.shape
sx = int(np.ceil(x / max_size))
sy = int(np.ceil(y / max_size))
img = np.zeros((max_size, max_size, 3), dtype=arr.dtype)
arr = arr[0:-1:sx, 0:-1:sy, :]
xl = (max_size - arr.shape[0]) // 2
yl = (max_size - arr.shape[1]) // 2
img[xl:arr.shape[0]+xl, yl:arr.shape[1]+yl, :] = arr
return img | [
"def",
"resample_image",
"(",
"arr",
",",
"max_size",
"=",
"400",
")",
":",
"dim",
"=",
"np",
".",
"max",
"(",
"arr",
".",
"shape",
"[",
"0",
":",
"2",
"]",
")",
"if",
"dim",
"<",
"max_size",
":",
"max_size",
"=",
"dim",
"x",
",",
"y",
",",
"... | Resamples a square image to an image of max_size | [
"Resamples",
"a",
"square",
"image",
"to",
"an",
"image",
"of",
"max_size"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L229-L242 | train | 217,611 |
vtkiorg/vtki | vtki/qt_plotting.py | pad_image | def pad_image(arr, max_size=400):
"""Pads an image to a square then resamples to max_size"""
dim = np.max(arr.shape)
img = np.zeros((dim, dim, 3), dtype=arr.dtype)
xl = (dim - arr.shape[0]) // 2
yl = (dim - arr.shape[1]) // 2
img[xl:arr.shape[0]+xl, yl:arr.shape[1]+yl, :] = arr
return resample_image(img, max_size=max_size) | python | def pad_image(arr, max_size=400):
"""Pads an image to a square then resamples to max_size"""
dim = np.max(arr.shape)
img = np.zeros((dim, dim, 3), dtype=arr.dtype)
xl = (dim - arr.shape[0]) // 2
yl = (dim - arr.shape[1]) // 2
img[xl:arr.shape[0]+xl, yl:arr.shape[1]+yl, :] = arr
return resample_image(img, max_size=max_size) | [
"def",
"pad_image",
"(",
"arr",
",",
"max_size",
"=",
"400",
")",
":",
"dim",
"=",
"np",
".",
"max",
"(",
"arr",
".",
"shape",
")",
"img",
"=",
"np",
".",
"zeros",
"(",
"(",
"dim",
",",
"dim",
",",
"3",
")",
",",
"dtype",
"=",
"arr",
".",
"... | Pads an image to a square then resamples to max_size | [
"Pads",
"an",
"image",
"to",
"a",
"square",
"then",
"resamples",
"to",
"max_size"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L245-L252 | train | 217,612 |
vtkiorg/vtki | vtki/qt_plotting.py | FileDialog.emit_accepted | def emit_accepted(self):
"""
Sends signal that the file dialog was closed properly.
Sends:
filename
"""
if self.result():
filename = self.selectedFiles()[0]
if os.path.isdir(os.path.dirname(filename)):
self.dlg_accepted.emit(filename) | python | def emit_accepted(self):
"""
Sends signal that the file dialog was closed properly.
Sends:
filename
"""
if self.result():
filename = self.selectedFiles()[0]
if os.path.isdir(os.path.dirname(filename)):
self.dlg_accepted.emit(filename) | [
"def",
"emit_accepted",
"(",
"self",
")",
":",
"if",
"self",
".",
"result",
"(",
")",
":",
"filename",
"=",
"self",
".",
"selectedFiles",
"(",
")",
"[",
"0",
"]",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",... | Sends signal that the file dialog was closed properly.
Sends:
filename | [
"Sends",
"signal",
"that",
"the",
"file",
"dialog",
"was",
"closed",
"properly",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L92-L102 | train | 217,613 |
vtkiorg/vtki | vtki/qt_plotting.py | ScaleAxesDialog.update_scale | def update_scale(self, value):
""" updates the scale of all actors in the plotter """
self.plotter.set_scale(self.x_slider_group.value,
self.y_slider_group.value,
self.z_slider_group.value) | python | def update_scale(self, value):
""" updates the scale of all actors in the plotter """
self.plotter.set_scale(self.x_slider_group.value,
self.y_slider_group.value,
self.z_slider_group.value) | [
"def",
"update_scale",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"plotter",
".",
"set_scale",
"(",
"self",
".",
"x_slider_group",
".",
"value",
",",
"self",
".",
"y_slider_group",
".",
"value",
",",
"self",
".",
"z_slider_group",
".",
"value",
")... | updates the scale of all actors in the plotter | [
"updates",
"the",
"scale",
"of",
"all",
"actors",
"in",
"the",
"plotter"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L222-L226 | train | 217,614 |
vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter.scale_axes_dialog | def scale_axes_dialog(self, show=True):
""" Open scale axes dialog """
return ScaleAxesDialog(self.app_window, self, show=show) | python | def scale_axes_dialog(self, show=True):
""" Open scale axes dialog """
return ScaleAxesDialog(self.app_window, self, show=show) | [
"def",
"scale_axes_dialog",
"(",
"self",
",",
"show",
"=",
"True",
")",
":",
"return",
"ScaleAxesDialog",
"(",
"self",
".",
"app_window",
",",
"self",
",",
"show",
"=",
"show",
")"
] | Open scale axes dialog | [
"Open",
"scale",
"axes",
"dialog"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L418-L420 | train | 217,615 |
vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter.clear_camera_positions | def clear_camera_positions(self):
""" clears all camera positions """
for action in self.saved_camera_menu.actions():
self.saved_camera_menu.removeAction(action) | python | def clear_camera_positions(self):
""" clears all camera positions """
for action in self.saved_camera_menu.actions():
self.saved_camera_menu.removeAction(action) | [
"def",
"clear_camera_positions",
"(",
"self",
")",
":",
"for",
"action",
"in",
"self",
".",
"saved_camera_menu",
".",
"actions",
"(",
")",
":",
"self",
".",
"saved_camera_menu",
".",
"removeAction",
"(",
"action",
")"
] | clears all camera positions | [
"clears",
"all",
"camera",
"positions"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L422-L425 | train | 217,616 |
vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter.save_camera_position | def save_camera_position(self):
""" Saves camera position to saved camera menu for recall """
self.saved_camera_positions.append(self.camera_position)
ncam = len(self.saved_camera_positions)
camera_position = self.camera_position[:] # py2.7 copy compatibility
def load_camera_position():
self.camera_position = camera_position
self.saved_camera_menu.addAction('Camera Position %2d' % ncam,
load_camera_position) | python | def save_camera_position(self):
""" Saves camera position to saved camera menu for recall """
self.saved_camera_positions.append(self.camera_position)
ncam = len(self.saved_camera_positions)
camera_position = self.camera_position[:] # py2.7 copy compatibility
def load_camera_position():
self.camera_position = camera_position
self.saved_camera_menu.addAction('Camera Position %2d' % ncam,
load_camera_position) | [
"def",
"save_camera_position",
"(",
"self",
")",
":",
"self",
".",
"saved_camera_positions",
".",
"append",
"(",
"self",
".",
"camera_position",
")",
"ncam",
"=",
"len",
"(",
"self",
".",
"saved_camera_positions",
")",
"camera_position",
"=",
"self",
".",
"cam... | Saves camera position to saved camera menu for recall | [
"Saves",
"camera",
"position",
"to",
"saved",
"camera",
"menu",
"for",
"recall"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L427-L437 | train | 217,617 |
vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter._spawn_background_rendering | def _spawn_background_rendering(self, rate=5.0):
"""
Spawns a thread that updates the render window.
Sometimes directly modifiying object data doesn't trigger
Modified() and upstream objects won't be updated. This
ensures the render window stays updated without consuming too
many resources.
"""
self.render_trigger.connect(self.ren_win.Render)
twait = rate**-1
def render():
while self.active:
time.sleep(twait)
self._render()
self.render_thread = Thread(target=render)
self.render_thread.start() | python | def _spawn_background_rendering(self, rate=5.0):
"""
Spawns a thread that updates the render window.
Sometimes directly modifiying object data doesn't trigger
Modified() and upstream objects won't be updated. This
ensures the render window stays updated without consuming too
many resources.
"""
self.render_trigger.connect(self.ren_win.Render)
twait = rate**-1
def render():
while self.active:
time.sleep(twait)
self._render()
self.render_thread = Thread(target=render)
self.render_thread.start() | [
"def",
"_spawn_background_rendering",
"(",
"self",
",",
"rate",
"=",
"5.0",
")",
":",
"self",
".",
"render_trigger",
".",
"connect",
"(",
"self",
".",
"ren_win",
".",
"Render",
")",
"twait",
"=",
"rate",
"**",
"-",
"1",
"def",
"render",
"(",
")",
":",
... | Spawns a thread that updates the render window.
Sometimes directly modifiying object data doesn't trigger
Modified() and upstream objects won't be updated. This
ensures the render window stays updated without consuming too
many resources. | [
"Spawns",
"a",
"thread",
"that",
"updates",
"the",
"render",
"window",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L439-L457 | train | 217,618 |
vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter.update_app_icon | def update_app_icon(self):
"""
Update the app icon if the user is not trying to resize the window.
"""
if os.name == 'nt' or not hasattr(self, '_last_window_size'): # pragma: no cover
# DO NOT EVEN ATTEMPT TO UPDATE ICON ON WINDOWS
return
cur_time = time.time()
if self._last_window_size != self.window_size: # pragma: no cover
# Window size hasn't remained constant since last render.
# This means the user is resizing it so ignore update.
pass
elif ((cur_time - self._last_update_time > BackgroundPlotter.ICON_TIME_STEP)
and self._last_camera_pos != self.camera_position):
# its been a while since last update OR
# the camera position has changed and its been at leat one second
# Update app icon as preview of the window
img = pad_image(self.image)
qimage = QtGui.QImage(img.copy(), img.shape[1],
img.shape[0], QtGui.QImage.Format_RGB888)
icon = QtGui.QIcon(QtGui.QPixmap.fromImage(qimage))
self.app.setWindowIcon(icon)
# Update trackers
self._last_update_time = cur_time
self._last_camera_pos = self.camera_position
# Update trackers
self._last_window_size = self.window_size | python | def update_app_icon(self):
"""
Update the app icon if the user is not trying to resize the window.
"""
if os.name == 'nt' or not hasattr(self, '_last_window_size'): # pragma: no cover
# DO NOT EVEN ATTEMPT TO UPDATE ICON ON WINDOWS
return
cur_time = time.time()
if self._last_window_size != self.window_size: # pragma: no cover
# Window size hasn't remained constant since last render.
# This means the user is resizing it so ignore update.
pass
elif ((cur_time - self._last_update_time > BackgroundPlotter.ICON_TIME_STEP)
and self._last_camera_pos != self.camera_position):
# its been a while since last update OR
# the camera position has changed and its been at leat one second
# Update app icon as preview of the window
img = pad_image(self.image)
qimage = QtGui.QImage(img.copy(), img.shape[1],
img.shape[0], QtGui.QImage.Format_RGB888)
icon = QtGui.QIcon(QtGui.QPixmap.fromImage(qimage))
self.app.setWindowIcon(icon)
# Update trackers
self._last_update_time = cur_time
self._last_camera_pos = self.camera_position
# Update trackers
self._last_window_size = self.window_size | [
"def",
"update_app_icon",
"(",
"self",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
"or",
"not",
"hasattr",
"(",
"self",
",",
"'_last_window_size'",
")",
":",
"# pragma: no cover",
"# DO NOT EVEN ATTEMPT TO UPDATE ICON ON WINDOWS",
"return",
"cur_time",
"=",
"... | Update the app icon if the user is not trying to resize the window. | [
"Update",
"the",
"app",
"icon",
"if",
"the",
"user",
"is",
"not",
"trying",
"to",
"resize",
"the",
"window",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L472-L501 | train | 217,619 |
vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter._qt_export_vtkjs | def _qt_export_vtkjs(self, show=True):
"""
Spawn an save file dialog to export a vtkjs file.
"""
return FileDialog(self.app_window,
filefilter=['VTK JS File(*.vtkjs)'],
show=show,
directory=os.getcwd(),
callback=self.export_vtkjs) | python | def _qt_export_vtkjs(self, show=True):
"""
Spawn an save file dialog to export a vtkjs file.
"""
return FileDialog(self.app_window,
filefilter=['VTK JS File(*.vtkjs)'],
show=show,
directory=os.getcwd(),
callback=self.export_vtkjs) | [
"def",
"_qt_export_vtkjs",
"(",
"self",
",",
"show",
"=",
"True",
")",
":",
"return",
"FileDialog",
"(",
"self",
".",
"app_window",
",",
"filefilter",
"=",
"[",
"'VTK JS File(*.vtkjs)'",
"]",
",",
"show",
"=",
"show",
",",
"directory",
"=",
"os",
".",
"g... | Spawn an save file dialog to export a vtkjs file. | [
"Spawn",
"an",
"save",
"file",
"dialog",
"to",
"export",
"a",
"vtkjs",
"file",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L511-L519 | train | 217,620 |
vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter.window_size | def window_size(self):
""" returns render window size """
the_size = self.app_window.baseSize()
return the_size.width(), the_size.height() | python | def window_size(self):
""" returns render window size """
the_size = self.app_window.baseSize()
return the_size.width(), the_size.height() | [
"def",
"window_size",
"(",
"self",
")",
":",
"the_size",
"=",
"self",
".",
"app_window",
".",
"baseSize",
"(",
")",
"return",
"the_size",
".",
"width",
"(",
")",
",",
"the_size",
".",
"height",
"(",
")"
] | returns render window size | [
"returns",
"render",
"window",
"size"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L532-L535 | train | 217,621 |
vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter.window_size | def window_size(self, window_size):
""" set the render window size """
BasePlotter.window_size.fset(self, window_size)
self.app_window.setBaseSize(*window_size) | python | def window_size(self, window_size):
""" set the render window size """
BasePlotter.window_size.fset(self, window_size)
self.app_window.setBaseSize(*window_size) | [
"def",
"window_size",
"(",
"self",
",",
"window_size",
")",
":",
"BasePlotter",
".",
"window_size",
".",
"fset",
"(",
"self",
",",
"window_size",
")",
"self",
".",
"app_window",
".",
"setBaseSize",
"(",
"*",
"window_size",
")"
] | set the render window size | [
"set",
"the",
"render",
"window",
"size"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L539-L542 | train | 217,622 |
vtkiorg/vtki | vtki/colors.py | hex_to_rgb | def hex_to_rgb(h):
""" Returns 0 to 1 rgb from a hex list or tuple """
h = h.lstrip('#')
return tuple(int(h[i:i+2], 16)/255. for i in (0, 2 ,4)) | python | def hex_to_rgb(h):
""" Returns 0 to 1 rgb from a hex list or tuple """
h = h.lstrip('#')
return tuple(int(h[i:i+2], 16)/255. for i in (0, 2 ,4)) | [
"def",
"hex_to_rgb",
"(",
"h",
")",
":",
"h",
"=",
"h",
".",
"lstrip",
"(",
"'#'",
")",
"return",
"tuple",
"(",
"int",
"(",
"h",
"[",
"i",
":",
"i",
"+",
"2",
"]",
",",
"16",
")",
"/",
"255.",
"for",
"i",
"in",
"(",
"0",
",",
"2",
",",
... | Returns 0 to 1 rgb from a hex list or tuple | [
"Returns",
"0",
"to",
"1",
"rgb",
"from",
"a",
"hex",
"list",
"or",
"tuple"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/colors.py#L321-L324 | train | 217,623 |
vtkiorg/vtki | vtki/errors.py | set_error_output_file | def set_error_output_file(filename):
"""Sets a file to write out the VTK errors"""
filename = os.path.abspath(os.path.expanduser(filename))
fileOutputWindow = vtk.vtkFileOutputWindow()
fileOutputWindow.SetFileName(filename)
outputWindow = vtk.vtkOutputWindow()
outputWindow.SetInstance(fileOutputWindow)
return fileOutputWindow, outputWindow | python | def set_error_output_file(filename):
"""Sets a file to write out the VTK errors"""
filename = os.path.abspath(os.path.expanduser(filename))
fileOutputWindow = vtk.vtkFileOutputWindow()
fileOutputWindow.SetFileName(filename)
outputWindow = vtk.vtkOutputWindow()
outputWindow.SetInstance(fileOutputWindow)
return fileOutputWindow, outputWindow | [
"def",
"set_error_output_file",
"(",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
")",
"fileOutputWindow",
"=",
"vtk",
".",
"vtkFileOutputWindow",
"(",
")",
"file... | Sets a file to write out the VTK errors | [
"Sets",
"a",
"file",
"to",
"write",
"out",
"the",
"VTK",
"errors"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/errors.py#L8-L15 | train | 217,624 |
vtkiorg/vtki | vtki/errors.py | Observer.log_message | def log_message(self, kind, alert):
"""Parses different event types and passes them to logging"""
if kind == 'ERROR':
logging.error(alert)
else:
logging.warning(alert)
return | python | def log_message(self, kind, alert):
"""Parses different event types and passes them to logging"""
if kind == 'ERROR':
logging.error(alert)
else:
logging.warning(alert)
return | [
"def",
"log_message",
"(",
"self",
",",
"kind",
",",
"alert",
")",
":",
"if",
"kind",
"==",
"'ERROR'",
":",
"logging",
".",
"error",
"(",
"alert",
")",
"else",
":",
"logging",
".",
"warning",
"(",
"alert",
")",
"return"
] | Parses different event types and passes them to logging | [
"Parses",
"different",
"event",
"types",
"and",
"passes",
"them",
"to",
"logging"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/errors.py#L40-L46 | train | 217,625 |
vtkiorg/vtki | vtki/errors.py | Observer.observe | def observe(self, algorithm):
"""Make this an observer of an algorithm
"""
if self.__observing:
raise RuntimeError('This error observer is already observing an algorithm.')
if hasattr(algorithm, 'GetExecutive') and algorithm.GetExecutive() is not None:
algorithm.GetExecutive().AddObserver(self.event_type, self)
algorithm.AddObserver(self.event_type, self)
self.__observing = True
return | python | def observe(self, algorithm):
"""Make this an observer of an algorithm
"""
if self.__observing:
raise RuntimeError('This error observer is already observing an algorithm.')
if hasattr(algorithm, 'GetExecutive') and algorithm.GetExecutive() is not None:
algorithm.GetExecutive().AddObserver(self.event_type, self)
algorithm.AddObserver(self.event_type, self)
self.__observing = True
return | [
"def",
"observe",
"(",
"self",
",",
"algorithm",
")",
":",
"if",
"self",
".",
"__observing",
":",
"raise",
"RuntimeError",
"(",
"'This error observer is already observing an algorithm.'",
")",
"if",
"hasattr",
"(",
"algorithm",
",",
"'GetExecutive'",
")",
"and",
"... | Make this an observer of an algorithm | [
"Make",
"this",
"an",
"observer",
"of",
"an",
"algorithm"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/errors.py#L75-L84 | train | 217,626 |
vtkiorg/vtki | vtki/export.py | get_range_info | def get_range_info(array, component):
"""Get the data range of the array's component"""
r = array.GetRange(component)
comp_range = {}
comp_range['min'] = r[0]
comp_range['max'] = r[1]
comp_range['component'] = array.GetComponentName(component)
return comp_range | python | def get_range_info(array, component):
"""Get the data range of the array's component"""
r = array.GetRange(component)
comp_range = {}
comp_range['min'] = r[0]
comp_range['max'] = r[1]
comp_range['component'] = array.GetComponentName(component)
return comp_range | [
"def",
"get_range_info",
"(",
"array",
",",
"component",
")",
":",
"r",
"=",
"array",
".",
"GetRange",
"(",
"component",
")",
"comp_range",
"=",
"{",
"}",
"comp_range",
"[",
"'min'",
"]",
"=",
"r",
"[",
"0",
"]",
"comp_range",
"[",
"'max'",
"]",
"=",... | Get the data range of the array's component | [
"Get",
"the",
"data",
"range",
"of",
"the",
"array",
"s",
"component"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L78-L85 | train | 217,627 |
vtkiorg/vtki | vtki/export.py | get_object_id | def get_object_id(obj):
"""Get object identifier"""
try:
idx = objIds.index(obj)
return idx + 1
except ValueError:
objIds.append(obj)
return len(objIds) | python | def get_object_id(obj):
"""Get object identifier"""
try:
idx = objIds.index(obj)
return idx + 1
except ValueError:
objIds.append(obj)
return len(objIds) | [
"def",
"get_object_id",
"(",
"obj",
")",
":",
"try",
":",
"idx",
"=",
"objIds",
".",
"index",
"(",
"obj",
")",
"return",
"idx",
"+",
"1",
"except",
"ValueError",
":",
"objIds",
".",
"append",
"(",
"obj",
")",
"return",
"len",
"(",
"objIds",
")"
] | Get object identifier | [
"Get",
"object",
"identifier"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L104-L111 | train | 217,628 |
vtkiorg/vtki | vtki/export.py | dump_data_array | def dump_data_array(dataset_dir, data_dir, array, root=None, compress=True):
"""Dump vtkjs data arry"""
if root is None:
root = {}
if not array:
return None
if array.GetDataType() == 12:
# IdType need to be converted to Uint32
array_size = array.GetNumberOfTuples() * array.GetNumberOfComponents()
new_array = vtk.vtkTypeUInt32Array()
new_array.SetNumberOfTuples(array_size)
for i in range(array_size):
new_array.SetValue(i, -1 if array.GetValue(i) <
0 else array.GetValue(i))
pbuffer = memoryview(new_array)
else:
pbuffer = memoryview(array)
pMd5 = hashlib.md5(pbuffer).hexdigest()
ppath = os.path.join(data_dir, pMd5)
with open(ppath, 'wb') as f:
f.write(pbuffer)
if compress:
with open(ppath, 'rb') as f_in, gzip.open(os.path.join(data_dir, pMd5 + '.gz'), 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
# Close then remove.
os.remove(ppath)
root['ref'] = get_ref(os.path.relpath(data_dir, dataset_dir), pMd5)
root['vtkClass'] = 'vtkDataArray'
root['name'] = array.GetName()
root['dataType'] = jsMapping[arrayTypesMapping[array.GetDataType()]]
root['numberOfComponents'] = array.GetNumberOfComponents()
root['size'] = array.GetNumberOfComponents() * array.GetNumberOfTuples()
root['ranges'] = []
if root['numberOfComponents'] > 1:
for i in range(root['numberOfComponents']):
root['ranges'].append(get_range_info(array, i))
root['ranges'].append(get_range_info(array, -1))
else:
root['ranges'].append(get_range_info(array, 0))
return root | python | def dump_data_array(dataset_dir, data_dir, array, root=None, compress=True):
"""Dump vtkjs data arry"""
if root is None:
root = {}
if not array:
return None
if array.GetDataType() == 12:
# IdType need to be converted to Uint32
array_size = array.GetNumberOfTuples() * array.GetNumberOfComponents()
new_array = vtk.vtkTypeUInt32Array()
new_array.SetNumberOfTuples(array_size)
for i in range(array_size):
new_array.SetValue(i, -1 if array.GetValue(i) <
0 else array.GetValue(i))
pbuffer = memoryview(new_array)
else:
pbuffer = memoryview(array)
pMd5 = hashlib.md5(pbuffer).hexdigest()
ppath = os.path.join(data_dir, pMd5)
with open(ppath, 'wb') as f:
f.write(pbuffer)
if compress:
with open(ppath, 'rb') as f_in, gzip.open(os.path.join(data_dir, pMd5 + '.gz'), 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
# Close then remove.
os.remove(ppath)
root['ref'] = get_ref(os.path.relpath(data_dir, dataset_dir), pMd5)
root['vtkClass'] = 'vtkDataArray'
root['name'] = array.GetName()
root['dataType'] = jsMapping[arrayTypesMapping[array.GetDataType()]]
root['numberOfComponents'] = array.GetNumberOfComponents()
root['size'] = array.GetNumberOfComponents() * array.GetNumberOfTuples()
root['ranges'] = []
if root['numberOfComponents'] > 1:
for i in range(root['numberOfComponents']):
root['ranges'].append(get_range_info(array, i))
root['ranges'].append(get_range_info(array, -1))
else:
root['ranges'].append(get_range_info(array, 0))
return root | [
"def",
"dump_data_array",
"(",
"dataset_dir",
",",
"data_dir",
",",
"array",
",",
"root",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"{",
"}",
"if",
"not",
"array",
":",
"return",
"None",
"if",
... | Dump vtkjs data arry | [
"Dump",
"vtkjs",
"data",
"arry"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L116-L160 | train | 217,629 |
vtkiorg/vtki | vtki/export.py | dump_color_array | def dump_color_array(dataset_dir, data_dir, color_array_info, root=None, compress=True):
"""Dump vtkjs color array"""
if root is None:
root = {}
root['pointData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['cellData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['fieldData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
colorArray = color_array_info['colorArray']
location = color_array_info['location']
dumped_array = dump_data_array(dataset_dir, data_dir, colorArray, {}, compress)
if dumped_array:
root[location]['activeScalars'] = 0
root[location]['arrays'].append({'data': dumped_array})
return root | python | def dump_color_array(dataset_dir, data_dir, color_array_info, root=None, compress=True):
"""Dump vtkjs color array"""
if root is None:
root = {}
root['pointData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['cellData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['fieldData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
colorArray = color_array_info['colorArray']
location = color_array_info['location']
dumped_array = dump_data_array(dataset_dir, data_dir, colorArray, {}, compress)
if dumped_array:
root[location]['activeScalars'] = 0
root[location]['arrays'].append({'data': dumped_array})
return root | [
"def",
"dump_color_array",
"(",
"dataset_dir",
",",
"data_dir",
",",
"color_array_info",
",",
"root",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"{",
"}",
"root",
"[",
"'pointData'",
"]",
"=",
"{"... | Dump vtkjs color array | [
"Dump",
"vtkjs",
"color",
"array"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L165-L212 | train | 217,630 |
vtkiorg/vtki | vtki/export.py | dump_t_coords | def dump_t_coords(dataset_dir, data_dir, dataset, root=None, compress=True):
"""dump vtkjs texture coordinates"""
if root is None:
root = {}
tcoords = dataset.GetPointData().GetTCoords()
if tcoords:
dumped_array = dump_data_array(dataset_dir, data_dir, tcoords, {}, compress)
root['pointData']['activeTCoords'] = len(root['pointData']['arrays'])
root['pointData']['arrays'].append({'data': dumped_array}) | python | def dump_t_coords(dataset_dir, data_dir, dataset, root=None, compress=True):
"""dump vtkjs texture coordinates"""
if root is None:
root = {}
tcoords = dataset.GetPointData().GetTCoords()
if tcoords:
dumped_array = dump_data_array(dataset_dir, data_dir, tcoords, {}, compress)
root['pointData']['activeTCoords'] = len(root['pointData']['arrays'])
root['pointData']['arrays'].append({'data': dumped_array}) | [
"def",
"dump_t_coords",
"(",
"dataset_dir",
",",
"data_dir",
",",
"dataset",
",",
"root",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"{",
"}",
"tcoords",
"=",
"dataset",
".",
"GetPointData",
"(",
... | dump vtkjs texture coordinates | [
"dump",
"vtkjs",
"texture",
"coordinates"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L217-L225 | train | 217,631 |
vtkiorg/vtki | vtki/export.py | dump_normals | def dump_normals(dataset_dir, data_dir, dataset, root=None, compress=True):
"""dump vtkjs normal vectors"""
if root is None:
root = {}
normals = dataset.GetPointData().GetNormals()
if normals:
dumped_array = dump_data_array(dataset_dir, data_dir, normals, {}, compress)
root['pointData']['activeNormals'] = len(root['pointData']['arrays'])
root['pointData']['arrays'].append({'data': dumped_array}) | python | def dump_normals(dataset_dir, data_dir, dataset, root=None, compress=True):
"""dump vtkjs normal vectors"""
if root is None:
root = {}
normals = dataset.GetPointData().GetNormals()
if normals:
dumped_array = dump_data_array(dataset_dir, data_dir, normals, {}, compress)
root['pointData']['activeNormals'] = len(root['pointData']['arrays'])
root['pointData']['arrays'].append({'data': dumped_array}) | [
"def",
"dump_normals",
"(",
"dataset_dir",
",",
"data_dir",
",",
"dataset",
",",
"root",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"{",
"}",
"normals",
"=",
"dataset",
".",
"GetPointData",
"(",
... | dump vtkjs normal vectors | [
"dump",
"vtkjs",
"normal",
"vectors"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L230-L238 | train | 217,632 |
vtkiorg/vtki | vtki/export.py | dump_all_arrays | def dump_all_arrays(dataset_dir, data_dir, dataset, root=None, compress=True):
"""Dump all data arrays to vtkjs"""
if root is None:
root = {}
root['pointData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['cellData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['fieldData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
# Point data
pd = dataset.GetPointData()
pd_size = pd.GetNumberOfArrays()
for i in range(pd_size):
array = pd.GetArray(i)
if array:
dumped_array = dump_data_array(
dataset_dir, data_dir, array, {}, compress)
root['pointData']['activeScalars'] = 0
root['pointData']['arrays'].append({'data': dumped_array})
# Cell data
cd = dataset.GetCellData()
cd_size = pd.GetNumberOfArrays()
for i in range(cd_size):
array = cd.GetArray(i)
if array:
dumped_array = dump_data_array(
dataset_dir, data_dir, array, {}, compress)
root['cellData']['activeScalars'] = 0
root['cellData']['arrays'].append({'data': dumped_array})
return root | python | def dump_all_arrays(dataset_dir, data_dir, dataset, root=None, compress=True):
"""Dump all data arrays to vtkjs"""
if root is None:
root = {}
root['pointData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['cellData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['fieldData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
# Point data
pd = dataset.GetPointData()
pd_size = pd.GetNumberOfArrays()
for i in range(pd_size):
array = pd.GetArray(i)
if array:
dumped_array = dump_data_array(
dataset_dir, data_dir, array, {}, compress)
root['pointData']['activeScalars'] = 0
root['pointData']['arrays'].append({'data': dumped_array})
# Cell data
cd = dataset.GetCellData()
cd_size = pd.GetNumberOfArrays()
for i in range(cd_size):
array = cd.GetArray(i)
if array:
dumped_array = dump_data_array(
dataset_dir, data_dir, array, {}, compress)
root['cellData']['activeScalars'] = 0
root['cellData']['arrays'].append({'data': dumped_array})
return root | [
"def",
"dump_all_arrays",
"(",
"dataset_dir",
",",
"data_dir",
",",
"dataset",
",",
"root",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"{",
"}",
"root",
"[",
"'pointData'",
"]",
"=",
"{",
"'vtkC... | Dump all data arrays to vtkjs | [
"Dump",
"all",
"data",
"arrays",
"to",
"vtkjs"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L243-L303 | train | 217,633 |
vtkiorg/vtki | vtki/export.py | dump_poly_data | def dump_poly_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
"""Dump poly data object to vtkjs"""
if root is None:
root = {}
root['vtkClass'] = 'vtkPolyData'
container = root
# Points
points = dump_data_array(dataset_dir, data_dir,
dataset.GetPoints().GetData(), {}, compress)
points['vtkClass'] = 'vtkPoints'
container['points'] = points
# Cells
_cells = container
# Verts
if dataset.GetVerts() and dataset.GetVerts().GetData().GetNumberOfTuples() > 0:
_verts = dump_data_array(dataset_dir, data_dir,
dataset.GetVerts().GetData(), {}, compress)
_cells['verts'] = _verts
_cells['verts']['vtkClass'] = 'vtkCellArray'
# Lines
if dataset.GetLines() and dataset.GetLines().GetData().GetNumberOfTuples() > 0:
_lines = dump_data_array(dataset_dir, data_dir,
dataset.GetLines().GetData(), {}, compress)
_cells['lines'] = _lines
_cells['lines']['vtkClass'] = 'vtkCellArray'
# Polys
if dataset.GetPolys() and dataset.GetPolys().GetData().GetNumberOfTuples() > 0:
_polys = dump_data_array(dataset_dir, data_dir,
dataset.GetPolys().GetData(), {}, compress)
_cells['polys'] = _polys
_cells['polys']['vtkClass'] = 'vtkCellArray'
# Strips
if dataset.GetStrips() and dataset.GetStrips().GetData().GetNumberOfTuples() > 0:
_strips = dump_data_array(dataset_dir, data_dir,
dataset.GetStrips().GetData(), {}, compress)
_cells['strips'] = _strips
_cells['strips']['vtkClass'] = 'vtkCellArray'
dump_color_array(dataset_dir, data_dir, color_array_info, container, compress)
# PointData TCoords
dump_t_coords(dataset_dir, data_dir, dataset, container, compress)
# dump_normals(dataset_dir, data_dir, dataset, container, compress)
return root | python | def dump_poly_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
"""Dump poly data object to vtkjs"""
if root is None:
root = {}
root['vtkClass'] = 'vtkPolyData'
container = root
# Points
points = dump_data_array(dataset_dir, data_dir,
dataset.GetPoints().GetData(), {}, compress)
points['vtkClass'] = 'vtkPoints'
container['points'] = points
# Cells
_cells = container
# Verts
if dataset.GetVerts() and dataset.GetVerts().GetData().GetNumberOfTuples() > 0:
_verts = dump_data_array(dataset_dir, data_dir,
dataset.GetVerts().GetData(), {}, compress)
_cells['verts'] = _verts
_cells['verts']['vtkClass'] = 'vtkCellArray'
# Lines
if dataset.GetLines() and dataset.GetLines().GetData().GetNumberOfTuples() > 0:
_lines = dump_data_array(dataset_dir, data_dir,
dataset.GetLines().GetData(), {}, compress)
_cells['lines'] = _lines
_cells['lines']['vtkClass'] = 'vtkCellArray'
# Polys
if dataset.GetPolys() and dataset.GetPolys().GetData().GetNumberOfTuples() > 0:
_polys = dump_data_array(dataset_dir, data_dir,
dataset.GetPolys().GetData(), {}, compress)
_cells['polys'] = _polys
_cells['polys']['vtkClass'] = 'vtkCellArray'
# Strips
if dataset.GetStrips() and dataset.GetStrips().GetData().GetNumberOfTuples() > 0:
_strips = dump_data_array(dataset_dir, data_dir,
dataset.GetStrips().GetData(), {}, compress)
_cells['strips'] = _strips
_cells['strips']['vtkClass'] = 'vtkCellArray'
dump_color_array(dataset_dir, data_dir, color_array_info, container, compress)
# PointData TCoords
dump_t_coords(dataset_dir, data_dir, dataset, container, compress)
# dump_normals(dataset_dir, data_dir, dataset, container, compress)
return root | [
"def",
"dump_poly_data",
"(",
"dataset_dir",
",",
"data_dir",
",",
"dataset",
",",
"color_array_info",
",",
"root",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"{",
"}",
"root",
"[",
"'vtkClass'",
... | Dump poly data object to vtkjs | [
"Dump",
"poly",
"data",
"object",
"to",
"vtkjs"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L308-L358 | train | 217,634 |
vtkiorg/vtki | vtki/export.py | dump_image_data | def dump_image_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
"""Dump image data object to vtkjs"""
if root is None:
root = {}
root['vtkClass'] = 'vtkImageData'
container = root
container['spacing'] = dataset.GetSpacing()
container['origin'] = dataset.GetOrigin()
container['extent'] = dataset.GetExtent()
dump_all_arrays(dataset_dir, data_dir, dataset, container, compress)
return root | python | def dump_image_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
"""Dump image data object to vtkjs"""
if root is None:
root = {}
root['vtkClass'] = 'vtkImageData'
container = root
container['spacing'] = dataset.GetSpacing()
container['origin'] = dataset.GetOrigin()
container['extent'] = dataset.GetExtent()
dump_all_arrays(dataset_dir, data_dir, dataset, container, compress)
return root | [
"def",
"dump_image_data",
"(",
"dataset_dir",
",",
"data_dir",
",",
"dataset",
",",
"color_array_info",
",",
"root",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"{",
"}",
"root",
"[",
"'vtkClass'",
... | Dump image data object to vtkjs | [
"Dump",
"image",
"data",
"object",
"to",
"vtkjs"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L366-L379 | train | 217,635 |
vtkiorg/vtki | vtki/export.py | write_data_set | def write_data_set(file_path, dataset, output_dir, color_array_info, new_name=None, compress=True):
"""write dataset to vtkjs"""
fileName = new_name if new_name else os.path.basename(file_path)
dataset_dir = os.path.join(output_dir, fileName)
data_dir = os.path.join(dataset_dir, 'data')
if not os.path.exists(data_dir):
os.makedirs(data_dir)
root = {}
root['metadata'] = {}
root['metadata']['name'] = fileName
writer = writer_mapping[dataset.GetClassName()]
if writer:
writer(dataset_dir, data_dir, dataset, color_array_info, root, compress)
else:
print(dataObject.GetClassName(), 'is not supported')
with open(os.path.join(dataset_dir, "index.json"), 'w') as f:
f.write(json.dumps(root, indent=2))
return dataset_dir | python | def write_data_set(file_path, dataset, output_dir, color_array_info, new_name=None, compress=True):
"""write dataset to vtkjs"""
fileName = new_name if new_name else os.path.basename(file_path)
dataset_dir = os.path.join(output_dir, fileName)
data_dir = os.path.join(dataset_dir, 'data')
if not os.path.exists(data_dir):
os.makedirs(data_dir)
root = {}
root['metadata'] = {}
root['metadata']['name'] = fileName
writer = writer_mapping[dataset.GetClassName()]
if writer:
writer(dataset_dir, data_dir, dataset, color_array_info, root, compress)
else:
print(dataObject.GetClassName(), 'is not supported')
with open(os.path.join(dataset_dir, "index.json"), 'w') as f:
f.write(json.dumps(root, indent=2))
return dataset_dir | [
"def",
"write_data_set",
"(",
"file_path",
",",
"dataset",
",",
"output_dir",
",",
"color_array_info",
",",
"new_name",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"fileName",
"=",
"new_name",
"if",
"new_name",
"else",
"os",
".",
"path",
".",
"bas... | write dataset to vtkjs | [
"write",
"dataset",
"to",
"vtkjs"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L387-L409 | train | 217,636 |
vtkiorg/vtki | vtki/common.py | Common.active_vectors | def active_vectors(self):
"""The active vectors array"""
field, name = self.active_vectors_info
if name:
if field is POINT_DATA_FIELD:
return self.point_arrays[name]
if field is CELL_DATA_FIELD:
return self.cell_arrays[name] | python | def active_vectors(self):
"""The active vectors array"""
field, name = self.active_vectors_info
if name:
if field is POINT_DATA_FIELD:
return self.point_arrays[name]
if field is CELL_DATA_FIELD:
return self.cell_arrays[name] | [
"def",
"active_vectors",
"(",
"self",
")",
":",
"field",
",",
"name",
"=",
"self",
".",
"active_vectors_info",
"if",
"name",
":",
"if",
"field",
"is",
"POINT_DATA_FIELD",
":",
"return",
"self",
".",
"point_arrays",
"[",
"name",
"]",
"if",
"field",
"is",
... | The active vectors array | [
"The",
"active",
"vectors",
"array"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L81-L88 | train | 217,637 |
vtkiorg/vtki | vtki/common.py | Common.arrows | def arrows(self):
"""
Returns a glyph representation of the active vector data as
arrows. Arrows will be located at the points of the mesh and
their size will be dependent on the length of the vector.
Their direction will be the "direction" of the vector
Returns
-------
arrows : vtki.PolyData
Active scalars represented as arrows.
"""
if self.active_vectors is None:
return
arrow = vtk.vtkArrowSource()
arrow.Update()
alg = vtk.vtkGlyph3D()
alg.SetSourceData(arrow.GetOutput())
alg.SetOrient(True)
alg.SetInputData(self)
alg.SetVectorModeToUseVector()
alg.SetScaleModeToScaleByVector()
alg.Update()
return vtki.wrap(alg.GetOutput()) | python | def arrows(self):
"""
Returns a glyph representation of the active vector data as
arrows. Arrows will be located at the points of the mesh and
their size will be dependent on the length of the vector.
Their direction will be the "direction" of the vector
Returns
-------
arrows : vtki.PolyData
Active scalars represented as arrows.
"""
if self.active_vectors is None:
return
arrow = vtk.vtkArrowSource()
arrow.Update()
alg = vtk.vtkGlyph3D()
alg.SetSourceData(arrow.GetOutput())
alg.SetOrient(True)
alg.SetInputData(self)
alg.SetVectorModeToUseVector()
alg.SetScaleModeToScaleByVector()
alg.Update()
return vtki.wrap(alg.GetOutput()) | [
"def",
"arrows",
"(",
"self",
")",
":",
"if",
"self",
".",
"active_vectors",
"is",
"None",
":",
"return",
"arrow",
"=",
"vtk",
".",
"vtkArrowSource",
"(",
")",
"arrow",
".",
"Update",
"(",
")",
"alg",
"=",
"vtk",
".",
"vtkGlyph3D",
"(",
")",
"alg",
... | Returns a glyph representation of the active vector data as
arrows. Arrows will be located at the points of the mesh and
their size will be dependent on the length of the vector.
Their direction will be the "direction" of the vector
Returns
-------
arrows : vtki.PolyData
Active scalars represented as arrows. | [
"Returns",
"a",
"glyph",
"representation",
"of",
"the",
"active",
"vector",
"data",
"as",
"arrows",
".",
"Arrows",
"will",
"be",
"located",
"at",
"the",
"points",
"of",
"the",
"mesh",
"and",
"their",
"size",
"will",
"be",
"dependent",
"on",
"the",
"length"... | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L128-L153 | train | 217,638 |
vtkiorg/vtki | vtki/common.py | Common.vectors | def vectors(self, array):
""" Sets the active vector """
if array.ndim != 2:
raise AssertionError('vector array must be a 2-dimensional array')
elif array.shape[1] != 3:
raise RuntimeError('vector array must be 3D')
elif array.shape[0] != self.n_points:
raise RuntimeError('Number of vectors be the same as the number of points')
self.point_arrays[DEFAULT_VECTOR_KEY] = array
self.active_vectors_name = DEFAULT_VECTOR_KEY | python | def vectors(self, array):
""" Sets the active vector """
if array.ndim != 2:
raise AssertionError('vector array must be a 2-dimensional array')
elif array.shape[1] != 3:
raise RuntimeError('vector array must be 3D')
elif array.shape[0] != self.n_points:
raise RuntimeError('Number of vectors be the same as the number of points')
self.point_arrays[DEFAULT_VECTOR_KEY] = array
self.active_vectors_name = DEFAULT_VECTOR_KEY | [
"def",
"vectors",
"(",
"self",
",",
"array",
")",
":",
"if",
"array",
".",
"ndim",
"!=",
"2",
":",
"raise",
"AssertionError",
"(",
"'vector array must be a 2-dimensional array'",
")",
"elif",
"array",
".",
"shape",
"[",
"1",
"]",
"!=",
"3",
":",
"raise",
... | Sets the active vector | [
"Sets",
"the",
"active",
"vector"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L161-L171 | train | 217,639 |
vtkiorg/vtki | vtki/common.py | Common.t_coords | def t_coords(self, t_coords):
"""Set the array to use as the texture coordinates"""
if not isinstance(t_coords, np.ndarray):
raise TypeError('Texture coordinates must be a numpy array')
if t_coords.ndim != 2:
raise AssertionError('Texture coordinates must be a 2-dimensional array')
if t_coords.shape[0] != self.n_points:
raise AssertionError('Number of texture coordinates ({}) must match number of points ({})'.format(t_coords.shape[0], self.n_points))
if t_coords.shape[1] != 2:
raise AssertionError('Texture coordinates must only have 2 components, not ({})'.format(t_coords.shape[1]))
if np.min(t_coords) < 0.0 or np.max(t_coords) > 1.0:
raise AssertionError('Texture coordinates must be within (0, 1) range.')
# convert the array
vtkarr = numpy_to_vtk(t_coords)
vtkarr.SetName('Texture Coordinates')
self.GetPointData().SetTCoords(vtkarr)
self.GetPointData().Modified()
return | python | def t_coords(self, t_coords):
"""Set the array to use as the texture coordinates"""
if not isinstance(t_coords, np.ndarray):
raise TypeError('Texture coordinates must be a numpy array')
if t_coords.ndim != 2:
raise AssertionError('Texture coordinates must be a 2-dimensional array')
if t_coords.shape[0] != self.n_points:
raise AssertionError('Number of texture coordinates ({}) must match number of points ({})'.format(t_coords.shape[0], self.n_points))
if t_coords.shape[1] != 2:
raise AssertionError('Texture coordinates must only have 2 components, not ({})'.format(t_coords.shape[1]))
if np.min(t_coords) < 0.0 or np.max(t_coords) > 1.0:
raise AssertionError('Texture coordinates must be within (0, 1) range.')
# convert the array
vtkarr = numpy_to_vtk(t_coords)
vtkarr.SetName('Texture Coordinates')
self.GetPointData().SetTCoords(vtkarr)
self.GetPointData().Modified()
return | [
"def",
"t_coords",
"(",
"self",
",",
"t_coords",
")",
":",
"if",
"not",
"isinstance",
"(",
"t_coords",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"'Texture coordinates must be a numpy array'",
")",
"if",
"t_coords",
".",
"ndim",
"!=",
"2... | Set the array to use as the texture coordinates | [
"Set",
"the",
"array",
"to",
"use",
"as",
"the",
"texture",
"coordinates"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L181-L198 | train | 217,640 |
vtkiorg/vtki | vtki/common.py | Common._activate_texture | def _activate_texture(mesh, name):
"""Grab a texture and update the active texture coordinates. This makes
sure to not destroy old texture coordinates
Parameters
----------
name : str
The name of the texture and texture coordinates to activate
Return
------
vtk.vtkTexture : The active texture
"""
if name == True or isinstance(name, int):
keys = list(mesh.textures.keys())
# Grab the first name availabe if True
idx = 0 if not isinstance(name, int) or name == True else name
if idx > len(keys):
idx = 0
try:
name = keys[idx]
except IndexError:
logging.warning('No textures associated with input mesh.')
return None
# Grab the texture object by name
try:
texture = mesh.textures[name]
except KeyError:
logging.warning('Texture ({}) not associated with this dataset'.format(name))
texture = None
else:
# Be sure to reset the tcoords if present
# Grab old coordinates
if name in mesh.scalar_names:
old_tcoord = mesh.GetPointData().GetTCoords()
mesh.GetPointData().SetTCoords(mesh.GetPointData().GetArray(name))
mesh.GetPointData().AddArray(old_tcoord)
mesh.Modified()
return texture | python | def _activate_texture(mesh, name):
"""Grab a texture and update the active texture coordinates. This makes
sure to not destroy old texture coordinates
Parameters
----------
name : str
The name of the texture and texture coordinates to activate
Return
------
vtk.vtkTexture : The active texture
"""
if name == True or isinstance(name, int):
keys = list(mesh.textures.keys())
# Grab the first name availabe if True
idx = 0 if not isinstance(name, int) or name == True else name
if idx > len(keys):
idx = 0
try:
name = keys[idx]
except IndexError:
logging.warning('No textures associated with input mesh.')
return None
# Grab the texture object by name
try:
texture = mesh.textures[name]
except KeyError:
logging.warning('Texture ({}) not associated with this dataset'.format(name))
texture = None
else:
# Be sure to reset the tcoords if present
# Grab old coordinates
if name in mesh.scalar_names:
old_tcoord = mesh.GetPointData().GetTCoords()
mesh.GetPointData().SetTCoords(mesh.GetPointData().GetArray(name))
mesh.GetPointData().AddArray(old_tcoord)
mesh.Modified()
return texture | [
"def",
"_activate_texture",
"(",
"mesh",
",",
"name",
")",
":",
"if",
"name",
"==",
"True",
"or",
"isinstance",
"(",
"name",
",",
"int",
")",
":",
"keys",
"=",
"list",
"(",
"mesh",
".",
"textures",
".",
"keys",
"(",
")",
")",
"# Grab the first name ava... | Grab a texture and update the active texture coordinates. This makes
sure to not destroy old texture coordinates
Parameters
----------
name : str
The name of the texture and texture coordinates to activate
Return
------
vtk.vtkTexture : The active texture | [
"Grab",
"a",
"texture",
"and",
"update",
"the",
"active",
"texture",
"coordinates",
".",
"This",
"makes",
"sure",
"to",
"not",
"destroy",
"old",
"texture",
"coordinates"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L210-L248 | train | 217,641 |
vtkiorg/vtki | vtki/common.py | Common.set_active_scalar | def set_active_scalar(self, name, preference='cell'):
"""Finds the scalar by name and appropriately sets it as active"""
_, field = get_scalar(self, name, preference=preference, info=True)
if field == POINT_DATA_FIELD:
self.GetPointData().SetActiveScalars(name)
elif field == CELL_DATA_FIELD:
self.GetCellData().SetActiveScalars(name)
else:
raise RuntimeError('Data field ({}) not useable'.format(field))
self._active_scalar_info = [field, name] | python | def set_active_scalar(self, name, preference='cell'):
"""Finds the scalar by name and appropriately sets it as active"""
_, field = get_scalar(self, name, preference=preference, info=True)
if field == POINT_DATA_FIELD:
self.GetPointData().SetActiveScalars(name)
elif field == CELL_DATA_FIELD:
self.GetCellData().SetActiveScalars(name)
else:
raise RuntimeError('Data field ({}) not useable'.format(field))
self._active_scalar_info = [field, name] | [
"def",
"set_active_scalar",
"(",
"self",
",",
"name",
",",
"preference",
"=",
"'cell'",
")",
":",
"_",
",",
"field",
"=",
"get_scalar",
"(",
"self",
",",
"name",
",",
"preference",
"=",
"preference",
",",
"info",
"=",
"True",
")",
"if",
"field",
"==",
... | Finds the scalar by name and appropriately sets it as active | [
"Finds",
"the",
"scalar",
"by",
"name",
"and",
"appropriately",
"sets",
"it",
"as",
"active"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L250-L259 | train | 217,642 |
vtkiorg/vtki | vtki/common.py | Common.set_active_vectors | def set_active_vectors(self, name, preference='cell'):
"""Finds the vectors by name and appropriately sets it as active"""
_, field = get_scalar(self, name, preference=preference, info=True)
if field == POINT_DATA_FIELD:
self.GetPointData().SetActiveVectors(name)
elif field == CELL_DATA_FIELD:
self.GetCellData().SetActiveVectors(name)
else:
raise RuntimeError('Data field ({}) not useable'.format(field))
self._active_vectors_info = [field, name] | python | def set_active_vectors(self, name, preference='cell'):
"""Finds the vectors by name and appropriately sets it as active"""
_, field = get_scalar(self, name, preference=preference, info=True)
if field == POINT_DATA_FIELD:
self.GetPointData().SetActiveVectors(name)
elif field == CELL_DATA_FIELD:
self.GetCellData().SetActiveVectors(name)
else:
raise RuntimeError('Data field ({}) not useable'.format(field))
self._active_vectors_info = [field, name] | [
"def",
"set_active_vectors",
"(",
"self",
",",
"name",
",",
"preference",
"=",
"'cell'",
")",
":",
"_",
",",
"field",
"=",
"get_scalar",
"(",
"self",
",",
"name",
",",
"preference",
"=",
"preference",
",",
"info",
"=",
"True",
")",
"if",
"field",
"==",... | Finds the vectors by name and appropriately sets it as active | [
"Finds",
"the",
"vectors",
"by",
"name",
"and",
"appropriately",
"sets",
"it",
"as",
"active"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L261-L270 | train | 217,643 |
vtkiorg/vtki | vtki/common.py | Common.rename_scalar | def rename_scalar(self, old_name, new_name, preference='cell'):
"""Changes array name by searching for the array then renaming it"""
_, field = get_scalar(self, old_name, preference=preference, info=True)
if field == POINT_DATA_FIELD:
self.point_arrays[new_name] = self.point_arrays.pop(old_name)
elif field == CELL_DATA_FIELD:
self.cell_arrays[new_name] = self.cell_arrays.pop(old_name)
else:
raise RuntimeError('Array not found.')
if self.active_scalar_info[1] == old_name:
self.set_active_scalar(new_name, preference=field) | python | def rename_scalar(self, old_name, new_name, preference='cell'):
"""Changes array name by searching for the array then renaming it"""
_, field = get_scalar(self, old_name, preference=preference, info=True)
if field == POINT_DATA_FIELD:
self.point_arrays[new_name] = self.point_arrays.pop(old_name)
elif field == CELL_DATA_FIELD:
self.cell_arrays[new_name] = self.cell_arrays.pop(old_name)
else:
raise RuntimeError('Array not found.')
if self.active_scalar_info[1] == old_name:
self.set_active_scalar(new_name, preference=field) | [
"def",
"rename_scalar",
"(",
"self",
",",
"old_name",
",",
"new_name",
",",
"preference",
"=",
"'cell'",
")",
":",
"_",
",",
"field",
"=",
"get_scalar",
"(",
"self",
",",
"old_name",
",",
"preference",
"=",
"preference",
",",
"info",
"=",
"True",
")",
... | Changes array name by searching for the array then renaming it | [
"Changes",
"array",
"name",
"by",
"searching",
"for",
"the",
"array",
"then",
"renaming",
"it"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L272-L282 | train | 217,644 |
vtkiorg/vtki | vtki/common.py | Common.active_scalar | def active_scalar(self):
"""Returns the active scalar as an array"""
field, name = self.active_scalar_info
if name is None:
return None
if field == POINT_DATA_FIELD:
return self._point_scalar(name)
elif field == CELL_DATA_FIELD:
return self._cell_scalar(name) | python | def active_scalar(self):
"""Returns the active scalar as an array"""
field, name = self.active_scalar_info
if name is None:
return None
if field == POINT_DATA_FIELD:
return self._point_scalar(name)
elif field == CELL_DATA_FIELD:
return self._cell_scalar(name) | [
"def",
"active_scalar",
"(",
"self",
")",
":",
"field",
",",
"name",
"=",
"self",
".",
"active_scalar_info",
"if",
"name",
"is",
"None",
":",
"return",
"None",
"if",
"field",
"==",
"POINT_DATA_FIELD",
":",
"return",
"self",
".",
"_point_scalar",
"(",
"name... | Returns the active scalar as an array | [
"Returns",
"the",
"active",
"scalar",
"as",
"an",
"array"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L285-L293 | train | 217,645 |
vtkiorg/vtki | vtki/common.py | Common._add_point_scalar | def _add_point_scalar(self, scalars, name, set_active=False, deep=True):
"""
Adds point scalars to the mesh
Parameters
----------
scalars : numpy.ndarray
Numpy array of scalars. Must match number of points.
name : str
Name of point scalars to add.
set_active : bool, optional
Sets the scalars to the active plotting scalars. Default False.
deep : bool, optional
Does not copy scalars when False. A reference to the scalars
must be kept to avoid a segfault.
"""
if not isinstance(scalars, np.ndarray):
raise TypeError('Input must be a numpy.ndarray')
if scalars.shape[0] != self.n_points:
raise Exception('Number of scalars must match the number of ' +
'points')
# need to track which arrays are boolean as all boolean arrays
# must be stored as uint8
if scalars.dtype == np.bool:
scalars = scalars.view(np.uint8)
if name not in self._point_bool_array_names:
self._point_bool_array_names.append(name)
if not scalars.flags.c_contiguous:
scalars = np.ascontiguousarray(scalars)
vtkarr = numpy_to_vtk(scalars, deep=deep)
vtkarr.SetName(name)
self.GetPointData().AddArray(vtkarr)
if set_active or self.active_scalar_info[1] is None:
self.GetPointData().SetActiveScalars(name)
self._active_scalar_info = [POINT_DATA_FIELD, name] | python | def _add_point_scalar(self, scalars, name, set_active=False, deep=True):
"""
Adds point scalars to the mesh
Parameters
----------
scalars : numpy.ndarray
Numpy array of scalars. Must match number of points.
name : str
Name of point scalars to add.
set_active : bool, optional
Sets the scalars to the active plotting scalars. Default False.
deep : bool, optional
Does not copy scalars when False. A reference to the scalars
must be kept to avoid a segfault.
"""
if not isinstance(scalars, np.ndarray):
raise TypeError('Input must be a numpy.ndarray')
if scalars.shape[0] != self.n_points:
raise Exception('Number of scalars must match the number of ' +
'points')
# need to track which arrays are boolean as all boolean arrays
# must be stored as uint8
if scalars.dtype == np.bool:
scalars = scalars.view(np.uint8)
if name not in self._point_bool_array_names:
self._point_bool_array_names.append(name)
if not scalars.flags.c_contiguous:
scalars = np.ascontiguousarray(scalars)
vtkarr = numpy_to_vtk(scalars, deep=deep)
vtkarr.SetName(name)
self.GetPointData().AddArray(vtkarr)
if set_active or self.active_scalar_info[1] is None:
self.GetPointData().SetActiveScalars(name)
self._active_scalar_info = [POINT_DATA_FIELD, name] | [
"def",
"_add_point_scalar",
"(",
"self",
",",
"scalars",
",",
"name",
",",
"set_active",
"=",
"False",
",",
"deep",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"scalars",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"'Inpu... | Adds point scalars to the mesh
Parameters
----------
scalars : numpy.ndarray
Numpy array of scalars. Must match number of points.
name : str
Name of point scalars to add.
set_active : bool, optional
Sets the scalars to the active plotting scalars. Default False.
deep : bool, optional
Does not copy scalars when False. A reference to the scalars
must be kept to avoid a segfault. | [
"Adds",
"point",
"scalars",
"to",
"the",
"mesh"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L330-L372 | train | 217,646 |
vtkiorg/vtki | vtki/common.py | Common.points_to_double | def points_to_double(self):
""" Makes points double precision """
if self.points.dtype != np.double:
self.points = self.points.astype(np.double) | python | def points_to_double(self):
""" Makes points double precision """
if self.points.dtype != np.double:
self.points = self.points.astype(np.double) | [
"def",
"points_to_double",
"(",
"self",
")",
":",
"if",
"self",
".",
"points",
".",
"dtype",
"!=",
"np",
".",
"double",
":",
"self",
".",
"points",
"=",
"self",
".",
"points",
".",
"astype",
"(",
"np",
".",
"double",
")"
] | Makes points double precision | [
"Makes",
"points",
"double",
"precision"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L374-L377 | train | 217,647 |
vtkiorg/vtki | vtki/common.py | Common.rotate_x | def rotate_x(self, angle):
"""
Rotates mesh about the x-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the x-axis.
"""
axis_rotation(self.points, angle, inplace=True, axis='x') | python | def rotate_x(self, angle):
"""
Rotates mesh about the x-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the x-axis.
"""
axis_rotation(self.points, angle, inplace=True, axis='x') | [
"def",
"rotate_x",
"(",
"self",
",",
"angle",
")",
":",
"axis_rotation",
"(",
"self",
".",
"points",
",",
"angle",
",",
"inplace",
"=",
"True",
",",
"axis",
"=",
"'x'",
")"
] | Rotates mesh about the x-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the x-axis. | [
"Rotates",
"mesh",
"about",
"the",
"x",
"-",
"axis",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L379-L389 | train | 217,648 |
vtkiorg/vtki | vtki/common.py | Common.rotate_y | def rotate_y(self, angle):
"""
Rotates mesh about the y-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the y-axis.
"""
axis_rotation(self.points, angle, inplace=True, axis='y') | python | def rotate_y(self, angle):
"""
Rotates mesh about the y-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the y-axis.
"""
axis_rotation(self.points, angle, inplace=True, axis='y') | [
"def",
"rotate_y",
"(",
"self",
",",
"angle",
")",
":",
"axis_rotation",
"(",
"self",
".",
"points",
",",
"angle",
",",
"inplace",
"=",
"True",
",",
"axis",
"=",
"'y'",
")"
] | Rotates mesh about the y-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the y-axis. | [
"Rotates",
"mesh",
"about",
"the",
"y",
"-",
"axis",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L391-L401 | train | 217,649 |
vtkiorg/vtki | vtki/common.py | Common.rotate_z | def rotate_z(self, angle):
"""
Rotates mesh about the z-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the z-axis.
"""
axis_rotation(self.points, angle, inplace=True, axis='z') | python | def rotate_z(self, angle):
"""
Rotates mesh about the z-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the z-axis.
"""
axis_rotation(self.points, angle, inplace=True, axis='z') | [
"def",
"rotate_z",
"(",
"self",
",",
"angle",
")",
":",
"axis_rotation",
"(",
"self",
".",
"points",
",",
"angle",
",",
"inplace",
"=",
"True",
",",
"axis",
"=",
"'z'",
")"
] | Rotates mesh about the z-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the z-axis. | [
"Rotates",
"mesh",
"about",
"the",
"z",
"-",
"axis",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L403-L413 | train | 217,650 |
vtkiorg/vtki | vtki/common.py | Common.transform | def transform(self, trans):
"""
Compute a transformation in place using a 4x4 transform.
Parameters
----------
trans : vtk.vtkMatrix4x4, vtk.vtkTransform, or np.ndarray
Accepts a vtk transformation object or a 4x4 transformation matrix.
"""
if isinstance(trans, vtk.vtkMatrix4x4):
t = vtki.trans_from_matrix(trans)
elif isinstance(trans, vtk.vtkTransform):
t = vtki.trans_from_matrix(trans.GetMatrix())
elif isinstance(trans, np.ndarray):
if trans.shape[0] != 4 or trans.shape[1] != 4:
raise Exception('Transformation array must be 4x4')
t = trans
else:
raise TypeError('Input transform must be either:\n'
+ '\tvtk.vtkMatrix4x4\n'
+ '\tvtk.vtkTransform\n'
+ '\t4x4 np.ndarray\n')
x = (self.points*t[0, :3]).sum(1) + t[0, -1]
y = (self.points*t[1, :3]).sum(1) + t[1, -1]
z = (self.points*t[2, :3]).sum(1) + t[2, -1]
# overwrite points
self.points[:, 0] = x
self.points[:, 1] = y
self.points[:, 2] = z | python | def transform(self, trans):
"""
Compute a transformation in place using a 4x4 transform.
Parameters
----------
trans : vtk.vtkMatrix4x4, vtk.vtkTransform, or np.ndarray
Accepts a vtk transformation object or a 4x4 transformation matrix.
"""
if isinstance(trans, vtk.vtkMatrix4x4):
t = vtki.trans_from_matrix(trans)
elif isinstance(trans, vtk.vtkTransform):
t = vtki.trans_from_matrix(trans.GetMatrix())
elif isinstance(trans, np.ndarray):
if trans.shape[0] != 4 or trans.shape[1] != 4:
raise Exception('Transformation array must be 4x4')
t = trans
else:
raise TypeError('Input transform must be either:\n'
+ '\tvtk.vtkMatrix4x4\n'
+ '\tvtk.vtkTransform\n'
+ '\t4x4 np.ndarray\n')
x = (self.points*t[0, :3]).sum(1) + t[0, -1]
y = (self.points*t[1, :3]).sum(1) + t[1, -1]
z = (self.points*t[2, :3]).sum(1) + t[2, -1]
# overwrite points
self.points[:, 0] = x
self.points[:, 1] = y
self.points[:, 2] = z | [
"def",
"transform",
"(",
"self",
",",
"trans",
")",
":",
"if",
"isinstance",
"(",
"trans",
",",
"vtk",
".",
"vtkMatrix4x4",
")",
":",
"t",
"=",
"vtki",
".",
"trans_from_matrix",
"(",
"trans",
")",
"elif",
"isinstance",
"(",
"trans",
",",
"vtk",
".",
... | Compute a transformation in place using a 4x4 transform.
Parameters
----------
trans : vtk.vtkMatrix4x4, vtk.vtkTransform, or np.ndarray
Accepts a vtk transformation object or a 4x4 transformation matrix. | [
"Compute",
"a",
"transformation",
"in",
"place",
"using",
"a",
"4x4",
"transform",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L427-L458 | train | 217,651 |
vtkiorg/vtki | vtki/common.py | Common._cell_scalar | def _cell_scalar(self, name=None):
"""
Returns the cell scalars of a vtk object
Parameters
----------
name : str
Name of cell scalars to retrive.
Returns
-------
scalars : np.ndarray
Numpy array of scalars
"""
if name is None:
# use active scalar array
field, name = self.active_scalar_info
if field != CELL_DATA_FIELD:
raise RuntimeError('Must specify an array to fetch.')
vtkarr = self.GetCellData().GetArray(name)
if vtkarr is None:
raise AssertionError('({}) is not a cell scalar'.format(name))
# numpy does not support bit array data types
if isinstance(vtkarr, vtk.vtkBitArray):
vtkarr = vtk_bit_array_to_char(vtkarr)
if name not in self._cell_bool_array_names:
self._cell_bool_array_names.append(name)
array = vtk_to_numpy(vtkarr)
if array.dtype == np.uint8 and name in self._cell_bool_array_names:
array = array.view(np.bool)
return array | python | def _cell_scalar(self, name=None):
"""
Returns the cell scalars of a vtk object
Parameters
----------
name : str
Name of cell scalars to retrive.
Returns
-------
scalars : np.ndarray
Numpy array of scalars
"""
if name is None:
# use active scalar array
field, name = self.active_scalar_info
if field != CELL_DATA_FIELD:
raise RuntimeError('Must specify an array to fetch.')
vtkarr = self.GetCellData().GetArray(name)
if vtkarr is None:
raise AssertionError('({}) is not a cell scalar'.format(name))
# numpy does not support bit array data types
if isinstance(vtkarr, vtk.vtkBitArray):
vtkarr = vtk_bit_array_to_char(vtkarr)
if name not in self._cell_bool_array_names:
self._cell_bool_array_names.append(name)
array = vtk_to_numpy(vtkarr)
if array.dtype == np.uint8 and name in self._cell_bool_array_names:
array = array.view(np.bool)
return array | [
"def",
"_cell_scalar",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"# use active scalar array",
"field",
",",
"name",
"=",
"self",
".",
"active_scalar_info",
"if",
"field",
"!=",
"CELL_DATA_FIELD",
":",
"raise",
"Runtime... | Returns the cell scalars of a vtk object
Parameters
----------
name : str
Name of cell scalars to retrive.
Returns
-------
scalars : np.ndarray
Numpy array of scalars | [
"Returns",
"the",
"cell",
"scalars",
"of",
"a",
"vtk",
"object"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L460-L494 | train | 217,652 |
vtkiorg/vtki | vtki/common.py | Common._add_cell_scalar | def _add_cell_scalar(self, scalars, name, set_active=False, deep=True):
"""
Adds cell scalars to the vtk object.
Parameters
----------
scalars : numpy.ndarray
Numpy array of scalars. Must match number of points.
name : str
Name of point scalars to add.
set_active : bool, optional
Sets the scalars to the active plotting scalars. Default False.
deep : bool, optional
Does not copy scalars when False. A reference to the scalars
must be kept to avoid a segfault.
"""
if not isinstance(scalars, np.ndarray):
raise TypeError('Input must be a numpy.ndarray')
if scalars.shape[0] != self.n_cells:
raise Exception('Number of scalars must match the number of cells (%d)'
% self.n_cells)
if not scalars.flags.c_contiguous:
raise AssertionError('Array must be contigious')
if scalars.dtype == np.bool:
scalars = scalars.view(np.uint8)
self._cell_bool_array_names.append(name)
vtkarr = numpy_to_vtk(scalars, deep=deep)
vtkarr.SetName(name)
self.GetCellData().AddArray(vtkarr)
if set_active or self.active_scalar_info[1] is None:
self.GetCellData().SetActiveScalars(name)
self._active_scalar_info = [CELL_DATA_FIELD, name] | python | def _add_cell_scalar(self, scalars, name, set_active=False, deep=True):
"""
Adds cell scalars to the vtk object.
Parameters
----------
scalars : numpy.ndarray
Numpy array of scalars. Must match number of points.
name : str
Name of point scalars to add.
set_active : bool, optional
Sets the scalars to the active plotting scalars. Default False.
deep : bool, optional
Does not copy scalars when False. A reference to the scalars
must be kept to avoid a segfault.
"""
if not isinstance(scalars, np.ndarray):
raise TypeError('Input must be a numpy.ndarray')
if scalars.shape[0] != self.n_cells:
raise Exception('Number of scalars must match the number of cells (%d)'
% self.n_cells)
if not scalars.flags.c_contiguous:
raise AssertionError('Array must be contigious')
if scalars.dtype == np.bool:
scalars = scalars.view(np.uint8)
self._cell_bool_array_names.append(name)
vtkarr = numpy_to_vtk(scalars, deep=deep)
vtkarr.SetName(name)
self.GetCellData().AddArray(vtkarr)
if set_active or self.active_scalar_info[1] is None:
self.GetCellData().SetActiveScalars(name)
self._active_scalar_info = [CELL_DATA_FIELD, name] | [
"def",
"_add_cell_scalar",
"(",
"self",
",",
"scalars",
",",
"name",
",",
"set_active",
"=",
"False",
",",
"deep",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"scalars",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"'Input... | Adds cell scalars to the vtk object.
Parameters
----------
scalars : numpy.ndarray
Numpy array of scalars. Must match number of points.
name : str
Name of point scalars to add.
set_active : bool, optional
Sets the scalars to the active plotting scalars. Default False.
deep : bool, optional
Does not copy scalars when False. A reference to the scalars
must be kept to avoid a segfault. | [
"Adds",
"cell",
"scalars",
"to",
"the",
"vtk",
"object",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L496-L534 | train | 217,653 |
vtkiorg/vtki | vtki/common.py | Common.copy_meta_from | def copy_meta_from(self, ido):
"""Copies vtki meta data onto this object from another object"""
self._active_scalar_info = ido.active_scalar_info
self._active_vectors_info = ido.active_vectors_info
if hasattr(ido, '_textures'):
self._textures = ido._textures | python | def copy_meta_from(self, ido):
"""Copies vtki meta data onto this object from another object"""
self._active_scalar_info = ido.active_scalar_info
self._active_vectors_info = ido.active_vectors_info
if hasattr(ido, '_textures'):
self._textures = ido._textures | [
"def",
"copy_meta_from",
"(",
"self",
",",
"ido",
")",
":",
"self",
".",
"_active_scalar_info",
"=",
"ido",
".",
"active_scalar_info",
"self",
".",
"_active_vectors_info",
"=",
"ido",
".",
"active_vectors_info",
"if",
"hasattr",
"(",
"ido",
",",
"'_textures'",
... | Copies vtki meta data onto this object from another object | [
"Copies",
"vtki",
"meta",
"data",
"onto",
"this",
"object",
"from",
"another",
"object"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L536-L541 | train | 217,654 |
vtkiorg/vtki | vtki/common.py | Common.copy | def copy(self, deep=True):
"""
Returns a copy of the object
Parameters
----------
deep : bool, optional
When True makes a full copy of the object.
Returns
-------
newobject : same as input
Deep or shallow copy of the input.
"""
thistype = type(self)
newobject = thistype()
if deep:
newobject.DeepCopy(self)
else:
newobject.ShallowCopy(self)
newobject.copy_meta_from(self)
return newobject | python | def copy(self, deep=True):
"""
Returns a copy of the object
Parameters
----------
deep : bool, optional
When True makes a full copy of the object.
Returns
-------
newobject : same as input
Deep or shallow copy of the input.
"""
thistype = type(self)
newobject = thistype()
if deep:
newobject.DeepCopy(self)
else:
newobject.ShallowCopy(self)
newobject.copy_meta_from(self)
return newobject | [
"def",
"copy",
"(",
"self",
",",
"deep",
"=",
"True",
")",
":",
"thistype",
"=",
"type",
"(",
"self",
")",
"newobject",
"=",
"thistype",
"(",
")",
"if",
"deep",
":",
"newobject",
".",
"DeepCopy",
"(",
"self",
")",
"else",
":",
"newobject",
".",
"Sh... | Returns a copy of the object
Parameters
----------
deep : bool, optional
When True makes a full copy of the object.
Returns
-------
newobject : same as input
Deep or shallow copy of the input. | [
"Returns",
"a",
"copy",
"of",
"the",
"object"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L543-L564 | train | 217,655 |
vtkiorg/vtki | vtki/common.py | Common.point_arrays | def point_arrays(self):
""" Returns the all point arrays """
pdata = self.GetPointData()
narr = pdata.GetNumberOfArrays()
# Update data if necessary
if hasattr(self, '_point_arrays'):
keys = list(self._point_arrays.keys())
if narr == len(keys):
if keys:
if self._point_arrays[keys[0]].size == self.n_points:
return self._point_arrays
else:
return self._point_arrays
# dictionary with callbacks
self._point_arrays = PointScalarsDict(self)
for i in range(narr):
name = pdata.GetArrayName(i)
self._point_arrays[name] = self._point_scalar(name)
self._point_arrays.enable_callback()
return self._point_arrays | python | def point_arrays(self):
""" Returns the all point arrays """
pdata = self.GetPointData()
narr = pdata.GetNumberOfArrays()
# Update data if necessary
if hasattr(self, '_point_arrays'):
keys = list(self._point_arrays.keys())
if narr == len(keys):
if keys:
if self._point_arrays[keys[0]].size == self.n_points:
return self._point_arrays
else:
return self._point_arrays
# dictionary with callbacks
self._point_arrays = PointScalarsDict(self)
for i in range(narr):
name = pdata.GetArrayName(i)
self._point_arrays[name] = self._point_scalar(name)
self._point_arrays.enable_callback()
return self._point_arrays | [
"def",
"point_arrays",
"(",
"self",
")",
":",
"pdata",
"=",
"self",
".",
"GetPointData",
"(",
")",
"narr",
"=",
"pdata",
".",
"GetNumberOfArrays",
"(",
")",
"# Update data if necessary",
"if",
"hasattr",
"(",
"self",
",",
"'_point_arrays'",
")",
":",
"keys",... | Returns the all point arrays | [
"Returns",
"the",
"all",
"point",
"arrays"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L572-L595 | train | 217,656 |
vtkiorg/vtki | vtki/common.py | Common.cell_arrays | def cell_arrays(self):
""" Returns the all cell arrays """
cdata = self.GetCellData()
narr = cdata.GetNumberOfArrays()
# Update data if necessary
if hasattr(self, '_cell_arrays'):
keys = list(self._cell_arrays.keys())
if narr == len(keys):
if keys:
if self._cell_arrays[keys[0]].size == self.n_cells:
return self._cell_arrays
else:
return self._cell_arrays
# dictionary with callbacks
self._cell_arrays = CellScalarsDict(self)
for i in range(narr):
name = cdata.GetArrayName(i)
self._cell_arrays[name] = self._cell_scalar(name)
self._cell_arrays.enable_callback()
return self._cell_arrays | python | def cell_arrays(self):
""" Returns the all cell arrays """
cdata = self.GetCellData()
narr = cdata.GetNumberOfArrays()
# Update data if necessary
if hasattr(self, '_cell_arrays'):
keys = list(self._cell_arrays.keys())
if narr == len(keys):
if keys:
if self._cell_arrays[keys[0]].size == self.n_cells:
return self._cell_arrays
else:
return self._cell_arrays
# dictionary with callbacks
self._cell_arrays = CellScalarsDict(self)
for i in range(narr):
name = cdata.GetArrayName(i)
self._cell_arrays[name] = self._cell_scalar(name)
self._cell_arrays.enable_callback()
return self._cell_arrays | [
"def",
"cell_arrays",
"(",
"self",
")",
":",
"cdata",
"=",
"self",
".",
"GetCellData",
"(",
")",
"narr",
"=",
"cdata",
".",
"GetNumberOfArrays",
"(",
")",
"# Update data if necessary",
"if",
"hasattr",
"(",
"self",
",",
"'_cell_arrays'",
")",
":",
"keys",
... | Returns the all cell arrays | [
"Returns",
"the",
"all",
"cell",
"arrays"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L602-L625 | train | 217,657 |
vtkiorg/vtki | vtki/common.py | Common.get_data_range | def get_data_range(self, arr=None, preference='cell'):
"""Get the non-NaN min and max of a named scalar array
Parameters
----------
arr : str, np.ndarray, optional
The name of the array to get the range. If None, the active scalar
is used
preference : str, optional
When scalars is specified, this is the perfered scalar type to
search for in the dataset. Must be either ``'point'`` or ``'cell'``
"""
if arr is None:
# use active scalar array
_, arr = self.active_scalar_info
if isinstance(arr, str):
arr = get_scalar(self, arr, preference=preference)
# If array has no tuples return a NaN range
if arr is None or arr.size == 0:
return (np.nan, np.nan)
# Use the array range
return np.nanmin(arr), np.nanmax(arr) | python | def get_data_range(self, arr=None, preference='cell'):
"""Get the non-NaN min and max of a named scalar array
Parameters
----------
arr : str, np.ndarray, optional
The name of the array to get the range. If None, the active scalar
is used
preference : str, optional
When scalars is specified, this is the perfered scalar type to
search for in the dataset. Must be either ``'point'`` or ``'cell'``
"""
if arr is None:
# use active scalar array
_, arr = self.active_scalar_info
if isinstance(arr, str):
arr = get_scalar(self, arr, preference=preference)
# If array has no tuples return a NaN range
if arr is None or arr.size == 0:
return (np.nan, np.nan)
# Use the array range
return np.nanmin(arr), np.nanmax(arr) | [
"def",
"get_data_range",
"(",
"self",
",",
"arr",
"=",
"None",
",",
"preference",
"=",
"'cell'",
")",
":",
"if",
"arr",
"is",
"None",
":",
"# use active scalar array",
"_",
",",
"arr",
"=",
"self",
".",
"active_scalar_info",
"if",
"isinstance",
"(",
"arr",... | Get the non-NaN min and max of a named scalar array
Parameters
----------
arr : str, np.ndarray, optional
The name of the array to get the range. If None, the active scalar
is used
preference : str, optional
When scalars is specified, this is the perfered scalar type to
search for in the dataset. Must be either ``'point'`` or ``'cell'`` | [
"Get",
"the",
"non",
"-",
"NaN",
"min",
"and",
"max",
"of",
"a",
"named",
"scalar",
"array"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L685-L708 | train | 217,658 |
vtkiorg/vtki | vtki/common.py | Common.scalar_names | def scalar_names(self):
"""A list of scalar names for the dataset. This makes
sure to put the active scalar's name first in the list."""
names = []
for i in range(self.GetPointData().GetNumberOfArrays()):
names.append(self.GetPointData().GetArrayName(i))
for i in range(self.GetCellData().GetNumberOfArrays()):
names.append(self.GetCellData().GetArrayName(i))
try:
names.remove(self.active_scalar_name)
names.insert(0, self.active_scalar_name)
except ValueError:
pass
return names | python | def scalar_names(self):
"""A list of scalar names for the dataset. This makes
sure to put the active scalar's name first in the list."""
names = []
for i in range(self.GetPointData().GetNumberOfArrays()):
names.append(self.GetPointData().GetArrayName(i))
for i in range(self.GetCellData().GetNumberOfArrays()):
names.append(self.GetCellData().GetArrayName(i))
try:
names.remove(self.active_scalar_name)
names.insert(0, self.active_scalar_name)
except ValueError:
pass
return names | [
"def",
"scalar_names",
"(",
"self",
")",
":",
"names",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"GetPointData",
"(",
")",
".",
"GetNumberOfArrays",
"(",
")",
")",
":",
"names",
".",
"append",
"(",
"self",
".",
"GetPointData",
"(",
... | A list of scalar names for the dataset. This makes
sure to put the active scalar's name first in the list. | [
"A",
"list",
"of",
"scalar",
"names",
"for",
"the",
"dataset",
".",
"This",
"makes",
"sure",
"to",
"put",
"the",
"active",
"scalar",
"s",
"name",
"first",
"in",
"the",
"list",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L749-L762 | train | 217,659 |
vtkiorg/vtki | vtki/common.py | Common.head | def head(self, display=True, html=None):
"""Return the header stats of this dataset. If in IPython, this will
be formatted to HTML. Otherwise returns a console friendly string"""
# Generate the output
if html:
fmt = ""
# HTML version
fmt += "\n"
fmt += "<table>\n"
fmt += "<tr><th>{}</th><th>Information</th></tr>\n".format(type(self).__name__)
row = "<tr><td>{}</td><td>{}</td></tr>\n"
# now make a call on the object to get its attributes as a list of len 2 tuples
for attr in self._get_attrs():
try:
fmt += row.format(attr[0], attr[2].format(*attr[1]))
except:
fmt += row.format(attr[0], attr[2].format(attr[1]))
fmt += row.format('N Scalars', self.n_scalars)
fmt += "</table>\n"
fmt += "\n"
if display:
from IPython.display import display, HTML
display(HTML(fmt))
return
return fmt
# Otherwise return a string that is Python console friendly
fmt = "{} ({})\n".format(type(self).__name__, hex(id(self)))
# now make a call on the object to get its attributes as a list of len 2 tuples
row = " {}:\t{}\n"
for attr in self._get_attrs():
try:
fmt += row.format(attr[0], attr[2].format(*attr[1]))
except:
fmt += row.format(attr[0], attr[2].format(attr[1]))
fmt += row.format('N Scalars', self.n_scalars)
return fmt | python | def head(self, display=True, html=None):
"""Return the header stats of this dataset. If in IPython, this will
be formatted to HTML. Otherwise returns a console friendly string"""
# Generate the output
if html:
fmt = ""
# HTML version
fmt += "\n"
fmt += "<table>\n"
fmt += "<tr><th>{}</th><th>Information</th></tr>\n".format(type(self).__name__)
row = "<tr><td>{}</td><td>{}</td></tr>\n"
# now make a call on the object to get its attributes as a list of len 2 tuples
for attr in self._get_attrs():
try:
fmt += row.format(attr[0], attr[2].format(*attr[1]))
except:
fmt += row.format(attr[0], attr[2].format(attr[1]))
fmt += row.format('N Scalars', self.n_scalars)
fmt += "</table>\n"
fmt += "\n"
if display:
from IPython.display import display, HTML
display(HTML(fmt))
return
return fmt
# Otherwise return a string that is Python console friendly
fmt = "{} ({})\n".format(type(self).__name__, hex(id(self)))
# now make a call on the object to get its attributes as a list of len 2 tuples
row = " {}:\t{}\n"
for attr in self._get_attrs():
try:
fmt += row.format(attr[0], attr[2].format(*attr[1]))
except:
fmt += row.format(attr[0], attr[2].format(attr[1]))
fmt += row.format('N Scalars', self.n_scalars)
return fmt | [
"def",
"head",
"(",
"self",
",",
"display",
"=",
"True",
",",
"html",
"=",
"None",
")",
":",
"# Generate the output",
"if",
"html",
":",
"fmt",
"=",
"\"\"",
"# HTML version",
"fmt",
"+=",
"\"\\n\"",
"fmt",
"+=",
"\"<table>\\n\"",
"fmt",
"+=",
"\"<tr><th>{}... | Return the header stats of this dataset. If in IPython, this will
be formatted to HTML. Otherwise returns a console friendly string | [
"Return",
"the",
"header",
"stats",
"of",
"this",
"dataset",
".",
"If",
"in",
"IPython",
"this",
"will",
"be",
"formatted",
"to",
"HTML",
".",
"Otherwise",
"returns",
"a",
"console",
"friendly",
"string"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L779-L814 | train | 217,660 |
vtkiorg/vtki | vtki/common.py | Common._repr_html_ | def _repr_html_(self):
"""A pretty representation for Jupyter notebooks that includes header
details and information about all scalar arrays"""
fmt = ""
if self.n_scalars > 0:
fmt += "<table>"
fmt += "<tr><th>Header</th><th>Data Arrays</th></tr>"
fmt += "<tr><td>"
# Get the header info
fmt += self.head(display=False, html=True)
# Fill out scalar arrays
if self.n_scalars > 0:
fmt += "</td><td>"
fmt += "\n"
fmt += "<table>\n"
row = "<tr><th>{}</th><th>{}</th><th>{}</th><th>{}</th><th>{}</th></tr>\n"
fmt += row.format("Name", "Field", "Type", "Min", "Max")
row = "<tr><td>{}</td><td>{}</td><td>{}</td><td>{:.3e}</td><td>{:.3e}</td></tr>\n"
def format_array(key, field):
"""internal helper to foramt array information for printing"""
arr = get_scalar(self, key)
dl, dh = self.get_data_range(key)
if key == self.active_scalar_info[1]:
key = '<b>{}</b>'.format(key)
return row.format(key, field, arr.dtype, dl, dh)
for i in range(self.GetPointData().GetNumberOfArrays()):
key = self.GetPointData().GetArrayName(i)
fmt += format_array(key, field='Points')
for i in range(self.GetCellData().GetNumberOfArrays()):
key = self.GetCellData().GetArrayName(i)
fmt += format_array(key, field='Cells')
fmt += "</table>\n"
fmt += "\n"
fmt += "</td></tr> </table>"
return fmt | python | def _repr_html_(self):
"""A pretty representation for Jupyter notebooks that includes header
details and information about all scalar arrays"""
fmt = ""
if self.n_scalars > 0:
fmt += "<table>"
fmt += "<tr><th>Header</th><th>Data Arrays</th></tr>"
fmt += "<tr><td>"
# Get the header info
fmt += self.head(display=False, html=True)
# Fill out scalar arrays
if self.n_scalars > 0:
fmt += "</td><td>"
fmt += "\n"
fmt += "<table>\n"
row = "<tr><th>{}</th><th>{}</th><th>{}</th><th>{}</th><th>{}</th></tr>\n"
fmt += row.format("Name", "Field", "Type", "Min", "Max")
row = "<tr><td>{}</td><td>{}</td><td>{}</td><td>{:.3e}</td><td>{:.3e}</td></tr>\n"
def format_array(key, field):
"""internal helper to foramt array information for printing"""
arr = get_scalar(self, key)
dl, dh = self.get_data_range(key)
if key == self.active_scalar_info[1]:
key = '<b>{}</b>'.format(key)
return row.format(key, field, arr.dtype, dl, dh)
for i in range(self.GetPointData().GetNumberOfArrays()):
key = self.GetPointData().GetArrayName(i)
fmt += format_array(key, field='Points')
for i in range(self.GetCellData().GetNumberOfArrays()):
key = self.GetCellData().GetArrayName(i)
fmt += format_array(key, field='Cells')
fmt += "</table>\n"
fmt += "\n"
fmt += "</td></tr> </table>"
return fmt | [
"def",
"_repr_html_",
"(",
"self",
")",
":",
"fmt",
"=",
"\"\"",
"if",
"self",
".",
"n_scalars",
">",
"0",
":",
"fmt",
"+=",
"\"<table>\"",
"fmt",
"+=",
"\"<tr><th>Header</th><th>Data Arrays</th></tr>\"",
"fmt",
"+=",
"\"<tr><td>\"",
"# Get the header info",
"fmt"... | A pretty representation for Jupyter notebooks that includes header
details and information about all scalar arrays | [
"A",
"pretty",
"representation",
"for",
"Jupyter",
"notebooks",
"that",
"includes",
"header",
"details",
"and",
"information",
"about",
"all",
"scalar",
"arrays"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L817-L853 | train | 217,661 |
vtkiorg/vtki | vtki/common.py | Common.overwrite | def overwrite(self, mesh):
"""
Overwrites this mesh inplace with the new mesh's geometries and data
Parameters
----------
mesh : vtk.vtkDataSet
The overwriting mesh.
"""
self.DeepCopy(mesh)
if is_vtki_obj(mesh):
self.copy_meta_from(mesh) | python | def overwrite(self, mesh):
"""
Overwrites this mesh inplace with the new mesh's geometries and data
Parameters
----------
mesh : vtk.vtkDataSet
The overwriting mesh.
"""
self.DeepCopy(mesh)
if is_vtki_obj(mesh):
self.copy_meta_from(mesh) | [
"def",
"overwrite",
"(",
"self",
",",
"mesh",
")",
":",
"self",
".",
"DeepCopy",
"(",
"mesh",
")",
"if",
"is_vtki_obj",
"(",
"mesh",
")",
":",
"self",
".",
"copy_meta_from",
"(",
"mesh",
")"
] | Overwrites this mesh inplace with the new mesh's geometries and data
Parameters
----------
mesh : vtk.vtkDataSet
The overwriting mesh. | [
"Overwrites",
"this",
"mesh",
"inplace",
"with",
"the",
"new",
"mesh",
"s",
"geometries",
"and",
"data"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L864-L876 | train | 217,662 |
vtkiorg/vtki | vtki/common.py | _ScalarsDict.pop | def pop(self, key):
"""Get and remove an element by key name"""
arr = dict.pop(self, key).copy()
self.remover(key)
return arr | python | def pop(self, key):
"""Get and remove an element by key name"""
arr = dict.pop(self, key).copy()
self.remover(key)
return arr | [
"def",
"pop",
"(",
"self",
",",
"key",
")",
":",
"arr",
"=",
"dict",
".",
"pop",
"(",
"self",
",",
"key",
")",
".",
"copy",
"(",
")",
"self",
".",
"remover",
"(",
"key",
")",
"return",
"arr"
] | Get and remove an element by key name | [
"Get",
"and",
"remove",
"an",
"element",
"by",
"key",
"name"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L901-L905 | train | 217,663 |
vtkiorg/vtki | vtki/common.py | _ScalarsDict.update | def update(self, data):
"""
Update this dictionary with th key-value pairs from a given
dictionary
"""
if not isinstance(data, dict):
raise TypeError('Data to update must be in a dictionary.')
for k, v in data.items():
arr = np.array(v)
try:
self[k] = arr
except TypeError:
logging.warning("Values under key ({}) not supported by VTK".format(k))
return | python | def update(self, data):
"""
Update this dictionary with th key-value pairs from a given
dictionary
"""
if not isinstance(data, dict):
raise TypeError('Data to update must be in a dictionary.')
for k, v in data.items():
arr = np.array(v)
try:
self[k] = arr
except TypeError:
logging.warning("Values under key ({}) not supported by VTK".format(k))
return | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'Data to update must be in a dictionary.'",
")",
"for",
"k",
",",
"v",
"in",
"data",
".",
"items",
"(",
")",
... | Update this dictionary with th key-value pairs from a given
dictionary | [
"Update",
"this",
"dictionary",
"with",
"th",
"key",
"-",
"value",
"pairs",
"from",
"a",
"given",
"dictionary"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L907-L920 | train | 217,664 |
chardet/chardet | convert_language_model.py | convert_sbcs_model | def convert_sbcs_model(old_model, alphabet):
"""Create a SingleByteCharSetModel object representing the charset."""
# Setup tables necessary for computing transition frequencies for model
char_to_order = {i: order
for i, order in enumerate(old_model['char_to_order_map'])}
pos_ratio = old_model['typical_positive_ratio']
keep_ascii_letters = old_model['keep_english_letter']
curr_model = SingleByteCharSetModel(charset_name=old_model['charset_name'],
language=old_model['language'],
char_to_order_map=char_to_order,
# language_model is filled in later
language_model=None,
typical_positive_ratio=pos_ratio,
keep_ascii_letters=keep_ascii_letters,
alphabet=alphabet)
return curr_model | python | def convert_sbcs_model(old_model, alphabet):
"""Create a SingleByteCharSetModel object representing the charset."""
# Setup tables necessary for computing transition frequencies for model
char_to_order = {i: order
for i, order in enumerate(old_model['char_to_order_map'])}
pos_ratio = old_model['typical_positive_ratio']
keep_ascii_letters = old_model['keep_english_letter']
curr_model = SingleByteCharSetModel(charset_name=old_model['charset_name'],
language=old_model['language'],
char_to_order_map=char_to_order,
# language_model is filled in later
language_model=None,
typical_positive_ratio=pos_ratio,
keep_ascii_letters=keep_ascii_letters,
alphabet=alphabet)
return curr_model | [
"def",
"convert_sbcs_model",
"(",
"old_model",
",",
"alphabet",
")",
":",
"# Setup tables necessary for computing transition frequencies for model",
"char_to_order",
"=",
"{",
"i",
":",
"order",
"for",
"i",
",",
"order",
"in",
"enumerate",
"(",
"old_model",
"[",
"'cha... | Create a SingleByteCharSetModel object representing the charset. | [
"Create",
"a",
"SingleByteCharSetModel",
"object",
"representing",
"the",
"charset",
"."
] | b5194bf8250b7d180ac4edff51e09cab9d99febe | https://github.com/chardet/chardet/blob/b5194bf8250b7d180ac4edff51e09cab9d99febe/convert_language_model.py#L57-L73 | train | 217,665 |
chardet/chardet | bench.py | get_py_impl | def get_py_impl():
"""Return what kind of Python this is"""
if hasattr(sys, 'pypy_version_info'):
pyimpl = 'PyPy'
elif sys.platform.startswith('java'):
pyimpl = 'Jython'
elif sys.platform == 'cli':
pyimpl = 'IronPython'
else:
pyimpl = 'CPython'
return pyimpl | python | def get_py_impl():
"""Return what kind of Python this is"""
if hasattr(sys, 'pypy_version_info'):
pyimpl = 'PyPy'
elif sys.platform.startswith('java'):
pyimpl = 'Jython'
elif sys.platform == 'cli':
pyimpl = 'IronPython'
else:
pyimpl = 'CPython'
return pyimpl | [
"def",
"get_py_impl",
"(",
")",
":",
"if",
"hasattr",
"(",
"sys",
",",
"'pypy_version_info'",
")",
":",
"pyimpl",
"=",
"'PyPy'",
"elif",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'java'",
")",
":",
"pyimpl",
"=",
"'Jython'",
"elif",
"sys",
".",
... | Return what kind of Python this is | [
"Return",
"what",
"kind",
"of",
"Python",
"this",
"is"
] | b5194bf8250b7d180ac4edff51e09cab9d99febe | https://github.com/chardet/chardet/blob/b5194bf8250b7d180ac4edff51e09cab9d99febe/bench.py#L36-L46 | train | 217,666 |
chardet/chardet | chardet/__init__.py | detect_all | def detect_all(byte_str):
"""
Detect all the possible encodings of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray``
"""
if not isinstance(byte_str, bytearray):
if not isinstance(byte_str, bytes):
raise TypeError('Expected object of type bytes or bytearray, got: '
'{0}'.format(type(byte_str)))
else:
byte_str = bytearray(byte_str)
detector = UniversalDetector()
detector.feed(byte_str)
detector.close()
if detector._input_state == InputState.HIGH_BYTE:
results = []
for prober in detector._charset_probers:
if prober.get_confidence() > detector.MINIMUM_THRESHOLD:
charset_name = prober.charset_name
lower_charset_name = prober.charset_name.lower()
# Use Windows encoding name instead of ISO-8859 if we saw any
# extra Windows-specific bytes
if lower_charset_name.startswith('iso-8859'):
if detector._has_win_bytes:
charset_name = detector.ISO_WIN_MAP.get(lower_charset_name,
charset_name)
results.append({
'encoding': charset_name,
'confidence': prober.get_confidence()
})
if len(results) > 0:
return sorted(results, key=lambda result: -result['confidence'])
return [detector.result] | python | def detect_all(byte_str):
"""
Detect all the possible encodings of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray``
"""
if not isinstance(byte_str, bytearray):
if not isinstance(byte_str, bytes):
raise TypeError('Expected object of type bytes or bytearray, got: '
'{0}'.format(type(byte_str)))
else:
byte_str = bytearray(byte_str)
detector = UniversalDetector()
detector.feed(byte_str)
detector.close()
if detector._input_state == InputState.HIGH_BYTE:
results = []
for prober in detector._charset_probers:
if prober.get_confidence() > detector.MINIMUM_THRESHOLD:
charset_name = prober.charset_name
lower_charset_name = prober.charset_name.lower()
# Use Windows encoding name instead of ISO-8859 if we saw any
# extra Windows-specific bytes
if lower_charset_name.startswith('iso-8859'):
if detector._has_win_bytes:
charset_name = detector.ISO_WIN_MAP.get(lower_charset_name,
charset_name)
results.append({
'encoding': charset_name,
'confidence': prober.get_confidence()
})
if len(results) > 0:
return sorted(results, key=lambda result: -result['confidence'])
return [detector.result] | [
"def",
"detect_all",
"(",
"byte_str",
")",
":",
"if",
"not",
"isinstance",
"(",
"byte_str",
",",
"bytearray",
")",
":",
"if",
"not",
"isinstance",
"(",
"byte_str",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"'Expected object of type bytes or bytearray, g... | Detect all the possible encodings of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray`` | [
"Detect",
"all",
"the",
"possible",
"encodings",
"of",
"the",
"given",
"byte",
"string",
"."
] | b5194bf8250b7d180ac4edff51e09cab9d99febe | https://github.com/chardet/chardet/blob/b5194bf8250b7d180ac4edff51e09cab9d99febe/chardet/__init__.py#L45-L82 | train | 217,667 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | geojson_to_wkt | def geojson_to_wkt(geojson_obj, feature_number=0, decimals=4):
"""Convert a GeoJSON object to Well-Known Text. Intended for use with OpenSearch queries.
In case of FeatureCollection, only one of the features is used (the first by default).
3D points are converted to 2D.
Parameters
----------
geojson_obj : dict
a GeoJSON object
feature_number : int, optional
Feature to extract polygon from (in case of MultiPolygon
FeatureCollection), defaults to first Feature
decimals : int, optional
Number of decimal figures after point to round coordinate to. Defaults to 4 (about 10
meters).
Returns
-------
polygon coordinates
string of comma separated coordinate tuples (lon, lat) to be used by SentinelAPI
"""
if 'coordinates' in geojson_obj:
geometry = geojson_obj
elif 'geometry' in geojson_obj:
geometry = geojson_obj['geometry']
else:
geometry = geojson_obj['features'][feature_number]['geometry']
def ensure_2d(geometry):
if isinstance(geometry[0], (list, tuple)):
return list(map(ensure_2d, geometry))
else:
return geometry[:2]
def check_bounds(geometry):
if isinstance(geometry[0], (list, tuple)):
return list(map(check_bounds, geometry))
else:
if geometry[0] > 180 or geometry[0] < -180:
raise ValueError('Longitude is out of bounds, check your JSON format or data')
if geometry[1] > 90 or geometry[1] < -90:
raise ValueError('Latitude is out of bounds, check your JSON format or data')
# Discard z-coordinate, if it exists
geometry['coordinates'] = ensure_2d(geometry['coordinates'])
check_bounds(geometry['coordinates'])
wkt = geomet.wkt.dumps(geometry, decimals=decimals)
# Strip unnecessary spaces
wkt = re.sub(r'(?<!\d) ', '', wkt)
return wkt | python | def geojson_to_wkt(geojson_obj, feature_number=0, decimals=4):
"""Convert a GeoJSON object to Well-Known Text. Intended for use with OpenSearch queries.
In case of FeatureCollection, only one of the features is used (the first by default).
3D points are converted to 2D.
Parameters
----------
geojson_obj : dict
a GeoJSON object
feature_number : int, optional
Feature to extract polygon from (in case of MultiPolygon
FeatureCollection), defaults to first Feature
decimals : int, optional
Number of decimal figures after point to round coordinate to. Defaults to 4 (about 10
meters).
Returns
-------
polygon coordinates
string of comma separated coordinate tuples (lon, lat) to be used by SentinelAPI
"""
if 'coordinates' in geojson_obj:
geometry = geojson_obj
elif 'geometry' in geojson_obj:
geometry = geojson_obj['geometry']
else:
geometry = geojson_obj['features'][feature_number]['geometry']
def ensure_2d(geometry):
if isinstance(geometry[0], (list, tuple)):
return list(map(ensure_2d, geometry))
else:
return geometry[:2]
def check_bounds(geometry):
if isinstance(geometry[0], (list, tuple)):
return list(map(check_bounds, geometry))
else:
if geometry[0] > 180 or geometry[0] < -180:
raise ValueError('Longitude is out of bounds, check your JSON format or data')
if geometry[1] > 90 or geometry[1] < -90:
raise ValueError('Latitude is out of bounds, check your JSON format or data')
# Discard z-coordinate, if it exists
geometry['coordinates'] = ensure_2d(geometry['coordinates'])
check_bounds(geometry['coordinates'])
wkt = geomet.wkt.dumps(geometry, decimals=decimals)
# Strip unnecessary spaces
wkt = re.sub(r'(?<!\d) ', '', wkt)
return wkt | [
"def",
"geojson_to_wkt",
"(",
"geojson_obj",
",",
"feature_number",
"=",
"0",
",",
"decimals",
"=",
"4",
")",
":",
"if",
"'coordinates'",
"in",
"geojson_obj",
":",
"geometry",
"=",
"geojson_obj",
"elif",
"'geometry'",
"in",
"geojson_obj",
":",
"geometry",
"=",... | Convert a GeoJSON object to Well-Known Text. Intended for use with OpenSearch queries.
In case of FeatureCollection, only one of the features is used (the first by default).
3D points are converted to 2D.
Parameters
----------
geojson_obj : dict
a GeoJSON object
feature_number : int, optional
Feature to extract polygon from (in case of MultiPolygon
FeatureCollection), defaults to first Feature
decimals : int, optional
Number of decimal figures after point to round coordinate to. Defaults to 4 (about 10
meters).
Returns
-------
polygon coordinates
string of comma separated coordinate tuples (lon, lat) to be used by SentinelAPI | [
"Convert",
"a",
"GeoJSON",
"object",
"to",
"Well",
"-",
"Known",
"Text",
".",
"Intended",
"for",
"use",
"with",
"OpenSearch",
"queries",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L889-L940 | train | 217,668 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | _check_scihub_response | def _check_scihub_response(response, test_json=True):
"""Check that the response from server has status code 2xx and that the response is valid JSON.
"""
# Prevent requests from needing to guess the encoding
# SciHub appears to be using UTF-8 in all of their responses
response.encoding = 'utf-8'
try:
response.raise_for_status()
if test_json:
response.json()
except (requests.HTTPError, ValueError):
msg = "Invalid API response."
try:
msg = response.headers['cause-message']
except:
try:
msg = response.json()['error']['message']['value']
except:
if not response.text.strip().startswith('{'):
try:
h = html2text.HTML2Text()
h.ignore_images = True
h.ignore_anchors = True
msg = h.handle(response.text).strip()
except:
pass
api_error = SentinelAPIError(msg, response)
# Suppress "During handling of the above exception..." message
# See PEP 409
api_error.__cause__ = None
raise api_error | python | def _check_scihub_response(response, test_json=True):
"""Check that the response from server has status code 2xx and that the response is valid JSON.
"""
# Prevent requests from needing to guess the encoding
# SciHub appears to be using UTF-8 in all of their responses
response.encoding = 'utf-8'
try:
response.raise_for_status()
if test_json:
response.json()
except (requests.HTTPError, ValueError):
msg = "Invalid API response."
try:
msg = response.headers['cause-message']
except:
try:
msg = response.json()['error']['message']['value']
except:
if not response.text.strip().startswith('{'):
try:
h = html2text.HTML2Text()
h.ignore_images = True
h.ignore_anchors = True
msg = h.handle(response.text).strip()
except:
pass
api_error = SentinelAPIError(msg, response)
# Suppress "During handling of the above exception..." message
# See PEP 409
api_error.__cause__ = None
raise api_error | [
"def",
"_check_scihub_response",
"(",
"response",
",",
"test_json",
"=",
"True",
")",
":",
"# Prevent requests from needing to guess the encoding",
"# SciHub appears to be using UTF-8 in all of their responses",
"response",
".",
"encoding",
"=",
"'utf-8'",
"try",
":",
"response... | Check that the response from server has status code 2xx and that the response is valid JSON. | [
"Check",
"that",
"the",
"response",
"from",
"server",
"has",
"status",
"code",
"2xx",
"and",
"that",
"the",
"response",
"is",
"valid",
"JSON",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L997-L1027 | train | 217,669 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | _parse_odata_timestamp | def _parse_odata_timestamp(in_date):
"""Convert the timestamp received from OData JSON API to a datetime object.
"""
timestamp = int(in_date.replace('/Date(', '').replace(')/', ''))
seconds = timestamp // 1000
ms = timestamp % 1000
return datetime.utcfromtimestamp(seconds) + timedelta(milliseconds=ms) | python | def _parse_odata_timestamp(in_date):
"""Convert the timestamp received from OData JSON API to a datetime object.
"""
timestamp = int(in_date.replace('/Date(', '').replace(')/', ''))
seconds = timestamp // 1000
ms = timestamp % 1000
return datetime.utcfromtimestamp(seconds) + timedelta(milliseconds=ms) | [
"def",
"_parse_odata_timestamp",
"(",
"in_date",
")",
":",
"timestamp",
"=",
"int",
"(",
"in_date",
".",
"replace",
"(",
"'/Date('",
",",
"''",
")",
".",
"replace",
"(",
"')/'",
",",
"''",
")",
")",
"seconds",
"=",
"timestamp",
"//",
"1000",
"ms",
"=",... | Convert the timestamp received from OData JSON API to a datetime object. | [
"Convert",
"the",
"timestamp",
"received",
"from",
"OData",
"JSON",
"API",
"to",
"a",
"datetime",
"object",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L1066-L1072 | train | 217,670 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | _parse_opensearch_response | def _parse_opensearch_response(products):
"""Convert a query response to a dictionary.
The resulting dictionary structure is {<product id>: {<property>: <value>}}.
The property values are converted to their respective Python types unless `parse_values`
is set to `False`.
"""
converters = {'date': _parse_iso_date, 'int': int, 'long': int, 'float': float, 'double': float}
# Keep the string type by default
default_converter = lambda x: x
output = OrderedDict()
for prod in products:
product_dict = {}
prod_id = prod['id']
output[prod_id] = product_dict
for key in prod:
if key == 'id':
continue
if isinstance(prod[key], string_types):
product_dict[key] = prod[key]
else:
properties = prod[key]
if isinstance(properties, dict):
properties = [properties]
if key == 'link':
for p in properties:
name = 'link'
if 'rel' in p:
name = 'link_' + p['rel']
product_dict[name] = p['href']
else:
f = converters.get(key, default_converter)
for p in properties:
try:
product_dict[p['name']] = f(p['content'])
except KeyError:
# Sentinel-3 has one element 'arr'
# which violates the name:content convention
product_dict[p['name']] = f(p['str'])
return output | python | def _parse_opensearch_response(products):
"""Convert a query response to a dictionary.
The resulting dictionary structure is {<product id>: {<property>: <value>}}.
The property values are converted to their respective Python types unless `parse_values`
is set to `False`.
"""
converters = {'date': _parse_iso_date, 'int': int, 'long': int, 'float': float, 'double': float}
# Keep the string type by default
default_converter = lambda x: x
output = OrderedDict()
for prod in products:
product_dict = {}
prod_id = prod['id']
output[prod_id] = product_dict
for key in prod:
if key == 'id':
continue
if isinstance(prod[key], string_types):
product_dict[key] = prod[key]
else:
properties = prod[key]
if isinstance(properties, dict):
properties = [properties]
if key == 'link':
for p in properties:
name = 'link'
if 'rel' in p:
name = 'link_' + p['rel']
product_dict[name] = p['href']
else:
f = converters.get(key, default_converter)
for p in properties:
try:
product_dict[p['name']] = f(p['content'])
except KeyError:
# Sentinel-3 has one element 'arr'
# which violates the name:content convention
product_dict[p['name']] = f(p['str'])
return output | [
"def",
"_parse_opensearch_response",
"(",
"products",
")",
":",
"converters",
"=",
"{",
"'date'",
":",
"_parse_iso_date",
",",
"'int'",
":",
"int",
",",
"'long'",
":",
"int",
",",
"'float'",
":",
"float",
",",
"'double'",
":",
"float",
"}",
"# Keep the strin... | Convert a query response to a dictionary.
The resulting dictionary structure is {<product id>: {<property>: <value>}}.
The property values are converted to their respective Python types unless `parse_values`
is set to `False`. | [
"Convert",
"a",
"query",
"response",
"to",
"a",
"dictionary",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L1075-L1116 | train | 217,671 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI.query | def query(self, area=None, date=None, raw=None, area_relation='Intersects',
order_by=None, limit=None, offset=0, **keywords):
"""Query the OpenSearch API with the coordinates of an area, a date interval
and any other search keywords accepted by the API.
Parameters
----------
area : str, optional
The area of interest formatted as a Well-Known Text string.
date : tuple of (str or datetime) or str, optional
A time interval filter based on the Sensing Start Time of the products.
Expects a tuple of (start, end), e.g. ("NOW-1DAY", "NOW").
The timestamps can be either a Python datetime or a string in one of the
following formats:
- yyyyMMdd
- yyyy-MM-ddThh:mm:ss.SSSZ (ISO-8601)
- yyyy-MM-ddThh:mm:ssZ
- NOW
- NOW-<n>DAY(S) (or HOUR(S), MONTH(S), etc.)
- NOW+<n>DAY(S)
- yyyy-MM-ddThh:mm:ssZ-<n>DAY(S)
- NOW/DAY (or HOUR, MONTH etc.) - rounds the value to the given unit
Alternatively, an already fully formatted string such as "[NOW-1DAY TO NOW]" can be
used as well.
raw : str, optional
Additional query text that will be appended to the query.
area_relation : {'Intersects', 'Contains', 'IsWithin'}, optional
What relation to use for testing the AOI. Case insensitive.
- Intersects: true if the AOI and the footprint intersect (default)
- Contains: true if the AOI is inside the footprint
- IsWithin: true if the footprint is inside the AOI
order_by: str, optional
A comma-separated list of fields to order by (on server side).
Prefix the field name by '+' or '-' to sort in ascending or descending order,
respectively. Ascending order is used if prefix is omitted.
Example: "cloudcoverpercentage, -beginposition".
limit: int, optional
Maximum number of products returned. Defaults to no limit.
offset: int, optional
The number of results to skip. Defaults to 0.
**keywords
Additional keywords can be used to specify other query parameters,
e.g. `relativeorbitnumber=70`.
See https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
for a full list.
Range values can be passed as two-element tuples, e.g. `cloudcoverpercentage=(0, 30)`.
`None` can be used in range values for one-sided ranges, e.g. `orbitnumber=(16302, None)`.
Ranges with no bounds (`orbitnumber=(None, None)`) will not be included in the query.
The time interval formats accepted by the `date` parameter can also be used with
any other parameters that expect time intervals (that is: 'beginposition', 'endposition',
'date', 'creationdate', and 'ingestiondate').
Returns
-------
dict[string, dict]
Products returned by the query as a dictionary with the product ID as the key and
the product's attributes (a dictionary) as the value.
"""
query = self.format_query(area, date, raw, area_relation, **keywords)
self.logger.debug("Running query: order_by=%s, limit=%s, offset=%s, query=%s",
order_by, limit, offset, query)
formatted_order_by = _format_order_by(order_by)
response, count = self._load_query(query, formatted_order_by, limit, offset)
self.logger.info("Found %s products", count)
return _parse_opensearch_response(response) | python | def query(self, area=None, date=None, raw=None, area_relation='Intersects',
order_by=None, limit=None, offset=0, **keywords):
"""Query the OpenSearch API with the coordinates of an area, a date interval
and any other search keywords accepted by the API.
Parameters
----------
area : str, optional
The area of interest formatted as a Well-Known Text string.
date : tuple of (str or datetime) or str, optional
A time interval filter based on the Sensing Start Time of the products.
Expects a tuple of (start, end), e.g. ("NOW-1DAY", "NOW").
The timestamps can be either a Python datetime or a string in one of the
following formats:
- yyyyMMdd
- yyyy-MM-ddThh:mm:ss.SSSZ (ISO-8601)
- yyyy-MM-ddThh:mm:ssZ
- NOW
- NOW-<n>DAY(S) (or HOUR(S), MONTH(S), etc.)
- NOW+<n>DAY(S)
- yyyy-MM-ddThh:mm:ssZ-<n>DAY(S)
- NOW/DAY (or HOUR, MONTH etc.) - rounds the value to the given unit
Alternatively, an already fully formatted string such as "[NOW-1DAY TO NOW]" can be
used as well.
raw : str, optional
Additional query text that will be appended to the query.
area_relation : {'Intersects', 'Contains', 'IsWithin'}, optional
What relation to use for testing the AOI. Case insensitive.
- Intersects: true if the AOI and the footprint intersect (default)
- Contains: true if the AOI is inside the footprint
- IsWithin: true if the footprint is inside the AOI
order_by: str, optional
A comma-separated list of fields to order by (on server side).
Prefix the field name by '+' or '-' to sort in ascending or descending order,
respectively. Ascending order is used if prefix is omitted.
Example: "cloudcoverpercentage, -beginposition".
limit: int, optional
Maximum number of products returned. Defaults to no limit.
offset: int, optional
The number of results to skip. Defaults to 0.
**keywords
Additional keywords can be used to specify other query parameters,
e.g. `relativeorbitnumber=70`.
See https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
for a full list.
Range values can be passed as two-element tuples, e.g. `cloudcoverpercentage=(0, 30)`.
`None` can be used in range values for one-sided ranges, e.g. `orbitnumber=(16302, None)`.
Ranges with no bounds (`orbitnumber=(None, None)`) will not be included in the query.
The time interval formats accepted by the `date` parameter can also be used with
any other parameters that expect time intervals (that is: 'beginposition', 'endposition',
'date', 'creationdate', and 'ingestiondate').
Returns
-------
dict[string, dict]
Products returned by the query as a dictionary with the product ID as the key and
the product's attributes (a dictionary) as the value.
"""
query = self.format_query(area, date, raw, area_relation, **keywords)
self.logger.debug("Running query: order_by=%s, limit=%s, offset=%s, query=%s",
order_by, limit, offset, query)
formatted_order_by = _format_order_by(order_by)
response, count = self._load_query(query, formatted_order_by, limit, offset)
self.logger.info("Found %s products", count)
return _parse_opensearch_response(response) | [
"def",
"query",
"(",
"self",
",",
"area",
"=",
"None",
",",
"date",
"=",
"None",
",",
"raw",
"=",
"None",
",",
"area_relation",
"=",
"'Intersects'",
",",
"order_by",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"0",
",",
"*",
"*",
... | Query the OpenSearch API with the coordinates of an area, a date interval
and any other search keywords accepted by the API.
Parameters
----------
area : str, optional
The area of interest formatted as a Well-Known Text string.
date : tuple of (str or datetime) or str, optional
A time interval filter based on the Sensing Start Time of the products.
Expects a tuple of (start, end), e.g. ("NOW-1DAY", "NOW").
The timestamps can be either a Python datetime or a string in one of the
following formats:
- yyyyMMdd
- yyyy-MM-ddThh:mm:ss.SSSZ (ISO-8601)
- yyyy-MM-ddThh:mm:ssZ
- NOW
- NOW-<n>DAY(S) (or HOUR(S), MONTH(S), etc.)
- NOW+<n>DAY(S)
- yyyy-MM-ddThh:mm:ssZ-<n>DAY(S)
- NOW/DAY (or HOUR, MONTH etc.) - rounds the value to the given unit
Alternatively, an already fully formatted string such as "[NOW-1DAY TO NOW]" can be
used as well.
raw : str, optional
Additional query text that will be appended to the query.
area_relation : {'Intersects', 'Contains', 'IsWithin'}, optional
What relation to use for testing the AOI. Case insensitive.
- Intersects: true if the AOI and the footprint intersect (default)
- Contains: true if the AOI is inside the footprint
- IsWithin: true if the footprint is inside the AOI
order_by: str, optional
A comma-separated list of fields to order by (on server side).
Prefix the field name by '+' or '-' to sort in ascending or descending order,
respectively. Ascending order is used if prefix is omitted.
Example: "cloudcoverpercentage, -beginposition".
limit: int, optional
Maximum number of products returned. Defaults to no limit.
offset: int, optional
The number of results to skip. Defaults to 0.
**keywords
Additional keywords can be used to specify other query parameters,
e.g. `relativeorbitnumber=70`.
See https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
for a full list.
Range values can be passed as two-element tuples, e.g. `cloudcoverpercentage=(0, 30)`.
`None` can be used in range values for one-sided ranges, e.g. `orbitnumber=(16302, None)`.
Ranges with no bounds (`orbitnumber=(None, None)`) will not be included in the query.
The time interval formats accepted by the `date` parameter can also be used with
any other parameters that expect time intervals (that is: 'beginposition', 'endposition',
'date', 'creationdate', and 'ingestiondate').
Returns
-------
dict[string, dict]
Products returned by the query as a dictionary with the product ID as the key and
the product's attributes (a dictionary) as the value. | [
"Query",
"the",
"OpenSearch",
"API",
"with",
"the",
"coordinates",
"of",
"an",
"area",
"a",
"date",
"interval",
"and",
"any",
"other",
"search",
"keywords",
"accepted",
"by",
"the",
"API",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L77-L149 | train | 217,672 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI.format_query | def format_query(area=None, date=None, raw=None, area_relation='Intersects',
**keywords):
"""Create a OpenSearch API query string.
"""
if area_relation.lower() not in {"intersects", "contains", "iswithin"}:
raise ValueError("Incorrect AOI relation provided ({})".format(area_relation))
# Check for duplicate keywords
kw_lower = set(x.lower() for x in keywords)
if (len(kw_lower) != len(keywords) or
(date is not None and 'beginposition' in kw_lower) or
(area is not None and 'footprint' in kw_lower)):
raise ValueError("Query contains duplicate keywords. Note that query keywords are case-insensitive.")
query_parts = []
if date is not None:
keywords['beginPosition'] = date
for attr, value in sorted(keywords.items()):
# Escape spaces, where appropriate
if isinstance(value, string_types):
value = value.strip()
if not any(value.startswith(s[0]) and value.endswith(s[1]) for s in ['[]', '{}', '//', '()']):
value = re.sub(r'\s', r'\ ', value, re.M)
# Handle date keywords
# Keywords from https://github.com/SentinelDataHub/DataHubSystem/search?q=text/date+iso8601
date_attrs = ['beginposition', 'endposition', 'date', 'creationdate', 'ingestiondate']
if attr.lower() in date_attrs:
# Automatically format date-type attributes
if isinstance(value, string_types) and ' TO ' in value:
# This is a string already formatted as a date interval,
# e.g. '[NOW-1DAY TO NOW]'
pass
elif not isinstance(value, string_types) and len(value) == 2:
value = (format_query_date(value[0]), format_query_date(value[1]))
else:
raise ValueError("Date-type query parameter '{}' expects a two-element tuple "
"of str or datetime objects. Received {}".format(attr, value))
# Handle ranged values
if isinstance(value, (list, tuple)):
# Handle value ranges
if len(value) == 2:
# Allow None to be used as a unlimited bound
value = ['*' if x is None else x for x in value]
if all(x == '*' for x in value):
continue
value = '[{} TO {}]'.format(*value)
else:
raise ValueError("Invalid number of elements in list. Expected 2, received "
"{}".format(len(value)))
query_parts.append('{}:{}'.format(attr, value))
if raw:
query_parts.append(raw)
if area is not None:
query_parts.append('footprint:"{}({})"'.format(area_relation, area))
return ' '.join(query_parts) | python | def format_query(area=None, date=None, raw=None, area_relation='Intersects',
**keywords):
"""Create a OpenSearch API query string.
"""
if area_relation.lower() not in {"intersects", "contains", "iswithin"}:
raise ValueError("Incorrect AOI relation provided ({})".format(area_relation))
# Check for duplicate keywords
kw_lower = set(x.lower() for x in keywords)
if (len(kw_lower) != len(keywords) or
(date is not None and 'beginposition' in kw_lower) or
(area is not None and 'footprint' in kw_lower)):
raise ValueError("Query contains duplicate keywords. Note that query keywords are case-insensitive.")
query_parts = []
if date is not None:
keywords['beginPosition'] = date
for attr, value in sorted(keywords.items()):
# Escape spaces, where appropriate
if isinstance(value, string_types):
value = value.strip()
if not any(value.startswith(s[0]) and value.endswith(s[1]) for s in ['[]', '{}', '//', '()']):
value = re.sub(r'\s', r'\ ', value, re.M)
# Handle date keywords
# Keywords from https://github.com/SentinelDataHub/DataHubSystem/search?q=text/date+iso8601
date_attrs = ['beginposition', 'endposition', 'date', 'creationdate', 'ingestiondate']
if attr.lower() in date_attrs:
# Automatically format date-type attributes
if isinstance(value, string_types) and ' TO ' in value:
# This is a string already formatted as a date interval,
# e.g. '[NOW-1DAY TO NOW]'
pass
elif not isinstance(value, string_types) and len(value) == 2:
value = (format_query_date(value[0]), format_query_date(value[1]))
else:
raise ValueError("Date-type query parameter '{}' expects a two-element tuple "
"of str or datetime objects. Received {}".format(attr, value))
# Handle ranged values
if isinstance(value, (list, tuple)):
# Handle value ranges
if len(value) == 2:
# Allow None to be used as a unlimited bound
value = ['*' if x is None else x for x in value]
if all(x == '*' for x in value):
continue
value = '[{} TO {}]'.format(*value)
else:
raise ValueError("Invalid number of elements in list. Expected 2, received "
"{}".format(len(value)))
query_parts.append('{}:{}'.format(attr, value))
if raw:
query_parts.append(raw)
if area is not None:
query_parts.append('footprint:"{}({})"'.format(area_relation, area))
return ' '.join(query_parts) | [
"def",
"format_query",
"(",
"area",
"=",
"None",
",",
"date",
"=",
"None",
",",
"raw",
"=",
"None",
",",
"area_relation",
"=",
"'Intersects'",
",",
"*",
"*",
"keywords",
")",
":",
"if",
"area_relation",
".",
"lower",
"(",
")",
"not",
"in",
"{",
"\"in... | Create a OpenSearch API query string. | [
"Create",
"a",
"OpenSearch",
"API",
"query",
"string",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L152-L214 | train | 217,673 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI.count | def count(self, area=None, date=None, raw=None, area_relation='Intersects', **keywords):
"""Get the number of products matching a query.
Accepted parameters are identical to :meth:`SentinelAPI.query()`.
This is a significantly more efficient alternative to doing `len(api.query())`,
which can take minutes to run for queries matching thousands of products.
Returns
-------
int
The number of products matching a query.
"""
for kw in ['order_by', 'limit', 'offset']:
# Allow these function arguments to be included for compatibility with query(),
# but ignore them.
if kw in keywords:
del keywords[kw]
query = self.format_query(area, date, raw, area_relation, **keywords)
_, total_count = self._load_query(query, limit=0)
return total_count | python | def count(self, area=None, date=None, raw=None, area_relation='Intersects', **keywords):
"""Get the number of products matching a query.
Accepted parameters are identical to :meth:`SentinelAPI.query()`.
This is a significantly more efficient alternative to doing `len(api.query())`,
which can take minutes to run for queries matching thousands of products.
Returns
-------
int
The number of products matching a query.
"""
for kw in ['order_by', 'limit', 'offset']:
# Allow these function arguments to be included for compatibility with query(),
# but ignore them.
if kw in keywords:
del keywords[kw]
query = self.format_query(area, date, raw, area_relation, **keywords)
_, total_count = self._load_query(query, limit=0)
return total_count | [
"def",
"count",
"(",
"self",
",",
"area",
"=",
"None",
",",
"date",
"=",
"None",
",",
"raw",
"=",
"None",
",",
"area_relation",
"=",
"'Intersects'",
",",
"*",
"*",
"keywords",
")",
":",
"for",
"kw",
"in",
"[",
"'order_by'",
",",
"'limit'",
",",
"'o... | Get the number of products matching a query.
Accepted parameters are identical to :meth:`SentinelAPI.query()`.
This is a significantly more efficient alternative to doing `len(api.query())`,
which can take minutes to run for queries matching thousands of products.
Returns
-------
int
The number of products matching a query. | [
"Get",
"the",
"number",
"of",
"products",
"matching",
"a",
"query",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L249-L269 | train | 217,674 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI.to_geojson | def to_geojson(products):
"""Return the products from a query response as a GeoJSON with the values in their
appropriate Python types.
"""
feature_list = []
for i, (product_id, props) in enumerate(products.items()):
props = props.copy()
props['id'] = product_id
poly = geomet.wkt.loads(props['footprint'])
del props['footprint']
del props['gmlfootprint']
# Fix "'datetime' is not JSON serializable"
for k, v in props.items():
if isinstance(v, (date, datetime)):
props[k] = v.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
feature_list.append(
geojson.Feature(geometry=poly, id=i, properties=props)
)
return geojson.FeatureCollection(feature_list) | python | def to_geojson(products):
"""Return the products from a query response as a GeoJSON with the values in their
appropriate Python types.
"""
feature_list = []
for i, (product_id, props) in enumerate(products.items()):
props = props.copy()
props['id'] = product_id
poly = geomet.wkt.loads(props['footprint'])
del props['footprint']
del props['gmlfootprint']
# Fix "'datetime' is not JSON serializable"
for k, v in props.items():
if isinstance(v, (date, datetime)):
props[k] = v.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
feature_list.append(
geojson.Feature(geometry=poly, id=i, properties=props)
)
return geojson.FeatureCollection(feature_list) | [
"def",
"to_geojson",
"(",
"products",
")",
":",
"feature_list",
"=",
"[",
"]",
"for",
"i",
",",
"(",
"product_id",
",",
"props",
")",
"in",
"enumerate",
"(",
"products",
".",
"items",
"(",
")",
")",
":",
"props",
"=",
"props",
".",
"copy",
"(",
")"... | Return the products from a query response as a GeoJSON with the values in their
appropriate Python types. | [
"Return",
"the",
"products",
"from",
"a",
"query",
"response",
"as",
"a",
"GeoJSON",
"with",
"the",
"values",
"in",
"their",
"appropriate",
"Python",
"types",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L340-L358 | train | 217,675 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI.to_dataframe | def to_dataframe(products):
"""Return the products from a query response as a Pandas DataFrame
with the values in their appropriate Python types.
"""
try:
import pandas as pd
except ImportError:
raise ImportError("to_dataframe requires the optional dependency Pandas.")
return pd.DataFrame.from_dict(products, orient='index') | python | def to_dataframe(products):
"""Return the products from a query response as a Pandas DataFrame
with the values in their appropriate Python types.
"""
try:
import pandas as pd
except ImportError:
raise ImportError("to_dataframe requires the optional dependency Pandas.")
return pd.DataFrame.from_dict(products, orient='index') | [
"def",
"to_dataframe",
"(",
"products",
")",
":",
"try",
":",
"import",
"pandas",
"as",
"pd",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"to_dataframe requires the optional dependency Pandas.\"",
")",
"return",
"pd",
".",
"DataFrame",
".",
"from_di... | Return the products from a query response as a Pandas DataFrame
with the values in their appropriate Python types. | [
"Return",
"the",
"products",
"from",
"a",
"query",
"response",
"as",
"a",
"Pandas",
"DataFrame",
"with",
"the",
"values",
"in",
"their",
"appropriate",
"Python",
"types",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L361-L370 | train | 217,676 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI.to_geodataframe | def to_geodataframe(products):
"""Return the products from a query response as a GeoPandas GeoDataFrame
with the values in their appropriate Python types.
"""
try:
import geopandas as gpd
import shapely.wkt
except ImportError:
raise ImportError("to_geodataframe requires the optional dependencies GeoPandas and Shapely.")
crs = {'init': 'epsg:4326'} # WGS84
if len(products) == 0:
return gpd.GeoDataFrame(crs=crs)
df = SentinelAPI.to_dataframe(products)
geometry = [shapely.wkt.loads(fp) for fp in df['footprint']]
# remove useless columns
df.drop(['footprint', 'gmlfootprint'], axis=1, inplace=True)
return gpd.GeoDataFrame(df, crs=crs, geometry=geometry) | python | def to_geodataframe(products):
"""Return the products from a query response as a GeoPandas GeoDataFrame
with the values in their appropriate Python types.
"""
try:
import geopandas as gpd
import shapely.wkt
except ImportError:
raise ImportError("to_geodataframe requires the optional dependencies GeoPandas and Shapely.")
crs = {'init': 'epsg:4326'} # WGS84
if len(products) == 0:
return gpd.GeoDataFrame(crs=crs)
df = SentinelAPI.to_dataframe(products)
geometry = [shapely.wkt.loads(fp) for fp in df['footprint']]
# remove useless columns
df.drop(['footprint', 'gmlfootprint'], axis=1, inplace=True)
return gpd.GeoDataFrame(df, crs=crs, geometry=geometry) | [
"def",
"to_geodataframe",
"(",
"products",
")",
":",
"try",
":",
"import",
"geopandas",
"as",
"gpd",
"import",
"shapely",
".",
"wkt",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"to_geodataframe requires the optional dependencies GeoPandas and Shapely.\""... | Return the products from a query response as a GeoPandas GeoDataFrame
with the values in their appropriate Python types. | [
"Return",
"the",
"products",
"from",
"a",
"query",
"response",
"as",
"a",
"GeoPandas",
"GeoDataFrame",
"with",
"the",
"values",
"in",
"their",
"appropriate",
"Python",
"types",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L373-L391 | train | 217,677 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI.get_product_odata | def get_product_odata(self, id, full=False):
"""Access OData API to get info about a product.
Returns a dict containing the id, title, size, md5sum, date, footprint and download url
of the product. The date field corresponds to the Start ContentDate value.
If `full` is set to True, then the full, detailed metadata of the product is returned
in addition to the above.
Parameters
----------
id : string
The UUID of the product to query
full : bool
Whether to get the full metadata for the Product. False by default.
Returns
-------
dict[str, Any]
A dictionary with an item for each metadata attribute
Notes
-----
For a full list of mappings between the OpenSearch (Solr) and OData attribute names
see the following definition files:
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-1/src/main/resources/META-INF/sentinel-1.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-2/src/main/resources/META-INF/sentinel-2.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-3/src/main/resources/META-INF/sentinel-3.owl
"""
url = urljoin(self.api_url, u"odata/v1/Products('{}')?$format=json".format(id))
if full:
url += '&$expand=Attributes'
response = self.session.get(url, auth=self.session.auth,
timeout=self.timeout)
_check_scihub_response(response)
values = _parse_odata_response(response.json()['d'])
return values | python | def get_product_odata(self, id, full=False):
"""Access OData API to get info about a product.
Returns a dict containing the id, title, size, md5sum, date, footprint and download url
of the product. The date field corresponds to the Start ContentDate value.
If `full` is set to True, then the full, detailed metadata of the product is returned
in addition to the above.
Parameters
----------
id : string
The UUID of the product to query
full : bool
Whether to get the full metadata for the Product. False by default.
Returns
-------
dict[str, Any]
A dictionary with an item for each metadata attribute
Notes
-----
For a full list of mappings between the OpenSearch (Solr) and OData attribute names
see the following definition files:
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-1/src/main/resources/META-INF/sentinel-1.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-2/src/main/resources/META-INF/sentinel-2.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-3/src/main/resources/META-INF/sentinel-3.owl
"""
url = urljoin(self.api_url, u"odata/v1/Products('{}')?$format=json".format(id))
if full:
url += '&$expand=Attributes'
response = self.session.get(url, auth=self.session.auth,
timeout=self.timeout)
_check_scihub_response(response)
values = _parse_odata_response(response.json()['d'])
return values | [
"def",
"get_product_odata",
"(",
"self",
",",
"id",
",",
"full",
"=",
"False",
")",
":",
"url",
"=",
"urljoin",
"(",
"self",
".",
"api_url",
",",
"u\"odata/v1/Products('{}')?$format=json\"",
".",
"format",
"(",
"id",
")",
")",
"if",
"full",
":",
"url",
"... | Access OData API to get info about a product.
Returns a dict containing the id, title, size, md5sum, date, footprint and download url
of the product. The date field corresponds to the Start ContentDate value.
If `full` is set to True, then the full, detailed metadata of the product is returned
in addition to the above.
Parameters
----------
id : string
The UUID of the product to query
full : bool
Whether to get the full metadata for the Product. False by default.
Returns
-------
dict[str, Any]
A dictionary with an item for each metadata attribute
Notes
-----
For a full list of mappings between the OpenSearch (Solr) and OData attribute names
see the following definition files:
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-1/src/main/resources/META-INF/sentinel-1.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-2/src/main/resources/META-INF/sentinel-2.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-3/src/main/resources/META-INF/sentinel-3.owl | [
"Access",
"OData",
"API",
"to",
"get",
"info",
"about",
"a",
"product",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L393-L429 | train | 217,678 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI._trigger_offline_retrieval | def _trigger_offline_retrieval(self, url):
""" Triggers retrieval of an offline product
Trying to download an offline product triggers its retrieval from the long term archive.
The returned HTTP status code conveys whether this was successful.
Parameters
----------
url : string
URL for downloading the product
Notes
-----
https://scihub.copernicus.eu/userguide/LongTermArchive
"""
with self.session.get(url, auth=self.session.auth, timeout=self.timeout) as r:
# check https://scihub.copernicus.eu/userguide/LongTermArchive#HTTP_Status_codes
if r.status_code == 202:
self.logger.info("Accepted for retrieval")
elif r.status_code == 503:
self.logger.error("Request not accepted")
raise SentinelAPILTAError('Request for retrieval from LTA not accepted', r)
elif r.status_code == 403:
self.logger.error("Requests exceed user quota")
raise SentinelAPILTAError('Requests for retrieval from LTA exceed user quota', r)
elif r.status_code == 500:
# should not happen
self.logger.error("Trying to download an offline product")
raise SentinelAPILTAError('Trying to download an offline product', r)
return r.status_code | python | def _trigger_offline_retrieval(self, url):
""" Triggers retrieval of an offline product
Trying to download an offline product triggers its retrieval from the long term archive.
The returned HTTP status code conveys whether this was successful.
Parameters
----------
url : string
URL for downloading the product
Notes
-----
https://scihub.copernicus.eu/userguide/LongTermArchive
"""
with self.session.get(url, auth=self.session.auth, timeout=self.timeout) as r:
# check https://scihub.copernicus.eu/userguide/LongTermArchive#HTTP_Status_codes
if r.status_code == 202:
self.logger.info("Accepted for retrieval")
elif r.status_code == 503:
self.logger.error("Request not accepted")
raise SentinelAPILTAError('Request for retrieval from LTA not accepted', r)
elif r.status_code == 403:
self.logger.error("Requests exceed user quota")
raise SentinelAPILTAError('Requests for retrieval from LTA exceed user quota', r)
elif r.status_code == 500:
# should not happen
self.logger.error("Trying to download an offline product")
raise SentinelAPILTAError('Trying to download an offline product', r)
return r.status_code | [
"def",
"_trigger_offline_retrieval",
"(",
"self",
",",
"url",
")",
":",
"with",
"self",
".",
"session",
".",
"get",
"(",
"url",
",",
"auth",
"=",
"self",
".",
"session",
".",
"auth",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"as",
"r",
":",
... | Triggers retrieval of an offline product
Trying to download an offline product triggers its retrieval from the long term archive.
The returned HTTP status code conveys whether this was successful.
Parameters
----------
url : string
URL for downloading the product
Notes
-----
https://scihub.copernicus.eu/userguide/LongTermArchive | [
"Triggers",
"retrieval",
"of",
"an",
"offline",
"product"
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L431-L461 | train | 217,679 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI.download | def download(self, id, directory_path='.', checksum=True):
"""Download a product.
Uses the filename on the server for the downloaded file, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
Incomplete downloads are continued and complete files are skipped.
Parameters
----------
id : string
UUID of the product, e.g. 'a8dd0cfd-613e-45ce-868c-d79177b916ed'
directory_path : string, optional
Where the file will be downloaded
checksum : bool, optional
If True, verify the downloaded file's integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Returns
-------
product_info : dict
Dictionary containing the product's info from get_product_info() as well as
the path on disk.
Raises
------
InvalidChecksumError
If the MD5 checksum does not match the checksum on the server.
"""
product_info = self.get_product_odata(id)
path = join(directory_path, product_info['title'] + '.zip')
product_info['path'] = path
product_info['downloaded_bytes'] = 0
self.logger.info('Downloading %s to %s', id, path)
if exists(path):
# We assume that the product has been downloaded and is complete
return product_info
# An incomplete download triggers the retrieval from the LTA if the product is not online
if not product_info['Online']:
self.logger.warning(
'Product %s is not online. Triggering retrieval from long term archive.',
product_info['id'])
self._trigger_offline_retrieval(product_info['url'])
return product_info
# Use a temporary file for downloading
temp_path = path + '.incomplete'
skip_download = False
if exists(temp_path):
if getsize(temp_path) > product_info['size']:
self.logger.warning(
"Existing incomplete file %s is larger than the expected final size"
" (%s vs %s bytes). Deleting it.",
str(temp_path), getsize(temp_path), product_info['size'])
remove(temp_path)
elif getsize(temp_path) == product_info['size']:
if self._md5_compare(temp_path, product_info['md5']):
skip_download = True
else:
# Log a warning since this should never happen
self.logger.warning(
"Existing incomplete file %s appears to be fully downloaded but "
"its checksum is incorrect. Deleting it.",
str(temp_path))
remove(temp_path)
else:
# continue downloading
self.logger.info(
"Download will resume from existing incomplete file %s.", temp_path)
pass
if not skip_download:
# Store the number of downloaded bytes for unit tests
product_info['downloaded_bytes'] = self._download(
product_info['url'], temp_path, self.session, product_info['size'])
# Check integrity with MD5 checksum
if checksum is True:
if not self._md5_compare(temp_path, product_info['md5']):
remove(temp_path)
raise InvalidChecksumError('File corrupt: checksums do not match')
# Download successful, rename the temporary file to its proper name
shutil.move(temp_path, path)
return product_info | python | def download(self, id, directory_path='.', checksum=True):
"""Download a product.
Uses the filename on the server for the downloaded file, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
Incomplete downloads are continued and complete files are skipped.
Parameters
----------
id : string
UUID of the product, e.g. 'a8dd0cfd-613e-45ce-868c-d79177b916ed'
directory_path : string, optional
Where the file will be downloaded
checksum : bool, optional
If True, verify the downloaded file's integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Returns
-------
product_info : dict
Dictionary containing the product's info from get_product_info() as well as
the path on disk.
Raises
------
InvalidChecksumError
If the MD5 checksum does not match the checksum on the server.
"""
product_info = self.get_product_odata(id)
path = join(directory_path, product_info['title'] + '.zip')
product_info['path'] = path
product_info['downloaded_bytes'] = 0
self.logger.info('Downloading %s to %s', id, path)
if exists(path):
# We assume that the product has been downloaded and is complete
return product_info
# An incomplete download triggers the retrieval from the LTA if the product is not online
if not product_info['Online']:
self.logger.warning(
'Product %s is not online. Triggering retrieval from long term archive.',
product_info['id'])
self._trigger_offline_retrieval(product_info['url'])
return product_info
# Use a temporary file for downloading
temp_path = path + '.incomplete'
skip_download = False
if exists(temp_path):
if getsize(temp_path) > product_info['size']:
self.logger.warning(
"Existing incomplete file %s is larger than the expected final size"
" (%s vs %s bytes). Deleting it.",
str(temp_path), getsize(temp_path), product_info['size'])
remove(temp_path)
elif getsize(temp_path) == product_info['size']:
if self._md5_compare(temp_path, product_info['md5']):
skip_download = True
else:
# Log a warning since this should never happen
self.logger.warning(
"Existing incomplete file %s appears to be fully downloaded but "
"its checksum is incorrect. Deleting it.",
str(temp_path))
remove(temp_path)
else:
# continue downloading
self.logger.info(
"Download will resume from existing incomplete file %s.", temp_path)
pass
if not skip_download:
# Store the number of downloaded bytes for unit tests
product_info['downloaded_bytes'] = self._download(
product_info['url'], temp_path, self.session, product_info['size'])
# Check integrity with MD5 checksum
if checksum is True:
if not self._md5_compare(temp_path, product_info['md5']):
remove(temp_path)
raise InvalidChecksumError('File corrupt: checksums do not match')
# Download successful, rename the temporary file to its proper name
shutil.move(temp_path, path)
return product_info | [
"def",
"download",
"(",
"self",
",",
"id",
",",
"directory_path",
"=",
"'.'",
",",
"checksum",
"=",
"True",
")",
":",
"product_info",
"=",
"self",
".",
"get_product_odata",
"(",
"id",
")",
"path",
"=",
"join",
"(",
"directory_path",
",",
"product_info",
... | Download a product.
Uses the filename on the server for the downloaded file, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
Incomplete downloads are continued and complete files are skipped.
Parameters
----------
id : string
UUID of the product, e.g. 'a8dd0cfd-613e-45ce-868c-d79177b916ed'
directory_path : string, optional
Where the file will be downloaded
checksum : bool, optional
If True, verify the downloaded file's integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Returns
-------
product_info : dict
Dictionary containing the product's info from get_product_info() as well as
the path on disk.
Raises
------
InvalidChecksumError
If the MD5 checksum does not match the checksum on the server. | [
"Download",
"a",
"product",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L463-L552 | train | 217,680 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI.download_all | def download_all(self, products, directory_path='.', max_attempts=10, checksum=True):
"""Download a list of products.
Takes a list of product IDs as input. This means that the return value of query() can be
passed directly to this method.
File names on the server are used for the downloaded files, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
In case of interruptions or other exceptions, downloading will restart from where it left
off. Downloading is attempted at most max_attempts times to avoid getting stuck with
unrecoverable errors.
Parameters
----------
products : list
List of product IDs
directory_path : string
Directory where the downloaded files will be downloaded
max_attempts : int, optional
Number of allowed retries before giving up downloading a product. Defaults to 10.
checksum : bool, optional
If True, verify the downloaded files' integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Raises
------
Raises the most recent downloading exception if all downloads failed.
Returns
-------
dict[string, dict]
A dictionary containing the return value from download() for each successfully
downloaded product.
dict[string, dict]
A dictionary containing the product information for products whose retrieval
from the long term archive was successfully triggered.
set[string]
The list of products that failed to download.
"""
product_ids = list(products)
self.logger.info("Will download %d products", len(product_ids))
return_values = OrderedDict()
last_exception = None
for i, product_id in enumerate(products):
for attempt_num in range(max_attempts):
try:
product_info = self.download(product_id, directory_path, checksum)
return_values[product_id] = product_info
break
except (KeyboardInterrupt, SystemExit):
raise
except InvalidChecksumError as e:
last_exception = e
self.logger.warning(
"Invalid checksum. The downloaded file for '%s' is corrupted.", product_id)
except SentinelAPILTAError as e:
last_exception = e
self.logger.exception("There was an error retrieving %s from the LTA", product_id)
break
except Exception as e:
last_exception = e
self.logger.exception("There was an error downloading %s", product_id)
self.logger.info("%s/%s products downloaded", i + 1, len(product_ids))
failed = set(products) - set(return_values)
# split up sucessfully processed products into downloaded and only triggered retrieval from the LTA
triggered = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is False])
downloaded = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is True])
if len(failed) == len(product_ids) and last_exception is not None:
raise last_exception
return downloaded, triggered, failed | python | def download_all(self, products, directory_path='.', max_attempts=10, checksum=True):
"""Download a list of products.
Takes a list of product IDs as input. This means that the return value of query() can be
passed directly to this method.
File names on the server are used for the downloaded files, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
In case of interruptions or other exceptions, downloading will restart from where it left
off. Downloading is attempted at most max_attempts times to avoid getting stuck with
unrecoverable errors.
Parameters
----------
products : list
List of product IDs
directory_path : string
Directory where the downloaded files will be downloaded
max_attempts : int, optional
Number of allowed retries before giving up downloading a product. Defaults to 10.
checksum : bool, optional
If True, verify the downloaded files' integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Raises
------
Raises the most recent downloading exception if all downloads failed.
Returns
-------
dict[string, dict]
A dictionary containing the return value from download() for each successfully
downloaded product.
dict[string, dict]
A dictionary containing the product information for products whose retrieval
from the long term archive was successfully triggered.
set[string]
The list of products that failed to download.
"""
product_ids = list(products)
self.logger.info("Will download %d products", len(product_ids))
return_values = OrderedDict()
last_exception = None
for i, product_id in enumerate(products):
for attempt_num in range(max_attempts):
try:
product_info = self.download(product_id, directory_path, checksum)
return_values[product_id] = product_info
break
except (KeyboardInterrupt, SystemExit):
raise
except InvalidChecksumError as e:
last_exception = e
self.logger.warning(
"Invalid checksum. The downloaded file for '%s' is corrupted.", product_id)
except SentinelAPILTAError as e:
last_exception = e
self.logger.exception("There was an error retrieving %s from the LTA", product_id)
break
except Exception as e:
last_exception = e
self.logger.exception("There was an error downloading %s", product_id)
self.logger.info("%s/%s products downloaded", i + 1, len(product_ids))
failed = set(products) - set(return_values)
# split up sucessfully processed products into downloaded and only triggered retrieval from the LTA
triggered = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is False])
downloaded = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is True])
if len(failed) == len(product_ids) and last_exception is not None:
raise last_exception
return downloaded, triggered, failed | [
"def",
"download_all",
"(",
"self",
",",
"products",
",",
"directory_path",
"=",
"'.'",
",",
"max_attempts",
"=",
"10",
",",
"checksum",
"=",
"True",
")",
":",
"product_ids",
"=",
"list",
"(",
"products",
")",
"self",
".",
"logger",
".",
"info",
"(",
"... | Download a list of products.
Takes a list of product IDs as input. This means that the return value of query() can be
passed directly to this method.
File names on the server are used for the downloaded files, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
In case of interruptions or other exceptions, downloading will restart from where it left
off. Downloading is attempted at most max_attempts times to avoid getting stuck with
unrecoverable errors.
Parameters
----------
products : list
List of product IDs
directory_path : string
Directory where the downloaded files will be downloaded
max_attempts : int, optional
Number of allowed retries before giving up downloading a product. Defaults to 10.
checksum : bool, optional
If True, verify the downloaded files' integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Raises
------
Raises the most recent downloading exception if all downloads failed.
Returns
-------
dict[string, dict]
A dictionary containing the return value from download() for each successfully
downloaded product.
dict[string, dict]
A dictionary containing the product information for products whose retrieval
from the long term archive was successfully triggered.
set[string]
The list of products that failed to download. | [
"Download",
"a",
"list",
"of",
"products",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L554-L627 | train | 217,681 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI.get_products_size | def get_products_size(products):
"""Return the total file size in GB of all products in the OpenSearch response."""
size_total = 0
for title, props in products.items():
size_product = props["size"]
size_value = float(size_product.split(" ")[0])
size_unit = str(size_product.split(" ")[1])
if size_unit == "MB":
size_value /= 1024.
if size_unit == "KB":
size_value /= 1024. * 1024.
size_total += size_value
return round(size_total, 2) | python | def get_products_size(products):
"""Return the total file size in GB of all products in the OpenSearch response."""
size_total = 0
for title, props in products.items():
size_product = props["size"]
size_value = float(size_product.split(" ")[0])
size_unit = str(size_product.split(" ")[1])
if size_unit == "MB":
size_value /= 1024.
if size_unit == "KB":
size_value /= 1024. * 1024.
size_total += size_value
return round(size_total, 2) | [
"def",
"get_products_size",
"(",
"products",
")",
":",
"size_total",
"=",
"0",
"for",
"title",
",",
"props",
"in",
"products",
".",
"items",
"(",
")",
":",
"size_product",
"=",
"props",
"[",
"\"size\"",
"]",
"size_value",
"=",
"float",
"(",
"size_product",... | Return the total file size in GB of all products in the OpenSearch response. | [
"Return",
"the",
"total",
"file",
"size",
"in",
"GB",
"of",
"all",
"products",
"in",
"the",
"OpenSearch",
"response",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L630-L642 | train | 217,682 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI.check_files | def check_files(self, paths=None, ids=None, directory=None, delete=False):
"""Verify the integrity of product files on disk.
Integrity is checked by comparing the size and checksum of the file with the respective
values on the server.
The input can be a list of products to check or a list of IDs and a directory.
In cases where multiple products with different IDs exist on the server for given product
name, the file is considered to be correct if any of them matches the file size and
checksum. A warning is logged in such situations.
The corrupt products' OData info is included in the return value to make it easier to
re-download the products, if necessary.
Parameters
----------
paths : list[string]
List of product file paths.
ids : list[string]
List of product IDs.
directory : string
Directory where the files are located, if checking based on product IDs.
delete : bool
Whether to delete corrupt products. Defaults to False.
Returns
-------
dict[str, list[dict]]
A dictionary listing the invalid or missing files. The dictionary maps the corrupt
file paths to a list of OData dictionaries of matching products on the server (as
returned by :meth:`SentinelAPI.get_product_odata()`).
"""
if not ids and not paths:
raise ValueError("Must provide either file paths or product IDs and a directory")
if ids and not directory:
raise ValueError("Directory value missing")
paths = paths or []
ids = ids or []
def name_from_path(path):
return splitext(basename(path))[0]
# Get product IDs corresponding to the files on disk
names = []
if paths:
names = list(map(name_from_path, paths))
result = self._query_names(names)
for product_dicts in result.values():
ids += list(product_dicts)
names_from_paths = set(names)
ids = set(ids)
# Collect the OData information for each product
# Product name -> list of matching odata dicts
product_infos = defaultdict(list)
for id in ids:
odata = self.get_product_odata(id)
name = odata['title']
product_infos[name].append(odata)
# Collect
if name not in names_from_paths:
paths.append(join(directory, name + '.zip'))
# Now go over the list of products and check them
corrupt = {}
for path in paths:
name = name_from_path(path)
if len(product_infos[name]) > 1:
self.logger.warning("{} matches multiple products on server".format(path))
if not exists(path):
# We will consider missing files as corrupt also
self.logger.info("{} does not exist on disk".format(path))
corrupt[path] = product_infos[name]
continue
is_fine = False
for product_info in product_infos[name]:
if (getsize(path) == product_info['size'] and
self._md5_compare(path, product_info['md5'])):
is_fine = True
break
if not is_fine:
self.logger.info("{} is corrupt".format(path))
corrupt[path] = product_infos[name]
if delete:
remove(path)
return corrupt | python | def check_files(self, paths=None, ids=None, directory=None, delete=False):
"""Verify the integrity of product files on disk.
Integrity is checked by comparing the size and checksum of the file with the respective
values on the server.
The input can be a list of products to check or a list of IDs and a directory.
In cases where multiple products with different IDs exist on the server for given product
name, the file is considered to be correct if any of them matches the file size and
checksum. A warning is logged in such situations.
The corrupt products' OData info is included in the return value to make it easier to
re-download the products, if necessary.
Parameters
----------
paths : list[string]
List of product file paths.
ids : list[string]
List of product IDs.
directory : string
Directory where the files are located, if checking based on product IDs.
delete : bool
Whether to delete corrupt products. Defaults to False.
Returns
-------
dict[str, list[dict]]
A dictionary listing the invalid or missing files. The dictionary maps the corrupt
file paths to a list of OData dictionaries of matching products on the server (as
returned by :meth:`SentinelAPI.get_product_odata()`).
"""
if not ids and not paths:
raise ValueError("Must provide either file paths or product IDs and a directory")
if ids and not directory:
raise ValueError("Directory value missing")
paths = paths or []
ids = ids or []
def name_from_path(path):
return splitext(basename(path))[0]
# Get product IDs corresponding to the files on disk
names = []
if paths:
names = list(map(name_from_path, paths))
result = self._query_names(names)
for product_dicts in result.values():
ids += list(product_dicts)
names_from_paths = set(names)
ids = set(ids)
# Collect the OData information for each product
# Product name -> list of matching odata dicts
product_infos = defaultdict(list)
for id in ids:
odata = self.get_product_odata(id)
name = odata['title']
product_infos[name].append(odata)
# Collect
if name not in names_from_paths:
paths.append(join(directory, name + '.zip'))
# Now go over the list of products and check them
corrupt = {}
for path in paths:
name = name_from_path(path)
if len(product_infos[name]) > 1:
self.logger.warning("{} matches multiple products on server".format(path))
if not exists(path):
# We will consider missing files as corrupt also
self.logger.info("{} does not exist on disk".format(path))
corrupt[path] = product_infos[name]
continue
is_fine = False
for product_info in product_infos[name]:
if (getsize(path) == product_info['size'] and
self._md5_compare(path, product_info['md5'])):
is_fine = True
break
if not is_fine:
self.logger.info("{} is corrupt".format(path))
corrupt[path] = product_infos[name]
if delete:
remove(path)
return corrupt | [
"def",
"check_files",
"(",
"self",
",",
"paths",
"=",
"None",
",",
"ids",
"=",
"None",
",",
"directory",
"=",
"None",
",",
"delete",
"=",
"False",
")",
":",
"if",
"not",
"ids",
"and",
"not",
"paths",
":",
"raise",
"ValueError",
"(",
"\"Must provide eit... | Verify the integrity of product files on disk.
Integrity is checked by comparing the size and checksum of the file with the respective
values on the server.
The input can be a list of products to check or a list of IDs and a directory.
In cases where multiple products with different IDs exist on the server for given product
name, the file is considered to be correct if any of them matches the file size and
checksum. A warning is logged in such situations.
The corrupt products' OData info is included in the return value to make it easier to
re-download the products, if necessary.
Parameters
----------
paths : list[string]
List of product file paths.
ids : list[string]
List of product IDs.
directory : string
Directory where the files are located, if checking based on product IDs.
delete : bool
Whether to delete corrupt products. Defaults to False.
Returns
-------
dict[str, list[dict]]
A dictionary listing the invalid or missing files. The dictionary maps the corrupt
file paths to a list of OData dictionaries of matching products on the server (as
returned by :meth:`SentinelAPI.get_product_odata()`). | [
"Verify",
"the",
"integrity",
"of",
"product",
"files",
"on",
"disk",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L702-L793 | train | 217,683 |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI._md5_compare | def _md5_compare(self, file_path, checksum, block_size=2 ** 13):
"""Compare a given MD5 checksum with one calculated from a file."""
with closing(self._tqdm(desc="MD5 checksumming", total=getsize(file_path), unit="B",
unit_scale=True)) as progress:
md5 = hashlib.md5()
with open(file_path, "rb") as f:
while True:
block_data = f.read(block_size)
if not block_data:
break
md5.update(block_data)
progress.update(len(block_data))
return md5.hexdigest().lower() == checksum.lower() | python | def _md5_compare(self, file_path, checksum, block_size=2 ** 13):
"""Compare a given MD5 checksum with one calculated from a file."""
with closing(self._tqdm(desc="MD5 checksumming", total=getsize(file_path), unit="B",
unit_scale=True)) as progress:
md5 = hashlib.md5()
with open(file_path, "rb") as f:
while True:
block_data = f.read(block_size)
if not block_data:
break
md5.update(block_data)
progress.update(len(block_data))
return md5.hexdigest().lower() == checksum.lower() | [
"def",
"_md5_compare",
"(",
"self",
",",
"file_path",
",",
"checksum",
",",
"block_size",
"=",
"2",
"**",
"13",
")",
":",
"with",
"closing",
"(",
"self",
".",
"_tqdm",
"(",
"desc",
"=",
"\"MD5 checksumming\"",
",",
"total",
"=",
"getsize",
"(",
"file_pat... | Compare a given MD5 checksum with one calculated from a file. | [
"Compare",
"a",
"given",
"MD5",
"checksum",
"with",
"one",
"calculated",
"from",
"a",
"file",
"."
] | eacfd79ff4e7e939147db9dfdd393c67d64eecaa | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L795-L807 | train | 217,684 |
celery/django-celery | djcelery/managers.py | transaction_retry | def transaction_retry(max_retries=1):
"""Decorator for methods doing database operations.
If the database operation fails, it will retry the operation
at most ``max_retries`` times.
"""
def _outer(fun):
@wraps(fun)
def _inner(*args, **kwargs):
_max_retries = kwargs.pop('exception_retry_count', max_retries)
for retries in count(0):
try:
return fun(*args, **kwargs)
except Exception: # pragma: no cover
# Depending on the database backend used we can experience
# various exceptions. E.g. psycopg2 raises an exception
# if some operation breaks the transaction, so saving
# the task result won't be possible until we rollback
# the transaction.
if retries >= _max_retries:
raise
try:
rollback_unless_managed()
except Exception:
pass
return _inner
return _outer | python | def transaction_retry(max_retries=1):
"""Decorator for methods doing database operations.
If the database operation fails, it will retry the operation
at most ``max_retries`` times.
"""
def _outer(fun):
@wraps(fun)
def _inner(*args, **kwargs):
_max_retries = kwargs.pop('exception_retry_count', max_retries)
for retries in count(0):
try:
return fun(*args, **kwargs)
except Exception: # pragma: no cover
# Depending on the database backend used we can experience
# various exceptions. E.g. psycopg2 raises an exception
# if some operation breaks the transaction, so saving
# the task result won't be possible until we rollback
# the transaction.
if retries >= _max_retries:
raise
try:
rollback_unless_managed()
except Exception:
pass
return _inner
return _outer | [
"def",
"transaction_retry",
"(",
"max_retries",
"=",
"1",
")",
":",
"def",
"_outer",
"(",
"fun",
")",
":",
"@",
"wraps",
"(",
"fun",
")",
"def",
"_inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_max_retries",
"=",
"kwargs",
".",
"pop... | Decorator for methods doing database operations.
If the database operation fails, it will retry the operation
at most ``max_retries`` times. | [
"Decorator",
"for",
"methods",
"doing",
"database",
"operations",
"."
] | 5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/managers.py#L31-L60 | train | 217,685 |
celery/django-celery | djcelery/managers.py | ResultManager.delete_expired | def delete_expired(self, expires):
"""Delete all expired taskset results."""
meta = self.model._meta
with commit_on_success():
self.get_all_expired(expires).update(hidden=True)
cursor = self.connection_for_write().cursor()
cursor.execute(
'DELETE FROM {0.db_table} WHERE hidden=%s'.format(meta),
(True, ),
) | python | def delete_expired(self, expires):
"""Delete all expired taskset results."""
meta = self.model._meta
with commit_on_success():
self.get_all_expired(expires).update(hidden=True)
cursor = self.connection_for_write().cursor()
cursor.execute(
'DELETE FROM {0.db_table} WHERE hidden=%s'.format(meta),
(True, ),
) | [
"def",
"delete_expired",
"(",
"self",
",",
"expires",
")",
":",
"meta",
"=",
"self",
".",
"model",
".",
"_meta",
"with",
"commit_on_success",
"(",
")",
":",
"self",
".",
"get_all_expired",
"(",
"expires",
")",
".",
"update",
"(",
"hidden",
"=",
"True",
... | Delete all expired taskset results. | [
"Delete",
"all",
"expired",
"taskset",
"results",
"."
] | 5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/managers.py#L115-L124 | train | 217,686 |
celery/django-celery | djcelery/managers.py | TaskManager.get_task | def get_task(self, task_id):
"""Get task meta for task by ``task_id``.
:keyword exception_retry_count: How many times to retry by
transaction rollback on exception. This could theoretically
happen in a race condition if another worker is trying to
create the same task. The default is to retry once.
"""
try:
return self.get(task_id=task_id)
except self.model.DoesNotExist:
if self._last_id == task_id:
self.warn_if_repeatable_read()
self._last_id = task_id
return self.model(task_id=task_id) | python | def get_task(self, task_id):
"""Get task meta for task by ``task_id``.
:keyword exception_retry_count: How many times to retry by
transaction rollback on exception. This could theoretically
happen in a race condition if another worker is trying to
create the same task. The default is to retry once.
"""
try:
return self.get(task_id=task_id)
except self.model.DoesNotExist:
if self._last_id == task_id:
self.warn_if_repeatable_read()
self._last_id = task_id
return self.model(task_id=task_id) | [
"def",
"get_task",
"(",
"self",
",",
"task_id",
")",
":",
"try",
":",
"return",
"self",
".",
"get",
"(",
"task_id",
"=",
"task_id",
")",
"except",
"self",
".",
"model",
".",
"DoesNotExist",
":",
"if",
"self",
".",
"_last_id",
"==",
"task_id",
":",
"s... | Get task meta for task by ``task_id``.
:keyword exception_retry_count: How many times to retry by
transaction rollback on exception. This could theoretically
happen in a race condition if another worker is trying to
create the same task. The default is to retry once. | [
"Get",
"task",
"meta",
"for",
"task",
"by",
"task_id",
"."
] | 5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/managers.py#L140-L155 | train | 217,687 |
celery/django-celery | djcelery/managers.py | TaskManager.store_result | def store_result(self, task_id, result, status,
traceback=None, children=None):
"""Store the result and status of a task.
:param task_id: task id
:param result: The return value of the task, or an exception
instance raised by the task.
:param status: Task status. See
:meth:`celery.result.AsyncResult.get_status` for a list of
possible status values.
:keyword traceback: The traceback at the point of exception (if the
task failed).
:keyword children: List of serialized results of subtasks
of this task.
:keyword exception_retry_count: How many times to retry by
transaction rollback on exception. This could theoretically
happen in a race condition if another worker is trying to
create the same task. The default is to retry twice.
"""
return self.update_or_create(task_id=task_id,
defaults={'status': status,
'result': result,
'traceback': traceback,
'meta': {'children': children}}) | python | def store_result(self, task_id, result, status,
traceback=None, children=None):
"""Store the result and status of a task.
:param task_id: task id
:param result: The return value of the task, or an exception
instance raised by the task.
:param status: Task status. See
:meth:`celery.result.AsyncResult.get_status` for a list of
possible status values.
:keyword traceback: The traceback at the point of exception (if the
task failed).
:keyword children: List of serialized results of subtasks
of this task.
:keyword exception_retry_count: How many times to retry by
transaction rollback on exception. This could theoretically
happen in a race condition if another worker is trying to
create the same task. The default is to retry twice.
"""
return self.update_or_create(task_id=task_id,
defaults={'status': status,
'result': result,
'traceback': traceback,
'meta': {'children': children}}) | [
"def",
"store_result",
"(",
"self",
",",
"task_id",
",",
"result",
",",
"status",
",",
"traceback",
"=",
"None",
",",
"children",
"=",
"None",
")",
":",
"return",
"self",
".",
"update_or_create",
"(",
"task_id",
"=",
"task_id",
",",
"defaults",
"=",
"{",... | Store the result and status of a task.
:param task_id: task id
:param result: The return value of the task, or an exception
instance raised by the task.
:param status: Task status. See
:meth:`celery.result.AsyncResult.get_status` for a list of
possible status values.
:keyword traceback: The traceback at the point of exception (if the
task failed).
:keyword children: List of serialized results of subtasks
of this task.
:keyword exception_retry_count: How many times to retry by
transaction rollback on exception. This could theoretically
happen in a race condition if another worker is trying to
create the same task. The default is to retry twice. | [
"Store",
"the",
"result",
"and",
"status",
"of",
"a",
"task",
"."
] | 5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/managers.py#L158-L187 | train | 217,688 |
celery/django-celery | djcelery/managers.py | TaskSetManager.restore_taskset | def restore_taskset(self, taskset_id):
"""Get the async result instance by taskset id."""
try:
return self.get(taskset_id=taskset_id)
except self.model.DoesNotExist:
pass | python | def restore_taskset(self, taskset_id):
"""Get the async result instance by taskset id."""
try:
return self.get(taskset_id=taskset_id)
except self.model.DoesNotExist:
pass | [
"def",
"restore_taskset",
"(",
"self",
",",
"taskset_id",
")",
":",
"try",
":",
"return",
"self",
".",
"get",
"(",
"taskset_id",
"=",
"taskset_id",
")",
"except",
"self",
".",
"model",
".",
"DoesNotExist",
":",
"pass"
] | Get the async result instance by taskset id. | [
"Get",
"the",
"async",
"result",
"instance",
"by",
"taskset",
"id",
"."
] | 5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/managers.py#L205-L210 | train | 217,689 |
celery/django-celery | djcelery/managers.py | TaskSetManager.delete_taskset | def delete_taskset(self, taskset_id):
"""Delete a saved taskset result."""
s = self.restore_taskset(taskset_id)
if s:
s.delete() | python | def delete_taskset(self, taskset_id):
"""Delete a saved taskset result."""
s = self.restore_taskset(taskset_id)
if s:
s.delete() | [
"def",
"delete_taskset",
"(",
"self",
",",
"taskset_id",
")",
":",
"s",
"=",
"self",
".",
"restore_taskset",
"(",
"taskset_id",
")",
"if",
"s",
":",
"s",
".",
"delete",
"(",
")"
] | Delete a saved taskset result. | [
"Delete",
"a",
"saved",
"taskset",
"result",
"."
] | 5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/managers.py#L212-L216 | train | 217,690 |
celery/django-celery | djcelery/managers.py | TaskSetManager.store_result | def store_result(self, taskset_id, result):
"""Store the async result instance of a taskset.
:param taskset_id: task set id
:param result: The return value of the taskset
"""
return self.update_or_create(taskset_id=taskset_id,
defaults={'result': result}) | python | def store_result(self, taskset_id, result):
"""Store the async result instance of a taskset.
:param taskset_id: task set id
:param result: The return value of the taskset
"""
return self.update_or_create(taskset_id=taskset_id,
defaults={'result': result}) | [
"def",
"store_result",
"(",
"self",
",",
"taskset_id",
",",
"result",
")",
":",
"return",
"self",
".",
"update_or_create",
"(",
"taskset_id",
"=",
"taskset_id",
",",
"defaults",
"=",
"{",
"'result'",
":",
"result",
"}",
")"
] | Store the async result instance of a taskset.
:param taskset_id: task set id
:param result: The return value of the taskset | [
"Store",
"the",
"async",
"result",
"instance",
"of",
"a",
"taskset",
"."
] | 5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/managers.py#L219-L228 | train | 217,691 |
celery/django-celery | djcelery/backends/database.py | DatabaseBackend._store_result | def _store_result(self, task_id, result, status,
traceback=None, request=None):
"""Store return value and status of an executed task."""
self.TaskModel._default_manager.store_result(
task_id, result, status,
traceback=traceback, children=self.current_task_children(request),
)
return result | python | def _store_result(self, task_id, result, status,
traceback=None, request=None):
"""Store return value and status of an executed task."""
self.TaskModel._default_manager.store_result(
task_id, result, status,
traceback=traceback, children=self.current_task_children(request),
)
return result | [
"def",
"_store_result",
"(",
"self",
",",
"task_id",
",",
"result",
",",
"status",
",",
"traceback",
"=",
"None",
",",
"request",
"=",
"None",
")",
":",
"self",
".",
"TaskModel",
".",
"_default_manager",
".",
"store_result",
"(",
"task_id",
",",
"result",
... | Store return value and status of an executed task. | [
"Store",
"return",
"value",
"and",
"status",
"of",
"an",
"executed",
"task",
"."
] | 5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/backends/database.py#L28-L35 | train | 217,692 |
celery/django-celery | djcelery/backends/database.py | DatabaseBackend._save_group | def _save_group(self, group_id, result):
"""Store the result of an executed group."""
self.TaskSetModel._default_manager.store_result(group_id, result)
return result | python | def _save_group(self, group_id, result):
"""Store the result of an executed group."""
self.TaskSetModel._default_manager.store_result(group_id, result)
return result | [
"def",
"_save_group",
"(",
"self",
",",
"group_id",
",",
"result",
")",
":",
"self",
".",
"TaskSetModel",
".",
"_default_manager",
".",
"store_result",
"(",
"group_id",
",",
"result",
")",
"return",
"result"
] | Store the result of an executed group. | [
"Store",
"the",
"result",
"of",
"an",
"executed",
"group",
"."
] | 5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/backends/database.py#L37-L40 | train | 217,693 |
celery/django-celery | djcelery/backends/database.py | DatabaseBackend._restore_group | def _restore_group(self, group_id):
"""Get group metadata for a group by id."""
meta = self.TaskSetModel._default_manager.restore_taskset(group_id)
if meta:
return meta.to_dict() | python | def _restore_group(self, group_id):
"""Get group metadata for a group by id."""
meta = self.TaskSetModel._default_manager.restore_taskset(group_id)
if meta:
return meta.to_dict() | [
"def",
"_restore_group",
"(",
"self",
",",
"group_id",
")",
":",
"meta",
"=",
"self",
".",
"TaskSetModel",
".",
"_default_manager",
".",
"restore_taskset",
"(",
"group_id",
")",
"if",
"meta",
":",
"return",
"meta",
".",
"to_dict",
"(",
")"
] | Get group metadata for a group by id. | [
"Get",
"group",
"metadata",
"for",
"a",
"group",
"by",
"id",
"."
] | 5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/backends/database.py#L46-L50 | train | 217,694 |
celery/django-celery | djcelery/backends/database.py | DatabaseBackend.cleanup | def cleanup(self):
"""Delete expired metadata."""
expires = maybe_timedelta(self.expires)
for model in self.TaskModel, self.TaskSetModel:
model._default_manager.delete_expired(expires) | python | def cleanup(self):
"""Delete expired metadata."""
expires = maybe_timedelta(self.expires)
for model in self.TaskModel, self.TaskSetModel:
model._default_manager.delete_expired(expires) | [
"def",
"cleanup",
"(",
"self",
")",
":",
"expires",
"=",
"maybe_timedelta",
"(",
"self",
".",
"expires",
")",
"for",
"model",
"in",
"self",
".",
"TaskModel",
",",
"self",
".",
"TaskSetModel",
":",
"model",
".",
"_default_manager",
".",
"delete_expired",
"(... | Delete expired metadata. | [
"Delete",
"expired",
"metadata",
"."
] | 5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/backends/database.py#L61-L65 | train | 217,695 |
celery/django-celery | djcelery/snapshot.py | Camera.handle_task | def handle_task(self, uuid_task, worker=None):
"""Handle snapshotted event."""
uuid, task = uuid_task
if task.worker and task.worker.hostname:
worker = self.handle_worker(
(task.worker.hostname, task.worker),
)
defaults = {
'name': task.name,
'args': task.args,
'kwargs': task.kwargs,
'eta': correct_awareness(maybe_iso8601(task.eta)),
'expires': correct_awareness(maybe_iso8601(task.expires)),
'state': task.state,
'tstamp': fromtimestamp(task.timestamp),
'result': task.result or task.exception,
'traceback': task.traceback,
'runtime': task.runtime,
'worker': worker
}
# Some fields are only stored in the RECEIVED event,
# so we should remove these from default values,
# so that they are not overwritten by subsequent states.
[defaults.pop(attr, None) for attr in NOT_SAVED_ATTRIBUTES
if defaults[attr] is None]
return self.update_task(task.state,
task_id=uuid, defaults=defaults) | python | def handle_task(self, uuid_task, worker=None):
"""Handle snapshotted event."""
uuid, task = uuid_task
if task.worker and task.worker.hostname:
worker = self.handle_worker(
(task.worker.hostname, task.worker),
)
defaults = {
'name': task.name,
'args': task.args,
'kwargs': task.kwargs,
'eta': correct_awareness(maybe_iso8601(task.eta)),
'expires': correct_awareness(maybe_iso8601(task.expires)),
'state': task.state,
'tstamp': fromtimestamp(task.timestamp),
'result': task.result or task.exception,
'traceback': task.traceback,
'runtime': task.runtime,
'worker': worker
}
# Some fields are only stored in the RECEIVED event,
# so we should remove these from default values,
# so that they are not overwritten by subsequent states.
[defaults.pop(attr, None) for attr in NOT_SAVED_ATTRIBUTES
if defaults[attr] is None]
return self.update_task(task.state,
task_id=uuid, defaults=defaults) | [
"def",
"handle_task",
"(",
"self",
",",
"uuid_task",
",",
"worker",
"=",
"None",
")",
":",
"uuid",
",",
"task",
"=",
"uuid_task",
"if",
"task",
".",
"worker",
"and",
"task",
".",
"worker",
".",
"hostname",
":",
"worker",
"=",
"self",
".",
"handle_worke... | Handle snapshotted event. | [
"Handle",
"snapshotted",
"event",
"."
] | 5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/snapshot.py#L73-L100 | train | 217,696 |
celery/django-celery | djcelery/common.py | respect_language | def respect_language(language):
"""Context manager that changes the current translation language for
all code inside the following block.
Can e.g. be used inside tasks like this::
from celery import task
from djcelery.common import respect_language
@task
def my_task(language=None):
with respect_language(language):
pass
"""
if language:
prev = translation.get_language()
translation.activate(language)
try:
yield
finally:
translation.activate(prev)
else:
yield | python | def respect_language(language):
"""Context manager that changes the current translation language for
all code inside the following block.
Can e.g. be used inside tasks like this::
from celery import task
from djcelery.common import respect_language
@task
def my_task(language=None):
with respect_language(language):
pass
"""
if language:
prev = translation.get_language()
translation.activate(language)
try:
yield
finally:
translation.activate(prev)
else:
yield | [
"def",
"respect_language",
"(",
"language",
")",
":",
"if",
"language",
":",
"prev",
"=",
"translation",
".",
"get_language",
"(",
")",
"translation",
".",
"activate",
"(",
"language",
")",
"try",
":",
"yield",
"finally",
":",
"translation",
".",
"activate",... | Context manager that changes the current translation language for
all code inside the following block.
Can e.g. be used inside tasks like this::
from celery import task
from djcelery.common import respect_language
@task
def my_task(language=None):
with respect_language(language):
pass | [
"Context",
"manager",
"that",
"changes",
"the",
"current",
"translation",
"language",
"for",
"all",
"code",
"inside",
"the",
"following",
"block",
"."
] | 5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/common.py#L10-L32 | train | 217,697 |
celery/django-celery | djcelery/loaders.py | autodiscover | def autodiscover():
"""Include tasks for all applications in ``INSTALLED_APPS``."""
global _RACE_PROTECTION
if _RACE_PROTECTION:
return
_RACE_PROTECTION = True
try:
return filter(None, [find_related_module(app, 'tasks')
for app in settings.INSTALLED_APPS])
finally:
_RACE_PROTECTION = False | python | def autodiscover():
"""Include tasks for all applications in ``INSTALLED_APPS``."""
global _RACE_PROTECTION
if _RACE_PROTECTION:
return
_RACE_PROTECTION = True
try:
return filter(None, [find_related_module(app, 'tasks')
for app in settings.INSTALLED_APPS])
finally:
_RACE_PROTECTION = False | [
"def",
"autodiscover",
"(",
")",
":",
"global",
"_RACE_PROTECTION",
"if",
"_RACE_PROTECTION",
":",
"return",
"_RACE_PROTECTION",
"=",
"True",
"try",
":",
"return",
"filter",
"(",
"None",
",",
"[",
"find_related_module",
"(",
"app",
",",
"'tasks'",
")",
"for",
... | Include tasks for all applications in ``INSTALLED_APPS``. | [
"Include",
"tasks",
"for",
"all",
"applications",
"in",
"INSTALLED_APPS",
"."
] | 5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/loaders.py#L167-L178 | train | 217,698 |
celery/django-celery | djcelery/loaders.py | find_related_module | def find_related_module(app, related_name):
"""Given an application name and a module name, tries to find that
module in the application."""
try:
app_path = importlib.import_module(app).__path__
except ImportError as exc:
warn('Autodiscover: Error importing %s.%s: %r' % (
app, related_name, exc,
))
return
except AttributeError:
return
try:
f, _, _ = imp.find_module(related_name, app_path)
# f is returned None when app_path is a module
f and f.close()
except ImportError:
return
return importlib.import_module('{0}.{1}'.format(app, related_name)) | python | def find_related_module(app, related_name):
"""Given an application name and a module name, tries to find that
module in the application."""
try:
app_path = importlib.import_module(app).__path__
except ImportError as exc:
warn('Autodiscover: Error importing %s.%s: %r' % (
app, related_name, exc,
))
return
except AttributeError:
return
try:
f, _, _ = imp.find_module(related_name, app_path)
# f is returned None when app_path is a module
f and f.close()
except ImportError:
return
return importlib.import_module('{0}.{1}'.format(app, related_name)) | [
"def",
"find_related_module",
"(",
"app",
",",
"related_name",
")",
":",
"try",
":",
"app_path",
"=",
"importlib",
".",
"import_module",
"(",
"app",
")",
".",
"__path__",
"except",
"ImportError",
"as",
"exc",
":",
"warn",
"(",
"'Autodiscover: Error importing %s.... | Given an application name and a module name, tries to find that
module in the application. | [
"Given",
"an",
"application",
"name",
"and",
"a",
"module",
"name",
"tries",
"to",
"find",
"that",
"module",
"in",
"the",
"application",
"."
] | 5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/loaders.py#L181-L202 | train | 217,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.