예제 #1
0
    def sections(self):
        sections = []
        ''' Trade Section
        '''
        trade_section = {
            "title":
            _(u"%(product_name)s Trade.", product_name=self.attr.get_name()),
            "builds": []
        }

        exporters = Build("tree_map", self.classification, "export", "show",
                          "all", self.attr, self.year)
        exporters_subtitle = _(
            u"This treemap shows the share of countries that export %(product)s.",
            product=self.attr.get_name())
        trade_section["builds"].append({
            "title": u"Exporters",
            "build": exporters,
            "subtitle": exporters_subtitle
        })

        importers = Build("tree_map", self.classification, "import", "show",
                          "all", self.attr, self.year)
        importers_subtitle = _(
            u"This treemap shows the share of countries that import %(product)s.",
            product=self.attr.get_name())
        trade_section["builds"].append({
            "title": u"Importers",
            "build": importers,
            "subtitle": importers_subtitle
        })

        rings = Build("rings", self.classification, "export", "all", "all",
                      self.attr, self.year)
        rings_subtitle = _(
            u"This visualization shows products that are likely to be exported by countries that export %(product)s.",
            product=self.attr.get_name())
        trade_section["builds"].append({
            "title": u"Product Connections",
            "build": rings,
            "subtitle": rings_subtitle
        })

        sections.append(trade_section)

        sections.append({
            "title":
            _(u"More on %(country)s from our other sites",
              country=self.attr.get_name(article=True)),
            "source":
            "sisters"
        })
        ''' DataViva Section
        '''
        if self.classification == "hs92":

            dv_section = make_dv_section(self)
            sections.append(dv_section)

        return sections
예제 #2
0
파일: views.py 프로젝트: fxcebx/oec
def embed(app_name, classification, trade_flow, origin_id, dest_id, \
                prod_id, year=available_years['hs92'][-1]):
    '''support for legacy URLs that use hs not hs92'''
    if classification not in ['sitc', 'hs92', 'hs96', 'hs02', 'hs07']:
        return redirect(url_for('.embed', lang=g.locale, app_name=app_name, \
                        classification='hs92', trade_flow=trade_flow, \
                        origin_id=origin_id, dest_id=dest_id, prod_id=prod_id, \
                        year=year))

    b = Build(app_name, classification, trade_flow, origin_id, dest_id, prod_id, year)

    '''Get URL query parameters from reqest.args object to return to the view.
    '''
    global_vars = {x[0]:x[1] for x in request.args.items()}
    if "controls" not in global_vars:
        global_vars["controls"] = "true"

    return render_template("visualize/embed.html",
        build = b,
        global_vars = json.dumps(global_vars),
        facebook_id = FACEBOOK_ID)
예제 #3
0
파일: models.py 프로젝트: ablascoa/oec
    def sections(self):
        sections = []
        ''' Trade Section
        '''

        if self.attr.id == "xxwld":

            export_tmap = Build("tree_map", "hs92", "export", self.attr, "all",
                                "show", self.year)
            this_yo = self.models.Yo.query.filter_by(year=self.year).all()

            export_val = sum([o.export_val for o in this_yo])
            export_subtitle = _(
                u"The total world trade in %(year)s was %(export_val)s.",
                year=self.year,
                export_val=num_format(export_val, "export_val"))
            export_subtitle += u" "

            past_yr = self.year - 5
            past_yo = self.models.Yo.query.filter_by(year=past_yr).all()
            growth_val = median([o.export_val_growth_pct_5 for o in this_yo])
            chg = "increased" if growth_val >= 0 else "decreased"
            export_subtitle += _(u"During the last five years exports have %(increased_decreased)s at a median annualized rate of %(change_rate)s%%, from $%(past_export_val)s in %(past_year)s to $%(current_export_val)s in %(current_year)s.",
                                    increased_decreased=chg, change_rate=num_format(growth_val*100), \
                                    past_export_val=num_format(sum([o.export_val for o in past_yo])), past_year=past_yr, current_export_val=num_format(export_val), current_year=self.year)
            export_subtitle += u" "

            top_exports = self.models.Yp.query.filter_by(
                year=self.year,
                hs92_id_len=6).order_by(desc("export_val")).limit(2).all()
            export_subtitle += _(u"The most recent exports are led by %(top_export)s which represent %(top_export_pct)s%% of the total products exported, followed by %(second_export)s, which account for %(second_export_pct)s%%.",
                                    top_export=top_exports[0].product.get_profile_link(), top_export_pct=num_format((top_exports[0].export_val/export_val)*100), \
                                    second_export=top_exports[1].product.get_profile_link(), second_export_pct=num_format((top_exports[1].export_val/export_val)*100))

            origins_tmap = Build("tree_map", "hs92", "import", self.attr,
                                 "show", "all", self.year)
            yo_exp = self.models.Yo.query.filter_by(year=self.year).order_by(
                desc("export_val")).limit(5).all()
            origin_list = self.stringify_items(yo_exp, "export_val", "country")
            origin_subtitle = _(u"The top exporters globally are %(origins)s.",
                                origins=origin_list)

            trade_section = {
                "builds": [
                    {
                        "title": _(u"Exports"),
                        "build": export_tmap,
                        "subtitle": export_subtitle
                    },
                    {
                        "title": _(u"Origins"),
                        "build": origins_tmap,
                        "subtitle": origin_subtitle
                    },
                ]
            }

        else:
            export_subtitle, import_subtitle, dest_subtitle, origin_subtitle = [
                None
            ] * 4

            export_tmap = Build("tree_map", "hs92", "export", self.attr, "all",
                                "show", self.year)
            import_tmap = Build("tree_map", "hs92", "import", self.attr, "all",
                                "show", self.year)

            yop_base = self.models.Yop.query.filter_by(year=self.year,
                                                       origin=self.attr,
                                                       hs92_id_len=6)
            # get growth
            past_yr = self.year - 5
            past_yo = self.models.Yo.query.filter_by(
                year=past_yr, country=self.attr).first()
            this_yo = self.models.Yo.query.filter_by(
                year=self.year, country=self.attr).first()
            exp_val_stat = filter(lambda s: s["key"] == "export_val",
                                  self.stats())
            if exp_val_stat and this_yo:
                exp_val_stat = exp_val_stat.pop()
                export_subtitle = ""
                if self.attr.id != "xxwld":
                    exp_rank = num_format(
                        exp_val_stat["rank"],
                        "ordinal") if exp_val_stat["rank"] > 1 else ""
                    export_subtitle += _(
                        u"In %(year)s %(country)s exported $%(export_val)s, making it the %(export_rank)s largest exporter in the world.",
                        year=self.year,
                        country=self.attr.get_name(article=True),
                        export_val=num_format(exp_val_stat["val"]),
                        export_rank=exp_rank)
                    export_subtitle += u" "
                if past_yo and this_yo.export_val_growth_pct_5:
                    chg = "increased" if this_yo.export_val_growth_pct_5 >= 0 else "decreased"
                    export_subtitle += _(u"During the last five years the exports %(of_country)s have %(increased_decreased)s at an annualized rate of %(change_rate)s%%, from $%(past_export_val)s in %(past_year)s to $%(current_export_val)s in %(current_year)s.",
                                            of_country=self.attr.get_name(article="of"), increased_decreased=chg, change_rate=num_format(this_yo.export_val_growth_pct_5*100), \
                                            past_export_val=num_format(past_yo.export_val), past_year=past_yr, current_export_val=num_format(this_yo.export_val), current_year=self.year)
                    export_subtitle += u" "
                top_exports = yop_base.order_by(
                    desc("export_val")).limit(2).all()
                if top_exports:
                    # raise Exception(top_exports[0].product.get_profile_link(), num_format((top_exports[0].export_val/exp_val_stat["val"])*100), self.attr.get_name(article="of"), top_exports[1].product.get_profile_link(), num_format((top_exports[1].export_val/exp_val_stat["val"])*100))
                    export_subtitle += _(u"The most recent exports are led by %(top_export)s which represent %(top_export_pct)s%% of the total exports %(of_country)s, followed by %(second_export)s, which account for %(second_export_pct)s%%.",
                                            top_export=top_exports[0].product.get_profile_link(), top_export_pct=num_format((top_exports[0].export_val/exp_val_stat["val"])*100), \
                                            of_country=self.attr.get_name(article="of"), second_export=top_exports[1].product.get_profile_link(), second_export_pct=num_format((top_exports[1].export_val/exp_val_stat["val"])*100))
            imp_val_stat = filter(lambda s: s["key"] == "import_val",
                                  self.stats())
            if imp_val_stat and this_yo:
                imp_val_stat = imp_val_stat.pop()
                import_subtitle = ""
                if self.attr.id != "xxwld":
                    imp_rank = num_format(
                        imp_val_stat["rank"],
                        "ordinal") if imp_val_stat["rank"] > 1 else ""
                    import_subtitle += _(
                        u"In %(year)s %(country)s imported $%(import_val)s, making it the %(import_rank)s largest importer in the world.",
                        year=self.year,
                        country=self.attr.get_name(article=True),
                        import_val=num_format(imp_val_stat["val"]),
                        import_rank=imp_rank)
                    import_subtitle += u" "
                if past_yo and this_yo.import_val_growth_pct_5:
                    chg = "increased" if this_yo.import_val_growth_pct_5 >= 0 else "decreased"
                    import_subtitle += _(u"During the last five years the imports %(of_country)s have %(increased_decreased)s at an annualized rate of %(change_rate)s%%, from $%(past_import_val)s in %(past_year)s to $%(current_import_val)s in %(current_year)s.",
                                            of_country=self.attr.get_name(article="of"), increased_decreased=chg, change_rate=num_format(this_yo.import_val_growth_pct_5*100), \
                                            past_import_val=num_format(past_yo.import_val), past_year=past_yr, current_import_val=num_format(this_yo.import_val), current_year=self.year)
                    import_subtitle += u" "
                top_imports = yop_base.order_by(
                    desc("import_val")).limit(2).all()
                if top_imports:
                    import_subtitle += _(u"The most recent imports are led by %(top_import)s which represent %(top_import_pct)s%% of the total imports %(of_country)s, followed by %(second_import)s, which account for %(second_import_pct)s%%.",
                                            top_import=top_imports[0].product.get_profile_link(), top_import_pct=num_format((top_imports[0].import_val/imp_val_stat["val"])*100), \
                                            of_country=self.attr.get_name(article="of"), second_import=top_imports[1].product.get_profile_link(), second_import_pct=num_format((top_imports[1].import_val/imp_val_stat["val"])*100))

            dests_tmap = Build("tree_map", "hs92", "export", self.attr, "show",
                               "all", self.year)
            yod_exp = self.models.Yod.query.filter_by(
                year=self.year,
                origin=self.attr).order_by(desc("export_val")).limit(5).all()
            if yod_exp:
                dest_list = self.stringify_items(yod_exp, "export_val", "dest")
                dest_subtitle = _(
                    u"The top export destinations %(of_country)s are %(destinations)s.",
                    of_country=self.attr.get_name(article="of"),
                    destinations=dest_list)

            origins_tmap = Build("tree_map", "hs92", "import", self.attr,
                                 "show", "all", self.year)
            yod_imp = self.models.Yod.query.filter_by(
                year=self.year,
                dest=self.attr).order_by(desc("export_val")).limit(5).all()
            if yod_imp:
                origin_list = self.stringify_items(yod_imp, "export_val",
                                                   "origin")
                origin_subtitle = _(
                    u"The top import origins %(of_country)s are %(origins)s.",
                    of_country=self.attr.get_name(article="of"),
                    origins=origin_list)

            # trade balance viz --
            first_yo = self.models.Yo.query.filter_by(
                year=available_years["hs92"][-1], country=self.attr).first()
            tb_subtitle = ""
            tb_build = Build("line", "hs92", "show", self.attr, "all", "all",
                             available_years["hs92"])
            if first_yo:
                net_trade = this_yo.export_val - this_yo.import_val
                trade_balance = _("positive") if net_trade >= 0 else _(
                    "negative")
                trade_direction = _("exports") if net_trade >= 0 else _(
                    "imports")
                tb_subtitle = _(
                    u"As of %(year)s %(country)s had a %(positive_negative)s trade balance of $%(net_trade)s in net %(exports_imports)s.",
                    year=self.year,
                    country=self.attr.get_name(article=True),
                    positive_negative=trade_balance,
                    net_trade=num_format(abs(net_trade)),
                    exports_imports=trade_direction)
                old_yo = self.models.Yo.query.filter_by(
                    year=available_years["hs92"][0],
                    country=self.attr).first()
                if old_yo:
                    old_net_trade = old_yo.export_val - old_yo.import_val
                    old_trade_balance = _(
                        "positive") if old_net_trade >= 0 else _("negative")
                    old_trade_direction = _(
                        "exports") if old_net_trade >= 0 else _("imports")
                    is_diff = True if old_trade_balance != trade_balance else False
                    still_or_not = _(
                        "still") if old_trade_balance == trade_balance else ""
                    tb_subtitle += u" "
                    tb_subtitle += _(
                        u"As compared to their trade balance in %(year)s when they %(still)s had a %(positive_negative)s trade balance of $%(net_trade)s in net %(exports_imports)s.",
                        year=available_years["hs92"][0],
                        still=still_or_not,
                        positive_negative=old_trade_balance,
                        net_trade=num_format(abs(old_net_trade)),
                        exports_imports=old_trade_direction)

            trade_section = {
                "builds": [
                    {
                        "title": _(u"Exports"),
                        "build": export_tmap,
                        "subtitle": export_subtitle,
                        "tour": "This is just a test",
                        "seq": 5
                    },
                    {
                        "title": _(u"Imports"),
                        "build": import_tmap,
                        "subtitle": import_subtitle
                    },
                    {
                        "title": _(u"Trade Balance"),
                        "build": tb_build,
                        "subtitle": tb_subtitle
                    },
                    {
                        "title": _(u"Destinations"),
                        "build": dests_tmap,
                        "subtitle": dest_subtitle
                    },
                    {
                        "title": _(u"Origins"),
                        "build": origins_tmap,
                        "subtitle": origin_subtitle
                    },
                ]
            }

        sections.append(trade_section)
        ''' Product Space Section
        '''
        subtitle = False
        if self.attr.id != "xxwld":
            num_exports_w_rca = db.session.query(func.count(self.models.Yop.hs92_id)) \
                        .filter_by(year = self.year, origin = self.attr) \
                        .filter(self.models.Yop.export_rca >= 1) \
                        .filter(func.char_length(self.models.Yop.hs92_id)==6) \
                        .scalar()
            this_attr_yo = attrs.Yo.query.filter_by(year=self.year,
                                                    country=self.attr).first()
            if this_attr_yo:
                eci = this_attr_yo.eci
                eci_rank = this_attr_yo.eci_rank
                if eci_rank:
                    subtitle = _(
                        u"The economy %(of_country)s has an Economic Complexity Index (ECI) of %(eci)s making it the %(eci_rank)s most complex country.",
                        of_country=self.attr.get_name(article="of"),
                        eci=num_format(eci),
                        eci_rank=num_format(eci_rank, "ordinal"))
                    subtitle += u" "
                else:
                    subtitle = ""
                subtitle += _(u"%(country)s exports %(num_of_exports)s products with revealed comparative advantage " \
                    u"(meaning that its share of global exports is larger than what " \
                    u"would be expected from the size of its export economy " \
                    u"and from the size of a product’s global market).",
                    country=self.attr.get_name(article=True), num_of_exports=num_exports_w_rca)
        product_space = Build("network", "hs92", "export", self.attr, "all",
                              "show", self.year)
        ps_text = _(
            u"The product space is a network connecting products that are likely to be co-exported and can be used to predict the evolution of a country’s export structure."
        )
        if subtitle:
            ps_text = u"{}</p><p>{}".format(ps_text, subtitle)
        ps_section = {
            "title":
            _(u"Economic Complexity %(of_country)s",
              of_country=self.attr.get_name(article="of")),
            "builds": [{
                "title": _(u"Product Space"),
                "build": product_space,
                "subtitle": ps_text,
                "tour": "The product space...",
                "seq": 6
            }]
        }
        ''' PGI Section
        '''
        if self.attr.id != "xxwld":
            pgi_product_space = Build("network", "sitc", "pgi", self.attr,
                                      "all", "show",
                                      available_years["sitc"][-1])
            subtitle = _(
                "In this version of the product space products are colored according to their Product Gini Index, or PGI. The PGI of a product is the level of income inequality that we expect for the countries that export a product. For more information see: %(paper1)s and %(paper2)s.",
                country=self.attr.get_name(article=True),
                paper1=
                "<a target='_blank' href='https://arxiv.org/abs/1505.07907'>Linking Economic Complexity, Institutions and Income Inequality</a>",
                paper2=
                "<a target='_blank' href='https://arxiv.org/abs/1701.03770'>The structural constraints of income inequality in Latin America</a>"
            )
            ps_section["builds"].append({
                "title":
                _(u"Complexity and Income Inequality"),
                "build":
                pgi_product_space,
                "subtitle":
                subtitle
            })
        ''' ECI Ranking Section
        '''
        if self.attr.id == "xxwld":
            line_rankings = Build(
                "line", "sitc", "eci", "show", "all", "all",
                [y for y in available_years["sitc"] if y >= 1964])
            start_year = 1980
            start_year = max(1964, start_year) if start_year != 1980 else 1964
            year_range = self.year - start_year
            subtitle = _(
                "The Economic Complexity of each country visualized over the past %(year_range)s years.",
                year_range=year_range)
            ps_section["builds"].append({
                "title":
                _(u"Economic Complexity Ranking"),
                "build":
                line_rankings,
                "subtitle":
                subtitle
            })

        elif this_attr_yo and this_attr_yo.eci != None:
            line_rankings = Build(
                "line", "sitc", "eci", "show", self.attr, "all",
                [y for y in available_years["sitc"] if y >= 1964])
            start_year = earliest_data.get(self.attr.id, 1980)
            start_year = max(1964, start_year) if start_year != 1980 else 1964
            year_range = self.year - start_year

            attr_yo_historic = attrs.Yo.query.filter_by(
                country=self.attr).filter(attrs.Yo.year == start_year).first()
            if attr_yo_historic and attr_yo_historic.eci_rank != None and this_attr_yo.eci_rank != None:
                eci_delta = this_attr_yo.eci_rank - attr_yo_historic.eci_rank
                inc_dec = _('increased') if eci_delta < 0 else _('decreased')
                subtitle = _(
                    "The Economic Complexity ranking %(of_country)s has %(increased_or_decreased)s by %(rank_delta)s places over the past %(year_range)s years from %(old_eci)s in %(old_year)s to %(current_eci)s in %(current_year)s.",
                    of_country=self.attr.get_name(article="of"),
                    increased_or_decreased=inc_dec,
                    rank_delta=abs(eci_delta),
                    year_range=year_range,
                    old_eci=num_format(attr_yo_historic.eci_rank, "ordinal"),
                    old_year=start_year,
                    current_eci=num_format(this_attr_yo.eci_rank, "ordinal"),
                    current_year=self.year)
            ps_section["builds"].append({
                "title":
                _(u"Economic Complexity Ranking"),
                "build":
                line_rankings,
                "subtitle":
                subtitle
            })
        sections.append(ps_section)

        sections.append({
            "title":
            _(u"More on %(country)s from our other sites",
              country=self.attr.get_name(article=True)),
            "source":
            "sisters"
        })
        ''' DataViva
        '''
        # dv_section = make_dv_section(self)
        # sections.append(dv_section)
        ''' Data USA
        '''
        if self.attr.id == "nausa":
            us_section = make_us_section()
            sections.append(us_section)
        ''' Data Africa
        '''
        if any(country[0] == self.attr.id
               for country in data_africa_countries):
            da_country = filter(lambda x: x[0] == self.attr.id,
                                data_africa_countries)
            africa_section = make_africa_section(self, da_country[0])
            sections.append(africa_section)
            # raise Exception("found dataafrican country: {}".format(da_country[0]))
        ''' Pantheon
        '''
        pantheon_id = "all" if self.attr.id == "xxwld" else self.attr.id_2char
        if pantheon_id:
            if self.attr.id != "xxwld":
                pantheon_id = pantheon_id.upper()

            pantheon_section = make_pantheon_section(pantheon_id, self.attr)
            sections.append(pantheon_section)

        return sections
예제 #4
0
def visualize(app_name,
              classification,
              trade_flow,
              origin_id,
              dest_id,
              prod_id,
              year=None):
    g.page_type = "visualize"
    g.page_sub_type = app_name

    if app_name == "scatter":
        year = [y for y in year if y >= 1980]
    elif trade_flow == "eci":
        year = [y for y in year if y >= 1964]
    '''sanitize input args'''
    redir = sanitize(app_name, classification, trade_flow, origin_id, dest_id,
                     prod_id, year)
    if redir:
        flash(redir[0])
        return redirect(redir[1])
    '''get this build'''
    build = Build(app_name, classification, trade_flow, origin_id, dest_id,
                  prod_id, year)
    if build.title() is None and build.question() is None:
        abort(404)
    '''get every possible build for sub nav'''
    origin, dest, prod = get_origin_dest_prod(origin_id, dest_id, prod_id,
                                              classification, year, trade_flow)
    all_builds = get_all_builds(classification, origin_id, dest_id, prod_id,
                                year, {
                                    "origin": origin,
                                    "dest": dest,
                                    "prod": prod
                                })
    '''create the ui array for the current build'''
    ui = []

    all_country = {
        "color": "#333333",
        "display_id": "all",
        "id": "all",
        "icon": "/static/img/icons/app/app_geo_map.png",
        "name": "All"
    }
    all_placed = False

    if build.trade_flow != "eci" and build.viz["slug"] not in (
            "scatter", "geo_map") and build.origin != "show":
        if isinstance(build.origin, Country):
            origin_country = build.origin.serialize()
        else:
            origin_country = all_country
            all_placed = True

        ui.append({
            "id": "origin",
            "name": gettext("Country"),
            "data": [origin_country],
            "url": url_for('attr.attrs', attr='country', lang=g.locale)
        })

    dest_country = False
    prod_exists = isinstance(build.prod, (Sitc, Hs92, Hs96, Hs02, Hs07))

    if isinstance(build.dest, Country):
        dest_country = build.dest.serialize()
    elif not all_placed and not prod_exists and build.viz["slug"] in (
            "tree_map", "line", "stacked"):
        dest_country = all_country

    if dest_country:
        ui.append({
            "id":
            "destination",
            "name":
            gettext("Country")
            if build.trade_flow == "eci" else gettext("Partner"),
            "data": [dest_country],
            "url":
            url_for('attr.attrs', attr='country', lang=g.locale)
        })

    if prod_exists:
        product = {
            "id": "product",
            "name": gettext("Product"),
            "data": [build.prod.serialize()],
            "url": url_for('attr.attrs',
                           attr=build.classification,
                           lang=g.locale)
        }
        ui.append(product)

    if build.viz["slug"] == "scatter":
        trade_flow = {
            "id":
            "trade_flow",
            "name":
            gettext("Y Axis"),
            "current":
            build.trade_flow,
            "data": [{
                "name": gettext("GDP"),
                "display_id": "gdp"
            }, {
                "name": gettext("GDPpc (constant '05 US$)"),
                "display_id": "gdp_pc_constant"
            }, {
                "name": gettext("GDPpc (current US$)"),
                "display_id": "gdp_pc_current"
            }, {
                "name": gettext("GDPpc PPP (constant '11)"),
                "display_id": "gdp_pc_constant_ppp"
            }, {
                "name": gettext("GDPpc PPP (current)"),
                "display_id": "gdp_pc_current_ppp"
            }]
        }
    else:
        trade_flow = {
            "id":
            "trade_flow",
            "name":
            gettext("Trade Flow"),
            "current":
            build.trade_flow,
            "data": [{
                "name": gettext("Export"),
                "display_id": "export"
            }, {
                "name": gettext("Import"),
                "display_id": "import"
            }]
        }

    if build.trade_flow not in ("show", "eci"):
        ui.append(trade_flow)

    if build.trade_flow != "eci":
        ui.append({
            "id": "classification",
            "name": gettext("Dataset"),
            "current": build.classification,
            "data": ["HS92", "HS96", "HS02", "HS07", "SITC"]
        })

    years = set()
    for d in available_years:
        [
            years.add(y) for y in available_years[d]
            if (build.trade_flow == "eci" and y >= 1964) or
            (build.viz["slug"] == "scatter" and y >= 1980) or (
                build.viz["slug"] != "scatter" and build.trade_flow != "eci")
        ]

    if build.viz["slug"] in ("stacked", "line"):
        ui.append({
            "id": "start_year",
            "name": gettext("Start Year"),
            "current": build.year[0],
            "data": years
        })
        ui.append({
            "id": "end_year",
            "name": gettext("End Year"),
            "current": build.year[-1],
            "data": years
        })
    else:
        ui.append({
            "id": "year",
            "name": gettext("Year"),
            "current": build.year[-1],
            "data": years
        })

    builds_by_app = {}
    for b in all_builds:
        if b.viz["slug"] not in ("stacked", "line"):
            b.year = [b.year[-1]]
            b.year_str = Build.year_to_str(b, b.year)
        if not hasattr(builds_by_app, b.viz["slug"]):
            builds_by_app[b.viz["slug"]] = []
    for b in all_builds:
        builds_by_app[b.viz["slug"]].append(b)

    page = "index_new" if request.args.get("beta") == "" else "index"

    return render_template("visualize/{}.html".format(page),
                           current_build=build,
                           build_ui=ui,
                           all_builds=builds_by_app.values())
예제 #5
0
    def sections(self):
        sections = []
        ''' Trade Section
        '''
        trade_section = {
            "title": u"{} Trade".format(self.attr.get_name()),
            "builds": []
        }

        exporters = Build("tree_map", self.classification, "export", "show",
                          "all", self.attr, self.year)
        exporters_subtitle = u"This treemap shows the share of countries that export {}.".format(
            self.attr.get_name())
        trade_section["builds"].append({
            "title": u"Exporters",
            "build": exporters,
            "subtitle": exporters_subtitle
        })

        importers = Build("tree_map", self.classification, "import", "show",
                          "all", self.attr, self.year)
        importers_subtitle = u"This treemap shows the share of countries that import {}.".format(
            self.attr.get_name())
        trade_section["builds"].append({
            "title": u"Importers",
            "build": importers,
            "subtitle": importers_subtitle
        })

        rings = Build("rings", self.classification, "export", "all", "all",
                      self.attr, self.year)
        rings_subtitle = u"This visualization shows products that are likely to be exported by countries that export {}.".format(
            self.attr.get_name())
        trade_section["builds"].append({
            "title": u"Product Connections",
            "build": rings,
            "subtitle": rings_subtitle
        })

        sections.append(trade_section)

        sections.append({
            "title":
            _(u"More on %(country)s from our sister sites",
              country=self.attr.get_name(article=True)),
            "source":
            "sisters"
        })
        ''' DataViva Section
        '''
        if self.classification == "hs92":
            dv_hs = self.attr
            if len(dv_hs.id) > 6:
                dv_hs = self.attr_cls.query.get(self.attr.id[:6])
            dv_munic_exporters_iframe = "http://en.dataviva.info/apps/embed/tree_map/secex/all/{}/all/bra/?controls=false&size=export_val".format(
                dv_hs.id)
            dv_munic_importers_iframe = "http://en.dataviva.info/apps/embed/tree_map/secex/all/{}/all/bra/?controls=false&size=import_val".format(
                dv_hs.id)
            dv_munic_exporters_subtitle = u"""
                This treemap shows the municipalities in Brazil that export {}.<br /><br />
                DataViva is a visualization tool that provides official data on trade, industries, and education throughout Brazil. If you would like more info or to create a similar site get in touch with us at <a href='mailto:[email protected]'>[email protected]</a>.<br />
                <a target='_blank' href='http://en.dataviva.info/apps/builder/tree_map/secex/all/{}/all/bra/?controls=false&size=export_val'><img src='http://en.dataviva.info/static/img/nav/DataViva.png' /></a>
                """.format(dv_hs.get_name(), self.attr.id)
            dv_munic_importers_subtitle = u"""
                This treemap shows the municipalities in Brazil that import {}.<br />.<br />
                DataViva is a visualization tool that provides official data on trade, industries, and education throughout Brazil. If you would like more info or to create a similar site get in touch with us at <a href='mailto:[email protected]'>[email protected]</a>.<br />
                <a target='_blank' href='http://en.dataviva.info/apps/builder/tree_map/secex/all/{}/all/bra/?controls=false&size=import_val'><img src='http://en.dataviva.info/static/img/nav/DataViva.png' /></a>
                """.format(dv_hs.get_name(), self.attr.id)
            dv_section = {
                "title":
                u"<a href='http://dataviva.info/' target='_blank'><img src='http://en.dataviva.info/static/img/nav/DataViva.png' /></a>",
                "source":
                "dataviva",
                "builds": [
                    {
                        "title":
                        u"{} exporters in Brazil".format(dv_hs.get_name()),
                        "iframe": dv_munic_exporters_iframe,
                        "subtitle": dv_munic_exporters_subtitle
                    },
                    {
                        "title":
                        u"{} importers in Brazil".format(dv_hs.get_name()),
                        "iframe": dv_munic_importers_iframe,
                        "subtitle": dv_munic_importers_subtitle
                    },
                ]
            }
            sections.append(dv_section)

        return sections
예제 #6
0
    def sections(self):
        sections = []
        ''' Trade Section
        '''
        export_subtitle, import_subtitle, dest_subtitle, origin_subtitle = [
            None
        ] * 4

        export_tmap = Build("tree_map", "hs92", "export", self.attr, "all",
                            "show", self.year)
        import_tmap = Build("tree_map", "hs92", "import", self.attr, "all",
                            "show", self.year)

        yop_base = self.models.Yop.query.filter_by(year=self.year,
                                                   origin=self.attr,
                                                   hs92_id_len=6)
        # get growth
        past_yr = self.year - 5
        past_yo = self.models.Yo.query.filter_by(year=past_yr,
                                                 country=self.attr).first()
        this_yo = self.models.Yo.query.filter_by(year=self.year,
                                                 country=self.attr).first()
        exp_val_stat = filter(lambda s: s["key"] == "export_val", self.stats())
        if exp_val_stat:
            exp_val_stat = exp_val_stat.pop()
            exp_rank = num_format(
                exp_val_stat["rank"],
                "ordinal") if exp_val_stat["rank"] > 1 else ""
            export_subtitle = _(
                u"In %(year)s %(country)s exported $%(export_val)s, making it the %(export_rank)s largest exporter in the world. ",
                year=self.year,
                country=self.attr.get_name(article=True),
                export_val=num_format(exp_val_stat["val"]),
                export_rank=exp_rank)
            if past_yo:
                chg = "increased" if this_yo.export_val_growth_pct_5 >= 0 else "decreased"
                export_subtitle += _(u"During the last five years the exports %(of_country)s have %(increased_decreased)s at an annualized rate of %(change_rate)s%%, from $%(past_export_val)s in %(past_year)s to $%(current_export_val)s in %(current_year)s. ",
                                        of_country=self.attr.get_name(article="of"), increased_decreased=chg, change_rate=num_format(this_yo.export_val_growth_pct_5*100), \
                                        past_export_val=num_format(past_yo.export_val), past_year=past_yr, current_export_val=num_format(this_yo.export_val), current_year=self.year)
            top_exports = yop_base.order_by(desc("export_val")).limit(2).all()
            if top_exports:
                # raise Exception(top_exports[0].product.get_profile_link(), num_format((top_exports[0].export_val/exp_val_stat["val"])*100), self.attr.get_name(article="of"), top_exports[1].product.get_profile_link(), num_format((top_exports[1].export_val/exp_val_stat["val"])*100))
                export_subtitle += _(u"The most recent exports are led by %(top_export)s which represent %(top_export_pct)s%% of the total exports %(of_country)s, followed by %(second_export)s, which account for %(second_export_pct)s%%.",
                                        top_export=top_exports[0].product.get_profile_link(), top_export_pct=num_format((top_exports[0].export_val/exp_val_stat["val"])*100), \
                                        of_country=self.attr.get_name(article="of"), second_export=top_exports[1].product.get_profile_link(), second_export_pct=num_format((top_exports[1].export_val/exp_val_stat["val"])*100))
        imp_val_stat = filter(lambda s: s["key"] == "import_val", self.stats())
        if imp_val_stat:
            imp_val_stat = imp_val_stat.pop()
            imp_rank = num_format(
                imp_val_stat["rank"],
                "ordinal") if imp_val_stat["rank"] > 1 else ""
            import_subtitle = _(
                u"In %(year)s %(country)s imported $%(import_val)s, making it the %(import_rank)s largest importer in the world. ",
                year=self.year,
                country=self.attr.get_name(article=True),
                import_val=num_format(imp_val_stat["val"]),
                import_rank=imp_rank)
            if past_yo:
                chg = "increased" if this_yo.import_val_growth_pct_5 >= 0 else "decreased"
                import_subtitle += _(u"During the last five years the imports %(of_country)s have %(increased_decreased)s at an annualized rate of %(change_rate)s%%, from $%(past_import_val)s in %(past_year)s to $%(current_import_val)s in %(current_year)s. ",
                                        of_country=self.attr.get_name(article="of"), increased_decreased=chg, change_rate=num_format(this_yo.import_val_growth_pct_5*100), \
                                        past_import_val=num_format(past_yo.import_val), past_year=past_yr, current_import_val=num_format(this_yo.import_val), current_year=self.year)
            top_imports = yop_base.order_by(desc("import_val")).limit(2).all()
            if top_imports:
                import_subtitle += _(u"The most recent imports are led by %(top_import)s which represent %(top_import_pct)s%% of the total imports %(of_country)s, followed by %(second_import)s, which account for %(second_import_pct)s%%.",
                                        top_import=top_imports[0].product.get_profile_link(), top_import_pct=num_format((top_imports[0].import_val/imp_val_stat["val"])*100), \
                                        of_country=self.attr.get_name(article="of"), second_import=top_imports[1].product.get_profile_link(), second_import_pct=num_format((top_imports[1].import_val/imp_val_stat["val"])*100))

        dests_tmap = Build("tree_map", "hs92", "export", self.attr, "show",
                           "all", self.year)
        yod_exp = self.models.Yod.query.filter_by(
            year=self.year,
            origin=self.attr).order_by(desc("export_val")).limit(5).all()
        if yod_exp:
            dest_list = self.stringify_items(yod_exp, "export_val", "dest")
            dest_subtitle = _(
                u"The top export destinations %(of_country)s are %(destinations)s.",
                of_country=self.attr.get_name(article="of"),
                destinations=dest_list)

        origins_tmap = Build("tree_map", "hs92", "import", self.attr, "show",
                             "all", self.year)
        yod_imp = self.models.Yod.query.filter_by(
            year=self.year,
            dest=self.attr).order_by(desc("export_val")).limit(5).all()
        if yod_imp:
            origin_list = self.stringify_items(yod_imp, "export_val", "origin")
            origin_subtitle = _(
                u"The top import origins %(of_country)s are %(origins)s.",
                of_country=self.attr.get_name(article="of"),
                origins=origin_list)

        # trade balance viz --
        first_yo = self.models.Yo.query.filter_by(
            year=available_years["hs92"][-1], country=self.attr).first()
        tb_subtitle = ""
        tb_build = Build("line", "hs92", "show", self.attr, "all", "all",
                         available_years["hs92"])
        if first_yo:
            net_trade = this_yo.export_val - this_yo.import_val
            trade_balance = _("positive") if net_trade >= 0 else _("negative")
            trade_direction = _("exports") if net_trade >= 0 else _("imports")
            tb_subtitle = _(
                u"As of %(year)s %(country)s had a %(positive_negative)s trade balance of $%(net_trade)s in net %(exports_imports)s.",
                year=self.year,
                country=self.attr.get_name(article=True),
                positive_negative=trade_balance,
                net_trade=num_format(abs(net_trade)),
                exports_imports=trade_direction)
            old_yo = self.models.Yo.query.filter_by(
                year=available_years["hs92"][0], country=self.attr).first()
            if old_yo:
                old_net_trade = old_yo.export_val - old_yo.import_val
                old_trade_balance = _("positive") if old_net_trade >= 0 else _(
                    "negative")
                old_trade_direction = _(
                    "exports") if old_net_trade >= 0 else _("imports")
                is_diff = True if old_trade_balance != trade_balance else False
                still_or_not = _(
                    "still") if old_trade_balance == trade_balance else ""
                tb_subtitle += _(
                    u" As compared to their trade balance in %(year)s when they %(still)s had a %(positive_negative)s trade balance of $%(net_trade)s in net %(exports_imports)s.",
                    year=available_years["hs92"][0],
                    still=still_or_not,
                    positive_negative=old_trade_balance,
                    net_trade=num_format(abs(old_net_trade)),
                    exports_imports=old_trade_direction)

        trade_section = {
            "builds": [
                {
                    "title": _(u"Exports"),
                    "build": export_tmap,
                    "subtitle": export_subtitle,
                    "tour": "This is just a test",
                    "seq": 5
                },
                {
                    "title": _(u"Imports"),
                    "build": import_tmap,
                    "subtitle": import_subtitle
                },
                {
                    "title": _(u"Trade Balance"),
                    "build": tb_build,
                    "subtitle": tb_subtitle
                },
                {
                    "title": _(u"Destinations"),
                    "build": dests_tmap,
                    "subtitle": dest_subtitle
                },
                {
                    "title": _(u"Origins"),
                    "build": origins_tmap,
                    "subtitle": origin_subtitle
                },
            ]
        }
        sections.append(trade_section)
        ''' Product Space Section
        '''
        num_exports_w_rca = db.session.query(func.count(self.models.Yop.hs92_id)) \
                    .filter_by(year = self.year, origin = self.attr) \
                    .filter(self.models.Yop.export_rca >= 1) \
                    .filter(func.char_length(self.models.Yop.hs92_id)==6) \
                    .scalar()
        this_attr_yo = attrs.Yo.query.filter_by(year=self.year,
                                                country=self.attr).first()
        if this_attr_yo:
            eci = this_attr_yo.eci
            eci_rank = this_attr_yo.eci_rank
            if eci_rank:
                subtitle = _(
                    u"The economy %(of_country)s has an Economic Complexity Index (ECI) of %(eci)s making it the %(eci_rank)s most complex country. ",
                    of_country=self.attr.get_name(article="of"),
                    eci=num_format(eci),
                    eci_rank=num_format(eci_rank, "ordinal"))
            else:
                subtitle = ""
            subtitle += _(u"%(country)s exports %(num_of_exports)s products with revealed comparative advantage " \
                u"(meaning that its share of global exports is larger than what " \
                u"would be expected from the size of its export economy " \
                u"and from the size of a product’s global market).",
                country=self.attr.get_name(article=True), num_of_exports=num_exports_w_rca)
        else:
            subtitle = ""
        product_space = Build("network", "hs92", "export", self.attr, "all",
                              "show", self.year)
        ps_text = _(
            u"The product space is a network connecting products that are likely to be co-exported and can be used to predict the evolution of a country’s export structure."
        )
        ps_text = u"{}</p><p>{}".format(ps_text, subtitle)
        ps_section = {
            "title":
            _(u"Economic Complexity %(of_country)s",
              of_country=self.attr.get_name(article="of")),
            "builds": [{
                "title": _(u"Product Space"),
                "build": product_space,
                "subtitle": ps_text,
                "tour": "The product space...",
                "seq": 6
            }]
        }
        ''' ECI Ranking Section
        '''
        if this_attr_yo and this_attr_yo.eci != None:
            line_rankings = Build(
                "line", "sitc", "eci", "show", self.attr, "all",
                [y for y in available_years["sitc"] if y >= 1964])
            start_year = earliest_data.get(self.attr.id, 1980)
            start_year = max(1964, start_year) if start_year != 1980 else 1964
            year_range = self.year - start_year
            attr_yo_historic = attrs.Yo.query.filter_by(
                country=self.attr).filter(attrs.Yo.year == start_year).first()
            if attr_yo_historic.eci_rank:
                eci_delta = this_attr_yo.eci_rank - attr_yo_historic.eci_rank
                inc_dec = _('increased') if eci_delta < 0 else _('decreased')
                subtitle = _(
                    """The Economic Complexity ranking %(of_country)s has %(increased_or_decreased)s by %(rank_delta)s places
                    over the past %(year_range)s years from %(old_eci)s in %(old_year)s to %(current_eci)s in %(current_year)s.""",
                    of_country=self.attr.get_name(article="of"),
                    increased_or_decreased=inc_dec,
                    rank_delta=abs(eci_delta),
                    year_range=year_range,
                    old_eci=num_format(attr_yo_historic.eci_rank, "ordinal"),
                    old_year=start_year,
                    current_eci=num_format(this_attr_yo.eci_rank, "ordinal"),
                    current_year=self.year)
                ps_section["builds"].append({
                    "title":
                    _(u"Economic Complexity Ranking"),
                    "build":
                    line_rankings,
                    "subtitle":
                    subtitle
                })
        sections.append(ps_section)

        sections.append({
            "title":
            _(u"More on %(country)s from our sister sites",
              country=self.attr.get_name(article=True)),
            "source":
            "sisters"
        })
        ''' DataViva
        '''
        if self.attr.id == "sabra":
            dv_geo_map = "http://en.dataviva.info/apps/embed/geo_map/secex/all/all/all/bra/?color=export_val&controls=false&year=2013"
            dv_wages = "http://en.dataviva.info/apps/embed/bar/rais/all/all/all/bra/?controls=false&year=2013"
            dv_geo_map_subtitle = _(u"""
                This map shows the exports of Brazil by state.<br /><br />
                DataViva is a visualization tool that provides official data on trade, industries, and education throughout Brazil. If you would like more info or to create a similar site get in touch with us at <a href='mailto:[email protected]'>[email protected]</a>.
                </p><p><a target='_blank' href='http://en.dataviva.info/apps/builder/geo_map/secex/all/all/all/bra/?color=export_val&controls=false&year=2013'>Explore on DataViva <i class='fa fa-external-link'></i></a>
                """)
            dv_wages_subtitle = _(u"""
                This bar chart shows the wage distribution for the working population in Brazil.
                </p><p><a target='_blank' href='http://en.dataviva.info/apps/builder/bar/rais/all/all/all/bra/?controls=false&year=2013'>Explore on DataViva <i class='fa fa-external-link'></i></a>
                """)
            dv_section = {
                "title":
                u"<a href='http://dataviva.info/' target='_blank'><img src='http://en.dataviva.info/static/img/nav/DataViva.png' /></a>",
                "source":
                "dataviva",
                "builds": [
                    {
                        "title": _(u"State Exports"),
                        "iframe": dv_geo_map,
                        "subtitle": dv_geo_map_subtitle,
                        "tour":
                        "Profile pages also contain visualizations from other websites created by member of the OEC team. The following are 2 embeded visualization from DataViva, a similar visualization platorm centered around Brazilian data.",
                        "seq": 7
                    },
                    {
                        "title": _(u"Wage Distribution"),
                        "iframe": dv_wages,
                        "subtitle": dv_wages_subtitle
                    },
                ]
            }
        else:
            dv_country_id = "asrus" if self.attr.id == "eurus" else self.attr.id
            dv_munic_dest_iframe = "http://dataviva.info/apps/embed/tree_map/secex/all/all/{}/bra/?size=import_val&controls=false".format(
                dv_country_id)
            dv_munic_origin_iframe = "http://dataviva.info/apps/embed/tree_map/secex/all/all/{}/bra/?size=export_val&controls=false".format(
                dv_country_id)
            dv_munic_dest_subtitle = _(
                u"""
                This treemap shows the municipalities in Brazil that imported products from %(country)s.<br /><br />
                DataViva is a visualization tool that provides official data on trade, industries, and education throughout Brazil. If you would like more info or to create a similar site get in touch with us at <a href='mailto:[email protected]'>[email protected]</a>.
                </p><p><a target='_blank' href='http://dataviva.info/apps/builder/tree_map/secex/all/all/%(dv_country_id)s/bra/?size=import_val&controls=false'>Explore on DataViva <i class='fa fa-external-link'></i></a>
                """,
                country=self.attr.get_name(article=True),
                dv_country_id=dv_country_id)
            dv_munic_origin_subtitle = _(
                u"""
                This treemap shows the municipalities in Brazil that exported products to %(country)s.
                </p><p><a target='_blank' href='http://dataviva.info/apps/builder/tree_map/secex/all/all/%(dv_country_id)s/bra/?size=export_val&controls=false'>Explore on DataViva <i class='fa fa-external-link'></i></a>
                """,
                country=self.attr.get_name(article=True),
                dv_country_id=dv_country_id)
            dv_section = {
                "title":
                u"<a href='http://dataviva.info/' target='_blank'><img src='http://en.dataviva.info/static/img/nav/DataViva.png' /></a>",
                "source":
                "dataviva",
                "builds": [
                    {
                        "title":
                        _(u"Brazilian Municipalities that import from %(country)s",
                          country=self.attr.get_name(article=True)),
                        "iframe":
                        dv_munic_dest_iframe,
                        "subtitle":
                        dv_munic_dest_subtitle,
                        "tour":
                        "Profile pages also contain visualizations from other websites created by member of the OEC team. The following are 2 embeded visualization from DataViva, a similar visualization platorm centered around Brazilian data.",
                        "seq":
                        7
                    },
                    {
                        "title":
                        _(u"Brazilian Municipalities that export to %(country)s",
                          country=self.attr.get_name(article=True)),
                        "iframe":
                        dv_munic_origin_iframe,
                        "subtitle":
                        dv_munic_origin_subtitle
                    },
                ]
            }
        sections.append(dv_section)
        ''' Pantheon
        '''
        if self.attr.id_2char:
            pantheon_iframe_fields = "http://pantheon.media.mit.edu/treemap/country_exports/{}/all/-4000/2010/H15/pantheon/embed".format(
                self.attr.id_2char.upper())
            pantheon_link_fields = "<a target='_blank' href='http://pantheon.media.mit.edu/treemap/country_exports/{}/all/-4000/2010/H15/pantheon/'>Explore on Pantheon <i class='fa fa-external-link'></i></a>".format(
                self.attr.id_2char.upper())
            pantheon_iframe_cities = "http://pantheon.media.mit.edu/treemap/country_by_city/all/{}/-4000/2010/H15/pantheon/embed".format(
                self.attr.id_2char.upper())
            pantheon_link_cities = "<a target='_blank' href='http://pantheon.media.mit.edu/treemap/country_by_city/{}/all/-4000/2010/H15/pantheon/'>Explore on Pantheon <i class='fa fa-external-link'></i></a>".format(
                self.attr.id_2char.upper())
            pantheon_section = {
                "title":
                "<a target='_blank' href='http://pantheon.media.mit.edu'><img src='http://pantheon.media.mit.edu/pantheon_logo.png' />",
                "source":
                "pantheon",
                "builds": [
                    {
                        "title":
                        _(u"Globally Famous People %(of_country)s",
                          of_country=self.attr.get_name(article="of")),
                        "iframe":
                        pantheon_iframe_fields,
                        "subtitle":
                        _(u"This treemap shows the cultural exports %(of_country)s, as proxied by the production of globally famous historical characters.</p><p>%(pantheon_link)s",
                          of_country=self.attr.get_name(article="of"),
                          pantheon_link=pantheon_link_fields),
                        "tour":
                        "Pantheon...",
                        "seq":
                        8
                    },
                    {
                        "title":
                        _(u"Globally Famous People %(of_country)s by City",
                          of_country=self.attr.get_name(article="of")),
                        "iframe":
                        pantheon_iframe_cities,
                        "subtitle":
                        _(u"This treemap shows the cultural exports %(of_country)s by city, as proxied by the production of globally famous historical characters.</p><p>%(pantheon_link)s",
                          of_country=self.attr.get_name(article="of"),
                          pantheon_link=pantheon_link_cities)
                    },
                ]
            }
            sections.append(pantheon_section)

        return sections
예제 #7
0
파일: views.py 프로젝트: hartmado/oec
def visualize(app_name, classification, trade_flow, origin_id, dest_id, prod_id, year=None):
    g.page_type = "visualize"
    g.page_sub_type = app_name

    if app_name == "scatter":
        year = [y for y in year if y >= 1980]
    elif trade_flow == "eci":
        year = [y for y in year if y >= 1964]

    '''sanitize input args'''
    redir = sanitize(app_name, classification, trade_flow, origin_id, dest_id, prod_id, year)
    if redir:
        flash(redir[0])
        return redirect(redir[1])

    '''get this build'''
    build = Build(app_name, classification, trade_flow, origin_id, dest_id, prod_id, year)
    if build.title() is None and build.question() is None:
        abort(404)

    '''get every possible build for sub nav'''
    origin, dest, prod = get_origin_dest_prod(origin_id, dest_id, prod_id, classification, year, trade_flow)
    all_builds = get_all_builds(classification, origin_id, dest_id, prod_id, year, {"origin":origin, "dest":dest, "prod":prod})

    '''create the ui array for the current build'''
    ui = []

    all_country = {
        "color": "#333333",
        "display_id": "all",
        "id": "all",
        "icon": "/static/img/icons/app/app_geo_map.png",
        "name": "All"
    }
    all_placed = False

    if build.trade_flow != "eci" and build.viz["slug"] not in ("scatter", "geo_map") and build.origin != "show":
        if isinstance(build.origin, Country):
            origin_country = build.origin.serialize()
        else:
            origin_country = all_country
            all_placed = True

        ui.append({
            "id": "origin",
            "name": gettext("Country"),
            "data": [origin_country],
            "url": url_for('attr.attrs', attr='country', lang=g.locale)
        })

    dest_country = False
    prod_exists = isinstance(build.prod, (Sitc, Hs92, Hs96, Hs02, Hs07))

    if isinstance(build.dest, Country):
        dest_country = build.dest.serialize()
    elif not all_placed and not prod_exists and build.viz["slug"] in ("tree_map", "line", "stacked"):
        dest_country = all_country

    if dest_country:
        ui.append({
            "id": "destination",
            "name": gettext("Country") if build.trade_flow == "eci" else gettext("Partner"),
            "data": [dest_country],
            "url": url_for('attr.attrs', attr='country', lang=g.locale)
        })

    if prod_exists:
        product = {
            "id": "product",
            "name": gettext("Product"),
            "data": [build.prod.serialize()],
            "url": url_for('attr.attrs', attr=build.classification, lang=g.locale)
        }
        ui.append(product)

    if build.viz["slug"] == "scatter":
        trade_flow = {
            "id": "trade_flow",
            "name": gettext("Y Axis"),
            "current": build.trade_flow,
            "data": [
                {"name": gettext("GDP"), "display_id":"gdp"},
                {"name": gettext("GDPpc (constant '05 US$)"), "display_id":"gdp_pc_constant"},
                {"name": gettext("GDPpc (current US$)"), "display_id":"gdp_pc_current"},
                {"name": gettext("GDPpc PPP (constant '11)"), "display_id":"gdp_pc_constant_ppp"},
                {"name": gettext("GDPpc PPP (current)"), "display_id":"gdp_pc_current_ppp"}
            ]
        }
    else:
        trade_flow = {
            "id": "trade_flow",
            "name": gettext("Trade Flow"),
            "current": build.trade_flow,
            "data": [
                {"name": gettext("Export"), "display_id":"export"},
                {"name": gettext("Import"), "display_id":"import"}
            ]
        }

    if build.trade_flow not in ("show", "eci"):
        ui.append(trade_flow)

    if build.trade_flow != "eci":
        ui.append({
            "id": "classification",
            "name": gettext("Dataset"),
            "current": build.classification,
            "data": ["HS92", "HS96", "HS02", "HS07", "SITC"]
        })

    years = set()
    for d in available_years:
        [years.add(y) for y in available_years[d] if (build.trade_flow == "eci" and y >= 1964) or (build.viz["slug"] == "scatter" and y >= 1980) or (build.viz["slug"] != "scatter" and build.trade_flow != "eci")]

    if build.viz["slug"] in ("stacked", "line"):
        ui.append({
            "id": "start_year",
            "name": gettext("Start Year"),
            "current": build.year[0],
            "data": years
        })
        ui.append({
            "id": "end_year",
            "name": gettext("End Year"),
            "current": build.year[-1],
            "data": years
        })
    else:
        ui.append({
            "id": "year",
            "name": gettext("Year"),
            "current": build.year[-1],
            "data": years
        })

    builds_by_app = {}
    for b in all_builds:
        if b.viz["slug"] not in ("stacked", "line"):
            b.year = [b.year[-1]]
            b.year_str = Build.year_to_str(b, b.year)
        if not hasattr(builds_by_app, b.viz["slug"]):
            builds_by_app[b.viz["slug"]] = []
    for b in all_builds:
        builds_by_app[b.viz["slug"]].append(b)

    page = "index_new" if request.args.get("beta") == "" else "index"

    return render_template("visualize/{}.html".format(page),
        current_build = build, build_ui = ui,
        all_builds = builds_by_app.values())