Ejemplo n.º 1
0
    def test_plot(self):
        self.episode_data = EpisodeData.from_disk(
            os.path.join(self.agents_path, self.agent_name), self.scenario_name
        )
        self.episode_analytics = EpisodeAnalytics(
            self.episode_data, self.scenario_name, self.agent_name
        )
        self.episode_analytics.decorate(self.episode_data)

        make_network(self.episode_analytics).plot_obs(self.episode_analytics.observations[0])
Ejemplo n.º 2
0
 def update_interactive_graph(slider_value, study_agent, scenario):
     new_episode = make_episode(study_agent, scenario)
     act = new_episode.actions[slider_value]
     if any(act.get_types()):
         act_as_str = str(act)
     else:
         act_as_str = "NO ACTION"
     return make_network(new_episode).plot_obs(new_episode.observations[slider_value]), act_as_str
Ejemplo n.º 3
0
def layout(scenario, studied_agent):
    episode = make_episode(studied_agent, scenario)
    # TODO : center en correct time step
    network_graph = make_network(episode).plot_obs(
        observation=episode.observations[0]
    )
    return html.Div(id="simulation_page", children=[
        choose_assist_line(episode, network_graph),
        compare_line(network_graph),
    ])
Ejemplo n.º 4
0
 def update_network_graph(study_agent, scenario):
     episode = make_episode(study_agent, scenario)
     modified_lines = actions_model.get_modified_lines(episode)
     line_values = [None] * episode.n_lines
     for line in modified_lines.index:
         line_values[np.where(episode.line_names == line)[0][0]] = line
     network_graph = make_network(episode).plot_info(
         observation=episode.observations[0],
         line_values=line_values,
     )
     return network_graph
Ejemplo n.º 5
0
    def update_action(n_clicks, action_dict, agent, scenario):
        episode = make_episode(agent, scenario)
        if action_dict is None:
            raise PreventUpdate
        action_dict = json.loads(
            action_dict.replace("(", "[").replace(")", "]"))

        # Temporary implementation for testing purposes
        p = Parameters()
        p.NO_OVERFLOW_DISCONNECTION = False
        env = make(
            r"D:\Projects\RTE-Grid2Viz\Grid2Op\grid2op\data\rte_case14_realistic",
            test=True,
            param=p,
        )
        env.seed(0)

        params_for_runner = env.get_params_for_runner()
        params_to_fetch = ["init_grid_path"]
        params_for_reboot = {
            key: value
            for key, value in params_for_runner.items()
            if key in params_to_fetch
        }
        params_for_reboot["parameters"] = p

        episode_reboot = EpisodeReboot.EpisodeReboot()
        agent_path = r"D:/Projects/RTE-Grid2Viz/grid2viz/grid2viz/data/agents/do-nothing-baseline"
        episode_reboot.load(
            env.backend,
            data=episode,
            agent_path=agent_path,
            name=episode.episode_name,
            env_kwargs=params_for_reboot,
        )
        current_time_step = 0
        obs, reward, *_ = episode_reboot.go_to(1)
        agent = DoNothingAgent(action_space=episode_reboot.env.action_space)
        act = agent.act(obs, reward)
        act = act.update(action_dict)
        obs, *_ = obs.simulate(action=act, time_step=0)
        network_graph = make_network(episode).plot_obs(observation=obs)
        return json.dumps(action_dict, indent=1), network_graph
Ejemplo n.º 6
0
def layout(user_selected_timestamp, study_agent, ref_agent, scenario):
    best_episode = make_episode(best_agents[scenario]["agent"], scenario)
    new_episode = make_episode(study_agent, scenario)
    center_indx = center_index(user_selected_timestamp, new_episode)
    network_graph = make_network(new_episode).get_plot_observation(
        new_episode.observations[center_indx])

    return html.Div(id="micro_page",
                    children=[
                        dcc.Store(id="window",
                                  data=compute_window(user_selected_timestamp,
                                                      study_agent, scenario)),
                        indicator_line(),
                        flux_inspector_line(
                            network_graph,
                            slider_params(user_selected_timestamp,
                                          new_episode)),
                        context_inspector_line(best_episode, new_episode),
                        all_info_line
                    ])
Ejemplo n.º 7
0
    def update_action(
        add_n_clicks,
        reset_n_clicks,
        network_graph_t,
        actions,
        action_dict,
        method_tab,
        objet_tab,
        selected_line,
        selected_load,
        selected_gen,
        topology_type_lines,
        disc_rec_lines,
        target_lines,
        bus_lines,
        ex_or_lines,
        topology_type_loads,
        bus_loads,
        action_type_gens,
        topology_type_gens,
        bus_gens,
        redisp_volume,
        network_graph_new,
        scenario,
        study_agent,
        timestamp,
        timestep,
    ):
        ctx = callback_context

        if not ctx.triggered:
            raise PreventUpdate
        else:
            button_id = ctx.triggered[0]["prop_id"].split(".")[0]

        if button_id == "reset_action" or button_id == "network_graph_t":
            graph_div = dcc.Graph(figure=network_graph_t)
            return (
                None,
                "Compose some actions to study",
                graph_div,
                None,
                network_graph_t,
            )

        if add_n_clicks is None:
            raise PreventUpdate
        episode = make_episode(study_agent, scenario)
        if method_tab == "tab_method_dropdowns":
            # Dropdown
            if objet_tab == "tab_object_lines":
                # Lines
                params_dict = dict(
                    ex_or_lines=ex_or_lines,
                    target_lines=target_lines,
                    disc_rec_lines=disc_rec_lines,
                )
                action_dict = action_dict_from_choose_tab(
                    episode,
                    kind="Lines",
                    selected_object=selected_line,
                    bus=bus_lines,
                    topology_type=topology_type_lines,
                    params_dict=params_dict,
                )

            elif objet_tab == "tab_object_loads":
                # Loads
                action_dict = action_dict_from_choose_tab(
                    episode,
                    kind="Loads",
                    selected_object=selected_load,
                    bus=bus_loads,
                    topology_type=topology_type_loads,
                )
            else:
                # Gens: tab_object_gens
                params_dict = dict(
                    action_type_gens=action_type_gens,
                    redisp_volume=redisp_volume,
                )
                action_dict = action_dict_from_choose_tab(
                    episode,
                    kind="Gens",
                    selected_object=selected_gen,
                    bus=bus_gens,
                    topology_type=topology_type_gens,
                    params_dict=params_dict,
                )
            if actions is None:
                actions = [action_dict]
            else:
                actions.append(action_dict)
        else:
            # Dict: tab_method_dict
            if action_dict is None:
                raise PreventUpdate
            try:
                action_dict = json.loads(
                    action_dict.replace("(", "[").replace(")", "]"))
            except json.decoder.JSONDecodeError as ex:
                import traceback

                graph_div_child = html.Div(children=traceback.format_exc(),
                                           className="more-info-table")
                return actions, "", graph_div_child, action_dict, network_graph_t
            if "action_list" in action_dict:
                actions_for_textarea = action_dict["action_list"]
            else:
                actions_for_textarea = [action_dict]
            if actions is None:
                actions = actions_for_textarea
            else:
                actions.extend(actions_for_textarea)

        episode_reboot = EpisodeReboot.EpisodeReboot()
        episode_reboot.load(
            env.backend,
            data=episode,
            agent_path=os.path.join(agents_dir, study_agent),
            name=episode.episode_name,
            env_kwargs=params_for_reboot,
        )
        obs, reward, *_ = episode_reboot.go_to(int(timestep))
        obs._obs_env.set_thermal_limit(env.get_thermal_limit())
        act = env.action_space()

        if not np.all(
                np.round(episode.observations[int(timestep)].a_or, 2) ==
                np.round(obs.a_or, 2)):
            return (
                actions,
                "",
                html.Div(
                    children=
                    f"Issue - Unable to reboot episode at time step {timestep} for agent {episode.agent}",
                    className="more-info-table",
                ),
                "",
                network_graph_t,
            )

        for action in actions:
            act.update(action)
        obs, *_ = obs.simulate(action=act, time_step=0)

        try:
            graph_div_child = dcc.Graph(figure=network_graph_t)
            new_network_graph = make_network(episode).plot_obs(observation=obs)
        except ValueError:
            import traceback

            graph_div_child = html.Div(children=traceback.format_exc(),
                                       className="more-info-table")
            new_network_graph = network_graph_t

        try:
            json.dumps(actions)
        except Exception as ex:
            print("actions")
            print(actions)
        if method_tab == "tab_method_dropdowns":
            return (
                actions,
                str(act),
                graph_div_child,
                json.dumps(
                    (dict(action_list=[NoIndent(action)
                                       for action in actions])),
                    indent=2,
                    sort_keys=True,
                    cls=MyEncoder,
                ),
                new_network_graph,
            )
        else:
            actions_for_textarea = dict(action_list=[
                *[NoIndent(action) for action in actions[:-1]],
                actions[-1],
            ])

            return (
                actions,
                str(act),
                graph_div_child,
                json.dumps(
                    (dict(action_list=[NoIndent(action)
                                       for action in actions])),
                    indent=2,
                    sort_keys=True,
                    cls=MyEncoder,
                ),
                new_network_graph,
            )
Ejemplo n.º 8
0
def indicator_line(scenario, study_agent, ref_agent):
    episode = make_episode(study_agent, scenario)
    ref_episode = make_episode(ref_agent, scenario)
    figures_distribution = action_distrubtion(episode, ref_episode)

    modified_lines = actions_model.get_modified_lines(episode)
    line_values = [None] * episode.n_lines
    for line in modified_lines.index:
        line_values[np.where(episode.line_names == line)[0][0]] = line
    network_graph = make_network(episode).plot_info(
        observation=episode.observations[0],
        line_values=line_values,
    )
    nb_actions = episode.action_data_table[[
        'action_line', 'action_subs', 'action_redisp'
    ]].sum()

    if nb_actions.sum() == 0:
        pie_figure = go.Figure(
            layout=layout_no_data("No Actions for this Agent"))
    else:
        pie_figure = go.Figure(layout=layout_def,
                               data=[
                                   go.Pie(labels=[
                                       "Actions on Lines",
                                       "Actions on Substations",
                                       "Redispatching Actions"
                                   ],
                                          values=[
                                              nb_actions["action_line"],
                                              nb_actions["action_subs"],
                                              nb_actions["action_redisp"]
                                          ])
                               ])

    return html.Div(
        className="lineBlock card",
        children=[
            html.H4("Indicators"),
            html.Div(
                className="card-body row",
                children=[
                    html.Div(
                        className="col-2",
                        children=[
                            html.H5("Agent to study Selection"),
                            dcc.Dropdown(id='agent_log_selector',
                                         options=[{
                                             'label': agent,
                                             'value': agent
                                         } for agent in agents],
                                         value=study_agent,
                                         placeholder="Agent log"),
                            html.Div(
                                className="m-2",
                                children=[
                                    html.
                                    P(id="indicator_score_output",
                                      className=
                                      "border-bottom h3 mb-0 text-right",
                                      children=round(
                                          episode.meta["cumulative_reward"])),
                                    html.P(className="text-muted",
                                           children="Score")
                                ]),
                            html.Div(
                                className="m-2",
                                children=[
                                    html.P(
                                        id="indicator_nb_maintenances",
                                        className=
                                        "border-bottom h3 mb-0 text-right",
                                        children='{}/{}'.format(
                                            episode.meta['nb_timestep_played'],
                                            episode.
                                            meta['chronics_max_timestep'])),
                                    html.P(className="text-muted",
                                           children="Agent's Survival")
                                ]),
                            html.Div(
                                className="m-2",
                                children=[
                                    html.P(id="indicator_nb_overflow",
                                           className=
                                           "border-bottom h3 mb-0 text-right",
                                           children=episode.
                                           total_overflow_ts["value"].sum()),
                                    html.P(className="text-muted",
                                           children="Number of Overflow")
                                ]),
                            html.Div(
                                className="m-2",
                                children=[
                                    html.P(id="indicator_nb_action",
                                           className=
                                           "border-bottom h3 mb-0 text-right",
                                           children=episode.action_data_table[[
                                               'action_line', 'action_subs'
                                           ]].sum(axis=1).sum()),
                                    html.P(className="text-muted ",
                                           children="Number of Action")
                                ]),
                            html.Div(
                                className="m-2",
                                children=[
                                    html.P(id="indicator_nb_maintenances",
                                           className=
                                           "border-bottom h3 mb-0 text-right",
                                           children=episode.nb_maintenances),
                                    html.P(className="text-muted",
                                           children="Number of Maintenances")
                                ]),
                        ]),
                    html.Div(className="col-3",
                             children=[
                                 html.H6(className="text-center",
                                         children="Type Action Repartition"),
                                 dcc.Graph(id="agent_study_pie_chart",
                                           figure=pie_figure)
                             ]),
                    html.Div(className="col-7",
                             children=[
                                 html.H6(
                                     className="text-center",
                                     children="//WIP// Impacted grid assets"),
                                 dcc.Graph(id="network_actions",
                                           figure=network_graph)
                             ]),
                    html.Div(className="col-12",
                             children=[
                                 html.H2(className="text-center",
                                         children="Actions Distributions")
                             ]),
                    html.Div(className="col-4",
                             children=[
                                 html.H6(className="text-center",
                                         children="On Substations"),
                                 dcc.Graph(
                                     id="distribution_substation_action_chart",
                                     figure=figures_distribution.on_subs)
                             ]),
                    html.Div(className="col-4",
                             children=[
                                 html.H6(className="text-center",
                                         children="On Lines"),
                                 dcc.Graph(
                                     id="distribution_line_action_chart",
                                     figure=figures_distribution.on_lines)
                             ]),
                    html.Div(className="col-4",
                             children=[
                                 html.H6(className="text-center",
                                         children="Redispatching"),
                                 dcc.Graph(
                                     id="distribution_redisp_action_chart",
                                     figure=figures_distribution.redisp)
                             ]),
                ]),
        ])
Ejemplo n.º 9
0
def update_interactive_graph(slider_value, study_agent, scenario):
    new_episode = make_episode(study_agent, scenario)
    return make_network(new_episode).get_plot_observation(
        new_episode.observations[slider_value])