diff --git a/examples/backend_integration/Step1_loading.py b/examples/backend_integration/Step1_loading.py index a456a2106..4775ba85d 100644 --- a/examples/backend_integration/Step1_loading.py +++ b/examples/backend_integration/Step1_loading.py @@ -30,6 +30,8 @@ # to serve as an example import pandapower as pp +ERR_MSG_ELSEWHERE = "Will be detailed in another example script" + class CustomBackend_Step1(Backend): def load_grid(self, @@ -97,25 +99,25 @@ def load_grid(self, self._compute_pos_big_topo() def apply_action(self, backendAction: Union["grid2op.Action._backendAction._BackendAction", None]) -> None: - raise NotImplementedError("Will be detailed in another example script") + raise NotImplementedError() def runpf(self, is_dc : bool=False) -> Tuple[bool, Union[Exception, None]]: - raise NotImplementedError("Will be detailed in another example script") + raise NotImplementedError(ERR_MSG_ELSEWHERE) def get_topo_vect(self) -> np.ndarray: - raise NotImplementedError("Will be detailed in another example script") + raise NotImplementedError(ERR_MSG_ELSEWHERE) def generators_info(self)-> Tuple[np.ndarray, np.ndarray, np.ndarray]: - raise NotImplementedError("Will be detailed in another example script") + raise NotImplementedError(ERR_MSG_ELSEWHERE) def loads_info(self)-> Tuple[np.ndarray, np.ndarray, np.ndarray]: - raise NotImplementedError("Will be detailed in another example script") + raise NotImplementedError(ERR_MSG_ELSEWHERE) def lines_or_info(self)-> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - raise NotImplementedError("Will be detailed in another example script") + raise NotImplementedError(ERR_MSG_ELSEWHERE) def lines_ex_info(self)-> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - raise NotImplementedError("Will be detailed in another example script") + raise NotImplementedError(ERR_MSG_ELSEWHERE) if __name__ == "__main__": diff --git a/examples/backend_integration/Step4_modify_line_status.py b/examples/backend_integration/Step4_modify_line_status.py index 1f3cac741..e4e7c5057 100644 --- a/examples/backend_integration/Step4_modify_line_status.py +++ b/examples/backend_integration/Step4_modify_line_status.py @@ -224,10 +224,10 @@ def lines_ex_info(self)-> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: print(f"{q_or = }") print(f"{v_or = }") print(f"{a_or = }") - assert p_or[0] == 0. - assert q_or[0] == 0. - assert v_or[0] == 0. - assert a_or[0] == 0. + assert np.abs(p_or[0]) <= 1e-7 + assert np.abs(q_or[0]) <= 1e-7 + assert np.abs(v_or[0]) <= 1e-7 + assert np.abs(a_or[0]) <= 1e-7 # this is how "user" manipute the grid # in this I reconnect powerline 0 @@ -280,7 +280,7 @@ def lines_ex_info(self)-> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: print(f"{q_or = }") print(f"{v_or = }") print(f"{a_or = }") - assert p_or[line_id] == 0. - assert q_or[line_id] == 0. - assert v_or[line_id] == 0. - assert a_or[line_id] == 0. + assert np.abs(p_or[line_id]) <= 1e-7 + assert np.abs(q_or[line_id]) <= 1e-7 + assert np.abs(v_or[line_id]) <= 1e-7 + assert np.abs(a_or[line_id]) <= 1e-7 diff --git a/grid2op/Action/_backendAction.py b/grid2op/Action/_backendAction.py index fbc05f52c..33fd95ffe 100644 --- a/grid2op/Action/_backendAction.py +++ b/grid2op/Action/_backendAction.py @@ -59,7 +59,7 @@ def _change_val_int(self, newvals): self.values[changed_] = (1 - self.values[changed_]) + 2 def _change_val_float(self, newvals): - changed_ = newvals != 0.0 + changed_ = np.abs(newvals) >= 1e-7 self.changed[changed_] = True self.values[changed_] += newvals[changed_] diff --git a/grid2op/Action/baseAction.py b/grid2op/Action/baseAction.py index 11ec65282..596ff74bc 100644 --- a/grid2op/Action/baseAction.py +++ b/grid2op/Action/baseAction.py @@ -589,7 +589,7 @@ def _aux_serialize_add_key_change(self, attr_nm, dict_key, res): res[dict_key] = tmp_ def _aux_serialize_add_key_set(self, attr_nm, dict_key, res): - tmp_ = [(int(id_), int(val)) for id_, val in enumerate(getattr(self, attr_nm)) if val != 0.] + tmp_ = [(int(id_), int(val)) for id_, val in enumerate(getattr(self, attr_nm)) if np.abs(val) >= 1e-7] if tmp_: res[dict_key] = tmp_ @@ -683,7 +683,7 @@ def as_serializable_dict(self) -> dict: res["redispatch"] = [ (int(id_), float(val)) for id_, val in enumerate(self._redispatch) - if val != 0.0 + if np.abs(val) >= 1e-7 ] if not res["redispatch"]: del res["redispatch"] @@ -692,7 +692,7 @@ def as_serializable_dict(self) -> dict: res["set_storage"] = [ (int(id_), float(val)) for id_, val in enumerate(self._storage_power) - if val != 0.0 + if np.abs(val) >= 1e-7 ] if not res["set_storage"]: del res["set_storage"] @@ -701,7 +701,7 @@ def as_serializable_dict(self) -> dict: res["curtail"] = [ (int(id_), float(val)) for id_, val in enumerate(self._curtail) - if val != -1 + if np.abs(val + 1.) >= 1e-7 ] if not res["curtail"]: del res["curtail"] @@ -896,10 +896,10 @@ def _post_process_from_vect(self): self._modif_set_status = (self._set_line_status != 0).any() self._modif_change_status = (self._switch_line_status).any() self._modif_redispatch = ( - np.isfinite(self._redispatch) & (self._redispatch != 0.0) + np.isfinite(self._redispatch) & (np.abs(self._redispatch) >= 1e-7) ).any() - self._modif_storage = (self._storage_power != 0.0).any() - self._modif_curtailment = (self._curtail != -1.0).any() + self._modif_storage = (np.abs(self._storage_power) >= 1e-7).any() + self._modif_curtailment = (np.abs(self._curtail + 1.0) >= 1e-7).any() self._modif_alarm = self._raise_alarm.any() self._modif_alert = self._raise_alert.any() @@ -912,7 +912,7 @@ def _assign_attr_from_name(self, attr_nm, vect): super()._assign_attr_from_name(attr_nm, vect) self._post_process_from_vect() else: - if np.isfinite(vect).any() and (vect != 0.0).any(): + if np.isfinite(vect).any() and (np.abs(vect) >= 1e-7).any(): self._dict_inj[attr_nm] = vect def check_space_legit(self): @@ -1539,7 +1539,7 @@ def _aux_iadd_inj(self, other): def _aux_iadd_redisp(self, other): redispatching = other._redispatch - if (redispatching != 0.0).any(): + if (np.abs(redispatching) >= 1e-7).any(): if "_redispatch" not in self.attr_list_set: warnings.warn( type(self).ERR_ACTION_CUT.format("_redispatch") @@ -1550,7 +1550,7 @@ def _aux_iadd_redisp(self, other): def _aux_iadd_curtail(self, other): curtailment = other._curtail - ok_ind = np.isfinite(curtailment) & (curtailment != -1.0) + ok_ind = np.isfinite(curtailment) & (np.abs(curtailment + 1.0) >= 1e-7) if ok_ind.any(): if "_curtail" not in self.attr_list_set: warnings.warn( @@ -1564,7 +1564,7 @@ def _aux_iadd_curtail(self, other): def _aux_iadd_storage(self, other): set_storage = other._storage_power - ok_ind = np.isfinite(set_storage) & (set_storage != 0.0).any() + ok_ind = np.isfinite(set_storage) & (np.abs(set_storage) >= 1e-7).any() if ok_ind.any(): if "_storage_power" not in self.attr_list_set: warnings.warn( @@ -2423,7 +2423,7 @@ def _check_for_correct_modif_flags(self): "You illegally act on the powerline status (using change)" ) - if (self._redispatch != 0.0).any(): + if (np.abs(self._redispatch) >= 1e-7).any(): if not self._modif_redispatch: raise AmbiguousAction( "A action of type redispatch is performed while the appropriate flag " @@ -2434,7 +2434,7 @@ def _check_for_correct_modif_flags(self): if "redispatch" not in self.authorized_keys: raise IllegalAction("You illegally act on the redispatching") - if (self._storage_power != 0.0).any(): + if (np.abs(self._storage_power) >= 1e-7).any(): if not self._modif_storage: raise AmbiguousAction( "A action on the storage unit is performed while the appropriate flag " @@ -2445,7 +2445,7 @@ def _check_for_correct_modif_flags(self): if "set_storage" not in self.authorized_keys: raise IllegalAction("You illegally act on the storage unit") - if (self._curtail != -1.0).any(): + if (np.abs(self._curtail + 1.0) >= 1e-7).any(): if not self._modif_curtailment: raise AmbiguousAction( "A curtailment is performed while the action is not supposed to have done so. " @@ -2876,8 +2876,8 @@ def _is_curtailment_ambiguous(self): "units affected" ) - if ((self._curtail < 0.0) & (self._curtail != -1.0)).any(): - where_bug = np.nonzero((self._curtail < 0.0) & (self._curtail != -1.0))[0] + if ((self._curtail < 0.0) & (np.abs(self._curtail + 1.0) >= 1e-7)).any(): + where_bug = np.nonzero((self._curtail < 0.0) & (np.abs(self._curtail + 1.0) >= 1e-7))[0] raise InvalidCurtailment( f"you asked to perform a negative curtailment: " f"self._curtail[{where_bug}] < 0. " @@ -2890,7 +2890,7 @@ def _is_curtailment_ambiguous(self): f"self._curtail[{where_bug}] > 1. " f"Curtailment should be a real number between 0.0 and 1.0" ) - if (self._curtail[~cls.gen_renewable] != -1.0).any(): + if (np.abs(self._curtail[~cls.gen_renewable] +1.0) >= 1e-7).any(): raise InvalidCurtailment( "Trying to apply a curtailment on a non renewable generator" ) @@ -2989,7 +2989,7 @@ def __str__(self) -> str: "\t - Modify the generators with redispatching in the following way:" ) for gen_idx in range(self.n_gen): - if self._redispatch[gen_idx] != 0.0: + if np.abs(self._redispatch[gen_idx]) >= 1e-7: gen_name = self.name_gen[gen_idx] r_amount = self._redispatch[gen_idx] res.append( @@ -3005,7 +3005,7 @@ def __str__(self) -> str: res.append("\t - Modify the storage units in the following way:") for stor_idx in range(self.n_storage): amount_ = self._storage_power[stor_idx] - if np.isfinite(amount_) and amount_ != 0.0: + if np.isfinite(amount_) and np.abs(amount_) >= 1e-7: name_ = self.name_storage[stor_idx] res.append( '\t \t - Ask unit "{}" to {} {:.2f} MW (setpoint: {:.2f} MW)' @@ -3024,7 +3024,7 @@ def __str__(self) -> str: res.append("\t - Perform the following curtailment:") for gen_idx in range(self.n_gen): amount_ = self._curtail[gen_idx] - if np.isfinite(amount_) and amount_ != -1.0: + if np.isfinite(amount_) and np.abs(amount_ + 1.0) >= 1e-7: name_ = self.name_gen[gen_idx] res.append( '\t \t - Limit unit "{}" to {:.1f}% of its Pmax (setpoint: {:.3f})' @@ -3245,9 +3245,9 @@ def impact_on_objects(self) -> dict: # handle redispatching redispatch = {"changed": False, "generators": []} - if (self._redispatch != 0.0).any(): + if (np.abs(self._redispatch) >= 1e-7).any(): for gen_idx in range(self.n_gen): - if self._redispatch[gen_idx] != 0.0: + if np.abs(self._redispatch[gen_idx]) >= 1e-7: gen_name = self.name_gen[gen_idx] r_amount = self._redispatch[gen_idx] redispatch["generators"].append( @@ -3277,7 +3277,7 @@ def impact_on_objects(self) -> dict: if self._modif_curtailment: for gen_idx in range(self.n_gen): tmp = self._curtail[gen_idx] - if np.isfinite(tmp) and tmp != -1: + if np.isfinite(tmp) and np.abs(tmp + 1.) >= 1e-7: name_ = self.name_gen[gen_idx] new_max = tmp curtailment["limit"].append( @@ -3540,7 +3540,7 @@ def get_types(self) -> Tuple[bool, bool, bool, bool, bool, bool, bool]: lines_impacted, subs_impacted = self.get_topological_impact() topology = subs_impacted.any() line = lines_impacted.any() - redispatching = (self._redispatch != 0.0).any() + redispatching = (np.abs(self._redispatch) >= 1e-7).any() storage = self._modif_storage curtailment = self._modif_curtailment return injection, voltage, topology, line, redispatching, storage, curtailment @@ -6135,7 +6135,7 @@ def limit_curtail_storage(self, total_storage_consumed = res._storage_power.sum() # curtailment - gen_curtailed = (res._curtail != -1) & cls.gen_renewable + gen_curtailed = (np.abs(res._curtail + 1) >= 1e-7) & cls.gen_renewable gen_curtailed &= ( (obs.gen_p > res._curtail * cls.gen_pmax) | (obs.gen_p_before_curtail > obs.gen_p )) gen_p_after_max = (res._curtail * cls.gen_pmax)[gen_curtailed] diff --git a/grid2op/Action/serializableActionSpace.py b/grid2op/Action/serializableActionSpace.py index 04a3a1720..e291ec07e 100644 --- a/grid2op/Action/serializableActionSpace.py +++ b/grid2op/Action/serializableActionSpace.py @@ -1486,7 +1486,7 @@ def _custom_deepcopy_for_copy(self, new_obj): new_obj._template_act = self.actionClass() def _aux_get_back_to_ref_state_curtail(self, res, obs): - is_curtailed = obs.curtailment_limit != 1.0 + is_curtailed = np.abs(obs.curtailment_limit - 1.0) >= 1e-7 if is_curtailed.any(): res["curtailment"] = [] if not self.supports_type("curtail"): @@ -1546,7 +1546,7 @@ def _aux_get_back_to_ref_state_sub(self, res, obs): def _aux_get_back_to_ref_state_redisp(self, res, obs, precision=1e-5): # TODO this is ugly, probably slow and could definitely be optimized - notredisp_setpoint = obs.target_dispatch != 0.0 + notredisp_setpoint = np.abs(obs.target_dispatch) >= 1e-7 if notredisp_setpoint.any(): need_redisp = np.nonzero(notredisp_setpoint)[0] res["redispatching"] = [] @@ -1587,14 +1587,14 @@ def _aux_get_back_to_ref_state_redisp(self, res, obs, precision=1e-5): continue if obs.target_dispatch[gen_id] > 0.0: if nb_act < nb_[gen_id] - 1 or ( - rem[gen_id] == 0.0 and nb_act == nb_[gen_id] - 1 + np.abs(rem[gen_id]) <= 1e-7 and nb_act == nb_[gen_id] - 1 ): reds[gen_id] = -obs.gen_max_ramp_down[gen_id] else: reds[gen_id] = -rem[gen_id] else: if nb_act < nb_[gen_id] - 1 or ( - rem[gen_id] == 0.0 and nb_act == nb_[gen_id] - 1 + np.abs(rem[gen_id]) <= 1e-7 and nb_act == nb_[gen_id] - 1 ): reds[gen_id] = obs.gen_max_ramp_up[gen_id] else: @@ -1658,14 +1658,14 @@ def _aux_get_back_to_ref_state_storage( continue if current_state[stor_id] > 0.0: if nb_act < nb_[stor_id] - 1 or ( - rem[stor_id] == 0.0 and nb_act == nb_[stor_id] - 1 + np.abs(rem[stor_id]) <= 1e-7 and nb_act == nb_[stor_id] - 1 ): reds[stor_id] = -obs.storage_max_p_prod[stor_id] else: reds[stor_id] = -rem[stor_id] else: if nb_act < nb_[stor_id] - 1 or ( - rem[stor_id] == 0.0 and nb_act == nb_[stor_id] - 1 + np.abs(rem[stor_id]) <= 1e-7 and nb_act == nb_[stor_id] - 1 ): reds[stor_id] = obs.storage_max_p_absorb[stor_id] else: diff --git a/grid2op/Backend/backend.py b/grid2op/Backend/backend.py index 89ec9e060..a0fab4ebd 100644 --- a/grid2op/Backend/backend.py +++ b/grid2op/Backend/backend.py @@ -744,11 +744,11 @@ def set_thermal_limit(self, limits : Union[np.ndarray, Dict["str", float]]) -> N if el in limits: try: tmp = dt_float(limits[el]) - except: + except Exception as exc_: raise BackendError( 'Impossible to convert data ({}) for powerline named "{}" into float ' "values".format(limits[el], el) - ) + ) from exc_ if tmp <= 0: raise BackendError( 'New thermal limit for powerlines "{}" is not positive ({})' diff --git a/grid2op/Chronics/GSFFWFWM.py b/grid2op/Chronics/GSFFWFWM.py index 55d88196d..385886a34 100644 --- a/grid2op/Chronics/GSFFWFWM.py +++ b/grid2op/Chronics/GSFFWFWM.py @@ -157,7 +157,7 @@ def _fix_maintenance_format(obj_with_maintenance): ) # there are _maintenance and hazards only if the value in the file is not 0. - obj_with_maintenance.maintenance = obj_with_maintenance.maintenance != 0.0 + obj_with_maintenance.maintenance = np.abs(obj_with_maintenance.maintenance) >= 1e-7 obj_with_maintenance.maintenance = obj_with_maintenance.maintenance.astype(dt_bool) @staticmethod diff --git a/grid2op/Chronics/fromOneEpisodeData.py b/grid2op/Chronics/fromOneEpisodeData.py index 46e155a09..e3214b5b7 100644 --- a/grid2op/Chronics/fromOneEpisodeData.py +++ b/grid2op/Chronics/fromOneEpisodeData.py @@ -350,7 +350,6 @@ def get_id(self) -> str: else: # TODO EpisodeData.path !!! return "" - raise NotImplementedError() def shuffle(self, shuffler=None): # TODO diff --git a/grid2op/Chronics/gridStateFromFile.py b/grid2op/Chronics/gridStateFromFile.py index 1cc53a725..d9824637f 100644 --- a/grid2op/Chronics/gridStateFromFile.py +++ b/grid2op/Chronics/gridStateFromFile.py @@ -736,7 +736,7 @@ def _init_attrs( self.hazards[:, line_id] ) - self.hazards = self.hazards != 0.0 + self.hazards = np.abs(self.hazards) >= 1e-7 if maintenance is not None: self.maintenance = copy.deepcopy( maintenance.values[:, self._order_maintenance] @@ -759,7 +759,7 @@ def _init_attrs( ] = self.get_maintenance_duration_1d(self.maintenance[:, line_id]) # there are _maintenance and hazards only if the value in the file is not 0. - self.maintenance = self.maintenance != 0.0 + self.maintenance = np.abs(self.maintenance) >= 1e-7 self.maintenance = self.maintenance.astype(dt_bool) def done(self): @@ -1026,14 +1026,14 @@ def _convert_datetime(self, datetime_beg): if not isinstance(datetime_beg, datetime): try: res = datetime.strptime(datetime_beg, "%Y-%m-%d %H:%M") - except: + except Exception as exc_: try: res = datetime.strptime(datetime_beg, "%Y-%m-%d") - except: + except Exception as exc_2: raise ChronicsError( 'Impossible to convert "{}" to a valid datetime. Accepted format is ' '"%Y-%m-%d %H:%M"'.format(datetime_beg) - ) + ) from exc_2 return res def _extract_array(self, nm): diff --git a/grid2op/Chronics/handlers/csvMaintenanceHandler.py b/grid2op/Chronics/handlers/csvMaintenanceHandler.py index 19d45727e..2c47c510f 100644 --- a/grid2op/Chronics/handlers/csvMaintenanceHandler.py +++ b/grid2op/Chronics/handlers/csvMaintenanceHandler.py @@ -79,7 +79,7 @@ def _init_attrs(self, array): ] = GridValue.get_maintenance_duration_1d(self.array[:, line_id]) # there are _maintenance and hazards only if the value in the file is not 0. - self.array = self.array != 0.0 + self.array = np.abs(self.array) >= 1e-7 self.array = self.array.astype(dt_bool) def load_next_maintenance(self) -> Tuple[np.ndarray, np.ndarray]: diff --git a/grid2op/Chronics/readPypowNetData.py b/grid2op/Chronics/readPypowNetData.py index de5589f7a..68ca46db0 100644 --- a/grid2op/Chronics/readPypowNetData.py +++ b/grid2op/Chronics/readPypowNetData.py @@ -191,8 +191,8 @@ def initialize( self.start_datetime = datetime.strptime(datetimes_.iloc[0, 0], "%Y-%b-%d") # there are maintenance and hazards only if the value in the file is not 0. - self.maintenance = self.maintenance != 0.0 - self.hazards = self.hazards != 0.0 + self.maintenance = np.abs(self.maintenance) >= 1e-7 + self.hazards = np.abs(self.hazards) >= 1e-7 self.curr_iter = 0 if self.max_iter == -1: @@ -294,9 +294,8 @@ def initialize( self.hazard_duration[:, line_id] = self.get_maintenance_duration_1d( self.hazards[:, line_id] ) - - self.maintenance_forecast = self.maintenance != 0.0 - + self.maintenance_forecast = np.abs(self.maintenance) >= 1e-7 + self.curr_iter = 0 if self.maintenance is not None: n_ = self.maintenance.shape[0] diff --git a/grid2op/Converter/ConnectivityConverter.py b/grid2op/Converter/ConnectivityConverter.py index 41eed4adc..e9864d1dd 100644 --- a/grid2op/Converter/ConnectivityConverter.py +++ b/grid2op/Converter/ConnectivityConverter.py @@ -386,7 +386,7 @@ def convert_act(self, encoded_act, explore=None): f"encoded action at positions {indexes[:5]}... (only first 5 displayed)" ) - act_want_change = encoded_act != 0.0 + act_want_change = np.abs(encoded_act) >= 1e-7 encoded_act_filtered = encoded_act[act_want_change] if encoded_act_filtered.shape[0] == 0: # do nothing action in this case @@ -489,7 +489,7 @@ def _compute_disagreement(self, encoded_act, topo_vect): Lower disagreement is always better. """ - set_component = encoded_act != 0.0 + set_component = np.abs(encoded_act) >= 1e-7 bus_el1 = topo_vect[self.pos_topo[:, 0]] bus_el2 = topo_vect[self.pos_topo[:, 1]] # for the element that will connected diff --git a/grid2op/Environment/baseEnv.py b/grid2op/Environment/baseEnv.py index 14742504d..d35a9666d 100644 --- a/grid2op/Environment/baseEnv.py +++ b/grid2op/Environment/baseEnv.py @@ -1847,9 +1847,9 @@ def _prepare_redisp(self, action, new_p, already_modified_gen): redisp_act_orig = 1.0 * action._redispatch if ( - np.all(redisp_act_orig == 0.0) - and np.all(self._target_dispatch == 0.0) - and np.all(self._actual_dispatch == 0.0) + np.all(np.abs(redisp_act_orig) <= 1e-7) + and np.all(np.abs(self._target_dispatch) <= 1e-7) + and np.all(np.abs(self._actual_dispatch) <= 1e-7) ): return valid, except_, info_ # check that everything is consistent with pmin, pmax: @@ -1879,7 +1879,7 @@ def _prepare_redisp(self, action, new_p, already_modified_gen): return valid, except_, info_ # i can't redispatch turned off generators [turned off generators need to be turned on before redispatching] - if (redisp_act_orig[new_p == 0.0]).any() and self._forbid_dispatch_off: + if (redisp_act_orig[np.abs(new_p) <= 1e-7]).any() and self._forbid_dispatch_off: # action is invalid, a generator has been redispatched, but it's turned off except_ = InvalidRedispatching( "Impossible to dispatch a turned off generator" @@ -1889,7 +1889,7 @@ def _prepare_redisp(self, action, new_p, already_modified_gen): if self._forbid_dispatch_off is True: redisp_act_orig_cut = 1.0 * redisp_act_orig - redisp_act_orig_cut[new_p == 0.0] = 0.0 + redisp_act_orig_cut[np.abs(new_p) <= 1e-7] = 0.0 if (redisp_act_orig_cut != redisp_act_orig).any(): info_.append( { @@ -1924,7 +1924,7 @@ def _compute_dispatch_vect(self, already_modified_gen, new_p): # these are the generators that will be adjusted for redispatching gen_participating = ( (new_p > 0.0) - | (self._actual_dispatch != 0.0) + | (np.abs(self._actual_dispatch) >= 1e-7) | (self._target_dispatch != self._actual_dispatch) ) gen_participating[~self.gen_redispatchable] = False @@ -2075,8 +2075,8 @@ def _compute_dispatch_vect(self, already_modified_gen, new_p): # the idea here is to chose a initial point that would be close to the # desired solution (split the (sum of the) dispatch to the available generators) x0 = np.zeros(gen_participating.sum()) - if (self._target_dispatch != 0.).any() or already_modified_gen.any(): - gen_for_x0 = self._target_dispatch[gen_participating] != 0. + if (np.abs(self._target_dispatch) >= 1e-7).any() or already_modified_gen.any(): + gen_for_x0 = np.abs(self._target_dispatch[gen_participating]) >= 1e-7 gen_for_x0 |= already_modified_gen[gen_participating] x0[gen_for_x0] = ( self._target_dispatch[gen_participating][gen_for_x0] @@ -2088,7 +2088,7 @@ def _compute_dispatch_vect(self, already_modified_gen, new_p): # in this "if" block I set the other component of x0 to # their "right" value - can_adjust = (x0 == 0.0) + can_adjust = (np.abs(x0) <= 1e-7) if can_adjust.any(): init_sum = x0.sum() denom_adjust = (1.0 / weights[can_adjust]).sum() @@ -2525,7 +2525,7 @@ def _aux_remove_power_too_low(self, delta_, indx_too_low): def _compute_storage(self, action_storage_power): self._storage_previous_charge[:] = self._storage_current_charge - storage_act = np.isfinite(action_storage_power) & (action_storage_power != 0.0) + storage_act = np.isfinite(action_storage_power) & (np.abs(action_storage_power) >= 1e-7) self._action_storage[:] = 0.0 self._storage_power[:] = 0.0 modif = False @@ -2646,7 +2646,7 @@ def _aux_update_curtailment_act(self, action): def _aux_compute_new_p_curtailment(self, new_p, curtailment_vect): """modifies the new_p argument !!!!""" gen_curtailed = ( - curtailment_vect != 1.0 + np.abs(curtailment_vect - 1.) >= 1e-7 ) # curtailed either right now, or in a previous action max_action = self.gen_pmax[gen_curtailed] * curtailment_vect[gen_curtailed] new_p[gen_curtailed] = np.minimum(max_action, new_p[gen_curtailed]) @@ -2655,7 +2655,7 @@ def _aux_compute_new_p_curtailment(self, new_p, curtailment_vect): def _aux_handle_curtailment_without_limit(self, action, new_p): """modifies the new_p argument !!!! (but not the action)""" if self.redispatching_unit_commitment_availble and ( - action._modif_curtailment or (self._limit_curtailment != 1.0).any() + action._modif_curtailment or (np.abs(self._limit_curtailment - 1.) >= 1e-7).any() ): self._aux_update_curtailment_act(action) @@ -2676,7 +2676,7 @@ def _aux_handle_curtailment_without_limit(self, action, new_p): else: self._sum_curtailment_mw = -self._sum_curtailment_mw_prev self._sum_curtailment_mw_prev = dt_float(0.0) - gen_curtailed = self._limit_curtailment != 1.0 + gen_curtailed = np.abs(self._limit_curtailment - 1.) >= 1e-7 return gen_curtailed diff --git a/grid2op/Episode/EpisodeReplay.py b/grid2op/Episode/EpisodeReplay.py index b21f21fc7..0e9d98a91 100644 --- a/grid2op/Episode/EpisodeReplay.py +++ b/grid2op/Episode/EpisodeReplay.py @@ -198,7 +198,7 @@ def replay_episode( from pygifsicle import optimize optimize(gif_path, options=["-w", "--no-conserve-memory"]) - except: + except Exception as exc_: warn_msg = ( "Failed to optimize .GIF size, but gif is still saved:\n" "Install dependencies to reduce size by ~3 folds\n" diff --git a/grid2op/MakeEnv/MakeFromPath.py b/grid2op/MakeEnv/MakeFromPath.py index 708da74ba..88e3732e8 100644 --- a/grid2op/MakeEnv/MakeFromPath.py +++ b/grid2op/MakeEnv/MakeFromPath.py @@ -466,7 +466,7 @@ def make_from_dataset_path( try: int_ = int(el) available_parameters_int[int_] = el - except: + except Exception as exc_: pass max_ = np.max(list(available_parameters_int.keys())) keys_ = available_parameters_int[max_] diff --git a/grid2op/MakeEnv/UserUtils.py b/grid2op/MakeEnv/UserUtils.py index e7b0e7de9..3400f95c3 100644 --- a/grid2op/MakeEnv/UserUtils.py +++ b/grid2op/MakeEnv/UserUtils.py @@ -163,12 +163,12 @@ def change_local_dir(new_path): try: new_path = str(new_path) - except: + except Exception as exc_: raise Grid2OpException( 'The new path should be convertible to str. It is currently "{}"'.format( new_path ) - ) + ) from exc_ root_dir = os.path.split(new_path)[0] if not os.path.exists(root_dir): @@ -190,21 +190,21 @@ def change_local_dir(new_path): try: with open(DEFAULT_PATH_CONFIG, "r", encoding="utf-8") as f: newconfig = json.load(f) - except: + except Exception as exc_: raise Grid2OpException( 'Impossible to read the grid2op configuration files "{}". Make sure it is a ' 'valid json encoded with "utf-8" encoding.'.format(DEFAULT_PATH_CONFIG) - ) + ) from exc_ newconfig[KEY_DATA_PATH] = new_path try: with open(DEFAULT_PATH_CONFIG, "w", encoding="utf-8") as f: json.dump(fp=f, obj=newconfig, sort_keys=True, indent=4) - except: + except Exception as exc_: raise Grid2OpException( 'Impossible to write the grid2op configuration files "{}". Make sure you have ' "writing access to it.".format(DEFAULT_PATH_CONFIG) - ) + ) from exc_ grid2op.MakeEnv.PathUtils.DEFAULT_PATH_DATA = new_path diff --git a/grid2op/Plot/EpisodeReplay.py b/grid2op/Plot/EpisodeReplay.py index 77d20d1bd..d2e8ae87a 100644 --- a/grid2op/Plot/EpisodeReplay.py +++ b/grid2op/Plot/EpisodeReplay.py @@ -31,7 +31,8 @@ import imageio_ffmpeg can_save_gif = True -except: +except ImportError as exc_: + warnings.warn(f"Error while importing imageio and imageio_ffmpeg: \n{exc_}") can_save_gif = False diff --git a/grid2op/PlotGrid/BasePlot.py b/grid2op/PlotGrid/BasePlot.py index 041cd6d45..707c8d349 100644 --- a/grid2op/PlotGrid/BasePlot.py +++ b/grid2op/PlotGrid/BasePlot.py @@ -1011,10 +1011,10 @@ def plot_info( observation.rho = copy.deepcopy(line_values) try: observation.rho = np.array(observation.rho).astype(dt_float) - except: + except Exception as exc_: raise PlotError( "Impossible to convert the input values (line_values) to floating point" - ) + ) from exc_ # rescaling to have range 0 - 1.0 tmp = observation.rho[np.isfinite(observation.rho)] @@ -1038,10 +1038,10 @@ def plot_info( observation.prod_p = np.array(observation.prod_p).astype( dt_float ) - except: + except Exception as exc_: raise PlotError( "Impossible to convert the input values (gen_values) to floating point" - ) + ) from exc_ # rescaling to have range 0 - 1.0 tmp = observation.prod_p[np.isfinite(observation.prod_p)] diff --git a/grid2op/PlotGrid/PlotMatplot.py b/grid2op/PlotGrid/PlotMatplot.py index 9befd1cc4..ca584dd94 100644 --- a/grid2op/PlotGrid/PlotMatplot.py +++ b/grid2op/PlotGrid/PlotMatplot.py @@ -879,7 +879,7 @@ def draw_powerline( ) self._draw_powerline_bus(pos_ex_x, pos_ex_y, ex_dir_x, ex_dir_y, ex_bus) watt_value = observation.p_or[line_id] - if rho > 0.0 and watt_value != 0.0: + if rho > 0.0 and np.abs(watt_value) >= 1e-7: self._draw_powerline_arrow( pos_or_x, pos_or_y, pos_ex_x, pos_ex_y, color, watt_value ) diff --git a/grid2op/PlotGrid/PlotPlotly.py b/grid2op/PlotGrid/PlotPlotly.py index 52653b0b9..126e40ce9 100644 --- a/grid2op/PlotGrid/PlotPlotly.py +++ b/grid2op/PlotGrid/PlotPlotly.py @@ -144,8 +144,10 @@ def convert_figure_to_numpy_HWC(self, figure): format="png", width=self.width, height=self.height, scale=1 ) return imageio.imread(img_bytes, format="png") - except: - warnings.warn("Plotly need additional dependencies for offline rendering") + except Exception as exc_: + warnings.warn(f"Plotly need additional dependencies for " + f"offline rendering. Error was: " + f"\n{exc_}") return np.full((self.height, self.width, 3), 255, dtype=np.unit8) def _draw_substation_txt(self, name, pos_x, pos_y, text): @@ -564,7 +566,7 @@ def draw_powerline( capacity = observation.rho[line_id] capacity = np.clip(capacity, 0.0, 1.0) color = color_scheme[int(capacity * float(len(color_scheme) - 1))] - if capacity == 0.0: + if np.abs(capacity) <= 1e-7: color = "black" line_style = dict(dash=None if connected else "dash", color=color) line_text = "" @@ -613,7 +615,7 @@ def update_powerline( capacity = min(observation.rho[line_id], 1.0) color_idx = int(capacity * (len(color_scheme) - 1)) color = color_scheme[color_idx] - if capacity == 0.0: + if np.abs(capacity) <= 1e-7: color = "black" if line_value is not None: line_text = pltu.format_value_unit(line_value, line_unit) diff --git a/grid2op/Rules/PreventDiscoStorageModif.py b/grid2op/Rules/PreventDiscoStorageModif.py index 8adff9d7c..d75f449d2 100644 --- a/grid2op/Rules/PreventDiscoStorageModif.py +++ b/grid2op/Rules/PreventDiscoStorageModif.py @@ -24,17 +24,17 @@ def __call__(self, action, env): """ See :func:`BaseRules.__call__` for a definition of the parameters of this function. """ - if env.n_storage == 0: + env_cls = type(env) + if env_cls.n_storage == 0: # nothing to do if no storage return True, None # at first iteration, env.current_obs is None... - storage_disco = env.backend.get_topo_vect()[env.storage_pos_topo_vect] < 0 + storage_disco = env.backend.get_topo_vect()[env_cls.storage_pos_topo_vect] < 0 storage_power, storage_set_bus, storage_change_bus = action.get_storage_modif() - power_modif_disco = (np.isfinite(storage_power[storage_disco])) & ( - storage_power[storage_disco] != 0.0 - ) + power_modif_disco = (np.isfinite(storage_power[storage_disco]) & + (np.abs(storage_power[storage_disco]) >= 1e-7)) not_set_status = storage_set_bus[storage_disco] <= 0 not_change_status = ~storage_change_bus[storage_disco] if (power_modif_disco & not_set_status & not_change_status).any(): diff --git a/grid2op/Runner/runner.py b/grid2op/Runner/runner.py index 89037f026..6aa8624f6 100644 --- a/grid2op/Runner/runner.py +++ b/grid2op/Runner/runner.py @@ -479,7 +479,7 @@ def __init__( # Test if we can copy the agent for parallel runs try: copy.copy(self.agent) - except: + except Exception as exc_: self.__can_copy_agent = False else: raise RuntimeError( diff --git a/grid2op/gym_compat/box_gym_actspace.py b/grid2op/gym_compat/box_gym_actspace.py index 5cd4195a2..e9e13a1f2 100644 --- a/grid2op/gym_compat/box_gym_actspace.py +++ b/grid2op/gym_compat/box_gym_actspace.py @@ -449,7 +449,7 @@ def _get_info(self, functs): if el in self._multiply: # special case if a 0 were entered arr_ = 1.0 * self._multiply[el] - is_nzero = arr_ != 0.0 + is_nzero = np.abs(arr_) >= 1e-7 low_ = 1.0 * low_.astype(dtype) high_ = 1.0 * high_.astype(dtype) diff --git a/grid2op/simulator/simulator.py b/grid2op/simulator/simulator.py index c7493b6bf..8f5ba6943 100644 --- a/grid2op/simulator/simulator.py +++ b/grid2op/simulator/simulator.py @@ -316,7 +316,7 @@ def _adjust_controlable_gen( # which generators needs to be "optimized" -> the one where # the target function matter - gen_in_target = target_dispatch[self.current_obs.gen_redispatchable] != 0.0 + gen_in_target = np.abs(target_dispatch[self.current_obs.gen_redispatchable]) >= 1e-7 # compute the upper / lower bounds for the generators dispatchable = new_gen_p[self.current_obs.gen_redispatchable] @@ -403,7 +403,7 @@ def f(init): # the idea here is to chose a initial point that would be close to the # desired solution (split the (sum of the) dispatch to the available generators) x0 = 1.0 * target_dispatch_redisp - can_adjust = x0 == 0.0 + can_adjust = np.abs(x0) <= 1e-7 if (can_adjust).any(): init_sum = x0.sum() denom_adjust = (1.0 / weights[can_adjust]).sum() @@ -480,8 +480,8 @@ def _fix_redisp_curtailment_storage( target_dispatch = self.current_obs.target_dispatch + act.redispatch # if previous setpoint was say -2 and at this step I redispatch of # say + 4 then the real setpoint should be +2 (and not +4) - new_vect_redisp = (act.redispatch != 0.0) & ( - self.current_obs.target_dispatch == 0.0 + new_vect_redisp = (np.abs(act.redispatch) >= 1e-7) & ( + np.abs(self.current_obs.target_dispatch) <= 1e-7 ) target_dispatch[new_vect_redisp] += self.current_obs.actual_dispatch[ new_vect_redisp diff --git a/grid2op/tests/BaseRedispTest.py b/grid2op/tests/BaseRedispTest.py index b6a4b6567..3fe3ea4e6 100644 --- a/grid2op/tests/BaseRedispTest.py +++ b/grid2op/tests/BaseRedispTest.py @@ -803,7 +803,7 @@ def test_dispatch_still_not_zero(self): assert np.all( obs.prod_p[0:2] <= obs.gen_pmax[0:2] ), "above pmax for ts {}".format(i) - except: + except Exception as exc_: pass assert np.all( obs.prod_p[0:2] >= -obs.gen_pmin[0:2]