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)[source]

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)[source]

Bases: object

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

Parameters:host – url of the OpenQuake Platform instance to use
get_countries_info()[source]

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)[source]

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)[source]

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)[source]

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()[source]

Get the list of socioeconomic themes

Returns:list of themes
login(username, password)[source]
svir.utilities.import_sv_data.get_loggedin_downloader(iface)[source]

Attempt to login to the OpenQuake Platform

Parameters:iface – needed to get the credentials and to use the messageBar
Returns:a svir.utilities.SvDownloader instance

svir.utilities.shared module

class svir.utilities.shared.DiscardedFeature(feature_id, reason)[source]

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)[source]
svir.utilities.sldadapter.adaptQgsToGs(sld, layer)[source]
svir.utilities.sldadapter.createCssParameterElement(document, name, value)[source]
svir.utilities.sldadapter.createFunctionElement(document, element, function)[source]
svir.utilities.sldadapter.createGeometryElement(document, element, geomFunc)[source]
svir.utilities.sldadapter.create_displacement_element(document, element, offset)[source]
svir.utilities.sldadapter.encodeSldUom(outputUnit, scaleFactor)[source]
svir.utilities.sldadapter.fill_to_sld(symbolLayer, document, element, brushStyle, color)[source]
svir.utilities.sldadapter.getGeomTypeFromSld(sld)[source]
svir.utilities.sldadapter.getGsCompatibleSld(layer, style_name)[source]
svir.utilities.sldadapter.getLabelingAsSld(layer)[source]
svir.utilities.sldadapter.getStyleAsSld(layer, styleName)[source]
svir.utilities.sldadapter.line_to_sld(document, element, penStyle, color, width, penJoinStyle, customDashPattern, dashOffset)[source]
svir.utilities.sldadapter.rule_to_sld(rule, document, element, props)[source]
svir.utilities.sldadapter.symbolLayer_to_sld(symbolLayer, document, element, props)[source]
svir.utilities.sldadapter.symbolv2_to_sld(symbol, document, element, props)[source]

svir.utilities.utils module

class svir.utilities.utils.IterableToFileAdapter(iterable)[source]

Bases: object

an adapter which makes the multipart-generator issued by poster accessible to requests. Based upon code from http://stackoverflow.com/a/13911048/1659732 https://goo.gl/zgLx0T

read(size=-1)[source]
class svir.utilities.utils.LayerEditingManager(layer, message, debug=False)[source]

Bases: object

Wrapper to be used to edit a layer, that executes startEditing and commitChanges

Parameters:
  • layer – the layer that is being edited
  • message – description of the task that is being performed
  • debug – if False, nothing will be logged
exception svir.utilities.utils.ReadMetadataError[source]

Bases: exceptions.Exception

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

suggestion = 'Check that the file is correct'
class svir.utilities.utils.Register(*args, **kwds)[source]

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)[source]

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.SvNetworkError[source]

Bases: exceptions.Exception

class svir.utilities.utils.TraceTimeManager(message, debug=False)[source]

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[source]

Bases: exceptions.Exception

class svir.utilities.utils.WaitCursorManager(msg=None, iface=None)[source]

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)')[source]

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')[source]

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)[source]

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.clear_progress_message_bar(msg_bar, msg_bar_item=None)[source]

Clear the progress messsage bar

svir.utilities.utils.confirm_overwrite(parent, files)[source]

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

svir.utilities.utils.confirmation_on_close(parent, event=None)[source]

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.count_heading_commented_lines(fname)[source]

count top lines in the file starting with ‘#’

svir.utilities.utils.create_progress_message_bar(msg_bar, msg, no_percentage=False)[source]

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)[source]

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.files_exist_in_destination(destination, file_names)[source]

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_field_names(sub_tree, field_names=None)[source]

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_irmt_version()[source]

Get the plugin’s version from metadata.txt

svir.utilities.utils.get_node(sub_tree, name)[source]

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_ui_class(ui_file)[source]
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.insert_platform_layer_id(layer_url, active_layer_id, supplemental_information)[source]

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.is_hdfview_installed()[source]
svir.utilities.utils.log_msg(message, tag='GEM IRMT Plugin', level='I')[source]

Add a message to the QGIS message log

Parameters:
  • message – the message
  • tag – the log topic
  • level

    the importance level (‘I’ -> QgsMessageLog.INFO,

    ‘W’ -> QgsMessageLog.WARNING, ‘C’ -> QgsMessageLog.CRITICAL)
svir.utilities.utils.multipart_encode_for_requests(params, boundary=None, cb=None)[source]

“helper function simulating the interface of posters multipart_encode()-function but wrapping its generator with the file-like adapter

svir.utilities.utils.platform_login(host, username, password, session)[source]

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_config_file(filename, cast_func=None)[source]
svir.utilities.utils.read_layer_suppl_info_from_qgs(layer_id, supplemental_information)[source]

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)[source]

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

    multiple tuples containing types

svir.utilities.utils.reload_layers_in_cbx(combo, layer_types=None, skip_layer_ids=None)[source]

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)[source]

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. :param 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
Parameters:
  • before – string to be replaced
  • after – new value for the replaced string
svir.utilities.utils.set_operator(sub_tree, operator)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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.upload_shp(host, session, file_stem, username)[source]

Upload a shapefile to the OpenQuake Platform

Parameters:
  • host – url of the OpenQuake Platform server
  • session – authenticated session to be used
  • file_stem – the name of the shapefile (without the extension)
  • username – the name of the user attempting to perform the action
Returns:

a tuple containing the server’s response and a boolean indicating if the uploading was successful

svir.utilities.utils.write_layer_suppl_info_to_qgs(layer_id, suppl_info)[source]

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