本文整理汇总了Python中safe.common.utilities.create_label函数的典型用法代码示例。如果您正苦于以下问题:Python create_label函数的具体用法?Python create_label怎么用?Python create_label使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了create_label函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_create_label
def test_create_label(self):
"""Test create label.
"""
the_tuple = ('1', '2')
extra_label = 'Low damage'
result = create_label(the_tuple)
expected = '[1 - 2]'
self.assertEqual(result, expected)
result = create_label(the_tuple, extra_label)
expected = '[1 - 2] Low damage'
self.assertEqual(result, expected)
示例2: test_create_label
def test_create_label(self):
"""Test create label.
"""
my_tuple = ('1', '2')
my_extra_label = 'Low damage'
my_result = create_label(my_tuple)
my_expected = '[1 - 2]'
assert my_result == my_expected, ' %s is not same with %s' % (
my_result, my_expected)
my_result = create_label(my_tuple, my_extra_label)
my_expected = '[1 - 2] Low damage'
assert my_result == my_expected, ' %s is not same with %s' % (
my_result, my_expected)
示例3: run
#.........这里部分代码省略.........
col_span=2)]),
TableRow([tr('Evacuation threshold'), '%s%%' % format_int(
self.parameters['evacuation_percentage'])], header=True),
TableRow(tr(
'Map shows the number of people affected in each flood prone '
'area')),
TableRow(tr(
'Table below shows the weekly minimum needs for all '
'evacuated people'))]
total_needs = evacuated_population_needs(
evacuated, minimum_needs)
for frequency, needs in total_needs.items():
table_body.append(TableRow(
[
tr('Needs should be provided %s' % frequency),
tr('Total')
],
header=True))
for resource in needs:
table_body.append(TableRow([
tr(resource['table name']),
format_int(resource['amount'])]))
impact_table = Table(table_body).toNewlineFreeString()
table_body.append(TableRow(tr('Action Checklist:'), header=True))
table_body.append(TableRow(tr('How will warnings be disseminated?')))
table_body.append(TableRow(tr('How will we reach stranded people?')))
table_body.append(TableRow(tr('Do we have enough relief items?')))
table_body.append(TableRow(
'If yes, where are they located and how will we distribute '
'them?'))
table_body.append(TableRow(
'If no, where can we obtain additional relief items from and '
'how will we transport them to here?'))
# Extend impact report for on-screen display
table_body.extend([
TableRow(tr('Notes'), header=True),
tr('Total population: %s') % format_int(total),
tr('People need evacuation if in the area identified as '
'"Flood Prone"'),
tr('Minimum needs are defined in BNPB regulation 7/2008')])
impact_summary = Table(table_body).toNewlineFreeString()
# Create style
# Define classes for legend for flooded population counts
colours = ['#FFFFFF', '#38A800', '#79C900', '#CEED00',
'#FFCC00', '#FF6600', '#FF0000', '#7A0000']
population_counts = [x['population'] for x in new_attributes]
classes = create_classes(population_counts, len(colours))
interval_classes = humanize_class(classes)
# Define style info for output polygons showing population counts
style_classes = []
for i in xrange(len(colours)):
style_class = dict()
style_class['label'] = create_label(interval_classes[i])
if i == 0:
transparency = 0
style_class['min'] = 0
else:
transparency = 0
style_class['min'] = classes[i - 1]
style_class['transparency'] = transparency
style_class['colour'] = colours[i]
style_class['max'] = classes[i]
style_classes.append(style_class)
# Override style info with new classes and name
style_info = dict(target_field=self.target_field,
style_classes=style_classes,
style_type='graduatedSymbol')
# For printing map purpose
map_title = tr('People affected by flood prone areas')
legend_notes = tr('Thousand separator is represented by \'.\'')
legend_units = tr('(people per polygon)')
legend_title = tr('Population Count')
# Create vector layer and return
vector_layer = Vector(
data=new_attributes,
projection=hazard_layer.get_projection(),
geometry=hazard_layer.get_geometry(),
name=tr('People affected by flood prone areas'),
keywords={
'impact_summary': impact_summary,
'impact_table': impact_table,
'target_field': self.target_field,
'map_title': map_title,
'legend_notes': legend_notes,
'legend_units': legend_units,
'legend_title': legend_title,
'affected_population': affected_population,
'total_population': total,
'total_needs': total_needs},
style_info=style_info)
return vector_layer
示例4: run
#.........这里部分代码省略.........
self.hazard_class_mapping[vector_hazard_class["name"]] = self.hazard_class_mapping.pop(
vector_hazard_class["key"]
)
# Adding the class name as a key in affected_building
self.affected_population[vector_hazard_class["name"]] = 0
# Interpolated layer represents grid cell that lies in the polygon
interpolated_layer, covered_exposure_layer = assign_hazard_values_to_exposure_data(
self.hazard.layer, self.exposure.layer, attribute_name=self.target_field
)
# Count total affected population per hazard zone
for row in interpolated_layer.get_data():
# Get population at this location
population = row[self.target_field]
if not numpy.isnan(population):
population = float(population)
# Update population count for this hazard zone
hazard_value = get_key_for_value(row[self.hazard_class_attribute], self.hazard_class_mapping)
if not hazard_value:
hazard_value = self._not_affected_value
self.affected_population[hazard_value] += population
# Count total population from exposure layer
self.total_population = int(numpy.nansum(self.exposure.layer.get_data()))
# Count total affected population
total_affected_population = self.total_affected_population
self.unaffected_population = self.total_population - total_affected_population
self.minimum_needs = [
parameter.serialize() for parameter in filter_needs_parameters(self.parameters["minimum needs"])
]
# check for zero impact
if total_affected_population == 0:
message = no_population_impact_message(self.question)
raise ZeroImpactException(message)
impact_table = impact_summary = self.html_report()
# Create style
colours = ["#FFFFFF", "#38A800", "#79C900", "#CEED00", "#FFCC00", "#FF6600", "#FF0000", "#7A0000"]
classes = create_classes(covered_exposure_layer.get_data().flat[:], len(colours))
interval_classes = humanize_class(classes)
# Define style info for output polygons showing population counts
style_classes = []
for i in xrange(len(colours)):
style_class = dict()
style_class["label"] = create_label(interval_classes[i])
if i == 1:
label = create_label(interval_classes[i], tr("Low Population [%i people/cell]" % classes[i]))
elif i == 4:
label = create_label(interval_classes[i], tr("Medium Population [%i people/cell]" % classes[i]))
elif i == 7:
label = create_label(interval_classes[i], tr("High Population [%i people/cell]" % classes[i]))
else:
label = create_label(interval_classes[i])
style_class["label"] = label
style_class["quantity"] = classes[i]
style_class["colour"] = colours[i]
style_class["transparency"] = 0
style_classes.append(style_class)
# Override style info with new classes and name
style_info = dict(target_field=None, style_classes=style_classes, style_type="rasterStyle")
# For printing map purpose
map_title = tr("People impacted by each hazard zone")
legend_title = tr("Population")
legend_units = tr("(people per cell)")
legend_notes = tr("Thousand separator is represented by %s" % get_thousand_separator())
extra_keywords = {
"impact_summary": impact_summary,
"impact_table": impact_table,
"target_field": self.target_field,
"map_title": map_title,
"legend_notes": legend_notes,
"legend_units": legend_units,
"legend_title": legend_title,
}
self.set_if_provenance()
impact_layer_keywords = self.generate_impact_keywords(extra_keywords)
# Create vector layer and return
impact_layer = Raster(
data=covered_exposure_layer.get_data(),
projection=covered_exposure_layer.get_projection(),
geotransform=covered_exposure_layer.get_geotransform(),
name=tr("People impacted by each hazard zone"),
keywords=impact_layer_keywords,
style_info=style_info,
)
self._impact = impact_layer
return impact_layer
示例5: run
#.........这里部分代码省略.........
[tr('Clean Water [l]'), format_int(tot_needs['water'])],
[tr('Family Kits'), format_int(tot_needs['family_kits'])],
[tr('Toilets'), format_int(tot_needs['toilets'])]]
table_body.append(TableRow(tr('Action Checklist:'), header=True))
table_body.append(TableRow(tr('How will warnings be disseminated?')))
table_body.append(TableRow(tr('How will we reach stranded people?')))
table_body.append(TableRow(tr('Do we have enough relief items?')))
table_body.append(TableRow(tr('If yes, where are they located and how '
'will we distribute them?')))
table_body.append(TableRow(tr(
'If no, where can we obtain additional relief items from and how '
'will we transport them to here?')))
# Extend impact report for on-screen display
table_body.extend([
TableRow(tr('Notes'), header=True),
tr('Total population: %s') % format_int(total),
tr('People need evacuation if flood levels exceed %(eps).1f m') %
{'eps': thresholds[-1]},
tr('Minimum needs are defined in BNPB regulation 7/2008'),
tr('All values are rounded up to the nearest integer in order to '
'avoid representing human lives as fractionals.')])
if len(counts) > 1:
table_body.append(TableRow(tr('Detailed breakdown'), header=True))
for i, val in enumerate(counts[:-1]):
s = (tr('People in %(lo).1f m to %(hi).1f m of water: %(val)i')
% {'lo': thresholds[i],
'hi': thresholds[i + 1],
'val': format_int(val)})
table_body.append(TableRow(s, header=False))
# Result
impact_summary = Table(table_body).toNewlineFreeString()
impact_table = impact_summary
# check for zero impact
if numpy.nanmax(my_impact) == 0 == numpy.nanmin(my_impact):
table_body = [
question,
TableRow([(tr('People in %.1f m of water') % thresholds[-1]),
'%s' % format_int(evacuated)],
header=True)]
my_message = Table(table_body).toNewlineFreeString()
raise ZeroImpactException(my_message)
# Create style
colours = ['#FFFFFF', '#38A800', '#79C900', '#CEED00',
'#FFCC00', '#FF6600', '#FF0000', '#7A0000']
classes = create_classes(my_impact.flat[:], len(colours))
interval_classes = humanize_class(classes)
style_classes = []
for i in xrange(len(colours)):
style_class = dict()
if i == 1:
label = create_label(interval_classes[i], 'Low')
elif i == 4:
label = create_label(interval_classes[i], 'Medium')
elif i == 7:
label = create_label(interval_classes[i], 'High')
else:
label = create_label(interval_classes[i])
style_class['label'] = label
style_class['quantity'] = classes[i]
if i == 0:
transparency = 100
else:
transparency = 0
style_class['transparency'] = transparency
style_class['colour'] = colours[i]
style_classes.append(style_class)
style_info = dict(target_field=None,
style_classes=style_classes,
style_type='rasterStyle')
# For printing map purpose
map_title = tr('People in need of evacuation')
legend_notes = tr('Thousand separator is represented by %s' %
get_thousand_separator())
legend_units = tr('(people per cell)')
legend_title = tr('Population density')
# Create raster object and return
R = Raster(my_impact,
projection=my_hazard.get_projection(),
geotransform=my_hazard.get_geotransform(),
name=tr('Population which %s') % (
get_function_title(self).lower()),
keywords={'impact_summary': impact_summary,
'impact_table': impact_table,
'map_title': map_title,
'legend_notes': legend_notes,
'legend_units': legend_units,
'legend_title': legend_title},
style_info=style_info)
return R
示例6: run
def run(self):
"""Risk plugin for tsunami population evacuation.
Counts number of people exposed to tsunami levels exceeding
specified threshold.
:returns: Map of population exposed to tsunami levels exceeding the
threshold. Table with number of people evacuated and supplies
required.
:rtype: tuple
"""
self.validate()
self.prepare()
# Determine depths above which people are regarded affected [m]
# Use thresholds from inundation layer if specified
thresholds = self.parameters['thresholds'].value
verify(
isinstance(thresholds, list),
'Expected thresholds to be a list. Got %s' % str(thresholds))
# Extract data as numeric arrays
data = self.hazard.layer.get_data(nan=True) # Depth
if has_no_data(data):
self.no_data_warning = True
# Calculate impact as population exposed to depths > max threshold
population = self.exposure.layer.get_data(nan=True, scaling=True)
if has_no_data(population):
self.no_data_warning = True
# merely initialize
impact = None
for i, lo in enumerate(thresholds):
if i == len(thresholds) - 1:
# The last threshold
thresholds_name = tr(
'People in >= %.1f m of water') % lo
impact = medium = numpy.where(data >= lo, population, 0)
self.impact_category_ordering.append(thresholds_name)
self._evacuation_category = thresholds_name
else:
# Intermediate thresholds
hi = thresholds[i + 1]
thresholds_name = tr(
'People in %.1f m to %.1f m of water' % (lo, hi))
medium = numpy.where((data >= lo) * (data < hi), population, 0)
# Count
val = int(numpy.nansum(medium))
self.affected_population[thresholds_name] = val
# Carry the no data values forward to the impact layer.
impact = numpy.where(numpy.isnan(population), numpy.nan, impact)
impact = numpy.where(numpy.isnan(data), numpy.nan, impact)
# Count totals
self.total_population = int(numpy.nansum(population))
self.unaffected_population = (
self.total_population - self.total_affected_population)
self.minimum_needs = [
parameter.serialize() for parameter in
filter_needs_parameters(self.parameters['minimum needs'])
]
impact_table = impact_summary = self.html_report()
# check for zero impact
if numpy.nanmax(impact) == 0 == numpy.nanmin(impact):
message = m.Message()
message.add(self.question)
message.add(tr('No people in %.1f m of water') % thresholds[-1])
message = message.to_html(suppress_newlines=True)
raise ZeroImpactException(message)
# Create style
colours = [
'#FFFFFF', '#38A800', '#79C900', '#CEED00',
'#FFCC00', '#FF6600', '#FF0000', '#7A0000']
classes = create_classes(impact.flat[:], len(colours))
interval_classes = humanize_class(classes)
style_classes = []
for i in xrange(len(colours)):
style_class = dict()
if i == 1:
label = create_label(interval_classes[i], 'Low')
elif i == 4:
label = create_label(interval_classes[i], 'Medium')
elif i == 7:
label = create_label(interval_classes[i], 'High')
else:
label = create_label(interval_classes[i])
style_class['label'] = label
style_class['quantity'] = classes[i]
if i == 0:
transparency = 100
else:
#.........这里部分代码省略.........
示例7: run
#.........这里部分代码省略.........
categories = {}
for attr in new_attributes:
attr[self.target_field] = 0
cat = attr[category_title]
categories[cat] = 0
# Count impacted building per polygon and total
for attr in P.get_data():
# Update building count for associated polygon
poly_id = attr['polygon_id']
if poly_id is not None:
new_attributes[poly_id][self.target_field] += 1
# Update building count for each category
cat = new_attributes[poly_id][category_title]
categories[cat] += 1
# Count totals
total = len(my_exposure)
# Generate simple impact report
blank_cell = ''
table_body = [question,
TableRow([tr('Volcanos considered'),
'%s' % volcano_names, blank_cell],
header=True),
TableRow([tr('Distance [km]'), tr('Total'),
tr('Cumulative')],
header=True)]
cum = 0
for name in category_names:
# prevent key error
count = categories.get(name, 0)
cum += count
if is_point_data:
name = int(name) / 1000
table_body.append(TableRow([name, format_int(count),
format_int(cum)]))
table_body.append(TableRow(tr('Map shows buildings affected in '
'each of volcano hazard polygons.')))
impact_table = Table(table_body).toNewlineFreeString()
# Extend impact report for on-screen display
table_body.extend([TableRow(tr('Notes'), header=True),
tr('Total number of buildings %s in the viewable '
'area') % format_int(total),
tr('Only buildings available in OpenStreetMap '
'are considered.')])
impact_summary = Table(table_body).toNewlineFreeString()
map_title = tr('Buildings affected by volcanic hazard zone')
# Create style
colours = ['#FFFFFF', '#38A800', '#79C900', '#CEED00',
'#FFCC00', '#FF6600', '#FF0000', '#7A0000']
building_counts = [x[self.target_field] for x in new_attributes]
classes = create_classes(building_counts, len(colours))
interval_classes = humanize_class(classes)
style_classes = []
for i in xrange(len(colours)):
style_class = dict()
style_class['label'] = create_label(interval_classes[i])
if i == 0:
transparency = 100
style_class['min'] = 0
else:
transparency = 30
style_class['min'] = classes[i - 1]
style_class['transparency'] = transparency
style_class['colour'] = colours[i]
style_class['max'] = classes[i]
style_classes.append(style_class)
# Override style info with new classes and name
style_info = dict(target_field=self.target_field,
style_classes=style_classes,
style_type='graduatedSymbol')
# For printing map purpose
map_title = tr('Building affected by volcanic hazard zone')
legend_notes = tr('Thousand separator is represented by \'.\'')
legend_units = tr('(building)')
legend_title = tr('Building count')
# Create vector layer and return
V = Vector(data=new_attributes,
projection=my_hazard.get_projection(),
geometry=my_hazard.get_geometry(as_geometry_objects=True),
name=tr('Buildings affected by volcanic hazard zone'),
keywords={'impact_summary': impact_summary,
'impact_table': impact_table,
'target_field': self.target_field,
'map_title': map_title,
'legend_notes': legend_notes,
'legend_units': legend_units,
'legend_title': legend_title},
style_info=style_info)
return V
示例8: run
#.........这里部分代码省略.........
high_exposure = numpy.where(
(hazard_data >= medium_t) & (hazard_data <= high_t),
exposure_data, 0)
impacted_exposure = low_exposure + medium_exposure + high_exposure
# Count totals
total = int(numpy.nansum(exposure_data))
low_total = int(numpy.nansum(low_exposure))
medium_total = int(numpy.nansum(medium_exposure))
high_total = int(numpy.nansum(high_exposure))
total_impact = high_total + medium_total + low_total
# Check for zero impact
if total_impact == 0:
table_body = [
self.question,
TableRow(
[tr('People impacted'),
'%s' % format_int(total_impact)], header=True)]
message = Table(table_body).toNewlineFreeString()
raise ZeroImpactException(message)
# Don't show digits less than a 1000
total = population_rounding(total)
total_impact = population_rounding(total_impact)
low_total = population_rounding(low_total)
medium_total = population_rounding(medium_total)
high_total = population_rounding(high_total)
minimum_needs = [
parameter.serialize() for parameter in
self.parameters['minimum needs']
]
table_body = self._tabulate(
high_total, low_total, medium_total, self.question, total_impact)
impact_table = Table(table_body).toNewlineFreeString()
table_body, total_needs = self._tabulate_notes(
minimum_needs, table_body, total, total_impact, no_data_warning)
impact_summary = Table(table_body).toNewlineFreeString()
map_title = tr('People in each hazard areas (low, medium, high)')
# Style for impact layer
colours = [
'#FFFFFF', '#38A800', '#79C900', '#CEED00',
'#FFCC00', '#FF6600', '#FF0000', '#7A0000']
classes = create_classes(impacted_exposure.flat[:], len(colours))
interval_classes = humanize_class(classes)
style_classes = []
for i in xrange(len(colours)):
style_class = dict()
if i == 1:
label = create_label(
interval_classes[i],
tr('Low Population [%i people/cell]' % classes[i]))
elif i == 4:
label = create_label(
interval_classes[i],
tr('Medium Population [%i people/cell]' % classes[i]))
elif i == 7:
label = create_label(
interval_classes[i],
tr('High Population [%i people/cell]' % classes[i]))
else:
label = create_label(interval_classes[i])
style_class['label'] = label
style_class['quantity'] = classes[i]
if i == 0:
transparency = 100
else:
transparency = 0
style_class['transparency'] = transparency
style_class['colour'] = colours[i]
style_classes.append(style_class)
style_info = dict(
target_field=None,
style_classes=style_classes,
style_type='rasterStyle')
# Create raster object and return
raster_layer = Raster(
data=impacted_exposure,
projection=hazard_layer.get_projection(),
geotransform=hazard_layer.get_geotransform(),
name=tr('Population might %s') % (
self.impact_function_manager.
get_function_title(self).lower()),
keywords={
'impact_summary': impact_summary,
'impact_table': impact_table,
'map_title': map_title,
'total_needs': total_needs},
style_info=style_info)
self._impact = raster_layer
return raster_layer
示例9: run
#.........这里部分代码省略.........
evacuated, rounding_evacuated = population_rounding_full(evacuated)
# Generate impact report for the pdf map
table_body, total_needs = self._tabulate(
total_affected_population,
evacuated,
minimum_needs,
self.question,
rounding,
rounding_evacuated)
impact_table = Table(table_body).toNewlineFreeString()
self._tabulate_action_checklist(
table_body,
total_population,
nan_warning)
impact_summary = Table(table_body).toNewlineFreeString()
# Create style
colours = ['#FFFFFF', '#38A800', '#79C900', '#CEED00',
'#FFCC00', '#FF6600', '#FF0000', '#7A0000']
classes = create_classes(
new_covered_exposure_data.flat[:], len(colours))
# check for zero impact
if min(classes) == 0 == max(classes):
table_body = [
self.question,
TableRow(
[tr('People affected'),
'%s' % format_int(total_affected_population)],
header=True)]
message = Table(table_body).toNewlineFreeString()
raise ZeroImpactException(message)
interval_classes = humanize_class(classes)
# Define style info for output polygons showing population counts
style_classes = []
for i in xrange(len(colours)):
style_class = dict()
style_class['label'] = create_label(interval_classes[i])
if i == 1:
label = create_label(
interval_classes[i],
tr('Low Population [%i people/cell]' % classes[i]))
elif i == 4:
label = create_label(
interval_classes[i],
tr('Medium Population [%i people/cell]' % classes[i]))
elif i == 7:
label = create_label(
interval_classes[i],
tr('High Population [%i people/cell]' % classes[i]))
else:
label = create_label(interval_classes[i])
if i == 0:
transparency = 100
else:
transparency = 0
style_class['label'] = label
style_class['quantity'] = classes[i]
style_class['colour'] = colours[i]
style_class['transparency'] = transparency
style_classes.append(style_class)
# Override style info with new classes and name
style_info = dict(
target_field=None,
style_classes=style_classes,
style_type='rasterStyle')
# For printing map purpose
map_title = tr('People affected by flood prone areas')
legend_notes = tr('Thousand separator is represented by \'.\'')
legend_units = tr('(people per polygon)')
legend_title = tr('Population Count')
# Create vector layer and return
impact_layer = Raster(
data=new_covered_exposure_data,
projection=covered_exposure.get_projection(),
geotransform=covered_exposure.get_geotransform(),
name=tr('People affected by flood prone areas'),
keywords={
'impact_summary': impact_summary,
'impact_table': impact_table,
'target_field': self.target_field,
'map_title': map_title,
'legend_notes': legend_notes,
'legend_units': legend_units,
'legend_title': legend_title,
'affected_population': total_affected_population,
'total_population': total_population,
'total_needs': total_needs},
style_info=style_info)
self._impact = impact_layer
return impact_layer
示例10: run
#.........这里部分代码省略.........
table_body.append(TableRow(tr('Do we have enough relief items?')))
table_body.append(TableRow(tr('If yes, where are they located and how '
'will we distribute them?')))
table_body.append(TableRow(tr(
'If no, where can we obtain additional relief items from and how '
'will we transport them to here?')))
# Extend impact report for on-screen display
table_body.extend([
TableRow(tr('Notes'), header=True),
tr('Total population: %s') % format_int(total),
tr('People need evacuation if tsunami levels exceed %(eps).1f m') %
{'eps': thresholds[-1]},
tr('Minimum needs are defined in BNPB regulation 7/2008'),
tr('All values are rounded up to the nearest integer in order to '
'avoid representing human lives as fractions.')])
if len(counts) > 1:
table_body.append(TableRow(tr('Detailed breakdown'), header=True))
for i, val in enumerate(counts[:-1]):
s = (tr('People in %(lo).1f m to %(hi).1f m of water: %(val)i')
% {'lo': thresholds[i],
'hi': thresholds[i + 1],
'val': format_int(val[0])})
table_body.append(TableRow(s))
# Result
impact_summary = Table(table_body).toNewlineFreeString()
impact_table = impact_summary
# check for zero impact
if numpy.nanmax(impact) == 0 == numpy.nanmin(impact):
table_body = [
question,
TableRow([(tr('People in %.1f m of water') % thresholds[-1]),
'%s' % format_int(evacuated)],
header=True)]
my_message = Table(table_body).toNewlineFreeString()
raise ZeroImpactException(my_message)
# Create style
colours = [
'#FFFFFF', '#38A800', '#79C900', '#CEED00',
'#FFCC00', '#FF6600', '#FF0000', '#7A0000']
classes = create_classes(impact.flat[:], len(colours))
interval_classes = humanize_class(classes)
style_classes = []
for i in xrange(len(colours)):
style_class = dict()
if i == 1:
label = create_label(interval_classes[i], 'Low')
elif i == 4:
label = create_label(interval_classes[i], 'Medium')
elif i == 7:
label = create_label(interval_classes[i], 'High')
else:
label = create_label(interval_classes[i])
style_class['label'] = label
style_class['quantity'] = classes[i]
if i == 0:
transparency = 100
else:
transparency = 0
style_class['transparency'] = transparency
style_class['colour'] = colours[i]
style_classes.append(style_class)
style_info = dict(
target_field=None,
style_classes=style_classes,
style_type='rasterStyle')
# For printing map purpose
map_title = tr('People in need of evacuation')
legend_notes = tr(
'Thousand separator is represented by %s' %
get_thousand_separator())
legend_units = tr('(people per cell)')
legend_title = tr('Population')
# Create raster object and return
raster = Raster(
impact,
projection=hazard_layer.get_projection(),
geotransform=hazard_layer.get_geotransform(),
name=tr('Population which %s') % (
get_function_title(self).lower()),
keywords={
'impact_summary': impact_summary,
'impact_table': impact_table,
'map_title': map_title,
'legend_notes': legend_notes,
'legend_units': legend_units,
'legend_title': legend_title,
'evacuated': evacuated,
'total_needs': total_needs},
style_info=style_info)
return raster
示例11: run
def run(self):
"""Indonesian Earthquake Fatality Model."""
self.validate()
self.prepare()
displacement_rate = self.hardcoded_parameters['displacement_rate']
# Extract data grids
hazard = self.hazard.layer.get_data() # Ground Shaking
# Population Density
exposure = self.exposure.layer.get_data(scaling=True)
# Calculate people affected by each MMI level
# FIXME (Ole): this range is 2-9. Should 10 be included?
mmi_range = self.hardcoded_parameters['mmi_range']
number_of_exposed = {}
number_of_displaced = {}
number_of_fatalities = {}
# Calculate fatality rates for observed Intensity values (hazard
# based on ITB power model
mask = numpy.zeros(hazard.shape)
for mmi in mmi_range:
# Identify cells where MMI is in class i and
# count people affected by this shake level
step = self.hardcoded_parameters['step']
mmi_matches = numpy.where(
(hazard > mmi - step) * (
hazard <= mmi + step),
exposure, 0)
# Calculate expected number of fatalities per level
exposed = numpy.nansum(mmi_matches)
fatalities = self.fatality_rate(mmi) * exposed
# Calculate expected number of displaced people per level
displacements = displacement_rate[mmi] * (exposed - fatalities)
# Adjust displaced people to disregard fatalities.
# Set to zero if there are more fatalities than displaced.
# displacements = numpy.where(
# displacements > fatalities, displacements - fatalities, 0)
# Sum up numbers for map
# We need to use matrices here and not just numbers #2235
mask += mmi_matches * (1 - self.fatality_rate(mmi)) # Displaced
# Generate text with result for this study
# This is what is used in the real time system exposure table
number_of_exposed[mmi] = exposed
number_of_displaced[mmi] = displacements
# noinspection PyUnresolvedReferences
number_of_fatalities[mmi] = fatalities
# Total statistics
self.total_population = numpy.nansum(number_of_exposed.values())
self.total_fatalities = numpy.nansum(number_of_fatalities.values())
total_displaced = numpy.nansum(number_of_displaced.values())
# As per email discussion with Ole, Trevor, Hadi, total fatalities < 50
# will be rounded down to 0 - Tim
# Needs to revisit but keep it alive for the time being - Hyeuk, Jono
if self.total_fatalities < 50:
self.total_fatalities = 0
affected_population = self.affected_population
affected_population[tr('Number of fatalities')] = self.total_fatalities
affected_population[
tr('Number of people displaced')] = total_displaced
self.unaffected_population = (
self.total_population - total_displaced - self.total_fatalities)
self._evacuation_category = tr('Number of people displaced')
self.minimum_needs = [
parameter.serialize() for parameter in
filter_needs_parameters(self.parameters['minimum needs'])
]
total_needs = self.total_needs
# Result
impact_summary = self.generate_html_report()
impact_table = impact_summary
# Create style
colours = ['#EEFFEE', '#FFFF7F', '#E15500', '#E4001B', '#730000']
classes = create_classes(mask.flat[:], len(colours))
interval_classes = humanize_class(classes)
style_classes = []
for i in xrange(len(interval_classes)):
style_class = dict()
style_class['label'] = create_label(interval_classes[i])
style_class['quantity'] = classes[i]
if i == 0:
transparency = 100
else:
transparency = 30
style_class['transparency'] = transparency
style_class['colour'] = colours[i]
style_classes.append(style_class)
#.........这里部分代码省略.........
示例12: run
#.........这里部分代码省略.........
for hazard_zone in hazard_zone_categories:
self.affected_population[hazard_zone] = 0
# Count affected population per polygon and total
for row in interpolated_layer.get_data():
# Get population at this location
population = row[self.target_field]
if not numpy.isnan(population):
population = float(population)
# Update population count for this category
category = row[self.hazard_class_attribute]
self.affected_population[category] += population
# Count totals
self.total_population = int(
numpy.nansum(self.exposure.layer.get_data()))
self.unaffected_population = (
self.total_population - self.total_affected_population)
self.minimum_needs = [
parameter.serialize() for parameter in
filter_needs_parameters(self.parameters['minimum needs'])
]
impact_table = impact_summary = self.html_report()
# check for zero impact
if self.total_affected_population == 0:
message = no_population_impact_message(self.question)
raise ZeroImpactException(message)
# Create style
colours = ['#FFFFFF', '#38A800', '#79C900', '#CEED00',
'#FFCC00', '#FF6600', '#FF0000', '#7A0000']
classes = create_classes(
covered_exposure_layer.get_data().flat[:], len(colours))
interval_classes = humanize_class(classes)
# Define style info for output polygons showing population counts
style_classes = []
for i in xrange(len(colours)):
style_class = dict()
style_class['label'] = create_label(interval_classes[i])
if i == 1:
label = create_label(
interval_classes[i],
tr('Low Population [%i people/cell]' % classes[i]))
elif i == 4:
label = create_label(
interval_classes[i],
tr('Medium Population [%i people/cell]' % classes[i]))
elif i == 7:
label = create_label(
interval_classes[i],
tr('High Population [%i people/cell]' % classes[i]))
else:
label = create_label(interval_classes[i])
if i == 0:
transparency = 100
else:
transparency = 0
style_class['label'] = label
style_class['quantity'] = classes[i]
style_class['colour'] = colours[i]
style_class['transparency'] = transparency
style_classes.append(style_class)
# Override style info with new classes and name
style_info = dict(
target_field=None,
style_classes=style_classes,
style_type='rasterStyle')
# For printing map purpose
map_title = tr('People affected by Volcano Hazard Zones')
legend_title = tr('Population')
legend_units = tr('(people per cell)')
legend_notes = tr(
'Thousand separator is represented by %s' %
get_thousand_separator())
# Create vector layer and return
impact_layer = Raster(
data=covered_exposure_layer.get_data(),
projection=covered_exposure_layer.get_projection(),
geotransform=covered_exposure_layer.get_geotransform(),
name=tr('People affected by volcano hazard zones'),
keywords={'impact_summary': impact_summary,
'impact_table': impact_table,
'target_field': self.target_field,
'map_title': map_title,
'legend_notes': legend_notes,
'legend_units': legend_units,
'legend_title': legend_title,
'total_needs': self.total_needs},
style_info=style_info)
self._impact = impact_layer
return impact_layer
示例13: run
def run(self):
"""Risk plugin for flood population evacuation.
Counts number of people exposed to flood levels exceeding
specified threshold.
:returns: Map of population exposed to flood levels exceeding the
threshold. Table with number of people evacuated and supplies
required.
:rtype: tuple
"""
# Determine depths above which people are regarded affected [m]
# Use thresholds from inundation layer if specified
thresholds = self.parameters['thresholds'].value
verify(
isinstance(thresholds, list),
'Expected thresholds to be a list. Got %s' % str(thresholds))
# Extract data as numeric arrays
data = self.hazard.layer.get_data(nan=True) # Depth
if has_no_data(data):
self.no_data_warning = True
# Calculate impact as population exposed to depths > max threshold
population = self.exposure.layer.get_data(nan=True, scaling=True)
total = int(numpy.nansum(population))
if has_no_data(population):
self.no_data_warning = True
# merely initialize
impact = None
for i, lo in enumerate(thresholds):
if i == len(thresholds) - 1:
# The last threshold
thresholds_name = tr(
'People in >= %.1f m of water') % lo
self.impact_category_ordering.append(thresholds_name)
self._evacuation_category = thresholds_name
impact = medium = numpy.where(data >= lo, population, 0)
else:
# Intermediate thresholds
hi = thresholds[i + 1]
thresholds_name = tr(
'People in %.1f m to %.1f m of water' % (lo, hi))
self.impact_category_ordering.append(thresholds_name)
medium = numpy.where((data >= lo) * (data < hi), population, 0)
# Count
val = int(numpy.nansum(medium))
self.affected_population[thresholds_name] = val
# Put the deepest area in top #2385
self.impact_category_ordering.reverse()
self.total_population = total
self.unaffected_population = total - self.total_affected_population
# Carry the no data values forward to the impact layer.
impact = numpy.where(numpy.isnan(population), numpy.nan, impact)
impact = numpy.where(numpy.isnan(data), numpy.nan, impact)
# Count totals
evacuated = self.total_evacuated
self.minimum_needs = [
parameter.serialize() for parameter in
self.parameters['minimum needs']
]
total_needs = self.total_needs
# check for zero impact
if numpy.nanmax(impact) == 0 == numpy.nanmin(impact):
message = no_population_impact_message(self.question)
raise ZeroImpactException(message)
# Create style
colours = [
'#FFFFFF', '#38A800', '#79C900', '#CEED00',
'#FFCC00', '#FF6600', '#FF0000', '#7A0000']
classes = create_classes(impact.flat[:], len(colours))
interval_classes = humanize_class(classes)
style_classes = []
for i in xrange(len(colours)):
style_class = dict()
if i == 1:
label = create_label(interval_classes[i], 'Low')
elif i == 4:
label = create_label(interval_classes[i], 'Medium')
elif i == 7:
label = create_label(interval_classes[i], 'High')
else:
label = create_label(interval_classes[i])
style_class['label'] = label
style_class['quantity'] = classes[i]
#.........这里部分代码省略.........
示例14: run
#.........这里部分代码省略.........
# Calculate estimated needs based on BNPB Perka
# 7/2008 minimum bantuan
# FIXME (Ole): Refactor into one function to be shared
rice = int(evacuated * 2.8)
drinking_water = int(evacuated * 17.5)
water = int(evacuated * 67)
family_kits = int(evacuated / 5)
toilets = int(evacuated / 20)
# Generate impact report for the pdf map
blank_cell = ''
table_body = [question,
TableRow([tr('Volcanos considered'),
'%s' % volcano_names, blank_cell],
header=True),
TableRow([tr('People needing evacuation'),
'%s' % format_int(evacuated),
blank_cell],
header=True),
TableRow([category_header,
tr('Total'), tr('Cumulative')],
header=True)]
for name in category_names:
table_body.append(TableRow([name,
format_int(pops[name]),
format_int(cums[name])]))
table_body.extend([TableRow(tr('Map shows population affected in '
'each of volcano hazard polygons.')),
TableRow([tr('Needs per week'), tr('Total'),
blank_cell],
header=True),
[tr('Rice [kg]'), format_int(rice), blank_cell],
[tr('Drinking Water [l]'),
format_int(drinking_water), blank_cell],
[tr('Clean Water [l]'), format_int(water),
blank_cell],
[tr('Family Kits'), format_int(family_kits),
blank_cell],
[tr('Toilets'), format_int(toilets),
blank_cell]])
impact_table = Table(table_body).toNewlineFreeString()
# Extend impact report for on-screen display
table_body.extend([TableRow(tr('Notes'), header=True),
tr('Total population %s in the exposure layer')
% format_int(total),
tr('People need evacuation if they are within the '
'volcanic hazard zones.')])
impact_summary = Table(table_body).toNewlineFreeString()
# Create style
colours = ['#FFFFFF', '#38A800', '#79C900', '#CEED00',
'#FFCC00', '#FF6600', '#FF0000', '#7A0000']
population_counts = [x[self.target_field] for x in new_attributes]
classes = create_classes(population_counts, len(colours))
interval_classes = humanize_class(classes)
# Define style info for output polygons showing population counts
style_classes = []
for i in xrange(len(colours)):
style_class = dict()
style_class['label'] = create_label(interval_classes[i])
if i == 0:
transparency = 100
style_class['min'] = 0
else:
transparency = 30
style_class['min'] = classes[i - 1]
style_class['transparency'] = transparency
style_class['colour'] = colours[i]
style_class['max'] = classes[i]
style_classes.append(style_class)
# Override style info with new classes and name
style_info = dict(target_field=self.target_field,
style_classes=style_classes,
style_type='graduatedSymbol')
# For printing map purpose
map_title = tr('People affected by volcanic hazard zone')
legend_notes = tr('Thousand separator is represented by \'.\'')
legend_units = tr('(people)')
legend_title = tr('Population count')
# Create vector layer and return
V = Vector(data=new_attributes,
projection=my_hazard.get_projection(),
geometry=my_hazard.get_geometry(as_geometry_objects=True),
name=tr('Population affected by volcanic hazard zone'),
keywords={'impact_summary': impact_summary,
'impact_table': impact_table,
'target_field': self.target_field,
'map_title': map_title,
'legend_notes': legend_notes,
'legend_units': legend_units,
'legend_title': legend_title},
style_info=style_info)
return V
示例15: run
#.........这里部分代码省略.........
unicode(hazard_class) for
hazard_class in self.hazard_class_mapping[self.wet]
]))
else:
affected_population = tr('People within any hazard polygon.')
self.affected_population[affected_population] = (
total_affected_population)
self.total_population = int(
numpy.nansum(self.exposure.layer.get_data(scaling=False)))
self.unaffected_population = (
self.total_population - self.total_affected_population)
self.minimum_needs = [
parameter.serialize() for parameter in
filter_needs_parameters(self.parameters['minimum needs'])
]
impact_table = impact_summary = self.html_report()
# Create style
colours = ['#FFFFFF', '#38A800', '#79C900', '#CEED00',
'#FFCC00', '#FF6600', '#FF0000', '#7A0000']
classes = create_classes(
new_covered_exposure_data.flat[:], len(colours))
# check for zero impact
if total_affected_population == 0:
message = no_population_impact_message(self.question)
raise ZeroImpactException(message)
interval_classes = humanize_class(classes)
# Define style info for output polygons showing population counts
style_classes = []
for i in xrange(len(colours)):
style_class = dict()
style_class['label'] = create_label(interval_classes[i])
if i == 1:
label = create_label(
interval_classes[i],
tr('Low Population [%i people/cell]' % classes[i]))
elif i == 4:
label = create_label(
interval_classes[i],
tr('Medium Population [%i people/cell]' % classes[i]))
elif i == 7:
label = create_label(
interval_classes[i],
tr('High Population [%i people/cell]' % classes[i]))
else:
label = create_label(interval_classes[i])
style_class['label'] = label
style_class['quantity'] = classes[i]
style_class['colour'] = colours[i]
style_class['transparency'] = 0
style_classes.append(style_class)
# Override style info with new classes and name
style_info = dict(
target_field=None,
style_classes=style_classes,
style_type='rasterStyle')
# For printing map purpose
map_title = tr('People affected by flood prone areas')
legend_title = tr('Population Count')
legend_units = tr('(people per polygon)')
legend_notes = tr(
'Thousand separator is represented by %s' %
get_thousand_separator())
extra_keywords = {
'impact_summary': impact_summary,
'impact_table': impact_table,
'target_field': self.target_field,
'map_title': map_title,
'legend_notes': legend_notes,
'legend_units': legend_units,
'legend_title': legend_title,
'affected_population': total_affected_population,
'total_population': self.total_population,
'total_needs': self.total_needs
}
self.set_if_provenance()
impact_layer_keywords = self.generate_impact_keywords(extra_keywords)
# Create vector layer and return
impact_layer = Raster(
data=new_covered_exposure_data,
projection=covered_exposure.get_projection(),
geotransform=covered_exposure.get_geotransform(),
name=tr('People affected by flood prone areas'),
keywords=impact_layer_keywords,
style_info=style_info)
self._impact = impact_layer
return impact_layer