Skip to content

Allocation Types

AllocationTypes(baze)

Class used for handling allocation types.

Source code in echo_baze/baze_root.py
def __init__(self, baze: e_bz.Baze) -> None:
    """Base class that all subclasses should inherit from.

    Parameters
    ----------
    baze : Baze
        Top level object carrying all functionality and the connection handler.

    """
    # check inputs
    if not isinstance(baze, e_bz.Baze):
        raise ValueError(f"baze must be of type Baze, not {type(baze)}")

    self.baze: e_bz.Baze = baze

get(output_type='dict')

Gets all allocation types with detailed information.

The most useful keys/columns returned are: - id - acronym - description - disabled - linkedTypeId (parent type ID) - linkedTypeName (parent type name) - childrenIds (list of child type IDs) - childrenNames (list of child type names)

Parameters:

  • output_type

    (Literal['dict', 'DataFrame'], default: 'dict' ) –

    Output type of the data. Can be one of ["dict", "DataFrame"] By default "dict"

Returns:

  • dict[str, dict[str, Any]]

    In case output_type == "dict" it will return a dict with the following format: {name: {attribute: value, ...}, ...}

  • DataFrame

    In case output_type == "DataFrame" it will return a DataFrame with the following format: index = name, columns = [attribute, ...]

Source code in echo_baze/allocation_types.py
@validate_call
def get(self, output_type: Literal["dict", "DataFrame"] = "dict") -> dict[str, dict[str, Any]] | DataFrame:
    """Gets all allocation types with detailed information.

    The most useful keys/columns returned are:
    - id
    - acronym
    - description
    - disabled
    - linkedTypeId (parent type ID)
    - linkedTypeName (parent type name)
    - childrenIds (list of child type IDs)
    - childrenNames (list of child type names)

    Parameters
    ----------
    output_type : Literal["dict", "DataFrame"], optional
        Output type of the data. Can be one of ["dict", "DataFrame"]
        By default "dict"

    Returns
    -------
    dict[str, dict[str, Any]]
        In case output_type == "dict" it will return a dict with the following format: {name: {attribute: value, ...}, ...}
    DataFrame
        In case output_type == "DataFrame" it will return a DataFrame with the following format: index = name, columns = [attribute, ...]

    """
    endpoint = "allocationTypes"

    # getting the data
    result = self.baze.conn.get(endpoint)
    self._handle_http_errors(result)

    # converting to dict
    result: list[dict[str, Any]] = result.json()

    # adding linkedTypeName to the result
    for entry in result:
        # getting the linkedTypeId
        linked_type_id = entry.get("linkedTypeId")
        if linked_type_id is not None:
            for linked_type in result:
                if linked_type["id"] == linked_type_id:
                    entry["linkedTypeName"] = linked_type["name"]
                    break

    # adding childrenIds and childrenNames to the result
    for entry in result:
        # in case this entry has a parent type, add it to the children of the parent
        parent_id = entry.get("linkedTypeId")
        if parent_id is not None:
            for linked_type in result:
                if linked_type["id"] == parent_id:
                    # adding the current entry to the children of the parent
                    if "childrenIds" not in linked_type:
                        linked_type["childrenIds"] = []
                    if "childrenNames" not in linked_type:
                        linked_type["childrenNames"] = []
                    linked_type["childrenIds"].append(entry["id"])
                    linked_type["childrenNames"].append(entry["name"])
                    break

    # returning on the desired format
    match output_type:
        case "dict":
            # defining the name as the key for the dict
            result_dict = {entry["name"]: entry for entry in result}
            # removing the name from the dict values
            for entry in result_dict.values():
                del entry["name"]
            return result_dict
        case "DataFrame":
            df = json_normalize(result, max_level=1)
            df = df.convert_dtypes(dtype_backend="pyarrow")
            df = df.set_index("name")
            return df
        case _:
            raise ValueError(f"Invalid output_type: {output_type}")

get_default(object_types=None, object_names=None, **kwargs)

Method that gets the default allocation type for each wanted object type or object name.

The default allocation types are defined in the attribute "DefaultAllocationsType" of the object type.

Parameters:

  • object_types

    (list[str], default: None ) –

    Desired object types (Turbine, Inverter, etc.). Only valid if object_names is None. By default None

  • object_names

    (list[str] | None, default: None ) –

    Desired object names (Turbine1, Inverter1, etc.). Only valid if object_types is None. By default None

  • object_instances

    (dict[str, dict[str, Any]]) –

    Dictionary with the object instances. Will be used to avoid making extra requests to the API.

    It is the output of self.baze.objects.instances.get().

  • obj_type_attributes

    (dict[str, dict[str, Any]]) –

    Dictionary with the object types and their attributes. Will be used to avoid making extra requests to the API.

    It is the output of self.baze.objects.types.attributes.values.get().

  • allocation_types

    (dict[str, dict[str, Any]]) –

    Dictionary with the allocation types. Will be used to avoid making extra requests to the API.

    It is the output of self.baze.allocations.types.get().

Returns:

  • dict[str, list[str]]

    If object_names is not passed, it will return a dict in the format {object_type: [default_allocation_type1, default_allocation_type2, ...]}

    If object_names is passed, it will return a dict in the format {object_name: [default_allocation_type1, default_allocation_type2, ...]}

    The allocation types will have more than one value if the default allocation type is a parent type and has children types. The first value will be the parent type and the rest will be the children types.

Source code in echo_baze/allocation_types.py
@validate_call
def get_default(self, object_types: list[str] | None = None, object_names: list[str] | None = None, **kwargs) -> dict[str, list[str]]:
    """Method that gets the default allocation type for each wanted object type or object name.

    The default allocation types are defined in the attribute "DefaultAllocationsType" of the object type.

    Parameters
    ----------
    object_types : list[str]
        Desired object types (Turbine, Inverter, etc.). Only valid if object_names is None. By default None
    object_names : list[str] | None
        Desired object names (Turbine1, Inverter1, etc.). Only valid if object_types is None. By default None
    object_instances : dict[str, dict[str, Any]], optional
        Dictionary with the object instances. Will be used to avoid making extra requests to the API.

        It is the output of self.baze.objects.instances.get().
    obj_type_attributes : dict[str, dict[str, Any]], optional
        Dictionary with the object types and their attributes. Will be used to avoid making extra requests to the API.

        It is the output of self.baze.objects.types.attributes.values.get().
    allocation_types : dict[str, dict[str, Any]], optional
        Dictionary with the allocation types. Will be used to avoid making extra requests to the API.

        It is the output of self.baze.allocations.types.get().

    Returns
    -------
    dict[str, list[str]]
        If object_names is not passed, it will return a dict in the format {object_type: [default_allocation_type1, default_allocation_type2, ...]}

        If object_names is passed, it will return a dict in the format {object_name: [default_allocation_type1, default_allocation_type2, ...]}

        The allocation types will have more than one value if the default allocation type is a parent type and has children types. The first value will be the parent type and the rest will be the children types.

    """
    # checking if both are None or both are not None
    if bool(object_types) == bool(object_names):
        raise ValueError("Only one of object_types or object_names can be passed")

    # getting the allocation types
    allocation_types = kwargs.get("allocation_types")
    if allocation_types is None:
        allocation_types = self.get(output_type="dict")

    # if object names are passed, get the object types of the objects
    if object_names:
        objs_def = kwargs.get("object_instances")
        if objs_def is None:
            objs_def = self.baze.objects.instances.get(object_names=object_names)
        # checking for invalid object names
        if len(objs_def) != len(object_names):
            wrong_object_names = set(object_names) - set(objs_def.keys())
            raise ValueError(f"Invalid object names: {wrong_object_names}")
        object_types = list(
            {x["attributes"]["objectTypeName"] for x in objs_def.values()},
        )

    # getting attributes
    obj_type_attributes = kwargs.get("obj_type_attributes")
    if obj_type_attributes is None:
        obj_type_attributes = self.baze.objects.types.attributes.values.get(object_types=object_types)

    if len(obj_type_attributes) != len(object_types):
        wrong_object_types = set(object_types) - set(obj_type_attributes.keys())
        raise ValueError(f"Invalid object types: {wrong_object_types}")

    # converting to a dict with the format {object_type: default_allocation_type} or {object_name: default_allocation_type}
    result = {}
    if not object_names:
        for object_type, attributes_dict in obj_type_attributes.items():
            if "DefaultAllocationsType" not in attributes_dict:
                raise ValueError(f"Object type {object_type} does not have the attribute 'DefaultAllocationsType'")
            result[object_type] = [attributes_dict["DefaultAllocationsType"]["value"]]
    else:
        for object_name, object_attrs in objs_def.items():
            object_type = object_attrs["attributes"]["objectTypeName"]
            if "DefaultAllocationsType" not in obj_type_attributes[object_type]:
                raise ValueError(f"Object type {object_type} does not have the attribute 'DefaultAllocationsType'")
            result[object_name] = [obj_type_attributes[object_type]["DefaultAllocationsType"]["value"]]

    # getting children in case the default allocation type is a parent type
    for vals in result.values():
        children: list[str] | None = allocation_types[vals[0]].get("childrenNames")
        if children:
            vals.extend(children)

    return result

get_ids()

Gets a dictionary with all allocation type names and ids.

Returns:

  • dict[str, int]:

    Dictionary with all allocation types in the format {name: id, ...}

Source code in echo_baze/allocation_types.py
def get_ids(self) -> dict[str, int]:
    """Gets a dictionary with all allocation type names and ids.

    Returns
    -------
    dict[str, int]:
        Dictionary with all allocation types in the format {name: id, ...}

    """
    endpoint = "allocationTypes"

    # getting the data
    result = self.baze.conn.get(endpoint)
    self._handle_http_errors(result)

    # converting to dict
    result: list[dict[str, Any]] = result.json()

    return {entry["name"]: entry["id"] for entry in result}

get_parent_id()

Gets a dictionary with all allocation type names and their linked type IDs.

Returns:

  • dict[str, int | None]:

    Dictionary with all allocation types in the format {name: linkedTypeId, ...}.

    If linkedTypeId is not present, the value will be None.

Source code in echo_baze/allocation_types.py
def get_parent_id(self) -> dict[str, int | None]:
    """Gets a dictionary with all allocation type names and their linked type IDs.

    Returns
    -------
    dict[str, int | None]:
        Dictionary with all allocation types in the format {name: linkedTypeId, ...}.

        If linkedTypeId is not present, the value will be None.

    """
    endpoint = "allocationTypes"

    # getting the data
    result = self.baze.conn.get(endpoint)
    self._handle_http_errors(result)

    # converting to dict
    result: list[dict[str, Any]] = result.json()

    return {entry["name"]: entry.get("linkedTypeId") for entry in result}