-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexport_utils.jl
More file actions
330 lines (306 loc) · 10.9 KB
/
export_utils.jl
File metadata and controls
330 lines (306 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
"""
extract_svg(svg_string)
Extracts the raw SVG content from the representation.
"""
function extract_svg(svg_string)
# Extracts the raw SVG content from the representation
if isempty(svg_string)
return "", ""
else
svg_start = findfirst("<svg", svg_string)[1]
start_idx = findfirst(">", svg_string[svg_start:end])[end] + svg_start
end_idx = findfirst("</svg>", svg_string)[1] - 1
return svg_string[start_idx:end_idx], svg_string[1:(start_idx-1)]
end
end
"""
merge_svg_strings(svg1, svg2)
Merge two SVG strings `svg1` and `svg2` into one with header from `svg1`.
"""
function merge_svg_strings(svg1, svg2)
svg_str1, header = extract_svg(svg1)
svg_str2, _ = extract_svg(svg2)
return header * svg_str1 * svg_str2 * "</svg>\n"
end
"""
outer_bbox(ax::Makie.AbstractAxis; padding::Number = 0)
Compute the outer bounding box of the axis `ax` with additional `padding`.
"""
function outer_bbox(ax::Makie.AbstractAxis; padding::Number = 0)
sbb = ax.layoutobservables.suggestedbbox[]
prot = ax.layoutobservables.reporteddimensions[].outer
o = sbb.origin .- (prot.left, prot.bottom) .- padding
w = sbb.widths .+ (prot.left + prot.right, prot.bottom + prot.top) .+ 2 * padding
return Rect2f(o, w)
end
"""
get_svg(blockscene::Makie.Scene)
Get the SVG representation of the `blockscene`.
"""
function get_svg(blockscene::Makie.Scene)
svg = mktempdir() do dir
save(joinpath(dir, "output.svg"), blockscene; backend = CairoMakie)
read(joinpath(dir, "output.svg"), String)
end
return svg
end
"""
export_svg(ax::Makie.Block, filename::String)
Export the `ax` to a .svg file with path given by `filename`.
!!! note "Temporary approach"
This approach awaits solution from issue https://github.com/MakieOrg/Makie.jl/issues/4500
"""
function export_svg(
ax::Makie.Block, filename::String; legend::Union{Makie.Legend,Nothing} = nothing,
)
bbox = outer_bbox(ax)
_, sh = ax.blockscene.viewport[].widths
ox, oy = bbox.origin
w, h = bbox.widths
svg_ax = get_svg(ax.blockscene)
svg_legend = isnothing(legend) ? "" : get_svg(legend.blockscene)
svg = merge_svg_strings(svg_ax, svg_legend)
svg = replace(
svg,
r"viewBox=\".*?\"" => "viewBox=\"$ox $(sh - oy - h) $w $h\"",
r"width=\".*?\"" => "width=\"$w\"",
r"height=\".*?\"" => "height=\"$h\"",
count = 3,
)
# Add white background
svg_str1, header = extract_svg(svg)
svg =
header *
"""<rect x="$ox" y="$(sh - oy - h)" width="$w" height="$h" fill="white"/> """ *
svg_str1 * "</svg>\n"
open(filename, "w") do io
print(io, svg)
end
return 0
end
"""
export_xlsx(plots::Vector, filename::String, xlabel::Symbol)
Export the `plots` to a .xlsx file with path given by `filename` and top header `xlabel`.
"""
function export_xlsx(plots::Vector, filename::String, xlabel::Symbol)
if isempty(plots)
@warn "No data to be exported"
return 1
end
# Create a new Excel file and write data
XLSX.openxlsx(filename; mode = "w") do xf
sheet = xf[1] # Access the first sheet
no_columns = length(plots) + 1
data = Vector{Any}(undef, no_columns)
data[1] = string.(plots[1][:t])
for (i, plot) ∈ enumerate(plots)
data[i+1] = plot[:y]
end
labels::Vector{String} = [plot[:name] for plot ∈ plots]
headers::Vector{String} = vcat(string(xlabel), labels)
#XLSX.rename!(sheet, "My Data Sheet")
XLSX.writetable!(sheet, data, headers)
end
return 0
end
"""
export_xlsx(gui::GUI, filename::String)
Export the JuMP fields to an xlsx file with path given by `filename`.
"""
function export_xlsx(gui::GUI, filename::String)
model = get_model(gui)
if isempty(model)
@warn "No data to be exported"
return 1
end
# Create a new Excel file and write data
XLSX.openxlsx(filename; mode = "w") do xf
first_sheet::Bool = true
for (i, dict) ∈ enumerate(get_JuMP_names(gui))
container = model[dict]
if isempty(container)
continue
end
if first_sheet
sheet = xf[1]
XLSX.rename!(sheet, string(dict))
first_sheet = false
else
sheet = XLSX.addsheet!(xf, string(dict))
end
if typeof(container) <: JuMP.Containers.DenseAxisArray
axisTypes = nameof.([eltype(a) for a ∈ axes(model[dict])])
elseif typeof(container) <: SparseVars
axisTypes = collect(nameof.(typeof.(first(keys(container.data)))))
else
@info "dict = $dict, container = $container, typeof(container) = $(typeof(container))"
end
header = vcat(axisTypes, [:value])
data_jump = JuMP.Containers.rowtable(value, container; header = header)
no_columns = length(fieldnames(eltype(data_jump)))
num_tuples = length(data_jump)
data = [Vector{Any}(undef, num_tuples) for i ∈ range(1, no_columns)]
for (i, nt) ∈ enumerate(data_jump)
for (j, field) ∈ enumerate(fieldnames(typeof(nt)))
data[j][i] = string(getfield(nt, field))
end
end
XLSX.writetable!(sheet, data, header)
end
end
return 0
end
"""
export_to_file(gui::GUI)
Export results based on the state of `gui` to a file located within the folder specified
through the `path_to_results` keyword of [`GUI`](@ref).
"""
function export_to_file(gui::GUI)
path = get_var(gui, :path_to_results)
if isempty(path)
@error "Path not specified for exporting results; use GUI(case; path_to_results = \
\"<path to exporting folder>\")"
return nothing
end
if !isdir(path)
mkpath(path)
end
axes_str::String = get_menu(gui, :axes).selection[]
file_ending = get_menu(gui, :export_type).selection[]
filename = joinpath(path, axes_str * "." * file_ending)
if file_ending ∈ ["svg"]
CairoMakie.activate!() # Set CairoMakie as backend for proper export quality
cairo_makie_activated = true
else
cairo_makie_activated = false
end
if file_ending == "lp" || file_ending == "mps"
if isa(get_model(gui), DataFrame)
@info "Writing model to a $file_ending file is not supported when reading results from .csv-files"
return 1
elseif isempty(get_model(gui))
@info "No model to be exported"
return 2
end
try
write_to_file(get_model(gui), filename)
flag = 0
catch
flag = 2
end
else
valid_combinations = Dict(
"All" => ["jpg", "jpeg", "svg", "xlsx", "png"],
"Plots" => ["bmp", "tif", "tiff", "jpg", "jpeg", "svg", "xlsx", "png"],
"Topo" => ["bmp", "tif", "tiff", "jpg", "jpeg", "svg", "png"],
)
if !(file_ending ∈ valid_combinations[axes_str])
@info "Exporting $axes_str to a $file_ending file is not supported"
return 1
end
if axes_str == "All"
if file_ending == "xlsx"
flag = export_xlsx(gui, filename)
else
try
save(filename, get_fig(gui))
flag = 0
catch
flag = 2
end
end
else
if axes_str == "Plots"
ax_sym = :results
elseif axes_str == "Topo"
ax_sym = :topo
end
ax = get_ax(gui, ax_sym)
if file_ending == "svg"
if axes_str == "Plots"
flag = export_svg(ax, filename; legend = get_results_legend(gui))
elseif axes_str == "Topo"
flag = export_svg(ax, filename; legend = get_topo_legend(gui))
else
flag = export_svg(ax, filename)
end
elseif file_ending == "xlsx"
if axes_str == "Plots"
time_axis = get_menu(gui, :time).selection[]
plots = get_visible_data(gui, time_axis)
flag = export_xlsx(plots, filename, ax_sym)
end
elseif file_ending == "lp" || file_ending == "mps"
try
write_to_file(get_model(gui), filename)
flag = 0
catch
flag = 2
end
else
try
save(filename, colorbuffer(ax.scene))
flag = 0
catch
flag = 2
end
end
end
end
if cairo_makie_activated
GLMakie.activate!() # Return to GLMakie as a backend
end
if flag == 0
@info "Exported results to $filename"
elseif flag == 2
@info "An error occurred, no file exported"
end
return flag
end
"""
export_to_repl(gui::GUI)
Export results based on the state of `gui` to the REPL.
"""
function export_to_repl(gui::GUI)
axes_str::String = get_menu(gui, :axes).selection[]
if axes_str == "Plots"
time_axis = get_menu(gui, :time).selection[]
vis_plots = get_visible_data(gui, time_axis)
if !isempty(vis_plots) # Check if any plots exist
t = vis_plots[1][:t]
data = Matrix{Any}(undef, length(t), length(vis_plots) + 1)
data[:, 1] = t
header = [
Vector{String}(undef, length(vis_plots) + 1),
Vector{String}(undef, length(vis_plots) + 1),
]
header[1][1] = "t"
header[2][1] = "(" * string(nameof(eltype(t))) * ")"
for (j, vis_plot) ∈ enumerate(vis_plots)
data[:, j+1] = vis_plot[:y]
header[1][j+1] = vis_plots[j][:name]
header[2][j+1] = join([string(x) for x ∈ vis_plots[j][:selection]], ", ")
end
println("\n") # done in order to avoid the prompt shifting the topspline of the table
pretty_table(data; column_labels = header)
end
else
model = get_model(gui)
for sym ∈ get_JuMP_names(gui)
container = model[sym]
if isempty(container)
continue
end
if typeof(container) <: JuMP.Containers.DenseAxisArray
axis_types = nameof.([eltype(a) for a ∈ JuMP.axes(model[sym])])
elseif typeof(container) <: SparseVars
axis_types = collect(nameof.(typeof.(first(keys(container.data)))))
end
header = vcat(axis_types, [:value])
pretty_table(
JuMP.Containers.rowtable(value, container; header = header),
)
end
end
return 0
end