Beispiel #1
0
    def __init__(self, gridobj, subtype=object, _init_grid=True):
        """

        subtype: ``type``
            Type of action used to build :attr:`SerializableActionSpace._template_act`. This type should derive
            from :class:`grid2op.BaseAction.BaseAction` or :class:`grid2op.BaseObservation.BaseObservation` .

        _init_grid: ``bool``
            Whether or not to call 'init_grid' in the subtype (to initialize the class). Do not modify unless you
            are certain of what you want to do
        """

        if not isinstance(subtype, type):
            raise Grid2OpException(
                "Parameter \"subtype\" used to build the Space should be a type (a class) and not an object "
                "(an instance of a class). It is currently \"{}\"".format(
                    type(subtype)))

        GridObjects.__init__(self)
        RandomObject.__init__(self)
        self._init_subtype = subtype  # do not use, use to save restore only !!!
        if _init_grid:
            self.subtype = subtype.init_grid(gridobj)
            from grid2op.Action import BaseAction  # lazy loading to prevent circular reference
            if issubclass(self.subtype, BaseAction):
                # add the shunt data if needed by the action only
                self.subtype._add_shunt_data()
            # compute the class attribute "attr_list_set" from "attr_list_vect"
            self.subtype._update_value_set()
        else:
            self.subtype = subtype

        from grid2op.Action import BaseAction  # lazy import to avoid circular reference
        from grid2op.Observation import BaseObservation  # lazy import to avoid circular reference
        if not issubclass(subtype, (BaseAction, BaseObservation)):
            raise RuntimeError(
                f"\"subtype\" should inherit either BaseAction or BaseObservation. Currently it "
                f"is \"{subtype}\"")
        self._template_obj = self.subtype()
        self.n = self._template_obj.size()

        self.global_vars = None

        self.shape = self._template_obj.shape()
        self.dtype = self._template_obj.dtype()
        self.attr_list_vect = copy.deepcopy(self._template_obj.attr_list_vect)

        self._to_extract_vect = {
        }  # key: attr name, value: tuple: (beg_, end_, dtype)
        beg_ = 0
        end_ = 0
        for attr, size, dtype_ in zip(self.attr_list_vect, self.shape,
                                      self.dtype):
            end_ += size
            self._to_extract_vect[attr] = (beg_, end_, dtype_)
            beg_ += size
    def __init__(self, gridobj, subtype=object, _init_grid=True):
        """

        subtype: ``type``
            Type of action used to build :attr:`SerializableActionSpace._template_act`. This type should derive
            from :class:`grid2op.BaseAction.BaseAction` or :class:`grid2op.BaseObservation.BaseObservation` .

        _init_grid: ``bool``
            Whether or not to call 'init_grid' in the subtype (to initialize the class). Do not modify unless you
            are certain of what you want to do
        """

        if not isinstance(subtype, type):
            raise Grid2OpException(
                "Parameter \"subtype\" used to build the Space should be a type (a class) and not an object "
                "(an instance of a class). It is currently \"{}\"".format(
                    type(subtype)))

        GridObjects.__init__(self)
        RandomObject.__init__(self)
        self.init_grid(gridobj)

        self._init_subtype = subtype  # do not use, use to save restore only !!!
        # print(f"gridobj : {gridobj}")
        if _init_grid:
            self.subtype = subtype.init_grid(gridobj)
        else:
            self.subtype = subtype
        # print(f"subtype : {self.subtype}")
        self._template_obj = self.subtype()
        self.n = self._template_obj.size()

        self.global_vars = None

        self.shape = self._template_obj.shape()
        self.dtype = self._template_obj.dtype()
        self.attr_list_vect = self._template_obj.attr_list_vect

        self._to_extract_vect = {
        }  # key: attr name, value: tuple: (beg_, end_, dtype)
        beg_ = 0
        end_ = 0
        for attr, size, dtype_ in zip(self._template_obj.attr_list_vect,
                                      self.shape, self.dtype):
            end_ += size
            self._to_extract_vect[attr] = (beg_, end_, dtype_)
            beg_ += size
Beispiel #3
0
    def __init__(self, gridobj, subtype=object):
        """

        subtype: ``type``
            Type of action used to build :attr:`SerializableActionSpace._template_act`. This type should derive
            from :class:`grid2op.BaseAction.BaseAction` or :class:`grid2op.BaseObservation.BaseObservation` .

        """

        if not isinstance(subtype, type):
            raise Grid2OpException(
                "Parameter \"subtype\" used to build the Space should be a type (a class) and not an object "
                "(an instance of a class). It is currently \"{}\"".format(
                    type(subtype)))

        GridObjects.__init__(self)
        RandomObject.__init__(self)
        self.init_grid(gridobj)

        self._init_subtype = subtype  # do not use, use to save restore only !!!
        self.subtype = subtype.init_grid(gridobj)
        self._template_obj = self.subtype()
        self.n = self._template_obj.size()

        self.global_vars = None

        self.shape = self._template_obj.shape()
        self.dtype = self._template_obj.dtype()
        self.attr_list_vect = self._template_obj.attr_list_vect

        self._to_extract_vect = {
        }  # key: attr name, value: tuple: (beg_, end_, dtype)
        beg_ = 0
        end_ = 0
        for attr, size, dtype_ in zip(self._template_obj.attr_list_vect,
                                      self.shape, self.dtype):
            end_ += size
            self._to_extract_vect[attr] = (beg_, end_, dtype_)
            beg_ += size
    def from_dict(dict_):
        """
        INTERNAL

        .. warning:: /!\\\\ Internal, do not use unless you know what you are doing /!\\\\
            This is used internally only to restore action_space or observation_space if they
            have been saved by `to_dict`. Do not
            attempt to use it in a different context.

        Allows the de-serialization of an object stored as a dictionary (for example in the case of json saving).

        Parameters
        ----------
        dict_: ``dict``
            Representation of an BaseObservation Space (aka :class:`grid2op.BaseObservation.ObservartionHelper`)
            or the BaseAction Space (aka :class:`grid2op.BaseAction.ActionSpace`)
            as a dictionary.

        Returns
        -------
        res: :class:`SerializableSpace`
            An instance of an SerializableSpace matching the dictionary.

        """

        if isinstance(dict_, str):
            path = dict_
            if not os.path.exists(path):
                raise Grid2OpException(
                    "Unable to find the file \"{}\" to load the ObservationSpace"
                    .format(path))
            with open(path, "r", encoding="utf-8") as f:
                dict_ = json.load(fp=f)

        gridobj = GridObjects.from_dict(dict_)
        actionClass_str = extract_from_dict(dict_, "_init_subtype", str)
        actionClass_li = actionClass_str.split('.')

        if actionClass_li[-1] in globals():
            subtype = globals()[actionClass_li[-1]]
        else:
            # TODO make something better and recursive here
            exec("from {} import {}".format(".".join(actionClass_li[:-1]),
                                            actionClass_li[-1]))
            try:
                subtype = eval(actionClass_li[-1])
            except NameError:
                if len(actionClass_li) > 1:
                    try:
                        subtype = eval(".".join(actionClass_li[1:]))
                    except:
                        msg_err_ = "Impossible to find the module \"{}\" to load back the space (ERROR 1). " \
                                   "Try \"from {} import {}\""
                        raise Grid2OpException(
                            msg_err_.format(actionClass_str,
                                            ".".join(actionClass_li[:-1]),
                                            actionClass_li[-1]))
                else:
                    msg_err_ = "Impossible to find the module \"{}\" to load back the space (ERROR 2). " \
                               "Try \"from {} import {}\""
                    raise Grid2OpException(
                        msg_err_.format(actionClass_str,
                                        ".".join(actionClass_li[:-1]),
                                        actionClass_li[-1]))
            except AttributeError:
                try:
                    subtype = eval(actionClass_li[-1])
                except:
                    if len(actionClass_li) > 1:
                        msg_err_ = "Impossible to find the class named \"{}\" to load back the space (ERROR 3)" \
                                   "(module is found but not the class in it) Please import it via " \
                                   "\"from {} import {}\"."
                        msg_err_ = msg_err_.format(
                            actionClass_str, ".".join(actionClass_li[:-1]),
                            actionClass_li[-1])
                    else:
                        msg_err_ = "Impossible to import the class named \"{}\" to load back the space (ERROR 4) " \
                                   "(the module is found but not the class in it)"
                        msg_err_ = msg_err_.format(actionClass_str)
                    raise Grid2OpException(msg_err_)
        # create the proper SerializableSpace class for this environment
        CLS = SerializableSpace.init_grid(gridobj)
        res = CLS(gridobj=gridobj, subtype=subtype, _init_grid=True)
        return res
Beispiel #5
0
    def from_dict(dict_):
        """
        Allows the de-serialization of an object stored as a dictionnary (for example in the case of json saving).

        Parameters
        ----------
        dict_: ``dict``
            Representation of an BaseObservation Space (aka :class:`grid2op.BaseObservation.ObservartionHelper`)
            or the BaseAction Space (aka :class:`grid2op.BaseAction.ActionSpace`)
            as a dictionnary.

        Returns
        -------
        res: :class:`SerializableSpace`
            An instance of an SerializableSpace matching the dictionnary.

        """

        if isinstance(dict_, str):
            path = dict_
            if not os.path.exists(path):
                raise Grid2OpException(
                    "Unable to find the file \"{}\" to load the ObservationSpace"
                    .format(path))
            with open(path, "r", encoding="utf-8") as f:
                dict_ = json.load(fp=f)

        gridobj = GridObjects.from_dict(dict_)

        actionClass_str = extract_from_dict(dict_, "_init_subtype", str)
        actionClass_li = actionClass_str.split('.')

        if actionClass_li[-1] in globals():
            subtype = globals()[actionClass_li[-1]]
        else:
            # TODO make something better and recursive here
            exec("from {} import {}".format(".".join(actionClass_li[:-1]),
                                            actionClass_li[-1]))
            try:
                subtype = eval(actionClass_li[-1])
            except NameError:
                if len(actionClass_li) > 1:
                    try:
                        subtype = eval(".".join(actionClass_li[1:]))
                    except:
                        msg_err_ = "Impossible to find the module \"{}\" to load back the space (ERROR 1). " \
                                   "Try \"from {} import {}\""
                        raise Grid2OpException(
                            msg_err_.format(actionClass_str,
                                            ".".join(actionClass_li[:-1]),
                                            actionClass_li[-1]))
                else:
                    msg_err_ = "Impossible to find the module \"{}\" to load back the space (ERROR 2). " \
                               "Try \"from {} import {}\""
                    raise Grid2OpException(
                        msg_err_.format(actionClass_str,
                                        ".".join(actionClass_li[:-1]),
                                        actionClass_li[-1]))
            except AttributeError:
                try:
                    subtype = eval(actionClass_li[-1])
                except:
                    if len(actionClass_li) > 1:
                        msg_err_ = "Impossible to find the class named \"{}\" to load back the space (ERROR 3)" \
                                   "(module is found but not the class in it) Please import it via " \
                                   "\"from {} import {}\"."
                        msg_err_ = msg_err_.format(
                            actionClass_str, ".".join(actionClass_li[:-1]),
                            actionClass_li[-1])
                    else:
                        msg_err_ = "Impossible to import the class named \"{}\" to load back the space (ERROR 4) " \
                                   "(the module is found but not the class in it)"
                        msg_err_ = msg_err_.format(actionClass_str)
                    raise Grid2OpException(msg_err_)

        res = SerializableSpace(gridobj=gridobj, subtype=subtype)
        return res