def copy_fields(layer, fields_to_copy):
"""Copy fields inside an attribute table.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_copy: Dictionary of fields to copy.
:type fields_to_copy: dict
"""
for field in fields_to_copy:
index = layer.fields().lookupField(field)
if index != -1:
layer.startEditing()
source_field = layer.fields().at(index)
new_field = QgsField(source_field)
new_field.setName(fields_to_copy[field])
layer.addAttribute(new_field)
new_index = layer.fields().lookupField(fields_to_copy[field])
for feature in layer.getFeatures():
attributes = feature.attributes()
source_value = attributes[index]
layer.changeAttributeValue(
feature.id(), new_index, source_value)
layer.commitChanges()
layer.updateFields() # Avoid crash #4729
开发者ID:inasafe,项目名称:inasafe,代码行数:32,代码来源:tools.py
示例2: addField
def addField(name):
"""
Adds a field to the output, keeping the same data type as the value_field
"""
field = QgsField(value_field)
field.setName(name)
fields.append(field)
def addFieldKeepType(original, stat):
"""
Adds a field to the output, keeping the same data type as the original
"""
field = QgsField(original)
field.setName(field.name() + '_' + stat)
fields_to_join.append(field)
def addField(original, stat, type):
"""
Adds a field to the output, with a specified type
"""
field = QgsField(original)
field.setName(field.name() + '_' + stat)
field.setType(type)
if type == QVariant.Double:
field.setLength(20)
field.setPrecision(6)
fields_to_join.append(field)
def test04_EditShapefile1(self):
"""Load a file, edit and overwrite. edits: add a field, set values to the field, and then remove the field"""
self._testAvailable() or self.skipTest("Not available")
fieldName = u'\u6587\u5b57\u52172'
c0 = ord(u'\u30a2')
infile = self.testDataPath(self.layerName)
for ignore in [True, False]:
setSettingValue("/qgis/ignoreShapeEncoding", ignore)
# copy a set of shapefile
layerName = u"{}_edit{}".format(self.layerName, 1 if ignore else 2)
workfile = self.testDataPath(layerName, output=True)
copyFileSet(infile, workfile, [".shp", ".shx", ".dbf", ".prj", ".cpg"])
# load the copy
layer = self._testLayer(workfile + ".shp", output=True)
# add a field
layer.startEditing()
f = QgsField(fieldName, QVariant.String, len=20)
assert layer.addAttribute(f), "failed to add a field"
fldIdx = layer.fieldNameIndex(fieldName)
# set strings with Japanese characters to the field
c = c0
for f in layer.getFeatures():
val = "".join([unichr(c + i) for i in range(5)])
assert layer.changeAttributeValue(f.id(), fldIdx, val), "failed to change attribute value"
c += 5
# save and reload the shapefile
assert layer.commitChanges(), "failed to commit changes"
del layer
layer = self._testLayer(workfile + ".shp", output=True)
# check the values of the field
c = c0
for f in layer.getFeatures():
val = "".join([unichr(c + i) for i in range(5)])
self.assertEqual(f.attribute(fieldName), val)
c += 5
# remove the added field
layer.startEditing()
layer.deleteAttribute(fldIdx)
assert layer.commitChanges(), "failed to commit changes"
# compare the file set with source
c = compareFileSet(infile, workfile, [".shp", ".shx", ".dbf", ".prj", ".cpg"])
self.assertEqual(c, [], "input and output do not match: {}".format(str(c)))
print 'with "ignore..." option = {}...success'.format(ignore)
def combineVectorFields(layerA, layerB):
"""Create single field map from two input field maps.
"""
fields = []
fieldsA = layerA.pendingFields()
fields.extend(fieldsA)
namesA = [unicode(f.name()).lower() for f in fieldsA]
fieldsB = layerB.pendingFields()
for field in fieldsB:
name = unicode(field.name()).lower()
if name in namesA:
idx = 2
newName = name + '_' + unicode(idx)
while newName in namesA:
idx += 1
newName = name + '_' + unicode(idx)
field = QgsField(newName, field.type(), field.typeName())
fields.append(field)
return fields
开发者ID:a11656358,项目名称:QGIS,代码行数:20,代码来源:vector.py
示例8: combineFields
def combineFields(fieldsA, fieldsB):
"""Create single field map from two input field maps.
"""
fields = []
fields.extend(fieldsA)
namesA = [str(f.name()).lower() for f in fieldsA]
for field in fieldsB:
name = str(field.name()).lower()
if name in namesA:
idx = 2
newName = name + '_' + str(idx)
while newName in namesA:
idx += 1
newName = name + '_' + str(idx)
field = QgsField(newName, field.type(), field.typeName())
fields.append(field)
real_fields = QgsFields()
for f in fields:
real_fields.append(f)
return real_fields
def test_find_attribute_id(self):
field_names = ['first', 'second']
field_one = QgsField(field_names[0], QVariant.String)
field_one.setTypeName(STRING_FIELD_TYPE_NAME)
field_two = QgsField(field_names[1], QVariant.Int)
field_two.setTypeName(INT_FIELD_TYPE_NAME)
attributes = [field_one, field_two]
ProcessLayer(self.layer).add_attributes(attributes)
added_field_names = [field.name() for field in self.dp.fields()]
# Double-check that add_attributes is working properly
assert added_field_names == field_names
# Check that both attributes are correctly found
for attr_name in field_names:
try:
ProcessLayer(self.layer).find_attribute_id(attr_name)
except AttributeError:
print "We would expect both attributes to be found!"
raise
# Check that an inexistent field doesn't get found and that the
# AttributeError exception is correctly raised
with self.assertRaises(AttributeError):
ProcessLayer(self.layer).add_attributes('dummy')
def calculate_iri(
iface, current_layer, project_definition, svi_attr_id, aal_field_name, discarded_feats_ids, iri_operator=None
):
"""
Copy the AAL and calculate an IRI attribute to the current layer
"""
# set default
if iri_operator is None:
iri_operator = DEFAULT_COMBINATION
aal_weight = project_definition["children"][0]["weight"]
svi_weight = project_definition["children"][1]["weight"]
iri_attr_name = "IRI"
iri_field = QgsField(iri_attr_name, QVariant.Double)
iri_field.setTypeName(DOUBLE_FIELD_TYPE_NAME)
attr_names = ProcessLayer(current_layer).add_attributes([iri_field])
# get the id of the new attributes
iri_attr_id = ProcessLayer(current_layer).find_attribute_id(attr_names[iri_attr_name])
discarded_aal_feats_ids = []
try:
with LayerEditingManager(current_layer, "Add IRI", DEBUG):
for feat in current_layer.getFeatures():
feat_id = feat.id()
svi_value = feat.attributes()[svi_attr_id]
aal_value = feat[aal_field_name]
if aal_value == QPyNullVariant(float) or feat_id in discarded_feats_ids:
iri_value = QPyNullVariant(float)
discarded_aal_feats_ids.append(feat_id)
elif iri_operator == "Sum (simple)":
iri_value = svi_value + aal_value
elif iri_operator == "Multiplication (simple)":
iri_value = svi_value * aal_value
elif iri_operator == "Sum (weighted)":
iri_value = svi_value * svi_weight + aal_value * aal_weight
elif iri_operator == "Multiplication (weighted)":
iri_value = svi_value * svi_weight * aal_value * aal_weight
elif iri_operator == "Average (equal weights)":
# For "Average (equal weights)" it's equivalent to use
# equal weights, or to sum the indices (all weights 1)
# and divide by the number of indices (we use
# the latter solution)
iri_value = (svi_value + aal_value) / 2.0
# store IRI
current_layer.changeAttributeValue(feat_id, iri_attr_id, iri_value)
project_definition["iri_operator"] = iri_operator
# set the field name for the copied AAL layer
project_definition["aal_field"] = aal_field_name
project_definition["iri_field"] = attr_names[iri_attr_name]
msg = (
"The IRI has been calculated for fields containing "
"non-NULL values and it was added to the layer as "
"a new attribute called %s"
) % attr_names[iri_attr_name]
iface.messageBar().pushMessage(tr("Info"), tr(msg), level=QgsMessageBar.INFO)
widget = toggle_select_features_widget(
tr("Warning"),
tr("Invalid values were found in some features while calculating " "IRI"),
tr("Select invalid features"),
current_layer,
discarded_aal_feats_ids,
current_layer.selectedFeaturesIds(),
)
iface.messageBar().pushWidget(widget, QgsMessageBar.WARNING)
return iri_attr_id
except TypeError as e:
current_layer.dataProvider().deleteAttributes([iri_attr_id])
msg = "Could not calculate IRI due to data problems: %s" % e
iface.messageBar().pushMessage(tr("Error"), tr(msg), level=QgsMessageBar.CRITICAL)
def saveAutoField( self ):
""" Do some validation and then call AutoFieldManager """
# Check layers
if not self.tblLayers.selectedItems():
self.msg.show( QApplication.translate( "AutoFieldsDockWidgetPy",
"[Warning] Please first select a layer." ), 'warning' )
return
# Check expression
expression = u''
if self.optXCoord.isChecked():
expression = u'$x'
elif self.optYCoord.isChecked():
expression = u'$y'
elif self.optLength.isChecked():
expression = u'$length'
elif self.optPerimeter.isChecked():
expression = u'$perimeter'
elif self.optArea.isChecked():
expression = u'$area'
elif self.optDate.isChecked():
expression = u'now()'
elif self.optCustomExpression.isChecked():
if self.expressionDlg:
expression = self.expressionDlg.expression
if not self.expressionDlg or not expression:
self.msg.show( QApplication.translate( "AutoFieldsDockWidgetPy",
"[Warning] Please first set a valid custom expression." ),
'warning' )
return
else: # optSpatialValue
pass
# Check fields
fieldName = ''
if self.optNewField.isChecked():
if self.txtFieldName.text():
fieldName = self.txtFieldName.text().strip()
newField = QgsField( fieldName,
self.cboFieldType.itemData( self.cboFieldType.currentIndex(), Qt.UserRole) )
length = self.txtFieldLength.value()
precision = self.txtFieldPrecision.value()
# Ensure length and precision are valid values when dealing with Real numbers
if self.fieldTypesDict[self.cboFieldType.currentIndex()] == 'Real':
if precision > length:
precision = length
newField.setLength( length )
newField.setPrecision( precision )
for item in self.tblLayers.selectedItems():
if item.column() == 1: # It's the layer name item
layer = QgsMapLayerRegistry.instance().mapLayer( item.data( Qt.UserRole ) )
if layer.fieldNameIndex( fieldName ) != -1:
self.msg.show(
QApplication.translate( "AutoFieldsDockWidgetPy",
"[Error] The field " ) + fieldName + \
QApplication.translate( "AutoFieldsDockWidgetPy",
" already exists in layer " ) + layer.name() + ". " + \
QApplication.translate( "AutoFieldsDockWidgetPy",
" If you want to create an AutoField on it, you need to choose it from 'Existing Field' list." ),
'warning' )
else:
res = layer.dataProvider().addAttributes( [ newField ] )
if res:
layer.updateFields()
# Check if fieldName is preserved by the provider after field creation.
if layer.fieldNameIndex( fieldName ) == -1:
self.msg.show(
QApplication.translate( "AutoFieldsDockWidgetPy",
"[Error] The field " ) + fieldName + \
QApplication.translate( "AutoFieldsDockWidgetPy",
" was probably created with another name by the layer (" ) + \
layer.name() + \
QApplication.translate( "AutoFieldsDockWidgetPy",
") provider. " ) + \
QApplication.translate( "AutoFieldsDockWidgetPy",
" If you want to create an AutoField on it, you need to choose it from 'Existing Field' list." ),
'warning' )
else:
self.doSaveAutoField( layer, fieldName, expression )
else:
self.msg.show( QApplication.translate( "AutoFieldsDockWidgetPy",
"[Error] Couldn't create " ) + newField.name() + \
QApplication.translate( "AutoFieldsDockWidgetPy",
" field in " ) + layer.name() + \
QApplication.translate( "AutoFieldsDockWidgetPy", " layer." ),
'warning' )
# Some fields might have been created, update the field list once
self.updateFieldList()
else:
self.msg.show( QApplication.translate( "AutoFieldsDockWidgetPy",
"[Warning] Please first set a name for the new field." ), 'warning' )
#.........这里部分代码省略.........
def run(self):
"""Specific stuff at tool activating."""
cur_carhab_lyr = CarhabLayerRegistry.instance().getCurrentCarhabLayer()
if not cur_carhab_lyr:
no_carhab_lyr_msg()
return
csv_dir = QFileDialog.getExistingDirectory(None, "Select a folder:", None, QFileDialog.ShowDirsOnly)
if csv_dir:
now = time.strftime("%Y-%m-%d-%H%M%S")
directory = os.path.join(csv_dir, cur_carhab_lyr.getName() + "_" + now)
if not os.path.exists(directory):
os.makedirs(directory)
for tbl_name, desc in Config.DB_STRUCTURE:
file_name = desc.get("std_name")
tbl_fields = desc.get("fields")
if file_name:
if not desc.get("spatial"):
csv_name = file_name if file_name.endswith(".csv") else file_name + ".csv"
csv_path = os.path.join(directory, csv_name)
field_names = [row[1].get("std_name") for row in tbl_fields if row[1].get("std_name")]
db = DbManager(cur_carhab_lyr.dbPath)
r = Recorder(db, tbl_name)
tbl_rows = r.select_all()
csv_rows = []
for tbl_row in tbl_rows:
csv_row = {}
for dbf, value in tbl_row.items():
for field in desc.get("fields"):
if dbf == field[0] and field[1].get("std_name"):
csv_row[encode(field[1].get("std_name"))] = encode(value)
break
csv_rows.append(csv_row)
with open(csv_path, "wb") as csv_file:
writer = csv.DictWriter(csv_file, field_names)
writer.writeheader()
writer.writerows(csv_rows)
else:
for vlyr in cur_carhab_lyr.getQgisLayers():
vlyr_tbl = QgsDataSourceURI(vlyr.dataProvider().dataSourceUri()).table()
if tbl_name == vlyr_tbl:
shp_name = file_name if file_name.endswith(".shp") else file_name + ".shp"
shp_path = os.path.join(directory, shp_name)
QgsVectorFileWriter.writeAsVectorFormat(vlyr, shp_path, "utf-8", None)
shp_lyr = QgsVectorLayer(shp_path, "", "ogr")
shapefile = shp_lyr.dataProvider()
features = shapefile.getFeatures()
attrs_to_del = []
for attr, attr_desc in tbl_fields:
std_attr = attr_desc.get("std_name")
if not std_attr == attr:
if std_attr:
cur_field = shapefile.fields().field(attr)
new_field = QgsField(cur_field)
new_field.setName(std_attr)
shapefile.addAttributes([new_field])
for feat in features:
idx = shapefile.fields().indexFromName(std_attr)
update_map = {feat.id(): {idx: feat[attr]}}
shapefile.changeAttributeValues(update_map)
attrs_to_del.append(shapefile.fields().indexFromName(attr))
shapefile.deleteAttributes(attrs_to_del)
popup("Export effectué")
开发者ID:IGNF,项目名称:saisie_carhab,代码行数:65,代码来源:fse.py
示例16: create_field_from_definition
def create_field_from_definition(field_definition, name=None, sub_name=None):
"""Helper to create a field from definition.
:param field_definition: The definition of the field (see:
safe.definitions.fields).
:type field_definition: dict
:param name: The name is required if the field name is dynamic and need a
string formatting.
:type name: basestring
:param sub_name: The name is required if the field name is dynamic and need
a string formatting.
:type sub_name: basestring
:return: The new field.
:rtype: QgsField
"""
field = QgsField()
if name and not sub_name:
field.setName(field_definition['field_name'] % name)
elif name and sub_name:
field.setName(field_definition['field_name'] % (name, sub_name))
else:
field.setName(field_definition['field_name'])
if isinstance(field_definition['type'], list):
# Use the first element in the list of type
field.setType(field_definition['type'][0])
else:
field.setType(field_definition['type'])
field.setLength(field_definition['length'])
field.setPrecision(field_definition['precision'])
return field
开发者ID:inasafe,项目名称:inasafe,代码行数:35,代码来源:tools.py
示例17: reclassify
def reclassify(layer, exposure_key=None):
"""Reclassify a continuous vector layer.
This function will modify the input.
For instance if you want to reclassify like this table :
Original Value | Class
- ∞ < val <= 0 | 1
0 < val <= 0.5 | 2
0.5 < val <= 5 | 3
5 < val < + ∞ | 6
You need a dictionary :
ranges = OrderedDict()
ranges[1] = [None, 0]
ranges[2] = [0.0, 0.5]
ranges[3] = [0.5, 5]
ranges[6] = [5, None]
:param layer: The raster layer.
:type layer: QgsRasterLayer
:param exposure_key: The exposure key.
:type exposure_key: str
:return: The classified vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
output_layer_name = reclassify_vector_steps['output_layer_name']
output_layer_name = output_layer_name % layer.keywords['title']
# This layer should have this keyword, or it's a mistake from the dev.
inasafe_fields = layer.keywords['inasafe_fields']
continuous_column = inasafe_fields[hazard_value_field['key']]
if exposure_key:
classification_key = active_classification(
layer.keywords, exposure_key)
thresholds = active_thresholds_value_maps(layer.keywords, exposure_key)
layer.keywords['thresholds'] = thresholds
layer.keywords['classification'] = classification_key
else:
classification_key = layer.keywords.get('classification')
thresholds = layer.keywords.get('thresholds')
if not thresholds:
raise InvalidKeywordsForProcessingAlgorithm(
'thresholds are missing from the layer %s'
% layer.keywords['layer_purpose'])
continuous_index = layer.fields().lookupField(continuous_column)
classified_field = QgsField()
classified_field.setType(hazard_class_field['type'])
classified_field.setName(hazard_class_field['field_name'])
classified_field.setLength(hazard_class_field['length'])
classified_field.setPrecision(hazard_class_field['precision'])
layer.startEditing()
layer.addAttribute(classified_field)
classified_field_index = layer.fields(). \
lookupField(classified_field.name())
for feature in layer.getFeatures():
attributes = feature.attributes()
source_value = attributes[continuous_index]
classified_value = reclassify_value(source_value, thresholds)
if (classified_value is None
or (hasattr(classified_value, 'isNull')
and classified_value.isNull())):
layer.deleteFeature(feature.id())
else:
layer.changeAttributeValue(
feature.id(), classified_field_index, classified_value)
layer.commitChanges()
layer.updateFields()
# We transfer keywords to the output.
inasafe_fields[hazard_class_field['key']] = (
hazard_class_field['field_name'])
value_map = {}
hazard_classes = definition(classification_key)['classes']
for hazard_class in reversed(hazard_classes):
value_map[hazard_class['key']] = [hazard_class['value']]
layer.keywords['value_map'] = value_map
layer.keywords['title'] = output_layer_name
check_layer(layer)
return layer
def calculate_svi(
iface, current_layer, project_definition, indicators_operator=None, themes_operator=None, reuse_field=False
):
"""
add an SVI attribute to the current layer
"""
# set default
if indicators_operator is None:
indicators_operator = DEFAULT_COMBINATION
if themes_operator is None:
themes_operator = DEFAULT_COMBINATION
themes = project_definition["children"][1]["children"]
if reuse_field and "svi_field" in project_definition:
svi_attr_name = project_definition["svi_field"]
if DEBUG:
print "Reusing %s" % svi_attr_name
else:
svi_attr_name = "SVI"
svi_field = QgsField(svi_attr_name, QVariant.Double)
svi_field.setTypeName(DOUBLE_FIELD_TYPE_NAME)
attr_names = ProcessLayer(current_layer).add_attributes([svi_field])
svi_attr_name = attr_names[svi_attr_name]
# get the id of the new attribute
svi_attr_id = ProcessLayer(current_layer).find_attribute_id(svi_attr_name)
discarded_feats_ids = []
try:
with LayerEditingManager(current_layer, "Add SVI", DEBUG):
for feat in current_layer.getFeatures():
# If a feature contains any NULL value, discard_feat will
# be set to True and the corresponding SVI will be set to
# NULL
discard_feat = False
feat_id = feat.id()
# init svi_value to the correct value depending on
# themes_operator
if themes_operator in SUM_BASED_COMBINATIONS:
svi_value = 0
elif themes_operator in MUL_BASED_COMBINATIONS:
svi_value = 1
# iterate all themes of SVI
for theme in themes:
indicators = theme["children"]
# init theme_result to the correct value depending on
# indicators_operator
if indicators_operator in SUM_BASED_COMBINATIONS:
theme_result = 0
elif indicators_operator in MUL_BASED_COMBINATIONS:
theme_result = 1
# iterate all indicators of a theme
for indicator in indicators:
if feat[indicator["field"]] == QPyNullVariant(float):
discard_feat = True
discarded_feats_ids.append(feat_id)
break
# For "Average (equal weights)" it's equivalent to use
# equal weights, or to sum the indicators
# (all weights 1)
# and divide by the number of indicators (we use
# the latter solution)
if indicators_operator in (
"Sum (simple)",
"Average (equal weights)",
"Multiplication (simple)",
):
indicator_weighted = feat[indicator["field"]]
else:
indicator_weighted = feat[indicator["field"]] * indicator["weight"]
if indicators_operator in SUM_BASED_COMBINATIONS:
theme_result += indicator_weighted
elif indicators_operator in MUL_BASED_COMBINATIONS:
theme_result *= indicator_weighted
else:
error_message = "invalid indicators_operator: %s" % indicators_operator
raise RuntimeError(error_message)
if discard_feat:
break
if indicators_operator == "Average (equal weights)":
theme_result /= len(indicators)
# combine the indicators of each theme
# For "Average (equal weights)" it's equivalent to use
# equal weights, or to sum the themes (all weights 1)
# and divide by the number of themes (we use
# the latter solution)
if themes_operator in ("Sum (simple)", "Average (equal weights)", "Multiplication (simple)"):
theme_weighted = theme_result
else:
theme_weighted = theme_result * theme["weight"]
if themes_operator in SUM_BASED_COMBINATIONS:
svi_value += theme_weighted
#.........这里部分代码省略.........
def on_btnRun_clicked(self):
#Check for combo and list box selections
if self.ui.cmbBaseLayer.count() < 1 or self.ui.cmbProcessLayer.count() < 1:
QMessageBox.critical(self, 'Vector Geoprocessor', 'Invalid layer selection.')
return
if len(self.ui.listFields.selectedItems()) < 1:
QMessageBox.critical(self, 'Vector Geoprocessor', 'Invalid field selection.')
return
#Initializations
self.ui.ProgressBar.setValue(0)
self.setCursor(Qt.WaitCursor)
data = []
#Add new attributes to base layer
bprovider = self.blayer.dataProvider()
pprovider = self.player.dataProvider()
pfields = pprovider.fields()
for item in self.ui.listFields.selectedItems():
fname = item.text()
for fld in pfields.toList():
if fname == fld.name():
newfield = QgsField()
newfield.setName(fld.name())
newfield.setType(fld.type())
newfield.setTypeName(fld.typeName())
newfield.setLength(fld.length())
newfield.setPrecision(fld.precision())
newfield.setComment(fld.comment())
bprovider.addAttributes([newfield])
#Create a spatial index for faster processing
spindex = QgsSpatialIndex()
for pfeat in pprovider.getFeatures():
spindex.insertFeature(pfeat)
#Find the intersection of process layer features with base layer
#To increase speed, intersect with a bounding box rectangle first
#Then further process within the geometric shape
#Add requested processed information to base layer
featreq = QgsFeatureRequest()
bfields = bprovider.fields()
ddic = {}
len1 = len(self.ui.listFields.selectedItems())
len2 = len(bfields)
b1 = 0
b2 = bprovider.featureCount()
attr={}
for bfeat in bprovider.getFeatures():
b1+=1
attr.clear()
bgeom = bfeat.geometry()
intersect = spindex.intersects(bgeom.boundingBox())
data[:] = []
for fid in intersect:
pfeat = self.player.getFeatures(featreq.setFilterFid(fid)).next()
if pfeat.geometry().intersects(bgeom) == False:
data.append(fid)
for fid in data:
intersect.pop(intersect.index(fid))
count = 0
for item in self.ui.listFields.selectedItems():
pfindx = pprovider.fieldNameIndex(item.text())
if pfindx < 0:
self.setCursor(Qt.ArrowCursor)
QMessageBox.critical(self, 'Vector Geoprocessor', 'Processing error.')
return
data[:] = []
for fid in intersect:
pfeat = self.player.getFeatures(featreq.setFilterFid(fid)).next()
if self.oindex in [0,1,2,3,4]:
data.append(float(pfeat.attribute(item.text())))
elif self.oindex in [5,6]:
data.append(str(pfeat.attribute(item.text())))
if len(data) == 0:
value = None
elif self.oindex == 0: #Find mean value of points within polygons
value = sum(data)/float(len(data))
elif self.oindex == 1: #Find median value of points within polygons
data = sorted(data)
lendata = len(data)
if lendata % 2:
value = data[(lendata+1)/2-1]
else:
d1 = data[lendata/2-1]
d2 = data[lendata/2]
value = (d1 + d2)/2.0
elif self.oindex == 2: #Find maximum value of points within polygons
value = max(data)
elif self.oindex == 3: #Find minimum value of points within polygons
value = min(data)
elif self.oindex == 4: #Find mean value (area-weighted) of polygons within polygons
value = 0.0
totalarea = 0.0
for fid in intersect:
pfeat = self.player.getFeatures(featreq.setFilterFid(fid)).next()
pgeom = pfeat.geometry()
isect = bgeom.intersection(pgeom)
#.........这里部分代码省略.........
请发表评论