-
Notifications
You must be signed in to change notification settings - Fork 0
/
gnuplot-iostream.h
executable file
·2240 lines (1882 loc) · 73.4 KB
/
gnuplot-iostream.h
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
// vim:foldmethod=marker
/*
Copyright (c) 2013 Daniel Stahlke ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* A C++ interface to gnuplot.
* Web page: http://www.stahlke.org/dan/gnuplot-iostream
* Documentation: https://github.com/dstahlke/gnuplot-iostream/wiki
*
* The whole library consists of this monolithic header file, for ease of installation (the
* Makefile and *.cc files are only for examples and tests).
*
* TODO:
* What version of boost is currently required?
* Callbacks via gnuplot's 'bind' function. This would allow triggering user functions when
* keys are pressed in the gnuplot window. However, it would require a PTY reader thread.
* Maybe temporary files read in a thread can replace PTY stuff.
*/
#ifndef GNUPLOT_IOSTREAM_H
#define GNUPLOT_IOSTREAM_H
// {{{1 Includes and defines
#define GNUPLOT_IOSTREAM_VERSION 2
#ifndef GNUPLOT_ENABLE_CXX11
# define GNUPLOT_ENABLE_CXX11 (__cplusplus >= 201103)
#endif
// C system includes
#include <cstdio>
#ifdef GNUPLOT_ENABLE_PTY
# include <termios.h>
# include <unistd.h>
#ifdef __APPLE__
# include <util.h>
#else
# include <pty.h>
#endif
#endif // GNUPLOT_ENABLE_PTY
// C++ system includes
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <iomanip>
#include <vector>
#include <complex>
#include <cstdlib>
#include <cmath>
#if GNUPLOT_ENABLE_CXX11
# include <tuple>
#endif
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/version.hpp>
#include <boost/utility.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/mpl/bool.hpp>
// This is the version of boost which has v3 of the filesystem libraries by default.
#if BOOST_VERSION >= 104600
# define GNUPLOT_USE_TMPFILE
# include <boost/filesystem.hpp>
#endif // BOOST_VERSION
// This is used because VS2008 doesn't have stdint.h.
#include <boost/cstdint.hpp>
// Note: this is here for reverse compatibility. The new way to enable blitz support is to
// just include the gnuplot-iostream.h header after you include the blitz header (likewise for
// armadillo).
#ifdef GNUPLOT_ENABLE_BLITZ
# include <blitz/array.h>
#endif
#ifdef BOOST_STATIC_ASSERT_MSG
# define GNUPLOT_STATIC_ASSERT_MSG(cond, msg) BOOST_STATIC_ASSERT_MSG((cond), msg)
#else
# define GNUPLOT_STATIC_ASSERT_MSG(cond, msg) BOOST_STATIC_ASSERT((cond))
#endif
// If this is defined, warn about use of deprecated functions.
#ifdef GNUPLOT_DEPRECATE_WARN
# ifdef __GNUC__
# define GNUPLOT_DEPRECATE(msg) __attribute__ ((deprecated(msg)))
# elif defined(_MSC_VER)
# define GNUPLOT_DEPRECATE(msg) __declspec(deprecated(msg))
# else
# define GNUPLOT_DEPRECATE(msg)
# endif
#else
# define GNUPLOT_DEPRECATE(msg)
#endif
// Patch for Windows by Damien Loison
#ifdef _WIN32
# include <windows.h>
# define GNUPLOT_PCLOSE _pclose
# define GNUPLOT_POPEN _popen
# define GNUPLOT_FILENO _fileno
#else
# define GNUPLOT_PCLOSE pclose
# define GNUPLOT_POPEN popen
# define GNUPLOT_FILENO fileno
#endif
#ifdef _WIN32
# define GNUPLOT_ISNAN _isnan
#else
// cppreference.com says std::isnan is only for C++11. However, this seems to work on Linux
// and I am assuming that if isnan exists in math.h then std::isnan exists in cmath.
# define GNUPLOT_ISNAN std::isnan
#endif
// MSVC gives a warning saying that fopen and getenv are not secure. But they are secure.
// Unfortunately their replacement functions are not simple drop-in replacements. The best
// solution is to just temporarily disable this warning whenever fopen or getenv is used.
// http://stackoverflow.com/a/4805353/1048959
#if defined(_MSC_VER) && _MSC_VER >= 1400
# define GNUPLOT_MSVC_WARNING_4996_PUSH \
__pragma(warning(push)) \
__pragma(warning(disable:4996))
# define GNUPLOT_MSVC_WARNING_4996_POP \
__pragma(warning(pop))
#else
# define GNUPLOT_MSVC_WARNING_4996_PUSH
# define GNUPLOT_MSVC_WARNING_4996_POP
#endif
#ifndef GNUPLOT_DEFAULT_COMMAND
#ifdef _WIN32
// "pgnuplot" is considered deprecated according to the Internet. It may be faster. It
// doesn't seem to handle binary data though.
//# define GNUPLOT_DEFAULT_COMMAND "pgnuplot -persist"
// On Windows, gnuplot echos commands to stderr. So we forward its stderr to the bit bucket.
// Unfortunately, this means you will miss out on legitimate error messages.
# define GNUPLOT_DEFAULT_COMMAND "gnuplot -persist 2> NUL"
#else
# define GNUPLOT_DEFAULT_COMMAND "gnuplot -persist"
#endif
#endif
// }}}1
namespace gnuplotio {
// {{{1 Basic traits helpers
//
// The mechanisms constructed in this section enable us to detect what sort of datatype has
// been passed to a function.
// This can be specialized as needed, in order to not use the STL interfaces for specific
// classes.
template <typename T>
struct dont_treat_as_stl_container {
typedef boost::mpl::bool_<false> type;
};
BOOST_MPL_HAS_XXX_TRAIT_DEF(value_type)
BOOST_MPL_HAS_XXX_TRAIT_DEF(const_iterator)
template <typename T>
struct is_like_stl_container {
typedef boost::mpl::and_<
typename has_value_type<T>::type,
typename has_const_iterator<T>::type,
boost::mpl::not_<dont_treat_as_stl_container<T> >
> type;
static const bool value = type::value;
};
template <typename T>
struct is_boost_tuple_nulltype {
static const bool value = false;
typedef boost::mpl::bool_<value> type;
};
template <>
struct is_boost_tuple_nulltype<boost::tuples::null_type> {
static const bool value = true;
typedef boost::mpl::bool_<value> type;
};
BOOST_MPL_HAS_XXX_TRAIT_DEF(head_type)
BOOST_MPL_HAS_XXX_TRAIT_DEF(tail_type)
template <typename T>
struct is_boost_tuple {
typedef boost::mpl::and_<
typename has_head_type<T>::type,
typename has_tail_type<T>::type
> type;
static const bool value = type::value;
};
// More fine-grained, but doesn't compile!
//template <typename T>
//struct is_boost_tuple {
// typedef boost::mpl::and_<
// typename boost::is_class<T>::type,
// typename boost::mpl::and_<
// typename has_head_type<T>::type,
// typename boost::mpl::and_<
// typename has_tail_type<T>::type,
// typename boost::mpl::or_<
// typename is_boost_tuple_nulltype<typename T::tail_type>::type,
// typename is_boost_tuple<typename T::tail_type>::type
// >::type
// >::type
// >::type
// > type;
//};
//
//template <>
//struct is_boost_tuple<boost::tuples::null_type> {
// typedef boost::mpl::bool_<false> type;
//};
// }}}1
// {{{1 Tmpfile helper class
#ifdef GNUPLOT_USE_TMPFILE
// RAII temporary file. File is removed when this object goes out of scope.
class GnuplotTmpfile {
public:
GnuplotTmpfile() :
file(boost::filesystem::unique_path(
boost::filesystem::temp_directory_path() /
"tmp-gnuplot-%%%%-%%%%-%%%%-%%%%"))
{ }
private:
// noncopyable
GnuplotTmpfile(const GnuplotTmpfile &);
const GnuplotTmpfile& operator=(const GnuplotTmpfile &);
public:
~GnuplotTmpfile() {
// it is never good to throw exceptions from a destructor
try {
remove(file);
} catch(const std::exception &) {
std::cerr << "Failed to remove temporary file " << file << std::endl;
}
}
public:
boost::filesystem::path file;
};
#endif // GNUPLOT_USE_TMPFILE
// }}}1
// {{{1 Feedback helper classes
//
// Used for reading stuff sent from gnuplot via gnuplot's "print" function.
//
// For example, this is used for capturing mouse clicks in the gnuplot window. There are two
// implementations, only the first of which is complete. The first implementation allocates a
// PTY (pseudo terminal) which is written to by gnuplot and read by us. This only works in
// Linux. The second implementation creates a temporary file which is written to by gnuplot
// and read by us. However, this doesn't currently work since fscanf doesn't block. It would
// be possible to get this working using a more complicated mechanism (select or threads) but I
// haven't had the need for it.
class GnuplotFeedback {
public:
GnuplotFeedback() { }
virtual ~GnuplotFeedback() { }
virtual std::string filename() const = 0;
virtual FILE *handle() const = 0;
private:
// noncopyable
GnuplotFeedback(const GnuplotFeedback &);
const GnuplotFeedback& operator=(const GnuplotFeedback &);
};
#ifdef GNUPLOT_ENABLE_PTY
#define GNUPLOT_ENABLE_FEEDBACK
class GnuplotFeedbackPty : public GnuplotFeedback {
public:
explicit GnuplotFeedbackPty(bool debug_messages) :
pty_fn(),
pty_fh(NULL),
master_fd(-1),
slave_fd(-1)
{
// adapted from http://www.gnuplot.info/files/gpReadMouseTest.c
if(0 > openpty(&master_fd, &slave_fd, NULL, NULL, NULL)) {
perror("openpty");
throw std::runtime_error("openpty failed");
}
char pty_fn_buf[1024];
if(ttyname_r(slave_fd, pty_fn_buf, 1024)) {
perror("ttyname_r");
throw std::runtime_error("ttyname failed");
}
pty_fn = std::string(pty_fn_buf);
if(debug_messages) {
std::cerr << "feedback_fn=" << pty_fn << std::endl;
}
// disable echo
struct termios tios;
if(tcgetattr(slave_fd, &tios) < 0) {
perror("tcgetattr");
throw std::runtime_error("tcgetattr failed");
}
tios.c_lflag &= ~(ECHO | ECHONL);
if(tcsetattr(slave_fd, TCSAFLUSH, &tios) < 0) {
perror("tcsetattr");
throw std::runtime_error("tcsetattr failed");
}
pty_fh = fdopen(master_fd, "r");
if(!pty_fh) {
throw std::runtime_error("fdopen failed");
}
}
private:
// noncopyable
GnuplotFeedbackPty(const GnuplotFeedbackPty &);
const GnuplotFeedbackPty& operator=(const GnuplotFeedbackPty &);
public:
~GnuplotFeedbackPty() {
if(pty_fh) fclose(pty_fh);
if(master_fd > 0) ::close(master_fd);
if(slave_fd > 0) ::close(slave_fd);
}
std::string filename() const {
return pty_fn;
}
FILE *handle() const {
return pty_fh;
}
private:
std::string pty_fn;
FILE *pty_fh;
int master_fd, slave_fd;
};
//#elif defined GNUPLOT_USE_TMPFILE
//// Currently this doesn't work since fscanf doesn't block (need something like "tail -f")
//#define GNUPLOT_ENABLE_FEEDBACK
//class GnuplotFeedbackTmpfile : public GnuplotFeedback {
//public:
// explicit GnuplotFeedbackTmpfile(bool debug_messages) :
// tmp_file(),
// fh(NULL)
// {
// if(debug_messages) {
// std::cerr << "feedback_fn=" << filename() << std::endl;
// }
// GNUPLOT_MSVC_WARNING_4996_PUSH
// fh = std::fopen(filename().c_str(), "a");
// GNUPLOT_MSVC_WARNING_4996_POP
// }
//
// ~GnuplotFeedbackTmpfile() {
// fclose(fh);
// }
//
//private:
// // noncopyable
// GnuplotFeedbackTmpfile(const GnuplotFeedbackTmpfile &);
// const GnuplotFeedbackTmpfile& operator=(const GnuplotFeedbackTmpfile &);
//
//public:
// std::string filename() const {
// return tmp_file.file.string();
// }
//
// FILE *handle() const {
// return fh;
// }
//
//private:
// GnuplotTmpfile tmp_file;
// FILE *fh;
//};
#endif // GNUPLOT_ENABLE_PTY, GNUPLOT_USE_TMPFILE
// }}}1
// {{{1 Traits and printers for entry datatypes
//
// This section contains the mechanisms for sending scalar and tuple data to gnuplot. Pairs
// and tuples are sent by appealing to the senders defined for their component scalar types.
// Senders for arrays are defined in a later section.
//
// There are three classes which need to be specialized for each supported datatype:
// 1. TextSender to send data as text. The default is to just send using the ostream's `<<`
// operator.
// 2. BinarySender to send data as binary, in a format which gnuplot can understand. There is
// no default implementation (unimplemented types raise a compile time error), however
// inheriting from FlatBinarySender will send the data literally as it is stored in memory.
// This suffices for most of the standard built-in types (e.g. uint32_t or double).
// 3. BinfmtSender sends a description of the data format to gnuplot (e.g. `%uint32`). Type
// `show datafile binary datasizes` in gnuplot to see a list of supported formats.
// {{{2 Basic entry datatypes
// Default TextSender, sends data using `<<` operator.
template <typename T, typename Enable=void>
struct TextSender {
static void send(std::ostream &stream, const T &v) {
stream << v;
}
};
// Default BinarySender, raises a compile time error.
template <typename T, typename Enable=void>
struct BinarySender {
GNUPLOT_STATIC_ASSERT_MSG((sizeof(T) == 0), "BinarySender class not specialized for this type");
// This is here to avoid further compilation errors, beyond what the assert prints.
static void send(std::ostream &stream, const T &v);
};
// This is a BinarySender implementation that just sends directly from memory. Data types
// which can be sent this way can have their BinarySender specialization inherit from this.
template <typename T>
struct FlatBinarySender {
static void send(std::ostream &stream, const T &v) {
stream.write(reinterpret_cast<const char *>(&v), sizeof(T));
}
};
// Default BinfmtSender, raises a compile time error.
template <typename T, typename Enable=void>
struct BinfmtSender {
GNUPLOT_STATIC_ASSERT_MSG((sizeof(T) == 0), "BinfmtSender class not specialized for this type");
// This is here to avoid further compilation errors, beyond what the assert prints.
static void send(std::ostream &);
};
// BinfmtSender implementations for basic data types supported by gnuplot.
// Types from boost/cstdint.hpp are used because VS2008 doesn't have stdint.h.
template<> struct BinfmtSender< float> { static void send(std::ostream &stream) { stream << "%float"; } };
template<> struct BinfmtSender<double> { static void send(std::ostream &stream) { stream << "%double"; } };
template<> struct BinfmtSender<boost:: int8_t> { static void send(std::ostream &stream) { stream << "%int8"; } };
template<> struct BinfmtSender<boost:: uint8_t> { static void send(std::ostream &stream) { stream << "%uint8"; } };
template<> struct BinfmtSender<boost:: int16_t> { static void send(std::ostream &stream) { stream << "%int16"; } };
template<> struct BinfmtSender<boost::uint16_t> { static void send(std::ostream &stream) { stream << "%uint16"; } };
template<> struct BinfmtSender<boost:: int32_t> { static void send(std::ostream &stream) { stream << "%int32"; } };
template<> struct BinfmtSender<boost::uint32_t> { static void send(std::ostream &stream) { stream << "%uint32"; } };
template<> struct BinfmtSender<boost:: int64_t> { static void send(std::ostream &stream) { stream << "%int64"; } };
template<> struct BinfmtSender<boost::uint64_t> { static void send(std::ostream &stream) { stream << "%uint64"; } };
// BinarySender implementations for basic data types supported by gnuplot. These types can
// just be sent as stored in memory, so all these senders inherit from FlatBinarySender.
template<> struct BinarySender< float> : public FlatBinarySender< float> { };
template<> struct BinarySender<double> : public FlatBinarySender<double> { };
template<> struct BinarySender<boost:: int8_t> : public FlatBinarySender<boost:: int8_t> { };
template<> struct BinarySender<boost:: uint8_t> : public FlatBinarySender<boost:: uint8_t> { };
template<> struct BinarySender<boost:: int16_t> : public FlatBinarySender<boost:: int16_t> { };
template<> struct BinarySender<boost::uint16_t> : public FlatBinarySender<boost::uint16_t> { };
template<> struct BinarySender<boost:: int32_t> : public FlatBinarySender<boost:: int32_t> { };
template<> struct BinarySender<boost::uint32_t> : public FlatBinarySender<boost::uint32_t> { };
template<> struct BinarySender<boost:: int64_t> : public FlatBinarySender<boost:: int64_t> { };
template<> struct BinarySender<boost::uint64_t> : public FlatBinarySender<boost::uint64_t> { };
// Make char types print as integers, not as characters.
template <typename T>
struct CastIntTextSender {
static void send(std::ostream &stream, const T &v) {
stream << int(v);
}
};
template<> struct TextSender< char> : public CastIntTextSender< char> { };
template<> struct TextSender< signed char> : public CastIntTextSender< signed char> { };
template<> struct TextSender< unsigned char> : public CastIntTextSender< unsigned char> { };
// Make sure that the same not-a-number string is printed on all platforms.
template <typename T>
struct FloatTextSender {
static void send(std::ostream &stream, const T &v) {
if(GNUPLOT_ISNAN(v)) { stream << "nan"; } else { stream << v; }
}
};
template<> struct TextSender< float> : FloatTextSender< float> { };
template<> struct TextSender< double> : FloatTextSender< double> { };
template<> struct TextSender<long double> : FloatTextSender<long double> { };
// }}}2
// {{{2 std::pair support
template <typename T, typename U>
struct TextSender<std::pair<T, U> > {
static void send(std::ostream &stream, const std::pair<T, U> &v) {
TextSender<T>::send(stream, v.first);
stream << " ";
TextSender<U>::send(stream, v.second);
}
};
template <typename T, typename U>
struct BinfmtSender<std::pair<T, U> > {
static void send(std::ostream &stream) {
BinfmtSender<T>::send(stream);
BinfmtSender<U>::send(stream);
}
};
template <typename T, typename U>
struct BinarySender<std::pair<T, U> > {
static void send(std::ostream &stream, const std::pair<T, U> &v) {
BinarySender<T>::send(stream, v.first);
BinarySender<U>::send(stream, v.second);
}
};
// }}}2
// {{{2 std::complex support
template <typename T>
struct TextSender<std::complex<T> > {
static void send(std::ostream &stream, const std::complex<T> &v) {
TextSender<T>::send(stream, v.real());
stream << " ";
TextSender<T>::send(stream, v.imag());
}
};
template <typename T>
struct BinfmtSender<std::complex<T> > {
static void send(std::ostream &stream) {
BinfmtSender<T>::send(stream);
BinfmtSender<T>::send(stream);
}
};
template <typename T>
struct BinarySender<std::complex<T> > {
static void send(std::ostream &stream, const std::complex<T> &v) {
BinarySender<T>::send(stream, v.real());
BinarySender<T>::send(stream, v.imag());
}
};
// }}}2
// {{{2 boost::tuple support
template <typename T>
struct TextSender<T,
typename boost::enable_if<
boost::mpl::and_<
is_boost_tuple<T>,
boost::mpl::not_<is_boost_tuple_nulltype<typename T::tail_type> >
>
>::type
> {
static void send(std::ostream &stream, const T &v) {
TextSender<typename T::head_type>::send(stream, v.get_head());
stream << " ";
TextSender<typename T::tail_type>::send(stream, v.get_tail());
}
};
template <typename T>
struct TextSender<T,
typename boost::enable_if<
boost::mpl::and_<
is_boost_tuple<T>,
is_boost_tuple_nulltype<typename T::tail_type>
>
>::type
> {
static void send(std::ostream &stream, const T &v) {
TextSender<typename T::head_type>::send(stream, v.get_head());
}
};
template <typename T>
struct BinfmtSender<T,
typename boost::enable_if<
boost::mpl::and_<
is_boost_tuple<T>,
boost::mpl::not_<is_boost_tuple_nulltype<typename T::tail_type> >
>
>::type
> {
static void send(std::ostream &stream) {
BinfmtSender<typename T::head_type>::send(stream);
stream << " ";
BinfmtSender<typename T::tail_type>::send(stream);
}
};
template <typename T>
struct BinfmtSender<T,
typename boost::enable_if<
boost::mpl::and_<
is_boost_tuple<T>,
is_boost_tuple_nulltype<typename T::tail_type>
>
>::type
> {
static void send(std::ostream &stream) {
BinfmtSender<typename T::head_type>::send(stream);
}
};
template <typename T>
struct BinarySender<T,
typename boost::enable_if<
boost::mpl::and_<
is_boost_tuple<T>,
boost::mpl::not_<is_boost_tuple_nulltype<typename T::tail_type> >
>
>::type
> {
static void send(std::ostream &stream, const T &v) {
BinarySender<typename T::head_type>::send(stream, v.get_head());
BinarySender<typename T::tail_type>::send(stream, v.get_tail());
}
};
template <typename T>
struct BinarySender<T,
typename boost::enable_if<
boost::mpl::and_<
is_boost_tuple<T>,
is_boost_tuple_nulltype<typename T::tail_type>
>
>::type
> {
static void send(std::ostream &stream, const T &v) {
BinarySender<typename T::head_type>::send(stream, v.get_head());
}
};
// }}}2
// {{{2 std::tuple support
#if GNUPLOT_ENABLE_CXX11
// http://stackoverflow.com/questions/6245735/pretty-print-stdtuple
template<std::size_t> struct int_{}; // compile-time counter
template <typename Tuple, std::size_t I>
void std_tuple_formatcode_helper(std::ostream &stream, const Tuple *, int_<I>) {
std_tuple_formatcode_helper(stream, (const Tuple *)(0), int_<I-1>());
stream << " ";
BinfmtSender<typename std::tuple_element<I, Tuple>::type>::send(stream);
}
template <typename Tuple>
void std_tuple_formatcode_helper(std::ostream &stream, const Tuple *, int_<0>) {
BinfmtSender<typename std::tuple_element<0, Tuple>::type>::send(stream);
}
template <typename... Args>
struct BinfmtSender<std::tuple<Args...> > {
typedef typename std::tuple<Args...> Tuple;
static void send(std::ostream &stream) {
std_tuple_formatcode_helper(stream, (const Tuple *)(0), int_<sizeof...(Args)-1>());
}
};
template <typename Tuple, std::size_t I>
void std_tuple_textsend_helper(std::ostream &stream, const Tuple &v, int_<I>) {
std_tuple_textsend_helper(stream, v, int_<I-1>());
stream << " ";
TextSender<typename std::tuple_element<I, Tuple>::type>::send(stream, std::get<I>(v));
}
template <typename Tuple>
void std_tuple_textsend_helper(std::ostream &stream, const Tuple &v, int_<0>) {
TextSender<typename std::tuple_element<0, Tuple>::type>::send(stream, std::get<0>(v));
}
template <typename... Args>
struct TextSender<std::tuple<Args...> > {
typedef typename std::tuple<Args...> Tuple;
static void send(std::ostream &stream, const Tuple &v) {
std_tuple_textsend_helper(stream, v, int_<sizeof...(Args)-1>());
}
};
template <typename Tuple, std::size_t I>
void std_tuple_binsend_helper(std::ostream &stream, const Tuple &v, int_<I>) {
std_tuple_binsend_helper(stream, v, int_<I-1>());
BinarySender<typename std::tuple_element<I, Tuple>::type>::send(stream, std::get<I>(v));
}
template <typename Tuple>
void std_tuple_binsend_helper(std::ostream &stream, const Tuple &v, int_<0>) {
BinarySender<typename std::tuple_element<0, Tuple>::type>::send(stream, std::get<0>(v));
}
template <typename... Args>
struct BinarySender<std::tuple<Args...> > {
typedef typename std::tuple<Args...> Tuple;
static void send(std::ostream &stream, const Tuple &v) {
std_tuple_binsend_helper(stream, v, int_<sizeof...(Args)-1>());
}
};
#endif // GNUPLOT_ENABLE_CXX11
// }}}2
// }}}1
// {{{1 ArrayTraits and Range classes
//
// This section handles sending of array data to gnuplot. It is rather complicated because of
// the diversity of storage schemes supported. For example, it treats a
// `std::pair<std::vector<T>, std::vector<U>>` in the same way as a
// `std::vector<std::pair<T, U>>`, iterating through the two arrays in lockstep, and sending
// pairs <T,U> to gnuplot as columns. In fact, any nested combination of pairs, tuples, STL
// containers, Blitz arrays, and Armadillo arrays is supported (with the caveat that, for
// instance, Blitz arrays should never be put into an STL container or you will suffer
// unpredictable results due the way Blitz handles assignment). Nested containers are
// considered to be multidimensional arrays. Although gnuplot only supports 1D and 2D arrays,
// our module is in principle not limited.
//
// The ArrayTraits class is specialized for every supported array or container type (the
// default, unspecialized, version of ArrayTraits exists only to tell you that something is
// *not* a container, via the is_container flag). ArrayTraits tells you the depth of a nested
// (or multidimensional) container, as well as the value type, and provides a specialized
// sort of iterator (a.k.a. "range"). Ranges are sort of like STL iterators, except that they
// have built-in knowledge of the end condition so you don't have to carry around both a
// begin() and an end() iterator like in STL.
//
// As an example of how this works, consider a std::pair of std::vectors. Ultimately this gets
// sent to gnuplot as two columns, so the two vectors need to be iterated in lockstep.
// The `value_type` of `std::pair<std::vector<T>, std::vector<U>>` is then `std::pair<T, U>`
// and this is what deferencing the range (iterator) gives. Internally, this range is built
// out of a pair of ranges (PairOfRange class), the `inc()` (advance to next element)
// method calls `inc()` on each of the children, and `deref()` calls `deref()` on each child
// and combines the results to return a `std::pair`. Tuples are handled as nested pairs.
//
// In addition to PairOfRange, there is also a VecOfRange class that can be used to treat the
// outermost part of a nested container as if it were a tuple. Since tuples are printed as
// columns, this is like treating a multidimensional array as if it were column-major. A
// VecOfRange is obtained by calling `get_columns_range`. This is used by, for instance,
// `send1d_colmajor`. The implementation is similar to that of PairOfRange.
//
// The range, accessed via `ArrayTraits<T>::get_range`, will be of a different class depending
// on T, and this is defined by the ArrayTraits specialization for T. It will always have
// methods `inc()` to advance to the next element and `is_end()` for checking whether one has
// advanced past the final element. For nested containers, `deref_subiter()` returns a range
// iterator for the next nesting level. When at the innermost level of nesting, `deref()`
// returns the value of the entry the iterator points to (a scalar, pair, or tuple).
// Only one of `deref()` or `deref_subiter()` will be available, depending on whether there are
// deeper levels of nesting. The typedefs `value_type` and `subiter_type` tell the return
// types of these two methods.
//
// Support for standard C++ and boost containers and tuples of containers is provided in this
// section. Support for third party packages like Blitz and Armadillo is in a later section.
// {{{2 ArrayTraits generic class and defaults
// Error messages involving this stem from treating something that was not a container as if it
// was. This is only here to allow compiliation without errors in normal cases.
struct Error_WasNotContainer {
// This is just here to make VC++ happy.
// https://connect.microsoft.com/VisualStudio/feedback/details/777612/class-template-specialization-that-compiles-in-g-but-not-visual-c
typedef void subiter_type;
};
// Error messages involving this stem from calling deref instead of deref_subiter for a nested
// container.
struct Error_InappropriateDeref { };
// The unspecialized version of this class gives traits for things that are *not* arrays.
template <typename T, typename Enable=void>
class ArrayTraits {
public:
// The value type of elements after all levels of nested containers have been dereferenced.
typedef Error_WasNotContainer value_type;
// The type of the range (a.k.a. iterator) that `get_range()` returns.
typedef Error_WasNotContainer range_type;
// Tells whether T is in fact a container type.
static const bool is_container = false;
// This flag supports the legacy behavior of automatically guessing whether the data should
// be treated as column major. This guessing happens when `send()` is called rather than
// `send1d()` or `send2d()`. This is deprecated, but is still supported for reverse
// compatibility.
static const bool allow_auto_unwrap = false;
// The number of levels of nesting, or the dimension of multidimensional arrays.
static const size_t depth = 0;
// Returns the range (iterator) for an array.
static range_type get_range(const T &) {
GNUPLOT_STATIC_ASSERT_MSG((sizeof(T)==0), "argument was not a container");
throw std::logic_error("static assert should have been triggered by this point");
}
};
// Most specializations of ArrayTraits should inherit from this (with V set to the value type).
// It sets some default values.
template <typename V>
class ArrayTraitsDefaults {
public:
typedef V value_type;
static const bool is_container = true;
static const bool allow_auto_unwrap = true;
static const size_t depth = ArrayTraits<V>::depth + 1;
};
// This handles reference types, such as are given with boost::tie.
// It also allows for instance "ArrayTraits<T[N]>" to match "ArrayTraits<T (&) [N]>".
// I think this is okay to do... The alternative is to use remove_reference all over the place.
template <typename T>
class ArrayTraits<T&> : public ArrayTraits<T> { };
// FIXME - is this okay?
// It supports gp.send1d(std::forward_as_tuple(x, std::move(y)));
#if GNUPLOT_ENABLE_CXX11
template <typename T>
class ArrayTraits<T&&> : public ArrayTraits<T> { };
#endif
// }}}2
// {{{2 STL container support
template <typename TI, typename TV>
class IteratorRange {
public:
IteratorRange() { }
IteratorRange(const TI &_it, const TI &_end) : it(_it), end(_end) { }
static const bool is_container = ArrayTraits<TV>::is_container;
typedef typename boost::mpl::if_c<is_container,
Error_InappropriateDeref, TV>::type value_type;
typedef typename ArrayTraits<TV>::range_type subiter_type;
bool is_end() const { return it == end; }
void inc() { ++it; }
value_type deref() const {
GNUPLOT_STATIC_ASSERT_MSG(sizeof(TV) && !is_container,
"deref called on nested container");
if(is_end()) {
throw std::runtime_error("attepted to dereference past end of iterator");
}
return *it;
}
subiter_type deref_subiter() const {
GNUPLOT_STATIC_ASSERT_MSG(sizeof(TV) && is_container,
"deref_subiter called on non-nested container");
if(is_end()) {
throw std::runtime_error("attepted to dereference past end of iterator");
}
return ArrayTraits<TV>::get_range(*it);
}
private:
TI it, end;
};
template <typename T>
class ArrayTraits<T,
typename boost::enable_if<is_like_stl_container<T> >::type
> : public ArrayTraitsDefaults<typename T::value_type> {
public:
typedef IteratorRange<typename T::const_iterator, typename T::value_type> range_type;
static range_type get_range(const T &arg) {
return range_type(arg.begin(), arg.end());
}
};
// }}}2
// {{{2 C style array support
template <typename T, size_t N>
class ArrayTraits<T[N]> : public ArrayTraitsDefaults<T> {
public:
typedef IteratorRange<const T*, T> range_type;
static range_type get_range(const T (&arg)[N]) {
return range_type(arg, arg+N);
}
};
// }}}2
// {{{2 std::pair support
template <typename RT, typename RU>
class PairOfRange {
template <typename T, typename U, typename PrintMode>
friend void deref_and_print(std::ostream &, const PairOfRange<T, U> &, PrintMode);
public:
PairOfRange() { }
PairOfRange(const RT &_l, const RU &_r) : l(_l), r(_r) { }
static const bool is_container = RT::is_container && RU::is_container;
typedef std::pair<typename RT::value_type, typename RU::value_type> value_type;
typedef PairOfRange<typename RT::subiter_type, typename RU::subiter_type> subiter_type;
bool is_end() const {
bool el = l.is_end();
bool er = r.is_end();
if(el != er) {
throw std::length_error("columns were different lengths");
}
return el;
}
void inc() {
l.inc();
r.inc();
}
value_type deref() const {
return std::make_pair(l.deref(), r.deref());
}
subiter_type deref_subiter() const {
return subiter_type(l.deref_subiter(), r.deref_subiter());
}
private:
RT l;
RU r;
};
template <typename T, typename U>
class ArrayTraits<std::pair<T, U> > {
public:
typedef PairOfRange<typename ArrayTraits<T>::range_type, typename ArrayTraits<U>::range_type> range_type;
typedef std::pair<typename ArrayTraits<T>::value_type, typename ArrayTraits<U>::value_type> value_type;
static const bool is_container = ArrayTraits<T>::is_container && ArrayTraits<U>::is_container;
// Don't allow colwrap since it's already wrapped.
static const bool allow_auto_unwrap = false;
// It is allowed for l_depth != r_depth, for example one column could be 'double' and the
// other column could be 'vector<double>'.
static const size_t l_depth = ArrayTraits<T>::depth;
static const size_t r_depth = ArrayTraits<U>::depth;
static const size_t depth = (l_depth < r_depth) ? l_depth : r_depth;
static range_type get_range(const std::pair<T, U> &arg) {
return range_type(
ArrayTraits<T>::get_range(arg.first),
ArrayTraits<U>::get_range(arg.second)
);
}
};
// }}}2
// {{{2 boost::tuple support
template <typename T>
class ArrayTraits<T,
typename boost::enable_if<
boost::mpl::and_<
is_boost_tuple<T>,
boost::mpl::not_<is_boost_tuple_nulltype<typename T::tail_type> >
>
>::type