MEDfl 0.2.1__py3-none-any.whl → 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. MEDfl/LearningManager/__init__.py +13 -13
  2. MEDfl/LearningManager/client.py +150 -181
  3. MEDfl/LearningManager/dynamicModal.py +287 -287
  4. MEDfl/LearningManager/federated_dataset.py +60 -60
  5. MEDfl/LearningManager/flpipeline.py +192 -192
  6. MEDfl/LearningManager/model.py +223 -223
  7. MEDfl/LearningManager/params.yaml +14 -14
  8. MEDfl/LearningManager/params_optimiser.py +442 -442
  9. MEDfl/LearningManager/plot.py +229 -229
  10. MEDfl/LearningManager/server.py +181 -189
  11. MEDfl/LearningManager/strategy.py +82 -138
  12. MEDfl/LearningManager/utils.py +331 -331
  13. MEDfl/NetManager/__init__.py +10 -10
  14. MEDfl/NetManager/database_connector.py +43 -43
  15. MEDfl/NetManager/dataset.py +92 -92
  16. MEDfl/NetManager/flsetup.py +320 -320
  17. MEDfl/NetManager/net_helper.py +254 -254
  18. MEDfl/NetManager/net_manager_queries.py +142 -142
  19. MEDfl/NetManager/network.py +194 -194
  20. MEDfl/NetManager/node.py +184 -184
  21. MEDfl/__init__.py +2 -2
  22. MEDfl/scripts/__init__.py +1 -1
  23. MEDfl/scripts/base.py +29 -29
  24. MEDfl/scripts/create_db.py +126 -126
  25. Medfl/LearningManager/__init__.py +13 -0
  26. Medfl/LearningManager/client.py +150 -0
  27. Medfl/LearningManager/dynamicModal.py +287 -0
  28. Medfl/LearningManager/federated_dataset.py +60 -0
  29. Medfl/LearningManager/flpipeline.py +192 -0
  30. Medfl/LearningManager/model.py +223 -0
  31. Medfl/LearningManager/params.yaml +14 -0
  32. Medfl/LearningManager/params_optimiser.py +442 -0
  33. Medfl/LearningManager/plot.py +229 -0
  34. Medfl/LearningManager/server.py +181 -0
  35. Medfl/LearningManager/strategy.py +82 -0
  36. Medfl/LearningManager/utils.py +331 -0
  37. Medfl/NetManager/__init__.py +10 -0
  38. Medfl/NetManager/database_connector.py +43 -0
  39. Medfl/NetManager/dataset.py +92 -0
  40. Medfl/NetManager/flsetup.py +320 -0
  41. Medfl/NetManager/net_helper.py +254 -0
  42. Medfl/NetManager/net_manager_queries.py +142 -0
  43. Medfl/NetManager/network.py +194 -0
  44. Medfl/NetManager/node.py +184 -0
  45. Medfl/__init__.py +3 -0
  46. Medfl/scripts/__init__.py +2 -0
  47. Medfl/scripts/base.py +30 -0
  48. Medfl/scripts/create_db.py +126 -0
  49. alembic/env.py +61 -61
  50. {MEDfl-0.2.1.dist-info → medfl-2.0.0.dist-info}/METADATA +120 -108
  51. medfl-2.0.0.dist-info/RECORD +55 -0
  52. {MEDfl-0.2.1.dist-info → medfl-2.0.0.dist-info}/WHEEL +1 -1
  53. {MEDfl-0.2.1.dist-info → medfl-2.0.0.dist-info/licenses}/LICENSE +674 -674
  54. MEDfl-0.2.1.dist-info/RECORD +0 -31
  55. {MEDfl-0.2.1.dist-info → medfl-2.0.0.dist-info}/top_level.txt +0 -0
@@ -1,60 +1,60 @@
1
- from MEDfl.NetManager.net_helper import *
2
- from MEDfl.NetManager.net_manager_queries import *
3
- from MEDfl.NetManager.database_connector import DatabaseManager
4
-
5
- class FederatedDataset:
6
- def __init__(
7
- self,
8
- name: str,
9
- train_nodes: list,
10
- test_nodes: list,
11
- trainloaders: list,
12
- valloaders: list,
13
- testloaders: list,
14
- ):
15
- """
16
- Represents a Federated Dataset.
17
-
18
- :param name: Name of the Federated Dataset.
19
- :param train_nodes: List of train nodes.
20
- :param test_nodes: List of test nodes.
21
- :param trainloaders: List of train data loaders.
22
- :param valloaders: List of validation data loaders.
23
- :param testloaders: List of test data loaders.
24
- """
25
- self.name = name
26
- self.train_nodes = train_nodes
27
- self.test_nodes = test_nodes
28
- self.trainloaders = trainloaders
29
- self.valloaders = valloaders
30
- self.testloaders = testloaders
31
- self.size = len(self.trainloaders[0].dataset[0][0])
32
-
33
- db_manager = DatabaseManager()
34
- db_manager.connect()
35
- self.eng = db_manager.get_connection()
36
-
37
- def create(self, FLsetupId: int):
38
- """
39
- Create a new Federated Dataset in the database.
40
-
41
- :param FLsetupId: The FLsetup ID associated with the Federated Dataset.
42
- """
43
- query_params = {"name": self.name, "FLsetupId": FLsetupId}
44
- fedDataId = get_feddataset_id_from_name(self.name)
45
- if fedDataId :
46
- self.id = fedDataId
47
- else:
48
- self.eng.execute(text(INSERT_FLDATASET_QUERY), query_params)
49
- self.id = get_feddataset_id_from_name(self.name)
50
-
51
-
52
- def update(self, FLpipeId: int, FedId: int):
53
- """
54
- Update the FLpipe ID associated with the Federated Dataset in the database.
55
-
56
- :param FLpipeId: The new FLpipe ID to be updated.
57
- :param FedId: The Federated Dataset ID.
58
- """
59
- query_params = {"FLpipeId": FLpipeId, "FedId": FedId}
60
- self.eng.execute(text(UPDATE_FLDATASET_QUERY), **query_params)
1
+ from MEDfl.NetManager.net_helper import *
2
+ from MEDfl.NetManager.net_manager_queries import *
3
+ from MEDfl.NetManager.database_connector import DatabaseManager
4
+
5
+ class FederatedDataset:
6
+ def __init__(
7
+ self,
8
+ name: str,
9
+ train_nodes: list,
10
+ test_nodes: list,
11
+ trainloaders: list,
12
+ valloaders: list,
13
+ testloaders: list,
14
+ ):
15
+ """
16
+ Represents a Federated Dataset.
17
+
18
+ :param name: Name of the Federated Dataset.
19
+ :param train_nodes: List of train nodes.
20
+ :param test_nodes: List of test nodes.
21
+ :param trainloaders: List of train data loaders.
22
+ :param valloaders: List of validation data loaders.
23
+ :param testloaders: List of test data loaders.
24
+ """
25
+ self.name = name
26
+ self.train_nodes = train_nodes
27
+ self.test_nodes = test_nodes
28
+ self.trainloaders = trainloaders
29
+ self.valloaders = valloaders
30
+ self.testloaders = testloaders
31
+ self.size = len(self.trainloaders[0].dataset[0][0])
32
+
33
+ db_manager = DatabaseManager()
34
+ db_manager.connect()
35
+ self.eng = db_manager.get_connection()
36
+
37
+ def create(self, FLsetupId: int):
38
+ """
39
+ Create a new Federated Dataset in the database.
40
+
41
+ :param FLsetupId: The FLsetup ID associated with the Federated Dataset.
42
+ """
43
+ query_params = {"name": self.name, "FLsetupId": FLsetupId}
44
+ fedDataId = get_feddataset_id_from_name(self.name)
45
+ if fedDataId :
46
+ self.id = fedDataId
47
+ else:
48
+ self.eng.execute(text(INSERT_FLDATASET_QUERY), query_params)
49
+ self.id = get_feddataset_id_from_name(self.name)
50
+
51
+
52
+ def update(self, FLpipeId: int, FedId: int):
53
+ """
54
+ Update the FLpipe ID associated with the Federated Dataset in the database.
55
+
56
+ :param FLpipeId: The new FLpipe ID to be updated.
57
+ :param FedId: The Federated Dataset ID.
58
+ """
59
+ query_params = {"FLpipeId": FLpipeId, "FedId": FedId}
60
+ self.eng.execute(text(UPDATE_FLDATASET_QUERY), **query_params)
@@ -1,192 +1,192 @@
1
- import datetime
2
- from typing import List
3
- import json
4
- import pandas as pd
5
-
6
-
7
- # File: create_query.py
8
- from sqlalchemy import text
9
- from torch.utils.data import DataLoader, TensorDataset
10
- import torch
11
-
12
- from MEDfl.LearningManager.server import FlowerServer
13
- from MEDfl.LearningManager.utils import params, test
14
- from MEDfl.NetManager.net_helper import get_flpipeline_from_name
15
- from MEDfl.NetManager.net_manager_queries import (CREATE_FLPIPELINE_QUERY,
16
- DELETE_FLPIPELINE_QUERY , CREATE_TEST_RESULTS_QUERY)
17
- from MEDfl.NetManager.database_connector import DatabaseManager
18
-
19
- def create_query(name, description, creation_date, result):
20
- query = text(
21
- f"INSERT INTO FLpipeline(name, description, creation_date, results) "
22
- f"VALUES ('{name}', '{description}', '{creation_date}', '{result}')"
23
- )
24
- return query
25
-
26
-
27
-
28
- class FLpipeline:
29
- """
30
- FLpipeline class for managing Federated Learning pipelines.
31
-
32
- Attributes:
33
- name (str): The name of the FLpipeline.
34
- description (str): A description of the FLpipeline.
35
- server (FlowerServer): The FlowerServer object associated with the FLpipeline.
36
-
37
- Methods:
38
- __init__(self, name: str, description: str, server: FlowerServer) -> None:
39
- Initialize FLpipeline with the specified name, description, and server.
40
-
41
-
42
- """
43
-
44
- def __init__(
45
- self, name: str, description: str, server: FlowerServer
46
- ) -> None:
47
- self.name = name
48
- self.description = description
49
- self.server = server
50
- self.validate()
51
-
52
- db_manager = DatabaseManager()
53
- db_manager.connect()
54
- self.eng = db_manager.get_connection()
55
-
56
- def validate(self) -> None:
57
- """
58
- Validate the name, description, and server attributes.
59
- Raises:
60
- TypeError: If the name is not a string, the description is not a string,
61
- or the server is not a FlowerServer object.
62
- """
63
- if not isinstance(self.name, str):
64
- raise TypeError("name argument must be a string")
65
-
66
- if not isinstance(self.description, str):
67
- raise TypeError("description argument must be a string")
68
-
69
- # if not isinstance(self.server, FlowerServer):
70
- # raise TypeError("server argument must be a FlowerServer")
71
-
72
- def create(self, result: str) -> None:
73
- """
74
- Create a new FLpipeline entry in the database with the given result.
75
-
76
- Args:
77
- result (str): The result string to store in the database.
78
-
79
- """
80
- creation_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
81
- query = CREATE_FLPIPELINE_QUERY.format(
82
- name=self.name,
83
- description=self.description,
84
- creation_date=creation_date,
85
- result=result,
86
- )
87
- self.eng.execute(text(query))
88
- self.id = get_flpipeline_from_name(self.name)
89
- try:
90
- self.server.fed_dataset.update(
91
- FLpipeId=self.id, FedId=self.server.fed_dataset.id
92
- )
93
- except:
94
- pass
95
-
96
- def delete(self) -> None:
97
- """
98
- Delete the FLpipeline entry from the database based on its name.
99
-
100
- Note: This is a placeholder method and needs to be implemented based on your specific database setup.
101
-
102
- """
103
- # Placeholder code for deleting the FLpipeline entry from the database based on the name.
104
- # You need to implement the actual deletion based on your database setup.
105
- self.eng.execute(DELETE_FLPIPELINE_QUERY.format(self.name))
106
-
107
-
108
- def test_by_node(self, node_name: str, test_frac=1) -> dict:
109
- """
110
- Test the FLpipeline by node with the specified test_frac.
111
-
112
- Args:
113
- node_name (str): The name of the node to test.
114
- test_frac (float, optional): The fraction of the test data to use. Default is 1.
115
-
116
- Returns:
117
- dict: A dictionary containing the node name and the classification report.
118
-
119
- """
120
- idx = self.server.fed_dataset.test_nodes.index(node_name)
121
- global_model, test_loader = (
122
- self.server.global_model,
123
- self.server.fed_dataset.testloaders[idx],
124
- )
125
-
126
- # Move model to GPU if available
127
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
128
- global_model.model.to(device)
129
-
130
- # Prepare test data
131
- test_data = test_loader.dataset
132
- num_samples = int(test_frac * len(test_data))
133
- test_data = TensorDataset(test_data[:num_samples][0].to(device), test_data[:num_samples][1].to(device))
134
-
135
- # Create DataLoader for test data
136
- test_loader = DataLoader(test_data, batch_size=params["test_batch_size"])
137
-
138
- # Perform testing
139
- classification_report = test(model=global_model.model, test_loader=test_loader, device=device)
140
-
141
- return {
142
- "node_name": node_name,
143
- "classification_report": str(classification_report),
144
- }
145
-
146
-
147
- def auto_test(self, test_frac=1) -> List[dict]:
148
- """
149
- Automatically test the FLpipeline on all nodes with the specified test_frac.
150
-
151
- Args:
152
- test_frac (float, optional): The fraction of the test data to use. Default is 1.
153
-
154
- Returns:
155
- List[dict]: A list of dictionaries containing the node names and the classification reports.
156
-
157
- """
158
- result = [
159
- self.test_by_node(node, test_frac)
160
- for node in self.server.fed_dataset.test_nodes
161
- ]
162
- self.create("\n".join(str(res).replace("'", '"') for res in result))
163
-
164
- # stockage des resultats des tests
165
- for entry in result:
166
- node_name = entry['node_name']
167
- classification_report_str = entry['classification_report']
168
-
169
- # Convert the 'classification_report' string to a dictionary
170
- classification_report_dict = json.loads(classification_report_str.replace("'", "\""))
171
- try:
172
- # Insert record into the 'testResults' table
173
- query = CREATE_TEST_RESULTS_QUERY.format(
174
- pipelineId = self.id,
175
- nodeName = node_name ,
176
- confusion_matrix = json.dumps(classification_report_dict['confusion matrix']),
177
- accuracy =classification_report_dict['Accuracy'] ,
178
- sensivity = classification_report_dict['Sensitivity/Recall'] ,
179
- ppv = classification_report_dict['PPV/Precision'] ,
180
- npv= classification_report_dict['NPV'] ,
181
- f1score= classification_report_dict['F1-score'] ,
182
- fpr= classification_report_dict['False positive rate'] ,
183
- tpr= classification_report_dict['True positive rate']
184
- )
185
- self.eng.execute(text(query))
186
- except Exception as e:
187
- # This block will catch any other exceptions
188
- print(f"An unexpected error occurred: {e}")
189
-
190
-
191
-
192
- return result
1
+ import datetime
2
+ from typing import List
3
+ import json
4
+ import pandas as pd
5
+
6
+
7
+ # File: create_query.py
8
+ from sqlalchemy import text
9
+ from torch.utils.data import DataLoader, TensorDataset
10
+ import torch
11
+
12
+ from MEDfl.LearningManager.server import FlowerServer
13
+ from MEDfl.LearningManager.utils import params, test
14
+ from MEDfl.NetManager.net_helper import get_flpipeline_from_name
15
+ from MEDfl.NetManager.net_manager_queries import (CREATE_FLPIPELINE_QUERY,
16
+ DELETE_FLPIPELINE_QUERY , CREATE_TEST_RESULTS_QUERY)
17
+ from MEDfl.NetManager.database_connector import DatabaseManager
18
+
19
+ def create_query(name, description, creation_date, result):
20
+ query = text(
21
+ f"INSERT INTO FLpipeline(name, description, creation_date, results) "
22
+ f"VALUES ('{name}', '{description}', '{creation_date}', '{result}')"
23
+ )
24
+ return query
25
+
26
+
27
+
28
+ class FLpipeline:
29
+ """
30
+ FLpipeline class for managing Federated Learning pipelines.
31
+
32
+ Attributes:
33
+ name (str): The name of the FLpipeline.
34
+ description (str): A description of the FLpipeline.
35
+ server (FlowerServer): The FlowerServer object associated with the FLpipeline.
36
+
37
+ Methods:
38
+ __init__(self, name: str, description: str, server: FlowerServer) -> None:
39
+ Initialize FLpipeline with the specified name, description, and server.
40
+
41
+
42
+ """
43
+
44
+ def __init__(
45
+ self, name: str, description: str, server: FlowerServer
46
+ ) -> None:
47
+ self.name = name
48
+ self.description = description
49
+ self.server = server
50
+ self.validate()
51
+
52
+ db_manager = DatabaseManager()
53
+ db_manager.connect()
54
+ self.eng = db_manager.get_connection()
55
+
56
+ def validate(self) -> None:
57
+ """
58
+ Validate the name, description, and server attributes.
59
+ Raises:
60
+ TypeError: If the name is not a string, the description is not a string,
61
+ or the server is not a FlowerServer object.
62
+ """
63
+ if not isinstance(self.name, str):
64
+ raise TypeError("name argument must be a string")
65
+
66
+ if not isinstance(self.description, str):
67
+ raise TypeError("description argument must be a string")
68
+
69
+ # if not isinstance(self.server, FlowerServer):
70
+ # raise TypeError("server argument must be a FlowerServer")
71
+
72
+ def create(self, result: str) -> None:
73
+ """
74
+ Create a new FLpipeline entry in the database with the given result.
75
+
76
+ Args:
77
+ result (str): The result string to store in the database.
78
+
79
+ """
80
+ creation_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
81
+ query = CREATE_FLPIPELINE_QUERY.format(
82
+ name=self.name,
83
+ description=self.description,
84
+ creation_date=creation_date,
85
+ result=result,
86
+ )
87
+ self.eng.execute(text(query))
88
+ self.id = get_flpipeline_from_name(self.name)
89
+ try:
90
+ self.server.fed_dataset.update(
91
+ FLpipeId=self.id, FedId=self.server.fed_dataset.id
92
+ )
93
+ except:
94
+ pass
95
+
96
+ def delete(self) -> None:
97
+ """
98
+ Delete the FLpipeline entry from the database based on its name.
99
+
100
+ Note: This is a placeholder method and needs to be implemented based on your specific database setup.
101
+
102
+ """
103
+ # Placeholder code for deleting the FLpipeline entry from the database based on the name.
104
+ # You need to implement the actual deletion based on your database setup.
105
+ self.eng.execute(DELETE_FLPIPELINE_QUERY.format(self.name))
106
+
107
+
108
+ def test_by_node(self, node_name: str, test_frac=1) -> dict:
109
+ """
110
+ Test the FLpipeline by node with the specified test_frac.
111
+
112
+ Args:
113
+ node_name (str): The name of the node to test.
114
+ test_frac (float, optional): The fraction of the test data to use. Default is 1.
115
+
116
+ Returns:
117
+ dict: A dictionary containing the node name and the classification report.
118
+
119
+ """
120
+ idx = self.server.fed_dataset.test_nodes.index(node_name)
121
+ global_model, test_loader = (
122
+ self.server.global_model,
123
+ self.server.fed_dataset.testloaders[idx],
124
+ )
125
+
126
+ # Move model to GPU if available
127
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
128
+ global_model.model.to(device)
129
+
130
+ # Prepare test data
131
+ test_data = test_loader.dataset
132
+ num_samples = int(test_frac * len(test_data))
133
+ test_data = TensorDataset(test_data[:num_samples][0].to(device), test_data[:num_samples][1].to(device))
134
+
135
+ # Create DataLoader for test data
136
+ test_loader = DataLoader(test_data, batch_size=params["test_batch_size"])
137
+
138
+ # Perform testing
139
+ classification_report = test(model=global_model.model, test_loader=test_loader, device=device)
140
+
141
+ return {
142
+ "node_name": node_name,
143
+ "classification_report": str(classification_report),
144
+ }
145
+
146
+
147
+ def auto_test(self, test_frac=1) -> List[dict]:
148
+ """
149
+ Automatically test the FLpipeline on all nodes with the specified test_frac.
150
+
151
+ Args:
152
+ test_frac (float, optional): The fraction of the test data to use. Default is 1.
153
+
154
+ Returns:
155
+ List[dict]: A list of dictionaries containing the node names and the classification reports.
156
+
157
+ """
158
+ result = [
159
+ self.test_by_node(node, test_frac)
160
+ for node in self.server.fed_dataset.test_nodes
161
+ ]
162
+ self.create("\n".join(str(res).replace("'", '"') for res in result))
163
+
164
+ # stockage des resultats des tests
165
+ for entry in result:
166
+ node_name = entry['node_name']
167
+ classification_report_str = entry['classification_report']
168
+
169
+ # Convert the 'classification_report' string to a dictionary
170
+ classification_report_dict = json.loads(classification_report_str.replace("'", "\""))
171
+ try:
172
+ # Insert record into the 'testResults' table
173
+ query = CREATE_TEST_RESULTS_QUERY.format(
174
+ pipelineId = self.id,
175
+ nodeName = node_name ,
176
+ confusion_matrix = json.dumps(classification_report_dict['confusion matrix']),
177
+ accuracy =classification_report_dict['Accuracy'] ,
178
+ sensivity = classification_report_dict['Sensitivity/Recall'] ,
179
+ ppv = classification_report_dict['PPV/Precision'] ,
180
+ npv= classification_report_dict['NPV'] ,
181
+ f1score= classification_report_dict['F1-score'] ,
182
+ fpr= classification_report_dict['False positive rate'] ,
183
+ tpr= classification_report_dict['True positive rate']
184
+ )
185
+ self.eng.execute(text(query))
186
+ except Exception as e:
187
+ # This block will catch any other exceptions
188
+ print(f"An unexpected error occurred: {e}")
189
+
190
+
191
+
192
+ return result