本文整理汇总了Python中safe_qgis.keyword_io.KeywordIO类的典型用法代码示例。如果您正苦于以下问题:Python KeywordIO类的具体用法?Python KeywordIO怎么用?Python KeywordIO使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了KeywordIO类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_printImpactTable
def test_printImpactTable(self):
"""Test that we can render html from impact table keywords."""
LOGGER.debug('InaSAFE HtmlRenderer testing printImpactTable')
myFilename = 'test_floodimpact.tif'
myLayer, _ = loadLayer(myFilename)
myMessage = 'Layer is not valid: %s' % myFilename
assert myLayer.isValid(), myMessage
myPageDpi = 300
myHtmlRenderer = HtmlRenderer(myPageDpi)
myPath = unique_filename(prefix='impactTable',
suffix='.pdf',
dir=temp_dir('test'))
myKeywordIO = KeywordIO()
myKeywords = myKeywordIO.readKeywords(myLayer)
myPath = myHtmlRenderer.printImpactTable(myKeywords,
theFilename=myPath)
myMessage = 'Rendered output does not exist: %s' % myPath
assert os.path.exists(myPath), myMessage
# pdf rendering is non deterministic so we can't do a hash check
# test_renderComposition renders just the image instead of pdf
# so we hash check there and here we just do a basic minimum file
# size check.
mySize = os.stat(myPath).st_size
myExpectedSize = 20936 # as rendered on linux ub 12.04 64
myMessage = ('Expected rendered table pdf to be at least %s, got %s'
% (myExpectedSize, mySize))
assert mySize >= myExpectedSize, myMessage
示例2: __init__
def __init__(self, parent, iface, theDock=None):
"""Constructor for the dialog.
Args:
* parent - parent widget of this dialog
* iface - a Quantum GIS QGisAppInterface instance.
* theDock - Optional dock widget instance that we can notify of
changes to the keywords.
Returns:
not applicable
Raises:
no exceptions explicitly raised
"""
QtGui.QDialog.__init__(self, parent)
self.setupUi(self)
self.setWindowTitle(self.tr('InaSAFE %s Options' % get_version()))
# Save reference to the QGIS interface and parent
self.iface = iface
self.parent = parent
self.dock = theDock
self.helpDialog = None
self.keywordIO = KeywordIO()
# Set up things for context help
myButton = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'),
self.showHelp)
self.grpNotImplemented.hide()
self.adjustSize()
self.restoreState()
# hack prevent showing use thread visible and set it false see #557
self.cbxUseThread.setChecked(True)
self.cbxUseThread.setVisible(False)
示例3: setUp
def setUp(self):
self.keywordIO = KeywordIO()
myUri = QgsDataSourceURI()
myUri.setDatabase(os.path.join(TESTDATA, 'jk.sqlite'))
myUri.setDataSource('', 'osm_buildings', 'Geometry')
self.sqliteLayer = QgsVectorLayer(myUri.uri(), 'OSM Buildings',
'spatialite')
myHazardPath = os.path.join(HAZDATA, 'Shakemap_Padang_2009.asc')
self.fileRasterLayer, myType = loadLayer(myHazardPath,
theDirectory=None)
del myType
self.fileVectorLayer, myType = loadLayer('Padang_WGS84.shp')
del myType
self.expectedSqliteKeywords = {'category': 'exposure',
'datatype': 'OSM',
'subcategory': 'building'}
self.expectedVectorKeywords = {'category': 'exposure',
'datatype': 'itb',
'subcategory': 'structure'}
self.expectedRasterKeywords = {'category': 'hazard',
'source': 'USGS',
'subcategory': 'earthquake',
'unit': 'MMI',
'title': ('An earthquake in Padang '
'like in 2009')}
示例4: __init__
def __init__(self, theLayer, theDpi=300, theLegendTitle=None,
theLegendNotes=None, theLegendUnits=None):
"""Constructor for the Map Legend class.
Args:
* theLayer: QgsMapLayer object that the legend should be generated
for.
* theDpi: Optional DPI for generated legend image. Defaults to
300 if not specified.
Returns:
None
Raises:
Any exceptions raised will be propagated.
"""
LOGGER.debug('InaSAFE Map class initialised')
self.legendImage = None
self.layer = theLayer
# how high each row of the legend should be
self.legendIncrement = 42
self.keywordIO = KeywordIO()
self.legendFontSize = 8
self.legendWidth = 900
self.dpi = theDpi
if theLegendTitle is None:
self.legendTitle = self.tr('Legend')
else:
self.legendTitle = theLegendTitle
print 'AFUFUFU', self.legendTitle
self.legendNotes = theLegendNotes
self.legendUnits = theLegendUnits
示例5: __init__
def __init__(self, theIface):
"""Constructor for the Map class.
Args:
theIface - reference to the QGIS iface object
Returns:
None
Raises:
Any exceptions raised by the InaSAFE library will be propagated.
"""
LOGGER.debug("InaSAFE Map class initialised")
self.iface = theIface
self.layer = theIface.activeLayer()
self.keywordIO = KeywordIO()
self.printer = None
self.composition = None
self.legend = None
self.pageWidth = 210 # width in mm
self.pageHeight = 297 # height in mm
self.pageDpi = 300.0
self.pageMargin = 10 # margin in mm
self.verticalSpacing = 1 # vertical spacing between elements
self.showFramesFlag = False # intended for debugging use only
# make a square map where width = height = page width
self.mapHeight = self.pageWidth - (self.pageMargin * 2)
self.mapWidth = self.mapHeight
self.disclaimer = self.tr("InaSAFE has been jointly developed by" " BNPB, AusAid & the World Bank")
示例6: __init__
def __init__(self, parent, iface, theDock=None):
"""Constructor for the dialog.
.. note:: In QtDesigner the advanced editor's predefined keywords
list should be shown in english always, so when adding entries to
cboKeyword, be sure to choose :safe_qgis:`Properties<<` and untick
the :safe_qgis:`translatable` property.
Args:
* parent - parent widget of this dialog
* iface - a Quantum GIS QGisAppInterface instance.
* theDock - Optional dock widget instance that we can notify of
changes to the keywords.
Returns:
not applicable
Raises:
no exceptions explicitly raised
"""
QtGui.QDialog.__init__(self, parent)
self.setupUi(self)
self.setWindowTitle(self.tr(
'InaSAFE %s Keywords Editor' % __version__))
self.keywordIO = KeywordIO()
# note the keys should remain untranslated as we need to write
# english to the keywords file. The keys will be written as user data
# in the combo entries.
# .. seealso:: http://www.voidspace.org.uk/python/odict.html
self.standardExposureList = OrderedDict([('population [density]',
self.tr('population [density]')),
('population [count]',
self.tr('population [count]')),
('building',
self.tr('building')),
('building [osm]',
self.tr('building [osm]')),
('building [sigab]',
self.tr('building [sigab]')),
('roads',
self.tr('roads'))])
self.standardHazardList = OrderedDict([('earthquake [MMI]',
self.tr('earthquake [MMI]')),
('tsunami [m]',
self.tr('tsunami [m]')),
('tsunami [wet/dry]',
self.tr('tsunami [wet/dry]')),
('tsunami [feet]',
self.tr('tsunami [feet]')),
('flood [m]',
self.tr('flood [m]')),
('flood [wet/dry]',
self.tr('flood [wet/dry]')),
('flood [feet]', self.tr('flood [feet]')),
('tephra [kg2/m2',
self.tr('tephra [kg2/m2]'))])
# Save reference to the QGIS interface and parent
self.iface = iface
self.parent = parent
self.dock = theDock
QtCore.QObject.connect(self.lstKeywords,
QtCore.SIGNAL("itemClicked(QListWidgetItem *)"),
self.makeKeyValueEditable)
# Set up help dialog showing logic.
self.helpDialog = None
myButton = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'),
self.showHelp)
# set some inital ui state:
self.pbnAdvanced.setChecked(True)
self.pbnAdvanced.toggle()
self.radPredefined.setChecked(True)
self.adjustSize()
#myButton = self.buttonBox.button(QtGui.QDialogButtonBox.Ok)
#myButton.setEnabled(False)
self.layer = self.iface.activeLayer()
if self.layer:
self.loadStateFromKeywords()
示例7: KeywordsDialog
class KeywordsDialog(QtGui.QDialog, Ui_KeywordsDialogBase):
"""Dialog implementation class for the Risk In A Box keywords editor."""
def __init__(self, parent, iface, theDock=None):
"""Constructor for the dialog.
.. note:: In QtDesigner the advanced editor's predefined keywords
list should be shown in english always, so when adding entries to
cboKeyword, be sure to choose :safe_qgis:`Properties<<` and untick
the :safe_qgis:`translatable` property.
Args:
* parent - parent widget of this dialog
* iface - a Quantum GIS QGisAppInterface instance.
* theDock - Optional dock widget instance that we can notify of
changes to the keywords.
Returns:
not applicable
Raises:
no exceptions explicitly raised
"""
QtGui.QDialog.__init__(self, parent)
self.setupUi(self)
self.setWindowTitle(self.tr(
'InaSAFE %s Keywords Editor' % __version__))
self.keywordIO = KeywordIO()
# note the keys should remain untranslated as we need to write
# english to the keywords file. The keys will be written as user data
# in the combo entries.
# .. seealso:: http://www.voidspace.org.uk/python/odict.html
self.standardExposureList = OrderedDict([('population [density]',
self.tr('population [density]')),
('population [count]',
self.tr('population [count]')),
('building',
self.tr('building')),
('building [osm]',
self.tr('building [osm]')),
('building [sigab]',
self.tr('building [sigab]')),
('roads',
self.tr('roads'))])
self.standardHazardList = OrderedDict([('earthquake [MMI]',
self.tr('earthquake [MMI]')),
('tsunami [m]',
self.tr('tsunami [m]')),
('tsunami [wet/dry]',
self.tr('tsunami [wet/dry]')),
('tsunami [feet]',
self.tr('tsunami [feet]')),
('flood [m]',
self.tr('flood [m]')),
('flood [wet/dry]',
self.tr('flood [wet/dry]')),
('flood [feet]', self.tr('flood [feet]')),
('tephra [kg2/m2',
self.tr('tephra [kg2/m2]'))])
# Save reference to the QGIS interface and parent
self.iface = iface
self.parent = parent
self.dock = theDock
QtCore.QObject.connect(self.lstKeywords,
QtCore.SIGNAL("itemClicked(QListWidgetItem *)"),
self.makeKeyValueEditable)
# Set up help dialog showing logic.
self.helpDialog = None
myButton = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'),
self.showHelp)
# set some inital ui state:
self.pbnAdvanced.setChecked(True)
self.pbnAdvanced.toggle()
self.radPredefined.setChecked(True)
self.adjustSize()
#myButton = self.buttonBox.button(QtGui.QDialogButtonBox.Ok)
#myButton.setEnabled(False)
self.layer = self.iface.activeLayer()
if self.layer:
self.loadStateFromKeywords()
def showHelp(self):
"""Load the help text for the keywords safe_qgis"""
if not self.helpDialog:
self.helpDialog = Help(self.iface.mainWindow(), 'keywords')
self.helpDialog.show()
# prevents actions being handled twice
@pyqtSignature('bool')
def on_pbnAdvanced_toggled(self, theFlag):
"""Automatic slot executed when the advanced button is toggled.
.. note:: some of the behaviour for hiding widgets is done using
the signal/slot editor in designer, so if you are trying to figure
out how the interactions work, look there too!
Args:
#.........这里部分代码省略.........
示例8: MapLegend
class MapLegend():
"""A class for creating a map legend."""
def __init__(self, theLayer, theDpi=300):
"""Constructor for the Map Legend class.
Args:
* theLayer: QgsMapLayer object that the legend should be generated
for.
* theDpi: Optional DPI for generated legend image. Defaults to
300 if not specified.
Returns:
None
Raises:
Any exceptions raised will be propagated.
"""
LOGGER.debug('InaSAFE Map class initialised')
self.legendImage = None
self.layer = theLayer
# how high each row of the legend should be
self.legendIncrement = 42
self.keywordIO = KeywordIO()
self.legendFontSize = 8
self.legendWidth = 900
self.dpi = theDpi
def tr(self, theString):
"""We implement this ourself since we do not inherit QObject.
Args:
theString - string for translation.
Returns:
Translated version of theString.
Raises:
no exceptions explicitly raised.
"""
return QtCore.QCoreApplication.translate('MapLegend', theString)
def getLegend(self):
"""Examine the classes of the impact layer associated with this print
job.
.. note: This is a wrapper for the rasterLegend and vectorLegend
methods.
Args:
None
Returns:
None
Raises:
An InvalidLegendLayer will be raised if a legend cannot be
created from the layer.
"""
LOGGER.debug('InaSAFE Map Legend getLegend called')
if self.layer is None:
myMessage = self.tr('Unable to make a legend when map generator '
'has no layer set.')
raise LegendLayerError(myMessage)
try:
self.keywordIO.readKeywords(self.layer, 'impact_summary')
except KeywordNotFoundError, e:
myMessage = self.tr('This layer does not appear to be an impact '
'layer. Try selecting an impact layer in the '
'QGIS layers list or creating a new impact '
'scenario before using the print tool.'
'\nMessage: %s' % str(e))
raise Exception(myMessage)
if self.layer.type() == QgsMapLayer.VectorLayer:
return self.getVectorLegend()
else:
return self.getRasterLegend()
示例9: OptionsDialog
class OptionsDialog(QtGui.QDialog, Ui_OptionsDialogBase):
"""Options dialog for the InaSAFE plugin."""
def __init__(self, parent, iface, theDock=None):
"""Constructor for the dialog.
Args:
* parent - parent widget of this dialog
* iface - a Quantum GIS QGisAppInterface instance.
* theDock - Optional dock widget instance that we can notify of
changes to the keywords.
Returns:
not applicable
Raises:
no exceptions explicitly raised
"""
QtGui.QDialog.__init__(self, parent)
self.setupUi(self)
self.setWindowTitle(self.tr('InaSAFE %s Options' % get_version()))
# Save reference to the QGIS interface and parent
self.iface = iface
self.parent = parent
self.dock = theDock
self.helpDialog = None
self.keywordIO = KeywordIO()
# Set up things for context help
myButton = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'),
self.showHelp)
self.grpNotImplemented.hide()
self.adjustSize()
self.restoreState()
# hack prevent showing use thread visible and set it false see #557
self.cbxUseThread.setChecked(True)
self.cbxUseThread.setVisible(False)
def restoreState(self):
"""
Args: Reinstate the options based on the user's stored session info
None
Returns:
None
Raises:
"""
mySettings = QtCore.QSettings()
# myFlag = mySettings.value(
# 'inasafe/useThreadingFlag', False).toBool()
# hack set use thread to false see #557
myFlag = False
self.cbxUseThread.setChecked(myFlag)
myFlag = mySettings.value(
'inasafe/visibleLayersOnlyFlag', True).toBool()
self.cbxVisibleLayersOnly.setChecked(myFlag)
myFlag = mySettings.value(
'inasafe/setLayerNameFromTitleFlag', True).toBool()
self.cbxSetLayerNameFromTitle.setChecked(myFlag)
myFlag = mySettings.value(
'inasafe/setZoomToImpactFlag', True).toBool()
self.cbxZoomToImpact.setChecked(myFlag)
# whether exposure layer should be hidden after model completes
myFlag = mySettings.value(
'inasafe/setHideExposureFlag', False).toBool()
self.cbxHideExposure.setChecked(myFlag)
myFlag = mySettings.value(
'inasafe/clipToViewport', True).toBool()
self.cbxClipToViewport.setChecked(myFlag)
myFlag = mySettings.value(
'inasafe/clipHard', False).toBool()
self.cbxClipHard.setChecked(myFlag)
myFlag = mySettings.value(
'inasafe/useSentry', False).toBool()
self.cbxUseSentry.setChecked(myFlag)
myFlag = mySettings.value(
'inasafe/showPostProcLayers', False).toBool()
self.cbxShowPostprocessingLayers.setChecked(myFlag)
myRatio = mySettings.value(
'inasafe/defaultFemaleRatio',
DEFAULTS['FEM_RATIO']).toDouble()
self.dsbFemaleRatioDefault.setValue(myRatio[0])
myPath = mySettings.value(
'inasafe/keywordCachePath',
self.keywordIO.defaultKeywordDbPath()).toString()
self.leKeywordCachePath.setText(myPath)
def saveState(self):
"""
Args: Store the options into the user's stored session info
None
Returns:
#.........这里部分代码省略.........
示例10: KeywordIOTest
class KeywordIOTest(unittest.TestCase):
"""Tests for reading and writing of raster and vector data
"""
def setUp(self):
self.keywordIO = KeywordIO()
myUri = QgsDataSourceURI()
myUri.setDatabase(os.path.join(TESTDATA, 'jk.sqlite'))
myUri.setDataSource('', 'osm_buildings', 'Geometry')
self.sqliteLayer = QgsVectorLayer(myUri.uri(), 'OSM Buildings',
'spatialite')
myHazardPath = os.path.join(HAZDATA, 'Shakemap_Padang_2009.asc')
self.fileRasterLayer, myType = loadLayer(myHazardPath,
theDirectory=None)
del myType
self.fileVectorLayer, myType = loadLayer('Padang_WGS84.shp')
del myType
self.expectedSqliteKeywords = {'category': 'exposure',
'datatype': 'OSM',
'subcategory': 'building'}
self.expectedVectorKeywords = {'category': 'exposure',
'datatype': 'itb',
'subcategory': 'structure'}
self.expectedRasterKeywords = {'category': 'hazard',
'source': 'USGS',
'subcategory': 'earthquake',
'unit': 'MMI',
'title': ('An earthquake in Padang '
'like in 2009')}
def tearDown(self):
pass
def test_getHashForDatasource(self):
"""Test we can reliably get a hash for a uri"""
myHash = self.keywordIO.getHashForDatasource(PG_URI)
myExpectedHash = '7cc153e1b119ca54a91ddb98a56ea95e'
myMessage = "Got: %s\nExpected: %s" % (myHash, myExpectedHash)
assert myHash == myExpectedHash, myMessage
def test_writeReadKeywordFromUri(self):
"""Test we can set and get keywords for a non local datasource"""
myHandle, myFilename = tempfile.mkstemp('.db', 'keywords_',
temp_dir())
# Ensure the file is deleted before we try to write to it
# fixes windows specific issue where you get a message like this
# ERROR 1: c:\temp\inasafe\clip_jpxjnt.shp is not a directory.
# This is because mkstemp creates the file handle and leaves
# the file open.
os.close(myHandle)
os.remove(myFilename)
myExpectedKeywords = {'category': 'exposure',
'datatype': 'itb',
'subcategory': 'building'}
# SQL insert test
# On first write schema is empty and there is no matching hash
self.keywordIO.setKeywordDbPath(myFilename)
self.keywordIO.writeKeywordsForUri(PG_URI, myExpectedKeywords)
# SQL Update test
# On second write schema is populated and we update matching hash
myExpectedKeywords = {'category': 'exposure',
'datatype': 'OSM', # <--note the change here!
'subcategory': 'building'}
self.keywordIO.writeKeywordsForUri(PG_URI, myExpectedKeywords)
# Test getting all keywords
myKeywords = self.keywordIO.readKeywordFromUri(PG_URI)
myMessage = 'Got: %s\n\nExpected %s\n\nDB: %s' % (
myKeywords, myExpectedKeywords, myFilename)
assert myKeywords == myExpectedKeywords, myMessage
# Test getting just a single keyword
myKeyword = self.keywordIO.readKeywordFromUri(PG_URI, 'datatype')
myExpectedKeyword = 'OSM'
myMessage = 'Got: %s\n\nExpected %s\n\nDB: %s' % (
myKeyword, myExpectedKeyword, myFilename)
assert myKeyword == myExpectedKeyword, myMessage
# Test deleting keywords actually does delete
self.keywordIO.deleteKeywordsForUri(PG_URI)
try:
myKeyword = self.keywordIO.readKeywordFromUri(PG_URI, 'datatype')
#if the above didnt cause an exception then bad
myMessage = 'Expected a HashNotFoundException to be raised'
assert myMessage
except HashNotFoundException:
#we expect this outcome so good!
pass
def test_areKeywordsFileBased(self):
"""Can we correctly determine if keywords should be written to file or
to database?"""
assert not self.keywordIO.areKeywordsFileBased(self.sqliteLayer)
assert self.keywordIO.areKeywordsFileBased(self.fileRasterLayer)
assert self.keywordIO.areKeywordsFileBased(self.fileVectorLayer)
def test_readRasterFileKeywords(self):
"""Can we read raster file keywords using generic readKeywords method
"""
myKeywords = self.keywordIO.readKeywords(self.fileRasterLayer)
myExpectedKeywords = self.expectedRasterKeywords
mySource = self.fileRasterLayer.source()
#.........这里部分代码省略.........
示例11: _clipRasterLayer
#.........这里部分代码省略.........
Path to the output clipped layer (placed in the
system temp dir).
Raises:
Exception if input layer is a density layer in projected coordinates -
see issue #123
"""
if not theLayer or not theExtent:
myMessage = tr('Layer or Extent passed to clip is None.')
raise InvalidParameterException(myMessage)
if theLayer.type() != QgsMapLayer.RasterLayer:
myMessage = tr('Expected a raster layer but received a %s.' %
str(theLayer.type()))
raise InvalidParameterException(myMessage)
myWorkingLayer = str(theLayer.source())
# Check for existence of keywords file
myKeywordsPath = myWorkingLayer[:-4] + '.keywords'
myMessage = tr('Input file to be clipped "%s" does not have the '
'expected keywords file %s' % (myWorkingLayer,
myKeywordsPath))
verify(os.path.isfile(myKeywordsPath), myMessage)
# Raise exception if layer is projected and refers to density (issue #123)
# FIXME (Ole): Need to deal with it - e.g. by automatically reprojecting
# the layer at this point and setting the native resolution accordingly
# in its keywords.
myKeywords = readKeywordsFromFile(myKeywordsPath)
if 'datatype' in myKeywords and myKeywords['datatype'] == 'density':
if theLayer.srs().epsg() != 4326:
# This layer is not WGS84 geographic
myMessage = ('Layer %s represents density but has spatial '
'reference "%s". Density layers must be given in '
'WGS84 geographic coordinates, so please reproject '
'and try again. For more information, see issue '
'https://github.com/AIFDR/inasafe/issues/123'
% (myWorkingLayer, theLayer.srs().toProj4()))
raise InvalidProjectionException(myMessage)
# We need to provide gdalwarp with a dataset for the clip
# because unline gdal_translate, it does not take projwin.
myClipKml = extentToKml(theExtent)
# Create a filename for the clipped, resampled and reprojected layer
myHandle, myFilename = tempfile.mkstemp('.tif', 'clip_',
temp_dir())
os.close(myHandle)
os.remove(myFilename)
# If no cell size is specified, we need to run gdalwarp without
# specifying the output pixel size to ensure the raster dims
# remain consistent.
if theCellSize is None:
myCommand = ('gdalwarp -q -t_srs EPSG:4326 -r near '
'-cutline %s -crop_to_cutline -of GTiff '
'"%s" "%s"' % (myClipKml,
myWorkingLayer,
myFilename))
else:
myCommand = ('gdalwarp -q -t_srs EPSG:4326 -r near -tr %f %f '
'-cutline %s -crop_to_cutline -of GTiff '
'"%s" "%s"' % (theCellSize,
theCellSize,
myClipKml,
myWorkingLayer,
myFilename))
myExecutablePrefix = ''
if sys.platform == 'darwin': # Mac OS X
# .. todo:: FIXME - softcode gdal version in this path
myExecutablePrefix = ('/Library/Frameworks/GDAL.framework/'
'Versions/1.9/Programs/')
myCommand = myExecutablePrefix + myCommand
LOGGER.debug(myCommand)
myResult = QProcess().execute(myCommand)
# For QProcess exit codes see
# http://qt-project.org/doc/qt-4.8/qprocess.html#execute
if myResult == -2: # cannot be started
myMessageDetail = tr('Process could not be started.')
myMessage = tr('<p>Error while executing the following shell command:'
'</p><pre>%s</pre><p>Error message: %s'
% (myCommand, myMessageDetail))
raise CallGDALError(myMessage)
elif myResult == -1: # process crashed
myMessageDetail = tr('Process could not be started.')
myMessage = tr('<p>Error while executing the following shell command:'
'</p><pre>%s</pre><p>Error message: %s'
% (myCommand, myMessageDetail))
raise CallGDALError(myMessage)
# .. todo:: Check the result of the shell call is ok
myKeywordIO = KeywordIO()
myKeywordIO.copyKeywords(theLayer, myFilename,
theExtraKeywords=theExtraKeywords)
return myFilename # Filename of created file
示例12: _clipVectorLayer
#.........这里部分代码省略.........
None
"""
if not theLayer or not theExtent:
myMessage = tr('Layer or Extent passed to clip is None.')
raise InvalidParameterException(myMessage)
if theLayer.type() != QgsMapLayer.VectorLayer:
myMessage = tr('Expected a vector layer but received a %s.' %
str(theLayer.type()))
raise InvalidParameterException(myMessage)
#myHandle, myFilename = tempfile.mkstemp('.sqlite', 'clip_',
# temp_dir())
myHandle, myFilename = tempfile.mkstemp('.shp', 'clip_',
temp_dir())
# Ensure the file is deleted before we try to write to it
# fixes windows specific issue where you get a message like this
# ERROR 1: c:\temp\inasafe\clip_jpxjnt.shp is not a directory.
# This is because mkstemp creates the file handle and leaves
# the file open.
os.close(myHandle)
os.remove(myFilename)
# Get the clip extents in the layer's native CRS
myGeoCrs = QgsCoordinateReferenceSystem()
myGeoCrs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
myXForm = QgsCoordinateTransform(myGeoCrs, theLayer.crs())
myRect = QgsRectangle(theExtent[0], theExtent[1],
theExtent[2], theExtent[3])
myProjectedExtent = myXForm.transformBoundingBox(myRect)
# Get vector layer
myProvider = theLayer.dataProvider()
if myProvider is None:
myMessage = tr('Could not obtain data provider from '
'layer "%s"' % theLayer.source())
raise Exception(myMessage)
# Get the layer field list, select by our extent then write to disk
# .. todo:: FIXME - for different geometry types we should implement
# different clipping behaviour e.g. reject polygons that
# intersect the edge of the bbox. Tim
myAttributes = myProvider.attributeIndexes()
myFetchGeometryFlag = True
myUseIntersectFlag = True
myProvider.select(myAttributes,
myProjectedExtent,
myFetchGeometryFlag,
myUseIntersectFlag)
myFieldList = myProvider.fields()
myWriter = QgsVectorFileWriter(myFilename,
'UTF-8',
myFieldList,
theLayer.wkbType(),
myGeoCrs,
#'SQLite') # FIXME (Ole): This works but is far too slow
'ESRI Shapefile')
if myWriter.hasError() != QgsVectorFileWriter.NoError:
myMessage = tr('Error when creating shapefile: <br>Filename:'
'%s<br>Error: %s' %
(myFilename, myWriter.hasError()))
raise Exception(myMessage)
# Reverse the coordinate xform now so that we can convert
# geometries from layer crs to geocrs.
myXForm = QgsCoordinateTransform(theLayer.crs(), myGeoCrs)
# Retrieve every feature with its geometry and attributes
myFeature = QgsFeature()
myCount = 0
while myProvider.nextFeature(myFeature):
myGeometry = myFeature.geometry()
# Loop through the parts adding them to the output file
# we write out single part features unless explodeMultipart is False
if explodeMultipart:
myGeometryList = explodeMultiPartGeometry(myGeometry)
else:
myGeometryList = [myGeometry]
for myPart in myGeometryList:
myPart.transform(myXForm)
myFeature.setGeometry(myPart)
myWriter.addFeature(myFeature)
myCount += 1
del myWriter # Flush to disk
if myCount < 1:
myMessage = tr('No features fall within the clip extents. '
'Try panning / zooming to an area containing data '
'and then try to run your analysis again.')
raise NoFeaturesInExtentException(myMessage)
myKeywordIO = KeywordIO()
myKeywordIO.copyKeywords(theLayer, myFilename,
theExtraKeywords=theExtraKeywords)
return myFilename # Filename of created file
示例13: _clipVectorLayer
#.........这里部分代码省略.........
if type(theExtent) is list:
myRect = QgsRectangle(
theExtent[0], theExtent[1],
theExtent[2], theExtent[3])
# noinspection PyCallByClass
myClipPolygon = QgsGeometry.fromRect(myRect)
elif (type(theExtent) is QgsGeometry and
theExtent.wkbType in myAllowedClipTypes):
myRect = theExtent.boundingBox().toRectF()
myClipPolygon = theExtent
else:
raise InvalidClipGeometryError(
tr(
'Clip geometry must be an extent or a single part'
'polygon based geometry.'))
myProjectedExtent = myXForm.transformBoundingBox(myRect)
# Get vector layer
myProvider = theLayer.dataProvider()
if myProvider is None:
myMessage = tr('Could not obtain data provider from '
'layer "%s"' % theLayer.source())
raise Exception(myMessage)
# Get the layer field list, select by our extent then write to disk
# .. todo:: FIXME - for different geometry types we should implement
# different clipping behaviour e.g. reject polygons that
# intersect the edge of the bbox. Tim
myAttributes = myProvider.attributeIndexes()
myFetchGeometryFlag = True
myUseIntersectFlag = True
myProvider.select(
myAttributes,
myProjectedExtent,
myFetchGeometryFlag,
myUseIntersectFlag)
myFieldList = myProvider.fields()
myWriter = QgsVectorFileWriter(
myFilename,
'UTF-8',
myFieldList,
theLayer.wkbType(),
myGeoCrs,
#'SQLite') # FIXME (Ole): This works but is far too slow
'ESRI Shapefile')
if myWriter.hasError() != QgsVectorFileWriter.NoError:
myMessage = tr('Error when creating shapefile: <br>Filename:'
'%s<br>Error: %s' %
(myFilename, myWriter.hasError()))
raise Exception(myMessage)
# Reverse the coordinate xform now so that we can convert
# geometries from layer crs to geocrs.
myXForm = QgsCoordinateTransform(theLayer.crs(), myGeoCrs)
# Retrieve every feature with its geometry and attributes
myFeature = QgsFeature()
myCount = 0
while myProvider.nextFeature(myFeature):
myGeometry = myFeature.geometry()
# Loop through the parts adding them to the output file
# we write out single part features unless theExplodeFlag is False
if theExplodeFlag:
myGeometryList = explodeMultiPartGeometry(myGeometry)
else:
myGeometryList = [myGeometry]
for myPart in myGeometryList:
myPart.transform(myXForm)
if theHardClipFlag:
# Remove any dangling bits so only intersecting area is
# kept.
myPart = clipGeometry(myClipPolygon, myPart)
if myPart is None:
continue
myFeature.setGeometry(myPart)
myWriter.addFeature(myFeature)
myCount += 1
del myWriter # Flush to disk
if myCount < 1:
myMessage = tr('No features fall within the clip extents. '
'Try panning / zooming to an area containing data '
'and then try to run your analysis again.'
'If hazard and exposure data doesn\'t overlap '
'at all, it is not possible to do an analysis.'
'Another possibility is that the layers do overlap '
'but because they may have different spatial '
'references, they appear to be disjoint. '
'If this is the case, try to turn on reproject '
'on-the-fly in QGIS.')
raise NoFeaturesInExtentError(myMessage)
myKeywordIO = KeywordIO()
myKeywordIO.copyKeywords(
theLayer, myFilename, theExtraKeywords=theExtraKeywords)
return myFilename # Filename of created file
示例14: tr
except CalledProcessError, e:
myMessage = tr('<p>Error while executing the following shell command:'
'</p><pre>%s</pre><p>Error message: %s'
% (myCommand, str(e)))
# shameless hack - see https://github.com/AIFDR/inasafe/issues/141
if sys.platform == 'darwin': # Mac OS X
if 'Errno 4' in str(e):
# continue as the error seems to be non critical
pass
else:
raise Exception(myMessage)
else:
raise Exception(myMessage)
# .. todo:: Check the result of the shell call is ok
myKeywordIO = KeywordIO()
myKeywordIO.copyKeywords(theLayer, myFilename,
theExtraKeywords=theExtraKeywords)
return myFilename # Filename of created file
def extentToKml(theExtent):
"""A helper to get a little kml doc for an extent so that
we can use it with gdal warp for clipping."""
myBottomLeftCorner = '%f,%f' % (theExtent[0], theExtent[1])
myTopLeftCorner = '%f,%f' % (theExtent[0], theExtent[3])
myTopRightCorner = '%f,%f' % (theExtent[2], theExtent[3])
myBottomRightCorner = '%f,%f' % (theExtent[2], theExtent[1])
myKml = ("""<?xml version="1.0" encoding="utf-8" ?>
<kml xmlns="http://www.opengis.net/kml/2.2">