Моделирование насос-форсунки EUI
作者
# =============================================================================
# simulation_display.jl — Запуск расчетов и безопасное отображение графиков Plotly
# =============================================================================
using Plots
plotlyjs() # Устанавливаем интерактивный бэкенд
# Подключаем файл с функциями отрисовки графиков
include("simulation_plots.jl")
# -----------------------------------------------------------------------------
# Функция для безопасного, адаптивного и центрированного отображения Plotly
# -----------------------------------------------------------------------------
function display_plotly_safe(p; base_width=1200, base_height=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. Убираем жесткие размеры из JSON конфигурации Plotly (чтобы он не рисовал шире окна)
html_str = replace(html_str, r"\"width\":\s*\d+(\.\d+)?" => "\"width\": null")
html_str = replace(html_str, r"\"height\":\s*\d+(\.\d+)?" => "\"height\": null")
# 3. Добавляем скрипт принудительного ресайза при загрузке
resize_script = """
<script>
window.addEventListener('load', function() {
setTimeout(function() {
var plots = document.querySelectorAll('.plotly-graph-div');
plots.forEach(function(p) { Plotly.Plots.resize(p); });
}, 100);
});
</script>
"""
html_str *= resize_script
# Экранируем кавычки для srcdoc
escaped_html = replace(html_str, "\"" => """)
# 4. Используем aspect-ratio для идеального сохранения пропорций
# Добавляем 40px к высоте, чтобы верхние/нижние подписи осей никогда не обрезались
aspect = "$(base_width) / $(base_height + 40)"
iframe_html = """
<div style="display: flex; justify-content: center; width: 100%; margin: 20px 0;">
<div style="width: 100%; max-width: $(base_width)px; aspect-ratio: $(aspect);">
<iframe
srcdoc="$escaped_html"
style="width: 100%; height: 100%; 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
# -----------------------------------------------------------------------------
# Основной блок запуска
# -----------------------------------------------------------------------------
# Запускаем функцию, которая всё считает и возвращает 4 графика
field_voa, field_rpm, fig_velocity, fig_characteristic = run_simulations_and_plot(modelName, rpm_vectors, voa_vectors)
# Выводим графики, передавая их родные размеры из simulation_plots.jl
# Для сеток 2x2 (родной размер 1200x680)
display_plotly_safe(field_voa, base_width=1200, base_height=680)
display_plotly_safe(field_rpm, base_width=1200, base_height=680)
# Для одиночных графиков (родной размер 800x450)
display_plotly_safe(fig_velocity, base_width=800, base_height=450)
display_plotly_safe(fig_characteristic, base_width=800, base_height=450)