# svir.calculations package

## Submodules

## svir.calculations.aggregate_loss_by_zone module

`svir.calculations.aggregate_loss_by_zone.``add_zone_id_to_points`(points_layer, zonal_layer, zone_field_name)

`svir.calculations.aggregate_loss_by_zone.``calculate_zonal_stats`(callback, zonal_layer, points_layer, join_fields, output_layer_name, discard_nonmatching=False, predicates=('intersects', ), summaries=('sum', ))

  Leveraging the QGIS processing algorithm ‘Join attributes by location (summary)’, that is described in QGIS as follows: This algorithm takes an input vector layer and creates a new vector layer that is an extended version of the input one, with additional attributes in its attribute table. The additional attributes and their values are taken from a second vector layer. A spatial criteria is applied to select the values from the second layer that are added to each feature from the first layer in the resulting one. The algorithm calculates a statistical summary for the values from matching features in the second layer (e.g. maximum value, mean value, etc). The full description of the algorithm can be obtained as follows: processing.algorithmHelp(‘qgis:joinbylocationsummary’) and it includes the lists of predicates and summaries. The code of the algorithm is here: https://github.com/qgis/QGIS/blob /483b4ff977e3d36b166fac792254c31e89e3aeae/python/plugins/processing/algs /qgis/SpatialJoinSummary.py # NOQA

  Parameters: | callback – function to be called once the aggregation is complete, passing the output zonal layer as a parameter zonal_layer – vector layer containing polygons (or its path) points_layer – vector layer containing points (or its path) join_fields – fields for which we want to calculate statistics (e.g. structural) output_layer_name – a memory layer will be produced, named ‘memory:output_layer_name’ discard_nonmatching – discard records which could not be joined (in our case, purge zones that contain no loss/damage points) predicates – geometric predicates (default: ‘intersects’) summaries – statistics to be calculated for each join field (default: ‘sum’)
  Returns: | it waits until the task is complete or terminated, then it calls the callback function, passing the output QgsVectorLayer as parameter, or None in case of failure

`svir.calculations.aggregate_loss_by_zone.``task_finished`(context, callback, successful, results)

## svir.calculations.calculate_utils module

exception `svir.calculations.calculate_utils.``InvalidChild`

  Bases: `Exception`

exception `svir.calculations.calculate_utils.``InvalidFormula`

  Bases: `Exception`

exception `svir.calculations.calculate_utils.``InvalidNode`

  Bases: `Exception`

exception `svir.calculations.calculate_utils.``InvalidOperator`

  Bases: `Exception`

`svir.calculations.calculate_utils.``add_numeric_attribute`(proposed_attr_name, layer)

`svir.calculations.calculate_utils.``add_textual_attribute`(proposed_attr_name, layer)

`svir.calculations.calculate_utils.``calculate_composite_variable`(iface, layer, node)

  Calculate a composite variable (a tree node that has children) starting from the children’s values and inverters and using the operator defined for the node. While calculating a composite index, the tree can be modified. For instance, a theme that was not associated to any field in the layer, could be linked to a new field that is created before performing the calculation. For this reason, the function must return the modified tree, and the original tree needs to be modified accordingly. If the children of the node are not final leaves of the tree, the function will be called recursively to compute those children, before proceeding with the calculation of the node.

  Parameters: | iface – the iface, to be used to access the messageBar layer – the layer that contains the data to be used in the calculation and that will be modified adding new fields if needed node – the root node of the project definition’s sub-tree to be calculated
  Returns (added_attrs_ids, discarded_feats, node, any_change):
  | added_attrs_ids: the set of ids of the attributes added to the layer during the calculation discarded_feats: the set of DiscardedFeature that can’t contribute to the calculation, because of missing data or invalid data (e.g. when it’s impossible to calculate the geometric mean because it causes the calculation of the fractionary power of a negative value) node: the transformed (or unmodified) sub-tree any_change: True if the calculation caused any change in the subtree

`svir.calculations.calculate_utils.``calculate_node`(node, node_attr_name, node_attr_id, layer, discarded_feats)

`svir.calculations.calculate_utils.``get_node_attr_id_and_name`(node, layer)

  Get the field (id and name) to be re-used to store the results of the calculation, if possible. Otherwise, add a new field to the layer and return its id and name. Also return True if a new field was added, or False if an old field was re-used.

## svir.calculations.process_layer module

class `svir.calculations.process_layer.``ProcessLayer`(layer)

  Bases: `object`

  Set of utilities to manage a layer or compare layers.

  Parameters: | layer (QgsVectorLayer) – layer to be processed

  An example of usage:

      has_same_content = \
          ProcessLayer(a_layer).has_same_content_as(another_layer)

  `add_attributes`(attribute_list, simulate=False)

    Add attributes to the layer

    Parameters: | attribute_list (list of QgsField) – list of QgsField to add to the layer simulate – if True, fields will not be added, but their addition will be simulated in order to find out the field names that would be assigned after the original names are laundered
    Returns: | dict having as keys the elements of the list of attributes passed as input argument, and as values the actual names of the assigned attributes

  `count_vertices`()
    Inspired by “https://github.com/GeospatialEnablingTechnologies/
      GET-Qgis-plugins/blob/master/Vertices_Counter/ Vertices_Counter.py”

    Count the total number of vertices in the layer. In DEBUG mode, also print vertices count for each single feature

    Returns: | The total number of vertices in the layer

  `delete_attributes`(attribute_list)

    Delete attributes from the layer

    Parameters: | attribute_list (list of int (or list of str)) – list of ids of attributes to be removed from the layer (if a list of field names is given instead of a list of ids, then the corresponding indices are found and used)
    Returns: | true in case of success and false in case of failure

  `duplicate_in_memory`(new_name='', add_to_registry=False)

    Return a memory copy of the layer

    Parameters: | new_name (str) – The name of the copied layer. add_to_registry – if True, the new layer will be added to the QgsMapRegistry
    Type: | bool
    Returns: | An in-memory copy of a layer.
    Return type: | QgsMapLayer

  `find_attribute_id`(attribute_name)

    Get the id of the attribute called attribute_name :param attribute_name: name of the attribute :return: id of the attribute, or raise AttributeError exception if not found

  `has_same_content_as`(other_layer)

    Check if the layer has the same content as another layer

    Parameters: | other_layer (QgsVectorLayer) – layer to compare with

  `has_same_projection_as`(other_layer)

    Check if the layer uses the same projection as another layer

    Parameters: | other_layer (QgsVectorLayer) – layer to compare with
    Returns: | (bool, str): (True, msg) if the layers use the same coordinates, specifying the projection in the message (False, msg) if they use different projections, specifying the projections in the message

  `is_type_in`(type_list)

    Parameters: | type_list – we want to check if the type of the layer is included in this list
    Returns: | True if the layer is a VectorLayer and its type is in the list

  `pprint`(usage='gui')

    Pretty print the contents of the layer

    Parameters: | usage – it can be either ‘gui’ or ‘testing’, indicating if the output has to be written to the QGIS logging system (default) or to stderr as it is useful for testing

  `transform_attribute`(input_attr_name, algorithm_name, variant='', inverse=False, new_attr_name=None, new_attr_alias=None, simulate=False)

    Use one of the available transformation algorithms to transform an attribute of the layer, and add a new attribute with the transformed data, or overwrite the input attribute with the results

    Parameters: | input_attr_name – name of the attribute to be transformed algorithm_name – name of the transformation algorithm variant – name of the algorithm variant inverse – boolean indicating if the inverse transformation has to be performed new_attr_name – name of the target attribute that will store the results of the transformation (if it is equal to the input_attr_name, the attribute will be overwritten) new_attr_alias – alias of the target attribute that will store ther results of the transformation simulate – if True, the method will just simulate the creation of the target attribute and return the name that would be assigned to it
    Returns: | (actual_new_attr_name, invalid_input_values)

## svir.calculations.transformation_algs module

`svir.calculations.transformation_algs.``log10_`(input_values, variant_name='IGNORE ZEROS', inverse=False)

  Accept only input_values containing positive (or zero) values In case of zeros:

  - the variant IGNORE ZEROS produces NULL as output when any input is zero
  - the variant INCREMENT BY ONE IF ZEROS ARE FOUND increments all input data by 1

  Then use numpy.log10 function to perform the log10 transformation on the list of values

`svir.calculations.transformation_algs.``min_max`(input_values, variant_name=None, inverse=False)
  Direct:
    f(x_i) = \frac{x_i - \min(x)}{\max(x) - \min(x)}
  Inverse:
    f(x_i) = 1 - \frac{x_i - \min(x)}{\max(x) - \min(x)}

`svir.calculations.transformation_algs.``rank`(input_values, variant_name='AVERAGE', inverse=False)

  Assign ranks to data, dealing with ties appropriately.

  Parameters: | input_values – the list of numbers to rank variant_name – available variants are [AVERAGE, MIN, MAX, DENSE, ORDINAL] and they correspond to different strategies on how to cope with ties (default: AVERAGE) inverse – instead of giving the highest rank to the biggest input value, give the highest rank to the smallest input value
  Returns: | list of ranks corresponding to the input data
  Raises: | NotImplementedError if variant_name is not implemented

`svir.calculations.transformation_algs.``sigmoid`(input_values, variant_name='', inverse=False)
  Logistic sigmoid function:
    f(x) = \frac{1}{1 + e^{-x}}
  Inverse function:
    f(x) = \ln(\frac{x}{1-x})

`svir.calculations.transformation_algs.``simple_quadratic`(input_values, variant_name='INCREASING', inverse=False)

  Simple quadratic transformation (bottom = 0)

  quadratic(x_i) = \frac{(x_i - bottom)^2}{(\max(x) - bottom)^2} \Rightarrow simple\_quadratic(x_i) = \frac{x_i^2}{\max(x)^2}

  Inverse:
    For each output x, the final output will be 1 - x

`svir.calculations.transformation_algs.``transform`(features_dict, algorithm, variant_name='', inverse=False)

  Use the chosen algorithm (and optional variant and/or inversion) on the input dict, and return a dict containing the transformed values with the original ids and the list of invalid input values (or None)

  Parameters: | features_dict – dictionary containing the features to transform algorithm – the function to be used to transform the data variant_name – the (optional) variant to be used inverse – a boolean (default False) to run the inverse function if available
  Returns: | (transformed_dict, invalid_input_values)

`svir.calculations.transformation_algs.``z_score`(input_values, variant_name=None, inverse=False)
  Direct:
    f(x_i) = \frac{x_i - \mu_x}{\sigma_x}
  Inverse:
    Multiply each input by -1, before doing exactly the same

## Module contents