Skip to content

icj_to_csv

inset_chart_json_to_csv_dataframe_pd(output_path)

Convert InsetChart.json file in 'output_path' to InsetChart.csv. Adding Simulation_Year column if Base_Year exists in config.json.

Args:

1
output_path (str): Subdirectory in which to find InsetChart.json

Returns:

Raises:

Type Description
ValueError

if InsetChart.json can't be found.

ValueError

if InsetChart.csv can't be written.

Source code in emod_api/channelreports/icj_to_csv.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def inset_chart_json_to_csv_dataframe_pd(output_path: str):
    """
    Convert InsetChart.json file in 'output_path' to InsetChart.csv.
    Adding Simulation_Year column if Base_Year exists in config.json.

    Args:

        output_path (str): Subdirectory in which to find InsetChart.json

    Returns:

    Raises:
        ValueError: if InsetChart.json can't be found.
        ValueError: if InsetChart.csv can't be written.
    """

    icj_path = os.path.join(output_path, "InsetChart.json")
    if not os.path.exists(icj_path):
        raise ValueError(f"InsetChart.json not found at {output_path}.")

    # Load JSON data from file
    with open(icj_path) as fp:
        icj = json.load(fp)

    optional_years_channel = _get_sim_years(output_path)
    if optional_years_channel:
        icj["Channels"]["Simulation_Year"]["Data"] = optional_years_channel

    # Create an empty DataFrame
    df = pd.DataFrame()

    # Iterate over the Channels keys and extract time series data
    for channel, values in icj["Channels"].items():
        # Create a column in the DataFrame for each channel
        df[channel] = values["Data"]

    try:
        # Convert DataFrame to CSV
        csv_path = os.path.join(output_path, "InsetChart.csv")
        df.to_csv(csv_path, index=False)
    except Exception as ex:
        print(f"ERROR: Exception {ex} while writing csv dataframe of InsetChart.json to disk.")
        raise ValueError(ex)