Module: safe_qgis.utilities

InaSAFE Disaster risk assessment tool developed by AusAid -
IS Utilitles implementation.

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.

class safe_qgis.utilities.QgsLogHandler(level=0)[source]

A logging handler that will log messages to the QGIS logging console.

emit(theRecord)[source]

Try to log the message to QGIS if available, otherwise do nothing.

Args:
theRecord: logging record containing whatever info needs to be
logged.
Returns:
None
Raises:
None
safe_qgis.utilities.addLoggingHanderOnce(theLogger, theHandler)[source]

A helper to add a handler to a logger, ensuring there are no duplicates.

Args:
  • theLogger: logging.logger instance

  • theHandler: logging.Handler instance to be added. It will not be

    added if an instance of that Handler subclass already exists.

Returns:
bool: True if the logging handler was added
Raises:
None
safe_qgis.utilities.getDefaults(theDefault=None)[source]

returns a dictionary of defaults values to be used it takes the DEFAULTS from safe and modifies them according to qgis

QSettings
Args:
  • theDefault: a key of the defaults dictionary
Returns:
  • A dictionary of defaults values to be used
  • or the default value if a key is passed
  • or None if the requested default value is not valid
Raises:
no exceptions explicitly raised
safe_qgis.utilities.getExceptionWithStacktrace(e, html=False, context=None)[source]

Convert exception into a string and and stack trace

Input
e: Exception object html: Optional flat if output is to wrapped as html context: Optional context message
Output
Exception with stack trace info suitable for display
safe_qgis.utilities.getLayerAttributeNames(theLayer, theAllowedTypes, theCurrentKeyword=None)[source]

iterates over self.layer and returns all the attribute names of attributes that have int or string as field type and the position

of the theCurrentKeyword in the attribute names list
Args:
  • theAllowedTypes: list(Qvariant) - a list of QVariants types that are

    acceptable for the attribute. e.g.: [QtCore.QVariant.Int, QtCore.QVariant.String]

  • theCurrentKeyword - the currently stored keyword for the attribute

Returns:
  • all the attribute names of attributes that have int or string as

    field type

  • the position of the theCurrentKeyword in the attribute names list,

    this is None if theCurrentKeyword is not in the lis of attributes

Raises:
no exceptions explicitly raised
safe_qgis.utilities.getWGS84resolution(theLayer)[source]

Return resolution of raster layer in EPSG:4326

Input
theLayer: Raster layer
Output
resolution.

If input layer is already in EPSG:4326, simply return the resolution If not, work it out based on EPSG:4326 representations of its extent

safe_qgis.utilities.htmlFooter()[source]

Get a standard html footer for wrapping content in.

safe_qgis.utilities.htmlHeader()[source]

Get a standard html header for wrapping content in.

safe_qgis.utilities.humaniseSeconds(theSeconds)[source]

Utility function to humanise seconds value into e.g. 10 seconds ago.

The function will try to make a nice phrase of the seconds count provided.

Note

Currently theSeconds that amount to days are not supported.

Args:
theSeconds: int - mandatory seconds value e.g. 1100
Returns:
str: A humanised version of the seconds count.
Raises:
None
safe_qgis.utilities.impactLayerAttribution(theKeywords, theInaSAFEFlag=False)[source]

Make a little table for attribution of data sources used in impact.

Args:
  • theKeywords: dict{} - a keywords dict for an impact layer.

  • theInaSAFEFlag: bool - whether to show a little InaSAFE promotional

    text in the attribution output. Defaults to False.

Returns:
str: an html snippet containing attribution information for the impact
layer. If no keywords are present or no appropriate keywords are present, None is returned.
Raises:
None
safe_qgis.utilities.isLayerPolygonal(theLayer)[source]

tell if a qgis theLayer is vectorial and d its geometries polygons Args:

the theLayer
Returns:
bool - true if the theLayer contains polygons
Raises:
None
safe_qgis.utilities.mmToPoints(theMM, theDpi)[source]

Convert measurement in points to one in mm.

Args:
  • theMM: int - distance in millimeters
  • theDpi: int - dots per inch in the print / display medium
Returns:
mm converted value
Raises:
Any exceptions raised by the InaSAFE library will be propagated.
safe_qgis.utilities.pointsToMM(thePoints, theDpi)[source]

Convert measurement in points to one in mm.

Args:
  • thePoints: int - number of points in display / print medium
  • theDpi: int - dots per inch in the print / display medium
Returns:
mm converted value
Raises:
Any exceptions raised by the InaSAFE library will be propagated.
safe_qgis.utilities.qgisVersion()[source]

Get the version of QGIS Args:

None
Returns:
QGIS Version where 10700 represents QGIS 1.7 etc.
Raises:
None
safe_qgis.utilities.setRasterStyle(theQgsRasterLayer, theStyle)[source]

Set QGIS raster style based on InaSAFE style dictionary.

This function will set both the colour map and the transparency for the passed in layer.

Args:
  • theQgsRasterLayer: QgsRasterLayer
  • style: dict - Dictionary of the form as in the example below.
Example:
style_classes = [dict(colour=’#38A800’, quantity=2, transparency=0),
dict(colour=’#38A800’, quantity=5, transparency=50), dict(colour=’#79C900’, quantity=10, transparency=50), dict(colour=’#CEED00’, quantity=20, transparency=50), dict(colour=’#FFCC00’, quantity=50, transparency=34), dict(colour=’#FF6600’, quantity=100, transparency=77), dict(colour=’#FF0000’, quantity=200, transparency=24), dict(colour=’#7A0000’, quantity=300, transparency=22)]
Returns:
list: RangeList list: TransparencyList
safe_qgis.utilities.setVectorStyle(theQgisVectorLayer, theStyle)[source]

Set QGIS vector style based on InaSAFE style dictionary.

For opaque a value of 0 can be used. For fully transparent, a value of 100 can be used. The function should take care to scale the transparency level to between 0 and 100.

Args:
  • theQgisVectorLayer: QgsMapLayer
  • theStyle: dict - Dictionary of the form as in the example below
Returns:
None - Sets and saves style for theQgisVectorLayer
Raises:
None

Example:

{‘target_field’: ‘DMGLEVEL’, ‘style_classes’: [{‘transparency’: 1, ‘max’: 1.5, ‘colour’: ‘#fecc5c’,

‘min’: 0.5, ‘label’: ‘Low damage’, ‘size’ : 1},
{‘transparency’: 55, ‘max’: 2.5, ‘colour’: ‘#fd8d3c’,
‘min’: 1.5, ‘label’: ‘Medium damage’, ‘size’ : 1},
{‘transparency’: 80, ‘max’: 3.5, ‘colour’: ‘#f31a1c’,
‘min’: 2.5, ‘label’: ‘High damage’, ‘size’ : 1}]}

Note

The transparency and size keys are optional. Size applies to points only.

safe_qgis.utilities.setupLogger()[source]

Run once when the module is loaded and enable logging

Args: None

Returns: None

Raises: None

Borrowed heavily from this: http://docs.python.org/howto/logging-cookbook.html

Use this to first initialise the logger (see safe/__init__.py):

from safe_qgis import utilities
utilities.setupLogger()

You would typically only need to do the above once ever as the safe modle is initialised early and will set up the logger globally so it is available to all packages / subpackages as shown below.

In a module that wants to do logging then use this example as a guide to get the initialised logger instance:

# The LOGGER is intialised in utilities.py by init
import logging
LOGGER = logging.getLogger('InaSAFE')

Now to log a message do:

LOGGER.debug('Some debug message')

Note

The file logs are written to the inasafe user tmp dir e.g.: /tmp/inasafe/23-08-2012/timlinux/logs/inasafe.log

safe_qgis.utilities.setupPrinter(theFilename, theResolution=300, thePageHeight=297, thePageWidth=210)[source]

Create a QPrinter instance defaulted to print to an A4 portrait pdf

Args:
theFilename - filename for pdf generated using this printer
Returns:
None
Raises:
None
safe_qgis.utilities.tr(theText)[source]

We define a tr() alias here since the utilities implementation below is not a class and does not inherit from QObject. .. note:: see http://tinyurl.com/pyqt-differences Args:

theText - string to be translated
Returns:
Translated version of the given string if available, otherwise the original string.

This module forms part of the InaSAFE tool.

Previous topic

Module: safe_qgis.impact_functions_doc_base

Next topic

Module: safe_qgis.options_dialog_base

This Page