/
plot_utils.erl
2267 lines (1579 loc) · 66.2 KB
/
plot_utils.erl
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% Copyright (C) 2023-2024 Olivier Boudeville
%
% This file is part of the Ceylan-Myriad library.
%
% This library is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License or
% the GNU General Public License, as they are published by the Free Software
% Foundation, either version 3 of these Licenses, or (at your option)
% any later version.
% You can also redistribute it and/or modify it under the terms of the
% Mozilla Public License, version 1.1 or later.
%
% This library is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License and the GNU General Public License
% for more details.
%
% You should have received a copy of the GNU Lesser General Public
% License, of the GNU General Public License and of the Mozilla Public License
% along with this library.
% If not, see <http://www.gnu.org/licenses/> and
% <http://www.mozilla.org/MPL/>.
%
% Author: Olivier Boudeville [olivier (dot) boudeville (at) esperide (dot) com]
% Creation date: Saturday, October 7, 2023.
% @doc Gathering of facilities <b>to plot graphs</b>.
-module(plot_utils).
% For the plot_settings record:
-include("plot_utils.hrl").
-type plot_settings() :: #plot_settings{}.
% The settings governing a given plot.
%
% The underlying conventions are the gnuplot ones.
-type user_plot_name() :: any_string().
% The user-specified plot name, whence for example the corresponding file names
% will be derived.
-type bin_plot_name() :: bin_string().
% Internal plot name.
-type user_plot_path() :: any_file_path().
% The path to a file corresponding to a rendering of a plot, as an image.
%
% Typically a PNG or a SVG file.
-type plot_style() :: 'linespoints' % (default)
| 'lines'
| 'points'
| 'boxes'
| 'histograms'
| 'filledcurves'
| 'fillsteps'
| atom(). % As many others exist.
% Plot style (default being 'linespoints'):
%
% (see http://gnuplot.info/docs_5.5/Plotting_Styles.html)
-type fill_style() :: 'empty' % (default)
| term(). % to be further specified
% Fill style (default being 'empty'):
%
% (see http://gnuplot.info/docs_5.5/loc15482.html)
-type user_key_options() :: any_string().
% A user-specified string containing key options.
%
% For example "box".
-type bin_command_file_name() :: bin_file_name().
% The name of a gnuplot command file (see the command_extension define).
-type command_file_path() :: file_path().
% A path to a gnuplot command file (see the command_extension define).
-type bin_command_file_path() :: bin_file_path().
% A path to a gnuplot command file (see the command_extension define).
-type plot_meta_data() :: list_table( atom(), any_string() ).
% Extra information about data, used to enrich (as comments) data to be plotted,
% for example to specify origin of data, measurement time, source, author,
% accuracy, version, etc.
%
% Reserved keys:
%
% - first_column_description :: ustring(): to describe the semantics of the plot
% parameter; for example: "First column corresponds to the abscissa, expressed
% in tick offsets."
%
% - plot_point_count :: count(): the number of points to plot
-type plot_function() :: float_to_float_fun().
% A function to be plotted.
-type plot_data() :: [ plot_point() ].
% A data to plot, based on an (unordered) list of points to be plotted.
-type plot_point() :: { plot_parameter(), plot_sample() }.
% A data point to plot, made of a parameter (like a function one, for example
% time) and the associated sample values to be plotted (like the values of
% various functions for the previous parameter).
%
% May also be designated as a data row.
%
% For example {"Monday", {1, undefined, 5.1}}, or {5.5, "hello"}.
-type plot_parameter() :: any_string() | number().
% A parameter corresponding to a plot point.
%
% This may be a timestamp.
%
% For example "Monday", or 14557.
-type plot_parameter_bin_string() :: bin_string().
% A string corresponding to a plot parameter.
-type plot_sample() :: type_utils:tuploid( maybe( plot_value() ) ).
% A sample to plot.
%
% For example {1, undefined, "red", 5.1}, or "hello".
-type plot_value() :: any_string() | number().
% A value corresponding to a plot point.
%
% For example "active", or 1.12.
-type bin_data_file_name() :: bin_file_name().
% The name of a data file (see the command_extension define).
-type data_file_path() :: file_path().
% A path to a data file (see the data_extension define).
-type bin_data_file_path() :: bin_file_path().
% A path to a data file (see the data_extension define).
-type row_data_string() :: format_string().
% A data row, typically to be written in a data file.
-type row_format_string() :: format_string().
% Describes how a data row is to be formatted.
-type bin_plot_path() :: bin_file_path().
% A path to a plot (image) file (see the image_format field in the plot
% settings).
-type bin_plot_filename() :: bin_file_name().
% A filename of a plot (image) file (see the image_format field in the plot
% settings).
-type plot_generation_outcome() ::
{ 'success', bin_plot_path() }
| { 'warning', bin_plot_path(), warning_message() }
| { 'error', error_message() }.
% The possible outcomes of an attempt of plot generation.
-type warning_message() :: ustring().
% Any warning (still a success case, plot was generated) message issued when
% trying to generate a plot.
-type error_message() :: ustring().
% Any error (failure case, no plot was generated) message issued when
% trying to generate a plot.
-export_type([ plot_settings/0,
user_plot_name/0, bin_plot_name/0, user_plot_path/0,
plot_style/0, fill_style/0,
bin_command_file_name/0,
command_file_path/0, bin_command_file_path/0,
plot_data/0, plot_point/0,
plot_parameter/0, plot_parameter_bin_string/0,
plot_sample/0, plot_value/0,
bin_data_file_name/0,
data_file_path/0, bin_data_file_path/0,
row_data_string/0, row_format_string/0,
bin_plot_path/0, bin_plot_filename/0,
plot_generation_outcome/0, warning_message/0, error_message/0 ]).
-type declared_curve_name() :: any_string().
% The name of a user-specified curve.
-type special_curve_id() :: 'abscissa_top' | 'abscissa_bottom'.
% Identifiers of pseudo-curves (Ordinate = constant), corresponding respectively
% to the highest ordinate value and lowest one.
-type declared_curve_id() :: declared_curve_name() | special_curve_id().
% The identifier of a user-specified extended curve.
-type declared_zone_name() :: any_string().
% The name of a user-specified zone.
-type declared_zone() :: { declared_zone_name(),
{ declared_curve_id(), declared_curve_id() } }.
% The definition of a user-specified zone, which is the specific area between
% the two specified curves.
-type curve_count() :: count().
% A number of curves.
-type point_size_factor() :: pos_integer().
% A factor by which the default point size is multiplied.
-export_type([ declared_curve_name/0, special_curve_id/0, declared_curve_id/0,
declared_zone_name/0, declared_zone/0,
curve_count/0,
point_size_factor/0 ]).
-type plot_label() :: #plot_label{}.
% Fully defines a label on a plot.
-type label_location() :: gui:point().
% Corresponds to the 2D integer coordinates of the label on the plot.
-type label_text() :: bin_string().
% Actual text of a label.
%
% Note that texts can be "enhanced" (e.g. "for some {/:Bold important} text"),
% and may include newlines (e.g. "radius\\nat...").
-type label_color() :: color().
% Color of the text (default: "blue").
-type label_justification() :: 'left' | 'center' | 'right'.
% Describes the justification of the text based on the specified location for
% the label.
-type label_orientation() :: 'upright' | int_degrees().
% Describes whether the text of the label should be rendered with an angle, from
% the abscissa axis.
-type user_point_style_spec() :: any_string() | boolean().
% A user specification of a point to be rendered.
%
% For example `<<"pointtype 1">>'.
%
% If true, a default point style is selected; if false no point will be
% rendered.
-type point_style_spec() :: bin_string().
% The internal specification of a point to be rendered.
%
% For example `<<"pointtype 1">>'.
-type label_spec() :: { label_text(), label_location() }
| { label_text(), label_location(), user_point_style_spec() }.
% A user specification of a label.
-export_type([ plot_label/0,
label_location/0, label_text/0, label_color/0,
label_justification/0, label_orientation/0,
user_point_style_spec/0, point_style_spec/0,
label_spec/0 ]).
-type gnuplot_version() :: basic_utils:two_digit_version().
% A version of gnuplot.
-export_type([ gnuplot_version/0 ]).
-type extra_curve_settings() :: rgb_hexastring().
% The color of a given curve.
-type extra_zone_settings() :: rgb_hexastring().
% The color of a given zone.
-type key_options() :: bin_string().
% Options related to the plot key.
%
% See http://gnuplot.info/docs_5.5/loc12343.html.
-type tick_option() :: 'rotate'.
% Option applying to label ticks.
-type ticks_option() :: bin_string().
% Option applying to ticks (e.g. axis, border, start, font, textcolor, etc.) for
% a fine control of the major (labelled) tics on an axis (e.g. see Xtics, in
% http://www.gnuplot.info/docs_4.2/node295.html)
-type timestamp_time_format() ::
% Time then date, on a single line:
'single_line'
% Time, newline, date, hence on two lines:
| 'double_line'.
% The display time format to use for timestamped axes.
-export_type([ extra_curve_settings/0, extra_zone_settings/0,
key_options/0, tick_option/0, ticks_option/0,
timestamp_time_format/0 ]).
-type elementary_command() :: ustring().
% A (complete) elementary (gnuplot) command, that is a self-standing line
% (possibly a comment) of a command file thereof.
-type command_element() :: ustring().
% An element of a gnuplot command.
-type timestamp_string() :: ustring().
% String describing a timestamp (typically either a tick or a textual
% timestamp).
-type timestamp_bin_string() :: bin_string().
-export_type([ elementary_command/0, command_element/0,
timestamp_string/0, timestamp_bin_string/0 ]).
% Main user API:
-export([ get_plot_settings/1,
get_default_plot_settings/0, get_default_plot_settings/1,
get_timestamp_settings/1, get_timestamp_settings/2,
set_plot_name/2,
set_title/2, set_x_label/2, set_y_label/2,
set_key_options/2,
add_label/3, add_label/4, add_label/7, add_labels/2,
remove_labels/1,
declare_curves/2, declare_zones/2,
get_plot_command/5,
plot_samples/2, plot_samples/3,
plot/3, plot/4 ]).
% Exported gnuplot helpers, mostly for internal use:
-export([ transform_curve_names/1, transform_declared_zones/2,
get_default_curve_plot_suffix/0, get_default_zone_plot_suffix/0,
get_formatted_orientation/1,
get_label_definitions/1, get_label_definitions/2,
get_gnuplot_reference_version/0, get_basic_options/1,
get_xticks_option/1, get_yticks_option/1,
get_x_range_option/1, get_y_range_option/1,
get_x_ticks_option/1, get_y_ticks_option/1,
add_plot_index_back/2,
generate_command_file/1, generate_data_file/2, write_row/3,
forge_format_string_for/1 ]).
% Section for internal types:
-type plot_name() :: bin_string().
% The internal plot name.
-type plot_path() :: bin_file_path().
% The (internal) path to a file corresponding to a rendering of a plot, as an
% image.
%
% Typically a PNG or a SVG file.
-type curve_name() :: bin_string().
% The internal name for a curve.
-type curve_index() :: curve_count().
% Curves are numbered internally, and correspond to the position of data in
% specified samples.
-type extended_curve_id() :: curve_index() | special_curve_id().
% Extended to allow for zone definitions.
-type curve_entry() :: { curve_index(), curve_name(), curve_plot_suffix() }.
% Information specific to the rendering of a curve.
-type curve_offset() :: count().
% Applies notably if using (unquoted) timestamps that account for more than one
% field in data. Prefer relying on quoted timestamps.
-type curve_plot_suffix() :: bin_string().
% A (binary string) suffix (e.g. `<<"noenhanced with filledcurves">>', `<<"with
% boxes">>' or `<<"with boxes lt rgb '#f0f0f0'">>') to be added to the plot
% command of the corresponding curve.
-type zone_name() :: bin_string().
% Tne name of a zone.
-type zone_plot_suffix() :: bin_string().
% A (binary string) suffix (e.g. `<<"fillcolor red">>') to be added to the plot
% command of the corresponding zone.
-type zone_entry() ::
{ zone_name(), { extended_curve_id(), extended_curve_id() },
zone_plot_suffix() }.
% Information specific to the rendering of a zone.
% For internal sharing:
-export_type([ plot_name/0, plot_path/0,
curve_name/0, curve_index/0, extended_curve_id/0,
curve_entry/0, curve_offset/0, curve_plot_suffix/0,
zone_name/0, zone_plot_suffix/0, zone_entry/0 ]).
% Implementation notes:
%
% Although there are open-source, cross-platform alternatives to gnuplot
% (e.g. LabPlot, SciDaVis, KAlgebra, KSEG and clip), none seemed to reach its
% richness/level of maturity. So we stick with good old gnuplot, hopefully for
% the best.
% Element needed:
%
% - gnuplot version 5.4 or higher is preferred (and 4.2 or above is required)
%
% - an image viewer, for example eog (eye of gnome) of gwenview; see the
% executable_utils module (e.g. display_image_file/2 or browse_images_in/1)
% module for viewers
% To debug the generated command/data files, one can run directly gnuplot. This
% is as simple as 'gnuplot My_test_plot.p'.
% See http://www.gnuplot.info/docs/gnuplot.html for graph generation.
% Regarding zones:
%
% Zones are different from "stacked histograms" (see 'rowstacked') insofar as a
% zone corresponds just to the filling of the area between two curves, whereas a
% stacked histogram should stack (add) values read from columns; for example,
% if, for a given abscissa, V1 can be read for column C1 and V2 for column C2,
% then a zone would spread in [C1,C2] whereas a stacked histogram would
% represent a first "zone" between the abscissa axis and C1, and a second zone
% between C1 and C1+C2 (*not* C2).
%
% The simplest way (other options, such as using 'rowstacked' gnuplot histograms
% or filledcurves, are considerably less convenient/more problematic) to display
% with gnuplot such "stacked histograms" is to use our zone feature, and thus to
% preprocess entries so that they stack additively; e.g. instead of having raw
% samples like {Timestamp, C1, C2, C3}, the probe should be fed with {Timestamp,
% C1, C1+C2, C1+C2+C3} samples, and curves shall be rendered from the topmost to
% the bottom one (i.e. C1+C2+C3, C1+C2 and C1 here), so that the C1+C2 is drawn
% over C1+C2+C3, and so on; refer to send_stacked_data/3 to have it done for
% you.
%
% We however used filledcurves, an approach supposed to be more robust, yet it
% does not (and probably cannot) render the desired histograms: with
% filledcurves two data points are linked by a line segment (which of course
% gets filled), leading to unwanted filled triangles (picture a curve equal to
% zero until being equal to 1 at timestamp T: the area delimited by the previous
% timestamp and T will be an upright triangle raising from 0 to 1, whereas we
% would want a step from 0 to 1 at T. So we now use normal curves drawn as
% "boxes" (actually 'fillsteps').
%
% When rendering them, generally a fill style is needed (generally solid),
% specific zone colors are specified, ordinates shall start at zero (no
% autoscaling: y_range = {0,undefined}) and no zone based on abscissa_top is
% requested.
% Shorthands:
-type count() :: basic_utils:count().
-type ustring() :: text_utils:ustring().
-type bin_string() :: text_utils:bin_string().
-type any_string() :: text_utils:any_string().
-type format_string() :: text_utils:format_string().
-type list_table( K, V ) :: list_table:list_table( K, V ).
% Implies any_string():
-type title() :: ui:title().
-type label() :: ui:label().
-type file_path() :: file_utils:file_path().
-type any_file_path() :: file_utils:any_file_path().
-type bin_file_path() :: file_utils:bin_file_path().
-type bin_file_name() :: file_utils:bin_file_name().
-type file() :: file_utils:file().
-type int_degrees() :: unit_utils:int_degrees().
-type bounds() :: math_utils:bounds().
-type float_to_float_fun() :: math_utils:float_to_float_fun().
-type width() :: gui:width().
-type height() :: gui:height().
-type color() :: gui_color:color().
-type rgb_hexastring() :: gui_color:rgb_hexastring().
%-type coordinate() :: gui:coordinate().
-type image_format() :: gui_image:image_format().
% @doc Returns the specification of a plot of the specified name.
-spec get_plot_settings( user_plot_name() ) -> plot_settings().
get_plot_settings( UsrPlotName ) ->
#plot_settings{ name=text_utils:ensure_binary( UsrPlotName ) }.
% @doc Returns reasonable defaults in terms of plot settings, for a single,
% anonymous curve.
%
-spec get_default_plot_settings() -> plot_settings().
get_default_plot_settings() ->
get_default_plot_settings( "Myriad plot" ).
% @doc Returns reasonable defaults in terms of plot settings, for the specified
% single curve.
%
-spec get_default_plot_settings( user_plot_name() ) -> plot_settings().
get_default_plot_settings( PlotName ) ->
BasePlotSettings = get_plot_settings( PlotName ),
declare_curves( _CurveNames=[ "Function value" ], BasePlotSettings ).
% @doc Sets the name of the target plot.
-spec set_plot_name( user_plot_name(), plot_settings() ) -> plot_settings().
set_plot_name( UsrPlotName, PlotSettings ) ->
PlotSettings#plot_settings{ name=text_utils:ensure_binary( UsrPlotName ) }.
% @doc Returns the specification of a plot corresponding to the specified one
% once the specified title (if any) has been set.
%
-spec set_title( maybe( title() ), plot_settings() ) -> plot_settings().
set_title( MaybeTitle, PlotSettings ) ->
PlotSettings#plot_settings{
title=text_utils:ensure_maybe_binary( MaybeTitle ) }.
% @doc Returns the specification of a plot corresponding to the specified one
% once the specified label (if any) for abscissas has been set.
%
-spec set_x_label( maybe( label() ), plot_settings() ) -> plot_settings().
set_x_label( MaybeLabel, PlotSettings ) ->
PlotSettings#plot_settings{
x_label=text_utils:ensure_maybe_binary( MaybeLabel ) }.
% @doc Returns the specification of a plot corresponding to the specified one
% once the specified label (if any) for ordinate has been set.
%
-spec set_y_label( maybe( label() ), plot_settings() ) -> plot_settings().
set_y_label( MaybeLabel, PlotSettings ) ->
PlotSettings#plot_settings{
y_label=text_utils:ensure_maybe_binary( MaybeLabel ) }.
% @doc Returns the specification of a plot corresponding to the specified one
% once the specified key options (if any) have been set.
%
% Example of
-spec set_key_options( maybe( user_key_options() ), plot_settings() ) ->
plot_settings().
set_key_options( MaybeKeyOpts, PlotSettings ) ->
PlotSettings#plot_settings{
key_options=text_utils:ensure_maybe_binary( MaybeKeyOpts ) }.
% @doc Adds a in-plot label, with the specified text at the specified location.
-spec add_label( label_text(), label_location(), plot_settings() ) ->
plot_settings().
add_label( Text, Location, PlotSettings=#plot_settings{ labels=Labels } ) ->
Label = #plot_label{ text=text_utils:ensure_binary( Text ),
location=Location },
PlotSettings#plot_settings{ labels=[ Label | Labels ] }.
% @doc Adds a in-plot label, with the specified text at the specified location,
% possibly with a point being marked there.
%
-spec add_label( label_text(), label_location(), user_point_style_spec(),
plot_settings() ) -> plot_settings().
add_label( Text, Location, UsrPtStyleSpec,
PlotSettings=#plot_settings{ labels=Labels } ) ->
Label = #plot_label{ text=text_utils:ensure_binary( Text ),
location=Location,
point=from_user_point_style_spec( UsrPtStyleSpec ) },
PlotSettings#plot_settings{ labels=[ Label | Labels ] }.
% @doc Adds a in-plot label, with the specified text at the specified location,
% possibly with a point being marked there.
%
% (most complete label definition)
%
add_label( Text, Location, Color, Justification, Orientation, UsrPtStyleSpec,
PlotSettings=#plot_settings{ labels=Labels } ) ->
Label = #plot_label{ text=text_utils:ensure_binary( Text ),
location=Location,
color=Color,
justification=Justification,
orientation=Orientation,
point=from_user_point_style_spec( UsrPtStyleSpec ) },
PlotSettings#plot_settings{ labels=[ Label | Labels ] }.
-spec from_user_point_style_spec( user_point_style_spec() ) ->
point_style_spec().
from_user_point_style_spec( _DoMarkPoint=false ) ->
undefined;
from_user_point_style_spec( _DoMarkPoint=true ) ->
<<"pointtype 2">>;
from_user_point_style_spec( MarkPointStyle ) ->
text_utils:ensure_binary( MarkPointStyle ) .
% @doc Adds the specified in-plot labels.
-spec add_labels( [ label_spec() ], plot_settings() ) -> plot_settings().
add_labels( _LabelSpecs=[], PlotSettings ) ->
PlotSettings;
add_labels( _LabelSpecs=[ { Text, Location } | T ], PlotSettings ) ->
NewPlotSettings = add_label( Text, Location, PlotSettings ),
add_labels( T, NewPlotSettings );
add_labels( _LabelSpecs=[ { Text, Location, UserPtStSpec } | T ],
PlotSettings ) ->
NewPlotSettings = add_label( Text, Location, UserPtStSpec, PlotSettings ),
add_labels( T, NewPlotSettings );
add_labels( _LabelSpecs=[ { Text, Location, Color, Justification, Orientation,
UserPtStSpec } | T ],
PlotSettings ) ->
NewPlotSettings = add_label( Text, Location, Color, Justification,
Orientation, UserPtStSpec, PlotSettings ),
add_labels( T, NewPlotSettings ).
% @doc Removes all in-plot labels.
-spec remove_labels( plot_settings() ) -> plot_settings().
remove_labels( PlotSettings ) ->
PlotSettings#plot_settings{ labels=[] }.
% @doc Declares the specified curves.
%
% Supersedes any previous curve entries.
%
-spec declare_curves( [ declared_curve_name() ], plot_settings() ) ->
plot_settings().
declare_curves( CurveNames, PlotSettings ) ->
CurveEntries = transform_curve_names( CurveNames ),
PlotSettings#plot_settings{ curve_entries=CurveEntries }.
% @doc Transforms a list of names into a list of {Number, Name, CurvePlotSuffix}
% curve entries, where Number is the index of the name in the list (starting at
% 1), Name is a binary name, and CurvePlotSuffix is the curve-specific default
% plot suffix.
%
% Respects the order of specified names.
%
% For example `transform_curve_names(["a", "b", "c"])' should result in:
% `[{1,<<"a">>,DefaultBinPlotSuffix}, {2,<<"b">>,DefaultBinPlotSuffix},
% {3,<<"c">>,DefaultBinPlotSuffix}]'.
%
-spec transform_curve_names( [ declared_curve_name() ] ) -> [ curve_entry() ].
transform_curve_names( CurveNames ) ->
transform_curve_names( CurveNames, get_default_curve_plot_suffix(), _Acc=[],
_Count=1 ).
% (helper)
transform_curve_names( _CurveNames=[], _BinPlotSuffix, Acc, _Count ) ->
lists:reverse( Acc );
transform_curve_names( _CurveNames=[ CurveName | T ], BinPlotSuffix, Acc,
Count ) ->
CurveEntry = { Count, text_utils:ensure_binary( CurveName ),
BinPlotSuffix },
transform_curve_names( T, BinPlotSuffix, [ CurveEntry| Acc ], Count+1 ).
% @doc Declares the specified zones.
%
% Supersedes any previous zone entries.
%
-spec declare_zones( [ declared_zone() ], plot_settings() ) -> plot_settings().
declare_zones( DeclaredZones, PlotSettings=#plot_settings{
curve_entries=CurveEntries } ) ->
ZoneEntries = transform_declared_zones( DeclaredZones, CurveEntries ),
PlotSettings#plot_settings{ zone_entries=ZoneEntries }.
% @doc Transforms a list of zone declarations into actual zone entries, while
% checking them against the curve names.
%
% (defined for re-use)
%
-spec transform_declared_zones( [ declared_zone() ], [ curve_entry() ] ) ->
[ zone_entry() ].
transform_declared_zones( DeclaredZones, CurveEntries ) ->
transform_declared_zones( DeclaredZones, CurveEntries, _Acc=[] ).
% Transforms a list of zone declarations into actual zone entries, while
% checking them against the curve names.
%
% (helper)
transform_declared_zones( _DeclaredZones=[], _CurveEntries, Acc ) ->
% We preserve order here as well, otherwise zones will be listed in the plot
% keys in reverse order:
%
lists:reverse( Acc );
transform_declared_zones( [ Z={ ZoneName,
{ FirstCurveName, SecondCurveName } } | T ],
CurveEntries, Acc ) ->
First = get_curve_index_for( FirstCurveName, CurveEntries ),
Second = get_curve_index_for( SecondCurveName, CurveEntries ),
% We want to ensure that:
%
% 1. at least one actual curve is referenced (not two 'abscissa_*' atoms)
%
% 2. if there is one 'abscissa_*' atom, it ends up in first position of the
% returned pair
%
% 3. we preserve the input curve order (useful for plot styles requiring a
% single value column, like fillsteps, rather than two, like linecurves:
% they can always select the second curve of the pair):
%
NewBounds = case First of
_ when First == 'abscissa_top' orelse First == 'abscissa_bottom' ->
case Second of
_ when Second == 'abscissa_top'
orelse Second == 'abscissa_bottom' ->
throw( { curveless_zone, Z } );
_ ->
{ First, Second }
end;
_ ->
% So that we are sure that any abscissa_* atom would end up in first
% position:
%
%{ Second, First }
% Now preserving input order of normal curves:
case Second == 'abscissa_top'
orelse Second == 'abscissa_bottom' of
true ->
{ Second, First };
false ->
{ First, Second }
end
end,
ZoneBinName = text_utils:ensure_binary( ZoneName ),
transform_declared_zones( T, CurveEntries,
[ { ZoneBinName, NewBounds, get_default_zone_plot_suffix() } | Acc ] );
transform_declared_zones( [ Other | _T ], _CurveEntries, _Acc ) ->
throw( { invalid_zone_declaration, Other } ).
% @doc Returns an appropriate curve index to define internally a zone.
-spec get_curve_index_for( declared_curve_id(), [ curve_entry() ] ) ->
extended_curve_id().
get_curve_index_for( CurveId='abscissa_top', _CurveEntries ) ->
CurveId;
get_curve_index_for( CurveId='abscissa_bottom', _CurveEntries ) ->
CurveId;
get_curve_index_for( CurveName, CurveEntries ) ->
BinCurveName = text_utils:ensure_binary( CurveName ),
case lists:keyfind( _Key=BinCurveName, _Index=2, CurveEntries ) of
false ->
throw( { zone_specified_unknown_curve, CurveName, CurveEntries } );
{ CurveIndex, _BinCurveName, _BinPlotSuffix } ->
CurveIndex
end.
% doc Plots the specified samples, based on the specified plot specification,
% and returns the path to the corresponding generated plot file.
%
% Any previous plot file will be overwritten.
%
% The plot will not be specifically displayed.
%
-spec plot_samples( plot_data(), plot_settings() ) ->
plot_generation_outcome().
plot_samples( PlotData, PlotSettings ) ->
plot_samples( PlotData, PlotSettings, _DoDisplay=false ).
% doc Plots the specified samples, based on the specified plot specification,
% displays it if requested, and returns the path to the corresponding generated
% plot file.
%
% Any previous plot file will be overwritten.
%
-spec plot_samples( plot_data(), plot_settings(), boolean() ) ->
plot_generation_outcome().
plot_samples( PlotData, PlotSettings=#plot_settings{
name=BinPlotName,
image_format=ImgFormat,
plot_directory=MaybePlotDir }, DoDisplay ) ->
BinPlotDir = basic_utils:set_maybe( MaybePlotDir,
file_utils:get_bin_current_directory() ),
% Same logic as in the command file:
BinImgFilename = get_plot_filename( PlotSettings ),
BinPlotPath = file_utils:bin_join( BinPlotDir, BinImgFilename ),
trace_utils:debug_fmt( "Plot to be generated in '~ts'.", [ BinPlotPath ] ),
BinCmdFilename = generate_command_file( PlotSettings ),
_BinDataFilename = generate_data_file( PlotData, PlotSettings ),
GnuplotExecPath = executable_utils:get_gnuplot_path(),
BinPlotPath = file_utils:bin_join( BinPlotDir, BinImgFilename ),
% Not wanting to be confused by a prior file:
file_utils:remove_file_if_existing( BinPlotPath ),
% We must set the current directory to the one intended for the plot, yet
% just for that execution (we do not want to interfere at the level of the
% whole VM), otherwise the plot image will be created in the current
% directory; specifying in the command file an absolute path for the image
% is not an option either, as we want to be able to move around all
% plot-related files
%
{ ReturnCode, CmdOutput } = system_utils:run_executable( GnuplotExecPath,
_Args=[ BinCmdFilename ], _Env=[], _MaybeWorkingDir=MaybePlotDir ),
{ Outcome, Displayable } =
case file_utils:is_existing_file( BinPlotPath ) of
% Must have succeeded:
true ->
case ReturnCode of
0 ->
case CmdOutput of
"" ->
{ { success, BinPlotPath }, _Displ=true };
_ ->
WarningMsg = text_utils:format(
"Plot generation succeeded for '~ts', but "
"following information was output: ~ts",
[ BinPlotName, CmdOutput ] ),
{ { warning, BinPlotPath, WarningMsg },
_Displ=true }
end;
% Abnormal, surprising case, we suppose that this plot file is
% bogus:
%
ErrorRetCode ->
BaseErrorMsg = case CmdOutput of
"" ->
" (no generation information output)";
_ ->
text_utils:format(
", following information was output: '~ts'",
[ CmdOutput ] )
end,
ErrorMsg = text_utils:format( "Plot generation failed "
"for '~ts' with error code #~B~ts; "
"a plot file was however written",
[ BinPlotName, ErrorRetCode, BaseErrorMsg ] ),