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
@@ -0,0 +1,287 @@
1
+ import torch
2
+ import torch.nn as nn
3
+ from sklearn.svm import SVC
4
+
5
+ class DynamicModel:
6
+ """DynamicModel class for creating various types of neural network models."""
7
+
8
+ # Create a binary classifier model
9
+ @staticmethod
10
+ def create_binary_classifier(input_dim, hidden_dims, output_dim, activation='relu', dropout_rate=0.0,
11
+ batch_norm=False, use_gpu=False):
12
+ """
13
+ Creates a binary classifier neural network model with customizable architecture.
14
+
15
+ Args:
16
+ input_dim (int): Dimension of the input data.
17
+ hidden_dims (List[int]): List of dimensions for hidden layers.
18
+ output_dim (int): Dimension of the output (number of classes).
19
+ activation (str, optional): Activation function for hidden layers. Default is 'relu'.
20
+ dropout_rate (float, optional): Dropout rate for regularization. Default is 0.0 (no dropout).
21
+ batch_norm (bool, optional): Whether to apply batch normalization. Default is False.
22
+ use_gpu (bool, optional): Whether to use GPU acceleration. Default is False.
23
+
24
+ Returns:
25
+ torch.nn.Module: Created PyTorch model.
26
+ """
27
+
28
+ layers = []
29
+
30
+ for i in range(len(hidden_dims)):
31
+ if i == 0:
32
+ layers.append(nn.Linear(input_dim, hidden_dims[0]))
33
+ else:
34
+ layers.append(nn.Linear(hidden_dims[i - 1], hidden_dims[i]))
35
+
36
+ if batch_norm:
37
+ layers.append(nn.BatchNorm1d(hidden_dims[i]))
38
+
39
+ activation_layer = nn.ReLU() if activation == 'relu' else nn.Sigmoid()
40
+ layers.append(activation_layer)
41
+
42
+ if dropout_rate > 0.0:
43
+ layers.append(nn.Dropout(dropout_rate))
44
+
45
+ layers.append(nn.Linear(hidden_dims[-1], output_dim))
46
+ layers.append(nn.Sigmoid())
47
+
48
+ model = nn.Sequential(*layers)
49
+
50
+ if use_gpu:
51
+ model = model.cuda()
52
+
53
+ return model
54
+
55
+ # Create a multi-class classifier model
56
+ @staticmethod
57
+ def create_multiclass_classifier(input_dim, hidden_dims, output_dim, activation='relu', dropout_rate=0.0,
58
+ batch_norm=False, use_gpu=False):
59
+ """
60
+ Creates a multiclass classifier neural network model with customizable architecture.
61
+
62
+ Args:
63
+ input_dim (int): Dimension of the input data.
64
+ hidden_dims (List[int]): List of dimensions for hidden layers.
65
+ output_dim (int): Dimension of the output (number of classes).
66
+ activation (str, optional): Activation function for hidden layers. Default is 'relu'.
67
+ dropout_rate (float, optional): Dropout rate for regularization. Default is 0.0 (no dropout).
68
+ batch_norm (bool, optional): Whether to apply batch normalization. Default is False.
69
+ use_gpu (bool, optional): Whether to use GPU acceleration. Default is False.
70
+
71
+ Returns:
72
+ torch.nn.Module: Created PyTorch model.
73
+ """
74
+ layers = []
75
+
76
+ for i in range(len(hidden_dims)):
77
+ if i == 0:
78
+ layers.append(nn.Linear(input_dim, hidden_dims[0]))
79
+ else:
80
+ layers.append(nn.Linear(hidden_dims[i - 1], hidden_dims[i]))
81
+
82
+ if batch_norm:
83
+ layers.append(nn.BatchNorm1d(hidden_dims[i]))
84
+
85
+ activation_layer = nn.ReLU() if activation == 'relu' else nn.Sigmoid()
86
+ layers.append(activation_layer)
87
+
88
+ if dropout_rate > 0.0:
89
+ layers.append(nn.Dropout(dropout_rate))
90
+
91
+ layers.append(nn.Linear(hidden_dims[-1], output_dim))
92
+ layers.append(nn.LogSoftmax(dim=1))
93
+
94
+ model = nn.Sequential(*layers)
95
+
96
+ if use_gpu:
97
+ model = model.cuda()
98
+
99
+ return model
100
+
101
+ # Create a linear regressor model
102
+ @staticmethod
103
+ def create_linear_regressor(input_dim, output_dim, use_gpu=False):
104
+ """
105
+ Creates a linear regressor neural network model.
106
+
107
+ Args:
108
+ input_dim (int): Dimension of the input data.
109
+ output_dim (int): Dimension of the output.
110
+
111
+ Returns:
112
+ torch.nn.Module: Created PyTorch model.
113
+ """
114
+ class LinearRegressionModel(nn.Module):
115
+ def __init__(self):
116
+ super(LinearRegressionModel, self).__init__()
117
+ self.linear = nn.Linear(input_dim, output_dim)
118
+
119
+ def forward(self, x):
120
+ return self.linear(x)
121
+
122
+ model = LinearRegressionModel()
123
+
124
+ if use_gpu:
125
+ model = model.cuda()
126
+
127
+ return model
128
+
129
+ # Create a logistic regressor model
130
+ @staticmethod
131
+ def create_logistic_regressor(input_dim, use_gpu=False):
132
+ """
133
+ Creates a logistic regressor neural network model.
134
+
135
+ Args:
136
+ input_dim (int): Dimension of the input data.
137
+
138
+ Returns:
139
+ torch.nn.Module: Created PyTorch model.
140
+ """
141
+ class LogisticRegressionModel(nn.Module):
142
+ def __init__(self):
143
+ super(LogisticRegressionModel, self).__init__()
144
+ self.linear = nn.Linear(input_dim, 1)
145
+
146
+ def forward(self, x):
147
+ return torch.sigmoid(self.linear(x))
148
+
149
+ model = LogisticRegressionModel()
150
+
151
+ if use_gpu:
152
+ model = model.cuda()
153
+
154
+ return model
155
+
156
+ @staticmethod
157
+ def create_convolutional_neural_network(input_channels, output_channels, kernel_size, use_gpu=False):
158
+ """
159
+ Creates a convolutional neural network (CNN) model.
160
+
161
+ Args:
162
+ input_channels (int): Number of input channels.
163
+ output_channels (int): Number of output channels.
164
+ kernel_size (int): Size of the convolutional kernel.
165
+
166
+ Returns:
167
+ torch.nn.Module: Created PyTorch model.
168
+ """
169
+
170
+ model = nn.Sequential(
171
+ nn.Conv2d(input_channels, output_channels, kernel_size),
172
+ nn.ReLU(),
173
+ nn.MaxPool2d(2)
174
+ )
175
+
176
+ if use_gpu:
177
+ model = model.cuda()
178
+
179
+ return model
180
+
181
+ @staticmethod
182
+ def create_recurrent_neural_network(input_size, hidden_size, use_gpu=False):
183
+ """
184
+ Creates a recurrent neural network (RNN) model.
185
+
186
+ Args:
187
+ input_size (int): Size of the input.
188
+ hidden_size (int): Size of the hidden layer.
189
+
190
+ Returns:
191
+ torch.nn.Module: Created PyTorch model.
192
+ """
193
+
194
+ model = nn.RNN(input_size, hidden_size, batch_first=True)
195
+
196
+ if use_gpu:
197
+ model = model.cuda()
198
+
199
+ return model
200
+
201
+ @staticmethod
202
+ def create_lstm_network(input_size, hidden_size, use_gpu=False):
203
+ """
204
+ Creates a Long Short-Term Memory (LSTM) network model.
205
+
206
+ Args:
207
+ input_size (int): Size of the input layer.
208
+ hidden_size (int): Size of the hidden layer.
209
+
210
+ Returns:
211
+ torch.nn.Module: Created PyTorch model.
212
+ """
213
+
214
+ model = nn.LSTM(input_size, hidden_size, batch_first=True)
215
+
216
+ if use_gpu:
217
+ model = model.cuda()
218
+
219
+ return model
220
+
221
+ # Create the dynamic model
222
+ def create_model(self, model_type: str, params_dict={}) -> torch.nn.Module:
223
+ """
224
+ Create a specific type of model dynamically based on the given parameters.
225
+
226
+ Args:
227
+ model_type (str): Type of the model to create ('Binary Classifier', 'Multiclass Classifier', 'Linear Regressor', 'Logistic Regressor', 'SVM', 'Neural Network Classifier', 'Convolutional Neural Network', 'Recurrent Neural Network', 'LSTM Network', 'Autoencoder').
228
+ params_dict (dict): Dictionary containing parameters for model creation.
229
+
230
+ Returns:
231
+ torch.nn.Module: Created PyTorch model.
232
+ """
233
+ if model_type == 'Binary Classifier':
234
+ return self.create_binary_classifier(
235
+ params_dict['input_dim'], params_dict['hidden_dims'],
236
+ params_dict['output_dim'], params_dict.get('activation', 'relu'),
237
+ params_dict.get('dropout_rate', 0.0), params_dict.get('batch_norm', False),
238
+ params_dict.get('use_gpu', False)
239
+ )
240
+ elif model_type == 'Multiclass Classifier':
241
+ return self.create_multiclass_classifier(
242
+ params_dict['input_dim'], params_dict['hidden_dims'],
243
+ params_dict['output_dim'], params_dict.get('activation', 'relu'),
244
+ params_dict.get('dropout_rate', 0.0), params_dict.get('batch_norm', False),
245
+ params_dict.get('use_gpu', False)
246
+ )
247
+ elif model_type == 'Linear Regressor':
248
+ return self.create_linear_regressor(
249
+ params_dict['input_dim'], params_dict['output_dim'],
250
+ params_dict.get('use_gpu', False)
251
+ )
252
+ elif model_type == 'Logistic Regressor':
253
+ return self.create_logistic_regressor(
254
+ params_dict['input_dim'], params_dict.get('use_gpu', False)
255
+ )
256
+ elif model_type == 'Neural Network Classifier':
257
+ return self.create_neural_network_classifier(
258
+ params_dict['input_dim'], params_dict['output_dim'],
259
+ params_dict['hidden_dims'], params_dict.get('activation', 'relu'),
260
+ params_dict.get('dropout_rate', 0.0), params_dict.get('batch_norm', False),
261
+ params_dict.get('num_layers', 2), params_dict.get('use_gpu', False)
262
+ )
263
+ elif model_type == 'Convolutional Neural Network':
264
+ return self.create_convolutional_neural_network(
265
+ params_dict['input_channels'], params_dict['output_channels'],
266
+ params_dict['kernel_size'], params_dict.get('use_gpu', False)
267
+ )
268
+ elif model_type == 'Recurrent Neural Network':
269
+ return self.create_recurrent_neural_network(
270
+ params_dict['input_size'], params_dict['hidden_size'],
271
+ params_dict.get('use_gpu', False)
272
+ )
273
+ elif model_type == 'LSTM Network':
274
+ return self.create_lstm_network(
275
+ params_dict['input_size'], params_dict['hidden_size'],
276
+ params_dict.get('use_gpu', False)
277
+ )
278
+ elif model_type == 'Autoencoder':
279
+ return self.create_autoencoder(
280
+ params_dict['input_size'], params_dict['encoder_hidden_size'],
281
+ params_dict.get('use_gpu', False)
282
+ )
283
+ else:
284
+ raise ValueError("Invalid model type provided")
285
+
286
+
287
+
@@ -0,0 +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)
@@ -0,0 +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