本文整理汇总了Python中safe.common.utilities.humanize_class函数的典型用法代码示例。如果您正苦于以下问题:Python humanize_class函数的具体用法?Python humanize_class怎么用?Python humanize_class使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了humanize_class函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_humanize_class3
def test_humanize_class3(self):
"""Test humanize class 3
First class interval < 1
Interval < 1
"""
my_array = [0.1, 0.5, 0.9]
my_result_class = humanize_class(my_array)
my_expected_class = [('0', '0.1'),
('0.1', '0.5'),
('0.5', '0.9')]
my_msg = 'got: %s expect: %s' % (my_result_class, my_expected_class)
# print_class(my_array, my_result_class, my_expected_class)
assert my_result_class == my_expected_class, my_msg
示例2: test_humanize_class2
def test_humanize_class2(self):
"""Test humanize class 2
First class interval > 1
Interval > 1
"""
my_array = [1.1, 5754.1, 11507.1]
my_result_class = humanize_class(my_array)
my_expected_class = [('0', '1'),
('1', '5,754'),
('5,754', '11,507')]
# print_class(my_array, my_result_class, my_expected_class)
my_msg = 'got: %s expect: %s' % (my_result_class, my_expected_class)
assert my_result_class == my_expected_class, my_msg
示例3: test_humanize_class4
def test_humanize_class4(self):
"""Test humanize class 4
First class interval > 1
Interval < 1
"""
my_array = [7.1, 7.5, 7.9]
my_result_class = humanize_class(my_array)
my_expected_class = [('0', '7.1'),
('7.1', '7.5'),
('7.5', '7.9')]
my_msg = 'got: ' + str(my_result_class)
my_msg += ' expect: ' + str(my_expected_class)
print_class(my_array, my_result_class, my_expected_class)
assert my_result_class == my_expected_class, my_msg
示例4: test_humanize_class6
def test_humanize_class6(self):
"""Test humanize class 5
First class interval < 1
Interval > 1
"""
my_array = [0, 6.1, 7.2, 8.3, 9.4, 10.5]
my_result_class = humanize_class(my_array)
my_expected_class = [('0', '6'),
('6', '7'),
('7', '8'),
('8', '9'),
('9', '11')]
# print_class(my_array, my_result_class, my_expected_class)
my_msg = 'got: %s expect: %s' % (my_result_class, my_expected_class)
assert my_result_class == my_expected_class, my_msg
示例5: test_humanize_class
def test_humanize_class(self):
"""Test humanize class
First class interval < 1
Interval > 1
"""
my_array = [0.1, 1.2, 2.3, 3.4, 4.5]
my_result_class = humanize_class(my_array)
my_expected_class = [('0', '0.1'),
('0.1', '1.2'),
('1.2', '2.3'),
('2.3', '3.4'),
('3.4', '4.5')]
print_class(my_array, my_result_class, my_expected_class)
my_msg = 'got: ' + str(my_result_class)
my_msg += ' expect: ' + str(my_expected_class)
assert my_result_class == my_expected_class, my_msg
示例6: test_humanize_class
def test_humanize_class(self):
"""Test humanize class
First class interval < 1
Interval > 1
"""
array = [0.1, 1.2, 2.3, 3.4, 4.5]
result_class = humanize_class(array)
expected_class = [
('0', '0.1'),
('0.1', '1.2'),
('1.2', '2.3'),
('2.3', '3.4'),
('3.4', '4.5')
]
# print_class(array, result_class, expected_class)
self.assertEqual(result_class, expected_class)
示例7: run
def run(self):
"""Plugin for impact of population as derived by classified hazard.
Counts number of people exposed to each class of the hazard
Return
Map of population exposed to high class
Table with number of people in each class
"""
self.validate()
self.prepare()
# The 3 classes
# TODO (3.2): shouldnt these be defined in keywords rather? TS
categorical_hazards = self.parameters['Categorical hazards'].value
low_class = categorical_hazards[0].value
medium_class = categorical_hazards[1].value
high_class = categorical_hazards[2].value
# The classes must be different to each other
unique_classes_flag = all(
x != y for x, y in list(
itertools.combinations(
[low_class, medium_class, high_class], 2)))
if not unique_classes_flag:
raise FunctionParametersError(
'There is hazard class that has the same value with other '
'class. Please check the parameters.')
# Extract data as numeric arrays
hazard_data = self.hazard.layer.get_data(nan=True) # Class
if has_no_data(hazard_data):
self.no_data_warning = True
# Calculate impact as population exposed to each class
population = self.exposure.layer.get_data(scaling=True)
# Get all population data that falls in each hazard class
high_hazard_population = numpy.where(
hazard_data == high_class, population, 0)
medium_hazard_population = numpy.where(
hazard_data == medium_class, population, 0)
low_hazard_population = numpy.where(
hazard_data == low_class, population, 0)
affected_population = (
high_hazard_population + medium_hazard_population +
low_hazard_population)
# Carry the no data values forward to the impact layer.
affected_population = numpy.where(
numpy.isnan(population),
numpy.nan,
affected_population)
affected_population = numpy.where(
numpy.isnan(hazard_data),
numpy.nan,
affected_population)
# Count totals
self.total_population = int(numpy.nansum(population))
self.affected_population[
tr('Population in High hazard class areas')] = int(
numpy.nansum(high_hazard_population))
self.affected_population[
tr('Population in Medium hazard class areas')] = int(
numpy.nansum(medium_hazard_population))
self.affected_population[
tr('Population in Low hazard class areas')] = int(
numpy.nansum(low_hazard_population))
self.unaffected_population = (
self.total_population - self.total_affected_population)
# check for zero impact
if self.total_affected_population == 0:
message = no_population_impact_message(self.question)
raise ZeroImpactException(message)
self.minimum_needs = [
parameter.serialize() for parameter in
self.parameters['minimum needs']
]
total_needs = self.total_needs
impact_table = impact_summary = self.html_report()
# Create style
colours = [
'#FFFFFF', '#38A800', '#79C900', '#CEED00',
'#FFCC00', '#FF6600', '#FF0000', '#7A0000']
classes = create_classes(affected_population.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:
#.........这里部分代码省略.........
示例8: 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:
#.........这里部分代码省略.........
示例9: run
#.........这里部分代码省略.........
# Update building count for each category
category = new_data_table[poly_id][category_title]
categories[category] += 1
# Count totals
total = len(exposure_layer)
# Generate simple impact report
blank_cell = ''
table_body = [question,
TableRow([tr('Volcanoes considered'),
'%s' % volcano_names, blank_cell],
header=True),
TableRow([tr('Distance [km]'), tr('Total'),
tr('Cumulative')],
header=True)]
cumulative = 0
for name in category_names:
# prevent key error
count = categories.get(name, 0)
cumulative += count
if is_point_data:
name = int(name) / 1000
table_body.append(TableRow([name, format_int(count),
format_int(cumulative)]))
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()
building_counts = [x[self.target_field] for x in new_data_table]
if max(building_counts) == 0 == min(building_counts):
table_body = [
question,
TableRow([tr('Number of buildings affected'),
'%s' % format_int(cumulative), blank_cell],
header=True)]
my_message = Table(table_body).toNewlineFreeString()
raise ZeroImpactException(my_message)
# Create style
colours = ['#FFFFFF', '#38A800', '#79C900', '#CEED00',
'#FFCC00', '#FF6600', '#FF0000', '#7A0000']
# Create Classes
classes = create_classes(building_counts, len(colours))
# Create Interval Classes
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:
style_class['min'] = 0
else:
style_class['min'] = classes[i - 1]
style_class['transparency'] = 30
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('Buildings affected by volcanic hazard zone')
legend_notes = tr('Thousand separator is represented by %s' %
get_thousand_separator())
legend_units = tr('(building)')
legend_title = tr('Building count')
# Create vector layer and return
impact_layer = Vector(
data=new_data_table,
projection=hazard_layer.get_projection(),
geometry=hazard_layer.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 impact_layer
示例10: 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
示例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
def run(self):
"""Run classified population evacuation Impact Function.
Counts number of people exposed to each hazard zones.
:returns: Map of population exposed to each hazard zone.
The returned dict will include a table with number of people
evacuated and supplies required.
:rtype: dict
:raises:
* Exception - When hazard layer is not vector layer
"""
self.validate()
self.prepare()
# Value from layer's keywords
self.hazard_class_attribute = self.hazard.keyword('field')
# Input checks
msg = ('Input hazard must be a polygon layer. I got %s with '
'layer type %s' % (
self.hazard.name, self.hazard.layer.get_geometry_name()))
if not self.hazard.layer.is_polygon_data:
raise Exception(msg)
# Check if hazard_class_attribute exists in hazard_layer
if (self.hazard_class_attribute not in
self.hazard.layer.get_attribute_names()):
msg = ('Hazard data %s does not contain expected hazard '
'zone attribute "%s". Please change it in the option. ' %
(self.hazard.name, self.hazard_class_attribute))
# noinspection PyExceptionInherit
raise InaSAFEError(msg)
# Get unique hazard zones from the layer attribute
self.hazard_zones = list(
set(self.hazard.layer.get_data(self.hazard_class_attribute)))
# 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
)
# Initialise total population affected by each hazard zone
for hazard_zone in self.hazard_zones:
self.affected_population[hazard_zone] = 0
# 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_zone = row[self.hazard_class_attribute]
self.affected_population[hazard_zone] += 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:
table_body = [
self.question,
TableRow(
[tr('People impacted'),
'%s' % format_int(total_affected_population)],
header=True)]
message = Table(table_body).toNewlineFreeString()
raise ZeroImpactException(message)
impact_table = impact_summary = self.generate_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:
#.........这里部分代码省略.........
示例13: run
#.........这里部分代码省略.........
'%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(all_categories_population[name]),
format_int(all_categories_cumulative[name])]))
table_body.extend([
TableRow(tr(
'Map shows the number of people affected in each of volcano '
'hazard polygons.')),
TableRow(
[tr('Needs per week'), tr('Total'), blank_cell], header=True),
[tr('Rice [kg]'), format_int(total_needs['rice']), blank_cell], [
tr('Drinking Water [l]'),
format_int(total_needs['drinking_water']),
blank_cell],
[tr('Clean Water [l]'), format_int(total_needs['water']),
blank_cell],
[tr('Family Kits'), format_int(total_needs['family_kits']),
blank_cell],
[tr('Toilets'), format_int(total_needs['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.')])
population_counts = [x[self.target_field] for x in new_data_table]
impact_summary = Table(table_body).toNewlineFreeString()
# check for zero impact
if numpy.nanmax(population_counts) == 0 == numpy.nanmin(
population_counts):
table_body = [
question,
TableRow([tr('People needing evacuation'),
'%s' % format_int(evacuated),
blank_cell], 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(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 %s' %
get_thousand_separator())
legend_units = tr('(people)')
legend_title = tr('Population count')
# Create vector layer and return
impact_layer = Vector(
data=new_data_table,
projection=hazard_layer.get_projection(),
geometry=hazard_layer.get_geometry(as_geometry_objects=True),
name=tr('People 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 impact_layer
示例14: run
def run(self):
"""Run volcano point population evacuation Impact Function.
Counts number of people exposed to volcano event.
:returns: Map of population exposed to the volcano hazard zone.
The returned dict will include a table with number of people
evacuated and supplies required.
:rtype: dict
:raises:
* Exception - When hazard layer is not vector layer
* RadiiException - When radii are not valid (they need to be
monotonically increasing)
"""
self.validate()
self.prepare()
# Parameters
radii = self.parameters['distances'].value
# Get parameters from layer's keywords
volcano_name_attribute = self.hazard.keyword('volcano_name_field')
# Input checks
if not self.hazard.layer.is_point_data:
msg = (
'Input hazard must be a polygon or point layer. I got %s with '
'layer type %s' % (
self.hazard.name, self.hazard.layer.get_geometry_name()))
raise Exception(msg)
data_table = self.hazard.layer.get_data()
# Use concentric circles
category_title = 'Radius'
centers = self.hazard.layer.get_geometry()
rad_m = [x * 1000 for x in radii] # Convert to meters
hazard_layer = buffer_points(
centers, rad_m, category_title, data_table=data_table)
# Get names of volcanoes considered
if volcano_name_attribute in hazard_layer.get_attribute_names():
volcano_name_list = []
# Run through all polygons and get unique names
for row in data_table:
volcano_name_list.append(row[volcano_name_attribute])
volcano_names = ''
for radius in volcano_name_list:
volcano_names += '%s, ' % radius
self.volcano_names = volcano_names[:-2] # Strip trailing ', '
# Run interpolation function for polygon2raster
interpolated_layer, covered_exposure_layer = \
assign_hazard_values_to_exposure_data(
hazard_layer,
self.exposure.layer,
attribute_name=self.target_field
)
# Initialise affected population per categories
for radius in rad_m:
category = 'Distance %s km ' % format_int(radius)
self.affected_population[category] = 0
if has_no_data(self.exposure.layer.get_data(nan=True)):
self.no_data_warning = True
# 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 = 'Distance %s km ' % format_int(
row[category_title])
self.affected_population[category] += population
# Count totals
self.total_population = population_rounding(
int(numpy.nansum(self.exposure.layer.get_data())))
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(
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)):
#.........这里部分代码省略.........
示例15: run
def run(self):
"""Indonesian Earthquake Fatality Model."""
displacement_rate = self.hardcoded_parameters['displacement_rate']
fatality_rate = self.compute_fatality_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
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 = fatality_rate[mmi] * exposed
# Calculate expected number of displaced people per level
displacements = displacement_rate[mmi] * (
exposed - numpy.median(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
# filter out NaN to avoid overflow additions
mmi_matches = numpy.nan_to_num(mmi_matches)
mask += mmi_matches # 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
total_fatalities_raw = numpy.nansum(
number_of_fatalities.values(), axis=0)
# Compute probability of fatality in each magnitude bin
if (self.__class__.__name__ == 'PAGFatalityFunction') or (
self.__class__.__name__ == 'ITBBayesianFatalityFunction'):
prob_fatality_mag = self.compute_probability(total_fatalities_raw)
else:
prob_fatality_mag = None
# Compute number of fatalities
self.total_population = numpy.nansum(number_of_exposed.values())
self.total_fatalities = numpy.median(total_fatalities_raw)
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
# 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]
style_class['transparency'] = 30
style_class['colour'] = colours[i]
style_classes.append(style_class)
#.........这里部分代码省略.........