#!/usr/bin/env python3 """ Example script demonstrating how to load the IFVI Value Factors dataset in different formats (JSON, CSV, Parquet). """ import os import json import pandas as pd import matplotlib.pyplot as plt from pathlib import Path # Get the repository root directory REPO_ROOT = Path(__file__).parent.parent.parent.absolute() def load_json_data(country_name): """ Load value factors for a specific country from JSON file. Args: country_name (str): Name of the country Returns: dict: Value factors data for the country """ # First try to find the country in the by-territory structure continents = ["Africa", "Asia", "Europe", "North America", "Oceania", "South America"] for continent in continents: country_path = REPO_ROOT / "data" / "by-territory" / "by-continent" / continent / f"{country_name}.json" if country_path.exists(): # This is a Git LFS file, so we need to handle it differently # In a real implementation, you would use the git-lfs Python package # For this example, we'll assume the file is already pulled # For demonstration purposes, we'll load the composite data instead composite_path = REPO_ROOT / "data" / "composite-data" / "all-formats" / "composite_value_factors.json" if composite_path.exists(): with open(composite_path, 'r') as f: data = json.load(f) # Filter for the specific country if country_name in data: return data[country_name] print(f"Country file found but using composite data instead: {country_path}") return {} print(f"Country not found: {country_name}") return {} def load_csv_data(): """ Load the entire dataset from CSV. Returns: pandas.DataFrame: Value factors data """ csv_path = REPO_ROOT / "data" / "composite-data" / "all-formats" / "composite_value_factors.csv" if csv_path.exists(): return pd.read_csv(csv_path) else: print(f"CSV file not found: {csv_path}") return pd.DataFrame() def load_parquet_data(): """ Load the entire dataset from Parquet. Returns: pandas.DataFrame: Value factors data """ parquet_path = REPO_ROOT / "data" / "composite-data" / "all-formats" / "composite_value_factors.parquet" if parquet_path.exists(): return pd.read_parquet(parquet_path) else: print(f"Parquet file not found: {parquet_path}") return pd.DataFrame() def compare_countries(countries, category, impact): """ Compare value factors across countries for a specific category and impact. Args: countries (list): List of country names category (str): Environmental impact category impact (str): Impact type Returns: pandas.DataFrame: Comparison data """ data = load_csv_data() if data.empty: return pd.DataFrame() # Filter for the specific category and impact filtered_data = data[(data['Category'] == category) & (data['Impact'] == impact)] # Filter for the specified countries country_data = filtered_data[filtered_data['Territory'].isin(countries)] return country_data def plot_country_comparison(countries, category, impact): """ Plot a comparison of value factors across countries. Args: countries (list): List of country names category (str): Environmental impact category impact (str): Impact type """ comparison_data = compare_countries(countries, category, impact) if comparison_data.empty: print("No data available for the specified parameters") return plt.figure(figsize=(10, 6)) plt.bar(comparison_data['Territory'], comparison_data['ValueFactor']) plt.title(f"{category} - {impact} Value Factors by Country") plt.xlabel("Country") plt.ylabel("Value Factor (USD)") plt.xticks(rotation=45) plt.tight_layout() # Save the plot output_dir = REPO_ROOT / "examples" / "outputs" output_dir.mkdir(parents=True, exist_ok=True) plt.savefig(output_dir / f"{category}_{impact}_comparison.png") plt.close() def main(): """Main function demonstrating the use of the dataset.""" # Example 1: Load data for a specific country country_data = load_json_data("United States") print(f"Number of value factors for United States: {len(country_data) if country_data else 0}") # Example 2: Load CSV data csv_data = load_csv_data() print(f"CSV data shape: {csv_data.shape}") # Example 3: Load Parquet data parquet_data = load_parquet_data() print(f"Parquet data shape: {parquet_data.shape}") # Example 4: Compare countries countries_to_compare = ["United States", "China", "Germany", "Brazil", "India"] comparison = compare_countries(countries_to_compare, "PM2.5", "Primary Health") print("\nComparison of PM2.5 Primary Health value factors:") print(comparison[['Territory', 'Location', 'ValueFactor']].to_string(index=False)) # Example 5: Plot comparison plot_country_comparison(countries_to_compare, "PM2.5", "Primary Health") print("\nPlot saved to examples/outputs/PM2.5_Primary Health_comparison.png") if __name__ == "__main__": main()