text:
"""
Initialitation of model of 0-state synchronous (classic model) machine in Julia.
Refer to Power System Modelling and Scripting by F. Milano for the equations
"""
function initialize_mach_shaft!(
    device_states,
    device::PSY.DynamicGenerator{PSY.BaseMachine, S, A, TG, P},
) where {S <: PSY.Shaft, A <: PSY.AVR, TG <: PSY.TurbineGov, P <: PSY.PSS}
    #PowerFlow Data
    static_gen = PSY.get_static_injector(device)
    P0 = PSY.get_active_power(static_gen)
    Q0 = PSY.get_reactive_power(static_gen)
    Vm = PSY.get_magnitude(PSY.get_bus(static_gen))
    θ = PSY.get_angle(PSY.get_bus(static_gen))
    S0 = P0 + Q0 * 1im
    V_R = Vm * cos(θ)
    V_I = Vm * sin(θ)
    V = V_R + V_I * 1im
    I = conj(S0 / V)

    #Machine Data
    machine = PSY.get_machine(device)
    R = PSY.get_R(machine)
    #Assumption of Classical Machine: Xq = Xd_p
    Xd_p = PSY.get_Xd_p(machine)

    δ0 = angle(V + (R + Xd_p * 1im) * I)
    ω0 = 1.0
    τm0 = real(V * conj(I))
    #To solve: δ, τm, Vf0
    function f!(out, x)
        δ = x[1]
        τm = x[2]
        Vf0 = x[3]

        V_dq = LITS.ri_dq(δ) * [V_R; V_I]
        i_d = (1.0 / (R^2 + Xd_p^2)) * (Xd_p * (Vf0 - V_dq[2]) - R * V_dq[1])  #15.36
        i_q = (1.0 / (R^2 + Xd_p^2)) * (Xd_p * V_dq[1] + R * (Vf0 - V_dq[2])) #15.36
        Pe = (V_dq[1] + R * i_d) * i_d + (V_dq[2] + R * i_q) * i_q
        out[1] = τm - Pe #Mechanical Torque
        out[2] = P0 - (V_dq[1] * i_d + V_dq[2] * i_q) #Output Power
        out[3] = Q0 - (V_dq[2] * i_d - V_dq[1] * i_q) #Output Reactive Power
    end
    x0 = [δ0, τm0, 1.0]
    sol = NLsolve.nlsolve(f!, x0)
    if !NLsolve.converged(sol)
        @warn("Initialization in Synch. Machine failed")
    else
        sol_x0 = sol.zero
        #Update terminal voltages
        get_inner_vars(device)[VR_gen_var] = V_R
        get_inner_vars(device)[VI_gen_var] = V_I
        #Update δ and ω of Shaft. Works for every Shaft.
        shaft_ix = get_local_state_ix(device, S)
        shaft_states = @view device_states[shaft_ix]
        shaft_states[1] = sol_x0[1] #δ
        shaft_states[2] = ω0 #ω
        #Update Mechanical and Electrical Torque on Generator
        get_inner_vars(device)[τe_var] = sol_x0[2]
        get_inner_vars(device)[τm_var] = sol_x0[2]
        #Not necessary to update Vf for AVR in Base Machine. Update eq_p:
        PSY.set_eq_p!(machine, sol_x0[3])
        get_inner_vars(device)[Vf_var] = sol_x0[3]
    end
end

"""
Initialitation of model of 2-state (One d- and One q-) synchronous machine in Julia.
Refer to Power System Modelling and Scripting by F. Milano for the equations
"""
function initialize_mach_shaft!(
    device_states,
    device::PSY.DynamicGenerator{PSY.OneDOneQMachine, S, A, TG, P},
) where {S <: PSY.Shaft, A <: PSY.AVR, TG <: PSY.TurbineGov, P <: PSY.PSS}
    #PowerFlow Data
    static_gen = PSY.get_static_injector(device)
    P0 = PSY.get_active_power(static_gen)
    Q0 = PSY.get_reactive_power(static_gen)
    Vm = PSY.get_magnitude(PSY.get_bus(static_gen))
    θ = PSY.get_angle(PSY.get_bus(static_gen))
    S0 = P0 + Q0 * 1im
    V_R = Vm * cos(θ)
    V_I = Vm * sin(θ)
    V = V_R + V_I * 1im
    I = conj(S0 / V)

    #Machine Data
    machine = PSY.get_machine(device)
    R = PSY.get_R(machine)
    Xd = PSY.get_Xd(machine)
    Xq = PSY.get_Xq(machine)
    Xd_p = PSY.get_Xd_p(machine)
    Xq_p = PSY.get_Xq_p(machine)

    #States of OneDOneQMachine are [1] eq_p and [2] ed_p
    δ0 = angle(V + (R + Xq * 1im) * I)
    ω0 = 1.0
    τm0 = real(V * conj(I))
    #To solve: δ, τm, Vf0, eq_p, ed_p
    function f!(out, x)
        δ = x[1]
        τm = x[2]
        Vf0 = x[3]
        eq_p = x[4]
        ed_p = x[5]

        V_dq = LITS.ri_dq(δ) * [V_R; V_I]
        i_d = (1.0 / (R^2 + Xd_p * Xq_p)) * (Xq_p * (eq_p - V_dq[2]) + R * (ed_p - V_dq[1]))  #15.32
        i_q =
            (1.0 / (R^2 + Xd_p * Xq_p)) * (-Xd_p * (ed_p - V_dq[1]) + R * (eq_p - V_dq[2]))  #15.32
        Pe = (V_dq[1] + R * i_d) * i_d + (V_dq[2] + R * i_q) * i_q
        out[1] = τm - Pe #Mechanical Torque
        out[2] = P0 - (V_dq[1] * i_d + V_dq[2] * i_q) #Output Power
        out[3] = Q0 - (V_dq[2] * i_d - V_dq[1] * i_q) #Output Reactive Power
        out[4] = -eq_p - (Xd - Xd_p) * i_d + Vf0 #∂(eq_p)/∂t
        out[5] = -ed_p + (Xq - Xq_p) * i_q #∂(ed_p)/∂t
    end
    V_dq0 = LITS.ri_dq(δ0) * [V_R; V_I]
    x0 = [δ0, τm0, 1.0, V_dq0[2], V_dq0[1]]
    sol = NLsolve.nlsolve(f!, x0)
    if !NLsolve.converged(sol)
        @warn("Initialization in Synch. Machine failed")
    else
        sol_x0 = sol.zero
        #Update terminal voltages
        get_inner_vars(device)[VR_gen_var] = V_R
        get_inner_vars(device)[VI_gen_var] = V_I
        #Update δ and ω of Shaft. Works for every Shaft.
        shaft_ix = get_local_state_ix(device, S)
        shaft_states = @view device_states[shaft_ix]
        shaft_states[1] = sol_x0[1] #δ
        shaft_states[2] = ω0 #ω
        #Update Mechanical and Electrical Torque on Generator
        get_inner_vars(device)[τe_var] = sol_x0[2]
        get_inner_vars(device)[τm_var] = sol_x0[2]
        #Update Vf for AVR in OneDOneQ Machine.
        get_inner_vars(device)[Vf_var] = sol_x0[3]
        #Update eq_p and ed_p for Machine
        machine_ix = get_local_state_ix(device, PSY.OneDOneQMachine)
        machine_states = @view device_states[machine_ix]
        machine_states[1] = sol_x0[4] #eq_p
        machine_states[2] = sol_x0[5] #ed_p
    end
end

"""
Initialitation of model of 6-state (Marconato) synchronous machine in Julia.
Refer to Power System Modelling and Scripting by F. Milano for the equations
"""
function initialize_mach_shaft!(
    device_states,
    device::PSY.DynamicGenerator{PSY.MarconatoMachine, S, A, TG, P},
) where {S <: PSY.Shaft, A <: PSY.AVR, TG <: PSY.TurbineGov, P <: PSY.PSS}
    #PowerFlow Data
    static_gen = PSY.get_static_injector(device)
    P0 = PSY.get_active_power(static_gen)
    Q0 = PSY.get_reactive_power(static_gen)
    Vm = PSY.get_magnitude(PSY.get_bus(static_gen))
    θ = PSY.get_angle(PSY.get_bus(static_gen))
    S0 = P0 + Q0 * 1im
    V_R = Vm * cos(θ)
    V_I = Vm * sin(θ)
    V = V_R + V_I * 1im
    I = conj(S0 / V)

    #Machine Data
    machine = PSY.get_machine(device)
    R = PSY.get_R(machine)
    Xd = PSY.get_Xd(machine)
    Xq = PSY.get_Xq(machine)
    Xd_p = PSY.get_Xd_p(machine)
    Xq_p = PSY.get_Xq_p(machine)
    Xd_pp = PSY.get_Xd_pp(machine)
    Xq_pp = PSY.get_Xq_pp(machine)
    T_AA = PSY.get_T_AA(machine)
    Td0_p = PSY.get_Td0_p(machine)
    γd = PSY.get_γd(machine)
    γq = PSY.get_γq(machine)

    #States of MarconatoMachine are [1] ψq, [2] ψd, [3] eq_p, [4] ed_p, [5] eq_pp and [6] ed_pp
    δ0 = angle(V + (R + Xq * 1im) * I)
    ω0 = 1.0
    τm0 = real(V * conj(I))
    #To solve: δ, τm, Vf0, eq_p, ed_p
    function f!(out, x)
        δ = x[1]
        τm = x[2]
        Vf0 = x[3]
        ψq = x[4]
        ψd = x[5]
        eq_p = x[6]
        ed_p = x[7]
        eq_pp = x[8]
        ed_pp = x[9]

        V_dq = LITS.ri_dq(δ) * [V_R; V_I]
        i_d = (1.0 / Xd_pp) * (eq_pp - ψd)      #15.18
        i_q = (1.0 / Xq_pp) * (-ed_pp - ψq)     #15.18
        τ_e = ψd * i_q - ψq * i_d               #15.6
        out[1] = τm - τ_e #Mechanical Torque
        out[2] = P0 - (V_dq[1] * i_d + V_dq[2] * i_q) #Output Power
        out[3] = Q0 - (V_dq[2] * i_d - V_dq[1] * i_q) #Output Reactive Power
        out[4] = R * i_q - ω0 * ψd + V_dq[2]                                    #15.9 ψq
        out[5] = R * i_d + ω0 * ψq + V_dq[1]                                    #15.9 ψd
        out[6] = -eq_p - (Xd - Xd_p - γd) * i_d + (1 - (T_AA / Td0_p)) * Vf0    #15.16 eq_p
        out[7] = -ed_p + (Xq - Xq_p - γq) * i_q                                 #15.16 ed_p
        out[8] = -eq_pp + eq_p - (Xd_p - Xd_pp + γd) * i_d + (T_AA / Td0_p) * Vf0       #15.16 eq_pp
        out[9] = -ed_pp + ed_p + (Xq_p - Xq_pp + γq) * i_q #15.16 ed_pp
    end

    V_dq0 = LITS.ri_dq(δ0) * [V_R; V_I]
    x0 = [δ0, τm0, 1.0, V_dq0[1], V_dq0[2], V_dq0[2], V_dq0[1], V_dq0[2], V_dq0[1]]
    sol = NLsolve.nlsolve(f!, x0)
    if !NLsolve.converged(sol)
        @warn("Initialization in Synch. Machine failed")
    else
        sol_x0 = sol.zero
        #Update terminal voltages
        get_inner_vars(device)[VR_gen_var] = V_R
        get_inner_vars(device)[VI_gen_var] = V_I
        #Update δ and ω of Shaft. Works for every Shaft.
        shaft_ix = get_local_state_ix(device, S)
        shaft_states = @view device_states[shaft_ix]
        shaft_states[1] = sol_x0[1] #δ
        shaft_states[2] = ω0 #ω
        #Update Mechanical and Electrical Torque on Generator
        get_inner_vars(device)[τe_var] = sol_x0[2]
        get_inner_vars(device)[τm_var] = sol_x0[2]
        #Update Vf for AVR in OneDOneQ Machine.
        get_inner_vars(device)[Vf_var] = sol_x0[3]
        #Update states for Machine
        machine_ix = get_local_state_ix(device, PSY.MarconatoMachine)
        machine_states = @view device_states[machine_ix]
        machine_states[1] = sol_x0[4] #ψq
        machine_states[2] = sol_x0[5] #ψd
        machine_states[3] = sol_x0[6] #eq_p
        machine_states[4] = sol_x0[7] #ed_p
        machine_states[5] = sol_x0[8] #eq_pp
        machine_states[6] = sol_x0[9] #ed_pp
        #Update fluxes inner vars
        get_inner_vars(device)[ψq_var] = sol_x0[4]
        get_inner_vars(device)[ψd_var] = sol_x0[5]
    end
end

"""
Initialitation of model of 4-state (Simple Marconato) synchronous machine in Julia.
Refer to Power System Modelling and Scripting by F. Milano for the equations
"""
function initialize_mach_shaft!(
    device_states,
    device::PSY.DynamicGenerator{PSY.SimpleMarconatoMachine, S, A, TG, P},
) where {S <: PSY.Shaft, A <: PSY.AVR, TG <: PSY.TurbineGov, P <: PSY.PSS}
    #PowerFlow Data
    static_gen = PSY.get_static_injector(device)
    P0 = PSY.get_active_power(static_gen)
    Q0 = PSY.get_reactive_power(static_gen)
    Vm = PSY.get_magnitude(PSY.get_bus(static_gen))
    θ = PSY.get_angle(PSY.get_bus(static_gen))
    S0 = P0 + Q0 * 1im
    V_R = Vm * cos(θ)
    V_I = Vm * sin(θ)
    V = V_R + V_I * 1im
    I = conj(S0 / V)

    #Machine Data
    machine = PSY.get_machine(device)
    R = PSY.get_R(machine)
    Xd = PSY.get_Xd(machine)
    Xq = PSY.get_Xq(machine)
    Xd_p = PSY.get_Xd_p(machine)
    Xq_p = PSY.get_Xq_p(machine)
    Xd_pp = PSY.get_Xd_pp(machine)
    Xq_pp = PSY.get_Xq_pp(machine)
    T_AA = PSY.get_T_AA(machine)
    Td0_p = PSY.get_Td0_p(machine)
    γd = PSY.get_γd(machine)
    γq = PSY.get_γq(machine)

    #States of SimpleMarconatoMachine are [1] eq_p, [2] ed_p, [3] eq_pp and [4] ed_pp
    δ0 = angle(V + (R + Xq * 1im) * I)
    ω0 = 1.0
    τm0 = real(V * conj(I))
    #To solve: δ, τm, Vf0, eq_p, ed_p
    function f!(out, x)
        δ = x[1]
        τm = x[2]
        Vf0 = x[3]
        eq_p = x[4]
        ed_p = x[5]
        eq_pp = x[6]
        ed_pp = x[7]

        V_dq = LITS.ri_dq(δ) * [V_R; V_I]
        i_d =
            (1.0 / (R^2 + Xd_pp * Xq_pp)) *
            (Xq_pp * (eq_pp - V_dq[2]) + R * (ed_pp - V_dq[1]))      #15.25
        i_q =
            (1.0 / (R^2 + Xd_pp * Xq_pp)) *
            (-Xd_pp * (ed_pp - V_dq[1]) + R * (eq_pp - V_dq[2]))      #15.25
        Pe = (V_dq[1] + R * i_d) * i_d + (V_dq[2] + R * i_q) * i_q
        out[1] = τm - Pe #Mechanical Torque
        out[2] = P0 - (V_dq[1] * i_d + V_dq[2] * i_q) #Output Power
        out[3] = Q0 - (V_dq[2] * i_d - V_dq[1] * i_q) #Output Reactive Power
        out[4] = -eq_p - (Xd - Xd_p - γd) * i_d + (1 - (T_AA / Td0_p)) * Vf0             #15.16 eq_p
        out[5] = -ed_p + (Xq - Xq_p - γq) * i_q                                         #15.16 ed_p
        out[6] = -eq_pp + eq_p - (Xd_p - Xd_pp + γd) * i_d + (T_AA / Td0_p) * Vf0        #15.16 eq_pp
        out[7] = -ed_pp + ed_p + (Xq_p - Xq_pp + γq) * i_q                              #15.16 ed_pp
    end
    V_dq0 = LITS.ri_dq(δ0) * [V_R; V_I]
    x0 = [δ0, τm0, 1.0, V_dq0[2], V_dq0[1], V_dq0[2], V_dq0[1]]
    sol = NLsolve.nlsolve(f!, x0)
    if !NLsolve.converged(sol)
        @warn("Initialization in Synch. Machine failed")
    else
        sol_x0 = sol.zero
        #Update terminal voltages
        get_inner_vars(device)[VR_gen_var] = V_R
        get_inner_vars(device)[VI_gen_var] = V_I
        #Update δ and ω of Shaft. Works for every Shaft.
        shaft_ix = get_local_state_ix(device, S)
        shaft_states = @view device_states[shaft_ix]
        shaft_states[1] = sol_x0[1] #δ
        shaft_states[2] = ω0 #ω
        #Update Mechanical and Electrical Torque on Generator
        get_inner_vars(device)[τe_var] = sol_x0[2]
        get_inner_vars(device)[τm_var] = sol_x0[2]
        #Update Vf for AVR in OneDOneQ Machine.
        get_inner_vars(device)[Vf_var] = sol_x0[3]
        #Update eq_p and ed_p for Machine
        machine_ix = get_local_state_ix(device, PSY.SimpleMarconatoMachine)
        machine_states = @view device_states[machine_ix]
        machine_states[1] = sol_x0[4] #eq_p
        machine_states[2] = sol_x0[5] #ed_p
        machine_states[3] = sol_x0[6] #eq_pp
        machine_states[4] = sol_x0[7] #ed_pp
    end
end

"""
Initialitation of model of 6-state (Anderson-Fouad) synchronous machine in Julia.
Refer to Power System Modelling and Scripting by F. Milano for the equations
"""
function initialize_mach_shaft!(
    device_states,
    device::PSY.DynamicGenerator{PSY.AndersonFouadMachine, S, A, TG, P},
) where {S <: PSY.Shaft, A <: PSY.AVR, TG <: PSY.TurbineGov, P <: PSY.PSS}
    #PowerFlow Data
    static_gen = PSY.get_static_injector(device)
    P0 = PSY.get_active_power(static_gen)
    Q0 = PSY.get_reactive_power(static_gen)
    Vm = PSY.get_magnitude(PSY.get_bus(static_gen))
    θ = PSY.get_angle(PSY.get_bus(static_gen))
    S0 = P0 + Q0 * 1im
    V_R = Vm * cos(θ)
    V_I = Vm * sin(θ)
    V = V_R + V_I * 1im
    I = conj(S0 / V)

    #Machine Data
    machine = PSY.get_machine(device)
    R = PSY.get_R(machine)
    Xd = PSY.get_Xd(machine)
    Xq = PSY.get_Xq(machine)
    Xd_p = PSY.get_Xd_p(machine)
    Xq_p = PSY.get_Xq_p(machine)
    Xd_pp = PSY.get_Xd_pp(machine)
    Xq_pp = PSY.get_Xq_pp(machine)

    #States of Anderson-Fouad are [1] ψq, [2] ψd, [3] eq_p, [4] ed_p, [5] eq_pp and [6] ed_pp
    δ0 = angle(V + (R + Xq * 1im) * I)
    ω0 = 1.0
    τm0 = real(V * conj(I))
    #To solve: δ, τm, Vf0, eq_p, ed_p
    function f!(out, x)
        δ = x[1]
        τm = x[2]
        Vf0 = x[3]
        ψq = x[4]
        ψd = x[5]
        eq_p = x[6]
        ed_p = x[7]
        eq_pp = x[8]
        ed_pp = x[9]

        V_dq = LITS.ri_dq(δ) * [V_R; V_I]
        i_d = (1.0 / Xd_pp) * (eq_pp - ψd)      #15.18
        i_q = (1.0 / Xq_pp) * (-ed_pp - ψq)     #15.18
        τ_e = ψd * i_q - ψq * i_d               #15.6
        out[1] = τm - τ_e #Mechanical Torque
        out[2] = P0 - (V_dq[1] * i_d + V_dq[2] * i_q) #Output Power
        out[3] = Q0 - (V_dq[2] * i_d - V_dq[1] * i_q) #Output Reactive Power
        out[4] = R * i_q - ω0 * ψd + V_dq[2]                                    #15.9 ψq
        out[5] = R * i_d + ω0 * ψq + V_dq[1]                                    #15.9 ψd
        out[6] = -eq_p + (Xd - Xd_p) * i_d + Vf0           #15.19 eq_p
        out[7] = -ed_p + (Xq - Xq_p) * i_q                 #15.19 ed_p
        out[8] = -eq_pp + eq_p - (Xd_p - Xd_pp) * i_d      #15.19 eq_pp
        out[9] = -ed_pp + ed_p + (Xq_p - Xq_pp) * i_q      #15.19 ed_pp
    end

    V_dq0 = LITS.ri_dq(δ0) * [V_R; V_I]
    x0 = [δ0, τm0, 1.0, V_dq0[1], V_dq0[2], V_dq0[2], V_dq0[1], V_dq0[2], V_dq0[1]]
    sol = NLsolve.nlsolve(f!, x0)
    if !NLsolve.converged(sol)
        @warn("Initialization in Synch. Machine failed")
    else
        sol_x0 = sol.zero
        #Update terminal voltages
        get_inner_vars(device)[VR_gen_var] = V_R
        get_inner_vars(device)[VI_gen_var] = V_I
        #Update δ and ω of Shaft. Works for every Shaft.
        shaft_ix = get_local_state_ix(device, S)
        shaft_states = @view device_states[shaft_ix]
        shaft_states[1] = sol_x0[1] #δ
        shaft_states[2] = ω0 #ω
        #Update Mechanical and Electrical Torque on Generator
        get_inner_vars(device)[τe_var] = sol_x0[2]
        get_inner_vars(device)[τm_var] = sol_x0[2]
        #Update Vf for AVR in OneDOneQ Machine.
        get_inner_vars(device)[Vf_var] = sol_x0[3]
        #Update states for Machine
        machine_ix = get_local_state_ix(device, PSY.AndersonFouadMachine)
        machine_states = @view device_states[machine_ix]
        machine_states[1] = sol_x0[4] #ψq
        machine_states[2] = sol_x0[5] #ψd
        machine_states[3] = sol_x0[6] #eq_p
        machine_states[4] = sol_x0[7] #ed_p
        machine_states[5] = sol_x0[8] #eq_pp
        machine_states[6] = sol_x0[9] #ed_pp
        #Update fluxes inner vars
        get_inner_vars(device)[ψq_var] = sol_x0[4]
        get_inner_vars(device)[ψd_var] = sol_x0[5]
    end
end

"""
Initialitation of model of 4-state (Simple Anderson-Fouad) synchronous machine in Julia.
Refer to Power System Modelling and Scripting by F. Milano for the equations
"""
function initialize_mach_shaft!(
    device_states,
    device::PSY.DynamicGenerator{PSY.SimpleAFMachine, S, A, TG, P},
) where {S <: PSY.Shaft, A <: PSY.AVR, TG <: PSY.TurbineGov, P <: PSY.PSS}
    #PowerFlow Data
    static_gen = PSY.get_static_injector(device)
    P0 = PSY.get_active_power(static_gen)
    Q0 = PSY.get_reactive_power(static_gen)
    Vm = PSY.get_magnitude(PSY.get_bus(static_gen))
    θ = PSY.get_angle(PSY.get_bus(static_gen))
    S0 = P0 + Q0 * 1im
    V_R = Vm * cos(θ)
    V_I = Vm * sin(θ)
    V = V_R + V_I * 1im
    I = conj(S0 / V)

    #Get parameters
    machine = PSY.get_machine(device)
    R = PSY.get_R(machine)
    Xd = PSY.get_Xd(machine)
    Xq = PSY.get_Xq(machine)
    Xd_p = PSY.get_Xd_p(machine)
    Xq_p = PSY.get_Xq_p(machine)
    Xd_pp = PSY.get_Xd_pp(machine)
    Xq_pp = PSY.get_Xq_pp(machine)

    #States of SimpleAndersonFouad are [1] eq_p, [2] ed_p, [3] eq_pp and [4] ed_pp
    δ0 = angle(V + (R + Xq * 1im) * I)
    ω0 = 1.0
    τm0 = real(V * conj(I))
    #To solve: δ, τm, Vf0, eq_p, ed_p
    function f!(out, x)
        δ = x[1]
        τm = x[2]
        Vf0 = x[3]
        eq_p = x[4]
        ed_p = x[5]
        eq_pp = x[6]
        ed_pp = x[7]

        V_dq = LITS.ri_dq(δ) * [V_R; V_I]
        i_d =
            (1.0 / (R^2 + Xd_pp * Xq_pp)) *
            (Xq_pp * (eq_pp - V_dq[2]) + R * (ed_pp - V_dq[1]))      #15.25
        i_q =
            (1.0 / (R^2 + Xd_pp * Xq_pp)) *
            (-Xd_pp * (ed_pp - V_dq[1]) + R * (eq_pp - V_dq[2]))      #15.25
        Pe = (V_dq[1] + R * i_d) * i_d + (V_dq[2] + R * i_q) * i_q
        out[1] = τm - Pe #Mechanical Torque
        out[2] = P0 - (V_dq[1] * i_d + V_dq[2] * i_q) #Output Power
        out[3] = Q0 - (V_dq[2] * i_d - V_dq[1] * i_q) #Output Reactive Power
        out[4] = -eq_p + (Xd - Xd_p) * i_d + Vf0           #15.19 eq_p
        out[5] = -ed_p + (Xq - Xq_p) * i_q                 #15.19 ed_p
        out[6] = -eq_pp + eq_p - (Xd_p - Xd_pp) * i_d      #15.19 eq_pp
        out[7] = -ed_pp + ed_p + (Xq_p - Xq_pp) * i_q      #15.19 ed_pp
    end
    V_dq0 = LITS.ri_dq(δ0) * [V_R; V_I]
    x0 = [δ0, τm0, 1.0, V_dq0[2], V_dq0[1], V_dq0[2], V_dq0[1]]
    sol = NLsolve.nlsolve(f!, x0)
    if !NLsolve.converged(sol)
        @warn("Initialization in Synch. Machine failed")
    else
        sol_x0 = sol.zero
        #Update terminal voltages
        get_inner_vars(device)[VR_gen_var] = V_R
        get_inner_vars(device)[VI_gen_var] = V_I
        #Update δ and ω of Shaft. Works for every Shaft.
        shaft_ix = get_local_state_ix(device, S)
        shaft_states = @view device_states[shaft_ix]
        shaft_states[1] = sol_x0[1] #δ
        shaft_states[2] = ω0 #ω
        #Update Mechanical and Electrical Torque on Generator
        get_inner_vars(device)[τe_var] = sol_x0[2]
        get_inner_vars(device)[τm_var] = sol_x0[2]
        #Update Vf for AVR in OneDOneQ Machine.
        get_inner_vars(device)[Vf_var] = sol_x0[3]
        #Update eq_p and ed_p for Machine
        machine_ix = get_local_state_ix(device, PSY.SimpleAFMachine)
        machine_states = @view device_states[machine_ix]
        machine_states[1] = sol_x0[4] #eq_p
        machine_states[2] = sol_x0[5] #ed_p
        machine_states[3] = sol_x0[6] #eq_pp
        machine_states[4] = sol_x0[7] #ed_pp
    end
end

#=
"""
Initialitation of model of 5-state (Kundur) synchronous machine in Julia.
Refer to Power System Modelling and Scripting by F. Milano for the equations
"""
function initialize_mach_shaft!(
    device_states,
    device::PSY.DynamicGenerator{PSY.FullMachine, S, A, TG, P},
) where {S <: PSY.Shaft, A <: PSY.AVR, TG <: PSY.TurbineGov, P <: PSY.PSS}
    #PowerFlow Data
    static_gen = PSY.get_static_injector(device)
    P0 = PSY.get_active_power(static_gen)
    Q0 = PSY.get_reactive_power(static_gen)
    Vm = PSY.get_magnitude(PSY.get_bus(static_gen))
    θ = PSY.get_angle(PSY.get_bus(static_gen))
    S0 = P0 + Q0 * 1im
    V_R = Vm * cos(θ)
    V_I = Vm * sin(θ)
    V = V_R + V_I * 1im
    I = conj(S0 / V)

    #Machine Data
    machine = PSY.get_machine(device)
    R = PSY.get_R(machine)
    R_f = PSY.get_R_f(machine)
    R_1d = PSY.get_R_1d(machine)
    R_1q = PSY.get_R_1q(machine)
    Xq = PSY.get_L_q(machine)'
    Xd = PSY.get_L_d(machine)
    Xad = PSY.get_L_ad(machine)
    inv_d_fluxlink = PSY.get_inv_d_fluxlink(machine)
    inv_q_fluxlink = PSY.get_inv_q_fluxlink(machine)

    #States of FullMachine are [1] ψd, [2] ψq, [3] ψf , [4] ψ1d, [5] ψ1q
    δ0 = angle(V + (R + Xq * 1im) * I)
    ω0 = 1.0
    τm0 = real(V * conj(I))

    function f!(out, x)
        δ = x[1]
        τm = x[2]
        Vf0 = x[3]
        ψd = x[4]
        ψq = x[5]
        ψf = x[6]
        ψ1d = x[7]
        ψ1q = x[8]

        V_dq = LITS.ri_dq(δ) * [V_R; V_I]
        #Obtain electric currents] using Flux Linkage equations
        i_df1d = inv_d_fluxlink * [ψd; ψf; ψ1d]  #11.18 in Machowski (3.127, 3.130 and 3.131 in Kundur)
        i_q1q = inv_q_fluxlink * [ψq; ψ1q]        #11.19 in Machowski (3.128 and 3.132 in Kundur)
        τ_e = ψd * i_q1q[1] - ψq * i_df1d[1]            #15.6 in Milano or 3.117 in Kundur
        out[1] = τm - τ_e #Mechanical Torque
        out[2] = P0 - (V_dq[1] * i_df1d[1] + V_dq[2] * i_q1q[1]) #Output Power
        out[3] = Q0 - (V_dq[2] * i_df1d[1] - V_dq[1] * i_q1q[1]) #Output Reactive Power
        out[4] = R * i_df1d[1] + ω0 * ψq + V_dq[1]                                    #15.9 ψd
        out[5] = R * i_q1q[1] - ω0 * ψd + V_dq[2]                                    #15.9 ψq
        out[6] = -R_f * i_df1d[2] + Vf0          #15.19 eq_p
        out[7] = -R_1d * i_df1d[3]                #15.19 ed_p
        out[8] = -R_1q * i_q1q[2]        #15.19 eq_pp
    end

    V_dq0 = LITS.ri_dq(δ0) * [V_R; V_I]
    x0 = [δ0, τm0, 1.0, V_dq0[2], -V_dq0[1], 1.0, 0.0, 0.0]
    sol = NLsolve.nlsolve(f!, x0)
    if !NLsolve.converged(sol)
        @warn("Initialization in Synch. Machine failed")
    else
        sol_x0 = sol.zero
        #Update terminal voltages
        get_inner_vars(device)[VR_gen_var] = V_R
        get_inner_vars(device)[VI_gen_var] = V_I
        #Update δ and ω of Shaft. Works for every Shaft.
        shaft_ix = get_local_state_ix(device, S)
        shaft_states = @view device_states[shaft_ix]
        shaft_states[1] = sol_x0[1] #δ
        shaft_states[2] = ω0 #ω
        #Update Mechanical and Electrical Torque on Generator
        get_inner_vars(device)[τe_var] = sol_x0[2]
        get_inner_vars(device)[τm_var] = sol_x0[2]
        #Update Vf for AVR in OneDOneQ Machine.
        get_inner_vars(device)[Vf_var] = sol_x0[3]
        #Update states for Machine
        machine_ix = get_local_state_ix(device, PSY.FullMachine)
        machine_states = @view device_states[machine_ix]
        machine_states[1] = sol_x0[4] #ψd
        machine_states[2] = sol_x0[5] #ψq
        machine_states[3] = sol_x0[6] #ψf
        machine_states[4] = sol_x0[7] #ψ1d
        machine_states[5] = sol_x0[8] #ψ1q
        #Update fluxes inner vars
        get_inner_vars(device)[ψd_var] = sol_x0[4]
        get_inner_vars(device)[ψq_var] = sol_x0[5]
    end
end
=#


text:
module SeqBounds

    using Distributions, Roots, PrettyTables

    import Base:show

    export bounds

    include("functions.jl")

end # module

ext: jl


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct PacketCaptureListResult <: SwaggerModel
    value::Any # spec type: Union{ Nothing, Vector{PacketCaptureResult} } # spec name: value

    function PacketCaptureListResult(;value=nothing)
        o = new()
        validate_property(PacketCaptureListResult, Symbol("value"), value)
        setfield!(o, Symbol("value"), value)
        o
    end
end # type PacketCaptureListResult

const _property_map_PacketCaptureListResult = Dict{Symbol,Symbol}(Symbol("value")=>Symbol("value"))
const _property_types_PacketCaptureListResult = Dict{Symbol,String}(Symbol("value")=>"Vector{PacketCaptureResult}")
Base.propertynames(::Type{ PacketCaptureListResult }) = collect(keys(_property_map_PacketCaptureListResult))
Swagger.property_type(::Type{ PacketCaptureListResult }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_PacketCaptureListResult[name]))}
Swagger.field_name(::Type{ PacketCaptureListResult }, property_name::Symbol) =  _property_map_PacketCaptureListResult[property_name]

function check_required(o::PacketCaptureListResult)
    true
end

function validate_property(::Type{ PacketCaptureListResult }, name::Symbol, val)
end


text:
@testset "Potential" begin
    # CarrierCapture.harmonic potential generation and finding the crossing
    Qmin = -25
    Qmax = 35
    NQ = 3000
    Q = range(Qmin, stop=Qmax, length=NQ)
    nev = 30
    hw = 0.02

    pot1 = potential(); pot1.name = "pot1"
    pot1.Q0 = 0; pot1.E0 = 1
    pot1.nev = nev
    pot1.func = x -> CarrierCapture.harmonic(x, hw; E₀ = pot1.E0, Q₀ = pot1.Q0)
    pot1.Q = Q
    pot1.E = pot1.func.(Q)

    pot2 = potential(); pot2.name = "pot2"
    pot2.Q0 = 2; pot2.E0 = 0
    pot2.nev = nev
    pot2.func = x -> CarrierCapture.harmonic(x, hw; E₀ = pot2.E0, Q₀ = pot2.Q0)
    pot2.Q = Q
    pot2.E = pot2.func.(Q)

    solve_pot!(pot1)
    solve_pot!(pot2)

    # eigenvalue test
    @test isapprox(pot1.ϵ, 1 .+ pot2.ϵ ; rtol=1E-5)

    Qx, Ex = find_crossing(pot1, pot2)
    @test Qx ≈ -4.22519859246400
    @test Ex ≈ 1.8541447195665985

    # Spline fit test
    nev = 60
    name = "D"

    Q1 = [30.66721918 29.860133 29.05306268 28.24612992 27.43911044 26.63197583 25.82507425 25.01797262 24.21096115 23.40387798 22.59690043 21.78991117 20.98281579 20.17570172 19.36884219 18.56169249 17.75463179 16.94772679 16.14061031 15.33347439 14.52663309 13.71945696 12.91240658 12.10544441 11.29841968 10.4913338 9.684370388 8.877289725 8.070184138]
    E1 = [8.0902 7.5970 7.0749 6.5242 5.9461 5.3451 4.7300 4.1147 3.5182 2.9637 2.4769 2.0819 1.7972 1.6315 1.5800 1.6237 1.7301 1.8586 1.9687 2.0283 2.0190 2.0673 1.9910 2.0528 1.9730 2.0857 2.4550 3.1653 4.3448]

    pot = potential(); pot.name = name
    pot.nev = nev
    pot.Q0 = Q1[findmin(E1)[2]]; pot.E0 = 1.69834
    pot.QE_data = DataFrame(Q = Q1[:], E = E1[:])
    pot.QE_data.E .+= - minimum(pot.QE_data.E) + pot.E0
    pot.Q = Q

    pot.func_type = "spline"
    ## spline fitting parameters
    params = Dict()
    params["order"] = 4
    params["smoothness"] = 0.001
    params["weight"] = [1 1 1 1 1 0.5 0.4 0.4 0.5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]

    fit_pot!(pot, Q; params=params)
    @test pot.E == pot.func(Q)

    fit_pot!(pot, Q)
    @test pot.E == pot.func(Q)

    pot.func_type = "bspline"
    fit_pot!(pot, Q)
    @test pot.E == pot.func(Q)

    pot.func_type = "polyfunc"
    params["poly_order"] = 4
    params["p0"] = [1, 2, 3, 4, 6]
    fit_pot!(pot, Q; params=params)
    @test pot.E ≈ pot.func(Q) atol = 1e-8

    # potential types
    # CarrierCapture.harmonic
    # double well
    # polyfunc
    # morse
    # get_spline
    # get_bspline
end


text:
# !! auto-generated code, do not edit !!
module apriltag_ros
using RobotOSData.Messages
using RobotOSData.StdMsgs
using RobotOSData.CommonMsgs
struct AprilTagDetection <: Readable
    id::Vector{Int32}
    size::Vector{Float64}
    pose::geometry_msgs.PoseWithCovarianceStamped
end
struct AprilTagDetectionArray <: Readable
    header::std_msgs.Header
    detections::Vector{AprilTagDetection}
end
end


text:
module TestFold

include("../preamble.jl")
using Distributed: @everywhere
using InitialValues: INIT

const add = let fname = gensym(:add)
    @everywhere $fname(a, b) = a + b
    getproperty(Main, fname)
end
const parseint = Base.Fix1(parse, Int)

@testset "$fold" for fold in all_folds()
    @testset "no init" begin
        @test fold(+, Map(identity), 1:4) == 10
        @test fold(add, Map(identity), 1:4) == 10
        @test fold(+, Map(parseint), "1234") == 10
        @test fold(add, Map(parseint), "1234") == 10
        @test_throws EmptyResultError fold(+, Map(identity), 1:0)
    end
    @testset "INIT" begin
        @test fold(add, Map(identity), 1:4; init = INIT) == 10
        @test fold(add, Map(parseint), "1234"; init = INIT) == 10
    end
    @testset "IdentityTransducer" begin
        @test fold(+, IdentityTransducer(), 1:10) == sum(1:10)
    end
    @testset "GroupBy" begin
        @test fold(right, GroupBy(isodd, Map(last), +), 1:10) ==
              Dict(true => 25, false => 30)
    end
    @testset "StepRange{UInt64, UInt64}" begin
        @test fold(min, Map(identity), UInt64(0):typemax(UInt64)÷128:typemax(UInt64)) == 0
    end
    if fold ∉ (simple_reduce, random_reduce, foldxd_bs1, foldxd)
        @testset "NoAdjoint" begin
            @test fold(
                +,
                Map(identity),
                Transducers.NoAdjoint(x for x in 1:10 if isodd(x)),
            ) == sum(1:2:10)
        end
    end
end

@testset "$fold" for fold in inprocess_folds()
    # TODO: test them with `foldxd` (don't use local functions)
    @testset "AdHocRF" begin
        averaging =
            function add_average((sum, count), x)
                (sum + x, count + 1)
            end |>
            wheninit() do
                (Init(+), 0)
            end |>
            whencombine() do (sum1, count1), (sum2, count2)
                (sum1 + sum2), (count1 + count2)
            end |>
            whencomplete() do (sum, count)
                sum / count
            end
        @test fold(averaging, Filter(isodd), 1:5) === 3.0
        @test fold(averaging, Filter(isodd), 1:50) === 25.0

        averaging2 =
            function merge_average((sum1, count1), (sum2, count2))
                (sum1 + sum2, count1 + count2)
            end |>
            whencomplete() do (sum, count)
                sum / count
            end |>
            Map(x -> (x, 1))'
        @test fold(averaging2, Filter(isodd), 1:5) === 3.0
        @test fold(averaging2, Filter(isodd), 1:50) === 25.0
    end

    # TODO: make them work with `foldxd`
    @testset "dict" begin
        dict = Dict(zip("1234", 1:4))
        @test fold(+, Map(last), dict) == 10
        @test fold(add, Map(last), dict) == 10
        @test fold(+, Map(parseint ∘ first), dict) == 10
        @test fold(add, Map(parseint ∘ first), dict) == 10
    end
end

# TODO: make them work with `foldxd`
@testset "$fold" for fold in [foldxt_bs1, foldxt]
    @testset "eduction" begin
        @test fold(+, eduction(x for x in 1:10 if isodd(x))) == 25
        @test fold(+, Map(identity), eduction(x for x in 1:10 if isodd(x))) == 25
        @test fold(right, eduction(x for x in 1:10 if isodd(x))) == 9
        @test fold(right, Map(identity), eduction(x for x in 1:10 if isodd(x))) == 9
    end
end

@testset "$fold" for fold in [foldxl, foldxt, foldxd]
    foldxl = foldl = nothing  # don't use
    @test fold(TeeRF(min, max), [5, 2, 6, 8, 3]) === (2, 8)
    @test [5, 2, 6, 8, 3] |> fold(TeeRF(min, max)) === (2, 8)
    @test 1:5 |> Filter(isodd) |> fold(+) == 9
end

@testset "$ex" for ex in [SequentialEx, ThreadedEx, DistributedEx]
    fold = Transducers.fold
    @test transduce(Map(identity), min, Init(min), [5, 2, 6, 8, 3], ex()) === 2
    @test transduce(Map(-), max, Init(max), [5, 2, 6, 8, 3], ex()) === -2
    @test fold(min, [5, 2, 6, 8, 3], ex()) === 2
    @test fold(TeeRF(min, max), [5, 2, 6, 8, 3], ex()) === (2, 8)
    @testset "PartitionBy" begin
        # Testing that DistributedEx can handle a stateful transducer based on
        # an anonymous functions defined in Main:
        itr = @eval Main 1:10 |> $PartitionBy(x -> x ÷ 3) |> $Map(first)
        @test itr |> fcollect(ex()) == [1, 3, 6, 9]
    end
end

@testset "default executor" begin
    @test Transducers.fold(min, [5, 2, 6, 8, 3]) === 2
    @test [5, 2, 6, 8, 3] |> Transducers.fold(min) === 2
end

end  # module


text:
# rewrite.jl - expression pattern matching and rewriting.
#
# The general idea behind functions in this file is to provide easy means
# of finding specific pieces of expressions and using them elsewhere.
# At the time of writing it is used in 2 parts of this package:
#
# * for applyging derivatives, e.g. `x^n` ==> `n*x^(n-1)`
# * for expression simplification, e.g. `1 * x` ==> `x`
#
# Pieces of expression are matched to so-called placeholders - symbols that either
# start with `_` (e.g. `_x`) or are passed via `phs` paraneter, or set globally
# using `set_default_placeholders(::Set{Symbol})`. Using list of placeholders
# instead of _-prefixed names is convenient when writing a lot of transformation
# rules where using underscores creates unnecessary noise.

const Symbolic = Union{Expr, Symbol}
const Numeric = Union{Number, Array}

## pattern matching

const DEFAULT_PHS = [Set{Symbol}()]
set_default_placeholders(set::Set{Symbol}) = (DEFAULT_PHS[1] = set)

isplaceholder(x, phs) = false
isplaceholder(x::Symbol, phs) = (startswith(string(x), "_")
                                 || in(x, phs))
# isplaceholder(ex::Expr, phs) = ex.head == :... && isplaceholder(ex.args[1], phs)

function find_key(d::Dict{K, V}, val) where {K,V}
    r = nothing
    for (k,v) in d
        if v == val
            r = k
            break
        end
    end
    return r
end

function matchex!(m::Dict{Symbol,Any}, p::QuoteNode, x::QuoteNode;
                  opts...)
    return matchex!(m, p.value, x.value)
end

function matchex!(m::Dict{Symbol,Any}, ps::Vector, xs::Vector; opts...)
    opts = to_dict(opts)
    phs = get(opts, :phs, Set([]))
    length(ps) <= length(xs) || return false
    for i in eachindex(ps)
        if isa(ps[i], Expr) && ps[i].head == :... && isplaceholder(ps[i].args[1], phs)
            p = ps[i].args[1]
            haskey(m, p) && m[p] != xs[i] && m[p] != xs[i:end] && return false
            # TODO: add something here?
            m[p] = xs[i:end]
            return true
        else
            matchex!(m, ps[i], xs[i]; opts...) || return false
        end
    end
    # matched everything, didn't encounter dots expression
    return length(ps) == length(xs)
end

function matchex!(m::Dict{Symbol,Any}, p, x; phs=DEFAULT_PHS[1], allow_ex=true, exact=false)
    allow_ex = exact ? false : allow_ex  # override allow_ex=false if exact==true
    if isplaceholder(p, phs)
        if haskey(m, p) && m[p] != x
            # different bindings to the same pattern, treat as no match
            return false
        elseif !allow_ex && isa(x, Expr)
            # x is expression, but matching to expression is not allowed, treat as no match
            return false
        elseif exact
            k = find_key(m, x)
            if k != p
                return false
            else
                m[p] = x
                return true
            end
        else
            m[p] = x
            return true
        end
    elseif isa(p, Expr) && isa(x, Expr)
        return (matchex!(m, p.head, x.head) &&
                matchex!(m, p.args, x.args; phs=phs, allow_ex=allow_ex, exact=exact))
    else
        return p == x
    end
end

"""
Match expression `ex` to a pattern `pat`, return nullable dictionary of matched
symbols or rpatpressions.
Example:

```
ex = :(u ^ v)
pat = :(_x ^ _n)
matchex(pat, ex)
# ==> Union{ Dict{Symbol,Any}(:_n=>:v,:_x=>:u), Void }
```

NOTE: two symbols match if they are equal or symbol in pattern is a placeholder.
Placeholder is any symbol that starts with '_'. It's also possible to pass
list of placeholder names (not necessarily starting wiht '_') via `phs` parameter:

```
ex = :(u ^ v)
pat = :(x ^ n)
matchex(pat, ex; phs=Set([:x, :n]))
# ==> Union{ Dict{Symbol,Any}(:n=>:v,:x=>:u), Void }
```

Several elements may be matched using `...` expression, e.g.:

```
ex = :(A[i, j, k])
pat = :(x[I...])
matchex(pat, ex; phs=Set([:x, :I]))
# ==> Union{ Dict(:x=>:A, :I=>[:i,:j,:k]), Void }
```

Optional parameters:

 * phs::Set{Symbol} = DEFAULT_PHS[1]
       A set of placeholder symbols
 * allow_ex::Boolean = true
       Allow matchinng of symbol pattern to an expression. Example:

           matchex(:(_x + 1), :(a*b + 1); allow_ex=true)  # ==> matches
           matchex(:(_x + 1), :(a*b + 1); allow_ex=false)  # ==> doesn't match
 * exact::Boolean = false
       Allow matching of the same expression to different keys

           matchex(:(_x + _y), :(a + a); exact=false) # ==> matches
           matchex(:(_x = _y), :(a + a); exact=true)  # ==> doesn't match

"""
function matchex(pat, ex; opts...)
    m = Dict{Symbol,Any}()
    res = matchex!(m, pat, ex; opts...)
    if res
        return m
    else
        return nothing
    end
end

"""
Check if expression matches pattern. See `matchex()` for details.
"""
function matchingex(pat, ex; opts...)
    return matchex(pat, ex; opts...) != nothing
end

## find rpatpression

function findex!(res::Vector, pat, ex; phs=DEFAULT_PHS[1])
    if matchingex(pat, ex; phs=phs)
        push!(res, ex)
    elseif expr_like(ex)
        for arg in ex.args
            findex!(res, pat, arg; phs=phs)
        end
    end
end

"""
Find sub-expressions matching a pattern. Example:

    ex = :(a * f(x) + b * f(y))
    pat = :(f(_))
    findex(pat, ex)   # ==> [:(f(x)), :(f(y))]

"""
function findex(pat, ex; phs=DEFAULT_PHS[1])
    res = Any[]
    findex!(res, pat, ex; phs=phs)
    return res
end

## substitution

"""
Given a list of expression arguments, flatten the dotted ones. Example:

    args = [:foo, :([a, b, c]...)]
    flatten_dots(args)
    # ==> [:foo, :a, :b, :c]
"""
function flatten_dots(args::Vector)
    new_args = Vector{Any}()
    for arg in args
        if isa(arg, Expr) && arg.head == :... && isa(arg.args[1], AbstractArray)
            for x in arg.args[1]
                push!(new_args, x)
            end
        else
            push!(new_args, arg)
        end
    end
    return new_args
end

"""
Substitute symbols in `ex` according to substitute table `st`.
Example:

    ex = :(x ^ n)
    subs(ex, x=2)            # ==> :(2 ^ n)

alternatively:

    subs(ex, Dict(:x => 2))  # ==> :(2 ^ n)

If `ex` contains a :(xs...) argument and `st` contains an array-valued
sabstitute for it, the substitute will be flattened:

    ex = :(foo(xs...))
    subs(ex, Dict(:xs => [:a, :b, :c]))
    # ==> :(foo(a, b, c))
"""
function subs(ex::Expr, st::Dict)
    if haskey(st, ex)
        return st[ex]
        # elseif ex.head == :... && haskey(st, ex.args[1])
    else
        new_args = [subs(arg, st) for arg in ex.args]
        new_args = flatten_dots(new_args)
        return Expr(ex.head, new_args...)
    end
end

function subs(s::Symbol, st::Dict)
    return haskey(st, s) ? st[s] : s
end

subs(q::QuoteNode, st::Dict) = QuoteNode(subs(q.value, st))
subs(x::Any, st::Dict) = x
subs(ex; st...) = subs(ex, to_dict(st))

## remove rpatpression

"""
Remove rpatpression conforming to a pattern.
Example:

    ex = :(x * (m == n))
    pat = :(_i == _j)
    ex = without(ex, pat)  # ==> :x
"""
function without(ex::Expr, pat; phs=DEFAULT_PHS[1])
    new_args_without = [without(arg, pat; phs=phs) for arg in ex.args]
    new_args = filter(arg -> !matchingex(pat, arg; phs=phs), new_args_without)
    if ex.head == :call && length(new_args) == 2 &&
        (ex.args[1] == :+ || ex.args[1] == :*)
        # pop argument of now-single-valued operation
        # TODO: make more general, e.g. handle (x - y) with x removed
        return new_args[2]
    elseif ex.head == :call && length(new_args) == 1 && ex.args[1] == :*
        return 1.0
    elseif ex.head == :call && length(new_args) == 1 && ex.args[1] == :+
        return 0.0
    else
        return Expr(ex.head, new_args...) |> simplify
    end
end

without(x, pat; phs=DEFAULT_PHS[1]) = x

## rewriting

"""
rewrite(ex, pat, rpat)

Rewrite expression `ex` according to a transform from pattern `pat`
to a substituting expression `rpat`.
Example (derivative of x^n):

    ex = :(u ^ v)
    pat = :(_x ^ _n)
    rpat = :(_n * _x ^ (_n - 1))
    rewrite(ex, pat, rpat) # ==> :(v * u ^ (v - 1))
"""
function rewrite(ex::Symbolic, pat::Symbolic, rpat::Any; opts...)
    st = matchex(pat, ex; opts...)
    if st == nothing
        error("Expression $ex doesn't match pattern $pat")
    else
        return subs(rpat, st)
    end
end

"""
Same as rewrite, but returns Union{Expr, Void} and doesn't throw an error
when expression doesn't match pattern
"""
function tryrewrite(ex::Symbolic, pat::Symbolic, rpat::Any; opts...)
    st = matchex(pat, ex; opts...)
    if st == nothing
        return nothing
    else
        return subs(rpat, st)
    end
end

"""
rewrite_all(ex, rules)

Recursively rewrite an expression according to a list of rules like [pat => rpat]
Example:

    ex = :(foo(bar(foo(A))))
    rules = [:(foo(x)) => :(quux(x)),
             :(bar(x)) => :(baz(x))]
    rewrite_all(ex, rules; phs=[:x])
    # ==> :(quux(baz(quux(A))))
"""
function rewrite_all(ex::Symbolic, rules; opts...)
    new_ex = ex
    if isa(ex, Expr)
        new_args = [rewrite_all(arg, rules; opts...)
                    for arg in ex.args]
        new_ex = Expr(ex.head, new_args...)
    end
    for (pat, rpat) in rules
        if matchingex(pat, new_ex; opts...)
            new_ex = rewrite(new_ex, pat, rpat; opts...)
        end
    end
    return new_ex
end

"""
rewrite_all(ex, pat, rpat)

Recursively rewrite all occurrences of a pattern in an expression.
Example:

    ex = :(foo(bar(foo(A))))
    pat = :(foo(x))
    rpat = :(quux(x))
    rewrite_all(ex, pat, rpat; phs=[:x])
    # ==> :(quux(bar(quux(A))))
"""
function rewrite_all(ex::Symbolic, pat::Symbolic, rpat; opts...)
    return rewrite_all(ex, [pat => rpat]; opts...)
end

rewrite_all(x, pat, rpat; opts...) = x
rewrite_all(x, rules; opts...) = x


text:
include("./Load_packages.jl")
include("./Load_structures.jl")
include("./Load_data.jl")
include("./Load_functions.jl")

max_stars_repo_name: nimazzi/PlanModelDet

max_issues_repo_name: nimazzi/PlanModelDet

max_forks_repo_name: nimazzi/PlanModelDet


text:
function _update_all_methods_for_extensibleunion!(@nospecialize(u))
    global _registry_extensibleunion_to_genericfunctions
    for f in _registry_extensibleunion_to_genericfunctions[u]
        _update_all_methods_for_extensiblefunction!(f)
    end
    return u
end
function _update_all_methods_for_extensibleunion!(@nospecialize(u), p::Pair)
    global _registry_extensibleunion_to_genericfunctions
    for f in _registry_extensibleunion_to_genericfunctions[u]
        _update_all_methods_for_extensiblefunction!(f, p)
    end
    return u
end

function _update_all_methods_for_extensiblefunction!(@nospecialize(f))
    global _registry_genericfunctions_to_extensibleunions
    extensibleunions_for_this_genericfunction =
        _registry_genericfunctions_to_extensibleunions[f]
    for met in methods(f).ms
        _update_single_method!(f,
                               met.sig,
                               extensibleunions_for_this_genericfunction)
    end
    return f
end
function _update_all_methods_for_extensiblefunction!(@nospecialize(f), p::Pair)
    global _registry_genericfunctions_to_extensibleunions
    extensibleunions_for_this_genericfunction =
        _registry_genericfunctions_to_extensibleunions[f]
    for met in methods(f).ms
        _update_single_method!(f,
                               met.sig,
                               extensibleunions_for_this_genericfunction,
                               p)
    end
    return f
end

function _update_single_method!(@nospecialize(f::Function),
                                @nospecialize(oldsig::Type{<:Tuple}),
                                @nospecialize(unions::Set))
    global _registry_extensibleunion_to_members
    newsig = _replace_types(oldsig)
    for u in unions
        newsig = _replace_types(newsig, u =>
            _set_to_union(_registry_extensibleunion_to_members[u]))
    end
    if oldsig == newsig
    else
        oldsig_tuple = tuple(oldsig.types[2:end]...)
        newsig_tuple = tuple(newsig.types[2:end]...)
        @assert length(code_lowered(f, oldsig_tuple)) == 1
        codeinfo = code_lowered(f, oldsig_tuple)[1]
        @assert length(methods(f, oldsig_tuple).ms) == 1
        oldmet = methods(f, oldsig_tuple).ms[1]
        Base.delete_method(oldmet)
        addmethod!(f, newsig_tuple, codeinfo)
    end
    return f
end
function _update_single_method!(@nospecialize(f::Function),
                                @nospecialize(oldsig::Type{<:Tuple}),
                                @nospecialize(unions::Set),
                                p::Pair)
    global _registry_extensibleunion_to_members
    newsig = _replace_types(oldsig, p)
    for u in unions
        newsig = _replace_types(newsig, u =>
            _set_to_union(_registry_extensibleunion_to_members[u]))
    end
    if oldsig == newsig
    else
        oldsig_tuple = tuple(oldsig.types[2:end]...)
        newsig_tuple = tuple(newsig.types[2:end]...)
        @assert length(code_lowered(f, oldsig_tuple)) == 1
        codeinfo = code_lowered(f, oldsig_tuple)[1]
        @assert length(methods(f, oldsig_tuple).ms) == 1
        oldmet = methods(f, oldsig_tuple).ms[1]
        Base.delete_method(oldmet)
        addmethod!(f, newsig_tuple, codeinfo)
    end
    return f
end

function _update_single_method!(@nospecialize(f::Function),
                                @nospecialize(oldsig::Type{<:UnionAll}),
                                @nospecialize(unions::Set))
    throw(MethodError("Not yet implemented for when sig is a UnionAll"))
end
function _update_single_method!(@nospecialize(f::Function),
                                @nospecialize(oldsig::Type{<:UnionAll}),
                                @nospecialize(unions::Set),
                                p::Pair)
    throw(MethodError("Not yet implemented for when sig is a UnionAll"))
end

function _replace_types(sig::Type{<:UnionAll})
    throw(MethodError("Not yet implemented for when sig is a UnionAll"))
end
function _replace_types(sig::Type{<:UnionAll}, p::Pair)
    throw(MethodError("Not yet implemented for when sig is a UnionAll"))
end

# function _replace_types(sig::Core.SimpleVector)
#     v = Any[sig.types...]
#     for i = 2:length(v)
#         v[i] = _replace_types(v[i])
#     end
#     return Core.svec(v...)
# end
# function _replace_types(sig::Core.SimpleVector, p::Pair)
#     v = Any[sig.types...]
#     for i = 2:length(v)
#         v[i] = _replace_types(v[i], p)
#     end
#     return Core.svec(v...)
# end
_peel_unionall(sig) = sig
function _peel_unionall(sig::UnionAll)
    while sig isa UnionAll
        sig = sig.body
    end
    sig
end

@inline _replace_types(sig::TypeVar)  = _replace_types(sig.ub)
function _replace_types(sig::Type{<:Tuple})
    v = Any[_peel_unionall(sig).types...]
    for i = 2:length(v)
        v[i] = _replace_types(v[i])
    end
    return Tuple{v...}
end

@inline _replace_types(sig::TypeVar,  p::Pair) = _replace_types(sig.ub, p)
function _replace_types(sig::Type{<:Tuple}, p::Pair)
    v = Any[_peel_unionall(sig).types...]
    for i = 2:length(v)
        v[i] = _replace_types(v[i], p)
    end
    return Tuple{v...}
end

function _replace_types(::Type{Union{}})
    return Union{}
end
function _replace_types(sig::Type{Union{}}, p::Pair)
    if sig == p[1]
        return p[2]
    else
        return sig
    end
end

function _replace_types(sig::Union)
    union_length = Base.unionlen(sig)
    old_union_members = Base.uniontypes(sig)
    new_union_members = Vector{Any}(undef, union_length)
    for i = 1:union_length
        new_union_members[i] = _replace_types(old_union_members[i])
    end
    new_union = Union{new_union_members...}
    return new_union
end
function _replace_types(sig::Union, p::Pair)
    if sig == p[1]
        return p[2]
    else
        union_length = Base.unionlen(sig)
        old_union_members = Base.uniontypes(sig)
        new_union_members = Vector{Any}(undef, union_length)
        for i = 1:union_length
            new_union_members[i] = _replace_types(old_union_members[i], p)
        end
        new_union = Union{new_union_members...}
        return new_union
    end
end

function _replace_types(sig::Type)
    return sig
end
function _replace_types(sig::Type, p::Pair)
    if sig == p[1]
        return p[2]
    else
        return sig
    end
end

function _set_to_union(s::Set)
    result = Union{}
    for member in s
        result = Union{result, member}
    end
    return result
end


text:
using Revise, FLPDevelopment, BrowseTables

Directory = "/home/beatriz/mainen.flipping.5ht@gmail.com/Flipping/run_task_2/Test"
Directory = "/home/beatriz/mainen.flipping.5ht@gmail.com/Flipping/run_task_2/Dev_raw_data"
DataIndex, p, b, s = process_dataset(Directory)
######### Filtering Datas #############
data = filter(r->r.ExpSession == 1,s)
data[!,:Age] = [x in youngs ? "Young" : "Adult" for x in data.MouseID]
data[!,:Exp_type] = [x in age_exp ? "Development" : "Projections" for x in data.MouseID]
data[!,:Treatment] = [x in cnos_animals ? "CNO" : "SAL" for x in data.MouseID]
data[!,:Gen] = [x in wt_animals ? "WT" : "HET" for x in data.MouseID]
data[!,:Combo] = [g*t for (g,t) in zip(data.Gen, data.Treatment)]
gd = groupby(data,:MouseID)
transform!(gd, :Streak => maximum => :Performance)
CSV.write("/home/beatriz/mainen.flipping.5ht@gmail.com/Flipping/run_task_2/Dev_raw_data/Results_2020-05-24/full_streaks.csv",data)
proj = filter(r -> r.Exp_type == "Projections",data)
CSV.write("/home/beatriz/mainen.flipping.5ht@gmail.com/Flipping/run_task_2/Dev_raw_data/Results_2020-05-24/cno_streaks.csv",proj)
######### Analysis Projection Experiment #########
#data filtering
@df proj scatter(:MouseID, :Performance, group = :Gen,xrotation = 50, yticks = 0:10:300,
    xlabel = "Mouse ID", ylabel = "Trials number")
savefig("/home/beatriz/Documents/Dario_reports/development/performance.pdf");
replace!(proj.PreInterpoke, missing => 0.0) # missing to 0 nothing to worry this data will excluded anyway beacuse it occurs only if they poke just one time
filt = filter(r -> r.Num_pokes > 1 && # at least 2 pokes per trial
    r.Streak > 10 && #exclude the first 10 trials when they have no idea what is going on
    r.PreInterpoke <= 10 && # exclude streaks where the interpoke is longer than 10 seconds
    r.Performance > 49, # exclude animlas that did less than 50 trials in their session
    proj);
### this is for plotting the mean plus sem bar plot ###
df1 = combine(:AfterLast => mean, groupby(filt,[:Combo, :MouseID]))
df2 = combine(:AfterLast_mean => a -> (Mean = mean(a), SEM = sem(a)),groupby(df1,:Combo))
@df df2 bar(:Combo,:Mean, yerror  = :SEM,
    yticks = 0:0.25:4,
    linecolor = :black, markerstrokecolor = :black,
    xlabel = " Gen x Treatment", ylabel = "Pokes After Last Rew, mean + sem")
savefig("/home/beatriz/Documents/Dario_reports/development/50Trials_mean_sem.pdf");
## this is to plot the boxplot ##
@df filt boxplot(:Combo,:AfterLast,xlabel = " Gen x Treatment", ylabel = "Pokes After Last Rew, median + CI")
savefig("/home/beatriz/Documents/Dario_reports/development/50Trials_boxplot.pdf");
## Pokes after last reward stats per trial
hetcno = filter(r -> r.Combo == "HETCNO",filt).AfterLast;
hetsal = filter(r -> r.Combo == "HETSAL",filt).AfterLast;
wtcno = filter(r -> r.Combo == "WTCNO",filt).AfterLast;
pvalue(KSampleADTest(hetcno,hetsal,wtcno))
pvalue(MannWhitneyUTest(hetcno,hetsal))
pvalue(MannWhitneyUTest(wtcno,hetsal))
## Alternative analysis
pvalue(KruskalWallisTest(wtcno,hetsal,wtcno))
pvalue(KruskalWallisTest(hetcno,hetsal))
pvalue(KruskalWallisTest(wtcno,hetsal))
##
df1 = combine([:AfterLast,:Performance, :Gen] => (a,p,g) ->
    (AfterLast = mean(a), Performance = p[1], Gen = g[1]),
    groupby(filt,[:Combo, :MouseID]))
@df df1 boxplot(:Combo,:AfterLast,
    xlabel = " Gen x Treatment",
    ylabel = "Mean After Last Rew by Mouse, median + CI")
savefig("/home/beatriz/Documents/Dario_reports/development/50Trials_boxplotbymouse.pdf");
## Mean pokes after last reward by mouse stats
hetcno = filter(r -> r.Combo == "HETCNO",df1).AfterLast;
hetsal = filter(r -> r.Combo == "HETSAL",df1).AfterLast;
wtcno = filter(r -> r.Combo == "WTCNO",df1).AfterLast;
pvalue(KSampleADTest(hetcno,hetsal,wtcno))
pvalue(MannWhitneyUTest(hetcno,hetsal))
pvalue(MannWhitneyUTest(hetcno,wtcno))
##
@df df1 scatter(:MouseID, :Performance, group = :Combo)
savefig("/home/beatriz/Documents/Dario_reports/development/50Trials_performances.pdf");
################# fraction of errors analysis ###############
gd = groupby(filt, [:MouseID,:Combo])
df1 = combine(:CorrectLeave => x -> (FractionErrors = (1 - length(findall(x))/length(x)) * 100,),gd)
@df df1 boxplot(:Combo,:FractionErrors,
    xlabel = " Gen x Treatment",
    ylabel = "Incorrect leaving percentage by mouse, median + CI" )
savefig("/home/beatriz/Documents/Dario_reports/development/50Trials_Boxplot_errors%.pdf");
##
df2 = combine(:FractionErrors => a -> (Mean = mean(a), SEM = sem(a)),groupby(df1,:Combo))
@df df2 bar(:Combo,:Mean, yerror  = :SEM,
    yticks = 0:0.25:4,
    linecolor = :black, markerstrokecolor = :black,
    xlabel = " Gen x Treatment",
    guidefont = 8,
    ylabel = "Incorrect leaving percentage by mouse \n mean + sem" )
savefig("/home/beatriz/Documents/Dario_reports/development/50Trials_Mean_errors%.pdf");
## Analysis of fraction of errors per trial by mouse
hetcno = filter(r -> r.Combo == "HETCNO",df1).FractionErrors;
hetsal = filter(r -> r.Combo == "HETSAL",df1).FractionErrors;
wtcno = filter(r -> r.Combo == "WTCNO",df1).FractionErrors;
pvalue(KSampleADTest(hetcno,hetsal,wtcno))
pvalue(MannWhitneyUTest(hetcno,hetsal))
pvalue(MannWhitneyUTest(wtcno,hetsal))


text:
"""
    gevfit()

Estimate the GEV parameters by maximum likelihood.

# Implementation

The function uses Nelder-Mead solver implemented in the [Optim.jl](https://github.com/JuliaNLSolvers/Optim.jl)
package to find the point where the log-likelihood is maximal.

The GEV parameters can be modeled as function of covariates as follows:
```math
μ = X₁ × β₁,
```
```math
ϕ = X₂ × β₂,
```
```math
ξ = X₃ × β₃.
```

The covariates are standardized before estimating the parameters to help fit the
 model. They are transformed back on their original scales before returning the
 fitted model.

See also [`gevfit`](@ref) for the other methods, [`gevfitpwm`](@ref), [`gevfitbayes`](@ref) and [`BlockMaxima`](@ref).

"""
function gevfit end

"""
    gevfit(y,
        locationcov = Vector{Variable}(),
        logscalecov = Vector{Variable}(),
        shapecov = Vector{Variable}()
        )

Estimate the GEV parameters.

# Arguments

- `y::Vector{<:Real}`: The vector of block maxima.
- `locationcov::Vector{<:DataItem} = Vector{Variable}()`: The covariates of the location parameter.
- `logscalecov::Vector{<:DataItem} = Vector{Variable}()`: The covariates of the log-scale parameter.
- `shapecov::Vector{<:DataItem} = Vector{Variable}()`: The covariates of the shape parameter.
"""
function gevfit(y::Vector{<:Real};
    locationcov::Vector{<:DataItem} = Vector{Variable}(),
    logscalecov::Vector{<:DataItem} = Vector{Variable}(),
    shapecov::Vector{<:DataItem} = Vector{Variable}())::MaximumLikelihoodEVA

    locationcovstd = standardize.(locationcov)
    logscalecovstd = standardize.(logscalecov)
    shapecovstd = standardize.(shapecov)

    model = BlockMaxima(Variable("y", y), locationcov = locationcovstd, logscalecov = logscalecovstd, shapecov = shapecovstd)

    fittedmodel = fit(model)

    return transform(fittedmodel)

end

"""
    gevfit(y,
        initialvalues,
        locationcov = Vector{Variable}(),
        logscalecov = Vector{Variable}(),
        shapecov = Vector{Variable}()
        )

Estimate the GEV parameters.

# Arguments

- `y::Vector{<:Real}`: the vector of block maxima.
- `initialvalues::Vector{<:Real}`: Vector of parameters initial values.
- `locationcov::Vector{<:DataItem} = Vector{Variable}()`: The covariates of the location parameter.
- `logscalecov::Vector{<:DataItem} = Vector{Variable}()`: The covariates of the log-scale parameter.
- `shapecov::Vector{<:DataItem} = Vector{Variable}()`: The covariates of the shape parameter.
"""
function gevfit(y::Vector{<:Real}, initialvalues::Vector{<:Real};
    locationcov::Vector{<:DataItem} = Vector{Variable}(),
    logscalecov::Vector{<:DataItem} = Vector{Variable}(),
    shapecov::Vector{<:DataItem} = Vector{Variable}(),)::MaximumLikelihoodEVA

    model = BlockMaxima(Variable("y", y), locationcov = locationcov, logscalecov = logscalecov, shapecov = shapecov)

    return fit(model, initialvalues)

end

"""
    gevfit(df::DataFrame,
        datacol::Symbol,
        locationcovid = Vector{Symbol}(),
        logscalecovid = Vector{Symbol}(),
        shapecovid = Vector{Symbol}()
        )

Estimate the GEV parameters.

# Arguments
- `df::DataFrame`: The dataframe containing the data.
- `datacol::Symbol`: The symbol of the column of `df` containing the block maxima data.
- `locationcovid::Vector{Symbol} = Vector{Symbol}()`: The symbols of the columns of `df` containing the covariates of the location parameter.
- `logscalecovid::Vector{Symbol} = Vector{Symbol}()`: The symbols of the columns of `df` containing the covariates of the log-scale parameter.
- `shapecovid::Vector{Symbol} = Vector{Symbol}()`: The symbols of the columns of `df` containing the covariates of the shape parameter.
"""
function gevfit(df::DataFrame, datacol::Symbol;
    locationcovid::Vector{Symbol}=Symbol[],
    logscalecovid::Vector{Symbol}=Symbol[],
    shapecovid::Vector{Symbol}=Symbol[])::MaximumLikelihoodEVA

    locationcovstd = standardize.(buildVariables(df, locationcovid))
    logscalecovstd = standardize.(buildVariables(df, logscalecovid))
    shapecovstd = standardize.(buildVariables(df, shapecovid))

    model = BlockMaxima(Variable(string(datacol), df[:, datacol]), locationcov = locationcovstd, logscalecov = logscalecovstd, shapecov = shapecovstd)

    fittedmodel = fit(model)

    return transform(fittedmodel)

end

"""
    gevfit(df::DataFrame,
        datacol::Symbol,
        locationcovid = Vector{Symbol}(),
        logscalecovid = Vector{Symbol}(),
        shapecovid = Vector{Symbol}()
        )

Estimate the GEV parameters.

# Arguments
- `df::DataFrame`: The dataframe containing the data.
- `datacol::Symbol`: The symbol of the column of `df` containing the block maxima data.
- `initialvalues::Vector{<:Real}`: Vector of parameters initial values.
- `locationcovid::Vector{Symbol} = Vector{Symbol}()`: The symbols of the columns of `df` containing the covariates of the location parameter.
- `logscalecovid::Vector{Symbol} = Vector{Symbol}()`: The symbols of the columns of `df` containing the covariates of the log-scale parameter.
- `shapecovid::Vector{Symbol} = Vector{Symbol}()`: The symbols of the columns of `df` containing the covariates of the shape parameter.
"""
function gevfit(df::DataFrame, datacol::Symbol, initialvalues::Vector{<:Real};
    locationcovid::Vector{Symbol}=Symbol[],
    logscalecovid::Vector{Symbol}=Symbol[],
    shapecovid::Vector{Symbol}=Symbol[])::MaximumLikelihoodEVA

    locationcov = buildVariables(df, locationcovid)
    logscalecov = buildVariables(df, logscalecovid)
    shapecov = buildVariables(df, shapecovid)

    model = BlockMaxima(Variable(string(datacol), df[:, datacol]), locationcov = locationcov, logscalecov = logscalecov, shapecov = shapecov)

    return fit(model, initialvalues)

end

"""
    gevfit(model::BlockMaxima, initialvalues::Vector{<:Real})

Estimate the parameters of the `BlockMaxima` model using the given initialvalues.
"""
function gevfit(model::BlockMaxima, initialvalues::Vector{<:Real})::MaximumLikelihoodEVA

    fit(model, initialvalues)

end


text:
#! format: off

# Julia wrapper for header: highs_c_api.h
# Automatically generated using Clang.jl

function Highs_lpCall(numcol, numrow, numnz, a_format, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue, colvalue, coldual, rowvalue, rowdual, colbasisstatus, rowbasisstatus, modelstatus)
    ccall((:Highs_lpCall, libhighs), HighsInt, (HighsInt, HighsInt, HighsInt, HighsInt, HighsInt, Cdouble, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{HighsInt}), numcol, numrow, numnz, a_format, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue, colvalue, coldual, rowvalue, rowdual, colbasisstatus, rowbasisstatus, modelstatus)
end

function Highs_mipCall(numcol, numrow, numnz, a_format, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue, integrality, colvalue, rowvalue, modelstatus)
    ccall((:Highs_mipCall, libhighs), HighsInt, (HighsInt, HighsInt, HighsInt, HighsInt, HighsInt, Cdouble, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}), numcol, numrow, numnz, a_format, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue, integrality, colvalue, rowvalue, modelstatus)
end

function Highs_qpCall(numcol, numrow, numnz, q_numnz, a_format, q_format, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue, qstart, qindex, qvalue, colvalue, coldual, rowvalue, rowdual, colbasisstatus, rowbasisstatus, modelstatus)
    ccall((:Highs_qpCall, libhighs), HighsInt, (HighsInt, HighsInt, HighsInt, HighsInt, HighsInt, HighsInt, HighsInt, Cdouble, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{HighsInt}), numcol, numrow, numnz, q_numnz, a_format, q_format, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue, qstart, qindex, qvalue, colvalue, coldual, rowvalue, rowdual, colbasisstatus, rowbasisstatus, modelstatus)
end

function Highs_lpDimMpsRead(numcol, numrow, numNz)
    ccall((:Highs_lpDimMpsRead, libhighs), HighsInt, (Ptr{HighsInt}, Ptr{HighsInt}, Ptr{HighsInt}), numcol, numrow, numNz)
end

function Highs_lpDataMpsRead(numcol, numrow, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue)
    ccall((:Highs_lpDataMpsRead, libhighs), HighsInt, (HighsInt, HighsInt, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}), numcol, numrow, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue)
end

function Highs_create()
    ccall((:Highs_create, libhighs), Ptr{Cvoid}, ())
end

function Highs_destroy(highs)
    ccall((:Highs_destroy, libhighs), Cvoid, (Ptr{Cvoid},), highs)
end

function Highs_readModel(highs, filename)
    ccall((:Highs_readModel, libhighs), HighsInt, (Ptr{Cvoid}, Cstring), highs, filename)
end

function Highs_writeModel(highs, filename)
    ccall((:Highs_writeModel, libhighs), HighsInt, (Ptr{Cvoid}, Cstring), highs, filename)
end

function Highs_clearModel(highs)
    ccall((:Highs_clearModel, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_run(highs)
    ccall((:Highs_run, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_writeSolution(highs, filename)
    ccall((:Highs_writeSolution, libhighs), HighsInt, (Ptr{Cvoid}, Cstring), highs, filename)
end

function Highs_writeSolutionPretty(highs, filename)
    ccall((:Highs_writeSolutionPretty, libhighs), HighsInt, (Ptr{Cvoid}, Cstring), highs, filename)
end

function Highs_passLp(highs, numcol, numrow, numnz, a_format, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue)
    ccall((:Highs_passLp, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, HighsInt, HighsInt, HighsInt, HighsInt, Cdouble, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}), highs, numcol, numrow, numnz, a_format, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue)
end

function Highs_passMip(highs, numcol, numrow, numnz, a_format, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue, integrality)
    ccall((:Highs_passMip, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, HighsInt, HighsInt, HighsInt, HighsInt, Cdouble, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{HighsInt}), highs, numcol, numrow, numnz, a_format, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue, integrality)
end

function Highs_passModel(highs, numcol, numrow, numnz, q_num_nz, a_format, q_format, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue, qstart, qindex, qvalue, integrality)
    ccall((:Highs_passModel, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, HighsInt, HighsInt, HighsInt, HighsInt, HighsInt, HighsInt, Cdouble, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{HighsInt}), highs, numcol, numrow, numnz, q_num_nz, a_format, q_format, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue, qstart, qindex, qvalue, integrality)
end

function Highs_passHessian(highs, dim, num_nz, format, start, index, value)
    ccall((:Highs_passHessian, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, HighsInt, HighsInt, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}), highs, dim, num_nz, format, start, index, value)
end

function Highs_setBoolOptionValue(highs, option, value)
    ccall((:Highs_setBoolOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, HighsInt), highs, option, value)
end

function Highs_setIntOptionValue(highs, option, value)
    ccall((:Highs_setIntOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, HighsInt), highs, option, value)
end

function Highs_setDoubleOptionValue(highs, option, value)
    ccall((:Highs_setDoubleOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Cdouble), highs, option, value)
end

function Highs_setStringOptionValue(highs, option, value)
    ccall((:Highs_setStringOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Cstring), highs, option, value)
end

function Highs_setOptionValue(highs, option, value)
    ccall((:Highs_setOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Cstring), highs, option, value)
end

function Highs_getBoolOptionValue(highs, option, value)
    ccall((:Highs_getBoolOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Ptr{HighsInt}), highs, option, value)
end

function Highs_getIntOptionValue(highs, option, value)
    ccall((:Highs_getIntOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Ptr{HighsInt}), highs, option, value)
end

function Highs_getDoubleOptionValue(highs, option, value)
    ccall((:Highs_getDoubleOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Ptr{Cdouble}), highs, option, value)
end

function Highs_getStringOptionValue(highs, option, value)
    ccall((:Highs_getStringOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Cstring), highs, option, value)
end

function Highs_getOptionType(highs, option, type)
    ccall((:Highs_getOptionType, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Ptr{HighsInt}), highs, option, type)
end

function Highs_resetOptions(highs)
    ccall((:Highs_resetOptions, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_writeOptions(highs, filename)
    ccall((:Highs_writeOptions, libhighs), HighsInt, (Ptr{Cvoid}, Cstring), highs, filename)
end

function Highs_writeOptionsDeviations(highs, filename)
    ccall((:Highs_writeOptionsDeviations, libhighs), HighsInt, (Ptr{Cvoid}, Cstring), highs, filename)
end

function Highs_getIntInfoValue(highs, info, value)
    ccall((:Highs_getIntInfoValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Ptr{HighsInt}), highs, info, value)
end

function Highs_getDoubleInfoValue(highs, info, value)
    ccall((:Highs_getDoubleInfoValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Ptr{Cdouble}), highs, info, value)
end

function Highs_getSolution(highs, colvalue, coldual, rowvalue, rowdual)
    ccall((:Highs_getSolution, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}), highs, colvalue, coldual, rowvalue, rowdual)
end

function Highs_getBasis(highs, colstatus, rowstatus)
    ccall((:Highs_getBasis, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{HighsInt}, Ptr{HighsInt}), highs, colstatus, rowstatus)
end

function Highs_getModelStatus(highs)
    ccall((:Highs_getModelStatus, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_getScaledModelStatus(highs)
    ccall((:Highs_getScaledModelStatus, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_getDualRay(highs, has_dual_ray, dual_ray_value)
    ccall((:Highs_getDualRay, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{HighsInt}, Ptr{Cdouble}), highs, has_dual_ray, dual_ray_value)
end

function Highs_getPrimalRay(highs, has_primal_ray, primal_ray_value)
    ccall((:Highs_getPrimalRay, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{HighsInt}, Ptr{Cdouble}), highs, has_primal_ray, primal_ray_value)
end

function Highs_getObjectiveValue(highs)
    ccall((:Highs_getObjectiveValue, libhighs), Cdouble, (Ptr{Cvoid},), highs)
end

function Highs_getBasicVariables(highs, basic_variables)
    ccall((:Highs_getBasicVariables, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{HighsInt}), highs, basic_variables)
end

function Highs_getBasisInverseRow(highs, row, row_vector, row_num_nz, row_indices)
    ccall((:Highs_getBasisInverseRow, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}), highs, row, row_vector, row_num_nz, row_indices)
end

function Highs_getBasisInverseCol(highs, col, col_vector, col_num_nz, col_indices)
    ccall((:Highs_getBasisInverseCol, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}), highs, col, col_vector, col_num_nz, col_indices)
end

function Highs_getBasisSolve(highs, rhs, solution_vector, solution_num_nz, solution_indices)
    ccall((:Highs_getBasisSolve, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}), highs, rhs, solution_vector, solution_num_nz, solution_indices)
end

function Highs_getBasisTransposeSolve(highs, rhs, solution_vector, solution_nz, solution_indices)
    ccall((:Highs_getBasisTransposeSolve, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}), highs, rhs, solution_vector, solution_nz, solution_indices)
end

function Highs_getReducedRow(highs, row, row_vector, row_num_nz, row_indices)
    ccall((:Highs_getReducedRow, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}), highs, row, row_vector, row_num_nz, row_indices)
end

function Highs_getReducedColumn(highs, col, col_vector, col_num_nz, col_indices)
    ccall((:Highs_getReducedColumn, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}), highs, col, col_vector, col_num_nz, col_indices)
end

function Highs_setBasis(highs, colstatus, rowstatus)
    ccall((:Highs_setBasis, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{HighsInt}, Ptr{HighsInt}), highs, colstatus, rowstatus)
end

function Highs_setLogicalBasis(highs)
    ccall((:Highs_setLogicalBasis, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_getRunTime(highs)
    ccall((:Highs_getRunTime, libhighs), Cdouble, (Ptr{Cvoid},), highs)
end

function Highs_addRow(highs, lower, upper, num_new_nz, indices, values)
    ccall((:Highs_addRow, libhighs), HighsInt, (Ptr{Cvoid}, Cdouble, Cdouble, HighsInt, Ptr{HighsInt}, Ptr{Cdouble}), highs, lower, upper, num_new_nz, indices, values)
end

function Highs_addRows(highs, num_new_row, lower, upper, num_new_nz, starts, indices, values)
    ccall((:Highs_addRows, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Ptr{Cdouble}, Ptr{Cdouble}, HighsInt, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}), highs, num_new_row, lower, upper, num_new_nz, starts, indices, values)
end

function Highs_addCol(highs, cost, lower, upper, num_new_nz, indices, values)
    ccall((:Highs_addCol, libhighs), HighsInt, (Ptr{Cvoid}, Cdouble, Cdouble, Cdouble, HighsInt, Ptr{HighsInt}, Ptr{Cdouble}), highs, cost, lower, upper, num_new_nz, indices, values)
end

function Highs_addCols(highs, num_new_col, costs, lower, upper, num_new_nz, starts, indices, values)
    ccall((:Highs_addCols, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, HighsInt, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}), highs, num_new_col, costs, lower, upper, num_new_nz, starts, indices, values)
end

function Highs_changeObjectiveSense(highs, sense)
    ccall((:Highs_changeObjectiveSense, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt), highs, sense)
end

function Highs_changeObjectiveOffset(highs, offset)
    ccall((:Highs_changeObjectiveOffset, libhighs), HighsInt, (Ptr{Cvoid}, Cdouble), highs, offset)
end

function Highs_changeColIntegrality(highs, col, integrality)
    ccall((:Highs_changeColIntegrality, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, HighsInt), highs, col, integrality)
end

function Highs_changeColsIntegralityByRange(highs, from_col, to_col, integrality)
    ccall((:Highs_changeColsIntegralityByRange, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, HighsInt, Ptr{HighsInt}), highs, from_col, to_col, integrality)
end

function Highs_changeColsIntegralityBySet(highs, num_set_entries, set, integrality)
    ccall((:Highs_changeColsIntegralityBySet, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Ptr{HighsInt}, Ptr{HighsInt}), highs, num_set_entries, set, integrality)
end

function Highs_changeColsIntegralityByMask(highs, mask, integrality)
    ccall((:Highs_changeColsIntegralityByMask, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{HighsInt}, Ptr{HighsInt}), highs, mask, integrality)
end

function Highs_changeColCost(highs, col, cost)
    ccall((:Highs_changeColCost, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Cdouble), highs, col, cost)
end

function Highs_changeColsCostByRange(highs, from_col, to_col, cost)
    ccall((:Highs_changeColsCostByRange, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, HighsInt, Ptr{Cdouble}), highs, from_col, to_col, cost)
end

function Highs_changeColsCostBySet(highs, num_set_entries, set, cost)
    ccall((:Highs_changeColsCostBySet, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Ptr{HighsInt}, Ptr{Cdouble}), highs, num_set_entries, set, cost)
end

function Highs_changeColsCostByMask(highs, mask, cost)
    ccall((:Highs_changeColsCostByMask, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{HighsInt}, Ptr{Cdouble}), highs, mask, cost)
end

function Highs_changeColBounds(highs, col, lower, upper)
    ccall((:Highs_changeColBounds, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Cdouble, Cdouble), highs, col, lower, upper)
end

function Highs_changeColsBoundsByRange(highs, from_col, to_col, lower, upper)
    ccall((:Highs_changeColsBoundsByRange, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, HighsInt, Ptr{Cdouble}, Ptr{Cdouble}), highs, from_col, to_col, lower, upper)
end

function Highs_changeColsBoundsBySet(highs, num_set_entries, set, lower, upper)
    ccall((:Highs_changeColsBoundsBySet, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}), highs, num_set_entries, set, lower, upper)
end

function Highs_changeColsBoundsByMask(highs, mask, lower, upper)
    ccall((:Highs_changeColsBoundsByMask, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}), highs, mask, lower, upper)
end

function Highs_changeRowBounds(highs, row, lower, upper)
    ccall((:Highs_changeRowBounds, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Cdouble, Cdouble), highs, row, lower, upper)
end

function Highs_changeRowsBoundsBySet(highs, num_set_entries, set, lower, upper)
    ccall((:Highs_changeRowsBoundsBySet, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}), highs, num_set_entries, set, lower, upper)
end

function Highs_changeRowsBoundsByMask(highs, mask, lower, upper)
    ccall((:Highs_changeRowsBoundsByMask, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}), highs, mask, lower, upper)
end

function Highs_changeCoeff(highs, row, col, value)
    ccall((:Highs_changeCoeff, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, HighsInt, Cdouble), highs, row, col, value)
end

function Highs_getObjectiveSense(highs, sense)
    ccall((:Highs_getObjectiveSense, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{HighsInt}), highs, sense)
end

function Highs_getObjectiveOffset(highs, offset)
    ccall((:Highs_getObjectiveOffset, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{Cdouble}), highs, offset)
end

function Highs_getColsByRange(highs, from_col, to_col, num_col, costs, lower, upper, num_nz, matrix_start, matrix_index, matrix_value)
    ccall((:Highs_getColsByRange, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, HighsInt, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}), highs, from_col, to_col, num_col, costs, lower, upper, num_nz, matrix_start, matrix_index, matrix_value)
end

function Highs_getColsBySet(highs, num_set_entries, set, num_col, costs, lower, upper, num_nz, matrix_start, matrix_index, matrix_value)
    ccall((:Highs_getColsBySet, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}), highs, num_set_entries, set, num_col, costs, lower, upper, num_nz, matrix_start, matrix_index, matrix_value)
end

function Highs_getColsByMask(highs, mask, num_col, costs, lower, upper, num_nz, matrix_start, matrix_index, matrix_value)
    ccall((:Highs_getColsByMask, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}), highs, mask, num_col, costs, lower, upper, num_nz, matrix_start, matrix_index, matrix_value)
end

function Highs_getRowsByRange(highs, from_row, to_row, num_row, lower, upper, num_nz, matrix_start, matrix_index, matrix_value)
    ccall((:Highs_getRowsByRange, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, HighsInt, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}), highs, from_row, to_row, num_row, lower, upper, num_nz, matrix_start, matrix_index, matrix_value)
end

function Highs_getRowsBySet(highs, num_set_entries, set, num_row, lower, upper, num_nz, matrix_start, matrix_index, matrix_value)
    ccall((:Highs_getRowsBySet, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}), highs, num_set_entries, set, num_row, lower, upper, num_nz, matrix_start, matrix_index, matrix_value)
end

function Highs_getRowsByMask(highs, mask, num_row, lower, upper, num_nz, matrix_start, matrix_index, matrix_value)
    ccall((:Highs_getRowsByMask, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}), highs, mask, num_row, lower, upper, num_nz, matrix_start, matrix_index, matrix_value)
end

function Highs_deleteColsByRange(highs, from_col, to_col)
    ccall((:Highs_deleteColsByRange, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, HighsInt), highs, from_col, to_col)
end

function Highs_deleteColsBySet(highs, num_set_entries, set)
    ccall((:Highs_deleteColsBySet, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Ptr{HighsInt}), highs, num_set_entries, set)
end

function Highs_deleteColsByMask(highs, mask)
    ccall((:Highs_deleteColsByMask, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{HighsInt}), highs, mask)
end

function Highs_deleteRowsByRange(highs, from_row, to_row)
    ccall((:Highs_deleteRowsByRange, libhighs), HighsInt, (Ptr{Cvoid}, Cint, HighsInt), highs, from_row, to_row)
end

function Highs_deleteRowsBySet(highs, num_set_entries, set)
    ccall((:Highs_deleteRowsBySet, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Ptr{HighsInt}), highs, num_set_entries, set)
end

function Highs_deleteRowsByMask(highs, mask)
    ccall((:Highs_deleteRowsByMask, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{HighsInt}), highs, mask)
end

function Highs_scaleCol(highs, col, scaleval)
    ccall((:Highs_scaleCol, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Cdouble), highs, col, scaleval)
end

function Highs_scaleRow(highs, row, scaleval)
    ccall((:Highs_scaleRow, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, Cdouble), highs, row, scaleval)
end

function Highs_getInfinity(highs)
    ccall((:Highs_getInfinity, libhighs), Cdouble, (Ptr{Cvoid},), highs)
end

function Highs_getNumCol(highs)
    ccall((:Highs_getNumCol, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_getNumRow(highs)
    ccall((:Highs_getNumRow, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_getNumNz(highs)
    ccall((:Highs_getNumNz, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_getHessianNumNz(highs)
    ccall((:Highs_getHessianNumNz, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_getModel(highs, a_format, q_format, numcol, numrow, numnz, hessian_num_nz, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue, qstart, qindex, qvalue, integrality)
    ccall((:Highs_getModel, libhighs), HighsInt, (Ptr{Cvoid}, HighsInt, HighsInt, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{HighsInt}), highs, a_format, q_format, numcol, numrow, numnz, hessian_num_nz, sense, offset, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue, qstart, qindex, qvalue, integrality)
end

function Highs_crossover(highs)
    ccall((:Highs_crossover, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_crossover_set(highs, n, m, col_value, col_dual, row_dual)
    ccall((:Highs_crossover_set, libhighs), HighsInt, (Ptr{Cvoid}, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}), highs, n, m, col_value, col_dual, row_dual)
end

function Highs_call(numcol, numrow, numnz, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue, colvalue, coldual, rowvalue, rowdual, colbasisstatus, rowbasisstatus, modelstatus)
    ccall((:Highs_call, libhighs), HighsInt, (HighsInt, HighsInt, HighsInt, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{HighsInt}, Ptr{HighsInt}, Ptr{HighsInt}), numcol, numrow, numnz, colcost, collower, colupper, rowlower, rowupper, astart, aindex, avalue, colvalue, coldual, rowvalue, rowdual, colbasisstatus, rowbasisstatus, modelstatus)
end

function Highs_runQuiet(highs)
    ccall((:Highs_runQuiet, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_setHighsLogfile(highs, logfile)
    ccall((:Highs_setHighsLogfile, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{Cvoid}), highs, logfile)
end

function Highs_setHighsOutput(highs, outputfile)
    ccall((:Highs_setHighsOutput, libhighs), HighsInt, (Ptr{Cvoid}, Ptr{Cvoid}), highs, outputfile)
end

function Highs_getIterationCount(highs)
    ccall((:Highs_getIterationCount, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_getSimplexIterationCount(highs)
    ccall((:Highs_getSimplexIterationCount, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_setHighsBoolOptionValue(highs, option, value)
    ccall((:Highs_setHighsBoolOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, HighsInt), highs, option, value)
end

function Highs_setHighsIntOptionValue(highs, option, value)
    ccall((:Highs_setHighsIntOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, HighsInt), highs, option, value)
end

function Highs_setHighsDoubleOptionValue(highs, option, value)
    ccall((:Highs_setHighsDoubleOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Cdouble), highs, option, value)
end

function Highs_setHighsStringOptionValue(highs, option, value)
    ccall((:Highs_setHighsStringOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Cstring), highs, option, value)
end

function Highs_setHighsOptionValue(highs, option, value)
    ccall((:Highs_setHighsOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Cstring), highs, option, value)
end

function Highs_getHighsBoolOptionValue(highs, option, value)
    ccall((:Highs_getHighsBoolOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Ptr{HighsInt}), highs, option, value)
end

function Highs_getHighsIntOptionValue(highs, option, value)
    ccall((:Highs_getHighsIntOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Ptr{HighsInt}), highs, option, value)
end

function Highs_getHighsDoubleOptionValue(highs, option, value)
    ccall((:Highs_getHighsDoubleOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Ptr{Cdouble}), highs, option, value)
end

function Highs_getHighsStringOptionValue(highs, option, value)
    ccall((:Highs_getHighsStringOptionValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Cstring), highs, option, value)
end

function Highs_getHighsOptionType(highs, option, type)
    ccall((:Highs_getHighsOptionType, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Ptr{HighsInt}), highs, option, type)
end

function Highs_resetHighsOptions(highs)
    ccall((:Highs_resetHighsOptions, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_getHighsIntInfoValue(highs, info, value)
    ccall((:Highs_getHighsIntInfoValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Ptr{HighsInt}), highs, info, value)
end

function Highs_getHighsDoubleInfoValue(highs, info, value)
    ccall((:Highs_getHighsDoubleInfoValue, libhighs), HighsInt, (Ptr{Cvoid}, Cstring, Ptr{Cdouble}), highs, info, value)
end

function Highs_getNumCols(highs)
    ccall((:Highs_getNumCols, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_getNumRows(highs)
    ccall((:Highs_getNumRows, libhighs), HighsInt, (Ptr{Cvoid},), highs)
end

function Highs_getHighsInfinity(highs)
    ccall((:Highs_getHighsInfinity, libhighs), Cdouble, (Ptr{Cvoid},), highs)
end

function Highs_getHighsRunTime(highs)
    ccall((:Highs_getHighsRunTime, libhighs), Cdouble, (Ptr{Cvoid},), highs)
end
# Julia wrapper for header: HighsInt.h
# Automatically generated using Clang.jl


text:
using MinkowskiReduction
using Documenter

DocMeta.setdocmeta!(MinkowskiReduction, :DocTestSetup, :(using MinkowskiReduction); recursive=true)

makedocs(;
    modules=[MinkowskiReduction],
    authors="Gus Hart",
    repo="https://github.com/glwhart/MinkowskiReduction.jl/blob/{commit}{path}#{line}",
    sitename="MinkowskiReduction.jl",
    format=Documenter.HTML(;
        prettyurls=get(ENV, "CI", "false") == "true",
        canonical="https://glwhart.github.io/MinkowskiReduction.jl",
        assets=String[],
    ),
    pages=[
        "Home" => "index.md",
    ],
)

deploydocs(;
    repo="github.com/glwhart/MinkowskiReduction.jl",
    devbranch = "main",
    devurl="dev",
    target = "build",
    branch = "gh-pages",
    versions = ["stable" => "v^", "v#.#" ]
)


text:
Base.@kwdef mutable struct Microservice
    target_nodes::Int = 1
    running_nodes::Int = 1
    booting_nodes::Vector{Float64} = Vector{Float64}()
    closing_nodes::Vector{Float64} = Vector{Float64}()
    queue::Vector{Job} = Vector{Job}() # Waiting jobs and jobs being worked on are in this
    boot_time::Float64
    close_time::Float64
    min_scale::Int
    max_scale::Int
    max_queue::Int
    instance_cost::Float64
end

function Base.show(io::IO, ms::Microservice)
    print(io, "MS($(ms.running_nodes)->$(ms.target_nodes), +$(ms.booting_nodes), -$(ms.closing_nodes), $(ms.queue))")
end
function Base.show(io::IO, mss::Vector{Microservice})
    println(io, "Microservices: ")
    for ms in mss
        println(io, ms)
    end
end

function scale(ms::Microservice, a)
    ms.target_nodes = a
    if ms.running_nodes < a
        # We have to few nodes running, check running + booting
        if ms.running_nodes + length(ms.booting_nodes) < a
            # Need more booting
            n_boot = a - ms.running_nodes - length(ms.booting_nodes)
            append!(ms.booting_nodes, fill(ms.boot_time, n_boot))
        elseif a < ms.running_nodes + length(ms.booting_nodes)
            # Too many booting
            n_remove =  length(ms.booting_nodes) - (a - ms.running_nodes)
            deleteat!(ms.booting_nodes, length(ms.booting_nodes) - n_remove + 1 : length(ms.booting_nodes))
            append!(ms.closing_nodes, fill(ms.close_time, n_remove))
        end
    elseif a < ms.running_nodes
        # We have to many nodes, close all booting and any additional
        n_close = ms.running_nodes - a + length(ms.booting_nodes)
        ms.running_nodes = a # Currently we immideately scale down, but this also makes jobs not be worked on
        append!(ms.closing_nodes, fill(ms.close_time, n_close))
        empty!(ms.booting_nodes)
    end
end

max_stars_repo_name: albheim/ServiceMeshControl

max_issues_repo_name: albheim/ServiceMeshControl

max_forks_repo_name: albheim/ServiceMeshControl


text:
using OneClassActiveLearning
using SVDD
using Test
using Random
using JuMP, Ipopt
using MLDataUtils, MLLabelUtils, MLKernels
using ValueHistories
using PyCall
using Statistics
using LinearAlgebra
using Dates
using JSON, Unmarshal
using InteractiveUtils

TEST_SOLVER =  with_optimizer(Ipopt.Optimizer, print_level=0)

Random.seed!(0)

@testset "OneClassActiveLearning" begin
    include("QueryStrategies/qs_test.jl")
    include("data_util_test.jl")
    include("evaluate_test.jl")
    include("setup_test.jl")
    include("serialize_test.jl")
    include("result_test.jl")
end


text:
@forwardfun plot_autocorr
@forwardfun plot_compare
@forwardfun plot_density
@forwardfun plot_dist
@forwardfun plot_elpd
@forwardfun plot_energy
@forwardfun plot_ess
@forwardfun plot_forest
@forwardfun plot_hpd
@forwardfun plot_joint
@forwardfun plot_kde
@forwardfun plot_khat
@forwardfun plot_loo_pit
@forwardfun plot_mcse
@forwardfun plot_pair
@forwardfun plot_parallel
@forwardfun plot_posterior
@forwardfun plot_ppc
@forwardfun plot_rank
@forwardfun plot_trace
@forwardfun plot_violin


text:
module test_GLMakie2

import GLMakie

t = range(0.0, stop=10.0, length=100)

phi  = sin.(t)
phi2 = 0.5 * sin.(t)
w    = cos.(t)
w2   = 0.6 * cos.(t)

LinesLegend(args...) = GLMakie.Legend(args...; margin=[0,0,0,0], padding=[5,5,0,0], rowgap=0, halign=:right, valign=:top,
                                               linewidth=1, labelsize=10, tellheight=false, tellwidth=false)

GLMakie.set_theme!(fontsize = 12)

figure1 = GLMakie.Figure(resolution=(900,700))

        figure1[1,1] = GLMakie.Axis(figure1, title = "axis1", xlabel="xaxis1")
        figure1[2,1] = GLMakie.Axis(figure1, title = "axis2", xlabel="xaxis2")
        figure1[1,2] = GLMakie.Axis(figure1, title = "axis3", xlabel="xaxis3")
axis4 = figure1[2,2] = GLMakie.Axis(figure1)
axis4.title  = "axis4"
axis4.xlabel = "xaxis4"

line1 = GLMakie.lines!(figure1[1,1], t, phi , color="blue1")
line2 = GLMakie.lines!(figure1[2,1], t, phi2, color="red1")
line3 = GLMakie.lines!(figure1[2,1], t, w2  , color=("blue1", 0.3))
line4 = GLMakie.lines!(figure1[1,2], t, w   , color="blue1")
line5 = GLMakie.lines!(axis4, t, w2  , color="blue1")

#@show line1.attributes

figure1[1,1] = LinesLegend(figure1, [line1], ["line1"])
figure1[2,1] = LinesLegend(figure1, [line2, line3], ["line2", "line3"])

figure1[0,:] = GLMakie.Label(figure1, "Heading", textsize = 14)
figure1[1,1,GLMakie.TopLeft()] = GLMakie.Label(figure1, "showFigure(1)", textsize=9, color=:blue, halign = :left, padding = (0, 0, 0, -30))

GLMakie.trim!(  figure1.layout)
GLMakie.update!(figure1.scene)
display(figure1)

end


text: Dict{String, Any}("strings-and-ints" => Any[Dict{String, Any}("value" => "hi", "type" => "string"), Dict{String, Any}("value" => "42", "type" => "integer")])


text:
# Use baremodule to shave off a few KB from the serialized `.ji` file
baremodule Libxc_jll
using Base
using Base: UUID
import JLLWrappers

JLLWrappers.@generate_main_file_header("Libxc")
JLLWrappers.@generate_main_file("Libxc", UUID("a56a6d9d-ad03-58af-ab61-878bf78270d6"))
end  # module Libxc_jll


text:
module LITS

####################################### Structs Exports ####################################
#AVR Exports
export AVR
export AVRFixed
export AVRSimple
export AVRTypeI
export AVRTypeII
export AVRTypeIIManual

#Machine Exports
export Machine
export BaseMachine
export OneDOneQMachine
export MarconatoMachine
export SimpleMarconatoMachine
export AndersonFouadMachine
export SimpleAFMachine
export FullMachine
export SimpleFullMachine

#PSS Exports
export PSS
export PSSFixed
export PSSFixed

#Shaft Exports
export SingleMass
export FiveMassShaft

#TG Exports
export TurbineGov
export TGFixed
export TGTypeI
export TGTypeII

# Converter Exports
export Converter
export AvgCnvFixedDC

# DC Source Exports
export DCSource
export FixedDCSource

# Filter Exports
export Filter
export LCLFilter

# FrequencyEstimator Exports
export FrequencyEstimator
export PLL

# Outer Control Exports
export OuterControl
export VirtualInertiaQdroop
export VirtualInertia
export ReactivePowerDroop

# VSControl Export
export VSControl
export CombinedVIwithVZ

# DynBranches Export
export DynLine

# Sources Exports
export StaticSource

# Base Exports
export DynGenerator
export DynInverter
export DynamicSystem
export DynamicSimulation
export run_simulation!
export get_state_series
export get_voltagemag_series
export add_device!
export add_devices!
export add_network!

####################################### Package Imports ####################################
import DiffEqBase
import SparseArrays: SparseMatrixCSC
import LinearAlgebra: BLAS
import Base.to_index
import NLsolve
import PowerSystems
const PSY = PowerSystems

#Structs for General Devices and System
include("utils/util_macros.jl")
include("structs/base.jl")
include("structs/perturbations.jl")
include("structs/simulation.jl")

#Structs for Dynamic Devices
include("structs/common.jl")
include("structs/sources.jl")
include("structs/generator.jl")
include("structs/inverter.jl")
include("structs/dyn_branches.jl")

#Common Models
include("models/branch_model.jl")
include("models/device_model.jl")
include("models/kcl.jl")
include("models/dynline_model.jl")
include("models/ref_transformations.jl")

#Generator Component Models
include("models/generator_models/machine_models.jl")
include("models/generator_models/pss_models.jl")
include("models/generator_models/avr_models.jl")
include("models/generator_models/tg_models.jl")
include("models/generator_models/shaft_models.jl")

#Inverter Component Models
include("models/inverter_models/DCside_models.jl")
include("models/inverter_models/filter_models.jl")
include("models/inverter_models/frequency_estimator_models.jl")
include("models/inverter_models/outer_control_models.jl")
include("models/inverter_models/voltage_source_control_models.jl")
include("models/inverter_models/converter_models.jl")

#Injection Models
include("models/load_models.jl")
include("models/source_models.jl")

#System Model
include("models/system_model.jl")

#Perturbations
include("perturbations/common.jl")
include("perturbations/ThreePhaseFault.jl")
include("perturbations/PowerStepChange.jl")

#Utils
include("utils/plot_utils.jl")
include("utils/print.jl")

end # module


text:
## ------------------------------------------------------------------
# Utils

TkeyDict(T::DataType) = Dict{T, Any}()
function TkeyDict(nTkdict::Dict, T::DataType, convfun = T)
    Tkdict = TkeyDict(T)
    for (nTk, dat) in nTkdict
        Tkdict[convfun(nTk)] = dat
    end
    return Tkdict
end
TkeyDict(nt::NamedTuple, T::DataType, convfun = T) =
    TkeyDict(Dict(pairs(nt)...), T, convfun)

TkeyDict(nt::Base.Iterators.Pairs, T::DataType, convfun = T) =
    TkeyDict(Dict(pairs(nt)...), T, convfun)

max_stars_repo_name: josePereiro/GitWorkers

max_issues_repo_name: josePereiro/GitWorkers

max_forks_repo_name: josePereiro/GitWorkers


text:
## Main function to parse a template This works in several steps: each
## character parsed into a token, the tokens are squashed, then
## nested, then rendered.
function parse(template, tags = ("{{", "}}"))

    tokens = make_tokens(template, tags)
    out = nestTokens(tokens)
    ##out
    MustacheTokens(out)
end