Skip to content

Component Manager

This class provides auxiliary methods that facilitate object manipulation.

Source code in edge_sim_py/component_manager.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 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
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
class ComponentManager:
    """This class provides auxiliary methods that facilitate object manipulation."""

    __model = None

    def __str__(self) -> str:
        """Defines how the object is represented inside print statements.

        Returns:
            obj (str): Object representation
        """
        return f"{self.__class__.__name__}_{self.id}"

    def __repr__(self) -> str:
        """Defines how the object is represented inside the console.

        Returns:
            str: Object representation.
        """
        return f"{self.__class__.__name__}_{self.id}"

    @classmethod
    def export_scenario(
        cls, ignore_list: list = ["Simulator", "Topology", "NetworkFlow"], save_to_file: bool = False, file_name: str = "dataset"
    ) -> dict:
        """Exports metadata about the simulation model to a Python dictionary. If the "save_to_file" attribute is set to True, the
        external dataset file generated is saved inside the "datasets/" directory by default.

        Args:
            ignore_list (list, optional): List of entities that will not be included in the output dict. Defaults to ["Simulator", "Topology", "NetworkFlow"].
            save_to_file (bool, optional): Attribute that tells the method if it needs to save the scenario to an external file. Defaults to False.
            file_name (str, optional): Output file name. Defaults to "dataset".

        Returns:
            scenario (dict): Python dictionary representing the simulation model.
        """
        scenario = {}

        # Creating the "datasets" directory if it doesn't exists
        if not os.path.exists("datasets/"):
            os.makedirs("datasets")

        for component in ComponentManager.__subclasses__():
            if component.__name__ not in ignore_list:
                scenario[component.__name__] = [instance._to_dict() for instance in component._instances]
                with open(f"datasets/{file_name}.json", "w", encoding="UTF-8") as output_file:
                    json.dump(scenario, output_file, indent=4)

        return scenario

    @classmethod
    def _from_dict(cls, dictionary: dict) -> object:
        """Method that creates an object based on a dictionary specification.

        Args:
            dictionary (dict): Object specification.

        Returns:
            created_object (object): Object created from the dictionary specification.
        """
        created_object = cls()
        for attribute, value in dictionary.items():
            setattr(created_object, attribute, value)

        return created_object

    @classmethod
    def find_by(cls, attribute_name: str, attribute_value: object) -> object:
        """Finds objects from a given class based on an user-specified attribute.

        Args:
            attribute_name (str): Attribute name.
            attribute_value (object): Attribute value.

        Returns:
            object: Class object.
        """
        class_object = next((obj for obj in cls._instances if getattr(obj, attribute_name) == attribute_value), None)
        return class_object

    @classmethod
    def find_by_id(cls, obj_id: int) -> object:
        """Finds a class object based on its ID attribute.

        Args:
            obj_id (int): Object ID.

        Returns:
            class_object (object): Class object found.
        """
        class_object = next((obj for obj in cls._instances if obj.id == obj_id), None)
        return class_object

    @classmethod
    def all(cls) -> list:
        """Returns the list of created objects of a given class.

        Returns:
            list: List of objects from a given class.
        """
        return cls._instances

    @classmethod
    def first(cls) -> object:
        """Returns the first object within the list of instances from a given class.

        Returns:
            object: Class object.
        """
        if len(cls._instances) == 0:
            return None

        return cls._instances[0]

    @classmethod
    def last(cls) -> object:
        """Returns the last object within the list of instances from a given class.

        Returns:
            object: Class object.
        """
        return cls._instances[-1]

    @classmethod
    def count(cls) -> int:
        """Returns the number of instances from a given class.

        Returns:
            int: Number of instances from a given class.
        """
        return len(cls._instances)

    @classmethod
    def remove(cls, obj: object):
        """Removes an object from the list of instances of a given class.

        Args:
            obj (object): Object to be removed.
        """
        if obj not in cls._instances:
            raise Exception(f"Object {obj} is not in the list of instances of the '{cls.__name__}' class.")

        cls._instances.remove(obj)

__repr__()

Defines how the object is represented inside the console.

Returns:

Name Type Description
str str

Object representation.

Source code in edge_sim_py/component_manager.py
26
27
28
29
30
31
32
def __repr__(self) -> str:
    """Defines how the object is represented inside the console.

    Returns:
        str: Object representation.
    """
    return f"{self.__class__.__name__}_{self.id}"

__str__()

Defines how the object is represented inside print statements.

Returns:

Name Type Description
obj str

Object representation

Source code in edge_sim_py/component_manager.py
18
19
20
21
22
23
24
def __str__(self) -> str:
    """Defines how the object is represented inside print statements.

    Returns:
        obj (str): Object representation
    """
    return f"{self.__class__.__name__}_{self.id}"

all() classmethod

Returns the list of created objects of a given class.

Returns:

Name Type Description
list list

List of objects from a given class.

Source code in edge_sim_py/component_manager.py
106
107
108
109
110
111
112
113
@classmethod
def all(cls) -> list:
    """Returns the list of created objects of a given class.

    Returns:
        list: List of objects from a given class.
    """
    return cls._instances

count() classmethod

Returns the number of instances from a given class.

Returns:

Name Type Description
int int

Number of instances from a given class.

Source code in edge_sim_py/component_manager.py
136
137
138
139
140
141
142
143
@classmethod
def count(cls) -> int:
    """Returns the number of instances from a given class.

    Returns:
        int: Number of instances from a given class.
    """
    return len(cls._instances)

export_scenario(ignore_list=['Simulator', 'Topology', 'NetworkFlow'], save_to_file=False, file_name='dataset') classmethod

Exports metadata about the simulation model to a Python dictionary. If the "save_to_file" attribute is set to True, the external dataset file generated is saved inside the "datasets/" directory by default.

Parameters:

Name Type Description Default
ignore_list list

List of entities that will not be included in the output dict. Defaults to ["Simulator", "Topology", "NetworkFlow"].

['Simulator', 'Topology', 'NetworkFlow']
save_to_file bool

Attribute that tells the method if it needs to save the scenario to an external file. Defaults to False.

False
file_name str

Output file name. Defaults to "dataset".

'dataset'

Returns:

Name Type Description
scenario dict

Python dictionary representing the simulation model.

Source code in edge_sim_py/component_manager.py
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
@classmethod
def export_scenario(
    cls, ignore_list: list = ["Simulator", "Topology", "NetworkFlow"], save_to_file: bool = False, file_name: str = "dataset"
) -> dict:
    """Exports metadata about the simulation model to a Python dictionary. If the "save_to_file" attribute is set to True, the
    external dataset file generated is saved inside the "datasets/" directory by default.

    Args:
        ignore_list (list, optional): List of entities that will not be included in the output dict. Defaults to ["Simulator", "Topology", "NetworkFlow"].
        save_to_file (bool, optional): Attribute that tells the method if it needs to save the scenario to an external file. Defaults to False.
        file_name (str, optional): Output file name. Defaults to "dataset".

    Returns:
        scenario (dict): Python dictionary representing the simulation model.
    """
    scenario = {}

    # Creating the "datasets" directory if it doesn't exists
    if not os.path.exists("datasets/"):
        os.makedirs("datasets")

    for component in ComponentManager.__subclasses__():
        if component.__name__ not in ignore_list:
            scenario[component.__name__] = [instance._to_dict() for instance in component._instances]
            with open(f"datasets/{file_name}.json", "w", encoding="UTF-8") as output_file:
                json.dump(scenario, output_file, indent=4)

    return scenario

find_by(attribute_name, attribute_value) classmethod

Finds objects from a given class based on an user-specified attribute.

Parameters:

Name Type Description Default
attribute_name str

Attribute name.

required
attribute_value object

Attribute value.

required

Returns:

Name Type Description
object object

Class object.

Source code in edge_sim_py/component_manager.py
79
80
81
82
83
84
85
86
87
88
89
90
91
@classmethod
def find_by(cls, attribute_name: str, attribute_value: object) -> object:
    """Finds objects from a given class based on an user-specified attribute.

    Args:
        attribute_name (str): Attribute name.
        attribute_value (object): Attribute value.

    Returns:
        object: Class object.
    """
    class_object = next((obj for obj in cls._instances if getattr(obj, attribute_name) == attribute_value), None)
    return class_object

find_by_id(obj_id) classmethod

Finds a class object based on its ID attribute.

Parameters:

Name Type Description Default
obj_id int

Object ID.

required

Returns:

Name Type Description
class_object object

Class object found.

Source code in edge_sim_py/component_manager.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
@classmethod
def find_by_id(cls, obj_id: int) -> object:
    """Finds a class object based on its ID attribute.

    Args:
        obj_id (int): Object ID.

    Returns:
        class_object (object): Class object found.
    """
    class_object = next((obj for obj in cls._instances if obj.id == obj_id), None)
    return class_object

first() classmethod

Returns the first object within the list of instances from a given class.

Returns:

Name Type Description
object object

Class object.

Source code in edge_sim_py/component_manager.py
115
116
117
118
119
120
121
122
123
124
125
@classmethod
def first(cls) -> object:
    """Returns the first object within the list of instances from a given class.

    Returns:
        object: Class object.
    """
    if len(cls._instances) == 0:
        return None

    return cls._instances[0]

last() classmethod

Returns the last object within the list of instances from a given class.

Returns:

Name Type Description
object object

Class object.

Source code in edge_sim_py/component_manager.py
127
128
129
130
131
132
133
134
@classmethod
def last(cls) -> object:
    """Returns the last object within the list of instances from a given class.

    Returns:
        object: Class object.
    """
    return cls._instances[-1]

remove(obj) classmethod

Removes an object from the list of instances of a given class.

Parameters:

Name Type Description Default
obj object

Object to be removed.

required
Source code in edge_sim_py/component_manager.py
145
146
147
148
149
150
151
152
153
154
155
@classmethod
def remove(cls, obj: object):
    """Removes an object from the list of instances of a given class.

    Args:
        obj (object): Object to be removed.
    """
    if obj not in cls._instances:
        raise Exception(f"Object {obj} is not in the list of instances of the '{cls.__name__}' class.")

    cls._instances.remove(obj)