本文整理汇总了Python中safe.utilities.keyword_io.KeywordIO类的典型用法代码示例。如果您正苦于以下问题:Python KeywordIO类的具体用法?Python KeywordIO怎么用?Python KeywordIO使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了KeywordIO类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_issue1191
def test_issue1191(self):
"""Test setting a layer's title in the kw directly from qgis api"""
DOCK.set_layer_from_title_flag = True
set_canvas_crs(GEOCRS, True)
set_yogya_extent(DOCK)
result, message = setup_scenario(
DOCK,
hazard='An earthquake in Yogyakarta like in 2006',
exposure='OSM Building Polygons',
function='Be affected',
function_id='Earthquake Building Impact Function')
self.assertTrue(result, message)
layer = DOCK.get_hazard_layer()
keyword_io = KeywordIO()
original_title = 'An earthquake in Yogyakarta like in 2006'
title = keyword_io.read_keywords(layer, 'title')
self.assertEqual(title, original_title)
# change layer name as if done in the legend
expected_title = 'TEST'
layer.setLayerName(expected_title)
title = keyword_io.read_keywords(layer, 'title')
self.assertEqual(title, expected_title)
# reset KW file to original state
layer.setLayerName(original_title)
title = keyword_io.read_keywords(layer, 'title')
self.assertEqual(title, original_title)
DOCK.set_layer_from_title_flag = False
示例2: test_issue1191
def test_issue1191(self):
"""Test setting a layer's title in the kw directly from qgis api"""
settings = QtCore.QSettings()
settings.setValue(
'inasafe/analysis_extents_mode', 'HazardExposure')
self.dock.set_layer_from_title_flag = True
set_canvas_crs(GEOCRS, True)
set_yogya_extent(self.dock)
result, message = setup_scenario(
self.dock,
hazard='Earthquake',
exposure='Buildings',
function='Be affected',
function_id='EarthquakeBuildingFunction')
self.assertTrue(result, message)
layer = self.dock.get_hazard_layer()
keyword_io = KeywordIO()
original_title = 'Earthquake'
title = keyword_io.read_keywords(layer, 'title')
self.assertEqual(title, original_title)
# change layer name as if done in the legend
expected_title = 'TEST'
layer.setLayerName(expected_title)
title = keyword_io.read_keywords(layer, 'title')
self.assertEqual(title, expected_title)
# reset KW file to original state
layer.setLayerName(original_title)
title = keyword_io.read_keywords(layer, 'title')
self.assertEqual(title, original_title)
self.dock.set_layer_from_title_flag = False
示例3: show_keywords_editor
def show_keywords_editor(self):
"""Show the keywords editor."""
# import here only so that it is AFTER i18n set up
from safe.gui.tools.keywords_dialog import KeywordsDialog
# Next block is a fix for #776
if self.iface.activeLayer() is None:
return
try:
keyword_io = KeywordIO()
keyword_io.read_keywords(self.iface.activeLayer())
except UnsupportedProviderError:
# noinspection PyUnresolvedReferences,PyCallByClass
# noinspection PyTypeChecker,PyArgumentList
QMessageBox.warning(
None,
self.tr("Unsupported layer type"),
self.tr(
"The layer you have selected cannot be used for " "analysis because its data type is unsupported."
),
)
return
# End of fix for #776
# Fix for #793
except NoKeywordsFoundError:
# we will create them from scratch in the dialog
pass
# End of fix for #793
# Fix for filtered-layer
except InvalidParameterError, e:
# noinspection PyTypeChecker,PyTypeChecker,PyArgumentList
QMessageBox.warning(None, self.tr("Invalid Layer"), e.message)
return
示例4: resolve_dict_keywords
def resolve_dict_keywords(keywords):
"""Replace dictionary content with html.
:param keywords: The keywords.
:type keywords: dict
:return: New keywords with updated content.
:rtype: dict
"""
for keyword in ['value_map', 'inasafe_fields', 'inasafe_default_values']:
value = keywords.get(keyword)
if value:
value = value.get('content')
value = KeywordIO._dict_to_row(value).to_html()
keywords[keyword]['content'] = value
value_maps = keywords.get('value_maps')
thresholds = keywords.get('thresholds')
if value_maps:
value_maps = value_maps.get('content')
value_maps = KeywordIO._value_maps_row(value_maps).to_html()
keywords['value_maps']['content'] = value_maps
if thresholds:
thresholds = thresholds.get('content')
thresholds = KeywordIO._threshold_to_row(thresholds).to_html()
keywords['thresholds']['content'] = thresholds
return keywords
示例5: show_current_metadata
def show_current_metadata(self):
"""Show metadata of the current selected layer."""
LOGGER.debug('Showing layer: ' + self.layer.name())
keywords = KeywordIO(self.layer)
content_html = keywords.to_message().to_html()
full_html = html_header() + content_html + html_footer()
self.metadata_preview_web_view.setHtml(full_html)
示例6: test_layer_to_message
def test_layer_to_message(self):
"""Test to show augmented keywords if KeywordsIO ctor passed a layer.
.. versionadded:: 3.3
"""
keywords = KeywordIO(self.vector_layer)
message = keywords.to_message().to_text()
self.assertIn('*Reference system*, ', message)
示例7: create_keyword_file
def create_keyword_file(self, algorithm):
"""Create keyword file for the raster file created.
Basically copy a template from keyword file in converter data
and add extra keyword (usually a title)
:param algorithm: Which re-sampling algorithm to use.
valid options are 'nearest' (for nearest neighbour), 'invdist'
(for inverse distance), 'average' (for moving average). Defaults
to 'nearest' if not specified. Note that passing re-sampling alg
parameters is currently not supported. If None is passed it will
be replaced with 'nearest'.
:type algorithm: str
"""
keyword_io = KeywordIO()
classes = {}
for item in earthquake_mmi_scale['classes']:
classes[item['key']] = [
item['numeric_default_min'], item['numeric_default_max']]
keywords = {
'hazard': hazard_earthquake['key'],
'hazard_category': hazard_category_single_event['key'],
'keyword_version': inasafe_keyword_version,
'layer_geometry': layer_geometry_raster['key'],
'layer_mode': layer_mode_continuous['key'],
'layer_purpose': layer_purpose_hazard['key'],
'continuous_hazard_unit': unit_mmi['key'],
'classification': earthquake_mmi_scale['key'],
'thresholds': classes
}
if self.algorithm_name:
layer_path = os.path.join(
self.output_dir, '%s-%s.tif' % (
self.output_basename, algorithm))
else:
layer_path = os.path.join(
self.output_dir, '%s.tif' % self.output_basename)
# append title and source to the keywords file
if len(self.title.strip()) == 0:
keyword_title = self.output_basename
else:
keyword_title = self.title
keywords['title'] = keyword_title
hazard_layer = QgsRasterLayer(layer_path, keyword_title)
if not hazard_layer.isValid():
raise InvalidLayerError()
keyword_io.write_keywords(hazard_layer, keywords)
示例8: read_keywords_iso_metadata
def read_keywords_iso_metadata(metadata_url, keyword=None):
"""Read xml metadata of a layer"""
filename = download_file(metadata_url)
# add xml extension
new_filename = filename + '.xml'
shutil.move(filename, new_filename)
keyword_io = KeywordIO()
keywords = keyword_io.read_keywords_file(new_filename)
if keyword:
return keywords.get(keyword, None)
return keywords
示例9: analysis_execution
def analysis_execution():
from safe.test.utilities import get_qgis_app
# get_qgis_app must be called before importing Analysis
QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app()
from safe.utilities.analysis import Analysis
from safe.utilities.keyword_io import KeywordIO
analysis = Analysis()
arg = AnalysisArguments.read_arguments()
register_impact_functions()
registry = ImpactFunctionManager().registry
function = registry.get_instance(arg.impact_function_name)
hazard_layer = safe_to_qgis_layer(read_layer(arg.hazard_filename))
exposure_layer = safe_to_qgis_layer(read_layer(arg.exposure_filename))
if arg.aggregation_filename:
aggregation_layer = safe_to_qgis_layer(read_layer(
arg.aggregation_filename))
keywords_io = KeywordIO()
try:
analysis.map_canvas = IFACE.mapCanvas()
analysis.hazard_layer = hazard_layer
analysis.hazard_keyword = keywords_io.read_keywords(hazard_layer)
analysis.exposure_layer = exposure_layer
analysis.exposure_keyword = keywords_io.read_keywords(exposure_layer)
if aggregation_layer:
analysis.aggregation_layer = aggregation_layer
analysis.aggregation_keyword = keywords_io.read_keywords(
aggregation_layer)
analysis.impact_function = function
analysis.setup_analysis()
print 'Setup analysis done'
analysis.run_analysis()
print 'Analysis done'
except Exception as e:
print e.message
impact = analysis.impact_layer
qgis_impact = safe_to_qgis_layer(impact)
generate_styles(impact, qgis_impact)
copy_impact_layer(impact, arg.impact_filename)
示例10: layer_changed
def layer_changed(self, layer):
"""Enable or disable keywords editor icon when active layer changes.
:param layer: The layer that is now active.
:type layer: QgsMapLayer
"""
if not layer:
enable_keyword_wizard = False
elif not hasattr(layer, 'providerType'):
enable_keyword_wizard = False
elif layer.providerType() == 'wms':
enable_keyword_wizard = False
elif is_raster_layer(layer) and layer.bandCount() > 1:
enable_keyword_wizard = False
else:
enable_keyword_wizard = True
try:
if layer:
if is_raster_layer(layer):
enable_field_mapping_tool = False
else:
keywords = KeywordIO().read_keywords(layer)
layer_purpose = keywords.get('layer_purpose')
if not layer_purpose:
enable_field_mapping_tool = False
if layer_purpose == layer_purpose_exposure['key']:
layer_subcategory = keywords.get('exposure')
elif layer_purpose == layer_purpose_hazard['key']:
layer_subcategory = keywords.get('hazard')
else:
layer_subcategory = None
field_groups = get_field_groups(
layer_purpose, layer_subcategory)
if len(field_groups) == 0:
# No field group, disable field mapping tool.
enable_field_mapping_tool = False
else:
enable_field_mapping_tool = True
else:
enable_field_mapping_tool = False
except (KeywordNotFoundError, NoKeywordsFoundError, MetadataReadError):
# No keywords, disable field mapping tool.
enable_field_mapping_tool = False
self.action_keywords_wizard.setEnabled(enable_keyword_wizard)
self.action_field_mapping.setEnabled(enable_field_mapping_tool)
示例11: monkey_patch_keywords
def monkey_patch_keywords(layer):
"""In InaSAFE V4, we do monkey patching for keywords.
:param layer: The layer to monkey patch keywords.
:type layer: QgsMapLayer
"""
keyword_io = KeywordIO()
try:
layer.keywords = keyword_io.read_keywords(layer)
except (NoKeywordsFoundError, MetadataReadError):
layer.keywords = {}
if not layer.keywords.get('inasafe_fields'):
layer.keywords['inasafe_fields'] = {}
if not layer.keywords.get('layer_purpose'):
layer.keywords['layer_purpose'] = 'undefined'
示例12: monkey_patch_keywords
def monkey_patch_keywords(layer):
"""In InaSAFE V4, we do monkey patching for keywords.
:param layer: The layer to monkey patch keywords.
:type layer: QgsMapLayer
"""
keyword_io = KeywordIO()
try:
layer.keywords = keyword_io.read_keywords(layer)
except (NoKeywordsFoundError, MetadataReadError):
layer.keywords = {}
try:
layer.keywords['inasafe_fields']
except KeyError:
layer.keywords['inasafe_fields'] = {}
示例13: hazard_extra_keyword
def hazard_extra_keyword(keyword, feature, parent):
"""Given a keyword, it will return the value of the keyword
from the hazard layer's extra keywords.
For instance:
* hazard_extra_keyword( 'depth' ) -> will return the value of 'depth'
in current hazard layer's extra keywords.
"""
_ = feature, parent # NOQA
hazard_layer_path = QgsExpressionContextUtils. \
projectScope(QgsProject.instance()).variable(
'hazard_layer')
hazard_layer = load_layer(hazard_layer_path)[0]
keywords = KeywordIO.read_keywords(hazard_layer)
extra_keywords = keywords.get('extra_keywords')
if extra_keywords:
value = extra_keywords.get(keyword)
if value:
value_definition = definition(value)
if value_definition:
return value_definition['name']
return value
else:
return tr('Keyword %s is not found' % keyword)
return tr('No extra keywords found')
示例14: __init__
def __init__(self, iface, template, layer):
"""Constructor for the Composition Report class.
:param iface: Reference to the QGIS iface object.
:type iface: QgsAppInterface
:param template: The QGIS template path.
:type template: str
"""
LOGGER.debug('InaSAFE Impact Report class initialised')
self._iface = iface
self._template = template
self._layer = layer
self._extent = self._iface.mapCanvas().extent()
self._page_dpi = 300.0
self._safe_logo = resources_path(
'img', 'logos', 'inasafe-logo-url.svg')
self._organisation_logo = default_organisation_logo_path()
self._north_arrow = default_north_arrow_path()
self._disclaimer = disclaimer()
# For QGIS < 2.4 compatibility
# QgsMapSettings is added in 2.4
if qgis_version() < 20400:
map_settings = self._iface.mapCanvas().mapRenderer()
else:
map_settings = self._iface.mapCanvas().mapSettings()
self._template_composition = TemplateComposition(
template_path=self.template,
map_settings=map_settings)
self._keyword_io = KeywordIO()
示例15: __init__
def __init__(self, parent):
"""Constructor for the class.
:param parent: Parent widget i.e. the wizard dialog.
:type parent: QWidget
"""
QtCore.QObject.__init__(self)
self.parent = parent
# Do not delete this
self.iface = parent.iface
self.keyword_io = KeywordIO()
self.impact_function_manager = ImpactFunctionManager()
self.extent = Extent(self.iface)
self.analysis = None
# Values for settings these get set in read_settings.
self.run_in_thread_flag = None
self.zoom_to_impact_flag = None
self.hide_exposure_flag = None
self.clip_hard = None
self.show_intermediate_layers = None
self.show_rubber_bands = False
self.last_analysis_rubberband = None
# This is a rubber band to show what the AOI of the
# next analysis will be. Also added in 2.1.0
self.next_analysis_rubberband = None
self.read_settings()