using JuMP, Ipopt
using CSV
using DataFrames
include("structPS.jl")
include("basicfunctions.jl")
include("loadflow.jl")
LINES_DATAFRAME= create_dataframe("C:/Users/mayar.madboly/Documents/M A S T E R S S S S S S/chapter_4/work/excel/L3.CSV")
BUSES_NUMBER=3
LINES_NUMBER=3
LINES_ARRAY=create_array(Line,LINES_NUMBER)
set_array(LINES_ARRAY,Line,LINES_DATAFRAME)
Y_BUS=create_ybus(BUSES_NUMBER,LINES_ARRAY)
Y_LINES=get_ylines(BUSES_NUMBER,LINES_ARRAY)
G = real(Y_LINES);
B = imag(Y_LINES);
Nodes_set=[1,2,3]
Gen_set=[1,2,3]
Pd=[0,-4,0]
Qd=[0,-2.5,0]
S=zeros(3,3)
S=[2 2 2; 2 2 2; 2 2 2]
m = JuMP.Model(JuMP.with_optimizer(Ipopt.Optimizer, print_level =0))
# 2.1.Variables
JuMP.@variable(m, 0.1≤ v[i in Nodes_set] ≤ 1.06)
JuMP.@variable(m, -π/4 ≤ δ[i in Nodes_set] ≤ π/4)
JuMP.@variable(m, 0.1 ≤ p[i in Gen_set] ≤ 5)
JuMP.@variable(m, 0.1 ≤ q[i in Gen_set] ≤ 5)
JuMP.@variable(m, pij[i = Nodes_set, j = Nodes_set])
JuMP.@variable(m, qij[i = Nodes_set, j = Nodes_set])
JuMP.@constraint(m, Pg2,(p[2] == 0.0)) #bus 2 is a PQ bus ,there is no generator at bus 2
JuMP.@constraint(m, Qg2,(q[2] == 0.0))
JuMP.@constraint(m, ReferenceAngle,(δ[1] == 0.0))
JuMP.@NLconstraint(m, p_line[i in Nodes_set, j in Nodes_set],
(pij[i,j] == (v[i]^2*G[i,j]-v[i]*v[j]*(G[i,j]*cos(δ[i]-δ[j])+B[i,j]*sin(δ[i]-δ[j])))))
JuMP.@NLconstraint(m, q_line[i in Nodes_set, j in Nodes_set],
(qij[i,j] == (-1*v[i]^2*B[i,j]-v[i]*v[j]*(G[i,j]*sin(δ[i]-δ[j])-B[i,j]*cos(δ[i]-δ[j])))))
JuMP.@NLconstraint(m, Pnodal[i in Nodes_set],
(sum(pij[i,j] for j in Nodes_set) == p[i]+Pd[i]))
JuMP.@constraint(m, Qnodal[i in Nodes_set],
(sum(qij[i,j] for j = Nodes_set) == q[i]+Qd[i]))
JuMP.@NLconstraint(m, Smax[i in Nodes_set, j in Nodes_set],
pij[i,j]^2 + qij[i,j]^2 ≤ S[i,j]^2)
#OBJECTIVE
JuMP.@NLobjective(m,Min,p[1]+p[3])
JuMP.optimize!(m)
println("Optimal solutions:")
println("p1:",JuMP.value(p[1]))
println("p3:",JuMP.value(p[3]))
println("p12:",JuMP.value(pij[1,2]))
println("p21:",JuMP.value(pij[2,1]))
println("p13:",JuMP.value(pij[1,3]))
println("p31:",JuMP.value(pij[3,1]))
println("p23:",JuMP.value(pij[2,3]))
println("p32:",JuMP.value(pij[3,2]))
status = JuMP.termination_status(m)
println(status)