INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Compares whether fst_obj and snd_obj are deeply equal.
In case when both fst_obj and snd_obj are of type np.ndarray or either np.memmap, they are compared using
np.array_equal(fst_obj, snd_obj). Otherwise, when they are lists or tuples, they are compared for length and then
deep_eq is applied component... | def deep_eq(fst_obj, snd_obj):
"""Compares whether fst_obj and snd_obj are deeply equal.
In case when both fst_obj and snd_obj are of type np.ndarray or either np.memmap, they are compared using
np.array_equal(fst_obj, snd_obj). Otherwise, when they are lists or tuples, they are compared for length and... |
Returns the negated mask.
If elements of input mask have 0 and non-zero values, then the returned matrix will have all elements 0 (1) where
the original one has non-zero (0).
:param mask: Input mask
:type mask: np.array
:return: array of same shape and dtype=int8 as input array
:rtype:... | def negate_mask(mask):
"""Returns the negated mask.
If elements of input mask have 0 and non-zero values, then the returned matrix will have all elements 0 (1) where
the original one has non-zero (0).
:param mask: Input mask
:type mask: np.array
:return: array of same shape and dtype=i... |
Function pads an image of shape (rows, columns, channels) with zeros.
It pads an image so that the shape becomes (rows + padded_rows, columns + padded_columns, channels), where
padded_rows = (int(rows/multiple_of[0]) + 1) * multiple_of[0] - rows
Same rule is applied to columns.
:type X: array ... | def constant_pad(X, multiple_of, up_down_rule='even', left_right_rule='even', pad_value=0):
"""Function pads an image of shape (rows, columns, channels) with zeros.
It pads an image so that the shape becomes (rows + padded_rows, columns + padded_columns, channels), where
padded_rows = (int(rows/multipl... |
Takes a collection of features structured in a various ways and parses them into one way.
If input format is not recognized it raises an error.
:return: A collection of features
:rtype: collections.OrderedDict(FeatureType: collections.OrderedDict(str: str or Ellipsis) or Ellipsis)
... | def _parse_features(features, new_names):
"""Takes a collection of features structured in a various ways and parses them into one way.
If input format is not recognized it raises an error.
:return: A collection of features
:rtype: collections.OrderedDict(FeatureType: collections.... |
Helping function of `_parse_features` that parses a list. | def _parse_dict(features, new_names):
"""Helping function of `_parse_features` that parses a list."""
feature_collection = OrderedDict()
for feature_type, feature_names in features.items():
try:
feature_type = FeatureType(feature_type)
except ValueEr... |
Helping function of `_parse_features` that parses a list. | def _parse_list(features, new_names):
"""Helping function of `_parse_features` that parses a list."""
feature_collection = OrderedDict()
for feature in features:
if isinstance(feature, FeatureType):
feature_collection[feature] = ...
elif isinstance... |
Helping function of `_parse_features` that parses a tuple. | def _parse_tuple(features, new_names):
"""Helping function of `_parse_features` that parses a tuple."""
name_idx = 1
try:
feature_type = FeatureType(features[0])
except ValueError:
feature_type = None
name_idx = 0
if feature_type and ... |
Helping function of `_parse_features` that parses a collection of feature names. | def _parse_feature_names(feature_names, new_names):
"""Helping function of `_parse_features` that parses a collection of feature names."""
if isinstance(feature_names, set):
return FeatureParser._parse_names_set(feature_names)
if isinstance(feature_names, dict):
re... |
Helping function of `_parse_feature_names` that parses a set of feature names. | def _parse_names_set(feature_names):
"""Helping function of `_parse_feature_names` that parses a set of feature names."""
feature_collection = OrderedDict()
for feature_name in feature_names:
if isinstance(feature_name, str):
feature_collection[feature_name] = ..... |
Helping function of `_parse_feature_names` that parses a dictionary of feature names. | def _parse_names_dict(feature_names):
"""Helping function of `_parse_feature_names` that parses a dictionary of feature names."""
feature_collection = OrderedDict()
for feature_name, new_feature_name in feature_names.items():
if isinstance(feature_name, str) and (isinstance(new_f... |
Helping function of `_parse_feature_names` that parses a tuple or a list of feature names. | def _parse_names_tuple(feature_names, new_names):
"""Helping function of `_parse_feature_names` that parses a tuple or a list of feature names."""
for feature in feature_names:
if not isinstance(feature, str) and feature is not ...:
raise ValueError('Failed to parse {}, e... |
Checks that feature types are a subset of allowed feature types. (`None` is handled
:raises: ValueError | def _check_feature_types(self):
""" Checks that feature types are a subset of allowed feature types. (`None` is handled
:raises: ValueError
"""
if self.default_feature_type is not None and self.default_feature_type not in self.allowed_feature_types:
raise ValueError('D... |
A generator of parsed features.
:param eopatch: A given EOPatch
:type eopatch: EOPatch or None
:return: One by one feature
:rtype: tuple(FeatureType, str) or tuple(FeatureType, str, str) | def _get_features(self, eopatch=None):
"""A generator of parsed features.
:param eopatch: A given EOPatch
:type eopatch: EOPatch or None
:return: One by one feature
:rtype: tuple(FeatureType, str) or tuple(FeatureType, str, str)
"""
for feature_type, feat... |
Iterates over allowed feature types of given EOPatch and tries to find a feature type for which there
exists a feature with given name
:return: A feature type or `None` if such feature type does not exist
:rtype: FeatureType or None | def _find_feature_type(self, feature_name, eopatch):
""" Iterates over allowed feature types of given EOPatch and tries to find a feature type for which there
exists a feature with given name
:return: A feature type or `None` if such feature type does not exist
:rtype: FeatureType ... |
Helping function of `get_features` | def _return_feature(self, feature_type, feature_name, new_feature_name=...):
""" Helping function of `get_features`
"""
if self.new_names:
return feature_type, feature_name, (self.rename_function(feature_name) if new_feature_name is ... else
... |
Parses dependencies and adds names of task_names.
:param dependencies: Input of dependency parameter
:type dependencies: list(tuple or Dependency)
:param task_names: Human-readable names of tasks
:type task_names: dict(EOTask: str) or None
:return: List of dependencies
... | def _parse_dependencies(dependencies, task_names):
"""Parses dependencies and adds names of task_names.
:param dependencies: Input of dependency parameter
:type dependencies: list(tuple or Dependency)
:param task_names: Human-readable names of tasks
:type task_names: dict(... |
Adds universally unique user ids (UUID) to each task of the workflow.
:param dependencies: The list of dependencies between tasks defining the computational graph
:type dependencies: list(Dependency)
:return: A dictionary mapping UUID to dependencies
:rtype: dict(str: Dependency) | def _set_task_uuid(self, dependencies):
"""Adds universally unique user ids (UUID) to each task of the workflow.
:param dependencies: The list of dependencies between tasks defining the computational graph
:type dependencies: list(Dependency)
:return: A dictionary mapping UUID to d... |
Creates a directed graph from dependencies.
:param dependencies: A list of Dependency objects
:type dependencies: list(Dependency)
:return: A directed graph of the workflow
:rtype: DirectedGraph | def create_dag(self, dependencies):
"""Creates a directed graph from dependencies.
:param dependencies: A list of Dependency objects
:type dependencies: list(Dependency)
:return: A directed graph of the workflow
:rtype: DirectedGraph
"""
dag = DirectedGra... |
Computes an ordering < of tasks so that for any two tasks t and t' we have that if t depends on t' then
t' < t. In words, all dependencies of a task precede the task in this ordering.
:param dag: A directed acyclic graph representing dependencies between tasks.
:type dag: DirectedGraph
... | def _schedule_dependencies(dag):
"""
Computes an ordering < of tasks so that for any two tasks t and t' we have that if t depends on t' then
t' < t. In words, all dependencies of a task precede the task in this ordering.
:param dag: A directed acyclic graph representing dependencie... |
Executes the workflow.
:param input_args: External input arguments to the workflow. They have to be in a form of a dictionary where
each key is an EOTask used in the workflow and each value is a dictionary or a tuple of arguments.
:type input_args: dict(EOTask: dict(str: object) or tupl... | def execute(self, input_args=None, monitor=False):
"""Executes the workflow.
:param input_args: External input arguments to the workflow. They have to be in a form of a dictionary where
each key is an EOTask used in the workflow and each value is a dictionary or a tuple of arguments.
... |
Parses EOWorkflow input arguments provided by user and raises an error if something is wrong. This is
done automatically in the process of workflow execution | def parse_input_args(input_args):
""" Parses EOWorkflow input arguments provided by user and raises an error if something is wrong. This is
done automatically in the process of workflow execution
"""
input_args = input_args if input_args else {}
for task, args in input_args.... |
Executes tasks comprising the workflow in the predetermined order.
:param input_args: External input arguments to the workflow.
:type input_args: Dict
:param out_degs: Dictionary mapping vertices (task IDs) to their out-degrees. (The out-degree equals the number
of tasks that depen... | def _execute_tasks(self, *, input_args, out_degs, monitor):
"""Executes tasks comprising the workflow in the predetermined order.
:param input_args: External input arguments to the workflow.
:type input_args: Dict
:param out_degs: Dictionary mapping vertices (task IDs) to their out... |
Executes a task of the workflow.
:param dependency: A workflow dependency
:type dependency: Dependency
:param input_args: External task parameters.
:type input_args: dict
:param intermediate_results: The dictionary containing intermediate results, including the results of ... | def _execute_task(self, *, dependency, input_args, intermediate_results, monitor):
"""Executes a task of the workflow.
:param dependency: A workflow dependency
:type dependency: Dependency
:param input_args: External task parameters.
:type input_args: dict
:param ... |
Relaxes dependencies incurred by ``task_id``. After the task with ID ``task_id`` has been successfully
executed, all the tasks it depended on are upadted. If ``task_id`` was the last remaining dependency of a task
``t`` then ``t``'s result is removed from memory and, depending on ``remove_intermediate... | def _relax_dependencies(self, *, dependency, out_degrees, intermediate_results):
"""
Relaxes dependencies incurred by ``task_id``. After the task with ID ``task_id`` has been successfully
executed, all the tasks it depended on are upadted. If ``task_id`` was the last remaining dependency of a... |
Returns an ordered dictionary {task_name: task} of all tasks within this workflow.
:return: Ordered dictionary with key being task_name (str) and an instance of a corresponding task from this
workflow
:rtype: OrderedDict | def get_tasks(self):
"""Returns an ordered dictionary {task_name: task} of all tasks within this workflow.
:return: Ordered dictionary with key being task_name (str) and an instance of a corresponding task from this
workflow
:rtype: OrderedDict
"""
tasks = collect... |
Generates the DOT description of the underlying computational graph.
:return: The DOT representation of the computational graph
:rtype: Digraph | def get_dot(self):
"""Generates the DOT description of the underlying computational graph.
:return: The DOT representation of the computational graph
:rtype: Digraph
"""
dot = Digraph()
dep_to_dot_name = self._get_dep_to_dot_name_mapping(self.ordered_dependencie... |
Creates mapping between Dependency classes and names used in DOT graph | def _get_dep_to_dot_name_mapping(dependencies):
""" Creates mapping between Dependency classes and names used in DOT graph
"""
dot_name_to_deps = {}
for dep in dependencies:
dot_name = dep.name
if dot_name not in dot_name_to_deps:
dot_name... |
Visualize the computational graph.
:param filename: Filename of the output image together with file extension. Supported formats: `png`, `jpg`,
`pdf`, ... . Check `graphviz` Python package for more options
:type filename: str
:return: The DOT representation of the computational... | def dependency_graph(self, filename=None):
"""Visualize the computational graph.
:param filename: Filename of the output image together with file extension. Supported formats: `png`, `jpg`,
`pdf`, ... . Check `graphviz` Python package for more options
:type filename: str
... |
If some tasks of the workflow are the same they are deep copied. | def _make_tasks_unique(tasks):
"""If some tasks of the workflow are the same they are deep copied."""
unique_tasks = []
prev_tasks = set()
for task in tasks:
if task in prev_tasks:
task = copy.deepcopy(task)
unique_tasks.append(task)
... |
Returns dictionary items | def items(self):
""" Returns dictionary items """
return {dep.task: value for dep, value in self._result.items()}.items() |
Dictionary get method | def get(self, key, default=None):
""" Dictionary get method """
if isinstance(key, EOTask):
key = self._uuid_dict[key.private_task_config.uuid]
return self._result.get(key, default) |
Maps morphological operation type to function
:param morph_type: Morphological operation type
:type morph_type: MorphologicalOperations
:return: function | def get_operation(cls, morph_type):
""" Maps morphological operation type to function
:param morph_type: Morphological operation type
:type morph_type: MorphologicalOperations
:return: function
"""
return {
cls.OPENING: skimage.morphology.opening,
... |
Execute method takes EOPatch and changes the specified feature | def execute(self, eopatch):
""" Execute method takes EOPatch and changes the specified feature
"""
feature_type, feature_name = next(self.feature(eopatch))
eopatch[feature_type][feature_name] = self.process(eopatch[feature_type][feature_name])
return eopatch |
Applies the morphological operation to the mask object | def process(self, raster):
""" Applies the morphological operation to the mask object
"""
dim = len(raster.shape)
if dim == 3:
for dim in range(raster.shape[2]):
raster[:, :, dim] = self.morph_operation(raster[:, :, dim], self.struct_elem)
elif ... |
:return: dictionary of out-degrees, see get_outdegree | def get_outdegrees(self):
"""
:return: dictionary of out-degrees, see get_outdegree
"""
return {vertex: len(self.adj_dict[vertex]) for vertex in self.adj_dict} |
Adds the edge ``u_vertex -> v_vertex`` to the graph if the edge is not already present.
:param u_vertex: Vertex
:param v_vertex: Vertex
:return: ``True`` if a new edge was added. ``False`` otherwise. | def add_edge(self, u_vertex, v_vertex):
"""Adds the edge ``u_vertex -> v_vertex`` to the graph if the edge is not already present.
:param u_vertex: Vertex
:param v_vertex: Vertex
:return: ``True`` if a new edge was added. ``False`` otherwise.
"""
self._vertices.ad... |
Removes the edge ``u_vertex -> v_vertex`` from the graph if the edge is present.
:param u_vertex: Vertex
:param v_vertex: Vertex
:return: ``True`` if the existing edge was removed. ``False`` otherwise. | def del_edge(self, u_vertex, v_vertex):
"""Removes the edge ``u_vertex -> v_vertex`` from the graph if the edge is present.
:param u_vertex: Vertex
:param v_vertex: Vertex
:return: ``True`` if the existing edge was removed. ``False`` otherwise.
"""
if self.is_edge... |
Adds a new vertex to the graph if not present.
:param vertex: Vertex
:return: ``True`` if ``vertex`` added and not yet present. ``False`` otherwise. | def add_vertex(self, vertex):
"""Adds a new vertex to the graph if not present.
:param vertex: Vertex
:return: ``True`` if ``vertex`` added and not yet present. ``False`` otherwise.
"""
if vertex not in self._vertices:
self._vertices.add(vertex)
r... |
Removes the vertex ``vertex`` and all incident edges from the graph.
**Note** that this is an expensive operation that should be avoided!
Running time is O(V+E)
:param vertex: Vertex
:return: ``True`` if ``vertex`` was removed from the graph. ``False`` otherwise. | def del_vertex(self, vertex):
"""Removes the vertex ``vertex`` and all incident edges from the graph.
**Note** that this is an expensive operation that should be avoided!
Running time is O(V+E)
:param vertex: Vertex
:return: ``True`` if ``vertex`` was removed from the ... |
Return DirectedGraph created from edges
:param edges:
:return: DirectedGraph | def from_edges(edges):
""" Return DirectedGraph created from edges
:param edges:
:return: DirectedGraph
"""
dag = DirectedGraph()
for _u, _v in edges:
dag.add_edge(_u, _v)
return dag |
True if the directed graph dag contains a cycle. False otherwise.
The algorithm is naive, running in O(V^2) time, and not intended for serious use! For production purposes on
larger graphs consider implementing Tarjan's O(V+E)-time algorithm instead.
:type dag: DirectedGraph | def _is_cyclic(dag):
"""True if the directed graph dag contains a cycle. False otherwise.
The algorithm is naive, running in O(V^2) time, and not intended for serious use! For production purposes on
larger graphs consider implementing Tarjan's O(V+E)-time algorithm instead.
:type... |
Execute predicate on input eopatch
:param eopatch: Input `eopatch` instance
:return: The same `eopatch` instance with a `mask.valid_data` array computed according to the predicate | def execute(self, eopatch):
""" Execute predicate on input eopatch
:param eopatch: Input `eopatch` instance
:return: The same `eopatch` instance with a `mask.valid_data` array computed according to the predicate
"""
feature_type, feature_name = next(self.valid_data_feature())
... |
Mask values of `feature` according to the `mask_values` in `mask_feature`
:param eopatch: `eopatch` to be processed
:return: Same `eopatch` instance with masked `feature` | def execute(self, eopatch):
""" Mask values of `feature` according to the `mask_values` in `mask_feature`
:param eopatch: `eopatch` to be processed
:return: Same `eopatch` instance with masked `feature`
"""
feature_type, feature_name, new_feature_name = next(self.feature(eopatch... |
If given FeatureType stores a dictionary of numpy.ndarrays it returns dimensions of such arrays. | def ndim(self):
"""If given FeatureType stores a dictionary of numpy.ndarrays it returns dimensions of such arrays."""
if self.is_raster():
return {
FeatureType.DATA: 4,
FeatureType.MASK: 4,
FeatureType.SCALAR: 2,
FeatureType.LA... |
Returns type of the data for the given FeatureType. | def type(self):
"""Returns type of the data for the given FeatureType."""
if self is FeatureType.TIMESTAMP:
return list
if self is FeatureType.BBOX:
return BBox
return dict |
Splits the filename string by the extension of the file | def split_by_extensions(filename):
""" Splits the filename string by the extension of the file
"""
parts = filename.split('.')
idx = len(parts) - 1
while FileFormat.is_file_format(parts[idx]):
parts[idx] = FileFormat(parts[idx])
idx -= 1
return ['.... |
Resets all counters, truth and classification masks. | def reset_counters(self):
"""
Resets all counters, truth and classification masks.
"""
self.truth_masks = None
self.classification_masks = None
self.pixel_truth_counts = None
self.pixel_classification_counts = None
self.pixel_truth_sum = None
self.... |
Count the pixels belonging to each truth class | def _count_truth_pixels(self):
"""
Count the pixels belonging to each truth class
"""
pixel_count = np.array([[np.nonzero(mask)[0].shape[0] for mask in masktype]
for masktype in self.truth_masks])
pixel_count = np.moveaxis(pixel_count, 0, -1)
... |
Count the pixels belonging to each classified class. | def _count_classified_pixels(self):
"""
Count the pixels belonging to each classified class.
"""
class_values = self.class_dictionary.values()
classification_count = np.array([[[np.count_nonzero(prediction[np.nonzero(mask)] == class_val)
... |
Extracts ground truth and classification results from the EOPatch and
aggregates the results. | def add_validation_patch(self, patch):
"""
Extracts ground truth and classification results from the EOPatch and
aggregates the results.
"""
# 2. Convert 8-bit mask
self._transform_truth(patch)
# 3. Count truth labeled pixels
self._count_truth_pixels()
... |
Aggregate the results from all EOPatches. | def validate(self):
"""
Aggregate the results from all EOPatches.
"""
self.pixel_truth_sum = np.sum(self.pixel_truth_counts, axis=0)
self.pixel_classification_sum = np.sum(self.pixel_classification_counts, axis=0) |
Save validator object to pickle. | def save(self, filename):
"""
Save validator object to pickle.
"""
with open(filename, 'wb') as output:
pickle.dump(self, output, protocol=pickle.HIGHEST_PROTOCOL) |
Returns pandas DataFrame containing pixel counts for all truth classes,
classified classes (for each truth class), and file name of the input
EODataSet.
The data frame thus contains
N = self.n_validation_sets rows
and
M = len(self.truth_classes) + len(self.truth_clas... | def pandas_df(self):
"""
Returns pandas DataFrame containing pixel counts for all truth classes,
classified classes (for each truth class), and file name of the input
EODataSet.
The data frame thus contains
N = self.n_validation_sets rows
and
M = len(... |
Returns the normalised confusion matrix | def confusion_matrix(self):
"""
Returns the normalised confusion matrix
"""
confusion_matrix = self.pixel_classification_sum.astype(np.float)
confusion_matrix = np.divide(confusion_matrix.T, self.pixel_truth_sum.T).T
return confusion_matrix * 100.0 |
Plots the confusion matrix. | def plot_confusion_matrix(self, normalised=True):
"""
Plots the confusion matrix.
"""
conf_matrix = self.confusion_matrix()
if normalised:
sns.heatmap(conf_matrix,
annot=True, annot_kws={"size": 12}, fmt='2.1f', cmap='YlGnBu', vmin=0.0,
... |
Prints out the summary of validation for giving scoring function. | def summary(self, scoring):
"""
Prints out the summary of validation for giving scoring function.
"""
if scoring == 'class_confusion':
print('*' * 50)
print(' Confusion Matrix ')
print('x-axis: ' + ' | '.join(list(self.class_dictionary.keys())))
... |
:param eopatch: Input EOPatch.
:type eopatch: EOPatch
:return: Transformed eo patch
:rtype: EOPatch | def execute(self, eopatch):
"""
:param eopatch: Input EOPatch.
:type eopatch: EOPatch
:return: Transformed eo patch
:rtype: EOPatch
"""
feature_type, feature_name = next(self.feature(eopatch))
good_idxs = self._get_filtered_indices(eopatch[feature_type][f... |
Execute computation of HoG features on input eopatch
:param eopatch: Input eopatch
:type eopatch: eolearn.core.EOPatch
:return: EOPatch instance with new keys holding the HoG features and HoG image for visualisation.
:rtype: eolearn.core.EOPatch | def execute(self, eopatch):
""" Execute computation of HoG features on input eopatch
:param eopatch: Input eopatch
:type eopatch: eolearn.core.EOPatch
:return: EOPatch instance with new keys holding the HoG features and HoG image for visualisation.
:rtype: eolear... |
Execute computation of local binary patterns on input eopatch
:param eopatch: Input eopatch
:type eopatch: eolearn.core.EOPatch
:return: EOPatch instance with new key holding the LBP image.
:rtype: eolearn.core.EOPatch | def execute(self, eopatch):
""" Execute computation of local binary patterns on input eopatch
:param eopatch: Input eopatch
:type eopatch: eolearn.core.EOPatch
:return: EOPatch instance with new key holding the LBP image.
:rtype: eolearn.core.EOPatch
"""
... |
Fit model parameters to data using the RANSAC algorithm
This implementation is written from pseudo-code found at
http://en.wikipedia.org/w/index.php?title=RANSAC&oldid=116358182
:param npts: A set of observed data points
:param model: A model that can be fitted to data points
:param n: The minimum... | def ransac(npts, model, n, k, t, d):
""" Fit model parameters to data using the RANSAC algorithm
This implementation is written from pseudo-code found at
http://en.wikipedia.org/w/index.php?title=RANSAC&oldid=116358182
:param npts: A set of observed data points
:param model: A model that can be fi... |
return n random rows of data (and also the other len(data)-n rows) | def random_partition(n, n_data):
"""return n random rows of data (and also the other len(data)-n rows)"""
all_idxs = np.arange(n_data)
np.random.shuffle(all_idxs)
idxs1 = all_idxs[:n]
idxs2 = all_idxs[n:]
return idxs1, idxs2 |
Estimate rigid transformation given a set of indices
:param idx: Array of indices used to estimate the transformation
:return: Estimated transformation matrix | def estimate_rigid_transformation(self, idx):
""" Estimate rigid transformation given a set of indices
:param idx: Array of indices used to estimate the transformation
:return: Estimated transformation matrix
"""
# Look at points of given indices only
src_pts = self.src_... |
Estimate the registration error of estimated transformation matrix
:param idx: List of points used to estimate the transformation
:param warp_matrix: Matrix estimating Euler trasnformation
:return: Square root of Target Registration Error | def score(self, idx, warp_matrix):
""" Estimate the registration error of estimated transformation matrix
:param idx: List of points used to estimate the transformation
:param warp_matrix: Matrix estimating Euler trasnformation
:return: Square root of Target Registration Error
"... |
Create a view of `array` which for every point gives the n-dimensional
neighbourhood of size window. New dimensions are added at the end of
`array` or after the corresponding original dimension.
Parameters
----------
array : array_like
Array to which the rolling window is applied.
... | def rolling_window(array, window=(0,), asteps=None, wsteps=None, axes=None, toend=True):
"""Create a view of `array` which for every point gives the n-dimensional
neighbourhood of size window. New dimensions are added at the end of
`array` or after the corresponding original dimension.
Parameters
... |
Method that estimates registrations and warps EOPatch objects | def execute(self, eopatch):
""" Method that estimates registrations and warps EOPatch objects
"""
self.check_params()
self.get_params()
new_eopatch = copy.deepcopy(eopatch)
f_type, f_name = next(self.registration_feature(eopatch))
sliced_data = copy.deepcopy(eop... |
Function to warp input image given an estimated 2D linear transformation
:param warp_matrix: Linear 2x3 matrix to use to linearly warp the input images
:type warp_matrix: ndarray
:param img: Image to be warped with estimated transformation
:type img: ndarray
:param iflag: Interp... | def warp(self, warp_matrix, img, iflag=cv2.INTER_NEAREST):
""" Function to warp input image given an estimated 2D linear transformation
:param warp_matrix: Linear 2x3 matrix to use to linearly warp the input images
:type warp_matrix: ndarray
:param img: Image to be warped with estimated... |
Static method that check if estimated linear transformation could be unplausible
This function checks whether the norm of the estimated translation or the rotation angle exceed predefined
values. For the translation, a maximum translation radius of 20 pixels is flagged, while larger rotations than
... | def is_registration_suspicious(warp_matrix):
""" Static method that check if estimated linear transformation could be unplausible
This function checks whether the norm of the estimated translation or the rotation angle exceed predefined
values. For the translation, a maximum translation radius ... |
Implementation of pair-wise registration using thunder-registration
For more information on the model estimation, refer to https://github.com/thunder-project/thunder-registration
This function takes two 2D single channel images and estimates a 2D translation that best aligns the pair. The
estim... | def register(self, src, trg, trg_mask=None, src_mask=None):
""" Implementation of pair-wise registration using thunder-registration
For more information on the model estimation, refer to https://github.com/thunder-project/thunder-registration
This function takes two 2D single channel images and... |
Implementation of pair-wise registration and warping using Enhanced Correlation Coefficient
This function estimates an Euclidean transformation (x,y translation + rotation) using the intensities of the
pair of images to be registered. The similarity metric is a modification of the cross-correlation met... | def register(self, src, trg, trg_mask=None, src_mask=None):
""" Implementation of pair-wise registration and warping using Enhanced Correlation Coefficient
This function estimates an Euclidean transformation (x,y translation + rotation) using the intensities of the
pair of images to be register... |
Implementation of pair-wise registration and warping using point-based matching
This function estimates a number of transforms (Euler, PartialAffine and Homography) using point-based matching.
Features descriptor are first extracted from the pair of images using either SIFT or SURF descriptors. A
... | def register(self, src, trg, trg_mask=None, src_mask=None):
""" Implementation of pair-wise registration and warping using point-based matching
This function estimates a number of transforms (Euler, PartialAffine and Homography) using point-based matching.
Features descriptor are first extracte... |
Normalise and scale image in 0-255 range | def rescale_image(image):
""" Normalise and scale image in 0-255 range """
s2_min_value, s2_max_value = 0, 1
out_min_value, out_max_value = 0, 255
# Clamp values in 0-1 range
image[image > s2_max_value] = s2_max_value
image[image < s2_min_value] = s2_min_value
# R... |
Parameters
----------
X : array-like, shape [n x m]
The mask in form of n x m array. | def transform(self, X):
"""
Parameters
----------
X : array-like, shape [n x m]
The mask in form of n x m array.
"""
if self.mode_ == 'target':
return np.apply_along_axis(self._target, 1, np.reshape(X, (X.shape[0], X.shape[1] * X.shape[2]))... |
Parameters
----------
X : array-like, shape [n x m]
The mask in form of n x m array. | def transform(self, X):
"""
Parameters
----------
X : array-like, shape [n x m]
The mask in form of n x m array.
"""
if self.binary_:
return (X & self.definition_ > 0).astype(int)
return (X == self.definition_).astype(int) |
Returns a new geopandas dataframe with same structure as original one (columns) except that
it contains only polygons that are contained within the given bbox.
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: New EOPatch
:rtype: EOPatch | def _get_submap(self, eopatch):
"""
Returns a new geopandas dataframe with same structure as original one (columns) except that
it contains only polygons that are contained within the given bbox.
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: New EOPatch
... |
Execute function which adds new vector layer to the EOPatch
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: New EOPatch with added vector layer
:rtype: EOPatch | def execute(self, eopatch):
""" Execute function which adds new vector layer to the EOPatch
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: New EOPatch with added vector layer
:rtype: EOPatch
"""
bbox_map = self._get_submap(eopatch)
height, ... |
Vectorizes a data slice of a single time component
:param raster: Numpy array or shape (height, width, channels)
:type raster: numpy.ndarray
:param data_transform: Object holding a transform vector (i.e. geographical location vector) of the raster
:type data_transform: affine.Affine
... | def _vectorize_single_raster(self, raster, data_transform, crs, timestamp=None):
""" Vectorizes a data slice of a single time component
:param raster: Numpy array or shape (height, width, channels)
:type raster: numpy.ndarray
:param data_transform: Object holding a transform vector (i.e... |
Execute function which adds new vector layer to the EOPatch
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: New EOPatch with added vector layer
:rtype: EOPatch | def execute(self, eopatch):
""" Execute function which adds new vector layer to the EOPatch
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: New EOPatch with added vector layer
:rtype: EOPatch
"""
for raster_ft, raster_fn, vector_fn in self.feature_g... |
Returns the area of the selected polygon if index is provided or of all polygons if it's not. | def area(self, cc_index=None):
"""
Returns the area of the selected polygon if index is provided or of all polygons if it's not.
"""
if cc_index is not None:
return self.areas[cc_index]
return np.sum(self.areas) |
Sample n points from the provided raster mask. The number of points belonging
to each class is proportional to the area this class covers in the raster mask,
if weighted is set to True.
TODO: If polygon has holes the number of sampled points will be less than nsamples
:param nsamples: ... | def sample(self, nsamples=1, weighted=True):
"""
Sample n points from the provided raster mask. The number of points belonging
to each class is proportional to the area this class covers in the raster mask,
if weighted is set to True.
TODO: If polygon has holes the number of sam... |
Returns a random polygon of any class. The probability of each polygon to be sampled
is proportional to its area if weighted is True. | def sample_cc(self, nsamples=1, weighted=True):
"""
Returns a random polygon of any class. The probability of each polygon to be sampled
is proportional to its area if weighted is True.
"""
weights = self.areas / np.sum(self.areas) if weighted else None
for index in np.ra... |
Returns randomly sampled points from a polygon.
Complexity of this procedure is (A/a * nsamples) where A=area(bbox(P))
and a=area(P) where P is the polygon of the connected component cc_index | def sample_within_cc(self, cc_index, nsamples=1):
"""
Returns randomly sampled points from a polygon.
Complexity of this procedure is (A/a * nsamples) where A=area(bbox(P))
and a=area(P) where P is the polygon of the connected component cc_index
"""
polygon = self.geomet... |
Tests whether point lies within the polygon | def contains(polygon, point):
"""
Tests whether point lies within the polygon
"""
in_hole = functools.reduce(
lambda P, Q: P and Q,
[interior.covers(point) for interior in polygon.interiors]
) if polygon.interiors else False
return polygon.covers(p... |
Selects a random point in interior of a rectangle
:param bounds: Rectangle coordinates (x_min, y_min, x_max, y_max)
:type bounds: tuple(float)
:return: Random point from interior of rectangle
:rtype: tuple of x and y coordinates | def random_coords(bounds):
""" Selects a random point in interior of a rectangle
:param bounds: Rectangle coordinates (x_min, y_min, x_max, y_max)
:type bounds: tuple(float)
:return: Random point from interior of rectangle
:rtype: tuple of x and y coordinates
"""
... |
Selects a random point in interior of a triangle | def random_point_triangle(triangle, use_int_coords=True):
"""
Selects a random point in interior of a triangle
"""
xs, ys = triangle.exterior.coords.xy
A, B, C = zip(xs[:-1], ys[:-1])
r1, r2 = np.random.rand(), np.random.rand()
rx, ry = (1 - sqrt(r1)) * np.asarray... |
Finds the smallest integer value >=0 that is not in `labels`
:return: Value that is not in the labels
:rtype: int | def _get_unknown_value(self):
""" Finds the smallest integer value >=0 that is not in `labels`
:return: Value that is not in the labels
:rtype: int
"""
label_set = set(self.labels)
value = 0
while value in label_set:
value += 1
return value |
Sample `nsamples_per_label` points from the binary mask corresponding to `label`
Randomly sample `nsamples_per_label` point form the binary mask corresponding to `label`. Sampling with
replacement is used if the required `nsamples_per_label` is larger than the available `label_count`
:param im... | def _binary_sample(image, label, n_samples_per_label, label_count):
""" Sample `nsamples_per_label` points from the binary mask corresponding to `label`
Randomly sample `nsamples_per_label` point form the binary mask corresponding to `label`. Sampling with
replacement is used if the required `n... |
Sample `nsamples` points form raster
:param raster: Input 2D or single-channel 3D label image
:type raster: uint8 numpy array
:param n_samples: Number of points to sample in total
:type n_samples: uint32
:return: List of row indices of samples, list of column indices of samples
... | def sample(self, raster, n_samples=1000):
""" Sample `nsamples` points form raster
:param raster: Input 2D or single-channel 3D label image
:type raster: uint8 numpy array
:param n_samples: Number of points to sample in total
:type n_samples: uint32
:return: List of row ... |
Execute random spatial sampling of time-series stored in the input eopatch
:param eopatch: Input eopatch to be sampled
:type eopatch: EOPatch
:param seed: Setting seed of random sampling. If None no seed will be used.
:type seed: int or None
:return: An EOPatch with spatially sa... | def execute(self, eopatch, seed=None):
""" Execute random spatial sampling of time-series stored in the input eopatch
:param eopatch: Input eopatch to be sampled
:type eopatch: EOPatch
:param seed: Setting seed of random sampling. If None no seed will be used.
:type seed: int or... |
Saves the EOPatch to disk: `folder/eopatch_folder`.
:param eopatch: EOPatch which will be saved
:type eopatch: EOPatch
:param eopatch_folder: name of EOPatch folder containing data
:type eopatch_folder: str
:return: The same EOPatch
:rtype: EOPatch | def execute(self, eopatch, *, eopatch_folder):
"""Saves the EOPatch to disk: `folder/eopatch_folder`.
:param eopatch: EOPatch which will be saved
:type eopatch: EOPatch
:param eopatch_folder: name of EOPatch folder containing data
:type eopatch_folder: str
:return: The s... |
Loads the EOPatch from disk: `folder/eopatch_folder`.
:param eopatch_folder: name of EOPatch folder containing data
:type eopatch_folder: str
:return: EOPatch loaded from disk
:rtype: EOPatch | def execute(self, *, eopatch_folder):
"""Loads the EOPatch from disk: `folder/eopatch_folder`.
:param eopatch_folder: name of EOPatch folder containing data
:type eopatch_folder: str
:return: EOPatch loaded from disk
:rtype: EOPatch
"""
eopatch = EOPatch.load(os.... |
Returns the EOPatch with added features.
:param eopatch: input EOPatch
:type eopatch: EOPatch
:param data: data to be added to the feature
:type data: object
:return: input EOPatch with the specified feature
:rtype: EOPatch | def execute(self, eopatch, data):
"""Returns the EOPatch with added features.
:param eopatch: input EOPatch
:type eopatch: EOPatch
:param data: data to be added to the feature
:type data: object
:return: input EOPatch with the specified feature
:rtype: EOPatch
... |
Returns the EOPatch with removed features.
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: input EOPatch without the specified feature
:rtype: EOPatch | def execute(self, eopatch):
"""Returns the EOPatch with removed features.
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: input EOPatch without the specified feature
:rtype: EOPatch
"""
for feature_type, feature_name in self.feature_gen(eopatch):
... |
Returns the EOPatch with renamed features.
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: input EOPatch with the renamed features
:rtype: EOPatch | def execute(self, eopatch):
"""Returns the EOPatch with renamed features.
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: input EOPatch with the renamed features
:rtype: EOPatch
"""
for feature_type, feature_name, new_feature_name in self.feature_ge... |
Calculate percentile of numpy stack and return the index of the chosen pixel.
numpy percentile function is used with one of the following interpolations {'linear', 'lower', 'higher',
'midpoint', 'nearest'} | def _numpy_index_by_percentile(self, data, percentile):
""" Calculate percentile of numpy stack and return the index of the chosen pixel.
numpy percentile function is used with one of the following interpolations {'linear', 'lower', 'higher',
'midpoint', 'nearest'}
"""
d... |
Calculate percentile of numpy stack and return the index of the chosen pixel. | def _geoville_index_by_percentile(self, data, percentile):
""" Calculate percentile of numpy stack and return the index of the chosen pixel. """
# no_obs = bn.allnan(arr_tmp["data"], axis=0)
data_tmp = np.array(data, copy=True)
valid_obs = np.sum(np.isfinite(data_tmp), axis=0)
# ... |
Compute indices along temporal dimension corresponding to the sought percentile
:param data: Input 3D array holding the reference band
:type data: numpy array
:return: 2D array holding the temporal index corresponding to percentile | def _get_indices(self, data):
""" Compute indices along temporal dimension corresponding to the sought percentile
:param data: Input 3D array holding the reference band
:type data: numpy array
:return: 2D array holding the temporal index corresponding to percentile
"... |
Compute composite array merging temporal frames according to the compositing method
:param eopatch: eopatch holding time-series
:return: eopatch with composite image of time-series | def execute(self, eopatch):
""" Compute composite array merging temporal frames according to the compositing method
:param eopatch: eopatch holding time-series
:return: eopatch with composite image of time-series
"""
feature_type, feature_name = next(self.feature(eopatch... |
Extract the NDVI band from time-series
:param data: 4D array from which to compute the NDVI reference band
:type data: numpy array
:return: 3D array containing the NDVI reference band | def _get_reference_band(self, data):
""" Extract the NDVI band from time-series
:param data: 4D array from which to compute the NDVI reference band
:type data: numpy array
:return: 3D array containing the NDVI reference band
"""
nir = data[..., self.nir_idx].astype("floa... |
Extract the NDWI band from time-series
:param data: 4D array from which to compute the NDWI reference band
:type data: numpy array
:return: 3D array containing the NDWI reference band | def _get_reference_band(self, data):
""" Extract the NDWI band from time-series
:param data: 4D array from which to compute the NDWI reference band
:type data: numpy array
:return: 3D array containing the NDWI reference band
"""
nir = data[..., self.nir_idx].astype("floa... |
Extract the max-ratio band from time-series
The max-ratio is defined as max(NIR,SWIR1)/BLUE
:param data: 4D array from which to compute the max-ratio reference band
:type data: numpy array
:return: 3D array containing the max-ratio reference band | def _get_reference_band(self, data):
""" Extract the max-ratio band from time-series
The max-ratio is defined as max(NIR,SWIR1)/BLUE
:param data: 4D array from which to compute the max-ratio reference band
:type data: numpy array
:return: 3D array containing the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.