Горизонтальная разводка отопления по этажу МКД
作者
using Plots
using Plots.Measures
plotlyjs()
"""
display_plotly_safe(p; base_width=1050, base_height=680)
Оборачивает интерактивный график Plotly в адаптивный iframe (srcdoc)
с точной высотой рамки без пустого белого пространства снизу.
"""
function display_plotly_safe(p; base_width::Int = 1050, base_height::Int = 680)
io = IOBuffer()
show(io, MIME"text/html"(), p)
html_str = String(take!(io))
# 1. Заменяем жёсткие размеры в CSS на 100%
html_str = replace(html_str, r"width:\s*\d+(\.\d+)?px"i => "width:100%")
html_str = replace(html_str, r"height:\s*\d+(\.\d+)?px"i => "height:100%")
# 2. Убираем жёсткие размеры только у крупного холста (>= 100px), не затрагивая толщину линий (width: 2)
html_str = replace(html_str, r"\"width\":\s*[1-9]\d{2,}(\.\d+)?" => "\"width\": null")
html_str = replace(html_str, r"\"height\":\s*[1-9]\d{2,}(\.\d+)?" => "\"height\": $(base_height)")
# 3. Сжимаем 16-значные числа в JSON до 4 знаков после запятой для экономии места в srcdoc
html_str = replace(html_str, r"(-?\d+\.\d{4})\d+" => s"\1")
# 4. Адаптируем ширину под окно iframe
resize_script = """
<style>
html, body { margin: 0; padding: 0; overflow: hidden; background: white; }
</style>
<script>
function fitPlotlyToFrame() {
var w = window.innerWidth;
if (!window.Plotly || w < 100) return;
var plots = document.querySelectorAll('.plotly-graph-div');
plots.forEach(function(el) {
Plotly.relayout(el, { width: w, height: $(base_height) });
});
}
window.addEventListener('load', function() {
fitPlotlyToFrame();
setTimeout(fitPlotlyToFrame, 150);
setTimeout(fitPlotlyToFrame, 500);
});
window.addEventListener('resize', fitPlotlyToFrame);
</script>
"""
html_str *= resize_script
escaped_html = replace(html_str, "\"" => """)
iframe_html = """
<div style="display: flex; justify-content: center; width: 100%; margin: 8px 0;">
<div style="width: 100%; max-width: $(base_width)px; height: $(base_height)px;">
<iframe
srcdoc="$escaped_html"
style="width: 100%; height: $(base_height)px; border: 1px solid #eaeaea; border-radius: 6px; background-color: white; box-shadow: 0 4px 6px rgba(0,0,0,0.05);"
sandbox="allow-scripts allow-same-origin">
</iframe>
</div>
</div>
"""
display("text/html", iframe_html)
end
"""
run_asv_sweep(configs; kwargs...)
Универсальный последовательный расчёт списка конфигураций для любых имён моделей.
Считывает температуры (°C), расходы по комнатам, давления и перемещение штока клапана.
"""
function run_asv_sweep(
configs::AbstractVector;
simulation_time::Real = 100.0,
time_step::Real = 0.05,
target_dt::Real = 5.0,
outside_temp::Real = -35.0
)
global Outside_Temp = Float64(outside_temp)
results = []
for (i, cfg) in enumerate(configs)
m_name = cfg.model
engee.set_param!(m_name, "StopTime" => Float64(simulation_time), "FixedStep" => Float64(time_step))
if cfg.has_asv
global k = Float64(cfg.k)
global ForceStart = Float64(cfg.ForceStart)
println("Запуск $(i) из $(length(configs)): [$(m_name)] $(cfg.label) (k = $(k) Н/м, ForceStart = $(round(ForceStart, digits=2)) Н)")
else
println("Запуск $(i) из $(length(configs)): [$(m_name)] $(cfg.label)")
end
flush(stdout)
engee.run(m_name)
# Опорная шкала времени
time_raw = nothing
for ref_rel_path in [
"ASV-P/Pressure_Sensor_Supply/P_Supply",
"P_Return_Common_Line",
"Flat_1_Room_1/Temp_Flat1_R1"
]
try
time_raw = vec(collect(WorkspaceArray{Float64}("$m_name/$ref_rel_path")).time)
break
catch
end
end
isnothing(time_raw) && error("Не удалось найти базовый сигнал времени в модели $m_name")
n_pts = length(time_raw)
n_pts == 0 && error("Модель $m_name вернула пустой массив времени (0 точек)")
# Расчёт шага прореживания по параметру target_dt из ячейки 1
total_span = n_pts > 1 ? (last(time_raw) - first(time_raw)) : Float64(simulation_time)
target_pts = max(2, round(Int, total_span / target_dt) + 1)
step_size = max(1, fld(n_pts, target_pts))
idx = 1:step_size:n_pts
function get_ds_safe(rel_path::String; offset::Real = 0.0)
full_path = "$m_name/$rel_path"
try
vals = vec(collect(WorkspaceArray{Float64}(full_path)).value)
if length(vals) == n_pts
return vals[idx] .+ offset
else
s_step = max(1, fld(length(vals), length(idx)))
return vals[1:s_step:end] .+ offset
end
catch
@warn "Сигнал $full_path не найден в модели $m_name — заполнено нулями"
return zeros(Float64, length(idx))
end
end
run_data = (
label = cfg.label,
model = m_name,
has_asv = cfg.has_asv,
time = time_raw[idx],
Disp_ASV = get_ds_safe("ASV-P/Disp"),
# Температуры по комнатам (°C)
Temp_F1R1 = get_ds_safe("Flat_1_Room_1/Temp_Flat1_R1"; offset = -273.15),
Temp_F1R2 = get_ds_safe("Flat_1_Room_2/Temp_Flat1_R2"; offset = -273.15),
Temp_F1R3 = get_ds_safe("Flat_1_Room_3/Temp_Flat1_R3"; offset = -273.15),
Temp_F2R1 = get_ds_safe("Flat_2_Room_1/Temp_Flat2_R1"; offset = -273.15),
Temp_F2R2 = get_ds_safe("Flat_2_Room_2/Temp_Flat2_R2"; offset = -273.15),
# Расходы по комнатам (л/мин)
Flow_F1R1 = get_ds_safe("Branch_F1R1/F1R1_Supply/FR_Flat1_R1"),
Flow_F1R2 = get_ds_safe("Branch_F1R2/F1R2_Supply/FR_Flat1_R2"),
Flow_F1R3 = get_ds_safe("Branch_F1R3/F1R3_Supply/FR_Flat1_R3"),
Flow_F2R1 = get_ds_safe("Branch_F2R1/F2R1_Supply/FR_Flat2_R1"),
Flow_F2R2 = get_ds_safe("Branch_F2R2/F2R2_Supply/FR_Flat2_R2"),
# Давления
P_Supply = get_ds_safe("ASV-P/Pressure_Sensor_Supply/P_Supply"),
P_Return = get_ds_safe("ASV-P/Pressure_Sensor_Return/P_Return"),
P_Common = get_ds_safe("P_Return_Common_Line")
)
push!(results, run_data)
end
return results
end
"""
_plot_room_grid(results, signal_keys, ylabel_str; y_limits=nothing)
Универсальная сетка (3×2) из 5 графиков по комнатам и общей легендой в пустом 6-м слоте.
"""
function _plot_room_grid(results, signal_keys::AbstractVector{Symbol}, ylabel_str::String; y_limits = nothing)
room_titles = [
"Квартира 1, Комната 1",
"Квартира 1, Комната 2",
"Квартира 1, Комната 3",
"Квартира 2, Комната 1",
"Квартира 2, Комната 2"
]
line_colors = [:royalblue, :orange, :seagreen, :crimson]
line_styles = [:solid, :solid, :solid, :dashdot]
subplots = []
for (idx_sub, (key, title_str)) in enumerate(zip(signal_keys, room_titles))
x_lbl = idx_sub in (4, 5) ? "Время, с" : ""
p = plot(
title = title_str,
xlabel = x_lbl,
ylabel = ylabel_str,
left_margin = 16mm,
right_margin = 5mm,
top_margin = 6mm,
bottom_margin = 4mm
)
!isnothing(y_limits) && ylims!(p, y_limits)
for (res, clr, stl) in zip(results, line_colors, line_styles)
lbl = idx_sub == 1 ? (res.has_asv ? "Δp = $(res.label)" : res.label) : ""
plot!(p, res.time, res[key], label = lbl, lw = 2, color = clr, linestyle = stl)
end
push!(subplots, p)
end
# Пустой 6-й слот (справа снизу) — место под общую легенду
p_empty = plot(
grid = false,
showaxis = false,
ticks = false,
framestyle = :none
)
push!(subplots, p_empty)
p = plot(
subplots...,
layout = (3, 2),
size = (1050, 680),
legend = (0.62, 0.31),
legendfontsize = 11,
background_color_legend = RGBA(1, 1, 1, 0.95),
foreground_color_legend = :lightgray,
titlefont = font(11),
guidefont = font(10),
tickfont = font(9)
)
display_plotly_safe(p; base_width = 1050, base_height = 680)
return nothing
end
"""
plot_room_temperatures(results)
Холст 1: 5 графиков температур по комнатам (°C) с общей легендой.
"""
function plot_room_temperatures(results)
temp_keys = [:Temp_F1R1, :Temp_F1R2, :Temp_F1R3, :Temp_F2R1, :Temp_F2R2]
return _plot_room_grid(results, temp_keys, "Температура, °C")
end
"""
plot_room_flows(results; y_limits=(0, 8))
Холст 3: 5 графиков расходов теплоносителя по комнатам (л/мин, от 0 до 8)
с приведением к положительному знаку и общей легендой.
"""
function plot_room_flows(results; y_limits = (0, 8))
flow_keys = [:Flow_F1R1, :Flow_F1R2, :Flow_F1R3, :Flow_F2R1, :Flow_F2R2]
pos_results = [
merge(res, (
Flow_F1R1 = last(res.Flow_F1R1) < 0 ? -res.Flow_F1R1 : res.Flow_F1R1,
Flow_F1R2 = last(res.Flow_F1R2) < 0 ? -res.Flow_F1R2 : res.Flow_F1R2,
Flow_F1R3 = last(res.Flow_F1R3) < 0 ? -res.Flow_F1R3 : res.Flow_F1R3,
Flow_F2R1 = last(res.Flow_F2R1) < 0 ? -res.Flow_F2R1 : res.Flow_F2R1,
Flow_F2R2 = last(res.Flow_F2R2) < 0 ? -res.Flow_F2R2 : res.Flow_F2R2,
)) for res in results
]
return _plot_room_grid(pos_results, flow_keys, "Расход, л/мин"; y_limits = y_limits)
end
"""
plot_pressures_and_disp(results)
Холст 2: давления в системе (в кПа) и перемещение штока клапана ASV (в мм).
"""
function plot_pressures_and_disp(results)
line_colors = [:royalblue, :orange, :seagreen, :crimson]
line_styles = [:solid, :solid, :solid, :dashdot]
# 1. График давлений
p_press = plot(
title = "Давления в системе (ASV-P и без клапана)",
xlabel = "",
ylabel = "Давление, кПа",
ylims = (390, 575),
left_margin = 18mm,
right_margin = 6mm,
top_margin = 6mm,
bottom_margin = 4mm
)
base_run = first(results)
plot!(p_press, base_run.time, base_run.P_Supply .* 100.0, label = "Р подачи этажа (постоянное)", lw = 2, color = :black)
for (res, clr, stl) in zip(results, line_colors, line_styles)
lbl = res.has_asv ? "Р обратки этажа, Δp = $(res.label)" : "Р обратки этажа ($(res.label))"
plot!(p_press, res.time, res.P_Return .* 100.0, label = lbl, lw = 2, color = clr, linestyle = stl)
end
plot!(p_press, base_run.time, base_run.P_Common ./ 1000.0, label = "Р обратки общей линии", lw = 2, linestyle = :dash, color = :purple)
# 2. График перемещения клапана ASV
p_disp = plot(
title = "Перемещение клапана ASV (Disp)",
xlabel = "Время, с",
ylabel = "Перемещение, мм",
left_margin = 18mm,
right_margin = 6mm,
top_margin = 8mm,
bottom_margin = 6mm
)
for (res, clr, stl) in zip(results, line_colors, line_styles)
if res.has_asv
plot!(p_disp, res.time, res.Disp_ASV .* 1000.0, label = "", lw = 2, color = clr, linestyle = stl)
end
end
p = plot(
p_press,
p_disp,
layout = (2, 1),
size = (1050, 620),
legend = (0.68, 0.76),
legendfontsize = 10,
background_color_legend = RGBA(1, 1, 1, 0.92),
foreground_color_legend = :gray,
titlefont = font(11),
guidefont = font(10),
tickfont = font(9)
)
display_plotly_safe(p; base_width = 1050, base_height = 620)
return nothing
end