diff --git a/README.md b/README.md
index 3212fc269a351dffce308cbff38caccb55cf45a7..d59ae0de436eea6ed90d8251af3302176c4c02dd 100644
--- a/README.md
+++ b/README.md
@@ -1,93 +1,42 @@
-# fl_example
+# Federated Image Classification with Flower
 
+## Introduction
 
+In this GitHub code, we implement federated learning with the FLOWER framework for image classification. We will walk you through using this code for your own custom federated image classification use case.
 
-## Getting started
+We first start with a description of all the Python files, explaining their contents, and then go through a step-by-step process to run your custom dataset.
 
-To make it easy for you to get started with GitLab, here's a list of recommended next steps.
+## Getting Started
 
-Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
+Starting with a description of all files:
 
-## Add your files
+- `main.py` - Main file consisting of Flower with federated learning code.
+- `main_xx.py` (e.g., `main_flta` or `main_esaim`) - Custom extensions of the main code. Mainly alters the dataset path.
+- `strategy.py` - Implements plain and weighted averaging of weights.
+- `config.yaml` - Contains all the parameters required to run the federated learning code.
+- `train_and_test.py` - Implements centralized training for each individual client. The client to be trained is specified in `config.yaml` under `client_id`.
+- `test_global_weights.py` - Tests any weights (specifically global federated weights) on the global test dataset or any other private test dataset. The paths to the folder with test images and custom weights are set here. This file uses `config_test.yaml`.
 
-- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
-- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
+### Dataset Setup
 
-```
-cd existing_repo
-git remote add origin https://gitlab.rhrk.uni-kl.de/dalim/fl_example.git
-git branch -M main
-git push -uf origin main
-```
+1. Create a folder, e.g., `MNIST_DATASET`, and within that folder, create subfolders for each client. Name the folders 'Client1', 'Client2', ..., 'Clientx', and ensure each of these folders contains three subfolders: `train`, `test`, and `val`. Having a `test` folder is not compulsory, but having a `val` folder is necessary for evaluating the best weights for centralized training or early stopping.
 
-## Integrate with your tools
+2. Within each `train`, `test`, and `val` folder, create subfolders with names corresponding to their labels. For example, if using the MNIST dataset with 10 classes (0-9), each client folder should contain subfolders named '0', '1', ..., '9', each containing the respective images.
 
-- [ ] [Set up project integrations](https://gitlab.rhrk.uni-kl.de/dalim/fl_example/-/settings/integrations)
+3. Ensure the label names are set in `main.py` within the dictionary variable `class_map_str_to_idx` (line 101).
 
-## Collaborate with your team
+4. For research purposes, create a **global test dataset** comprising test images from all clients. This dataset is used to test the global federated weights obtained after each communication round.
 
-- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
-- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
-- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
-- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
-- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
+5. Specify the name of your output folder in `config.yaml`. The code will create a path within the `runs` folder as specified in `config.yaml`, saving all communication round (CR) weights for further testing and an `output.txt` file containing all test metrics for each CR weight.
 
-## Test and Deploy
+## Running the Code
 
-Use the built-in continuous integration in GitLab.
+1. Add the label names to the `class_map_str_to_idx` dictionary as mentioned above.
 
-- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
-- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
-- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
-- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
-- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
+2. Set the path to your dataset training directory (the folder containing 'Client1', 'Client2', etc.). The code will automatically load the train and val datasets for each client from the respective folder names.
 
-***
+3. Set the path to the global test dataset you wish to test the global weights with after each communication round.
 
-# Editing this README
+4. In `config.yaml`, select the architecture (EfficientNet, VGG, ResNet, InceptionNet, DenseNet), choose the federated strategy, set `use_best_weights` to True to save the best weights out of the total number of local epochs, and configure the optimizer, local epochs, batch size, image size, etc.
 
-When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
-
-## Suggestions for a good README
-
-Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
-
-## Name
-Choose a self-explaining name for your project.
-
-## Description
-Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
-
-## Badges
-On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
-
-## Visuals
-Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
-
-## Installation
-Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
-
-## Usage
-Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
-
-## Support
-Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
-
-## Roadmap
-If you have ideas for releases in the future, it is a good idea to list them in the README.
-
-## Contributing
-State if you are open to contributions and what your requirements are for accepting them.
-
-For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
-
-You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
-
-## Authors and acknowledgment
-Show your appreciation to those who have contributed to the project.
-
-## License
-For open source projects, say how it is licensed.
-
-## Project status
-If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
+With this, you can run any number of clients, provided you stick to the dataset setup as mentioned above.
\ No newline at end of file
diff --git a/arial.ttf b/arial.ttf
new file mode 100644
index 0000000000000000000000000000000000000000..24b9cf2948057a17bdcfe1a0830cd10e5ab8b485
Binary files /dev/null and b/arial.ttf differ
diff --git a/config.yaml b/config.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..8110fe81d4f407b55b4adcb6c56dcebd5b3c55d8
--- /dev/null
+++ b/config.yaml
@@ -0,0 +1,25 @@
+seed: 10
+
+strategy: PlainFedAvg # PlainFedAvg, FedAvg
+num_clients: 5
+num_classes: 5
+num_rounds: 1
+epochs: 1
+early_stopping: 5
+
+optimizer: SGD # SGD, Adam, AdamW
+momentum: 0.8
+loss_fcn: CrossEntropyLoss # CrossEntropyLoss
+lr: 0.001
+lr_scheduler: False
+
+batch_size: 8
+
+model: DenseNet # EfficientNet, VGG, ResNet, InceptionNet, DenseNet
+use_best_weights: False #True or False to use best ot last weights
+img_size: 300 #224 = ResNet,Vgg 229=Inception, DenseNet (anything), EfficientNet=300 or 380 #and 600 for all NET in FLTA paper
+output_folder: FLTA2024/DenseNet_Plain_lastweight
+#output_folder: FLTA_centralized/InceptionNet/InceptionNet_600img_centralized_client4
+
+##for train_and_test
+#client_id: 
diff --git a/config_test.yaml b/config_test.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..bdf1dbaa94cdca4f8672b7be50fb0c8c85f9c91a
--- /dev/null
+++ b/config_test.yaml
@@ -0,0 +1,11 @@
+num_classes: 2  # Number of classes in your dataset
+model_name: InceptionNet # EfficientNet, VGG, ResNet, InceptionNet, DenseNet
+batch_size: 16  # Batch size for testing
+image_size: 300  # Image size (input size) for your model 224 for all except inception net where size should be 300
+#class_names: ['No_windshield', 'With_windshield']
+#test_folder: dataset/ESAIM/global_test_set  # Path to the folder containing your test images
+test_folder: dataset/Cabins5_flta/global_test_set  # Path to the folder containing your test images
+#weights_path: /home/vinit/Desktop/federated_image_classification/runs/federated learning_ esaim/InceptionNet_ESAIM_WeightedAvg_lr001/global_model/best_server_round_10.pt  # Path to the trained weights of your model
+#output_folder: test_results/InceptionNet_global_weighted # Path where you want to save the results
+weights_path:
+output_folder: test_flta/
diff --git a/global_test_set.zip b/global_test_set.zip
new file mode 100644
index 0000000000000000000000000000000000000000..7357be29456e4970d3785b2749158ef773788559
Binary files /dev/null and b/global_test_set.zip differ
diff --git a/main.py b/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..8980a31d559f67b034dae60c51fb1f5516c33ec2
--- /dev/null
+++ b/main.py
@@ -0,0 +1,860 @@
+# ------------------------------
+# Import libraries
+# ------------------------------
+
+import zipfile
+import yaml
+from collections import OrderedDict
+from typing import Dict, List, Optional, Tuple, Union
+import os
+import sys
+import glob
+import shutil
+from copy import deepcopy
+import numpy as np
+import random
+import torch
+import torch.nn as nn
+from torch.optim import lr_scheduler
+from torch.utils.data import Dataset
+import torchvision
+from torchvision.models import efficientnet_v2_s, vgg19, resnet50, inception_v3, densenet121
+from torchvision.utils import make_grid, save_image
+import cv2
+# import albumentations as A
+import flwr as fl
+from flwr.common import (
+    Code,
+    EvaluateIns,
+    EvaluateRes,
+    FitIns,
+    FitRes,
+    GetParametersIns,
+    GetParametersRes,
+    Status,
+    NDArrays,
+    Parameters,
+    Scalar,
+    ndarrays_to_parameters,
+    parameters_to_ndarrays,
+)
+from flwr.server.strategy import FedAvg
+from strategy import PlainFedAvg
+
+
+
+# ------------------------------
+# Load config file
+# ------------------------------
+
+config_file_name = "config.yaml"
+with open(config_file_name) as file:
+    CONFIG = yaml.safe_load(file)
+
+
+
+# ------------------------------
+# Extract .zip folder
+# ------------------------------
+
+def extract_zip(zip_file_name: str, save_dir: str):
+    """
+    Extract .zip folder, if not already done
+    """
+
+    parts = zip_file_name.split(".")
+    file_name = parts[0]
+
+    if not os.path.isdir(file_name):
+        with zipfile.ZipFile(zip_file_name, "r") as zip_ref:
+            zip_ref.extractall(save_dir)
+        print(f"Folder '{zip_file_name}' was successfully extracted")
+    else:
+        print(f"Folder '{file_name}' already exists")
+
+
+
+# ------------------------------
+# Set seeds
+# ------------------------------
+
+def set_seeds(seed):
+    """
+
+    """
+
+    random.seed(seed)
+    os.environ['PYTHONHASHSEED'] = str(seed)
+    np.random.seed(seed)
+    torch.manual_seed(seed)
+    torch.cuda.manual_seed(seed)
+    torch.cuda.manual_seed_all(seed)
+    torch.backends.cudnn.deterministic = True
+    torch.backends.cudnn.benchmark = False
+
+
+
+# ----------------------------------------
+#
+# ----------------------------------------
+
+class_map_str_to_idx = {
+    "electric fan": 0,
+    "gas pump": 1,
+    "hourglass": 2,
+    "knot": 3,
+    "loudspeaker": 4,
+    "pinwheel": 5,
+    "screen": 6,
+    "space heater": 7,
+    "stopwatch": 8,
+    "syringe": 9,
+}
+
+
+
+# ----------------------------------------
+# Load data
+# ----------------------------------------
+
+class Dataloader(Dataset):
+    def __init__(self, root_dir, loader_mode, imgsz):
+        self.root_dir = root_dir
+        self.loader_mode = loader_mode
+        if self.loader_mode == "test":
+            self.imgs = [elem for elem in glob.glob(os.path.join(root_dir, "*", "*"))]
+        else:
+            self.imgs = [elem for elem in glob.glob(os.path.join(root_dir, self.loader_mode, "*", "*"))]
+
+        self.imgs_and_lbls = []
+        for path in self.imgs:
+            #print(class_map_str_to_idx[path.split(os.sep)[-2]])
+            self.imgs_and_lbls.append([cv2.imread(path, cv2.IMREAD_COLOR), class_map_str_to_idx[path.split(os.sep)[-2]]])
+
+        self.transform = torchvision.transforms.Compose([
+            torchvision.transforms.ToTensor(),
+            torchvision.transforms.Resize((imgsz, imgsz)),
+        ])
+
+        # if self.loader_mode == "train":
+        #     self.augment = A.Compose([
+        #         A.VerticalFlip(p=0.5),
+        #         A.Rotate(limit=15, border_mode=cv2.BORDER_CONSTANT, value=(0,0,0), p=0.75)
+        #     ])
+
+    def __len__(self):
+        return len(self.imgs)
+
+    def __getitem__(self, idx):
+        img, lbl = self.imgs_and_lbls[idx]
+
+        # add augmentation during training
+        # if self.loader_mode == "train":
+        #     augmented = self.augment(img)
+        #     img = augmented["image"]
+
+        # transform numpy array into Pytorch tensor
+        img_torch = self.transform(img)
+
+        return img_torch, lbl
+
+
+
+def load_train_val_data(root_dir, batch_size, imgsz):
+    """
+
+    """
+
+    train_dataset = Dataloader(root_dir=root_dir, loader_mode="train", imgsz=imgsz)
+    val_dataset = Dataloader(root_dir=root_dir, loader_mode="val", imgsz=imgsz)
+
+    train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, pin_memory=True, shuffle=True)
+    val_dataloader = torch.utils.data.DataLoader(val_dataset, batch_size=batch_size, pin_memory=True, shuffle=False)
+
+    return train_dataloader, val_dataloader
+
+
+
+def load_test_data(root_dir, batch_size, imgsz):
+    """
+
+    """
+
+    test_dataset = Dataloader(root_dir=root_dir, loader_mode="test", imgsz=imgsz)
+
+    test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, pin_memory=True, shuffle=False)
+
+    return test_dataloader
+
+
+
+# ----------------------------------------
+# Train model
+# ----------------------------------------
+
+def train_model(model,
+                train_dataloader,
+                val_dataloader,
+                optimizer,
+                num_epochs,
+                criterion,
+                device,
+                use_best_weights,
+                early_stopping,
+                save_dir):
+    """
+
+    """
+
+    # if CONFIG["lr_scheduler"]:
+    #     scheduler = lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.75)
+
+    best_loss = np.inf
+
+    model.to(device)
+    model.train()
+
+    hist_train_loss, hist_train_acc, hist_val_loss, hist_val_acc = [], [], [], []
+
+    epochs_without_improvement = 0
+
+    for epoch in range(num_epochs):
+        # training
+        model.train()
+
+        correct = 0
+        total = 0
+        epoch_train_loss = 0.0
+
+        for inputs, labels in train_dataloader:
+            inputs = inputs.to(device)
+            labels = labels.to(device)
+
+            optimizer.zero_grad()
+
+            outputs = model(inputs)
+            _, preds = torch.max(nn.functional.softmax(outputs, dim=1), 1)
+            loss = criterion(outputs, labels)
+
+            loss.backward()
+            optimizer.step()
+
+            epoch_train_loss += loss.item()
+            correct += torch.sum(preds == labels).item()
+            total += labels.size(0)
+
+        epoch_train_loss = epoch_train_loss / total
+        epoch_train_acc = correct / total
+        hist_train_loss.append(epoch_train_loss)
+        hist_train_acc.append(epoch_train_acc)
+
+        # scheduler.step()
+
+        # validation
+        model.eval()
+
+        correct = 0
+        total = 0
+        epoch_val_loss = 0.0
+
+        with torch.no_grad():
+            for inputs, labels in val_dataloader:
+                inputs = inputs.to(device)
+                labels = labels.to(device)
+
+                outputs = model(inputs)
+                _, preds = torch.max(nn.functional.softmax(outputs, dim=1), 1)
+
+                epoch_val_loss += criterion(outputs, labels).item()
+                correct += torch.sum(preds == labels).item()
+                total += labels.size(0)
+
+        epoch_val_loss = epoch_val_loss / total
+        epoch_val_acc = correct / total
+        hist_val_loss.append(epoch_val_loss)
+        hist_val_acc.append(epoch_val_acc)
+
+        # early stopping
+        if epoch_val_loss < best_loss:
+            best_loss = epoch_val_loss
+            epochs_without_improvement = 0
+
+            # save best model as .pt
+            save_model(model, os.path.join(save_dir, "best.pt"))
+            if use_best_weights:
+                best_model_state = deepcopy(model.state_dict())
+        else:
+            epochs_without_improvement += 1
+            if epochs_without_improvement >= early_stopping:
+                print(f"Early stopping after {epoch+1} epochs without improvement")
+                break
+
+    history = {"train_acc": hist_train_acc, "train_loss": hist_train_loss, "val_acc": hist_val_acc, "val_loss": hist_val_loss}
+
+    # save last model as .pt
+    save_model(model, os.path.join(save_dir, "last.pt"))
+
+    if use_best_weights:
+        model.load_state_dict(best_model_state)
+
+    return history
+
+
+
+# ----------------------------------------
+# Test model
+# ----------------------------------------
+
+def test_model(model, dataloader, criterion, device, num_classes):
+    """
+    Test model and calculate confusion matrix
+    """
+
+    model.to(device)
+    model.eval()
+
+    confusion_matrix = np.zeros((num_classes, num_classes))
+
+    correct = 0
+    total = 0
+    loss = 0.0
+
+    with torch.no_grad():
+        for inputs, labels in dataloader:
+            inputs = inputs.to(device)
+            labels = labels.to(device)
+
+            outputs = model(inputs)
+            _, preds = torch.max(nn.functional.softmax(outputs, dim=1), 1)
+
+            loss += criterion(outputs, labels).item()
+            correct += torch.sum(preds == labels).item()
+            total += labels.size(0)
+
+            pred_cls = preds.cpu().numpy()
+            real_cls = labels.cpu().numpy()
+            for pred_cls_i, real_cls_i in zip(pred_cls, real_cls):
+                confusion_matrix[int(pred_cls_i), int(real_cls_i)] += 1
+
+    loss = loss / total
+    acc = correct / total
+
+    return acc, loss, confusion_matrix
+
+
+
+# ----------------------------------------
+# Calculate metrics
+# ----------------------------------------
+
+def calculate_metrics(confusion_matrix):
+    """
+
+    """
+
+    num_classes = len(confusion_matrix)
+
+    Recall_list = []
+    Precision_list = []
+    F1_list = []
+
+    for i in range(num_classes):
+        TP_cls_i = confusion_matrix[i,i]
+        FP_cls_i = sum(confusion_matrix[i,:]) - TP_cls_i
+        FN_cls_i = sum(confusion_matrix[:,i]) - TP_cls_i
+
+        Recall_i = TP_cls_i/(TP_cls_i + FN_cls_i)
+        Precision_i = TP_cls_i/(TP_cls_i + FP_cls_i)
+        F1_i = 2*(Precision_i * Recall_i)/(Precision_i + Recall_i)
+
+        if np.isnan(Recall_i):
+            Recall_i = 0
+        if np.isnan(Precision_i):
+            Precision_i = 0
+        if np.isnan(F1_i):
+            F1_i = 0
+
+        Recall_list.append(Recall_i)
+        Precision_list.append(Precision_i)
+        F1_list.append(F1_i)
+
+    average_Recall = np.array(Recall_list).mean()
+    average_Precision = np.array(Precision_list).mean()
+    average_F1 = np.array(F1_list).mean()
+
+    return average_Precision, average_Recall, average_F1
+
+
+
+# ----------------------------------------
+# Save metrics
+# ----------------------------------------
+
+def save_metrics(metrics: Dict[str, Scalar], header, filename: str):
+    """
+    Write results to a text file
+    """
+
+    keys, vals = list(metrics.keys()), np.array(list(metrics.values())).T
+    num_cols = len(metrics) + 1
+    num_rows = vals.shape[0]
+    header = (("%23s," * num_cols % tuple([header] + keys)).rstrip(","))
+
+    with open(filename, "w") as f:
+        f.write(header + "\n")
+        for index in range(num_rows):
+            f.write(("%23.5g," * num_cols % tuple([index+1] + list(vals[index]))).rstrip(",") + "\n")
+
+    return
+
+
+
+# ------------------------------
+# Get model
+# ------------------------------
+
+def get_model(model_config: str, num_classes: int):
+    """
+
+    """
+
+    if model_config == "EfficientNet":
+        model = efficientnet_v2_s(weights="IMAGENET1K_V1")
+        in_features = model.classifier[-1].in_features
+        model.classifier[-1] = torch.nn.Linear(in_features, num_classes)
+    elif model_config == "VGG":
+        model = vgg19(weights="IMAGENET1K_V1")
+        in_features = model.classifier[-1].in_features
+        model.classifier[-1] = torch.nn.Linear(in_features, num_classes)
+    elif model_config == "ResNet":
+        model = resnet50(weights="IMAGENET1K_V1")
+        model.fc = torch.nn.Linear(model.fc.in_features, num_classes)
+    elif model_config == "InceptionNet":
+        model = inception_v3(weights="IMAGENET1K_V1")
+        model.aux_logits = False
+        model.fc = torch.nn.Linear(model.fc.in_features, num_classes)
+    elif model_config == "DenseNet":
+        model = densenet121(weights="IMAGENET1K_V1")
+        model.classifier = torch.nn.Linear(model.classifier.in_features, num_classes)
+
+    return model
+
+
+
+# ------------------------------
+# Get strategy
+# ------------------------------
+
+def get_strategy(strategy_config: str):
+    """
+
+    """
+
+    if strategy_config == "FedAvg":
+        strategy = FedAvg(fraction_fit=1.0,
+                          fraction_evaluate=0.0,
+                          min_fit_clients=CONFIG["num_clients"],
+                          min_evaluate_clients=CONFIG["num_clients"],
+                          min_available_clients=CONFIG["num_clients"],
+                          on_fit_config_fn=fit_config,
+                          evaluate_fn=evaluate)
+    elif strategy_config == "PlainFedAvg":
+        strategy = PlainFedAvg(fraction_fit=1.0,
+                               fraction_evaluate=0.0,
+                               min_fit_clients=CONFIG["num_clients"],
+                               min_evaluate_clients=CONFIG["num_clients"],
+                               min_available_clients=CONFIG["num_clients"],
+                               on_fit_config_fn=fit_config,
+                               evaluate_fn=evaluate)
+
+    return strategy
+
+
+
+# ------------------------------
+# Get optimizer
+# ------------------------------
+
+def get_optimizer(model, optimizer_config: str):
+    """
+
+    """
+
+    if optimizer_config == "SGD":
+        optimizer = torch.optim.SGD(model.parameters(),
+                                    lr=CONFIG["lr"],
+                                    momentum=CONFIG["momentum"])
+    elif optimizer_config == "Adam":
+        optimizer = torch.optim.Adam(model.parameters(),
+                                     lr=CONFIG["lr"],
+                                     momentum=CONFIG["momentum"])
+    elif optimizer_config == "AdamW":
+        optimizer = torch.optim.AdamW(model.parameters(),
+                                     lr=CONFIG["lr"],
+                                     momentum=CONFIG["momentum"])
+
+    return optimizer
+
+
+
+# ------------------------------
+# Get criterion
+# ------------------------------
+
+def get_criterion(criterion_config: str):
+    """
+
+    """
+
+    if criterion_config == "CrossEntropyLoss":
+        criterion = nn.CrossEntropyLoss()
+
+    return criterion
+
+
+
+# ------------------------------
+# Create folder
+# ------------------------------
+
+def create_folder(dir: str):
+    """
+    Check if folder already exists
+    If not create new folder
+    """
+
+    if not os.path.exists(dir):
+        os.makedirs(dir)
+
+
+
+# ------------------------------
+# Save model as .pt
+# ------------------------------
+
+def save_model(model, save_dir):
+    """
+    Export model to TorchScript and save it
+    """
+
+    if not os.path.exists(save_dir):
+        model_scripted = torch.jit.script(model)
+        model_scripted.save(save_dir)
+
+
+
+# ------------------------------
+# Get parameters
+# ------------------------------
+
+def get_parameters(model) -> NDArrays:
+    """
+    Return model parameters as a list of NumPy ndarrays
+    """
+
+    return [val.cpu().numpy() for _, val in model.state_dict().items()]
+
+
+
+# ------------------------------
+# Set parameters
+# ------------------------------
+
+def set_parameters(model, parameters: NDArrays) -> None:
+    """
+    Set model parameters from a list of NumPy ndarrays
+    """
+
+    params_dict = zip(model.state_dict().keys(), parameters)
+    state_dict = OrderedDict({k: torch.tensor(v) for k, v in params_dict})
+    model.load_state_dict(state_dict, strict=True)
+
+    return
+
+
+
+# ------------------------------
+# Implement Flower client
+# ------------------------------
+
+class FlowerClient(fl.client.Client):
+    """
+    Flower client using PyTorch
+    """
+
+    def __init__(self, cid, model, train_dataloader, val_dataloader, device, root_dir, save_dir):
+        self.cid = cid
+        self.model = model
+        self.train_dataloader = train_dataloader
+        self.val_dataloader = val_dataloader
+        self.device = device
+        self.root_dir = root_dir
+        self.save_dir = save_dir
+
+
+    def get_parameters(self,
+                       ins: GetParametersIns,
+                       ) -> GetParametersRes:
+        """
+        Return model parameters as a list of NumPy ndarrays
+        """
+
+        # serialize ndarrays parameters into Parameters object
+        parameters = ndarrays_to_parameters(get_parameters(self.model))
+
+        # build and return response
+        return GetParametersRes(
+            status=Status(code=Code.OK, message="Success"),
+            parameters=parameters,
+        )
+
+
+    def fit(self,
+            ins: FitIns,
+            ) -> FitRes:
+        """
+        Set model parameters, train model, return updated model parameters
+        """
+
+        # create folder
+        dir = os.path.join(self.save_dir, f"server_round_{ins.config['server_round']}")
+        create_folder(dir)
+
+        # deserialize parameters to Numpy ndarrays
+        parameters_ndarrays = parameters_to_ndarrays(ins.parameters)
+
+        # update local model
+        set_parameters(self.model, parameters_ndarrays)
+
+        # specify optimizer
+        optimizer = get_optimizer(self.model, ins.config["optimizer"])
+
+        # specify loss function
+        criterion = get_criterion(ins.config["loss_fcn"])
+
+        # train local model
+        metrics_dict = train_model(self.model,
+                                   self.train_dataloader,
+                                   self.val_dataloader,
+                                   optimizer,
+                                   ins.config["epochs"],
+                                   criterion,
+                                   self.device,
+                                   ins.config["use_best_weights"],
+                                   ins.config["early_stopping"],
+                                   dir)
+
+        # get updated parameters and serialize ndarrays parameters into Parameters object
+        parameters_updated = ndarrays_to_parameters(get_parameters(self.model))
+
+        # write training and validation metrics to .txt file
+        save_metrics(metrics_dict, "epoch", os.path.join(dir, "results.txt"))
+
+        # build and return response
+        return FitRes(
+            status=Status(code=Code.OK, message="Success"),
+            parameters=parameters_updated,
+            num_examples=len(self.train_dataloader),
+            metrics={},
+        )
+
+
+    def evaluate(self,
+                 ins: EvaluateIns,
+                 ) -> EvaluateRes:
+        """
+        Set model parameters, evaluate aggregated model on local test dataset, return result
+        """
+
+        # build and return response
+        return EvaluateRes(
+            status=Status(code=Code.OK, message="Success"),
+            loss=0.0,
+            num_examples=0,
+            metrics={},
+        )
+
+
+
+# ------------------------------
+# Evaluation function
+# ------------------------------
+
+def evaluate(server_round: int,
+             parameters: NDArrays,
+             config: Dict[str, Scalar],
+             ) -> Optional[Tuple[float, Dict[str, Scalar]]]:
+    """
+    The evaluate function will be called by Flower after each server round
+    """
+
+    # create folder
+    save_dir = os.path.join("runs", CONFIG["output_folder"], "global_model")
+    create_folder(save_dir)
+
+    # load pretrained model
+    model = get_model(CONFIG["model"], CONFIG["num_classes"])
+
+    # load data
+    test_dataloader = load_test_data(
+        os.path.join("global_test_set"),
+        CONFIG["batch_size"],
+        CONFIG["img_size"],
+    )
+
+    # update model
+    set_parameters(model, parameters)
+
+    # save aggregated model
+    save_model(model, os.path.join(save_dir, f"best_server_round_{server_round}.pt"))
+
+    # specify loss function
+    criterion = get_criterion(CONFIG["loss_fcn"])
+
+    # test aggregated model on test dataset
+    test_acc, test_loss, confusion_matrix = test_model(
+        model,
+        test_dataloader,
+        criterion,
+        DEVICE,
+        CONFIG["num_classes"],
+    )
+
+    # calculate metrics
+    average_Precision, average_Recall, average_F1 = calculate_metrics(confusion_matrix)
+
+    return 0.0, {"test_loss": test_loss, "test_acc": test_acc, "precision": average_Precision, "recall": average_Recall, "f1": average_F1}
+
+
+
+# ------------------------------
+# Create Flower client
+# ------------------------------
+
+def client_fn(cid: str) -> FlowerClient:
+    """
+    Create a Flower client instance. Each client will
+    be trained and validated on his own unique data
+    """
+
+    # load pretrained model
+    model = get_model(CONFIG["model"], CONFIG["num_classes"])
+
+    # specify output folder
+    root_dir = os.path.join("runs", CONFIG["output_folder"])
+    save_dir = os.path.join(root_dir, f"client_{int(cid)+1}")
+
+    # create folder
+    create_folder(save_dir)
+
+    # load data
+    train_dataloader, val_dataloader = load_train_val_data(
+        os.path.join("client_train_val_set", f"Client{int(cid)+1}"),
+        CONFIG["batch_size"],
+        CONFIG["img_size"],
+    )
+
+    # save one batch of training data
+    imgs, _ = next(iter(train_dataloader))
+    train_batch0 = make_grid(imgs, nrow=4, scale_each=True)
+    save_image(train_batch0, os.path.join(save_dir, "train_batch0"), "png")
+
+    return FlowerClient(cid, model, train_dataloader, val_dataloader, DEVICE, root_dir, save_dir)
+
+
+
+# ------------------------------
+# Fit config function
+# ------------------------------
+
+def fit_config(server_round: int) -> Dict[str, Scalar]:
+    """
+    Return training configuration dict for each round
+    """
+
+    config = {
+        "server_round": server_round,
+        "epochs": CONFIG["epochs"],
+        "optimizer": CONFIG["optimizer"],
+        "momentum": CONFIG["momentum"],
+        "lr": CONFIG["lr"],
+        "lr_scheduler": CONFIG["lr_scheduler"],
+        "loss_fcn": CONFIG["loss_fcn"],
+        "use_best_weights": CONFIG["use_best_weights"],
+        "early_stopping": CONFIG["early_stopping"],
+    }
+
+    return config
+
+
+
+# ------------------------------
+# Extract metrics
+# ------------------------------
+
+def extract_metrics(metrics: Dict[str, Scalar]) -> Dict[str, Scalar]:
+    """
+
+    """
+
+    extracted_metrics = {
+        "test_loss": [],
+        "test_acc": [],
+        "precision": [],
+        "recall": [],
+        "f1": [],
+    }
+
+    for key, values in metrics.items():
+        for i, (_, data) in enumerate(values):
+            extracted_metrics[key].append(data)
+
+    return extracted_metrics
+
+
+
+# ------------------------------
+# Start simulation
+# ------------------------------
+
+if __name__=="__main__":
+    # set seeds
+    set_seeds(CONFIG["seed"])
+
+    # define parameters
+    DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
+
+    # specify output folder
+    save_dir = os.path.join("runs", CONFIG["output_folder"])
+
+    # check if folder already exists
+    if os.path.exists(save_dir):
+        print("Output folder already exists. Exiting the program.")
+        sys.exit()
+
+    # create output folder
+    create_folder(save_dir)
+
+    # move copy of config file to output folder
+    shutil.copy(config_file_name, os.path.join(save_dir, config_file_name))
+
+    # get strategy
+    strategy = get_strategy(CONFIG["strategy"])
+
+    # specify client resources
+    client_resources = {"num_cpus": 16}
+    if DEVICE.type == "cuda":
+        client_resources = {"num_cpus": 16, "num_gpus": 1.0}
+
+    # start simulation
+    history = fl.simulation.start_simulation(
+        client_fn=client_fn,
+        num_clients=CONFIG["num_clients"],
+        config=fl.server.ServerConfig(num_rounds=CONFIG["num_rounds"]),
+        strategy=strategy,
+        client_resources=client_resources,
+    )
+
+    # write training and validation metrics to .txt file
+    extracted_metrics = extract_metrics(history.metrics_centralized)
+    save_metrics(extracted_metrics, "server_round", os.path.join(save_dir, "global_model", "results_aggregated_model.txt"))
diff --git a/main_esaim.py b/main_esaim.py
new file mode 100644
index 0000000000000000000000000000000000000000..b91484c4140f97256532a4b735edcc19a9fc2653
--- /dev/null
+++ b/main_esaim.py
@@ -0,0 +1,850 @@
+# ------------------------------
+# Import libraries
+# ------------------------------
+
+import zipfile
+import yaml
+from collections import OrderedDict
+from typing import Dict, List, Optional, Tuple, Union
+import os
+import sys
+import glob
+import shutil
+from copy import deepcopy
+import numpy as np
+import random
+import torch
+import torch.nn as nn
+from torch.optim import lr_scheduler
+from torch.utils.data import Dataset
+import torchvision
+from torchvision.models import efficientnet_v2_s, vgg19, resnet50, inception_v3, densenet121
+from torchvision.utils import make_grid, save_image
+import cv2
+# import albumentations as A
+import flwr as fl
+from flwr.common import (
+    Code,
+    EvaluateIns,
+    EvaluateRes,
+    FitIns,
+    FitRes,
+    GetParametersIns,
+    GetParametersRes,
+    Status,
+    NDArrays,
+    Parameters,
+    Scalar,
+    ndarrays_to_parameters,
+    parameters_to_ndarrays,
+)
+from flwr.server.strategy import FedAvg
+from strategy import PlainFedAvg
+
+
+
+# ------------------------------
+# Load config file
+# ------------------------------
+
+config_file_name = "config.yaml"
+with open(config_file_name) as file:
+    CONFIG = yaml.safe_load(file)
+
+
+
+# ------------------------------
+# Extract .zip folder
+# ------------------------------
+
+def extract_zip(zip_file_name: str, save_dir: str):
+    """
+    Extract .zip folder, if not already done
+    """
+
+    parts = zip_file_name.split(".")
+    file_name = parts[0]
+
+    if not os.path.isdir(file_name):
+        with zipfile.ZipFile(zip_file_name, "r") as zip_ref:
+            zip_ref.extractall(save_dir)
+        print(f"Folder '{zip_file_name}' was successfully extracted")
+    else:
+        print(f"Folder '{file_name}' already exists")
+
+
+
+# ------------------------------
+# Set seeds
+# ------------------------------
+
+def set_seeds(seed):
+    """
+
+    """
+
+    random.seed(seed)
+    os.environ['PYTHONHASHSEED'] = str(seed)
+    np.random.seed(seed)
+    torch.manual_seed(seed)
+    torch.cuda.manual_seed(seed)
+    torch.cuda.manual_seed_all(seed)
+    torch.backends.cudnn.deterministic = True
+    torch.backends.cudnn.benchmark = False
+
+
+
+# ----------------------------------------
+#
+# ----------------------------------------
+
+class_map_str_to_idx = {
+    "No_windshield": 0,
+    "With_windshield": 1
+}
+
+
+# ----------------------------------------
+# Load data
+# ----------------------------------------
+
+class Dataloader(Dataset):
+    def __init__(self, root_dir, loader_mode, imgsz):
+        self.root_dir = root_dir
+        self.loader_mode = loader_mode
+        if self.loader_mode == "test":
+            self.imgs = [elem for elem in glob.glob(os.path.join(root_dir, "*", "*"))]
+        else:
+            self.imgs = [elem for elem in glob.glob(os.path.join(root_dir, self.loader_mode, "*", "*"))]
+
+        self.imgs_and_lbls = []
+        for path in self.imgs:
+            #print(class_map_str_to_idx[path.split(os.sep)[-2]])
+            self.imgs_and_lbls.append([cv2.imread(path, cv2.IMREAD_COLOR), class_map_str_to_idx[path.split(os.sep)[-2]]])
+
+        self.transform = torchvision.transforms.Compose([
+            torchvision.transforms.ToTensor(),
+            torchvision.transforms.Resize((imgsz, imgsz)),
+        ])
+
+        # if self.loader_mode == "train":
+        #     self.augment = A.Compose([
+        #         A.VerticalFlip(p=0.5),
+        #         A.Rotate(limit=15, border_mode=cv2.BORDER_CONSTANT, value=(0,0,0), p=0.75)
+        #     ])
+
+    def __len__(self):
+        return len(self.imgs)
+
+    def __getitem__(self, idx):
+        img, lbl = self.imgs_and_lbls[idx]
+
+        # add augmentation during training
+        # if self.loader_mode == "train":
+        #     augmented = self.augment(img)
+        #     img = augmented["image"]
+
+        # transform numpy array into Pytorch tensor
+        img_torch = self.transform(img)
+
+        return img_torch, lbl
+
+
+
+def load_train_val_data(root_dir, batch_size, imgsz):
+    """
+
+    """
+
+    train_dataset = Dataloader(root_dir=root_dir, loader_mode="train", imgsz=imgsz)
+    val_dataset = Dataloader(root_dir=root_dir, loader_mode="val", imgsz=imgsz)
+
+    train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, pin_memory=True, shuffle=True)
+    val_dataloader = torch.utils.data.DataLoader(val_dataset, batch_size=batch_size, pin_memory=True, shuffle=False)
+
+    return train_dataloader, val_dataloader
+
+
+
+def load_test_data(root_dir, batch_size, imgsz):
+    """
+
+    """
+
+    test_dataset = Dataloader(root_dir=root_dir, loader_mode="test", imgsz=imgsz)
+
+    test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, pin_memory=True, shuffle=False)
+
+    return test_dataloader
+
+
+# ----------------------------------------
+# Train model
+# ----------------------------------------
+
+def train_model(model,
+                train_dataloader,
+                val_dataloader,
+                optimizer,
+                num_epochs,
+                criterion,
+                device,
+                use_best_weights,
+                early_stopping,
+                save_dir):
+    """
+
+    """
+
+    # if CONFIG["lr_scheduler"]:
+    #     scheduler = lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.75)
+
+    best_loss = np.inf
+
+    model.to(device)
+    model.train()
+
+    hist_train_loss, hist_train_acc, hist_val_loss, hist_val_acc = [], [], [], []
+
+    epochs_without_improvement = 0
+
+    for epoch in range(num_epochs):
+        # training
+        model.train()
+
+        correct = 0
+        total = 0
+        epoch_train_loss = 0.0
+
+        for inputs, labels in train_dataloader:
+            inputs = inputs.to(device)
+            labels = labels.to(device)
+
+            optimizer.zero_grad()
+
+            outputs = model(inputs)
+            _, preds = torch.max(nn.functional.softmax(outputs, dim=1), 1)
+            loss = criterion(outputs, labels)
+
+            loss.backward()
+            optimizer.step()
+
+            epoch_train_loss += loss.item()
+            correct += torch.sum(preds == labels).item()
+            total += labels.size(0)
+
+        epoch_train_loss = epoch_train_loss / total
+        epoch_train_acc = correct / total
+        hist_train_loss.append(epoch_train_loss)
+        hist_train_acc.append(epoch_train_acc)
+
+        # scheduler.step()
+
+        # validation
+        model.eval()
+
+        correct = 0
+        total = 0
+        epoch_val_loss = 0.0
+
+        with torch.no_grad():
+            for inputs, labels in val_dataloader:
+                inputs = inputs.to(device)
+                labels = labels.to(device)
+
+                outputs = model(inputs)
+                _, preds = torch.max(nn.functional.softmax(outputs, dim=1), 1)
+
+                epoch_val_loss += criterion(outputs, labels).item()
+                correct += torch.sum(preds == labels).item()
+                total += labels.size(0)
+
+        epoch_val_loss = epoch_val_loss / total
+        epoch_val_acc = correct / total
+        hist_val_loss.append(epoch_val_loss)
+        hist_val_acc.append(epoch_val_acc)
+
+        # early stopping
+        if epoch_val_loss < best_loss:
+            best_loss = epoch_val_loss
+            epochs_without_improvement = 0
+
+            # save best model as .pt
+            save_model(model, os.path.join(save_dir, "best.pt"))
+            if use_best_weights:
+                best_model_state = deepcopy(model.state_dict())
+        else:
+            epochs_without_improvement += 1
+            if epochs_without_improvement >= early_stopping:
+                print(f"Early stopping after {epoch+1} epochs without improvement")
+                break
+
+    history = {"train_acc": hist_train_acc, "train_loss": hist_train_loss, "val_acc": hist_val_acc, "val_loss": hist_val_loss}
+
+    # save last model as .pt
+    save_model(model, os.path.join(save_dir, "last.pt"))
+
+    if use_best_weights:
+        model.load_state_dict(best_model_state)
+
+    return history
+
+
+# ----------------------------------------
+# Test model
+# ----------------------------------------
+
+def test_model(model, dataloader, criterion, device, num_classes):
+    """
+    Test model and calculate confusion matrix
+    """
+
+    model.to(device)
+    model.eval()
+
+    confusion_matrix = np.zeros((num_classes, num_classes))
+
+    correct = 0
+    total = 0
+    loss = 0.0
+
+    with torch.no_grad():
+        for inputs, labels in dataloader:
+            inputs = inputs.to(device)
+            labels = labels.to(device)
+
+            outputs = model(inputs)
+            _, preds = torch.max(nn.functional.softmax(outputs, dim=1), 1)
+
+            loss += criterion(outputs, labels).item()
+            correct += torch.sum(preds == labels).item()
+            total += labels.size(0)
+
+            pred_cls = preds.cpu().numpy()
+            real_cls = labels.cpu().numpy()
+            for pred_cls_i, real_cls_i in zip(pred_cls, real_cls):
+                confusion_matrix[int(pred_cls_i), int(real_cls_i)] += 1
+
+    loss = loss / total
+    acc = correct / total
+
+    return acc, loss, confusion_matrix
+
+
+
+# ----------------------------------------
+# Calculate metrics
+# ----------------------------------------
+
+def calculate_metrics(confusion_matrix):
+    """
+
+    """
+
+    num_classes = len(confusion_matrix)
+
+    Recall_list = []
+    Precision_list = []
+    F1_list = []
+
+    for i in range(num_classes):
+        TP_cls_i = confusion_matrix[i,i]
+        FP_cls_i = sum(confusion_matrix[i,:]) - TP_cls_i
+        FN_cls_i = sum(confusion_matrix[:,i]) - TP_cls_i
+
+        Recall_i = TP_cls_i/(TP_cls_i + FN_cls_i)
+        Precision_i = TP_cls_i/(TP_cls_i + FP_cls_i)
+        F1_i = 2*(Precision_i * Recall_i)/(Precision_i + Recall_i)
+
+        if np.isnan(Recall_i):
+            Recall_i = 0
+        if np.isnan(Precision_i):
+            Precision_i = 0
+        if np.isnan(F1_i):
+            F1_i = 0
+
+        Recall_list.append(Recall_i)
+        Precision_list.append(Precision_i)
+        F1_list.append(F1_i)
+
+    average_Recall = np.array(Recall_list).mean()
+    average_Precision = np.array(Precision_list).mean()
+    average_F1 = np.array(F1_list).mean()
+
+    return average_Precision, average_Recall, average_F1
+
+
+
+# ----------------------------------------
+# Save metrics
+# ----------------------------------------
+
+def save_metrics(metrics: Dict[str, Scalar], header, filename: str):
+    """
+    Write results to a text file
+    """
+
+    keys, vals = list(metrics.keys()), np.array(list(metrics.values())).T
+    num_cols = len(metrics) + 1
+    num_rows = vals.shape[0]
+    header = (("%23s," * num_cols % tuple([header] + keys)).rstrip(","))
+
+    with open(filename, "w") as f:
+        f.write(header + "\n")
+        for index in range(num_rows):
+            f.write(("%23.5g," * num_cols % tuple([index+1] + list(vals[index]))).rstrip(",") + "\n")
+
+    return
+
+
+
+# ------------------------------
+# Get model
+# ------------------------------
+
+def get_model(model_config: str, num_classes: int):
+    """
+
+    """
+
+    if model_config == "EfficientNet":
+        model = efficientnet_v2_s(weights="IMAGENET1K_V1")
+        in_features = model.classifier[-1].in_features
+        model.classifier[-1] = torch.nn.Linear(in_features, num_classes)
+    elif model_config == "VGG":
+        model = vgg19(weights="IMAGENET1K_V1")
+        in_features = model.classifier[-1].in_features
+        model.classifier[-1] = torch.nn.Linear(in_features, num_classes)
+    elif model_config == "ResNet":
+        model = resnet50(weights="IMAGENET1K_V1")
+        model.fc = torch.nn.Linear(model.fc.in_features, num_classes)
+    elif model_config == "InceptionNet":
+        model = inception_v3(weights="IMAGENET1K_V1")
+        model.aux_logits = False
+        model.fc = torch.nn.Linear(model.fc.in_features, num_classes)
+    elif model_config == "DenseNet":
+        model = densenet121(weights="IMAGENET1K_V1")
+        model.classifier = torch.nn.Linear(model.classifier.in_features, num_classes)
+
+    return model
+
+
+
+# ------------------------------
+# Get strategy
+# ------------------------------
+
+def get_strategy(strategy_config: str):
+    """
+
+    """
+
+    if strategy_config == "FedAvg":
+        strategy = FedAvg(fraction_fit=1.0,
+                          fraction_evaluate=0.0,
+                          min_fit_clients=CONFIG["num_clients"],
+                          min_evaluate_clients=CONFIG["num_clients"],
+                          min_available_clients=CONFIG["num_clients"],
+                          on_fit_config_fn=fit_config,
+                          evaluate_fn=evaluate)
+    elif strategy_config == "PlainFedAvg":
+        strategy = PlainFedAvg(fraction_fit=1.0,
+                               fraction_evaluate=0.0,
+                               min_fit_clients=CONFIG["num_clients"],
+                               min_evaluate_clients=CONFIG["num_clients"],
+                               min_available_clients=CONFIG["num_clients"],
+                               on_fit_config_fn=fit_config,
+                               evaluate_fn=evaluate)
+
+    return strategy
+
+
+
+# ------------------------------
+# Get optimizer
+# ------------------------------
+
+def get_optimizer(model, optimizer_config: str):
+    """
+
+    """
+
+    if optimizer_config == "SGD":
+        optimizer = torch.optim.SGD(model.parameters(),
+                                    lr=CONFIG["lr"],
+                                    momentum=CONFIG["momentum"])
+    elif optimizer_config == "Adam":
+        optimizer = torch.optim.Adam(model.parameters(),
+                                     lr=CONFIG["lr"],
+                                     momentum=CONFIG["momentum"])
+    elif optimizer_config == "AdamW":
+        optimizer = torch.optim.AdamW(model.parameters(),
+                                     lr=CONFIG["lr"],
+                                     momentum=CONFIG["momentum"])
+
+    return optimizer
+
+
+
+# ------------------------------
+# Get criterion
+# ------------------------------
+
+def get_criterion(criterion_config: str):
+    """
+
+    """
+
+    if criterion_config == "CrossEntropyLoss":
+        criterion = nn.CrossEntropyLoss()
+
+    return criterion
+
+
+
+# ------------------------------
+# Create folder
+# ------------------------------
+
+def create_folder(dir: str):
+    """
+    Check if folder already exists
+    If not create new folder
+    """
+
+    if not os.path.exists(dir):
+        os.makedirs(dir)
+
+
+
+# ------------------------------
+# Save model as .pt
+# ------------------------------
+
+def save_model(model, save_dir):
+    """
+    Export model to TorchScript and save it
+    """
+
+    if not os.path.exists(save_dir):
+        model_scripted = torch.jit.script(model)
+        model_scripted.save(save_dir)
+
+
+
+# ------------------------------
+# Get parameters
+# ------------------------------
+
+def get_parameters(model) -> NDArrays:
+    """
+    Return model parameters as a list of NumPy ndarrays
+    """
+
+    return [val.cpu().numpy() for _, val in model.state_dict().items()]
+
+
+
+# ------------------------------
+# Set parameters
+# ------------------------------
+
+def set_parameters(model, parameters: NDArrays) -> None:
+    """
+    Set model parameters from a list of NumPy ndarrays
+    """
+
+    params_dict = zip(model.state_dict().keys(), parameters)
+    state_dict = OrderedDict({k: torch.tensor(v) for k, v in params_dict})
+    model.load_state_dict(state_dict, strict=True)
+
+    return
+
+
+
+# ------------------------------
+# Implement Flower client
+# ------------------------------
+
+class FlowerClient(fl.client.Client):
+    """
+    Flower client using PyTorch
+    """
+
+    def __init__(self, cid, model, train_dataloader, val_dataloader, device, root_dir, save_dir):
+        self.cid = cid
+        self.model = model
+        self.train_dataloader = train_dataloader
+        self.val_dataloader = val_dataloader
+        self.device = device
+        self.root_dir = root_dir
+        self.save_dir = save_dir
+
+
+    def get_parameters(self,
+                       ins: GetParametersIns,
+                       ) -> GetParametersRes:
+        """
+        Return model parameters as a list of NumPy ndarrays
+        """
+
+        # serialize ndarrays parameters into Parameters object
+        parameters = ndarrays_to_parameters(get_parameters(self.model))
+
+        # build and return response
+        return GetParametersRes(
+            status=Status(code=Code.OK, message="Success"),
+            parameters=parameters,
+        )
+
+
+    def fit(self,
+            ins: FitIns,
+            ) -> FitRes:
+        """
+        Set model parameters, train model, return updated model parameters
+        """
+
+        # create folder
+        dir = os.path.join(self.save_dir, f"server_round_{ins.config['server_round']}")
+        create_folder(dir)
+
+        # deserialize parameters to Numpy ndarrays
+        parameters_ndarrays = parameters_to_ndarrays(ins.parameters)
+
+        # update local model
+        set_parameters(self.model, parameters_ndarrays)
+
+        # specify optimizer
+        optimizer = get_optimizer(self.model, ins.config["optimizer"])
+
+        # specify loss function
+        criterion = get_criterion(ins.config["loss_fcn"])
+
+        # train local model
+        metrics_dict = train_model(self.model,
+                                   self.train_dataloader,
+                                   self.val_dataloader,
+                                   optimizer,
+                                   ins.config["epochs"],
+                                   criterion,
+                                   self.device,
+                                   ins.config["use_best_weights"],
+                                   ins.config["early_stopping"],
+                                   dir)
+
+        # get updated parameters and serialize ndarrays parameters into Parameters object
+        parameters_updated = ndarrays_to_parameters(get_parameters(self.model))
+
+        # write training and validation metrics to .txt file
+        save_metrics(metrics_dict, "epoch", os.path.join(dir, "results.txt"))
+
+        # build and return response
+        return FitRes(
+            status=Status(code=Code.OK, message="Success"),
+            parameters=parameters_updated,
+            num_examples=len(self.train_dataloader),
+            metrics={},
+        )
+
+
+    def evaluate(self,
+                 ins: EvaluateIns,
+                 ) -> EvaluateRes:
+        """
+        Set model parameters, evaluate aggregated model on local test dataset, return result
+        """
+
+        # build and return response
+        return EvaluateRes(
+            status=Status(code=Code.OK, message="Success"),
+            loss=0.0,
+            num_examples=0,
+            metrics={},
+        )
+
+
+
+# ------------------------------
+# Evaluation function
+# ------------------------------
+
+def evaluate(server_round: int,
+             parameters: NDArrays,
+             config: Dict[str, Scalar],
+             ) -> Optional[Tuple[float, Dict[str, Scalar]]]:
+    """
+    The evaluate function will be called by Flower after each server round
+    """
+
+    # create folder
+    save_dir = os.path.join("runs", CONFIG["output_folder"], "global_model")
+    create_folder(save_dir)
+
+    # load pretrained model
+    model = get_model(CONFIG["model"], CONFIG["num_classes"])
+
+    # load data
+    test_dataloader = load_test_data(
+        os.path.join("dataset/ESAIM/global_test_set"),
+        CONFIG["batch_size"],
+        CONFIG["img_size"],
+    )
+
+    # update model
+    set_parameters(model, parameters)
+
+    # save aggregated model
+    save_model(model, os.path.join(save_dir, f"best_server_round_{server_round}.pt"))
+
+    # specify loss function
+    criterion = get_criterion(CONFIG["loss_fcn"])
+
+    # test aggregated model on test dataset
+    test_acc, test_loss, confusion_matrix = test_model(
+        model,
+        test_dataloader,
+        criterion,
+        DEVICE,
+        CONFIG["num_classes"],
+    )
+
+    # calculate metrics
+    average_Precision, average_Recall, average_F1 = calculate_metrics(confusion_matrix)
+
+    return 0.0, {"test_loss": test_loss, "test_acc": test_acc, "precision": average_Precision, "recall": average_Recall, "f1": average_F1}
+
+
+
+
+# ------------------------------
+# Create Flower client
+# ------------------------------
+
+def client_fn(cid: str) -> FlowerClient:
+    """
+    Create a Flower client instance. Each client will
+    be trained and validated on his own unique data
+    """
+
+    # load pretrained model
+    model = get_model(CONFIG["model"], CONFIG["num_classes"])
+
+    # specify output folder
+    root_dir = os.path.join("runs", CONFIG["output_folder"])
+    save_dir = os.path.join(root_dir, f"client_{int(cid)+1}")
+
+    # create folder
+    create_folder(save_dir)
+
+    # load data
+    train_dataloader, val_dataloader = load_train_val_data(
+        os.path.join("dataset/ESAIM", f"Client{int(cid)+1}"),
+        CONFIG["batch_size"],
+        CONFIG["img_size"],
+    )
+
+    # save one batch of training data
+    imgs, _ = next(iter(train_dataloader))
+    train_batch0 = make_grid(imgs, nrow=4, scale_each=True)
+    save_image(train_batch0, os.path.join(save_dir, "train_batch0"), "png")
+
+    return FlowerClient(cid, model, train_dataloader, val_dataloader, DEVICE, root_dir, save_dir)
+
+
+
+# ------------------------------
+# Fit config function
+# ------------------------------
+
+def fit_config(server_round: int) -> Dict[str, Scalar]:
+    """
+    Return training configuration dict for each round
+    """
+
+    config = {
+        "server_round": server_round,
+        "epochs": CONFIG["epochs"],
+        "optimizer": CONFIG["optimizer"],
+        "momentum": CONFIG["momentum"],
+        "lr": CONFIG["lr"],
+        "lr_scheduler": CONFIG["lr_scheduler"],
+        "loss_fcn": CONFIG["loss_fcn"],
+        "use_best_weights": CONFIG["use_best_weights"],
+        "early_stopping": CONFIG["early_stopping"],
+    }
+
+    return config
+
+
+
+# ------------------------------
+# Extract metrics
+# ------------------------------
+
+def extract_metrics(metrics: Dict[str, Scalar]) -> Dict[str, Scalar]:
+    """
+
+    """
+
+    extracted_metrics = {
+        "test_loss": [],
+        "test_acc": [],
+        "precision": [],
+        "recall": [],
+        "f1": [],
+    }
+
+    for key, values in metrics.items():
+        for i, (_, data) in enumerate(values):
+            extracted_metrics[key].append(data)
+
+    return extracted_metrics
+
+
+
+# ------------------------------
+# Start simulation
+# ------------------------------
+
+if __name__=="__main__":
+    # set seeds
+    set_seeds(CONFIG["seed"])
+
+    # define parameters
+    DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
+
+    # specify output folder
+    save_dir = os.path.join("runs", CONFIG["output_folder"])
+
+    # check if folder already exists
+    if os.path.exists(save_dir):
+        print("Output folder already exists. Exiting the program.")
+        sys.exit()
+
+    # create output folder
+    create_folder(save_dir)
+
+    # move copy of config file to output folder
+    shutil.copy(config_file_name, os.path.join(save_dir, config_file_name))
+
+    # get strategy
+    strategy = get_strategy(CONFIG["strategy"])
+
+    # specify client resources
+    client_resources = {"num_cpus": 16}
+    if DEVICE.type == "cuda":
+        client_resources = {"num_cpus": 16, "num_gpus": 1.0}
+
+    # start simulation
+    history = fl.simulation.start_simulation(
+        client_fn=client_fn,
+        num_clients=CONFIG["num_clients"],
+        config=fl.server.ServerConfig(num_rounds=CONFIG["num_rounds"]),
+        strategy=strategy,
+        client_resources=client_resources,
+    )
+
+    # write training and validation metrics to .txt file
+    extracted_metrics = extract_metrics(history.metrics_centralized)
+    save_metrics(extracted_metrics, "server_round", os.path.join(save_dir, "global_model", "results_aggregated_model.txt"))
diff --git a/main_flta.py b/main_flta.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcb05a3c63e77fd66c4fb4daf89c6973dd22a2ce
--- /dev/null
+++ b/main_flta.py
@@ -0,0 +1,854 @@
+# ------------------------------
+# Import libraries
+# ------------------------------
+
+import zipfile
+import yaml
+from collections import OrderedDict
+from typing import Dict, List, Optional, Tuple, Union
+import os
+import sys
+import glob
+import shutil
+from copy import deepcopy
+import numpy as np
+import random
+import torch
+import torch.nn as nn
+from torch.optim import lr_scheduler
+from torch.utils.data import Dataset
+import torchvision
+from torchvision.models import efficientnet_v2_s, vgg19, resnet50, inception_v3, densenet121
+from torchvision.utils import make_grid, save_image
+import cv2
+# import albumentations as A
+import flwr as fl
+from flwr.common import (
+    Code,
+    EvaluateIns,
+    EvaluateRes,
+    FitIns,
+    FitRes,
+    GetParametersIns,
+    GetParametersRes,
+    Status,
+    NDArrays,
+    Parameters,
+    Scalar,
+    ndarrays_to_parameters,
+    parameters_to_ndarrays,
+)
+from flwr.server.strategy import FedAvg
+from strategy import PlainFedAvg
+
+
+
+# ------------------------------
+# Load config file
+# ------------------------------
+
+config_file_name = "config.yaml"
+with open(config_file_name) as file:
+    CONFIG = yaml.safe_load(file)
+
+
+
+# ------------------------------
+# Extract .zip folder
+# ------------------------------
+
+def extract_zip(zip_file_name: str, save_dir: str):
+    """
+    Extract .zip folder, if not already done
+    """
+
+    parts = zip_file_name.split(".")
+    file_name = parts[0]
+
+    if not os.path.isdir(file_name):
+        with zipfile.ZipFile(zip_file_name, "r") as zip_ref:
+            zip_ref.extractall(save_dir)
+        print(f"Folder '{zip_file_name}' was successfully extracted")
+    else:
+        print(f"Folder '{file_name}' already exists")
+
+
+
+# ------------------------------
+# Set seeds
+# ------------------------------
+
+def set_seeds(seed):
+    """
+
+    """
+
+    random.seed(seed)
+    os.environ['PYTHONHASHSEED'] = str(seed)
+    np.random.seed(seed)
+    torch.manual_seed(seed)
+    torch.cuda.manual_seed(seed)
+    torch.cuda.manual_seed_all(seed)
+    torch.backends.cudnn.deterministic = True
+    torch.backends.cudnn.benchmark = False
+
+
+
+# ----------------------------------------
+#
+# ----------------------------------------
+
+class_map_str_to_idx = {
+    "No_windshield": 0,
+    "Windshield_TypeA": 1,
+    "Windshield_TypeB": 2,
+    "Windshield_TypeC": 3,
+    "Windshield_TypeD": 4
+}
+
+
+
+# ----------------------------------------
+# Load data
+# ----------------------------------------
+
+class Dataloader(Dataset):
+    def __init__(self, root_dir, loader_mode, imgsz):
+        self.root_dir = root_dir
+        self.loader_mode = loader_mode
+        if self.loader_mode == "test":
+            self.imgs = [elem for elem in glob.glob(os.path.join(root_dir, "*", "*"))]
+        else:
+            self.imgs = [elem for elem in glob.glob(os.path.join(root_dir, self.loader_mode, "*", "*"))]
+
+        self.imgs_and_lbls = []
+        for path in self.imgs:
+            self.imgs_and_lbls.append([cv2.imread(path, cv2.IMREAD_COLOR), class_map_str_to_idx[path.split(os.sep)[-2]]])
+
+        self.transform = torchvision.transforms.Compose([
+            torchvision.transforms.ToTensor(),
+            torchvision.transforms.Resize((imgsz, imgsz)),
+        ])
+
+        # if self.loader_mode == "train":
+        #     self.augment = A.Compose([
+        #         A.VerticalFlip(p=0.5),
+        #         A.Rotate(limit=15, border_mode=cv2.BORDER_CONSTANT, value=(0,0,0), p=0.75)
+        #     ])
+
+    def __len__(self):
+        return len(self.imgs)
+
+    def __getitem__(self, idx):
+        img, lbl = self.imgs_and_lbls[idx]
+
+        # add augmentation during training
+        # if self.loader_mode == "train":
+        #     augmented = self.augment(img)
+        #     img = augmented["image"]
+
+        # transform numpy array into Pytorch tensor
+        img_torch = self.transform(img)
+
+        return img_torch, lbl
+
+
+
+def load_train_val_data(root_dir, batch_size, imgsz):
+    """
+
+    """
+
+    train_dataset = Dataloader(root_dir=root_dir, loader_mode="train", imgsz=imgsz)
+    val_dataset = Dataloader(root_dir=root_dir, loader_mode="val", imgsz=imgsz)
+
+    train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, pin_memory=True, shuffle=True)
+    val_dataloader = torch.utils.data.DataLoader(val_dataset, batch_size=batch_size, pin_memory=True, shuffle=False)
+
+    return train_dataloader, val_dataloader
+
+
+
+def load_test_data(root_dir, batch_size, imgsz):
+    """
+
+    """
+
+    test_dataset = Dataloader(root_dir=root_dir, loader_mode="test", imgsz=imgsz)
+
+    test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, pin_memory=True, shuffle=False)
+
+    return test_dataloader
+
+
+
+# ----------------------------------------
+# Train model
+# ----------------------------------------
+
+def train_model(model,
+                train_dataloader,
+                val_dataloader,
+                optimizer,
+                num_epochs,
+                criterion,
+                device,
+                use_best_weights,
+                early_stopping,
+                save_dir=None):
+    """
+
+    """
+
+    # if CONFIG["lr_scheduler"]:
+    #     scheduler = lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.75)
+
+    best_loss = np.inf
+
+    model.to(device)
+    model.train()
+
+    hist_train_loss, hist_train_acc, hist_val_loss, hist_val_acc = [], [], [], []
+
+    epochs_without_improvement = 0
+
+    for epoch in range(num_epochs):
+        # training
+        model.train()
+
+        correct = 0
+        total = 0
+        epoch_train_loss = 0.0
+
+        for inputs, labels in train_dataloader:
+            inputs = inputs.to(device)
+            labels = labels.to(device)
+
+            optimizer.zero_grad()
+
+            outputs = model(inputs)
+            _, preds = torch.max(nn.functional.softmax(outputs, dim=1), 1)
+            loss = criterion(outputs, labels)
+
+            loss.backward()
+            optimizer.step()
+
+            epoch_train_loss += loss.item()
+            correct += torch.sum(preds == labels).item()
+            total += labels.size(0)
+
+        epoch_train_loss = epoch_train_loss / total
+        epoch_train_acc = correct / total
+        hist_train_loss.append(epoch_train_loss)
+        hist_train_acc.append(epoch_train_acc)
+
+        # scheduler.step()
+
+        # validation
+        model.eval()
+
+        correct = 0
+        total = 0
+        epoch_val_loss = 0.0
+
+        with torch.no_grad():
+            for inputs, labels in val_dataloader:
+                inputs = inputs.to(device)
+                labels = labels.to(device)
+
+                outputs = model(inputs)
+                _, preds = torch.max(nn.functional.softmax(outputs, dim=1), 1)
+
+                epoch_val_loss += criterion(outputs, labels).item()
+                correct += torch.sum(preds == labels).item()
+                total += labels.size(0)
+
+        epoch_val_loss = epoch_val_loss / total
+        epoch_val_acc = correct / total
+        hist_val_loss.append(epoch_val_loss)
+        hist_val_acc.append(epoch_val_acc)
+
+        # early stopping
+        if epoch_val_loss < best_loss:
+            best_loss = epoch_val_loss
+            epochs_without_improvement = 0
+
+            # save best model as .pt
+            save_model(model, os.path.join(save_dir, "best.pt"))
+            if use_best_weights:
+                best_model_state = deepcopy(model.state_dict())
+        else:
+            epochs_without_improvement += 1
+            if epochs_without_improvement >= early_stopping:
+                print(f"Early stopping after {epoch+1} epochs without improvement")
+                break
+
+    history = {"train_acc": hist_train_acc, "train_loss": hist_train_loss, "val_acc": hist_val_acc, "val_loss": hist_val_loss}
+
+    # save last model as .pt
+    save_model(model, os.path.join(save_dir, "last.pt"))
+
+    if use_best_weights:
+        model.load_state_dict(best_model_state)
+
+    return history
+
+
+
+# ----------------------------------------
+# Test model
+# ----------------------------------------
+
+def test_model(model, dataloader, criterion, device, num_classes):
+    """
+    Test model and calculate confusion matrix
+    """
+
+    model.to(device)
+    model.eval()
+
+    confusion_matrix = np.zeros((num_classes, num_classes))
+
+    correct = 0
+    total = 0
+    loss = 0.0
+
+    with torch.no_grad():
+        for inputs, labels in dataloader:
+            inputs = inputs.to(device)
+            labels = labels.to(device)
+
+            outputs = model(inputs)
+            _, preds = torch.max(nn.functional.softmax(outputs, dim=1), 1)
+
+            loss += criterion(outputs, labels).item()
+            correct += torch.sum(preds == labels).item()
+            total += labels.size(0)
+
+            pred_cls = preds.cpu().numpy()
+            real_cls = labels.cpu().numpy()
+            for pred_cls_i, real_cls_i in zip(pred_cls, real_cls):
+                confusion_matrix[int(pred_cls_i), int(real_cls_i)] += 1
+
+    loss = loss / total
+    acc = correct / total
+
+    return acc, loss, confusion_matrix
+
+
+
+# ----------------------------------------
+# Calculate metrics
+# ----------------------------------------
+
+def calculate_metrics(confusion_matrix):
+    """
+
+    """
+
+    num_classes = len(confusion_matrix)
+
+    Recall_list = []
+    Precision_list = []
+    F1_list = []
+
+    for i in range(num_classes):
+        TP_cls_i = confusion_matrix[i,i]
+        FP_cls_i = sum(confusion_matrix[i,:]) - TP_cls_i
+        FN_cls_i = sum(confusion_matrix[:,i]) - TP_cls_i
+
+        Recall_i = TP_cls_i/(TP_cls_i + FN_cls_i)
+        Precision_i = TP_cls_i/(TP_cls_i + FP_cls_i)
+        F1_i = 2*(Precision_i * Recall_i)/(Precision_i + Recall_i)
+
+        if np.isnan(Recall_i):
+            Recall_i = 0
+        if np.isnan(Precision_i):
+            Precision_i = 0
+        if np.isnan(F1_i):
+            F1_i = 0
+
+        Recall_list.append(Recall_i)
+        Precision_list.append(Precision_i)
+        F1_list.append(F1_i)
+
+    average_Recall = np.array(Recall_list).mean()
+    average_Precision = np.array(Precision_list).mean()
+    average_F1 = np.array(F1_list).mean()
+
+    return average_Precision, average_Recall, average_F1
+
+
+
+# ----------------------------------------
+# Save metrics
+# ----------------------------------------
+
+def save_metrics(metrics: Dict[str, Scalar], header, filename: str):
+    """
+    Write results to a text file
+    """
+
+    keys, vals = list(metrics.keys()), np.array(list(metrics.values())).T
+    num_cols = len(metrics) + 1
+    num_rows = vals.shape[0]
+    header = (("%23s," * num_cols % tuple([header] + keys)).rstrip(","))
+
+    with open(filename, "w") as f:
+        f.write(header + "\n")
+        for index in range(num_rows):
+            f.write(("%23.5g," * num_cols % tuple([index+1] + list(vals[index]))).rstrip(",") + "\n")
+
+    return
+
+
+
+# ------------------------------
+# Get model
+# ------------------------------
+
+def get_model(model_config: str, num_classes: int):
+    """
+
+    """
+
+    if model_config == "EfficientNet":
+        model = efficientnet_v2_s(weights="IMAGENET1K_V1")
+        in_features = model.classifier[-1].in_features
+        model.classifier[-1] = torch.nn.Linear(in_features, num_classes)
+    elif model_config == "VGG":
+        model = vgg19(weights="IMAGENET1K_V1")
+        in_features = model.classifier[-1].in_features
+        model.classifier[-1] = torch.nn.Linear(in_features, num_classes)
+    elif model_config == "ResNet":
+        model = resnet50(weights="IMAGENET1K_V1")
+        model.fc = torch.nn.Linear(model.fc.in_features, num_classes)
+    elif model_config == "InceptionNet":
+        model = inception_v3(weights="IMAGENET1K_V1")
+        model.aux_logits = False
+        model.fc = torch.nn.Linear(model.fc.in_features, num_classes)
+    elif model_config == "DenseNet":
+        model = densenet121(weights="IMAGENET1K_V1")
+        model.classifier = torch.nn.Linear(model.classifier.in_features, num_classes)
+
+    return model
+
+
+
+# ------------------------------
+# Get strategy
+# ------------------------------
+
+def get_strategy(strategy_config: str):
+    """
+
+    """
+
+    if strategy_config == "FedAvg":
+        strategy = FedAvg(fraction_fit=1.0,
+                          fraction_evaluate=0.0,
+                          min_fit_clients=CONFIG["num_clients"],
+                          min_evaluate_clients=CONFIG["num_clients"],
+                          min_available_clients=CONFIG["num_clients"],
+                          on_fit_config_fn=fit_config,
+                          evaluate_fn=evaluate)
+    elif strategy_config == "PlainFedAvg":
+        strategy = PlainFedAvg(fraction_fit=1.0,
+                               fraction_evaluate=0.0,
+                               min_fit_clients=CONFIG["num_clients"],
+                               min_evaluate_clients=CONFIG["num_clients"],
+                               min_available_clients=CONFIG["num_clients"],
+                               on_fit_config_fn=fit_config,
+                               evaluate_fn=evaluate)
+
+    return strategy
+
+
+
+# ------------------------------
+# Get optimizer
+# ------------------------------
+
+def get_optimizer(model, optimizer_config: str):
+    """
+
+    """
+
+    if optimizer_config == "SGD":
+        optimizer = torch.optim.SGD(model.parameters(),
+                                    lr=CONFIG["lr"],
+                                    momentum=CONFIG["momentum"])
+    elif optimizer_config == "Adam":
+        optimizer = torch.optim.Adam(model.parameters(),
+                                     lr=CONFIG["lr"],
+                                     momentum=CONFIG["momentum"])
+    elif optimizer_config == "AdamW":
+        optimizer = torch.optim.AdamW(model.parameters(),
+                                     lr=CONFIG["lr"],
+                                     momentum=CONFIG["momentum"])
+
+    return optimizer
+
+
+
+# ------------------------------
+# Get criterion
+# ------------------------------
+
+def get_criterion(criterion_config: str):
+    """
+
+    """
+
+    if criterion_config == "CrossEntropyLoss":
+        criterion = nn.CrossEntropyLoss()
+
+    return criterion
+
+
+
+# ------------------------------
+# Create folder
+# ------------------------------
+
+def create_folder(dir: str):
+    """
+    Check if folder already exists
+    If not create new folder
+    """
+
+    if not os.path.exists(dir):
+        os.makedirs(dir)
+
+
+
+# ------------------------------
+# Save model as .pt
+# ------------------------------
+
+def save_model(model, save_dir):
+    """
+    Export model to TorchScript and save it
+    """
+
+    if not os.path.exists(save_dir):
+        model_scripted = torch.jit.script(model)
+        model_scripted.save(save_dir)
+
+
+
+# ------------------------------
+# Get parameters
+# ------------------------------
+
+def get_parameters(model) -> NDArrays:
+    """
+    Return model parameters as a list of NumPy ndarrays
+    """
+
+    return [val.cpu().numpy() for _, val in model.state_dict().items()]
+
+
+
+# ------------------------------
+# Set parameters
+# ------------------------------
+
+def set_parameters(model, parameters: NDArrays) -> None:
+    """
+    Set model parameters from a list of NumPy ndarrays
+    """
+
+    params_dict = zip(model.state_dict().keys(), parameters)
+    state_dict = OrderedDict({k: torch.tensor(v) for k, v in params_dict})
+    model.load_state_dict(state_dict, strict=True)
+
+    return
+
+
+
+# ------------------------------
+# Implement Flower client
+# ------------------------------
+
+class FlowerClient(fl.client.Client):
+    """
+    Flower client using PyTorch
+    """
+
+    def __init__(self, cid, model, train_dataloader, val_dataloader, device, root_dir, save_dir):
+        self.cid = cid
+        self.model = model
+        self.train_dataloader = train_dataloader
+        self.val_dataloader = val_dataloader
+        self.device = device
+        self.root_dir = root_dir
+        self.save_dir = save_dir
+
+
+    def get_parameters(self,
+                       ins: GetParametersIns,
+                       ) -> GetParametersRes:
+        """
+        Return model parameters as a list of NumPy ndarrays
+        """
+
+        # serialize ndarrays parameters into Parameters object
+        parameters = ndarrays_to_parameters(get_parameters(self.model))
+
+        # build and return response
+        return GetParametersRes(
+            status=Status(code=Code.OK, message="Success"),
+            parameters=parameters,
+        )
+
+
+    def fit(self,
+            ins: FitIns,
+            ) -> FitRes:
+        """
+        Set model parameters, train model, return updated model parameters
+        """
+
+        # create folder
+        dir = os.path.join(self.save_dir, f"server_round_{ins.config['server_round']}")
+        create_folder(dir)
+
+        # deserialize parameters to Numpy ndarrays
+        parameters_ndarrays = parameters_to_ndarrays(ins.parameters)
+
+        # update local model
+        set_parameters(self.model, parameters_ndarrays)
+
+        # specify optimizer
+        optimizer = get_optimizer(self.model, ins.config["optimizer"])
+
+        # specify loss function
+        criterion = get_criterion(ins.config["loss_fcn"])
+
+        # train local model
+        metrics_dict = train_model(self.model,
+                                   self.train_dataloader,
+                                   self.val_dataloader,
+                                   optimizer,
+                                   ins.config["epochs"],
+                                   criterion,
+                                   self.device,
+                                   ins.config["use_best_weights"],
+                                   ins.config["early_stopping"],
+                                   dir)
+
+        # get updated parameters and serialize ndarrays parameters into Parameters object
+        parameters_updated = ndarrays_to_parameters(get_parameters(self.model))
+
+        # write training and validation metrics to .txt file
+        save_metrics(metrics_dict, "epoch", os.path.join(dir, "results.txt"))
+
+        # build and return response
+        return FitRes(
+            status=Status(code=Code.OK, message="Success"),
+            parameters=parameters_updated,
+            num_examples=len(self.train_dataloader),
+            metrics={},
+        )
+
+
+    def evaluate(self,
+                 ins: EvaluateIns,
+                 ) -> EvaluateRes:
+        """
+        Set model parameters, evaluate aggregated model on local test dataset, return result
+        """
+
+        # build and return response
+        return EvaluateRes(
+            status=Status(code=Code.OK, message="Success"),
+            loss=0.0,
+            num_examples=0,
+            metrics={},
+        )
+
+
+
+# ------------------------------
+# Evaluation function
+# ------------------------------
+
+def evaluate(server_round: int,
+             parameters: NDArrays,
+             config: Dict[str, Scalar],
+             ) -> Optional[Tuple[float, Dict[str, Scalar]]]:
+    """
+    The evaluate function will be called by Flower after each server round
+    """
+
+    # create folder
+    save_dir = os.path.join("runs", CONFIG["output_folder"], "global_model")
+    create_folder(save_dir)
+
+    # load pretrained model
+    model = get_model(CONFIG["model"], CONFIG["num_classes"])
+
+    # load data
+    test_dataloader = load_test_data(
+        os.path.join("dataset", "Cabins5_flta", "global_test_set"),
+        CONFIG["batch_size"],
+        CONFIG["img_size"],
+    )
+
+    # update model
+    set_parameters(model, parameters)
+
+    # save aggregated model
+    save_model(model, os.path.join(save_dir, f"best_server_round_{server_round}.pt"))
+
+    # specify loss function
+    criterion = get_criterion(CONFIG["loss_fcn"])
+
+    # test aggregated model on test dataset
+    test_acc, test_loss, confusion_matrix = test_model(
+        model,
+        test_dataloader,
+        criterion,
+        DEVICE,
+        CONFIG["num_classes"],
+    )
+
+    # calculate metrics
+    average_Precision, average_Recall, average_F1 = calculate_metrics(confusion_matrix)
+
+    return 0.0, {"test_loss": test_loss, "test_acc": test_acc, "precision": average_Precision, "recall": average_Recall, "f1": average_F1}
+
+
+
+# ------------------------------
+# Create Flower client
+# ------------------------------
+
+def client_fn(cid: str) -> FlowerClient:
+    """
+    Create a Flower client instance. Each client will
+    be trained and validated on his own unique data
+    """
+
+    # load pretrained model
+    model = get_model(CONFIG["model"], CONFIG["num_classes"])
+
+    # specify output folder
+    root_dir = os.path.join("runs", CONFIG["output_folder"])
+    save_dir = os.path.join(root_dir, f"client_{int(cid)+1}")
+
+    # create folder
+    create_folder(save_dir)
+
+    # load data
+    train_dataloader, val_dataloader = load_train_val_data(
+        os.path.join("dataset", "Cabins5_flta", f"Client{int(cid)+1}"),
+        CONFIG["batch_size"],
+        CONFIG["img_size"],
+    )
+
+    # save one batch of training data
+    imgs, _ = next(iter(train_dataloader))
+    train_batch0 = make_grid(imgs, nrow=4, scale_each=True)
+    save_image(train_batch0, os.path.join(save_dir, "train_batch0"), "png")
+
+    return FlowerClient(cid, model, train_dataloader, val_dataloader, DEVICE, root_dir, save_dir)
+
+
+
+# ------------------------------
+# Fit config function
+# ------------------------------
+
+def fit_config(server_round: int) -> Dict[str, Scalar]:
+    """
+    Return training configuration dict for each round
+    """
+
+    config = {
+        "server_round": server_round,
+        "epochs": CONFIG["epochs"],
+        "optimizer": CONFIG["optimizer"],
+        "momentum": CONFIG["momentum"],
+        "lr": CONFIG["lr"],
+        "lr_scheduler": CONFIG["lr_scheduler"],
+        "loss_fcn": CONFIG["loss_fcn"],
+        "use_best_weights": CONFIG["use_best_weights"],
+        "early_stopping": CONFIG["early_stopping"],
+    }
+
+    return config
+
+
+
+# ------------------------------
+# Extract metrics
+# ------------------------------
+
+def extract_metrics(metrics: Dict[str, Scalar]) -> Dict[str, Scalar]:
+    """
+
+    """
+
+    extracted_metrics = {
+        "test_loss": [],
+        "test_acc": [],
+        "precision": [],
+        "recall": [],
+        "f1": [],
+    }
+
+    for key, values in metrics.items():
+        for i, (_, data) in enumerate(values):
+            extracted_metrics[key].append(data)
+
+    return extracted_metrics
+
+
+
+# ------------------------------
+# Start simulation
+# ------------------------------
+
+if __name__=="__main__":
+    # set seeds
+    set_seeds(CONFIG["seed"])
+
+    # define parameters
+    DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
+
+    # specify output folder
+    save_dir = os.path.join("runs", CONFIG["output_folder"])
+
+    # check if folder already exists
+    if os.path.exists(save_dir):
+        print("Output folder already exists. Exiting the program.")
+        sys.exit()
+
+    # create output folder
+    create_folder(save_dir)
+
+    # move copy of config file to output folder
+    shutil.copy(config_file_name, os.path.join(save_dir, config_file_name))
+
+    # get strategy
+    strategy = get_strategy(CONFIG["strategy"])
+
+    # specify client resources
+    client_resources = {"num_cpus": 16}
+    if DEVICE.type == "cuda":
+        client_resources = {"num_cpus": 16, "num_gpus": 1.0}
+
+    # start simulation
+    history = fl.simulation.start_simulation(
+        client_fn=client_fn,
+        num_clients=CONFIG["num_clients"],
+        config=fl.server.ServerConfig(num_rounds=CONFIG["num_rounds"]),
+        strategy=strategy,
+        client_resources=client_resources,
+    )
+
+    # write training and validation metrics to .txt file
+    extracted_metrics = extract_metrics(history.metrics_centralized)
+    save_metrics(extracted_metrics, "server_round", os.path.join(save_dir, "global_model", "results_aggregated_model.txt"))
diff --git a/runs/.gitkeep b/runs/.gitkeep
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/strategy.py b/strategy.py
new file mode 100644
index 0000000000000000000000000000000000000000..521c4995c0267154adb6e624e9be10c33edf58ce
--- /dev/null
+++ b/strategy.py
@@ -0,0 +1,83 @@
+# ------------------------------
+# Import libraries
+# ------------------------------
+
+from typing import Dict, List, Optional, Tuple, Union
+import numpy as np
+import flwr as fl
+from flwr.common import (
+    FitRes,
+    NDArrays,
+    Parameters,
+    Scalar,
+    ndarrays_to_parameters,
+    parameters_to_ndarrays,
+)
+from logging import WARNING
+from flwr.common.logger import log
+from flwr.server.client_proxy import ClientProxy
+from functools import reduce
+
+
+
+# ------------------------------
+# Compute plain average
+# ------------------------------
+
+def aggregate_plain_average(results: List[Tuple[NDArrays, int]]) -> NDArrays:
+    """
+    Compute plain average
+    """
+
+    weights_list = [weights for weights, _ in results]
+
+    # Compute average weights of each layer
+    weights_prime: NDArrays = [
+        reduce(np.add, layer_updates) / len(weights_list)
+        for layer_updates in zip(*weights_list)
+    ]
+
+    return weights_prime
+
+
+
+# ------------------------------
+# Overwrite FedAvg class
+# ------------------------------
+
+class PlainFedAvg(fl.server.strategy.FedAvg):
+
+    def aggregate_fit(self,
+                      server_round: int,
+                      results: List[Tuple[ClientProxy, FitRes]],
+                      failures: List[Union[Tuple[ClientProxy, FitRes], BaseException]],
+                      ) -> Tuple[Optional[Parameters], Dict[str, Scalar]]:
+        """
+        Aggregate fit results using plain average
+        """
+
+        if not results:
+            return None, {}
+        
+        # do not aggregate if there are failures and failures are not accepted
+        if not self.accept_failures and failures:
+            return None, {}
+
+        # Convert results
+        weights_results = [
+            (parameters_to_ndarrays(fit_res.parameters), fit_res.num_examples)
+            for _, fit_res in results
+        ]
+        aggregated_ndarrays = aggregate_plain_average(weights_results)
+
+        parameters_aggregated = ndarrays_to_parameters(aggregated_ndarrays)
+
+        # Aggregate custom metrics if aggregation fn was provided
+        metrics_aggregated = {}
+        if self.fit_metrics_aggregation_fn:
+            fit_metrics = [(res.num_examples, res.metrics) for _, res in results]
+            metrics_aggregated = self.fit_metrics_aggregation_fn(fit_metrics)
+        elif server_round == 1:  # Only log this warning once
+            log(WARNING, "No fit_metrics_aggregation_fn provided")
+
+        return parameters_aggregated, metrics_aggregated
\ No newline at end of file
diff --git a/test_global_weight.py b/test_global_weight.py
new file mode 100644
index 0000000000000000000000000000000000000000..30dd105e3d6bee8cef44b36121e2db5bd7543ee9
--- /dev/null
+++ b/test_global_weight.py
@@ -0,0 +1,207 @@
+import torch
+import torch.nn as nn
+import torchvision.transforms as transforms
+from torchvision.models import efficientnet_v2_s, vgg19, resnet50, inception_v3, densenet121
+from torchvision.datasets import ImageFolder
+from torch.utils.data import DataLoader
+from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
+import os
+import matplotlib.pyplot as plt
+import numpy as np
+import yaml
+from tqdm import tqdm
+import shutil
+import torch.nn.functional as F
+import seaborn as sns
+from PIL import Image, ImageDraw, ImageFont
+
+# Function to read configuration from a YAML config file
+def read_config(config_file):
+    with open(config_file, 'r') as f:
+        config = yaml.safe_load(f)
+    return config
+
+# Function to set up model architecture with configurable last layers
+def setup_model(num_classes, model_name):
+    model_classes = {
+        "EfficientNet": efficientnet_v2_s,
+        "VGG": vgg19,
+        "ResNet": resnet50,
+        "InceptionNet": inception_v3,
+        "DenseNet": densenet121
+    }
+    model = model_classes[model_name](pretrained=False)
+
+    if model_name in ["VGG", "EfficientNet"]:
+        in_features = model.classifier[-1].in_features
+        model.classifier[-1] = nn.Linear(in_features, num_classes)
+    elif model_name == "ResNet":
+        model.fc = nn.Linear(model.fc.in_features, num_classes)
+    elif model_name == "DenseNet":
+        model.classifier = nn.Linear(model.classifier.in_features, num_classes)
+    elif model_name == "InceptionNet":
+        model.aux_logits = False
+        in_features = model.fc.in_features
+        model.fc = nn.Linear(in_features, num_classes)
+
+    return model
+
+# Function to load TorchScript weights into the model
+def load_weights(model, weights_path):
+    loaded_model = torch.jit.load(weights_path) # Load the TorchScript model
+    model.load_state_dict(loaded_model.state_dict()) # Copy the parameters from the loaded model to the provided model
+    model.eval() # Set the model to evaluation mode
+
+class_map_str_to_idx = {
+    "No_windshield": 0,
+    "With_windshield": 1
+}
+
+# Function to test the model
+def test_model(model, test_loader):
+    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+    model.to(device)
+    criterion = nn.CrossEntropyLoss()
+
+    all_predictions = []
+    all_targets = []
+    all_confidences = []  # Store confidences
+
+    with torch.no_grad(), tqdm(total=len(test_loader), desc="Running tests") as pbar:
+        for images, labels in test_loader:
+            images, labels = images.to(device), labels.to(device)
+            outputs = model(images)
+            loss = criterion(outputs, labels)
+
+            probabilities = F.softmax(outputs, dim=1)  # Convert outputs to probabilities
+            confidences, predicted = torch.max(probabilities, 1)  # Get confidences and predictions
+            all_confidences.extend(confidences.cpu().numpy())  # Store confidences
+            all_predictions.extend(predicted.cpu().numpy())
+            all_targets.extend(labels.cpu().numpy())
+
+            pbar.update(1)
+
+    return all_predictions, all_targets, loss.item(), all_confidences
+
+# Function to save results
+def save_results(output_folder, all_predictions, all_targets, metrics, config, test_dataset, all_confidences):
+    # Create output folder if it doesn't exist
+    if not os.path.exists(output_folder):
+        os.makedirs(output_folder)
+
+    # Create folders based on class mapping
+    for class_name in class_map_str_to_idx.keys():
+        class_folder = os.path.join(output_folder, class_name)
+        os.makedirs(class_folder, exist_ok=True)
+
+    # Move images to respective class folders based on predictions
+    for image_path, prediction, target, confidence in zip(test_dataset.imgs, all_predictions, all_targets, all_confidences):
+        image_filename = os.path.basename(image_path[0])
+        try:
+            predicted_class_name = [name for name, idx in class_map_str_to_idx.items() if idx == prediction][0]
+            predicted_class_folder = os.path.join(output_folder, predicted_class_name)
+            image_dest_path = os.path.join(predicted_class_folder, image_filename)
+
+            # Open the image
+            image = Image.open(image_path[0])
+
+            # Write predicted class name and confidence on the top of the image
+            draw = ImageDraw.Draw(image)
+            font = font = ImageFont.truetype("arial.ttf", 25)  # Adjust font size
+            text = f"Class: {predicted_class_name}, Confidence: {confidence:.2f}"
+            draw.text((10, 10), text, fill=(57, 255, 20), font=font)  # Adjust font color to black
+
+            # Save the modified image
+            image.save(image_dest_path)
+
+        except IndexError:
+            print(f"No matching class name found for prediction: {prediction}")
+
+    # Save metrics to a text file
+    with open(os.path.join(output_folder, 'metrics.txt'), 'w') as f:
+        for metric, value in metrics.items():
+            f.write(f"{metric}: {value}\n")
+
+    # Save config file in the output folder
+    with open(os.path.join(output_folder, 'config_test.yaml'), 'w') as f:
+        yaml.dump(config, f)
+
+    # Generate and save confusion matrix
+    cm = confusion_matrix(all_targets, all_predictions)
+    plt.figure(figsize=(8, 6))
+    sns.heatmap(cm, annot=True, cmap="Blues", fmt="d")
+    # Get the class names
+    class_names = list(class_map_str_to_idx.keys())
+    # Set tick labels and rotation
+    plt.xticks(np.arange(len(class_names)) + 0.5, class_names, rotation=0)
+    plt.yticks(np.arange(len(class_names)) + 0.5, class_names, rotation=0)
+    plt.title('Confusion Matrix')
+    plt.xlabel('Predicted Label')
+    plt.ylabel('True Label')
+    plt.tight_layout()
+    plt.savefig(os.path.join(output_folder, 'confusion_matrix.png'))
+
+
+    # Print where the results are stored
+    print(f"\nResults are stored in: {output_folder}")
+
+# Main function
+def main(config_file):
+    # Read configuration
+    config = read_config(config_file)
+
+    # Set up output folder
+    output_folder = config['output_folder']
+    if os.path.exists(output_folder):
+        print("Output folder already exists. Exiting.")
+        return
+
+    # Set hyperparameters
+    num_classes = config['num_classes']
+    model_name = config['model_name']
+    batch_size = config['batch_size']
+    test_folder = config['test_folder']
+
+    # Set up data transformations
+    transform = transforms.Compose([
+        transforms.Resize(config['image_size']),
+        transforms.ToTensor(),
+    ])
+
+    # Load test dataset
+    test_dataset = ImageFolder(test_folder, transform=transform)
+    test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
+
+    # Print the architecture selected
+    print(f"Selected model architecture: {model_name}")
+
+    # Determine if GPU or CPU is used
+    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+    print(f"Device in use: {device}")
+
+    # Set up model
+    model = setup_model(num_classes, model_name)
+
+    # Load weights into the model
+    weights_path = config['weights_path']
+    print("Loading model weights...")
+    load_weights(model, weights_path)
+    print("Model weights loaded successfully.")
+
+    # Test the model
+    all_predictions, all_targets, test_loss, all_confidences = test_model(model, test_loader)
+
+    # Calculate metrics
+    accuracy = accuracy_score(all_targets, all_predictions)
+    precision = precision_score(all_targets, all_predictions, average='weighted')
+    recall = recall_score(all_targets, all_predictions, average='weighted')
+    f1 = f1_score(all_targets, all_predictions, average='weighted')
+
+    # Save results
+    metrics = {'Accuracy': accuracy, 'Precision': precision, 'Recall': recall, 'F1 Score': f1}
+    save_results(output_folder, all_predictions, all_targets, metrics, config, test_dataset, all_confidences)
+
+# Run the code
+if __name__ == "__main__":
+    config_file = 'config_test.yaml'  # Change this to your config file path
+    main(config_file)
diff --git a/train_and_test.py b/train_and_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b4edcee35cb0658e44f97d7a8c626a63e9a18de
--- /dev/null
+++ b/train_and_test.py
@@ -0,0 +1,153 @@
+import yaml
+import os
+import sys
+import shutil
+import torch
+import seaborn as sns
+from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
+import matplotlib.pyplot as plt
+import numpy as np
+from torchvision.utils import make_grid, save_image
+from main_esaim import (#change the from main to the file you used to train your federated dataset
+    set_seeds,
+    create_folder,
+    get_model,
+    get_criterion,
+    get_optimizer,
+    load_train_val_data,
+    load_test_data,
+    train_model,
+    test_model,
+    calculate_metrics,
+    save_metrics,
+)
+from tqdm import tqdm
+
+#### Set path to training dataset line 53 and Test at line 58!!!
+
+
+
+# load config file
+config_file_name = "config.yaml"
+with open(config_file_name) as file:
+    CONFIG = yaml.safe_load(file)
+
+# specify output folder
+save_dir = os.path.join("runs", CONFIG["output_folder"])
+
+# check if folder already exists
+if os.path.exists(save_dir):
+    print("Output folder already exists. Exiting the program.")
+    sys.exit()
+
+# create folder
+create_folder(save_dir)
+print("Output folder created.")
+
+# move copy of config file to output folder
+shutil.copy(config_file_name, os.path.join(save_dir, config_file_name))
+print("Config file copied to the output folder.")
+
+# specify client dataset
+cid = CONFIG["client_id"]
+
+# set seeds
+set_seeds(CONFIG["seed"])
+print("Seeds set.")
+
+# load pretrained model
+model = get_model(CONFIG["model"], CONFIG["num_classes"])
+print("Pretrained model loaded.")
+
+# load data
+print("Loading training and validation data...")
+train_dataloader, val_dataloader = load_train_val_data(
+    os.path.join("dataset/ESAIM", f"Client{int(cid)}"),
+    CONFIG["batch_size"],
+    CONFIG["img_size"],
+)
+print("Training and validation data loaded.")
+print("Loading test data...")
+test_dataloader = load_test_data(
+    "dataset/ESAIM/global_test_set",
+    CONFIG["batch_size"],
+    CONFIG["img_size"],
+)
+print("Test data loaded.")
+
+# save one batch of training data
+imgs, _ = next(iter(train_dataloader))
+train_batch0 = make_grid(imgs, nrow=4, scale_each=True)
+save_image(train_batch0, os.path.join(save_dir, "train_batch0"), "png")
+print("One batch of training data saved as image.")
+
+# specify optimizer
+optimizer = get_optimizer(model, CONFIG["optimizer"])
+print("Optimizer specified.")
+
+# specify loss function
+criterion = get_criterion(CONFIG["loss_fcn"])
+print("Loss function specified.")
+
+# specify device
+device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
+print(f"Device in use: {device}")
+
+# train model
+print("Training the model...")
+metrics_dict = train_model(
+    model,
+    train_dataloader,
+    val_dataloader,
+    optimizer,
+    CONFIG["epochs"],
+    criterion,
+    device,
+    CONFIG["use_best_weights"],
+    CONFIG["early_stopping"],
+    save_dir,
+)
+print("Model training completed.")
+
+# test model with best epoch weights
+best_epoch_weights_path = os.path.join(save_dir, "best.pt")
+
+if os.path.exists(best_epoch_weights_path):
+    print("Loading best epoch weights...")
+    model.load_state_dict(torch.jit.load(best_epoch_weights_path).state_dict())
+    print("Best epoch weights loaded successfully.")
+else:
+    print("Best epoch weights not found. Using final weights for testing.")
+
+# test model
+print("Testing the model...")
+test_acc, test_loss, confusion_matrix = test_model(
+    model,
+    test_dataloader,
+    criterion,
+    device,
+    CONFIG["num_classes"],
+)
+print("Model testing completed.")
+
+
+# calculate metrics
+print("Calculating metrics...")
+average_Precision, average_Recall, average_F1 = calculate_metrics(confusion_matrix)
+print("Metrics calculated.")
+
+# Determine the actual number of epochs completed
+num_epochs_completed = len(metrics_dict.get("train_loss", []))
+
+# Add test metrics to dict and pad the lists
+metrics_dict["test_acc"] = [0] * (num_epochs_completed - 1) + [test_acc]
+metrics_dict["test_loss"] = [0] * (num_epochs_completed - 1) + [test_loss]
+metrics_dict["precision"] = [0] * (num_epochs_completed - 1) + [average_Precision]
+metrics_dict["recall"] = [0] * (num_epochs_completed - 1) + [average_Recall]
+metrics_dict["f1"] = [0] * (num_epochs_completed - 1) + [average_F1]
+
+# write training and validation metrics to .txt file
+print("Saving metrics to a file...")
+save_metrics(metrics_dict, "epoch", os.path.join(save_dir, "results.txt"))
+print("Metrics saved to results.txt in the output folder.")
+print("\nResults are stored in:", save_dir)