diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 5e9df30..5798411 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -18,8 +18,8 @@ jobs: fail-fast: false matrix: version: - - '1.6' - - 'nightly' + - '1.11' + - '1.12' os: - ubuntu-latest arch: @@ -33,10 +33,4 @@ jobs: - uses: julia-actions/cache@v1 - uses: julia-actions/julia-buildpkg@v1 - uses: julia-actions/julia-runtest@v1 - - uses: julia-actions/julia-processcoverage@v1 - - uses: codecov/codecov-action@v2 - with: - files: lcov.info - - uses: julia-actions/julia-uploadcoveralls@v1 - env: - COVERALLS_TOKEN: ${{ secrets.COVERALLS_TOKEN }} + diff --git a/.gitignore b/.gitignore index 82bb227..f683c0f 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,7 @@ /tmp /.vscode /Result_Plots -*.log \ No newline at end of file +*.log +AGENTS/* +.agent/* +scripts/* \ No newline at end of file diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..83b2a11 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "AGENTS"] + path = AGENTS + url = git@github.com:avinashresearch1/AGENTS.git diff --git a/AGENTS b/AGENTS new file mode 160000 index 0000000..09ca233 --- /dev/null +++ b/AGENTS @@ -0,0 +1 @@ +Subproject commit 09ca233d0786c7fa2d7badfee78838e0b5cc5bce diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..0a20356 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,24 @@ +# Procedure for all cases: +1. Research: + - Read this folder and all files in it in depth, understand how it works deeply, what it does and all its specificities. when that’s done, write a detailed report of your learnings and findings in research.md +2. Planning: + - For the prompt given, write a detailed plan.md document outlining how to implement this. include code snippets. read source files before suggesting changes, base the plan on the actual codebase. +3. Implementation: + - implement it all. when you’re done with a task or phase, mark it as completed in the plan document. do not stop until all tasks and phases are completed. + - For each function you add or modify. Add detailed but concise documentation on what you have done. A developer and reviewer should be able to read the code and understand what was removed, modified and added and why. + + +# How to run Julia Code (relevant for Julia only) +- For Julia work, use a single DaemonMode server per Julia project to avoid repeated precompile costs. +- Start (or ensure) the daemon from the target Julia project directory (the one with `Project.toml`) before running any Julia code: `bash scripts/julia-daemon-start`. +- Run files via the daemon: `bash scripts/julia-daemon-run path/to/file.jl [args...]`. +- Run ad-hoc expressions via the daemon: `bash scripts/julia-daemon-expr 'expr'`. +- Avoid calling `julia` directly unless explicitly requested. +- Stop the daemon when asked: `bash scripts/julia-daemon-stop`. +- If working in a subproject, set `workdir` to that project's root or set `JULIA_PROJECT_DIR` to the project path. +- Port is stored in `.agent/julia-daemon.port` (default 3000); override with `JULIA_DAEMON_PORT`. +- **IMPORTANT**: All Julia commands require `all` permissions because the `juliaup` launcher needs write access to `~/.julia/juliaup/` (lockfile) which is outside the workspace sandbox. +- You must never directly run `julia` commands. Always use the Julia daemon server and client. + +You should never need to create a new Julia depot anywhere. Inform the user if you are stuck. +You should never need to install another Julia version. Always ask for permission if you think you do. diff --git a/Combinatorial mCp generator.pdf b/Combinatorial mCp generator.pdf new file mode 100644 index 0000000..d702521 Binary files /dev/null and b/Combinatorial mCp generator.pdf differ diff --git a/Examples/XLSX_interface/ClassicHENSProblem/6_Stream/6_stream.jl b/Examples/XLSX_interface/ClassicHENSProblem/6_Stream/6_stream.jl index 0e6ad02..8ebb4c5 100644 --- a/Examples/XLSX_interface/ClassicHENSProblem/6_Stream/6_stream.jl +++ b/Examples/XLSX_interface/ClassicHENSProblem/6_Stream/6_stream.jl @@ -4,11 +4,10 @@ using Plots using JuMP using HiGHS +using Ipopt +using MathOptInterface using Test - -using BARON - -exportall(CompHENS) +const MOI = MathOptInterface # 2. Specify path to xlsx file file_path_xlsx = joinpath(@__DIR__, "CompHENS_interface_SimpleExample.xlsx") @@ -20,13 +19,10 @@ prob = ClassicHENSProblem(file_path_xlsx; ΔT_min = 20.0, verbose = true) @time solve_minimum_utilities_subproblem!(prob) print_min_utils_pinch_points(prob) -@test prob.pinch_points == [(517.0, 497.0)] -@test isapprox(prob.hot_utilities_dict["ST"].Q, 244.13; atol = 1) -@test isapprox(prob.cold_utilities_dict["CW"].Q, 172.6; atol = 1) # 5. Solve the minimum number of units subproblem: @time solve_minimum_units_subproblem!(prob) -@test prob.min_units == 8 +@test prob.min_units == 5 # 6. Generate stream matches EMAT = 2.5 @@ -35,11 +31,14 @@ EMAT = 2.5 # 7. Network generation: # Specify which superstructure to use for each stream obj_func = CostScaledPaterson() -overall_network = merge(construct_superstructure(prob.stream_names, FloudasCiricGrossmann(), prob), construct_superstructure(prob.utility_names, ParallelSplit(), prob)) +overall_network = merge(construct_superstructure(prob.stream_names, FloudasCiricGrossmann(), prob), construct_superstructure(prob.utility_names, FloudasCiricGrossmann(), prob)) cost_coeff, scaling_coeff = 670, 0.83 -optimizer = BARON.Optimizer +optimizer = optimizer_with_attributes(Ipopt.Optimizer, "print_level" => 0, "max_iter" => 5000, "tol" => 1e-6) -generate_network!(prob, EMAT, overall_network; obj_func = CostScaledPaterson(), optimizer = optimizer, verbose = true, cost_coeff = cost_coeff, scaling_coeff = scaling_coeff) +generate_network!(prob, EMAT; overall_network = overall_network, obj_func = obj_func, optimizer = optimizer, verbose = true, cost_coeff = cost_coeff, scaling_coeff = scaling_coeff, save_model = true) +model = prob.results_dict[:network_gen_model] +@test termination_status(model) in [MOI.LOCALLY_SOLVED, MOI.OPTIMAL, MOI.ALMOST_LOCALLY_SOLVED, MOI.ALMOST_OPTIMAL] +@test primal_status(model) == MOI.FEASIBLE_POINT #= using Alpine @@ -62,5 +61,3 @@ const alpine = JuMP.optimizer_with_attributes( "partition_scaling_factor" => 10, ) =# - - diff --git a/Examples/XLSX_interface/ClassicHENSProblem/Colberg_Morari_1990/ColbergMorari.jl b/Examples/XLSX_interface/ClassicHENSProblem/Colberg_Morari_1990/ColbergMorari.jl index 230bae9..ce14c26 100644 --- a/Examples/XLSX_interface/ClassicHENSProblem/Colberg_Morari_1990/ColbergMorari.jl +++ b/Examples/XLSX_interface/ClassicHENSProblem/Colberg_Morari_1990/ColbergMorari.jl @@ -4,11 +4,10 @@ using Plots using JuMP using HiGHS +using Ipopt +using MathOptInterface using Test - -using BARON - -exportall(CompHENS) +const MOI = MathOptInterface # 2. Specify path to xlsx file file_path_xlsx = joinpath(@__DIR__, "CompHENS_interface_ColbergMorari.xlsx") @@ -39,17 +38,15 @@ prob.results_dict[:Q] obj_func = CostScaledPaterson() overall_network = merge(construct_superstructure(prob.stream_names, FloudasCiricGrossmann(), prob), construct_superstructure(prob.utility_names, FloudasCiricGrossmann(), prob)) base_cost, cost_coeff, scaling_coeff = 8600, 670, 0.83 -optimizer = BARON.Optimizer +optimizer = optimizer_with_attributes(Ipopt.Optimizer, "print_level" => 0, "max_iter" => 5000, "tol" => 1e-6) -generate_network!(prob, EMAT; overall_network = overall_network, obj_func = obj_func, optimizer = optimizer, verbose = true, cost_coeff = cost_coeff, scaling_coeff = scaling_coeff, base_cost = base_cost, save_model = true, time_limit = 20.0) +generate_network!(prob, EMAT; overall_network = overall_network, obj_func = obj_func, optimizer = optimizer, verbose = true, cost_coeff = cost_coeff, scaling_coeff = scaling_coeff, base_cost = base_cost, save_model = true) model = prob.results_dict[:network_gen_model] -#print(model) -file_name = "/home/avinash/Desktop/COMPHENS/CompHENS.jl/Result_Plots/Colberg_Morari.pdf" - -plot_HEN_streamwise(prob, model, overall_network, file_name; digits = 1) -#stream = "C2" -#CompHENS.print_stream_results(stream, prob, model, overall_network[stream]) +@test termination_status(model) in [MOI.LOCALLY_SOLVED, MOI.OPTIMAL, MOI.ALMOST_LOCALLY_SOLVED, MOI.ALMOST_OPTIMAL] +@show termination_status(model) +@test primal_status(model) == MOI.FEASIBLE_POINT +# print(model) value.(model[:ΔT_upper]) value.(model[:ΔT_lower]) value.(model[:T_LMTD]) -get_design_area(prob) \ No newline at end of file +get_design_area(prob) diff --git a/Examples/XLSX_interface/ClassicHENSProblem/Gundersen_4_stream/Gundersen_4_stream.jl b/Examples/XLSX_interface/ClassicHENSProblem/Gundersen_4_stream/Gundersen_4_stream.jl index a9b92dd..152c765 100644 --- a/Examples/XLSX_interface/ClassicHENSProblem/Gundersen_4_stream/Gundersen_4_stream.jl +++ b/Examples/XLSX_interface/ClassicHENSProblem/Gundersen_4_stream/Gundersen_4_stream.jl @@ -4,11 +4,11 @@ using Plots using JuMP +using Ipopt +using MathOptInterface using Test +const MOI = MathOptInterface -using BARON - -#exportall(CompHENS) # 2. Specify path to xlsx file file_path_xlsx = joinpath(@__DIR__, "Gundersen_4_stream.xlsx") @@ -42,14 +42,12 @@ overall_network = construct_superstructure(prob.all_names, FloudasCiricGrossmann obj_func = CostScaledPaterson() base_cost, cost_coeff, scaling_coeff = 4000, 500, 0.83 -# 7.i. Commercial using BARON: -optimizer = optimizer_with_attributes(BARON.Optimizer, "MaxTime" => 20.0, "AbsConFeasTol" => 1) -results_df = generate_network!(prob, EMAT; optimizer = optimizer, obj_func = obj_func, verbose = true, cost_coeff = cost_coeff, scaling_coeff = scaling_coeff, base_cost = base_cost, save_model = true) - +optimizer = optimizer_with_attributes(Ipopt.Optimizer, "print_level" => 0, "max_iter" => 8000, "tol" => 1e-6) +results_df = generate_network!(prob, EMAT; overall_network = overall_network, optimizer = optimizer, obj_func = obj_func, verbose = true, cost_coeff = cost_coeff, scaling_coeff = scaling_coeff, base_cost = base_cost, save_model = true) +@show termination_status(model) model = prob.results_dict[:network_gen_model] -file_name = "/home/avinash/Desktop/COMPHENS/CompHENS.jl/Examples/XLSX_interface/ClassicHENSProblem/Gundersen_4_stream/Gundersen_4_stream.pdf" - -plot_HEN_streamwise(prob, model, overall_network, file_name; digits = 1) +@test termination_status(model) in [MOI.LOCALLY_SOLVED, MOI.OPTIMAL, MOI.ALMOST_LOCALLY_SOLVED, MOI.ALMOST_OPTIMAL] +@test primal_status(model) == MOI.FEASIBLE_POINT #=Trials #CompHENS. @@ -106,4 +104,4 @@ initial_values = (; v_names = variable_ref, v_starts = start_vals) optimizer = IPOPT_solver optimizer = JUNIPER_solver generate_network!(prob, EMAT; optimizer = optimizer, verbose = true, cost_coeff = cost_coeff, scaling_coeff = scaling_coeff, base_cost = base_cost, save_model = true, initial_values = initial_values) -=# \ No newline at end of file +=# diff --git a/Examples/XLSX_interface/ClassicHENSProblem/Gundersen_4_stream/Gundersen_4_stream_opensolvers.jl b/Examples/XLSX_interface/ClassicHENSProblem/Gundersen_4_stream/Gundersen_4_stream_opensolvers.jl deleted file mode 100644 index f4ba639..0000000 --- a/Examples/XLSX_interface/ClassicHENSProblem/Gundersen_4_stream/Gundersen_4_stream_opensolvers.jl +++ /dev/null @@ -1,116 +0,0 @@ -#= -# Attempts to use open-source global solvers to solve NLP. Mostly failed, this file contains record. -# Workflow using XLSX input: -# 1. Import necessary packages: -@time using CompHENS - -using Plots -using JuMP -using Test - -#using BARON - -#exportall(CompHENS) - -# 2. Specify path to xlsx file -file_path_xlsx = joinpath(@__DIR__, "Gundersen_4_stream.xlsx") - -# 3. Construct the appropriate kind of problem: Here it is a `ClassicHENSProblem` -prob = ClassicHENSProblem(file_path_xlsx; ΔT_min = 10.0, verbose = true) - -#intervals = CompHENS.generate_transshipment_intervals(prob) -#print_full(intervals) - -# 4. Solve minimum utilities problem -@time solve_minimum_utilities_subproblem!(prob; verbose = true) - -print_min_utils_pinch_points(prob) - -# 5. Solve the minimum number of units subproblem:plot_HEN_streamwise(prob::ClassicHENSProblem, model::AbstractModel, overall_network::Dict{String, AbstractSuperstructure}, file_name; digits = 1) -@time solve_minimum_units_subproblem!(prob) -@test prob.min_units == 5 - -# 6. Generate stream matches -EMAT = prob.ΔT_min/8 -prob.results_dict[:add_units] = 1 -@time generate_stream_matches!(prob, EMAT; digits = 8, verbose = false) -prob.results_dict[:Q] - - -# 7. Network generation: -# Specify which superstructure to use for each stream -#obj_func = CostScaledPaterson() -#overall_network = merge(construct_superstructure(prob.stream_names, FloudasCiricGrossmann(), prob), construct_superstructure(prob.utility_names, FloudasCiricGrossmann(), prob)) -base_cost, cost_coeff, scaling_coeff = 4000, 500, 0.83 -obj_func = AreaArithmeticMean() -# using ALPINE for first-pass: -#optimizer = SCIP_solver - -#obj_func = CostScaledPaterson() -#obj_func = Tupper() -#optimizer = optimizer_with_attributes(BARON.Optimizer, "MaxTime" => 20.0, "AbsConFeasTol" => 1) - -generate_network!(prob, EMAT; optimizer = optimizer, obj_func = obj_func, verbose = true, cost_coeff = cost_coeff, scaling_coeff = scaling_coeff, base_cost = base_cost, save_model = true) -#generate_network!(prob, EMAT, "couenne"; verbose = true, cost_coeff = cost_coeff, scaling_coeff = scaling_coeff, base_cost = base_cost, save_model = true) -model = prob.results_dict[:network_gen_model] -#print(model) -file_name = "/home/avinash/Desktop/COMPHENS/CompHENS.jl/Result_Plots/Gundersen_4_stream.pdf" - -plot_HEN_streamwise(prob, model, overall_network, file_name; digits = 1) -#stream = "C2" -#CompHENS.print_stream_results(stream, prob, model, overall_network[stream]) -value.(model[:ΔT_upper]) -value.(model[:ΔT_lower]) -value.(model[:T_LMTD]) -get_design_area(prob) -# - -# Setting optimizer for 2nd-pass: -#Get initial values -var_names = JuMP.all_variables(model) - -initial_values = values.(model[JuMP.all_variables(model)]) -value(model[Symbol(initial_values[1])]) -for var in JuMP.all_variables(model) - push!(initial_values, var.name => value(model[var])) -end - -function get_results_dict(m::JuMP.Model) - av = JuMP.all_variables(m); - d = Dict() - for v in av - # special handling of time series, sub-indices, etc. - # e.g. a variable could have three sub-indices in a JuMP.Containers - v = string(v) # e.g. "x[a,2,3]" - k = Symbol(v[1:prevind(v, findfirst('[', v))[1]]) # :x - vm = value.(m[k]) - d[k] = vm.data - # e.g. typeof(vm) is JuMP.Containers.SparseAxisArray{Float64, 3, Tuple{SubString{String}, Int64, Int64}} - end - return d -end - -res = get_results_dict(model) - -set_optimizer(model, IPOPT_solver) - - -optimize!(model) - -variable_refs = [] -start_vals = [] - -keys(object_dictionary(model)) - - -# Using an ugle hack: -variable_ref = JuMP.all_variables(model) -start_vals = vcat(start_vals, res[:t], res[:f], res[:ΔT_upper], res[:ΔT_lower], res[:T_LMTD]) .+ 0.01 - -initial_values = (; v_names = variable_ref, v_starts = start_vals) - -optimizer = IPOPT_solver -optimizer = JUNIPER_solver -generate_network!(prob, EMAT; optimizer = optimizer, verbose = true, cost_coeff = cost_coeff, scaling_coeff = scaling_coeff, base_cost = base_cost, save_model = true, initial_values = initial_values) -=# -=# \ No newline at end of file diff --git a/Examples/XLSX_interface/ClassicHENSProblem/NaN_MWE/Infeasible_issue.jl b/Examples/XLSX_interface/ClassicHENSProblem/NaN_MWE/Infeasible_issue.jl index 57ae23d..0d1e79b 100644 --- a/Examples/XLSX_interface/ClassicHENSProblem/NaN_MWE/Infeasible_issue.jl +++ b/Examples/XLSX_interface/ClassicHENSProblem/NaN_MWE/Infeasible_issue.jl @@ -5,9 +5,11 @@ using Plots using JuMP using HiGHS +using Ipopt +using MathOptInterface using Test +const MOI = MathOptInterface -using BARON #using XLSX #using DataFrames @@ -35,7 +37,10 @@ overall_network = construct_superstructure(prob.all_names, FloudasCiricGrossmann obj_func = CostScaledPaterson() base_cost, cost_coeff, scaling_coeff = 8333.3, 641.7, 1 -optimizer = optimizer_with_attributes(BARON.Optimizer, "MaxTime" => -1, "AbsConFeasTol" => 10) +optimizer = optimizer_with_attributes(Ipopt.Optimizer, "print_level" => 0, "max_iter" => 10000, "tol" => 1e-6) results_df = generate_network!(prob, EMAT; optimizer = optimizer, obj_func = obj_func, verbose = true, cost_coeff = cost_coeff, scaling_coeff = scaling_coeff, base_cost = base_cost, save_model = true) +model = prob.results_dict[:network_gen_model] +@test termination_status(model) in [MOI.LOCALLY_SOLVED, MOI.OPTIMAL, MOI.ALMOST_LOCALLY_SOLVED, MOI.ALMOST_OPTIMAL] +@test primal_status(model) == MOI.FEASIBLE_POINT -prob.results_dict[:HLD_list] \ No newline at end of file +prob.results_dict[:HLD_list] diff --git a/Examples/XLSX_interface/ClassicHENSProblem/NaN_MWE/NaN_MWE.jl b/Examples/XLSX_interface/ClassicHENSProblem/NaN_MWE/NaN_MWE.jl index 945b70b..2a150ce 100644 --- a/Examples/XLSX_interface/ClassicHENSProblem/NaN_MWE/NaN_MWE.jl +++ b/Examples/XLSX_interface/ClassicHENSProblem/NaN_MWE/NaN_MWE.jl @@ -2,8 +2,10 @@ using Plots using JuMP using HiGHS +using Ipopt +using MathOptInterface using Test -using BARON +const MOI = MathOptInterface file_path_xlsx = joinpath(@__DIR__, "CompHENS_interface_KangLiu_Period1.xlsx") prob = ClassicHENSProblem(file_path_xlsx; ΔT_min = 10, verbose = true) @@ -41,10 +43,9 @@ overall_network = construct_superstructure(prob.all_names, FloudasCiricGrossmann obj_func = CostScaledPaterson() base_cost, cost_coeff, scaling_coeff = 4000, 500, 0.83 -optimizer = optimizer_with_attributes(BARON.Optimizer, "MaxTime" => 20.0, "AbsConFeasTol" => 1.5) +optimizer = optimizer_with_attributes(Ipopt.Optimizer, "print_level" => 0, "max_iter" => 8000, "tol" => 1e-6) results_df = generate_network!(prob, EMAT; optimizer = optimizer, obj_func = obj_func, verbose = true, cost_coeff = cost_coeff, scaling_coeff = scaling_coeff, base_cost = base_cost, save_model = true) model = prob.results_dict[:network_gen_model] -file_name = "/home/avinash/Desktop/COMPHENS/CompHENS.jl/Examples/XLSX_interface/ClassicHENSProblem/NaN_MWE/KangLiu_Period1.pdf" - -plot_HEN_streamwise(prob, model, overall_network, file_name; digits = 1) +@test termination_status(model) in [MOI.LOCALLY_SOLVED, MOI.OPTIMAL, MOI.ALMOST_LOCALLY_SOLVED, MOI.ALMOST_OPTIMAL] +@test primal_status(model) == MOI.FEASIBLE_POINT diff --git a/Examples/XLSX_interface/ClassicHENSProblem/TEP4125_Examples/Assignment_2.xlsx/Assignment_2.jl b/Examples/XLSX_interface/ClassicHENSProblem/TEP4125_Examples/Assignment_2.xlsx/Assignment_2.jl index 9aa6659..b4a3a56 100644 --- a/Examples/XLSX_interface/ClassicHENSProblem/TEP4125_Examples/Assignment_2.xlsx/Assignment_2.jl +++ b/Examples/XLSX_interface/ClassicHENSProblem/TEP4125_Examples/Assignment_2.xlsx/Assignment_2.jl @@ -4,9 +4,10 @@ using Plots using JuMP using HiGHS +using Ipopt +using MathOptInterface using Test - -using BARON +const MOI = MathOptInterface #exportall(CompHENS) @@ -26,7 +27,7 @@ print_min_utils_pinch_points(prob) # 5. Solve the minimum number of units subproblem: @time solve_minimum_units_subproblem!(prob) -@test prob.min_units == 8 +@test prob.min_units == 5 # 6. Generate stream matches EMAT = 2.5 @@ -35,12 +36,15 @@ EMAT = 2.5 # 7. Network generation: # Specify which superstructure to use for each stream obj_func = CostScaledPaterson() -overall_network = merge(construct_superstructure(prob.stream_names, FloudasCiricGrossmann(), prob), construct_superstructure(prob.utility_names, ParallelSplit(), prob)) +overall_network = merge(construct_superstructure(prob.stream_names, FloudasCiricGrossmann(), prob), construct_superstructure(prob.utility_names, FloudasCiricGrossmann(), prob)) cost_coeff, scaling_coeff = 670, 0.83 -optimizer = BARON.Optimizer - -generate_network!(prob, EMAT, overall_network; obj_func = CostScaledPaterson(), optimizer = optimizer, verbose = true, cost_coeff = cost_coeff, scaling_coeff = scaling_coeff) +optimizer = optimizer_with_attributes(Ipopt.Optimizer, "print_level" => 0, "max_iter" => 5000, "tol" => 1e-6) +generate_network!(prob, EMAT; overall_network = overall_network, obj_func = obj_func, optimizer = optimizer, verbose = true, cost_coeff = cost_coeff, scaling_coeff = scaling_coeff, save_model = true) +model = prob.results_dict[:network_gen_model] +@test termination_status(model) in [MOI.LOCALLY_SOLVED, MOI.OPTIMAL, MOI.ALMOST_LOCALLY_SOLVED, MOI.ALMOST_OPTIMAL] +@test primal_status(model) == MOI.FEASIBLE_POINT +@show termination_status(model) #= using Alpine const alpine = JuMP.optimizer_with_attributes( @@ -62,6 +66,3 @@ const alpine = JuMP.optimizer_with_attributes( "partition_scaling_factor" => 10, ) =# - - - diff --git a/Examples/XLSX_interface/MultiPeriodFlexibleHENSProblem/Floudas_Grossmann_1987/FloudasGrossmann1987.jl b/Examples/XLSX_interface/MultiPeriodFlexibleHENSProblem/Floudas_Grossmann_1987/FloudasGrossmann1987.jl index 9f2e83e..ac485bc 100644 --- a/Examples/XLSX_interface/MultiPeriodFlexibleHENSProblem/Floudas_Grossmann_1987/FloudasGrossmann1987.jl +++ b/Examples/XLSX_interface/MultiPeriodFlexibleHENSProblem/Floudas_Grossmann_1987/FloudasGrossmann1987.jl @@ -4,12 +4,11 @@ using CompHENS using Plots using JuMP using HiGHS +using Ipopt +using MathOptInterface using XLSX using DataFrames - -using BARON - -exportall(CompHENS) +const MOI = MathOptInterface # 2. Specify path to xlsx file, Construct the appropriate kind of problem: Here it is a `MultiPeriodFlexibleHENSProblem`. file_path_xlsx = joinpath(@__DIR__, "CompHENS_interface_FloudasGrossmann.xlsx") @@ -28,8 +27,16 @@ prob.results_dict[:add_units] = 1 generate_stream_matches!(prob, EMAT; verbose = false) print_HLD(prob) -optimizer = optimizer_with_attributes(BARON.Optimizer, "MaxTime" => 20.0, "AbsConFeasTol" => 1) - -output_folder = "/home/avinash/Desktop/COMPHENS/CompHENS.jl/Examples/MultiPeriodFlexibleHENSProblem/Floudas_Grossmann_1987/" -generate_network!(prob, EMAT; optimizer = optimizer, verbose = true, output_folder = output_folder) -get_design_area(prob) \ No newline at end of file +optimizer = optimizer_with_attributes(Ipopt.Optimizer, "print_level" => 0, "max_iter" => 8000, "tol" => 1e-6) + +output_folder = nothing +generate_network!(prob, EMAT; optimizer = optimizer, verbose = true, output_folder = output_folder, save_model = true) +for period in prob.period_names + model = prob.period_streams_dict[period].results_dict[:network_gen_model] + status = termination_status(model) + pstatus = primal_status(model) + if !(status in [MOI.LOCALLY_SOLVED, MOI.OPTIMAL, MOI.ALMOST_LOCALLY_SOLVED, MOI.ALMOST_OPTIMAL] && pstatus == MOI.FEASIBLE_POINT) + error("Period $(period) failed IPOPT solve: termination=$(status), primal=$(pstatus)") + end +end +get_design_area(prob) diff --git a/Project.toml b/Project.toml index d48dc18..7aa3994 100644 --- a/Project.toml +++ b/Project.toml @@ -4,35 +4,38 @@ authors = ["Avinash Subramanian"] version = "0.1.4" [deps] -BARON = "2e2ca445-9e14-5b13-8677-4410f177f82b" Conda = "8f4d0f93-b110-5947-807f-2305c1781a2d" DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" DocStringExtensions = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" HiGHS = "87dc4568-4c63-4d18-b0c0-bb2238e4078b" +Ipopt = "b6b21f68-93f8-5de0-b562-5493be1d77c9" JLD2 = "033835bb-8acc-5ee8-8aae-3f567f8a3819" JuMP = "4076af6c-e467-56ae-b986-b466b2749572" Kwonly = "18d08c8c-0732-55ee-a446-91a51d7b4206" MathOptInterface = "b8f27783-ece8-5eb3-8dc8-9495eed66fee" -NamedArrays = "86f7a689-2022-50b4-a561-43c23ac3c673" Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" -PyCall = "438e738f-606a-5dbb-bf0a-cddfbfd45ab0" XLSX = "fdbf4ff8-1666-58a4-91e7-1b58723a45e0" +[weakdeps] +PyCall = "438e738f-606a-5dbb-bf0a-cddfbfd45ab0" + +[extensions] +CompHENSNetworkXPlotsExt = "PyCall" + [compat] -BARON = "0.8" +Conda = "1" DataFrames = "1" DocStringExtensions = "0.9" HiGHS = "1" +Ipopt = "1" JLD2 = "0.4" JuMP = "1" Kwonly = "0.1" MathOptInterface = "1" -NamedArrays = "0.9" Plots = "1" -XLSX = "0.8, 0.9" -julia = "1.6" PyCall = "1" -Conda = "1" +XLSX = "0.8, 0.9" +julia = "1.10" [extras] Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" diff --git a/ext/CompHENSNetworkXPlotsExt.jl b/ext/CompHENSNetworkXPlotsExt.jl new file mode 100644 index 0000000..76ccafd --- /dev/null +++ b/ext/CompHENSNetworkXPlotsExt.jl @@ -0,0 +1,156 @@ +module CompHENSNetworkXPlotsExt + + using CompHENS + using PyCall + using Conda + + const nx = PyNULL() + const plt = PyNULL() + const back_pdf = PyNULL() + + + function __init__() + copy!(nx, pyimport_conda("networkx", "networkx")) + copy!(plt, pyimport_conda("matplotlib.pyplot", "matplotlib")) + copy!(back_pdf, pyimport_conda("matplotlib.backends.backend_pdf", "matplotlib")) + end + + """ + $(TYPEDSIGNATURES) + The visualization tools for the HEN uses the Python `NetworkX` and `MatPlotlib` packages. + By default, OS-X and Windows users should PyCall configured to use the Miniconda environment installed at `.julia/conda/` (this can be attained by calling `Conda.ROOTENV`). + For Linux users: By default the default system installation is used, and it is necessary to over-ride this as follows: + - Set + ``` + ENV["PYTHON"]="" + using Pkg + Pkg.build("PyCall") + ``` + Then **restart** the Julia process. + """ + function CompHENS.plot_HEN_streamwise(prob::ClassicHENSProblem, model::AbstractModel, overall_network::Dict{String, AbstractSuperstructure}, file_name; digits = 1) + __init__() + pdf = back_pdf.PdfPages(file_name) + for stream in prob.all_names + plt.close() + (g, edge_labels, node_labels, position, node_size) = get_stream_graph(prob.all_dict[stream], prob, model, overall_network[stream]; digits = digits) + nx.draw_networkx(g, position, node_size = node_size, with_labels=false, arrowstyle="->", node_shape = "s") + nx.draw_networkx_labels(g, position, labels = node_labels, font_size = 3, horizontalalignment = "left", verticalalignment = "top") + nx.draw_networkx_edge_labels(g, position, edge_labels = edge_labels, horizontalalignment = "center", verticalalignment = "center", font_size = 2, rotate=false) + pdf.savefig() + end + pdf.close() + end + + """ + + + Gets a NetworkX Digraph for each stream + Returns: (g, edge_labels, node_labels, position, node_size) + """ + function CompHENS.get_stream_graph(stream::AbstractStream, prob::ClassicHENSProblem, model::AbstractModel, superstructure::AbstractSplitSuperstructure; digits = 1) + g = nx.DiGraph() + edge_labels = Dict() + node_labels = Dict() + + # Add nodes to NetworkX graph + for node in superstructure.nodes + g.add_node(node.name) + if node isa HX + match = node.match + if stream isa HotStream + node_labels[node.name] = "match: $(match), Q = $(round((prob.results_dict[:Q][match, stream.name]), digits = digits))" + elseif stream isa ColdStream + node_labels[node.name] = "match: $(match), Q = $(round((prob.results_dict[:Q][stream.name, match]), digits = digits))" + end + end + end + + # Only add edges if f_edge is greater than 0 + for edge in superstructure.edges + if value(model[:f][(stream.name, edge)]) > 0.0 + g.add_edge(edge.in.name, edge.out.name) + edge_labels[(edge.in.name, edge.out.name)] = "m: $(round(value(model[:f][(stream.name, edge)]); digits = digits)) T: $(round(value(model[:t][(stream.name, edge)]); digits = digits))" + end + end + + num_matches = length(prob.results_dict[:HLD_list][stream.name]) + # Copied from SeqHENS.jl + # Setting the coordinates of the nodes + position = Dict() + coordinates = [] # Array to keep pushing paired coordinates to, will then go through and assign to dictionary + bfix = 0.4 # Determines the vertical spacing + + push!(coordinates, (0,0)) + push!(coordinates, (1,0)) + for e in 1:num_matches + push!(coordinates,(2,0-(bfix*(e-1)))) + push!(coordinates,(5,0-(bfix*(e-1)))) + push!(coordinates,(9,0-(bfix*(e-1)))) + end + push!(coordinates,(10,0)) + push!(coordinates,(11,0)) + + i = 0 # hack for now + for node in superstructure.nodes + i += 1 + position[node.name] = coordinates[i] + end + + node_size = fill(1.0, length(superstructure.nodes)) + return(g, edge_labels, node_labels, position, node_size) + end + + function CompHENS.get_stream_graph(stream::AbstractUtility, prob::ClassicHENSProblem, model::AbstractModel, superstructure::AbstractSplitSuperstructure; digits = 1) + g = nx.DiGraph() + edge_labels = Dict() + node_labels = Dict() + + # Add nodes to NetworkX graph + for node in superstructure.nodes + g.add_node(node.name) + if node isa HX + match = node.match + if stream isa HotStream + node_labels[node.name] = "o: $(match), Q = $(round((prob.results_dict[:Q][match, stream.name]), digits = digits))" + elseif stream isa ColdStream + node_labels[node.name] = "o: $(match), Q = $(round((prob.results_dict[:Q][stream.name, match]), digits = digits))" + end + end + end + + # Only add edges if f_edge is greater than 0 + for edge in superstructure.edges + if edge.in isa HX || edge.out isa HX # Only care about edges attached to HX + g.add_edge(edge.in.name, edge.out.name) + edge_labels[(edge.in.name, edge.out.name)] = "T: $(round(value(model[:t][(stream.name, edge)]); digits = digits))" + end + end + + num_matches = length(prob.results_dict[:HLD_list][stream.name]) + # Copied from SeqHENS.jl + # Setting the coordinates of the nodes + position = Dict() + coordinates = [] # Array to keep pushing paired coordinates to, will then go through and assign to dictionary + bfix = 0.4 # Determines the vertical spacing + + push!(coordinates, (0,0)) + push!(coordinates, (1,0)) + for e in 1:num_matches + push!(coordinates,(2,0-(bfix*(e-1)))) + push!(coordinates,(5,0-(bfix*(e-1)))) + push!(coordinates,(9,0-(bfix*(e-1)))) + end + push!(coordinates,(10,0)) + push!(coordinates,(11,0)) + + i = 0 # hack for now + for node in superstructure.nodes + i += 1 + position[node.name] = coordinates[i] + end + + node_size = fill(1.0, length(superstructure.nodes)) + return(g, edge_labels, node_labels, position, node_size) + end +end diff --git a/src/CompHENS.jl b/src/CompHENS.jl index 3527442..78b1596 100644 --- a/src/CompHENS.jl +++ b/src/CompHENS.jl @@ -102,6 +102,7 @@ include("Superstructures/ParallelSplit.jl") export generate_network!, postprocess_network!, plot_HEN_streamwise, print_stream_results, get_design_area, AreaArithmeticMean, AreaPaterson, CostScaledPaterson, get_stream_graph include("SubProblems/Network_generation/network_generator_JuMP.jl") +include("SubProblems/Network_generation/starting_point_generator.jl") include("SubProblems/Network_generation/network_postprocess.jl") include("SubProblems/Network_generation/conda_networkx_plots.jl") diff --git a/src/ProblemConstructors/classic_hens_prob.jl b/src/ProblemConstructors/classic_hens_prob.jl index 4a64d44..67e1e8e 100644 --- a/src/ProblemConstructors/classic_hens_prob.jl +++ b/src/ProblemConstructors/classic_hens_prob.jl @@ -64,7 +64,7 @@ Reads data from an XSLX file in `file_path_xlsx` and constructs a `ClassicHENSPr - **`file_path_xlsx`** needs to be a string that ends in .xlsx - By default `ΔT_min` is set to 10 °C. """ -function ClassicHENSProblem(file_path_xlsx::String; ΔT_min, verbose = false) +function ClassicHENSProblem(file_path_xlsx::String; ΔT_min = 10.0, verbose = false) stream_data_dfs = DataFrame[] XLSX.openxlsx(file_path_xlsx) do xf verbose && println("Num worksheets imported: $(XLSX.sheetcount(xf))") @@ -86,7 +86,7 @@ Given a `DataFrame` object (from a single excel worksheet), returns a `ClassicHE Note that this function can also called for other problem types e.g., `MultiPeriodFlexibleHENSProblem`. """ -function ClassicHENSProblem(stream_data_df::DataFrame; ΔT_min) +function ClassicHENSProblem(stream_data_df::DataFrame; ΔT_min = 10.0) # Column names of XLSX interface: stream_label, type_label, t_in_label, t_out_label, heat_cap_label, heat_coeff_label, cost_label, forbidden_label, compulsory_label = "Stream", "Type [H, C, HU or CU]", "Supply Temperature T_in [C or K]", "Target Temperature T_out [C or K]", "Heat Capacity mCp [kW/C or kW/K]", "Heat transfer coefficient h [kW/m2C or kW/m2K]", "Cost [\$/kW]", "Forbidden Matches", "Compulsory Matches" additional_user_fields = Set{String}(["Cost [\$/kW]", "Forbidden Matches", "Compulsory Matches", "Maximum Temperature", "Mininum Temperature"]) @@ -135,4 +135,3 @@ end - diff --git a/src/Streams/streams.jl b/src/Streams/streams.jl index 705875f..4ef20e5 100644 --- a/src/Streams/streams.jl +++ b/src/Streams/streams.jl @@ -44,6 +44,7 @@ mutable struct ColdStream <: AbstractStream T_in <= T_out || error("Supply and Target temperature don't match stream type") mcp >= 0.0 || error("mcp values negative") # Can be zero if stream doesn't exist in one period. h > smallest_value || error("values infeasible") + push!(add_user_data, "Working Terminal T" => T_out) new(name, Float64(T_in), Float64(T_out), Float64(mcp), Float64(h), add_user_data, calc) end end diff --git a/src/SubProblems/Network_generation/conda_networkx_plots.jl b/src/SubProblems/Network_generation/conda_networkx_plots.jl index 26e395f..a48d6bc 100644 --- a/src/SubProblems/Network_generation/conda_networkx_plots.jl +++ b/src/SubProblems/Network_generation/conda_networkx_plots.jl @@ -1,16 +1,3 @@ -using Conda, PyCall - -const nx = PyNULL() -const plt = PyNULL() -const back_pdf = PyNULL() - - -function __init__() - copy!(nx, pyimport_conda("networkx", "networkx")) - copy!(plt, pyimport_conda("matplotlib.pyplot", "matplotlib")) - copy!(back_pdf, pyimport_conda("matplotlib.backends.backend_pdf", "matplotlib")) -end - """ $(TYPEDSIGNATURES) The visualization tools for the HEN uses the Python `NetworkX` and `MatPlotlib` packages. @@ -24,18 +11,10 @@ Pkg.build("PyCall") ``` Then **restart** the Julia process. """ -function plot_HEN_streamwise(prob::ClassicHENSProblem, model::AbstractModel, overall_network::Dict{String, AbstractSuperstructure}, file_name; digits = 1) - __init__() - pdf = CompHENS.back_pdf.PdfPages(file_name) - for stream in prob.all_names - plt.close() - (g, edge_labels, node_labels, position, node_size) = get_stream_graph(prob.all_dict[stream], prob, model, overall_network[stream]; digits = digits) - nx.draw_networkx(g, position, node_size = node_size, with_labels=false, arrowstyle="->", node_shape = "s") - nx.draw_networkx_labels(g, position, labels = node_labels, font_size = 3, horizontalalignment = "left", verticalalignment = "top") - nx.draw_networkx_edge_labels(g, position, edge_labels = edge_labels, horizontalalignment = "center", verticalalignment = "center", font_size = 2, rotate=false) - pdf.savefig() - end - pdf.close() +function plot_HEN_streamwise(args...; kwargs...) + # Concrete plotting implementation was moved to optional extension + # `CompHENSNetworkXPlotsExt` to avoid hard dependency on PyCall. + error("Plotting requires the optional extension `CompHENSNetworkXPlotsExt` (install/load PyCall).") end """ @@ -44,108 +23,8 @@ end Gets a NetworkX Digraph for each stream Returns: (g, edge_labels, node_labels, position, node_size) """ -function get_stream_graph(stream::AbstractStream, prob::ClassicHENSProblem, model::AbstractModel, superstructure::AbstractSplitSuperstructure; digits = 1) - g = nx.DiGraph() - edge_labels = Dict() - node_labels = Dict() - - # Add nodes to NetworkX graph - for node in superstructure.nodes - g.add_node(node.name) - if node isa HX - match = node.match - if stream isa HotStream - node_labels[node.name] = "match: $(match), Q = $(round((prob.results_dict[:Q][match, stream.name]), digits = digits))" - elseif stream isa ColdStream - node_labels[node.name] = "match: $(match), Q = $(round((prob.results_dict[:Q][stream.name, match]), digits = digits))" - end - end - end - - # Only add edges if f_edge is greater than 0 - for edge in superstructure.edges - if value(model[:f][(stream.name, edge)]) > 0.0 - g.add_edge(edge.in.name, edge.out.name) - edge_labels[(edge.in.name, edge.out.name)] = "m: $(round(value(model[:f][(stream.name, edge)]); digits = digits)) T: $(round(value(model[:t][(stream.name, edge)]); digits = digits))" - end - end - - num_matches = length(prob.results_dict[:HLD_list][stream.name]) - # Copied from SeqHENS.jl - # Setting the coordinates of the nodes - position = Dict() - coordinates = [] # Array to keep pushing paired coordinates to, will then go through and assign to dictionary - bfix = 0.4 # Determines the vertical spacing - - push!(coordinates, (0,0)) - push!(coordinates, (1,0)) - for e in 1:num_matches - push!(coordinates,(2,0-(bfix*(e-1)))) - push!(coordinates,(5,0-(bfix*(e-1)))) - push!(coordinates,(9,0-(bfix*(e-1)))) - end - push!(coordinates,(10,0)) - push!(coordinates,(11,0)) - - i = 0 # hack for now - for node in superstructure.nodes - i += 1 - position[node.name] = coordinates[i] - end - - node_size = fill(1.0, length(superstructure.nodes)) - return(g, edge_labels, node_labels, position, node_size) -end - -function get_stream_graph(stream::AbstractUtility, prob::ClassicHENSProblem, model::AbstractModel, superstructure::AbstractSplitSuperstructure; digits = 1) - g = nx.DiGraph() - edge_labels = Dict() - node_labels = Dict() - - # Add nodes to NetworkX graph - for node in superstructure.nodes - g.add_node(node.name) - if node isa HX - match = node.match - if stream isa HotStream - node_labels[node.name] = "o: $(match), Q = $(round((prob.results_dict[:Q][match, stream.name]), digits = digits))" - elseif stream isa ColdStream - node_labels[node.name] = "o: $(match), Q = $(round((prob.results_dict[:Q][stream.name, match]), digits = digits))" - end - end - end - - # Only add edges if f_edge is greater than 0 - for edge in superstructure.edges - if edge.in isa HX || edge.out isa HX # Only care about edges attached to HX - g.add_edge(edge.in.name, edge.out.name) - edge_labels[(edge.in.name, edge.out.name)] = "T: $(round(value(model[:t][(stream.name, edge)]); digits = digits))" - end - end - - num_matches = length(prob.results_dict[:HLD_list][stream.name]) - # Copied from SeqHENS.jl - # Setting the coordinates of the nodes - position = Dict() - coordinates = [] # Array to keep pushing paired coordinates to, will then go through and assign to dictionary - bfix = 0.4 # Determines the vertical spacing - - push!(coordinates, (0,0)) - push!(coordinates, (1,0)) - for e in 1:num_matches - push!(coordinates,(2,0-(bfix*(e-1)))) - push!(coordinates,(5,0-(bfix*(e-1)))) - push!(coordinates,(9,0-(bfix*(e-1)))) - end - push!(coordinates,(10,0)) - push!(coordinates,(11,0)) - - i = 0 # hack for now - for node in superstructure.nodes - i += 1 - position[node.name] = coordinates[i] - end - - node_size = fill(1.0, length(superstructure.nodes)) - return(g, edge_labels, node_labels, position, node_size) +function get_stream_graph(args...; kwargs...) + # Concrete graph builder lives in optional extension + # `CompHENSNetworkXPlotsExt`. + error("Graph plotting requires the optional extension `CompHENSNetworkXPlotsExt` (install/load PyCall).") end diff --git a/src/SubProblems/Network_generation/network_generator_JuMP.jl b/src/SubProblems/Network_generation/network_generator_JuMP.jl index 0b77e3b..24a1ff6 100644 --- a/src/SubProblems/Network_generation/network_generator_JuMP.jl +++ b/src/SubProblems/Network_generation/network_generator_JuMP.jl @@ -43,6 +43,11 @@ function generate_network!(prob::ClassicHENSProblem, EMAT; optimizer, overall_ne haskey(prob.results_dict, :HLD_list) || error("Match list data not available. Solve corresponding subproblem first.") haskey(prob.results_dict, :T_bounds) || generate_temperature_bounds!(prob) + if any(!(super isa FloudasCiricGrossmann) for super in values(overall_network)) + @warn "BoundedParallel/ParallelSplit is unsupported. Rebuild overall_network with FloudasCiricGrossmann() for every stream and utility." + error("Unsupported superstructure detected. Only FloudasCiricGrossmann() is supported.") + end + #y, Q = prob.results_dict[:y], prob.results_dict[:Q] model = Model() @@ -67,9 +72,6 @@ function generate_network!(prob::ClassicHENSProblem, EMAT; optimizer, overall_ne @variable(model, 0.0 <= t[all_e_tuple_vec]) @variable(model, 0.0 <= f[stream_e_tuple_vec]) - # [WIP] - # set_starting_values && set_start_values(prob, EMAT, overall_network; verbose = verbose) - # 2. Sets stream-wise constraints for stream in prob.all_names add_stream_constraints!(model, prob.all_dict[stream], overall_network[stream], prob) @@ -98,6 +100,13 @@ function generate_network!(prob::ClassicHENSProblem, EMAT; optimizer, overall_ne set_objective_func!(model, HLD_list, obj_func, prob, EMAT; U_dict = U_dict, cost_coeff = cost_coeff, scaling_coeff = scaling_coeff, base_cost = base_cost) + # If user did not pass explicit starts, build combinatorial mCp-inspired starts. + # This keeps backward compatibility with explicit `initial_values` while improving + # IPOPT robustness on challenging networks. + if isnothing(initial_values) && set_starting_values + initial_values = build_network_start_values(prob, model, EMAT, overall_network, HLD_list; verbose = verbose) + end + # initial_values are a named tuple of (; v_names::Vector{VariableRef}, v_starts::Vector{Any}) if !isnothing(initial_values) @assert length(initial_values.v_names) == length(initial_values.v_starts) @@ -353,4 +362,3 @@ function set_match_objective!(hot::Union{HotStream, SimpleHotUtility}, cold::Uni @NLconstraint(hot_prob, hot_prob[:match_objective][cold.name] == coeff/(((2/3)*(hot_prob[:ΔT_upper][cold.name]*hot_prob[:ΔT_lower][cold.name])^0.5) - (1/6)*(hot_prob[:ΔT_upper][cold.name] + hot_prob[:ΔT_lower][cold.name]))) # Necessary to avoid the parsing error. end =# - diff --git a/src/SubProblems/Network_generation/network_postprocess.jl b/src/SubProblems/Network_generation/network_postprocess.jl index 9fc58b6..fd8b18a 100644 --- a/src/SubProblems/Network_generation/network_postprocess.jl +++ b/src/SubProblems/Network_generation/network_postprocess.jl @@ -22,6 +22,9 @@ Displays the matches and heat load distribution in a 2-D matrix form, maintains """ function postprocess_network!(prob::ClassicHENSProblem, model::AbstractModel, HLD_list, overall_network; results_path = nothing, visualize = true, digits = 4, display = true) results_df = DataFrame() + # Persist per-match area values so `get_design_area(prob)` remains valid + # for all example workflows after network generation. + areas = Dict{Tuple{String, String}, Float64}() match = HLD_list[1] for match in HLD_list hot, cold = match[1], match[2] @@ -42,8 +45,10 @@ function postprocess_network!(prob::ClassicHENSProblem, model::AbstractModel, HL ΔT_lower = smallest_value + value(model[:ΔT_lower][match]) LMTD = (ΔT_upper - ΔT_lower)/(smallest_value + log(ΔT_upper/ΔT_lower)) # Probable numerical issues. area = prob.results_dict[:Q][match[2], match[1]]/(LMTD*U(prob.all_dict[hot], prob.all_dict[cold])) + areas[(hot, cold)] = area push!(results_df, (Hot_stream = hot, Q = prob.results_dict[:Q][match[2], match[1]], Tin_Hot = value(model[:t][(hot, hot_hx_in_edge)]), Tout_Hot = value(model[:t][(hot, hot_hx_out_edge)]), Cold_stream = cold, Tin_Cold = value(model[:t][(cold, cold_hx_in_edge)]), Tout_Cold = value(model[:t][(cold, cold_hx_out_edge)]), ΔT_upper = ΔT_upper, ΔT_lower = ΔT_lower, LMTD = LMTD, U = U(prob.all_dict[hot], prob.all_dict[cold]), Area = area)) end + prob.results_dict[:areas] = areas return results_df end @@ -68,4 +73,3 @@ function get_design_area(prob::MultiPeriodFlexibleHENSProblem) end return area end - diff --git a/src/SubProblems/Network_generation/starting_point_generator.jl b/src/SubProblems/Network_generation/starting_point_generator.jl index d4f0c0e..b6e6b3f 100644 --- a/src/SubProblems/Network_generation/starting_point_generator.jl +++ b/src/SubProblems/Network_generation/starting_point_generator.jl @@ -1,62 +1,563 @@ -#[WIP] -#= -exportall(CompHENS) +using JuMP -verbose && @info "Solving the Network Generation subproblem" +""" +Heuristic warm-start builder for network generation NLPs. + +Implementation notes: +1. Mirrors the combinatorial mCp flow at a practical level: prioritize utility-quality matches, + attempt serial placement when feasible, and use paraT/alpha weighting for fallback parallel splits. +2. Produces starts for stream-edge temperatures/flows and match-level ΔT/LMTD terms. +3. Keeps all logic data-driven from `prob.results_dict[:HLD_list]` and `prob.results_dict[:Q]`. +""" + +""" +Return heat load `Q` for a hot stream to one matched cold stream/utility. +""" +function _stream_heat_load(prob::ClassicHENSProblem, stream::HotStream, match_name::String) + return prob.results_dict[:Q][match_name, stream.name] +end + +""" +Return heat load `Q` for a cold stream to one matched hot stream/utility. +""" +function _stream_heat_load(prob::ClassicHENSProblem, stream::ColdStream, match_name::String) + return prob.results_dict[:Q][stream.name, match_name] +end + +""" +Return mCp for streams and a safe proxy for utilities. +Utilities do not own mCp in this model, so a positive proxy keeps split formulas stable. +""" +function _mcp_or_proxy(stream) + if stream isa Union{HotStream, ColdStream} + return max(stream.mcp, smallest_value) + end + return 1.0 +end + +""" +Order matches for a hot stream by utility preference and heat quality. + +Rationale: +1. Cold utilities are prioritized at stream terminal positions. +2. Then sort by descending cold `T_out` to place tighter-quality cold matches earlier. +""" +function _ordered_matches(prob::ClassicHENSProblem, stream::HotStream) + matches = copy(prob.results_dict[:HLD_list][stream.name]) + sort!(matches; by = m -> begin + s = prob.all_dict[m] + util_priority = s isa SimpleColdUtility ? 1 : 0 + quality = -s.T_out + (util_priority, quality) + end) + return matches +end + +""" +Order matches for a cold stream by utility preference and heat quality. + +Rationale: +1. Hot utilities are prioritized at stream terminal positions. +2. Then sort by ascending hot `T_out` so lower-quality hot matches are allocated first. +""" +function _ordered_matches(prob::ClassicHENSProblem, stream::ColdStream) + matches = copy(prob.results_dict[:HLD_list][stream.name]) + sort!(matches; by = m -> begin + s = prob.all_dict[m] + util_priority = s isa SimpleHotUtility ? 1 : 0 + quality = s.T_out + (util_priority, quality) + end) + return matches +end + +function _ordered_matches(prob::ClassicHENSProblem, stream::AbstractUtility) + return copy(prob.results_dict[:HLD_list][stream.name]) +end + +""" +Return the unique HX node in one stream superstructure corresponding to one match. +""" +function _find_hx(superstructure::AbstractSplitSuperstructure, match_name::String) + return only(filter(v -> v.match == match_name, superstructure.hxs)) +end + +""" +Return the unique edge from `in_node` to `out_node` inside a superstructure. +""" +function _find_edge(superstructure::AbstractSplitSuperstructure, in_node::Node, out_node::Node) + return only(filter(e -> e.in == in_node && e.out == out_node, superstructure.edges)) +end + +""" +Propagate source-side stream temperature across outgoing splitter edges. + +Why: +To keep physically consistent starts before nonlinear mixer constraints are enforced. +""" +function _set_splitter_temperatures!(t_start::Dict{Edge, Float64}, stream_name::String, superstructure::AbstractSplitSuperstructure) + source_edge = only(out_edges(only(superstructure.source), superstructure)) + source_temp = t_start[source_edge] + for splitter in superstructure.splitters + edge_in = only(in_edges(splitter, superstructure)) + source_temp = get(t_start, edge_in, source_temp) + for edge_out in out_edges(splitter, superstructure) + t_start[edge_out] = source_temp + end + end + return +end + +""" +Check serial-feasibility for one hot stream across an ordered match list. + +The check uses both upper and lower approach temperature constraints with EMAT. +""" +function _serial_feasible(prob::ClassicHENSProblem, stream::HotStream, matches::Vector{String}, EMAT) + mcp = max(stream.mcp, smallest_value) + current_T = stream.T_in + for match in matches + q = _stream_heat_load(prob, stream, match) + other = prob.all_dict[match] + hot_in = current_T + hot_out = current_T - q / mcp + + if other isa ColdStream + other_mcp = max(other.mcp, smallest_value) + cold_in = other.T_in + cold_out = cold_in + q / other_mcp + elseif other isa SimpleColdUtility + cold_in = other.T_in + cold_out = other.T_out + else + return false + end + + if !(hot_in >= cold_out + EMAT && hot_out >= cold_in + EMAT) + return false + end + current_T = hot_out + end + return true +end + +""" +Check serial-feasibility for one cold stream across an ordered match list. + +The check uses both upper and lower approach temperature constraints with EMAT. +""" +function _serial_feasible(prob::ClassicHENSProblem, stream::ColdStream, matches::Vector{String}, EMAT) + mcp = max(stream.mcp, smallest_value) + current_T = stream.T_in + for match in matches + q = _stream_heat_load(prob, stream, match) + other = prob.all_dict[match] + cold_in = current_T + cold_out = current_T + q / mcp + + if other isa HotStream + other_mcp = max(other.mcp, smallest_value) + hot_in = other.T_in + hot_out = hot_in - q / other_mcp + elseif other isa SimpleHotUtility + hot_in = other.T_in + hot_out = other.T_out + else + return false + end + + if !(hot_in >= cold_out + EMAT && hot_out >= cold_in + EMAT) + return false + end + current_T = cold_out + end + return true +end + +function _serial_feasible(prob::ClassicHENSProblem, stream::AbstractUtility, matches::Vector{String}, EMAT) + return false +end + +""" +Compute combinatorial-style parallel split weights for one stream. + +Formula implemented from extracted method: +1. `paraT = quality_dT + Q/mCp_other` +2. `alpha = Q/paraT` +3. `split = alpha / sum(alpha)` +""" +function _parallel_split_weights(prob::ClassicHENSProblem, stream::Union{HotStream, ColdStream}, matches::Vector{String}, EMAT) + alpha = Float64[] + for match in matches + q = _stream_heat_load(prob, stream, match) + other = prob.all_dict[match] + other_mcp = _mcp_or_proxy(other) + + quality_dT = if stream isa HotStream + stream.T_in - other.T_out + else + other.T_in - stream.T_in + end + paraT = max(quality_dT, EMAT / 10) + q / other_mcp + push!(alpha, q / max(paraT, smallest_value)) + end + + total = sum(alpha) + if total <= smallest_value + qvals = [_stream_heat_load(prob, stream, m) for m in matches] + total_q = max(sum(qvals), smallest_value) + return [q / total_q for q in qvals] + end + return [a / total for a in alpha] +end + +""" +Uniform split fallback for utility-only branches. +""" +function _parallel_split_weights(prob::ClassicHENSProblem, stream::AbstractUtility, matches::Vector{String}, EMAT) + n = max(length(matches), 1) + return fill(1.0 / n, n) +end + +""" +Initialize per-edge temperature/flow starts with source/sink anchors. +""" +function _initialize_stream_defaults!(prob::ClassicHENSProblem, stream_name::String, superstructure::AbstractSplitSuperstructure) + stream = prob.all_dict[stream_name] + t_start = Dict{Edge, Float64}(edge => stream.T_in for edge in superstructure.edges) + f_start = Dict{Edge, Float64}(edge => 0.0 for edge in superstructure.edges) -haskey(prob.results_dict, :y) || error("Stream match data not available. Solve corresponding subproblem first.") -haskey(prob.results_dict, :Q) || error("HLD data not available. Solve corresponding subproblem first.") -haskey(prob.results_dict, :HLD_list) || error("Match list data not available. Solve corresponding subproblem first.") -haskey(prob.results_dict, :T_bounds) || generate_temperature_bounds!(prob) + source_edge = only(out_edges(only(superstructure.source), superstructure)) + sink_edge = only(in_edges(only(superstructure.sink), superstructure)) + t_start[source_edge] = stream.T_in + t_start[sink_edge] = stream.T_out -#y, Q = prob.results_dict[:y], prob.results_dict[:Q] + if stream isa Union{HotStream, ColdStream} + f_start[source_edge] = stream.mcp + f_start[sink_edge] = stream.mcp + end + + return t_start, f_start +end + +""" +Apply serial warm-starts over ordered matches for split superstructures. + +Effect: +1. Sends full stream mCp through one active branch at a time. +2. Connects branch exits serially toward subsequent matches. +3. Updates edge temperatures through each exchanged heat load. +""" +function _apply_serial_starts!(prob::ClassicHENSProblem, stream::Union{HotStream, ColdStream}, superstructure::AbstractSplitSuperstructure, matches::Vector{String}, t_start::Dict{Edge, Float64}, f_start::Dict{Edge, Float64}) + mcp = max(stream.mcp, smallest_value) + source_node = only(superstructure.source) + bs_node = only(get_destination_nodes(source_node, superstructure)) + + current_T = stream.T_in + source_edge = only(out_edges(source_node, superstructure)) + t_start[source_edge] = stream.T_in + + for edge in out_edges(bs_node, superstructure) + t_start[edge] = stream.T_in + end + + for (i, match) in enumerate(matches) + hx = _find_hx(superstructure, match) + hx_in_edge = only(in_edges(hx, superstructure)) + hx_out_edge = only(out_edges(hx, superstructure)) + + sm_node = only(get_source_nodes(hx, superstructure)) + bs_to_sm = _find_edge(superstructure, bs_node, sm_node) + + # In serial mode, only the first match receives flow directly from the + # major splitter. Downstream matches are fed by upstream minor splitters. + if i == 1 + f_start[bs_to_sm] = stream.mcp + else + f_start[bs_to_sm] = 0.0 + end + f_start[hx_in_edge] = stream.mcp + f_start[hx_out_edge] = stream.mcp + + t_start[hx_in_edge] = current_T + + q = _stream_heat_load(prob, stream, match) + next_T = if stream isa HotStream + current_T - q / mcp + else + current_T + q / mcp + end + t_start[hx_out_edge] = next_T + + ss_node = only(get_destination_nodes(hx, superstructure)) + if i < length(matches) + next_hx = _find_hx(superstructure, matches[i + 1]) + next_sm = only(get_source_nodes(next_hx, superstructure)) + link_edge = _find_edge(superstructure, ss_node, next_sm) + f_start[link_edge] = stream.mcp + t_start[link_edge] = next_T + else + bm_node = only(superstructure.major_mixer) + ss_to_bm = _find_edge(superstructure, ss_node, bm_node) + f_start[ss_to_bm] = stream.mcp + t_start[ss_to_bm] = next_T + end + + current_T = next_T + end + + sink_edge = only(in_edges(only(superstructure.sink), superstructure)) + t_start[sink_edge] = current_T + f_start[sink_edge] = stream.mcp + + _set_splitter_temperatures!(t_start, stream.name, superstructure) + return +end + +""" +Apply parallel warm-starts over ordered matches using computed split fractions. + +Effect: +1. Splits mCp across branches according to paraT/alpha weighting. +2. Computes each branch outlet temperature from assigned branch flow and heat load. +3. Mixes branch outlets to seed sink temperature. +""" +function _apply_parallel_starts!(prob::ClassicHENSProblem, stream::Union{HotStream, ColdStream}, superstructure::AbstractSplitSuperstructure, matches::Vector{String}, t_start::Dict{Edge, Float64}, f_start::Dict{Edge, Float64}, EMAT) + split = _parallel_split_weights(prob, stream, matches, EMAT) + source_node = only(superstructure.source) + bs_node = only(get_destination_nodes(source_node, superstructure)) + bm_node = only(superstructure.major_mixer) + + source_edge = only(out_edges(source_node, superstructure)) + t_start[source_edge] = stream.T_in + + for edge in out_edges(bs_node, superstructure) + t_start[edge] = stream.T_in + end + + branch_T_out = Float64[] + branch_f = Float64[] + + for (i, match) in enumerate(matches) + hx = _find_hx(superstructure, match) + hx_in_edge = only(in_edges(hx, superstructure)) + hx_out_edge = only(out_edges(hx, superstructure)) + + # Keep branch-flow conservation exact at the major mixer. + # A nonzero denominator safeguard is applied only in temperature update. + f_branch = split[i] * stream.mcp + q = _stream_heat_load(prob, stream, match) + t_out = if stream isa HotStream + stream.T_in - q / max(f_branch, smallest_value) + else + stream.T_in + q / max(f_branch, smallest_value) + end + + if hx_in_edge.in == bs_node + f_start[hx_in_edge] = f_branch + t_start[hx_in_edge] = stream.T_in + else + sm_node = hx_in_edge.in + bs_to_sm = _find_edge(superstructure, bs_node, sm_node) + f_start[bs_to_sm] = f_branch + t_start[bs_to_sm] = stream.T_in + f_start[hx_in_edge] = f_branch + t_start[hx_in_edge] = stream.T_in + end + + f_start[hx_out_edge] = f_branch + t_start[hx_out_edge] = t_out + + if hx_out_edge.out == bm_node + f_start[hx_out_edge] = f_branch + t_start[hx_out_edge] = t_out + else + ss_node = hx_out_edge.out + ss_to_bm = _find_edge(superstructure, ss_node, bm_node) + f_start[ss_to_bm] = f_branch + t_start[ss_to_bm] = t_out + end + + push!(branch_T_out, t_out) + push!(branch_f, f_branch) + end + + sink_edge = only(in_edges(only(superstructure.sink), superstructure)) + mixed_T = sum(branch_T_out[i] * branch_f[i] for i in eachindex(branch_f)) / max(sum(branch_f), smallest_value) + t_start[sink_edge] = mixed_T + f_start[sink_edge] = sum(branch_f) + + _set_splitter_temperatures!(t_start, stream.name, superstructure) + return +end -model = Model() +""" +Seed utility stream temperatures around HX-adjacent edges. -# Tuple set with stream and utility s and Edge e -all_e_tuple_vec = [] -for stream in prob.all_names - for edge in overall_network[stream].edges - push!(all_e_tuple_vec, (stream, edge)) +Utilities do not carry `f` variables in this formulation. +""" +function _apply_utility_starts!(stream::AbstractUtility, superstructure::AbstractSplitSuperstructure, t_start::Dict{Edge, Float64}) + source_edge = only(out_edges(only(superstructure.source), superstructure)) + sink_edge = only(in_edges(only(superstructure.sink), superstructure)) + t_start[source_edge] = stream.T_in + t_start[sink_edge] = stream.T_out + + for edge in superstructure.edges + if edge.in isa HX + t_start[edge] = stream.T_out + elseif edge.out isa HX + t_start[edge] = stream.T_in + end end + return end -# Tuple set with only streams (not utilities) and edges e -stream_e_tuple_vec = [] -for stream in prob.stream_names - for edge in overall_network[stream].edges - push!(stream_e_tuple_vec, (stream, edge)) +""" +Validate that candidate stream starts stay within declared model bounds. + +This is used as a guardrail for parallel warm starts: if a split allocation +drives branch temperatures/flows out of bounds, we fall back to serial starts. +""" +function _starts_within_bounds(prob::ClassicHENSProblem, stream::Union{HotStream, ColdStream}, superstructure::AbstractSplitSuperstructure, t_start::Dict{Edge, Float64}, f_start::Dict{Edge, Float64}; atol = 1e-6) + t_low, t_high = prob.results_dict[:T_bounds][stream.name] + f_high = max(stream.mcp, 0.0) + + for edge in superstructure.edges + t_val = get(t_start, edge, stream.T_in) + if !isfinite(t_val) || t_val < t_low - atol || t_val > t_high + atol + return false + end + + f_val = get(f_start, edge, 0.0) + if !isfinite(f_val) || f_val < -atol || f_val > f_high + atol + return false + end end + + return true end -# 1. Declaring the stream-wise variables -@variable(model, 0.0 <= t[all_e_tuple_vec]) -@variable(model, 0.0 <= f[stream_e_tuple_vec]) +""" +Build edge-level warm starts for one stream. + +Selection rule: +1. Utilities use utility-specific temperature seeding. +2. Process streams use serial starts when feasible. +3. Otherwise, process streams use parallel paraT/alpha starts. +""" +function _starts_for_stream!(prob::ClassicHENSProblem, stream_name::String, EMAT, superstructure::AbstractSplitSuperstructure) + stream = prob.all_dict[stream_name] + t_start, f_start = _initialize_stream_defaults!(prob, stream_name, superstructure) + + if stream isa AbstractUtility + _apply_utility_starts!(stream, superstructure, t_start) + return t_start, f_start + end -#function set_start_values!(prob, EMAT, overall_network; verbose = verbose) - # 1. Initialize the required dictionaries for book-keeping: - prob.results_dict[:unflagged_matches] = deepcopy(filter(prob.results_dict[:HX_list]) do (k,v) - k in prob.stream_names + matches = _ordered_matches(prob, stream) + if isempty(matches) + return t_start, f_start end - ) - prob.results_dict[:working_terminal_temp] = Dict(stream => prob.streams_dict[stream].T_out for stream in prob.stream_names) - prob.results_dict[:working_terminal_node] = Dict(stream => only(overall_network[stream].major_mixer) for stream in prob.stream_names) + can_serial = superstructure isa FloudasCiricGrossmann && _serial_feasible(prob, stream, matches, EMAT) + if can_serial + _apply_serial_starts!(prob, stream, superstructure, matches, t_start, f_start) + else + _apply_parallel_starts!(prob, stream, superstructure, matches, t_start, f_start, EMAT) + if !_starts_within_bounds(prob, stream, superstructure, t_start, f_start) + _apply_serial_starts!(prob, stream, superstructure, matches, t_start, f_start) + end + end + + return t_start, f_start +end + +""" +Create starts for match-level ΔT variables and optional LMTD variables. + +Why: +The NLP objective and feasibility constraints depend on these match variables; supplying +consistent starts reduces first-iteration infeasibility and improves IPOPT stability. +""" +function _match_temperature_starts!(prob::ClassicHENSProblem, model::AbstractModel, HLD_list, overall_network, EMAT) + start_vals = Dict{VariableRef, Float64}() + + has_T_lmtd = haskey(JuMP.object_dictionary(model), :T_LMTD) + for match in HLD_list + hot_name, cold_name = match + hot_super = overall_network[hot_name] + cold_super = overall_network[cold_name] + hot_hx = _find_hx(hot_super, cold_name) + cold_hx = _find_hx(cold_super, hot_name) + + hot_hx_in = only(in_edges(hot_hx, hot_super)) + hot_hx_out = only(out_edges(hot_hx, hot_super)) + cold_hx_in = only(in_edges(cold_hx, cold_super)) + cold_hx_out = only(out_edges(cold_hx, cold_super)) + t_hot_in = JuMP.start_value(model[:t][(hot_name, hot_hx_in)]) + t_hot_out = JuMP.start_value(model[:t][(hot_name, hot_hx_out)]) + t_cold_in = JuMP.start_value(model[:t][(cold_name, cold_hx_in)]) + t_cold_out = JuMP.start_value(model[:t][(cold_name, cold_hx_out)]) + dt_u = max(t_hot_in - t_cold_out, EMAT + 1e-3) + dt_l = max(t_hot_out - t_cold_in, EMAT + 1e-3) + + start_vals[model[:ΔT_upper][match]] = dt_u + start_vals[model[:ΔT_lower][match]] = dt_l + + if has_T_lmtd + lmtd = smallest_value + (2 / 3) * sqrt(dt_u * dt_l) + (1 / 6) * (dt_u + dt_l) + start_vals[model[:T_LMTD][match]] = max(lmtd, smallest_value) + end + end + + return start_vals +end -stream = prob.all_dict["C1"] -superstructure = overall_network["C1"] """ -$(TYPEDSIGNATURES) -Used to set the starting values of the network generation NLP. -This specifies that a given `match` HX should be placed serially at the working terminal of a given `stream`. -Initially, the `working_terminal_node` of a stream is its `MajorMixer`. If a `HX` match is set to be at the terminal, then the `working_terminal_node` is changed to the mixer feeding this `HX`. -The, `working_terminal_temp` is changed from `T_out` and calculated for each added terminal match. +Public entry-point: generate warm starts for network-generation NLP. + +Returned structure: +`(; v_names::Vector{VariableRef}, v_starts::Vector{Float64})` + +This function sets starts directly on model variables and also returns them to preserve +the existing `initial_values` interface used by `generate_network!`. """ -#function set_terminal_match!(model::AbstractModel, prob, stream::ColdStream, superstructure::AbstractSplitSuperstructure, match ; verbose = true) - # A. Set starting values for the flows: - set_start_value(model[:t][(stream.name, only(out_edges(only(superstructure.source), superstructure)))], 69.0) -=# +function build_network_start_values(prob::ClassicHENSProblem, model::AbstractModel, EMAT, overall_network::Dict{String, AbstractSuperstructure}, HLD_list; verbose = false) + v_names = VariableRef[] + v_starts = Float64[] + + for stream_name in prob.all_names + superstructure = overall_network[stream_name] + superstructure isa AbstractSplitSuperstructure || continue + t_start, f_start = _starts_for_stream!(prob, stream_name, EMAT, superstructure) + for edge in superstructure.edges + t_var = model[:t][(stream_name, edge)] + t_val = get(t_start, edge, prob.all_dict[stream_name].T_in) + push!(v_names, t_var) + push!(v_starts, t_val) + JuMP.set_start_value(t_var, t_val) + + if prob.all_dict[stream_name] isa AbstractStream + f_var = model[:f][(stream_name, edge)] + f_val = get(f_start, edge, 0.0) + push!(v_names, f_var) + push!(v_starts, f_val) + JuMP.set_start_value(f_var, f_val) + end + end + end + + match_starts = _match_temperature_starts!(prob, model, HLD_list, overall_network, EMAT) + for (v, s) in match_starts + push!(v_names, v) + push!(v_starts, s) + JuMP.set_start_value(v, s) + end + + verbose && @info "Generated starting values from combinatorial mCp heuristics" n_vars = length(v_names) + return (; v_names, v_starts) +end diff --git a/src/SubProblems/generate_stream_matches.jl b/src/SubProblems/generate_stream_matches.jl index af01045..4e447f4 100644 --- a/src/SubProblems/generate_stream_matches.jl +++ b/src/SubProblems/generate_stream_matches.jl @@ -1,6 +1,5 @@ using JuMP using HiGHS -using NamedArrays using MathOptInterface """ @@ -111,8 +110,8 @@ function post_HLD_matches!(prob::ClassicHENSProblem, model::AbstractModel, level Q_match = zeros(Float64, length(C_set), length(H_set)) y_match = zeros(Int, length(C_set), length(H_set)) - Q = NamedArray(Q_match, (C_set, H_set)) - y = NamedArray(y_match, (C_set, H_set)) + Q = JuMP.Containers.DenseAxisArray(Q_match, C_set, H_set) + y = JuMP.Containers.DenseAxisArray(y_match, C_set, H_set) for i in H_set for j in C_set @@ -157,24 +156,27 @@ function post_HLD_matches!(prob::ClassicHENSProblem, model::AbstractModel, level return end -#= Deprecated """ $(TYPEDSIGNATURES) -Displays the matches and heat load distribution in a 2-D matrix form. +Displays the current heat-load distribution matrix for `ClassicHENSProblem`. +Returns a `DenseAxisArray` indexed by cold-side names (rows) and hot-side names (columns). """ -function print_HLD(prob::ClassicHENSProblem) - hot_names = vcat(prob.stream_names[:hot_streams], prob.stream_names[:hot_utilities]) - cold_names = vcat(prob.stream_names[:cold_streams], prob.stream_names[:cold_utilities]) - Q = zeros(Float64, length(cold_names), length(hot_names)) - hld = NamedArray(Q, (cold_names, hot_names)) - for (name,val) in enamerate(hld) - hld[name[1], name[2]] = round(prob.results_dict[:Q][(name[2], name[1])]; digits = 1) +function print_HLD(prob::ClassicHENSProblem; digits = 1) + haskey(prob.results_dict, :Q) || error("Heat load data not available. Run `generate_stream_matches!` first.") + hot_names = prob.hot_names + cold_names = prob.cold_names + + hld = JuMP.Containers.DenseAxisArray(zeros(Float64, length(cold_names), length(hot_names)), cold_names, hot_names) + for hot in hot_names + for cold in cold_names + hld[cold, hot] = round(prob.results_dict[:Q][cold, hot]; digits = digits) + end end + @show hld return hld end -=# """ $(TYPEDSIGNATURES) @@ -318,10 +320,10 @@ function post_HLD_matches!(prob::MultiPeriodFlexibleHENSProblem, model::Abstract end y_match = zeros(Int, length(C_set), length(H_set)) - y = NamedArray(y_match, (C_set, H_set)) + y = JuMP.Containers.DenseAxisArray(y_match, C_set, H_set) for t in prob.period_names Q_match = zeros(Float64, length(C_set), length(H_set)) - Q = NamedArray(Q_match, (C_set, H_set)) + Q = JuMP.Containers.DenseAxisArray(Q_match, C_set, H_set) for i in H_set for j in C_set y[j,i] = round(value(model[:y][i,j]); digits = 0) @@ -378,4 +380,3 @@ function print_HLD(prob::MultiPeriodFlexibleHENSProblem) end return end - diff --git a/src/SubProblems/minimum_number_of_units.jl b/src/SubProblems/minimum_number_of_units.jl index 1fd9eab..d918328 100644 --- a/src/SubProblems/minimum_number_of_units.jl +++ b/src/SubProblems/minimum_number_of_units.jl @@ -1,6 +1,19 @@ using JuMP using HiGHS +""" +Round a solver objective to an integer with a strict absolute tolerance. + +The minimum-units MILP objective is integer by construction. Some solvers can +return values like `8.99999999999999`, so we allow only tiny floating-point +noise and throw if the result is materially non-integer. +""" +function _strict_integer_objective(value::Real; atol::Float64 = 1e-8) + rounded = round(Int, value) + abs(value - rounded) <= atol || error("Minimum-units objective is non-integer: $(value) (rounded=$(rounded), atol=$(atol)).") + return rounded +end + """ $(TYPEDSIGNATURES) @@ -62,7 +75,7 @@ function solve_minimum_units_subproblem!(prob::ClassicHENSProblem; time_limit = end # Post-processing - min_units = Int(objective_value(model)) + min_units = _strict_integer_objective(objective_value(model)) verbose && println("Minimum number of units: $(min_units)") prob.results_dict[:min_units] = min_units return @@ -163,9 +176,8 @@ function solve_minimum_units_subproblem!(prob::MultiPeriodFlexibleHENSProblem; o end # Post-processing - min_units = Int(round(objective_value(model); digits = 0)) + min_units = _strict_integer_objective(objective_value(model)) verbose && println("Minimum number of units: $(min_units)") prob.results_dict[:min_units] = min_units return end - diff --git a/src/Superstructures/FloudasCiricGrossmann.jl b/src/Superstructures/FloudasCiricGrossmann.jl index 5c9aa5b..9702d3b 100644 --- a/src/Superstructures/FloudasCiricGrossmann.jl +++ b/src/Superstructures/FloudasCiricGrossmann.jl @@ -26,12 +26,13 @@ Naming convention for `nodes`. Type of the node (see below) `_ edge.in == mixer, edges)) == 1 || error("Each mixer only has a single outgoing edge") end - return FloudasCiricGrossmann(nodes, edges) + return FloudasCiricGrossmann(nodes, edges, Dict{String, Any}()) end function construct_superstructure(stream::String, superstructure::FloudasCiricGrossmann, prob::ClassicHENSProblem; verbose = true) diff --git a/src/Superstructures/ParallelSplit.jl b/src/Superstructures/ParallelSplit.jl index e253834..89f0215 100644 --- a/src/Superstructures/ParallelSplit.jl +++ b/src/Superstructures/ParallelSplit.jl @@ -15,45 +15,27 @@ struct ParallelSplit <: AbstractSplitSuperstructure edges::Union{Nothing, Vector{Edge}} end +""" +Throw a clear warning + error for unsupported bounded-parallel superstructures. + +The current NLP workflow is validated only with `FloudasCiricGrossmann()`. +""" +function _parallel_split_unsupported() + @warn "BoundedParallel/ParallelSplit is unsupported for network generation. Use FloudasCiricGrossmann() for all streams and utilities." + error("ParallelSplit is disabled. Use FloudasCiricGrossmann().") +end + function ParallelSplit(; verbose = true) - verbose && @info "Using Superstructure: Parallel split of streams once at start and merge once at end" - ParallelSplit(nothing, nothing) + _parallel_split_unsupported() end function ParallelSplit(stream::String, prob::ClassicHENSProblem; verbose = true) - nodes = Node[] - push!(nodes, Source("SO_$(stream)")) - push!(nodes, MajorSplitter("BS_$(stream)")) - for match in prob.results_dict[:HLD_list][stream] - push!(nodes, HX("HX_$(stream)_$(match)", match)) - end - push!(nodes, MajorMixer("BM_$(stream)")) - push!(nodes, Sink("SK_$(stream)")) - - edges = Edge[] - for v in nodes - for node in define_out_nodes(v, nodes, ParallelSplit(; verbose = false)) - push!(edges, Edge(v, node)) - end - end - - # Sanity tests - length(nodes) == length(prob.results_dict[:HLD_list][stream]) + 4 || error("Incorrect number of nodes generated!") - length(edges) == (2 + 2*length(prob.results_dict[:HLD_list][stream])) || error("Incorrect number of edges generated!") - - for splitter in filter(v -> (v isa Splitter), nodes) - length(filter(edge -> edge.out == splitter, edges)) == 1 || error("Each splitter only has single incoming edge") - end - - for mixer in filter(v -> (v isa Mixer), nodes) - length(filter(edge -> edge.in == mixer, edges)) == 1 || error("Each mixer only has a single outgoing edge") - end - return ParallelSplit(nodes, edges) + _parallel_split_unsupported() end # Macro to do this? function construct_superstructure(stream::String, superstructure::ParallelSplit, prob::ClassicHENSProblem; verbose = true) - ParallelSplit(stream, prob; verbose = verbose) + _parallel_split_unsupported() end function define_out_nodes(node::MajorSplitter, nodes::Vector{Node}, superstructure::ParallelSplit) @@ -69,4 +51,4 @@ function define_out_nodes(node::HX, nodes::Vector{Node}, superstructure::Paralle v isa MajorMixer end return out_nodes -end \ No newline at end of file +end diff --git a/test/runtests.jl b/test/runtests.jl index 25f0aad..aabdd4b 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -5,4 +5,26 @@ using Test @testset "Problem Construction" begin include("classic_hens_constructor.jl") end + + @testset "XLSX Interface Examples" begin + # Ensure plotting backends run headless in CI. + ENV["GKSwstype"] = "100" + + examples_root = joinpath(@__DIR__, "..", "Examples", "XLSX_interface") + example_files = [ + joinpath(examples_root, "ClassicHENSProblem", "6_Stream", "6_stream.jl"), + joinpath(examples_root, "ClassicHENSProblem", "Colberg_Morari_1990", "ColbergMorari.jl"), + joinpath(examples_root, "ClassicHENSProblem", "TEP4125_Examples", "Assignment_2.xlsx", "Assignment_2.jl"), + joinpath(examples_root, "ClassicHENSProblem", "NaN_MWE", "NaN_MWE.jl"), + joinpath(examples_root, "ClassicHENSProblem", "NaN_MWE", "Infeasible_issue.jl"), + joinpath(examples_root, "ClassicHENSProblem", "Gundersen_4_stream", "Gundersen_4_stream.jl"), + joinpath(examples_root, "MultiPeriodFlexibleHENSProblem", "Floudas_Grossmann_1987", "FloudasGrossmann1987.jl"), + ] + + for file in example_files + @testset "$(basename(file))" begin + include(file) + end + end + end end