clear all
close all
clc
% Main file to run the Benders-bundle method for privacy-aware solution of
% energy management in Local Energy Communities
%% Initialization

load('Datos.mat'); % Input data

converged = 0; % Convergence flag
tol = 1e-3; % Convergence threshold
ResultsM.sol.pC = zeros(Datos.npc,Datos.nt); % Initial value of the power exchanged with prosumers
k = 0; % Iteration counter
tau = ones(1,Datos.npc); % Initial penalty term

%% Loop

while converged == 0
    
    k = k + 1; % Update iteration counter
    UB(k) = 0; % Upper bound (total prosumers cost)
    
    for c = 1:Datos.npc % HEM resolution for each prosumer
        ResultsH = HEM_milp(ResultsM.sol.pC(c,:),c); % HEM problem including binary variables
        ResultsH = HEM(ResultsM.sol.pC(c,:),ResultsH,c); % HEM problem without bnary variables
        History(c,k).pC = ResultsH.sol.pC; % Store P2P exchanges
        History(c,k).Sen = ResultsH.Sen.Constraints.Enforcing_power; % Store sensitivities
        History(c,k).f = ResultsH.f; % Store objective function
        UB(k) = UB(k) + History(c,k).f; % Update UB
    end
    
    if k >= 2
        if UB(k) >= UB(k-1) % Step null
            for c = 1:Datos.npc
                UB(k) = UB(k-1); % Do not update UB
            end
            tau = Update_tau(History,tau,k); % Update penalty parameter
        end
        if UB(k) < tol % Check convergence
            converged = 1;
            break
        end
    end
        
    ResultsM = Master(History,UB(k),tau); % Master (manager) results
    
    if k == 100 % Failure
        break
    end
       
end
