INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
The content - disposition of the attachment specifying display style. | def disposition(self, value):
"""The content-disposition of the attachment, specifying display style.
Specifies how you would like the attachment to be displayed.
- "inline" results in the attached file being displayed automatically
within the message.
- "attachment" resul... |
The content id for the attachment. | def content_id(self, value):
"""The content id for the attachment.
This is used when the disposition is set to "inline" and the attachment
is an image, allowing the file to be displayed within the email body.
:param content_id: The content id for the attachment.
... |
Get a JSON - ready representation of this Attachment. | def get(self):
"""
Get a JSON-ready representation of this Attachment.
:returns: This Attachment, ready for use in a request body.
:rtype: dict
"""
attachment = {}
if self.file_content is not None:
attachment["content"] = self.file_content.get()
... |
Execute computation of blobs on input eopatch | def execute(self, eopatch):
""" Execute computation of blobs on input eopatch
:param eopatch: Input eopatch
:type eopatch: eolearn.core.EOPatch
:return: EOPatch instance with new key holding the blob image.
:rtype: eolearn.core.EOPatch
"""
for feature_type, featu... |
Check if the classifier implements predict and predict_proba methods. | def _check_classifier(classifier):
"""
Check if the classifier implements predict and predict_proba methods.
"""
predict = getattr(classifier, "predict", None)
if not callable(predict):
raise ValueError('Classifier does not have predict method!')
pred... |
Checks the image size and its compatibility with classifier s receptive field. At this moment it is required that image size = K * receptive_field. This will be relaxed in future with the introduction of padding. | def _check_image(self, X):
"""
Checks the image size and its compatibility with classifier's receptive field.
At this moment it is required that image size = K * receptive_field. This will
be relaxed in future with the introduction of padding.
"""
if (len(X.shap... |
Predicts class label for the entire image. Parameters: ----------- X: array shape = [ n_samples n_pixels_y n_pixels_x n_bands ] Array of training images y: array shape = [ n_samples ] or [ n_samples n_pixels_y n_pixels_x ] Target labels or masks. | def image_predict(self, X):
"""
Predicts class label for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_y, n_pixels_x, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n_pixels_y, n_p... |
Predicts class probabilities for the entire image. Parameters: ----------- X: array shape = [ n_samples n_pixels_x n_pixels_y n_bands ] Array of training images y: array shape = [ n_samples ] or [ n_samples n_pixels_x n_pixels_y n_classes ] Target probabilities | def image_predict_proba(self, X):
"""
Predicts class probabilities for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n... |
Reshapes input to patches of the size of classifier s receptive field. For example: input X shape: [ n_samples n_pixels_y n_pixels_x n_bands ] output: [ n_samples * n_pixels_y/ receptive_field_y * n_pixels_x/ receptive_field_x receptive_field_y receptive_field_x n_bands ] | def _to_patches(self, X):
"""
Reshapes input to patches of the size of classifier's receptive field.
For example:
input X shape: [n_samples, n_pixels_y, n_pixels_x, n_bands]
output: [n_samples * n_pixels_y/receptive_field_y * n_pixels_x/receptive_field_x,
... |
Predicts class label for the entire image. Parameters: ----------- X: array shape = [ n_samples n_pixels_y n_pixels_x n_bands ] Array of training images y: array shape = [ n_samples ] or [ n_samples n_pixels_y n_pixels_x ] Target labels or masks. | def image_predict(self, X):
"""
Predicts class label for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_y, n_pixels_x, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n_pixels_y, n_p... |
Predicts class probabilities for the entire image. Parameters: ----------- X: array shape = [ n_samples n_pixels_x n_pixels_y n_bands ] Array of training images y: array shape = [ n_samples ] or [ n_samples n_pixels_x n_pixels_y n_classes ] Target probabilities | def image_predict_proba(self, X):
"""
Predicts class probabilities for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n... |
Reshapes input to patches of the size of classifier s receptive field. For example: input X shape: [ n_samples n_pixels_y n_pixels_x n_bands ] output: [ n_samples * n_pixels_y/ receptive_field_y * n_pixels_x/ receptive_field_x receptive_field_y receptive_field_x n_bands ] | def _to_patches(self, X):
"""
Reshapes input to patches of the size of classifier's receptive field.
For example:
input X shape: [n_samples, n_pixels_y, n_pixels_x, n_bands]
output: [n_samples * n_pixels_y/receptive_field_y * n_pixels_x/receptive_field_x,
... |
Predicts class label for the entire image. Parameters: ----------- X: array shape = [ n_samples n_pixels_y n_pixels_x n_bands ] Array of training images y: array shape = [ n_samples ] or [ n_samples n_pixels_y n_pixels_x ] Target labels or masks. | def image_predict(self, X):
"""
Predicts class label for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_y, n_pixels_x, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n_pixels_y, n_p... |
Predicts class probabilities for the entire image. Parameters: ----------- X: array shape = [ n_samples n_pixels_x n_pixels_y n_bands ] Array of training images y: array shape = [ n_samples ] or [ n_samples n_pixels_x n_pixels_y n_classes ] Target probabilities | def image_predict_proba(self, X):
"""
Predicts class probabilities for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n... |
Transforms [ n w h d ] eopatch into a [ n w h 1 ] eopatch adding it the classification mask.: param eopatch: An input EOPatch: type eopatch: EOPatch: return: Outputs EOPatch with n classification masks appended to out_feature_type with out_feature_name key: rtype: EOPatch | def execute(self, eopatch):
""" Transforms [n, w, h, d] eopatch into a [n, w, h, 1] eopatch, adding it the classification mask.
:param eopatch: An input EOPatch
:type eopatch: EOPatch
:return: Outputs EOPatch with n classification masks appended to out_feature_type with... |
Parses execution arguments provided by user and raises an error if something is wrong | def _parse_execution_args(execution_args):
""" Parses execution arguments provided by user and raises an error if something is wrong
"""
if not isinstance(execution_args, (list, tuple)):
raise ValueError("Parameter 'execution_args' should be a list")
return [EOWorkflow.parse... |
Runs the executor with n workers. | def run(self, workers=1):
""" Runs the executor with n workers.
:param workers: Number of parallel processes used in the execution. Default is a single process. If set to
`None` the number of workers will be the number of processors of the system.
:type workers: int or None
... |
Handles a single execution of a workflow | def _execute_workflow(cls, process_args):
""" Handles a single execution of a workflow
"""
workflow, input_args, log_path = process_args
if log_path:
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
handler = cls._get_log_handler(log_path)
... |
Makes a html report and saves it into the same folder where logs are stored. | def make_report(self):
""" Makes a html report and saves it into the same folder where logs are stored.
"""
if self.execution_stats is None:
raise RuntimeError('Cannot produce a report without running the executor first, check EOExecutor.run '
'method')... |
Action to be taken when an event is triggered. Event is scroll of the mouse s wheel. This leads to changing the temporal frame displayed.: param event: Scroll of mouse wheel | def onscroll(self, event):
"""Action to be taken when an event is triggered.
Event is scroll of the mouse's wheel. This leads to changing the temporal frame displayed.
:param event: Scroll of mouse wheel
"""
if event.button == 'up':
self.ind = (self.ind + 1)... |
Updates image to be displayed with new time frame. | def update(self):
"""Updates image to be displayed with new time frame."""
if self.single_channel:
self.im.set_data(self.data[self.ind, :, :])
else:
self.im.set_data(self.data[self.ind, :, :, :])
self.ax.set_ylabel('time frame %s' % self.ind)
self.i... |
Performs checks on dimensionality of data to makes it suitable for display.: param eopatch: Input eopatch: return: Array to display and whether it is single channel or not | def _get_data_to_display(self, eopatch):
"""Performs checks on dimensionality of data to makes it suitable for display.
:param eopatch: Input eopatch
:return: Array to display and whether it is single channel or not
"""
feature_type, feature_name = next(self.feature(eopatc... |
Shows data and scrolls through. Currently not working from Jupyter notebooks.: param eopatch: Image sequence to display. Can be single channel RGB or multi - channel. If multi - channel indices must be specified.: type eopatch: numpy array: param title: String to be displayed as title of the plot: type title: string: p... | def execute(self, eopatch, title=None, colorbar=False):
"""Shows data and scrolls through. Currently not working from Jupyter notebooks.
:param eopatch: Image sequence to display. Can be single channel, RGB or multi-channel. If multi-channel,
indices must be specified.
... |
Compute spatio - temporal features for input eopatch | def execute(self, eopatch):
""" Compute spatio-temporal features for input eopatch
:param eopatch: Input eopatch
:return: eopatch with computed spatio-temporal features
"""
# pylint: disable=invalid-name
amax_ndvi, amin_ndvi = eopatch.data_timeless[self.argmax_ndvi], eop... |
Compute argmax/ argmin of specified data_feature and data_index | def execute(self, eopatch):
""" Compute argmax/argmin of specified `data_feature` and `data_index`
:param eopatch: Input eopatch
:return: eopatch with added argmax/argmin features
"""
if self.mask_data:
valid_data_mask = eopatch.mask['VALID_DATA']
else:
... |
Computation of NDVI slope using finite central differences | def execute(self, eopatch):
""" Computation of NDVI slope using finite central differences
This implementation loops through every spatial location, considers the valid NDVI values and approximates their
first order derivative using central differences. The argument of min and max is added to t... |
Returns WMS request. | def _get_wms_request(self, bbox, size_x, size_y):
"""
Returns WMS request.
"""
bbox_3857 = transform_bbox(bbox, CRS.POP_WEB)
return GeopediaWmsRequest(layer=self.layer,
theme=self.theme,
bbox=bbox_3857,
... |
Reprojects the raster data from Geopedia s CRS ( POP_WEB ) to EOPatch s CRS. | def _reproject(self, eopatch, src_raster):
"""
Reprojects the raster data from Geopedia's CRS (POP_WEB) to EOPatch's CRS.
"""
height, width = src_raster.shape
dst_raster = np.ones((height, width), dtype=self.raster_dtype)
src_bbox = transform_bbox(eopatch.bbox, CRS.POP_... |
Each request represents a binary class which will be mapped to the scalar raster_value | def _map_from_binaries(self, eopatch, dst_shape, request_data):
"""
Each request represents a binary class which will be mapped to the scalar `raster_value`
"""
if self.feature_name in eopatch[self.feature_type]:
raster = eopatch[self.feature_type][self.feature_name].squeeze(... |
raster_value is a dictionary specifying the intensity values for each class and the corresponding label value. | def _map_from_multiclass(self, eopatch, dst_shape, request_data):
"""
`raster_value` is a dictionary specifying the intensity values for each class and the corresponding label value.
A dictionary example for GLC30 LULC mapping is:
raster_value = {'no_data': (0,[0,0,0,0]),
... |
Add requested feature to this existing EOPatch. | def execute(self, eopatch):
"""
Add requested feature to this existing EOPatch.
"""
data_arr = eopatch[FeatureType.MASK]['IS_DATA']
_, height, width, _ = data_arr.shape
request = self._get_wms_request(eopatch.bbox, width, height)
request_data, = np.asarray(reque... |
Collects the parameter either from initialization parameters or from EOPatch | def _get_parameter(self, name, eopatch):
""" Collects the parameter either from initialization parameters or from EOPatch
"""
if hasattr(self, name) and getattr(self, name) is not None:
return getattr(self, name)
if name == 'bbox' and eopatch.bbox:
return eopatch.... |
Collects all parameters used for DataRequest each one is taken either from initialization parameters or from EOPatch | def _prepare_request_data(self, eopatch, bbox, time_interval):
""" Collects all parameters used for DataRequest, each one is taken either from initialization parameters or
from EOPatch
"""
service_type = ServiceType(self._get_parameter('service_type', eopatch))
if time_interval ... |
Adds downloaded data to EOPatch | def _add_data(self, eopatch, data):
""" Adds downloaded data to EOPatch """
valid_mask = data[..., -1]
data = data[..., :-1]
if data.ndim == 3:
data = data.reshape(data.shape + (1,))
if not self.feature_type.is_time_dependent():
if data.shape[0] > 1:
... |
Adds any missing metadata info to EOPatch | def _add_meta_info(self, eopatch, request_params, service_type):
""" Adds any missing metadata info to EOPatch """
for param, eoparam in zip(['time', 'time_difference', 'maxcc'], ['time_interval', 'time_difference', 'maxcc']):
if eoparam not in eopatch.meta_info:
eopatch.met... |
Creates OGC ( WMS or WCS ) request downloads requested data and stores it together with valid data mask in newly created EOPatch. Returns the EOPatch. | def execute(self, eopatch=None, bbox=None, time_interval=None):
"""
Creates OGC (WMS or WCS) request, downloads requested data and stores it together
with valid data mask in newly created EOPatch. Returns the EOPatch.
:param eopatch:
:type eopatch: EOPatch or None
:param... |
Wrapper function for pixel - based S2 cloud detector S2PixelCloudDetector | def get_s2_pixel_cloud_detector(threshold=0.4, average_over=4, dilation_size=2, all_bands=True):
""" Wrapper function for pixel-based S2 cloud detector `S2PixelCloudDetector`
"""
return S2PixelCloudDetector(threshold=threshold,
average_over=average_over,
... |
Returns WMS request. | def _get_wms_request(self, bbox, time_interval, size_x, size_y, maxcc, time_difference, custom_url_params):
"""
Returns WMS request.
"""
return WmsRequest(layer=self.data_feature,
bbox=bbox,
time=time_interval,
... |
Returns WCS request. | def _get_wcs_request(self, bbox, time_interval, size_x, size_y, maxcc, time_difference, custom_url_params):
"""
Returns WCS request.
"""
return WcsRequest(layer=self.data_feature,
bbox=bbox,
time=time_interval,
... |
Compute the resampling factor for height and width of the input array | def _get_rescale_factors(self, reference_shape, meta_info):
""" Compute the resampling factor for height and width of the input array
:param reference_shape: Tuple specifying height and width in pixels of high-resolution array
:type reference_shape: tuple of ints
:param meta_info: Meta-... |
Downscale existing array to resolution requested by cloud detector | def _downscaling(self, hr_array, meta_info, interp='linear', smooth=True):
""" Downscale existing array to resolution requested by cloud detector
:param hr_array: High-resolution data array to be downscaled
:param meta_info: Meta-info of eopatch
:param interp: Interpolation method to be... |
Upsample the low - resolution array to the original high - resolution grid | def _upsampling(lr_array, rescale, reference_shape, interp='linear'):
""" Upsample the low-resolution array to the original high-resolution grid
:param lr_array: Low-resolution array to be upsampled
:param rescale: Rescale factor for rows/columns
:param reference_shape: Original size of... |
Make OGC request to create input for cloud detector classifier | def _make_request(self, bbox, meta_info, timestamps):
""" Make OGC request to create input for cloud detector classifier
:param bbox: Bounding box
:param meta_info: Meta-info dictionary of input eopatch
:return: Requested data
"""
service_type = ServiceType(meta_info['se... |
Add cloud binary mask and ( optionally ) cloud probability map to input eopatch | def execute(self, eopatch):
""" Add cloud binary mask and (optionally) cloud probability map to input eopatch
:param eopatch: Input `EOPatch` instance
:return: `EOPatch` with additional cloud maps
"""
# Downsample or make request
if not eopatch.data:
raise Va... |
Handles measuring execution time and error propagation | def _execute_handling(self, *eopatches, **kwargs):
""" Handles measuring execution time and error propagation
"""
self.private_task_config.start_time = datetime.datetime.now()
caught_exception = None
try:
return_value = self.execute(*eopatches, **kwargs)
... |
See eolearn. core. utilities. FeatureParser class. | def _parse_features(features, new_names=False, rename_function=None, default_feature_type=None,
allowed_feature_types=None):
""" See eolearn.core.utilities.FeatureParser class.
"""
return FeatureParser(features, new_names=new_names, rename_function=rename_function,
... |
Function which will process README. md file and divide it into INTRO. md and INSTALL. md which will be used in documentation | def process_readme():
""" Function which will process README.md file and divide it into INTRO.md and INSTALL.md, which will be used in
documentation
"""
with open('../../README.md', 'r') as file:
readme = file.read()
readme = readme.replace('# eo-learn', '# Introduction').replace('docs/sour... |
Return indices of timestamps from source that are also found in target.: param source: timestamps from source: type source: list of datetime objects: param target: timestamps from target: type target: list of datetime objects: return: indices of timestamps from source that are also found in target: rtype: list of ints | def get_common_timestamps(source, target):
"""Return indices of timestamps from source that are also found in target.
:param source: timestamps from source
:type source: list of datetime objects
:param target: timestamps from target
:type target: list of datetime objects
:return: indices... |
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 - wise. When t... | 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: np. array | 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 of shape ( rows... | 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 ): raises: ValueError | 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: rtype: list ( Dependency ) | 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: return: A list of topologically orde... | 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... |
Factory method for creating linear workflows.: param tasks: EOTask s t1 t2... tk with dependencies t1 - > t2 - >... - > tk: param kwargs: Optional keyword arguments ( such as workflow name ) forwarded to the constructor: return: A new EO workflow instance: rtype: EOWorkflow | def make_linear_workflow(*tasks, **kwargs):
"""Factory method for creating linear workflows.
:param tasks: EOTask's t1,t2,...,tk with dependencies t1->t2->...->tk
:param kwargs: Optional keyword arguments (such as workflow name) forwarded to the constructor
:return: A new EO workfl... |
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 tuple ( object )): param monitor... | 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 depend on this task. ): type out_deg... | 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 all tasks that the current task depends on.: typ... | 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 from disk.: param dependency: A workflow ... | 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 graph with some more formatting: rtype: Digraph | 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 | 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 | 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) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.