• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python util.resolve_from_dictionary函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中safe.report.extractors.util.resolve_from_dictionary函数的典型用法代码示例。如果您正苦于以下问题:Python resolve_from_dictionary函数的具体用法?Python resolve_from_dictionary怎么用?Python resolve_from_dictionary使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了resolve_from_dictionary函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: action_checklist_extractor

def action_checklist_extractor(impact_report, component_metadata):
    """Extracting action checklist of the exposure layer.

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.0
    """
    context = {}
    provenance = impact_report.impact_function.provenance
    extra_args = component_metadata.extra_args

    context['component_key'] = component_metadata.key
    context['header'] = resolve_from_dictionary(extra_args, 'header')
    context['items'] = provenance['action_checklist']

    return context
开发者ID:inasafe,项目名称:inasafe,代码行数:26,代码来源:action_notes.py


示例2: multi_exposure_analysis_question_extractor

def multi_exposure_analysis_question_extractor(
        impact_report, component_metadata):
    """Extracting analysis question from the impact layer.

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.3
    """
    context = {}
    extra_args = component_metadata.extra_args

    multi_exposure = impact_report.multi_exposure_impact_function
    provenance = multi_exposure.provenance

    header = resolve_from_dictionary(extra_args, 'header')
    analysis_questions = []

    analysis_question = provenance['analysis_question']
    analysis_questions.append(analysis_question)

    context['component_key'] = component_metadata.key
    context['header'] = header
    context['analysis_questions'] = analysis_questions

    return context
开发者ID:inasafe,项目名称:inasafe,代码行数:35,代码来源:analysis_question.py


示例3: action_checklist_report_extractor

def action_checklist_report_extractor(impact_report, component_metadata):
    """Extracting action checklist of the impact layer to its own report.

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.1
    """
    context = {}
    extra_args = component_metadata.extra_args

    components_list = resolve_from_dictionary(
        extra_args, 'components_list')

    context['brand_logo'] = resource_url(
        resources_path('img', 'logos', 'inasafe-logo-white.png'))
    for key, component in list(components_list.items()):
        context[key] = jinja2_output_as_string(
            impact_report, component['key'])

    context['inasafe_resources_base_dir'] = resources_path()

    return context
开发者ID:inasafe,项目名称:inasafe,代码行数:32,代码来源:action_notes.py


示例4: infographic_layout_extractor

def infographic_layout_extractor(impact_report, component_metadata):
    """Extracting infographic result and format it with a layout.

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.0
    """
    context = {}
    extra_args = component_metadata.extra_args

    infographics = resolve_from_dictionary(extra_args, ['infographics'])
    provenance = impact_report.impact_function.provenance

    infographic_result = ''

    for component_key in infographics:
        result = jinja2_output_as_string(impact_report, component_key)
        if result:
            infographic_result += result

    if not infographic_result:
        return context

    resources_dir = safe_dir(sub_dir='../resources')
    context['inasafe_resources_base_dir'] = resources_dir
    context['infographic_content'] = infographic_result
    version = provenance['inasafe_version']
    start_datetime = provenance['start_datetime']
    date = start_datetime.strftime('%Y-%m-%d')
    time = start_datetime.strftime('%H:%M')
    footer_format = resolve_from_dictionary(extra_args, 'footer_format')
    context['footer'] = footer_format.format(
        version=version, analysis_date=date, analysis_time=time)
    return context
开发者ID:ismailsunni,项目名称:inasafe,代码行数:44,代码来源:infographics.py


示例5: test_resolve_from_dictionary

    def test_resolve_from_dictionary(self):
        """Test resolve_from_dictionary method.

        .. versionadded:: 4.0
        """
        test_dict = {
            'foo': {
                'bar': {
                    'bin': {
                        'baz': 1
                    }
                }
            },
            'foobar': 10
        }

        # test nested resolve
        expected = 1
        actual = resolve_from_dictionary(test_dict, [
            'foo', 'bar', 'bin', 'baz'])

        self.assertEqual(expected, actual)

        # test single resolve using list

        expected = 10
        actual = resolve_from_dictionary(test_dict, ['foobar'])

        self.assertEqual(expected, actual)

        # test single resolve using shorthand notation

        expected = 10
        actual = resolve_from_dictionary(test_dict, 'foobar')

        self.assertEqual(expected, actual)
开发者ID:timlinux,项目名称:inasafe,代码行数:36,代码来源:test_util.py


示例6: impact_table_pdf_extractor

def impact_table_pdf_extractor(impact_report, component_metadata):
    """Extracting impact summary of the impact layer.

    For PDF generations

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.0
    """
    # QGIS Composer needed certain context to generate the output
    # - Map Settings
    # - Substitution maps
    # - Element settings, such as icon for picture file or image source

    context = QGISComposerContext()
    extra_args = component_metadata.extra_args

    html_report_component_key = resolve_from_dictionary(
        extra_args, ['html_report_component_key'])

    # we only have html elements for this
    html_frame_elements = [
        {
            'id': 'impact-report',
            'mode': 'text',
            'text': jinja2_output_as_string(
                impact_report, html_report_component_key),
            'margin_left': 10,
            'margin_top': 10,
        }
    ]
    context.html_frame_elements = html_frame_elements
    return context
开发者ID:inasafe,项目名称:inasafe,代码行数:43,代码来源:impact_table.py


示例7: impact_table_extractor

def impact_table_extractor(impact_report, component_metadata):
    """Extracting impact summary of the impact layer.

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.0
    """
    context = {}
    extra_args = component_metadata.extra_args
    debug_mode = impact_report.impact_function.debug_mode

    components_list = resolve_from_dictionary(
        extra_args, 'components_list')

    # TODO: Decide either to use it or not
    if not debug_mode:
        # only show experimental MMI Detail when in debug mode
        components_list.pop('mmi_detail', None)

    context['brand_logo'] = resource_url(
        resources_path('img', 'logos', 'inasafe-logo-white.png'))
    for key, component in components_list.iteritems():
        context[key] = jinja2_output_as_string(
            impact_report, component['key'])

    context['inasafe_resources_base_dir'] = resources_path()

    return context
开发者ID:timlinux,项目名称:inasafe,代码行数:38,代码来源:impact_table.py


示例8: analysis_detail_extractor

def analysis_detail_extractor(impact_report, component_metadata):
    """Extracting analysis result from the impact layer.

    :param impact_report: The impact report that acts as a proxy to fetch
        all the data that extractor needed.
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: The component metadata. Used to obtain
        information about the component we want to render.
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: Context for rendering phase.
    :rtype: dict

    .. versionadded:: 4.0
    """
    context = {}
    extra_args = component_metadata.extra_args

    analysis_layer = impact_report.analysis
    analysis_layer_fields = analysis_layer.keywords['inasafe_fields']
    analysis_feature = next(analysis_layer.getFeatures())
    exposure_summary_table = impact_report.exposure_summary_table
    if exposure_summary_table:
        exposure_summary_table_fields = exposure_summary_table.keywords[
            'inasafe_fields']
    provenance = impact_report.impact_function.provenance
    use_rounding = impact_report.impact_function.use_rounding
    hazard_keywords = provenance['hazard_keywords']
    exposure_keywords = provenance['exposure_keywords']

    """Initializations."""

    # Get hazard classification
    hazard_classification = definition(
        active_classification(hazard_keywords, exposure_keywords['exposure']))

    # Get exposure type definition
    exposure_type = definition(exposure_keywords['exposure'])
    # Only round the number when it is population exposure and we use rounding
    is_population = exposure_type is exposure_population

    # action for places with poopulation exposure
    is_place_with_population = False
    if exposure_type is exposure_place:
        exposure_fields = exposure_keywords['inasafe_fields']
        if exposure_fields.get(population_count_field['key']):
            is_place_with_population = True

    # Analysis detail only applicable for breakable exposure types:
    itemizable_exposures_all = [
        exposure for exposure in exposure_all
        if exposure.get('classifications')]
    if exposure_type not in itemizable_exposures_all:
        return context

    # Get breakdown field
    breakdown_field = None
    # I'm not sure what's the difference
    # It is possible to have exposure_type_field or exposure_class_field
    # at the moment
    breakdown_fields = [
        exposure_type_field,
        exposure_class_field
    ]
    for field in breakdown_fields:
        if field['key'] in exposure_summary_table_fields:
            breakdown_field = field
            break

    """Create detail header."""
    headers = []

    # breakdown header
    breakdown_header_template = ''
    if breakdown_field == exposure_type_field:
        breakdown_header_template = resolve_from_dictionary(
            extra_args, 'breakdown_header_type_format')
    elif breakdown_field == exposure_class_field:
        breakdown_header_template = resolve_from_dictionary(
            extra_args, 'breakdown_header_class_format')

    # check if there is header type associations
    type_header_mapping = resolve_from_dictionary(
        extra_args, 'exposure_type_header_mapping')

    if exposure_type['key'] in type_header_mapping:
        exposure_header = type_header_mapping[exposure_type['key']]
    else:
        exposure_header = exposure_type['name']

    headers.append(
        breakdown_header_template.format(exposure=exposure_header))

    # this is mapping for customizing double header for
    # affected/not affected hazard classes
    hazard_class_header_mapping = resolve_from_dictionary(
        extra_args,
        'hazard_class_header_mapping')
#.........这里部分代码省略.........
开发者ID:inasafe,项目名称:inasafe,代码行数:101,代码来源:analysis_detail.py


示例9: infographic_people_section_notes_extractor

def infographic_people_section_notes_extractor(
        impact_report, component_metadata):
    """Extracting notes for people section in the infographic.

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.2
    """
    hazard_layer = impact_report.hazard
    extra_args = component_metadata.extra_args

    context = {}
    context['notes'] = []

    note = {
        'title': None,
        'description': resolve_from_dictionary(extra_args, 'extra_note'),
        'citations': None
    }
    context['notes'].append(note)

    concept_keys = ['affected_people', 'displaced_people']
    for key in concept_keys:
        note = {
            'title': concepts[key].get('name'),
            'description': concepts[key].get('description'),
            'citations': concepts[key].get('citations')[0]['text']
        }
        context['notes'].append(note)

    hazard_classification = layer_hazard_classification(hazard_layer)

    # generate rate description
    displacement_rates_note_format = resolve_from_dictionary(
        extra_args, 'hazard_displacement_rates_note_format')
    displacement_rates_note = []
    for hazard_class in hazard_classification['classes']:
        hazard_class['classification_unit'] = (
            hazard_classification['classification_unit'])
        displacement_rates_note.append(
            displacement_rates_note_format.format(**hazard_class))

    rate_description = ', '.join(displacement_rates_note)

    note = {
        'title': concepts['displacement_rate'].get('name'),
        'description': rate_description,
        'citations': concepts['displacement_rate'].get('citations')[0]['text']
    }

    context['notes'].append(note)

    return context
开发者ID:akbargumbira,项目名称:inasafe,代码行数:63,代码来源:infographics.py


示例10: population_chart_extractor

def population_chart_extractor(impact_report, component_metadata):
    """Creating population donut chart.

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.0
    """
    context = {}
    extra_args = component_metadata.extra_args

    hazard_layer = impact_report.hazard
    analysis_layer = impact_report.analysis
    analysis_layer_fields = analysis_layer.keywords['inasafe_fields']

    """Generate Donut chart for affected population"""

    # create context for the donut chart

    # retrieve hazard classification from hazard layer
    hazard_classification = layer_hazard_classification(hazard_layer)

    if not hazard_classification:
        return context

    data = []
    labels = []
    colors = []

    for hazard_class in hazard_classification['classes']:

        # Skip if it is not affected hazard class
        if not hazard_class['affected']:
            continue

        # hazard_count_field is a dynamic field with hazard class
        # as parameter
        field_key_name = hazard_count_field['key'] % (
            hazard_class['key'],)

        try:
            # retrieve dynamic field name from analysis_fields keywords
            # will cause key error if no hazard count for that particular
            # class
            field_name = analysis_layer_fields[field_key_name]
            # Hazard label taken from translated hazard count field
            # label, string-formatted with translated hazard class label
            hazard_value = value_from_field_name(field_name, analysis_layer)
            hazard_value = round_affected_number(
                hazard_value,
                enable_rounding=True,
                use_population_rounding=True)
        except KeyError:
            # in case the field was not found
            continue

        data.append(hazard_value)
        labels.append(hazard_class['name'])
        colors.append(hazard_class['color'].name())

    # add total not affected
    try:
        field_name = analysis_layer_fields[total_not_affected_field['key']]
        hazard_value = value_from_field_name(field_name, analysis_layer)
        hazard_value = round_affected_number(
            hazard_value,
            enable_rounding=True,
            use_population_rounding=True)

        data.append(hazard_value)
        labels.append(total_not_affected_field['name'])
        colors.append(green.name())
    except KeyError:
        # in case the field is not there
        pass

    # add number for total not affected
    chart_title = resolve_from_dictionary(extra_args, 'chart_title')
    total_header = resolve_from_dictionary(extra_args, 'total_header')
    donut_context = DonutChartContext(
        data=data,
        labels=labels,
        colors=colors,
        inner_radius_ratio=0.5,
        stroke_color='#fff',
        title=chart_title,
        total_header=total_header,
        as_file=True)

    context['context'] = donut_context

#.........这里部分代码省略.........
开发者ID:ismailsunni,项目名称:inasafe,代码行数:101,代码来源:population_chart.py


示例11: minimum_needs_extractor

def minimum_needs_extractor(impact_report, component_metadata):
    """Extracting minimum needs of the impact layer.

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.0
    """
    context = {}
    extra_args = component_metadata.extra_args
    analysis_layer = impact_report.analysis
    analysis_keywords = analysis_layer.keywords['inasafe_fields']
    debug_mode = impact_report.impact_function.debug_mode
    is_rounding = not debug_mode

    header = resolve_from_dictionary(extra_args, 'header')
    context['header'] = header

    # check if displaced is not zero
    try:
        displaced_field_name = analysis_keywords[displaced_field['key']]
        total_displaced = value_from_field_name(
            displaced_field_name, analysis_layer)
        if total_displaced == 0:
            zero_displaced_message = resolve_from_dictionary(
                extra_args, 'zero_displaced_message')
            context['zero_displaced'] = {
                'status': True,
                'message': zero_displaced_message
            }
            return context
    except KeyError:
        # in case no displaced field
        pass

    # minimum needs calculation only affect population type exposure
    # check if analysis keyword have minimum_needs keywords
    have_minimum_needs_field = False
    for field_key in analysis_keywords:
        if field_key.startswith(minimum_needs_namespace):
            have_minimum_needs_field = True
            break

    if not have_minimum_needs_field:
        return context

    frequencies = {}
    # map each needs to its frequency groups
    for field in (minimum_needs_fields + additional_minimum_needs):
        need_parameter = field.get('need_parameter')
        if isinstance(need_parameter, ResourceParameter):
            frequency = need_parameter.frequency
        else:
            frequency = field.get('frequency')

        if frequency:
            if frequency not in frequencies:
                frequencies[frequency] = [field]
            else:
                frequencies[frequency].append(field)

    needs = []
    analysis_feature = analysis_layer.getFeatures().next()
    header_frequency_format = resolve_from_dictionary(
        extra_args, 'header_frequency_format')
    total_header = resolve_from_dictionary(extra_args, 'total_header')
    need_header_format = resolve_from_dictionary(
        extra_args, 'need_header_format')
    # group the needs by frequency
    for key, frequency in frequencies.iteritems():
        group = {
            'header': header_frequency_format.format(frequency=tr(key)),
            'total_header': total_header,
            'needs': []
        }
        for field in frequency:
            # check value exists in the field
            field_idx = analysis_layer.fieldNameIndex(field['field_name'])
            if field_idx == -1:
                # skip if field doesn't exists
                continue
            value = format_number(
                analysis_feature[field_idx],
                enable_rounding=is_rounding,
                is_population=True)

            if field.get('need_parameter'):
                need_parameter = field['need_parameter']
                """:type: ResourceParameter"""
                name = tr(need_parameter.name)
                unit_abbreviation = need_parameter.unit.abbreviation
#.........这里部分代码省略.........
开发者ID:timlinux,项目名称:inasafe,代码行数:101,代码来源:minimum_needs.py


示例12: aggregation_result_extractor


#.........这里部分代码省略.........
    # It is possible to have exposure_type_field or exposure_class_field
    # at the moment
    breakdown_fields = [
        exposure_type_field,
        exposure_class_field
    ]
    for field in breakdown_fields:
        if field['key'] in exposure_summary_table_fields:
            breakdown_field = field
            break
    breakdown_field_name = breakdown_field['field_name']
    breakdown_field_index = exposure_summary_table.fieldNameIndex(
        breakdown_field_name)

    # Fetch total affected for each breakdown name
    value_dict = {}
    for feat in exposure_summary_table.getFeatures():
        # exposure summary table is in csv format, so the field returned is
        # always in text format
        affected_value = int(float(feat[affected_field_index]))
        affected_value = format_number(
            affected_value,
            enable_rounding=is_rounded,
            is_population=is_population)
        value_dict[feat[breakdown_field_index]] = affected_value

    if value_dict:
        for type_name in type_fields:
            affected_value_string_formatted = value_dict[type_name]
            if affected_value_string_formatted == '0':
                # if total affected for breakdown type is zero
                # current column index
                column_index = len(type_total_values)
                # cut column header
                type_header_labels = (
                    type_header_labels[:column_index] +
                    type_header_labels[column_index + 1:])
                # cut all row values for the column
                for item in rows:
                    type_values = item['type_values']
                    item['type_values'] = (
                        type_values[:column_index] +
                        type_values[column_index + 1:])
                continue
            type_total_values.append(affected_value_string_formatted)

    """Get the super total affected"""

    # total for affected (super total)
    analysis_feature = analysis_layer.getFeatures().next()
    field_index = analysis_layer.fieldNameIndex(
        total_affected_field['field_name'])
    total_all = format_number(
        analysis_feature[field_index],
        enable_rounding=is_rounded)

    """Generate and format the context"""
    aggregation_area_default_header = resolve_from_dictionary(
        extra_args, 'aggregation_area_default_header')
    header_label = (
        aggregation_summary.title() or aggregation_area_default_header)

    table_header_format = resolve_from_dictionary(
        extra_args, 'table_header_format')

    # check unit
    units = exposure_type['units']
    if units:
        unit = units[0]
        abbreviation = unit['abbreviation']
        if abbreviation:
            unit_string = '({abbreviation})'.format(abbreviation=abbreviation)
        else:
            unit_string = ''
    else:
        unit_string = ''

    table_header = table_header_format.format(
        title=provenance['map_legend_title'],
        unit=unit_string)
    table_header = ' '.join(table_header.split())

    section_header = resolve_from_dictionary(extra_args, 'header')
    notes = resolve_from_dictionary(extra_args, 'notes')
    total_header = resolve_from_dictionary(extra_args, 'total_header')
    total_in_aggregation_header = resolve_from_dictionary(
        extra_args, 'total_in_aggregation_header')
    context['header'] = section_header
    context['notes'] = notes
    context['aggregation_result'] = {
        'table_header': table_header,
        'header_label': header_label,
        'type_header_labels': type_header_labels,
        'total_label': total_header,
        'total_in_aggregation_area_label': total_in_aggregation_header,
        'rows': rows,
        'type_total_values': type_total_values,
        'total_all': total_all,
    }
    return context
开发者ID:timlinux,项目名称:inasafe,代码行数:101,代码来源:aggregate_result.py


示例13: mmi_detail_extractor

def mmi_detail_extractor(impact_report, component_metadata):
    """Extracting MMI-related analysis result.

    This extractor should only be used for EQ Raster with Population.

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.0
    """
    context = {}
    analysis_layer = impact_report.analysis
    analysis_layer_keywords = analysis_layer.keywords
    extra_args = component_metadata.extra_args
    use_rounding = impact_report.impact_function.use_rounding
    provenance = impact_report.impact_function.provenance
    hazard_keywords = provenance['hazard_keywords']
    exposure_keywords = provenance['exposure_keywords']

    # check if this is EQ raster with population
    hazard_type = definition(hazard_keywords['hazard'])
    if not hazard_type == hazard_earthquake:
        return context

    hazard_geometry = hazard_keywords[layer_geometry['key']]
    if not hazard_geometry == layer_geometry_raster['key']:
        return context

    exposure_type = definition(exposure_keywords['exposure'])
    if not exposure_type == exposure_population:
        return context

    header = resolve_from_dictionary(extra_args, 'header')

    context['header'] = header

    reported_fields = resolve_from_dictionary(extra_args, 'reported_fields')

    """Generate headers."""
    table_header = [
        resolve_from_dictionary(extra_args, 'mmi_header')
    ] + [v['header'] for v in reported_fields]

    """Extract MMI-related data"""
    # mmi is ranged from 1 to 10, which means: [1, 11)
    mmi_range = list(range(1, 11))
    rows = []
    roman_numeral = [
        'I',
        'II',
        'III',
        'IV',
        'V',
        'VI',
        'VII',
        'VIII',
        'IX',
        'X'
    ]
    for i in mmi_range:
        columns = [roman_numeral[i - 1]]
        for value in reported_fields:
            field = value['field']
            try:
                key_name = field['key'] % (i, )
                field_name = analysis_layer_keywords[key_name]
                # check field exists
                count = value_from_field_name(field_name, analysis_layer)
                if not count:
                    count = 0
            except KeyError:
                count = 0
            count = format_number(
                count,
                use_rounding=use_rounding,
                is_population=True)
            columns.append(count)

        rows.append(columns)

    """Extract total."""
    total_footer = [
        resolve_from_dictionary(extra_args, 'total_header')
    ]

    total_fields = resolve_from_dictionary(extra_args, 'total_fields')
    for field in total_fields:
        try:
            field_name = analysis_layer_keywords[field['key']]
            total = value_from_field_name(field_name, analysis_layer)
            if not total:
#.........这里部分代码省略.........
开发者ID:inasafe,项目名称:inasafe,代码行数:101,代码来源:mmi_detail.py


示例14: qgis_composer_infographic_extractor

def qgis_composer_infographic_extractor(impact_report, component_metadata):
    """Extract composer context specific for infographic template.

    This method extract necessary context for a given impact report and
    component metadata and save the context so it can be used in composer
    rendering phase

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.2
    """
    qgis_context = impact_report.qgis_composition_context
    extra_args = component_metadata.extra_args

    context = QGISComposerContext()

    """Image Elements"""

    # get all image elements with their respective source path
    image_elements = deepcopy(image_item_elements)

    # remove inasafe_logo_white because we use expression for the image source
    image_elements.remove(inasafe_logo_white)
    # remove population_chart because we still don't have the source path
    image_elements.remove(population_chart)
    context.image_elements = image_elements

    # get the source path of population_chart
    population_donut_path = impact_report.component_absolute_output_path(
        'population-chart-png')
    population_chart['path'] = population_donut_path

    context.image_elements.append(population_chart)

    """HTML Elements"""

    components = resolve_from_dictionary(extra_args, 'components')
    html_elements = deepcopy(html_frame_elements)

    # get the html content from component that has been proceed
    for element in html_elements:
        component = components.get(element['component'])
        if component:
            element['text'] = jinja2_output_as_string(
                impact_report, component['key'])

    context.html_frame_elements = html_elements

    """Map Elements"""

    map_overview_layer = None
    layer_registry = QgsMapLayerRegistry.instance()
    for layer in layer_registry.mapLayers().values():
        if layer.name() == map_overview['id']:
            map_overview_layer = layer

    layers = [impact_report.impact_function.analysis_impacted]

    if map_overview_layer:
        layers.append(map_overview_layer)

    # default extent is analysis extent
    if not qgis_context.extent:
        qgis_context.extent = impact_report.impact_function.analysis_extent

    map_elements = [
        {
            'id': 'map-overview',
            'extent': qgis_context.extent,
            'grid_split_count': 5,
            'layers': layers,
        }
    ]

    context.map_elements = map_elements

    return context
开发者ID:timlinux,项目名称:inasafe,代码行数:87,代码来源:composer.py


示例15: qgis_composer_extractor


#.........这里部分代码省略.........
        layers = [impact_report.impact]
    symbol_count = 0
    for l in layers:
        layer = l
        """:type: qgis.core.QgsMapLayer"""
        try:
            symbol_count += len(layer.legendSymbologyItems())
            continue
        except Exception:  # pylint: disable=broad-except
            pass
        try:
            symbol_count += len(layer.renderer().legendSymbolItems())
            continue
        except Exception:  # pylint: disable=broad-except
            pass
        symbol_count += 1

    legend_title = provenance.get('map_legend_title') or ''

    map_legends = [
        {
            'id': 'impact-legend',
            'title': legend_title,
            'layers': layers,
            'symbol_count': symbol_count,
            # 'column_count': 2,  # the number of column in legend display
        }
    ]
    context.map_legends = map_legends

    # process substitution map
    start_datetime = provenance['start_datetime']
    """:type: datetime.datetime"""
    date_format = resolve_from_dictionary(extra_args, 'date-format')
    time_format = resolve_from_dictionary(extra_args, 'time-format')
    if isinstance(start_datetime, datetime.datetime):
        date = start_datetime.strftime(date_format)
        time = start_datetime.strftime(time_format)
    else:
        date = ''
        time = ''
    long_version = get_version()
    tokens = long_version.split('.')
    version = '%s.%s.%s' % (tokens[0], tokens[1], tokens[2])
    # Get title of the layer
    title = provenance.get('map_title') or ''

    # Set source
    unknown_source_text = resolve_from_dictionary(
        extra_args, ['defaults', 'unknown_source'])
    aggregation_not_used = resolve_from_dictionary(
        extra_args, ['defaults', 'aggregation_not_used'])

    hazard_source = (
        provenance.get(
            'hazard_keywords', {}).get('source') or unknown_source_text)
    exposure_source = (
        provenance.get(
            'exposure_keywords', {}).get('source') or unknown_source_text)
    if provenance['aggregation_layer']:
        aggregation_source = (
            provenance['aggregation_keywords'].get('source')
            or unknown_source_text)
    else:
        aggregation_source = aggregation_not_used
开发者ID:inasafe,项目名称:inasafe,代码行数:66,代码来源:composer.py


示例16: analysis_provenance_details_extractor

def analysis_provenance_details_extractor(impact_report, component_metadata):
    """Extracting provenance details of layers.

    This extractor would be the main provenance details extractor which produce
    tree view provenance details.

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.1
    """
    context = {}
    extra_args = component_metadata.extra_args

    default_source = resolve_from_dictionary(
        extra_args, ['defaults', 'source'])
    default_reference = resolve_from_dictionary(
        extra_args, ['defaults', 'reference'])
    provenance_format_args = resolve_from_dictionary(
        extra_args, 'provenance_format')

    keywords_order = [
        'title',
        'source',
        'layer_purpose',
        'layer_geometry',
        'hazard',
        'exposure',
        'hazard_category',
        'exposure_unit',
        'value_map',
        'value_maps',
        'inasafe_fields',
        'inasafe_default_values',
        'layer_mode',
        'hazard_layer',
        'exposure_layer',
        'aggregation_layer',
        'keywords_version']

    debug_mode = impact_report.impact_function.debug_mode

    # we define dict here to create a different object of keyword
    hazard_keywords = dict(impact_report.impact_function.provenance[
        'hazard_keywords'])

    # hazard_keywords doesn't have hazard_layer path information
    hazard_layer = impact_report.impact_function.provenance.get('hazard_layer')
    hazard_keywords['hazard_layer'] = hazard_layer

    # keep only value maps with IF exposure
    for keyword in ['value_maps', 'thresholds']:
        if hazard_keywords.get(keyword):
            temp_keyword = dict(hazard_keywords[keyword])
            for key in temp_keyword:
                if key not in impact_report.impact_function.provenance[
                        'exposure_keywords']['exposure']:
                    del hazard_keywords[keyword][key]

    header = resolve_from_dictionary(
        provenance_format_args, 'hazard_header')
    provenance_format = resolve_from_dictionary(
        provenance_format_args, 'hazard_format')
    hazard_provenance = {
        'header': header.title(),
        'provenances': headerize(
            sorted_keywords_by_order(hazard_keywords, keywords_order))
    }

    # convert value if there is dict_keywords
    provenances = hazard_provenance['provenances']
    hazard_provenance['provenances'] = resolve_dict_keywords(provenances)

    # we define dict here to create a different object of keyword
    exposure_keywords = dict(impact_report.impact_function.provenance[
        'exposure_keywords'])

    # exposure_keywords doesn't have exposure_layer path information
    exposure_layer = impact_report.impact_function.provenance.get(
        'exposure_layer')
    exposure_keywords['exposure_layer'] = exposure_layer

    header = resolve_from_dictionary(
        provenance_format_args, 'exposure_header')
    provenance_format = resolve_from_dictionary(
        provenance_format_args, 'exposure_format')
    exposure_provenance = {
        'header': header.title(),
        'provenances': headerize(
            sorted_keywords_by_order(exposure_keywords, keywords_order))
    }
#.........这里部分代码省略.........
开发者ID:ismailsunni,项目名称:inasafe,代码行数:101,代码来源:analysis_provenance_details.py


示例17: analysis_provenance_details_simplified_extractor

def analysis_provenance_details_simplified_extractor(
        impact_report, component_metadata):
    """Extracting simplified version of provenance details of layers.

    This extractor will produce provenance details which will be displayed in
    the main report.

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.0
    """
    context = {}
    extra_args = component_metadata.extra_args

    default_source = resolve_from_dictionary(
        extra_args, ['defaults', 'source'])
    default_reference = resolve_from_dictionary(
        extra_args, ['defaults', 'reference'])
    provenance_format_args = resolve_from_dictionary(
        extra_args, 'provenance_format')

    hazard_keywords = impact_report.impact_function.provenance[
        'hazard_keywords']
    header = resolve_from_dictionary(
        provenance_format_args, 'hazard_header')
    provenance_format = resolve_from_dictionary(
        provenance_format_args, 'hazard_format')
    hazard_provenance = {
        'header': header,
        'provenance': provenance_format.format(
            layer_name=hazard_keywords.get('title'),
            source=hazard_keywords.get('source') or default_source)
    }

    exposure_keywords = impact_report.impact_function.provenance[
        'exposure_keywords']
    header = resolve 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python impact_report.ImpactReport类代码示例发布时间:2022-05-27
下一篇:
Python abstract_postprocessor.AbstractPostprocessor类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap