# svir.utilities package

## Submodules

## svir.utilities.defaults module

SAFE (Scenario Assessment For Emergencies) - API

The purpose of the module is to provide a well defined public API for the packages that constitute the SAFE engine. Modules using SAFE should only need to import functions from here.

Contact : ole.moller.nielsen@gmail.com

Note

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

`svir.utilities.defaults.``get_defaults`(default=None)

  Get defaults for aggregation / post processing.

  Parameters: | default (str) – Optional parameter if you only want a specific default.
  Returns: | A single value (when default is passed) or a dict of values.
  Return type: | str, int, float, dict

## svir.utilities.import_sv_data module

class `svir.utilities.import_sv_data.``SvDownloader`(host)

  Bases: `object`

  Utility to use the OpenQuake Platform’s API to download socioeconomic data.

  Parameters: | host – url of the OpenQuake Platform instance to use

  `get_countries_info`()

    Get information about countries for which socioeconomic data is available in the OpenQuake Platform’s database

    Returns: | a dictionary iso -> name

  `get_indicators_info`(name_filter=None, keywords=None, theme=None, subtheme=None)

    Get information about indicators that comply with the provided filtering parameters

    Parameters: | name_filter – indicator name (or part of it) keywords – comma-separated keywords theme – socioeconomic theme
    Subtheme: | socioeconomic subtheme
    Returns: | a dictionary code -> name, theme, subtheme, description, measurement_type, source, aggregation_method, keywords_str

  `get_subthemes_by_theme`(theme)

    Get the list of subthemes of a given socioeconomic theme

    Parameters: | theme – a socioeconomic theme
    Returns: | list of subthemes

  `get_sv_data`(sv_variables_ids, load_geometries, country_iso_codes, message_bar)

    Get a csv file containing data corresponding to the social vulnerability variables which ids are given in input If country iso codes are also provided, only the corresponding data will be exported

    Parameters: | sv_variables_ids – a string of comma-separated ids of social vulnerability variables country_iso_codes – a string of comma-separated country iso codes (optional - default: all countries) export_geometries – ‘True’ or ‘False’, indicating if also the geometries of countries have to be exported (optional - default: ‘False’)

  `get_themes`()

    Get the list of socioeconomic themes

    Returns: | list of themes

  `login`(username, password)

`svir.utilities.import_sv_data.``get_loggedin_downloader`(message_bar)

  Attempt to login to the OpenQuake Platform

  Parameters: | message_bar – needed to display messages
  Returns: | a `svir.utilities.SvDownloader` instance

## svir.utilities.shared module

class `svir.utilities.shared.``DiscardedFeature`(feature_id, reason)

  Bases: `object`

  Class storing information about a discarded feature

  Parameters: | feature_id – unique feature identifier reason – indicating if the feature is being discarded because of a missing value or an invalid value

  `valid_reasons` = ('Missing value', 'Invalid value')

## svir.utilities.sldadapter module

`svir.utilities.sldadapter.``adaptGsToQgs`(sld)

`svir.utilities.sldadapter.``adaptQgsToGs`(sld, layer)

`svir.utilities.sldadapter.``createCssParameterElement`(document, name, value)

`svir.utilities.sldadapter.``createFunctionElement`(document, element, function)

`svir.utilities.sldadapter.``createGeometryElement`(document, element, geomFunc)

`svir.utilities.sldadapter.``create_displacement_element`(document, element, offset)

`svir.utilities.sldadapter.``encodeSldUom`(outputUnit, scaleFactor)

`svir.utilities.sldadapter.``fill_to_sld`(symbolLayer, document, element, brushStyle, color)

`svir.utilities.sldadapter.``getGeomTypeFromSld`(sld)

`svir.utilities.sldadapter.``getGsCompatibleSld`(layer, style_name)

`svir.utilities.sldadapter.``getLabelingAsSld`(layer)

`svir.utilities.sldadapter.``getStyleAsSld`(layer, styleName)

`svir.utilities.sldadapter.``line_to_sld`(document, element, penStyle, color, width, penJoinStyle, customDashPattern, dashOffset)

`svir.utilities.sldadapter.``rule_to_sld`(rule, document, element, props)

`svir.utilities.sldadapter.``symbolLayer_to_sld`(symbolLayer, document, element, props)

`svir.utilities.sldadapter.``symbolv2_to_sld`(symbol, document, element, props)

## svir.utilities.utils module

exception `svir.utilities.utils.``InvalidHeaderError`

  Bases: `Exception`

exception `svir.utilities.utils.``ReadMetadataError`

  Bases: `Exception`

  When a metadata xml is not correctly formatted can’t be read

  `suggestion` = 'Check that the file is correct'

exception `svir.utilities.utils.``RedirectionError`

  Bases: `Exception`

class `svir.utilities.utils.``Register`

  Bases: `collections.OrderedDict`

  Useful to keep (in a single point) a register of available variants of something, e.g. a set of different transformation algorithms

  `add`(tag)

    Add a new variant to the OrderedDict For instance, if we add a class implementing a specific transformation algorithm, the register will keep track of a new item having as key the name of the algorithm and as value the class implementing the algorithm

exception `svir.utilities.utils.``ServerError`

  Bases: `Exception`

exception `svir.utilities.utils.``SvNetworkError`

  Bases: `Exception`

class `svir.utilities.utils.``TraceTimeManager`(message, debug=False)

  Bases: `object`

  Wrapper to check how much time is needed to complete a block of code

  Parameters: | message – message describing the task to be monitored debug – if False, nothing will be done. Otherwise, times will be measured and logged

exception `svir.utilities.utils.``UserAbortedNotification`

  Bases: `Exception`

class `svir.utilities.utils.``WaitCursorManager`(msg=None, message_bar=None)

  Bases: `object`

  Wrapper to be used for a time-consuming block of code, that changes the mouse cursor and adds an info message to the messageBar

`svir.utilities.utils.``ask_for_destination_full_path_name`(parent, text='Save File', filter='Shapefiles (*.shp)')

  Open a dialog to ask for a destination full path name, initially pointing to the home directory. QFileDialog by defaults asks for confirmation if an existing file is selected and it automatically resolves symlinks.

  Parameters: | parent – the parent dialog text – the dialog’s title text filter – filter files by specific formats. Default: ‘Shapefiles (*.shp)’ A more elaborate example: “Images (*.png *.xpm *.jpg);; Text files (*.txt);;XML files (*.xml)”
  Returns: | full path name of the destination file

`svir.utilities.utils.``ask_for_download_destination_folder`(parent, text='Download destination')

  Open a dialog to ask for a download destination folder, initially pointing to the home directory.

  Parameters: | parent – the parent dialog text – the dialog’s title text
  Returns: | full path of the destination folder

`svir.utilities.utils.``assign_default_weights`(svi_themes)

  Count themes and indicators and assign default weights using 2 decimal points (%.2f)

  Parameters: | svi_themes – list of nodes corresponding to socioeconomic themes

`svir.utilities.utils.``check_is_lockdown`(hostname, session)

`svir.utilities.utils.``clear_progress_message_bar`(msg_bar, msg_bar_item=None)

  Clear the progress message bar

`svir.utilities.utils.``clear_widgets_from_layout`(layout)

  Recursively remove all widgets from the layout, except from nested layouts. If any of such widgets is a layout, then clear its widgets instead of deleting it.

`svir.utilities.utils.``confirm_overwrite`(parent, files)

  Open a dialog to ask for user’s confirmation on file overwriting

`svir.utilities.utils.``confirmation_on_close`(parent, event=None)

  Open a QMessageBox to confirm closing a dialog discarding changes

  Parameters: | parent – the parent dialog that is being closed event – event that triggered this dialog (e.g. reject or closeEvent)

`svir.utilities.utils.``convert_bytes`(num)

  this function will convert bytes to MB.... GB... etc

`svir.utilities.utils.``count_heading_commented_lines`(fname)

  count top lines in the file starting with ‘#’

`svir.utilities.utils.``create_progress_message_bar`(msg_bar, msg, no_percentage=False)

  Use the messageBar of QGIS to display a message describing what’s going on (typically during a time-consuming task), and a bar showing the progress of the process.

  Parameters: | msg – Message to be displayed, describing the current task
  Type: | str
  Returns: | progress object on which we can set the percentage of completion of the task through progress.setValue(percentage)
  Return type: | QProgressBar

`svir.utilities.utils.``engine_login`(host, username, password, session)

  Logs in a session to a engine server

  Parameters: | host (str) – The host url username (str) – The username password (str) – The password session (Session) – The session to be autenticated

`svir.utilities.utils.``extract_npz`(session, hostname, calc_id, output_type, message_bar, params=None)

`svir.utilities.utils.``files_exist_in_destination`(destination, file_names)

  Check if any of the provided file names exist in the destination folder

  Parameters: | destination – destination folder file_names – list of file names
  Returns: | list of file names that already exist in the destination folder

`svir.utilities.utils.``get_checksum`(file_path)

`svir.utilities.utils.``get_credentials`(server)

  Get from the QSettings the credentials to access the OpenQuake Engine or the OpenQuake Platform. If those settings are not found, use defaults instead.

  Parameters: | server – it can be either ‘platform’ or ‘engine’
  Returns: | tuple (hostname, username, password)

`svir.utilities.utils.``get_field_names`(sub_tree, field_names=None)

  Return a list of all the field names defined in the project definition

  Sub_tree: | root of the subtree for which we want to collect field names
  Parameters: | field_names – an accumulator that is extended browsing the tree recursively (if None, a list will be created) and collecting the field names
  Returns: | the accumulator

`svir.utilities.utils.``get_file_size`(file_path)

  this function will return the file size

`svir.utilities.utils.``get_headers`(fname, sep=', ')

`svir.utilities.utils.``get_irmt_version`()

  Get the plugin’s version from metadata.txt

`svir.utilities.utils.``get_layer_setting`(layer, setting)

`svir.utilities.utils.``get_loss_types`(session, hostname, calc_id, message_bar)

`svir.utilities.utils.``get_node`(sub_tree, name)

  Browse the tree (recursively searching each node’s children), looking for a node with a specific name.

  Parameters: | sub_tree – root of the subtree through which we want to search name – name of the node to be searched
  Returns: | the node, if found, otherwise None

`svir.utilities.utils.``get_params_from_comment_line`(comment_line)

  Parameters: | commented_line – a line starting with “# “
  Returns: | an OrderedDict with parameter -> value

      >>> get_params_from_comment_line('# investigation_time=1000.0')
      OrderedDict([('investigation_time', '1000.0')])

      >>> get_params_from_comment_line("# p1=10, p2=20")
      OrderedDict([('p1', '10'), ('p2', '20')])

      >>> get_params_from_comment_line('h1, h2, h3')
      Traceback (most recent call last):
          ...
      svir.utilities.utils.InvalidHeaderError: Unable to extract parameters from line:
      h1, h2, h3
      because the line does not start with "# "

      >>> get_params_from_comment_line("# p1=10,p2=20")
      Traceback (most recent call last):
          ...
      svir.utilities.utils.InvalidHeaderError: Unable to extract parameters from line:
      # p1=10,p2=20

`svir.utilities.utils.``get_style`(layer, message_bar, restore_defaults=False)

`svir.utilities.utils.``get_ui_class`(ui_file)
  Get UI Python class from .ui file.
    Can be filename.ui or subdirectory/filename.ui

  Parameters: | ui_file (str) – The file of the ui in svir.ui

`svir.utilities.utils.``import_layer_from_csv`(parent, csv_path, layer_name, iface, longitude_field='lon', latitude_field='lat', delimiter=', ', quote='"', lines_to_skip_count=0, wkt_field=None, save_as_shp=False, dest_shp=None, zoom_to_layer=True, has_geom=True, subset=None, add_to_legend=True, add_on_top=False)

`svir.utilities.utils.``insert_platform_layer_id`(layer_url, active_layer_id, supplemental_information)

  Insert the platform layer id into the supplemental information

  Parameters: | layer_url – url of the OpenQuake Platform layer active_layer_id – id of the QGIS layer that is currently selected supplemental_information – the supplemental information

`svir.utilities.utils.``listdir_fullpath`(path)

`svir.utilities.utils.``log_msg`(message, tag='GEM OpenQuake IRMT plugin', level='I', message_bar=None, duration=None, exception=None, print_to_stderr=False)

  Add a message to the QGIS message log. If a messageBar is provided, the same message will be displayed also in the messageBar. In the latter case, warnings and critical messages will have no timeout, whereas info messages will have a duration of 5 seconds.

  Parameters: | message – the message tag – the log topic level – the importance level ‘I’ -> Qgis.Info, ‘W’ -> Qgis.Warning, ‘C’ -> Qgis.Critical, ‘S’ -> Qgis.Success, message_bar – a QgsMessageBar instance duration – how long (in seconds) the message will be displayed (use 0 to keep the message visible indefinitely, or None to use the default duration of the chosen level exception – an optional exception, from which the traceback will be extracted and written in the log. When the exception is provided, an additional button in the QgsMessageBar allows to visualize the traceback in a separate window.
  Print_to_stderr:
  | if True, the error message will be printed also to stderr

`svir.utilities.utils.``platform_login`(host, username, password, session)

  Logs in a session to a platform

  Parameters: | host (str) – The host url username (str) – The username password (str) – The password session (Session) – The session to be autenticated

`svir.utilities.utils.``read_layer_suppl_info_from_qgs`(layer_id, supplemental_information)

  Read from the QgsProject the supplemental information associated to the given layer

  Parameters: | layer_id – the layer id for which we want to retrieve the supplemental information supplemental_information – the supplemental information to be updated
  Returns: | a tuple, with the returned supplemental information and a boolean indicating if such property is available

`svir.utilities.utils.``reload_attrib_cbx`(combo, layer, prepend_empty_item=False, *valid_field_types)

  Load attributes of a layer into a combobox. Can filter by field data type. the optional filter can be NUMERIC_FIELD_TYPES, TEXTUAL_FIELD_TYPES, ... if no filter is specified all fields are returned

  Parameters: | combo (QComboBox) – The combobox to be repopulated layer (Bool) – The QgsVectorLayer from where the fields are read prepend_empty_item – if to prepend an empty item to the combo *valid_field_types (tuple, tuple, ...) – multiple tuples containing types

`svir.utilities.utils.``reload_layers_in_cbx`(combo, layer_types=None, skip_layer_ids=None)

  Load layers into a combobox. Can filter by layer type. the additional filter can be QgsMapLayer.VectorLayer, ...

  Parameters: | combo (QComboBox) – The combobox to be repopulated layer_types ([QgsMapLayer.LayerType, ...]) – list containing types or None if all type accepted skip_layer_ids ([QgsMapLayer ...]) – list containing layers to be skipped in the combobox or None if all layers accepted

`svir.utilities.utils.``replace_fields`(sub_tree_root, before, after)

  Recursively search the project definition for ‘field’s equal to the string before and replace the value with the string after. It is useful, e.g., when we transform a field that is tracked by the project definition, and we obtain a new field that we want to track instead of the original one. It works by side-effect, modifying the passed project definition.

  Parameters: | sub_tree_root – node of a project definition. From that node (used as root) towards the leaves of the tree, the function will recursively search for nodes with a ‘field’ property that contains the string before before – string to be replaced after – new value for the replaced string

`svir.utilities.utils.``save_layer_as_shapefile`(orig_layer, dest_path, crs=None)

`svir.utilities.utils.``save_layer_setting`(layer, setting, value)

`svir.utilities.utils.``set_operator`(sub_tree, operator)

  if the root of the sub_tree has children, set the operator to be used to combine the children. If any of the children have children, set also their operators to the same one applied to the root.

  Parameters: | sub_tree – root of the subtree to which we want to set the operator operator – the operator to be applied
  Returns: | the modified subtree

`svir.utilities.utils.``toggle_select_features`(layer, use_new, new_feature_ids, old_feature_ids)

  Toggles feature selection between two sets.

  Parameters: | layer (QgsVectorLayer) – The QgsVectorLayer where the selection is applied use_new (bool) – which list to select new_feature_ids (QgsFeatureIds) – The list to select if use_new is true old_feature_ids (QgsFeatureIds) – The list to select if use_new is false

`svir.utilities.utils.``toggle_select_features_widget`(title, text, button_text, layer, new_feature_ids, old_feature_ids)

  Create a widget for QgsMessageBar to switch between two sets.

  Parameters: | title (str) – The title text (str) – The text message button_text (str) – The text on the toggle button layer (QgsVectorLayer) – The QgsVectorLayer where the selection is applied new_feature_ids (QgsFeatureIds) – The list to select if use_new is true old_feature_ids (QgsFeatureIds) – The list to select if use_new is false
  Returns: | the widget

`svir.utilities.utils.``tr`(message)

  Leverage QApplication.translate to translate a message

  Parameters: | message – the message to be translated
  Returns: | the return value of QApplication.translate(‘Irmt’, message)

`svir.utilities.utils.``update_platform_project`(host, session, project_definition, platform_layer_id)

  Add a project definition to one of the available projects on the OpenQuake Platform

  Parameters: | host – url of the OpenQuake Platform server session – authenticated session to be used project_definition – the project definition to be added platform_layer_id – the id of the platform layer to be updated
  Returns: | the server’s response

`svir.utilities.utils.``warn_missing_package`(package_name, message_bar=None)

`svir.utilities.utils.``write_layer_suppl_info_to_qgs`(layer_id, suppl_info)

  Write into the QgsProject the given supplemental information, associating it with the given layer id.

  Parameters: | layer_id – id of the layer for which we want to update the corresponding supplemental_information suppl_info – the supplemental information

## Module contents