-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatplotlib.c
3372 lines (3198 loc) · 116 KB
/
matplotlib.c
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
#include "matplotlib.h"
char *strclone(const char *s) {
int size = strlen(s) + 1;
char *ret = (char *)malloc(size);
SYSEXPECT(ret != NULL);
memcpy(ret, s, size);
return ret;
}
//* fp_*
double fp_power10(int num) {
// If num == 0 if will return 1.0
double ret = 1.0f;
if(num >= 0) {
for(int i = 0;i < num;i++) {
ret *= 10.0;
}
} else {
num = -num;
for(int i = 0;i < num;i++) {
ret /= 10.0;
}
}
return ret;
}
// frac_count specifies the number of digits after the decimal point
// - If set to 0 then we print integer
// - How fp numbers are rounded is dependent on printf() implementation
// - Negative frac_count will cause digits left to the decimal point to be zero
char *fp_print(double num, int frac_count) {
int buf_size = FP_BUF_SIZE;
int count = 0;
char *buf;
int printf_ret;
// Append digit "0" to the string after printf
int append_zero_count = 0;
if(frac_count < 0) {
num /= fp_power10(-frac_count);
append_zero_count = -frac_count;
frac_count = 0;
}
assert(append_zero_count >= 0);
assert(append_zero_count == 0 || frac_count == 0);
do {
buf = (char *)malloc(buf_size);
SYSEXPECT(buf != NULL);
printf_ret = snprintf(buf, buf_size, "%.*f", frac_count, num);
// Since we may append extra zeros after this, also count them into ret
if(printf_ret > 0 && (printf_ret + append_zero_count) < buf_size) {
break;
} else if(printf_ret <= 0) {
// Directly push binary into the stack
error_exit("Encoding error occurred while printing floating point number 0x%lX\n", *(uint64_t *)&num);
}
free(buf);
buf_size *= 2;
// Set these two to make sure we always exit from the loop
buf = NULL;
count++;
} while(count < FP_MAX_ITER);
if(buf == NULL) error_exit("Internal error: maximum iteration count reached (%d)\n", count);
// Append zero to the end (there must be no decimal point)
assert(printf_ret + append_zero_count < buf_size);
// Corner case: If the resulting number is already zero, we do not append anything
if(streq(buf, "0") == 0) {
for(int i = 0;i < append_zero_count;i++) {
strcat(buf, "0");
}
}
return buf;
}
// Remove trailing zeros after the decimal point
// - If no decimal point then directly exit
// - If all zeros after the decimal point, we also remove the point itself
char *fp_rtrim(char *buf) {
char *decimal = strchr(buf, '.');
if(decimal == NULL) return buf; // No change
char *p = decimal + 1;
assert(*p != '\0'); // Can't be trailing decimal
char *q = buf + strlen(buf) - 1;
assert(q[1] == '\0');
// Find first non-zero from the end of the string
while(*q == '0') {
q--;
assert(q >= decimal);
}
// Overwrite decimal if all digits after it are zero; Otherwise do not overwrite
if(q != decimal) q++;
*q = '\0'; // Terminate the string here
return buf;
}
//* color_*
uint32_t color_scheme_mixed[] = {
COLOR_GEN(0xff, 0x66, 0x00),
COLOR_GEN(0x33, 0x66, 0x99),
COLOR_GEN(0x02, 0x84, 0x82),
COLOR_GEN(0xcc, 0x99, 0x00),
COLOR_GEN(0xcc, 0xcc, 0xff),
COLOR_GEN(0x9c, 0x9f, 0x84),
};
uint32_t color_scheme_red[] = {
COLOR_GEN(0xfd, 0xd4, 0x9e),
COLOR_GEN(0xfd, 0xbb, 0x84),
COLOR_GEN(0xfc, 0x8d, 0x59),
COLOR_GEN(0xef, 0x65, 0x48),
COLOR_GEN(0xd7, 0x30, 0x1f),
COLOR_GEN(0xb3, 0x00, 0x00),
COLOR_GEN(0x7f, 0x00, 0x00),
};
uint32_t color_scheme_blue[] = {
COLOR_GEN(0x0a, 0x11, 0x72),
COLOR_GEN(0x13, 0x38, 0xbe),
COLOR_GEN(0x04, 0x92, 0xc2),
COLOR_GEN(0x63, 0xc5, 0xda),
COLOR_GEN(0x82, 0xee, 0xfd),
};
uint32_t color_scheme_grey[] = {
COLOR_GEN(0xee, 0xee, 0xee),
COLOR_GEN(0xcc, 0xcc, 0xcc),
COLOR_GEN(0xaa, 0xaa, 0xaa),
COLOR_GEN(0x88, 0x88, 0x88),
COLOR_GEN(0x66, 0x66, 0x66),
COLOR_GEN(0x44, 0x44, 0x44),
COLOR_GEN(0x22, 0x22, 0x22),
COLOR_GEN(0x00, 0x00, 0x00),
};
color_scheme_t color_schemes[] = {
COLOR_SCHEME_GEN("mixed", color_scheme_mixed),
COLOR_SCHEME_GEN("red", color_scheme_red),
COLOR_SCHEME_GEN("blue", color_scheme_blue),
COLOR_SCHEME_GEN("grey", color_scheme_grey),
};
color_scheme_t *color_scheme_init(const char *name, uint32_t *base, int item_count) {
color_scheme_t *scheme = (color_scheme_t *)malloc(sizeof(color_scheme_t));
SYSEXPECT(scheme != NULL);
memset(scheme, 0x00, sizeof(color_scheme_t));
scheme->name = strclone(name);
scheme->base = (uint32_t *)malloc(COLOR_SIZE * item_count);
SYSEXPECT(scheme->base != NULL);
memcpy(scheme->base, base, COLOR_SIZE * item_count);
scheme->item_count = item_count;
return scheme;
}
// This function does not terminate program on error; It returns NULL and caller should handle error
color_scheme_t *color_scheme_init_file(const char *filename) {
FILE *fp = fopen(filename, "r");
if(fp == NULL) {
printf("Could not open file \"%s\" for read\n", filename);
return NULL;
}
// We use the file name as scheme name
// Use item_count as capacity when reading from file
color_scheme_t *scheme = (color_scheme_t *)malloc(sizeof(color_scheme_t));
SYSEXPECT(scheme != NULL);
memset(scheme, 0x00, sizeof(color_scheme_t));
scheme->name = strclone(filename);
scheme->base = (uint32_t *)malloc(COLOR_SIZE * COLOR_INIT_FILE_COUNT);
SYSEXPECT(scheme->base != NULL);
scheme->item_count = COLOR_INIT_FILE_COUNT;
int count = 0; // item count
int line = 1; // For error reporting
char buf[16];
while(fgets(buf, 16, fp) != NULL) {
// Jump over space
char *p = buf;
while(isspace(*p)) p++;
int len = strlen(p);
if(len == 0) {
continue;
} if(len < 7) {
printf("Illegal color in line %d: \"%s\"\n", line, buf);
return NULL;
}
// Check if any non-space char after the color code
char *q = p + 7;
while(isspace(*q)) q++;
if(*q != '\0') {
printf("Illegal color in line %d: \"%s\"\n", line, buf);
return NULL;
}
// Length check passed, truncate first 7 non-space chars
p[7] = '\0';
// This may also print error message
uint32_t color = color_decode(p);
if(color == -1U) return NULL;
assert(count <= scheme->item_count);
// Expand the base array if it is too small
if(count == scheme->item_count) {
uint32_t *old = scheme->base;
scheme->item_count *= 2;
scheme->base = (uint32_t *)malloc(COLOR_SIZE * scheme->item_count);
SYSEXPECT(scheme->base != NULL);
memcpy(scheme->base, old, COLOR_SIZE * (scheme->item_count / 2));
free(old);
}
assert(count < scheme->item_count);
scheme->base[count++] = color;
line++;
}
fclose(fp);
// Now this represents item count, not capacity
scheme->item_count = count;
return scheme;
}
void color_scheme_free(color_scheme_t *scheme) {
free(scheme->name);
free(scheme->base);
free(scheme);
return;
}
// This function is re-entrant
// Users should call color_str() / color_str_latex()
void _color_str(uint32_t color, char *buf, int for_latex) {
if(color & 0xFF000000) {
error_exit("Color value 0x%08X has non-zero upper 8 bits\n", color);
}
if(for_latex == 1) {
sprintf(buf, "\\#%02X%02X%02X", COLOR_R(color), COLOR_G(color), COLOR_B(color));
} else {
sprintf(buf, "#%02X%02X%02X", COLOR_R(color), COLOR_G(color), COLOR_B(color));
}
return;
}
// Returns 0xFFFFFFFF to indicate failure
// This function does not report error; Instead, it prints error message, and caller should handle it
uint32_t color_decode(const char *s) {
if(*s++ != '#') {
printf("Color code must begin with '#' (see \"%s\")\n", s);
return -1u;
}
uint32_t ret = 0u;
int shift = 20;
for(int i = 0;i < 6;i++) {
char ch = *s++;
if(ch == '\0') {
printf("Unexpected end of color code\n");
return -1u;
}
uint32_t hex;
if((ch >= '0' && ch <= '9')) {
hex = (uint32_t)(ch - '0');
} else if(ch >= 'a' && ch <= 'f') {
hex = (uint32_t)(ch - 'a' + 10);
} else if(ch >= 'A' && ch <= 'F') {
hex = (uint32_t)(ch - 'A' + 10);
} else {
const char *rgb;
if(i <= 1) rgb = "Red";
else if(i <= 3) rgb = "Green";
else rgb = "Blue";
printf("Invalid color code: \"%s\"; Component \"%s\" contains invalid digit\n", s, rgb);
return -1u;
}
assert((hex & ~0xffu) == 0);
ret |= (hex << shift);
shift -= 4;
}
if(*s != '\0') {
printf("Unexpected character after color code\n");
return -1u;
}
return ret;
}
// Duplicates an existing scheme
color_scheme_t *color_scheme_dup(color_scheme_t *scheme) {
return color_scheme_init(scheme->name, scheme->base, scheme->item_count);
}
// Returns NULL if the name does not exist; Otherwise return the pointer to the scheme
color_scheme_t *color_find_scheme(const char *name) {
for(int i = 0;i < (int)(sizeof(color_schemes) / sizeof(color_scheme_t));i++) {
if(streq(color_schemes[i].name, name) == 1) {
return color_schemes + i;
}
}
return NULL;
}
void color_scheme_print(color_scheme_t *scheme, int print_content) {
printf("[color] Name \"%s\" count %d base 0x%p\n", scheme->name, scheme->item_count, scheme->base);
if(print_content == 1) {
for(int i = 0;i < scheme->item_count;i++) {
char buf[16];
color_str(scheme->base[i], buf);
printf(" Index %d color %s\n", i, buf);
}
}
return;
}
//* hatch_*
hatch_scheme_t *hatch_scheme_init(const char *name, char *base, int item_count) {
hatch_scheme_t *scheme = (hatch_scheme_t *)malloc(sizeof(hatch_scheme_t));
SYSEXPECT(scheme != NULL);
memset(scheme, 0x00, sizeof(hatch_scheme_t));
scheme->name = strclone(name);
scheme->base = (char *)malloc(HATCH_SIZE * item_count);
SYSEXPECT(scheme->base != NULL);
memcpy(scheme->base, base, HATCH_SIZE * item_count);
scheme->item_count = item_count;
return scheme;
}
hatch_scheme_t *hatch_scheme_init_file(const char *filename) {
FILE *fp = fopen(filename, "r");
if(fp == NULL) {
printf("Could not open file \"%s\" for read\n", filename);
return NULL;
}
hatch_scheme_t *scheme = (hatch_scheme_t *)malloc(sizeof(hatch_scheme_t));
SYSEXPECT(scheme != NULL);
memset(scheme, 0x00, sizeof(hatch_scheme_t));
scheme->name = strclone(filename);
scheme->base = (char *)malloc(HATCH_SIZE * HATCH_INIT_FILE_COUNT);
SYSEXPECT(scheme->base != NULL);
scheme->item_count = HATCH_INIT_FILE_COUNT;
int count = 0; // item count
int line = 1; // For error reporting
char buf[16];
while(fgets(buf, 16, fp) != NULL) {
// Jump over space
char *p = buf;
while(isspace(*p)) p++;
int len = strlen(p);
if(len == 0) continue;
// Removing trailing spaces
char *q = p + len - 1;
while(isspace(*q)) { *q = '\0'; q--; }
len = strlen(p);
//printf("len %d p[1] %d valid %d\n", len, len == 2 ? p[1] : -1, hatch_is_valid(p[0]));
// Length either 1 or 2; If it is 2 then p[1] must be \n
if(len > 2 || (len == 2 && p[1] != '\n') || (hatch_is_valid(p[0]) == 0)) {
printf("Illegal hatch in line %d: \"%s\"\n", line, buf);
return NULL;
}
assert(count <= scheme->item_count);
// Expand the base array if it is too small
if(count == scheme->item_count) {
char *old = scheme->base;
scheme->item_count *= 2;
scheme->base = (char *)malloc(HATCH_SIZE * scheme->item_count);
SYSEXPECT(scheme->base != NULL);
memcpy(scheme->base, old, HATCH_SIZE * (scheme->item_count / 2));
free(old);
}
assert(count < scheme->item_count);
scheme->base[count++] = p[0];
line++;
}
fclose(fp);
// Now this represents item count, not capacity
scheme->item_count = count;
return scheme;
}
void hatch_scheme_free(hatch_scheme_t *scheme) {
free(scheme->name);
free(scheme->base);
free(scheme);
return;
}
// This is a full list of charracter hatches supported by matplotlib
char hatch_scheme_all[] = {
'-', '+', 'x', '\\', '*', 'o', 'O', '.', ',', 'v', '^', '<', '>', '1', '2', '3', '4', '8',
's', 'p', 'P', 'h', 'H', 'X', 'd', 'D', '|', '_', '/',
};
int hatch_scheme_all_count = sizeof(hatch_scheme_all) / sizeof(char);
char *hatch_scheme_default = hatch_scheme_all;
hatch_scheme_t hatch_schemes[] = {
HATCH_SCHEME_GEN("default", hatch_scheme_all),
};
// Returns the hatch char given a string (basically containing the hatch char)
// Similar to color_decode, this function returns 0xFF if error, prints error message, and caller
// should actually handle the error
char hatch_decode(const char *s) {
if(strlen(s) != 1) {
printf("Hatch should be only one character in length (see \"%s\")\n", s);
return 0xFF;
} else if(hatch_is_valid(s[0]) == 0) {
printf("Invalid hatch character: \'%c\'\n", s[0]);
return 0xFF;
}
return s[0];
}
int hatch_is_valid(char hatch) {
for(int i = 0;i < hatch_scheme_all_count;i++) {
if(hatch_scheme_all[i] == hatch) return 1;
}
return 0;
}
// Returns NULL if not found
hatch_scheme_t *hatch_find_scheme(const char *name) {
for(int i = 0;i < (int)(sizeof(hatch_schemes) / sizeof(hatch_scheme_t));i++) {
if(streq(hatch_schemes[i].name, name) == 1) {
return hatch_schemes + i;
}
}
return NULL;
}
hatch_scheme_t *hatch_scheme_dup(hatch_scheme_t *scheme) {
return hatch_scheme_init(scheme->name, scheme->base, scheme->item_count);
}
void hatch_scheme_print(hatch_scheme_t *scheme, int print_content) {
printf("[hatch] Name \"%s\" count %d base 0x%p\n", scheme->name, scheme->item_count, scheme->base);
if(print_content == 1) {
for(int i = 0;i < scheme->item_count;i++) {
printf(" Index %d hatch '%c'\n", i, scheme->base[i]);
}
}
return;
}
//* py_t
static int py_count = 0;
static int inited = 0;
py_t *py_init() {
py_t *py = (py_t *)malloc(sizeof(py_t));
SYSEXPECT(py != NULL);
memset(py, 0x00, sizeof(py_t));
// This is recommended by Python doc
Py_SetProgramName("matplotlib-c");
// Always only init/fin python lib once during the program's lifetime
// Some modules do not clean up properly and will crash otherwise
if(inited == 0) {
inited = 1;
Py_Initialize();
atexit(Py_Finalize);
}
//if(py_count == 0) Py_Initialize();
py_count++;
return py;
}
void py_free(py_t *py) {
// Only free when ref count is zero
assert(py_count != 0);
py_count--;
// Don't init/fin multiple times!
// This will cause numpy to crash
//if(py_count == 0) Py_Finalize();
free(py);
return;
}
void py_run(py_t *py, const char *s) {
int ret = PyRun_SimpleString(s);
if(ret != 0) {
error_exit("Python interpreter raises an exception. Exiting.\n");
}
(void)py;
return;
}
int py_get_instance_count() { return py_count; }
//* vec_t
vec_t *vec_init() {
vec_t *vec = (vec_t *)malloc(sizeof(vec_t));
SYSEXPECT(vec != NULL);
memset(vec, 0x00, sizeof(vec_t));
vec->count = 0;
vec->capacity = VEC_INIT_COUNT;
vec->data = (void **)malloc(sizeof(void *) * VEC_INIT_COUNT);
SYSEXPECT(vec->data != NULL);
return vec;
}
void vec_free(vec_t *vec) {
free(vec->data);
free(vec);
return;
}
void vec_append(vec_t *vec, void *p) {
assert(vec->count >= 0 && vec->count <= vec->capacity);
if(vec->count == vec->capacity) {
vec->capacity *= 2;
void **old = vec->data;
vec->data = (void **)malloc(sizeof(void *) * vec->capacity);
SYSEXPECT(vec->data != NULL);
memcpy(vec->data, old, sizeof(void *) * vec->count);
free(old);
}
assert(vec->count < vec->capacity);
vec->data[vec->count++] = p;
return;
}
void vec_print(vec_t *vec) {
printf("[vec] count %d cap %d data %p\n", vec->count, vec->capacity, vec->data);
return;
}
//* buf_t
buf_t *buf_init_sz(int sz) {
if(sz <= 0) {
error_exit("Initialized size must be non-negative (see %d)\n", sz);
}
buf_t *buf = (buf_t *)malloc(sizeof(buf_t));
SYSEXPECT(buf != NULL);
memset(buf, 0x00, sizeof(buf_t));
buf->size = 1; // Note that this includes the trailing zero
buf->capacity = sz;
buf->data = (char *)malloc(sz);
SYSEXPECT(buf->data != NULL);
memset(buf->data, 0x00, sz);
return buf;
}
buf_t *buf_init() {
return buf_init_sz(BUF_INIT_SIZE);
}
void buf_free(buf_t *buf) {
free(buf->data);
free(buf);
return;
}
// Clear all content, but do not realloc storage
void buf_reset(buf_t *buf) {
assert(buf->capacity > 0);
buf->size = 1;
buf->data[0] = '\0';
return;
}
// Reallocate storage, doubling the buffer capacity
// This call has no effect if target if smaller than current capacity
void buf_realloc(buf_t *buf, int target) {
assert(buf->size <= buf->capacity);
if(target <= buf->capacity) {
return;
}
// Always allocate power of two
while(buf->capacity < target) buf->capacity *= 2;
void *old_data = buf->data;
buf->data = (char *)malloc(buf->capacity);
SYSEXPECT(buf->data != NULL);
// This includes the trailing zero
memcpy(buf->data, old_data, buf->size);
free(old_data);
return;
}
// Append the string to the end of the buffer
void buf_append(buf_t *buf, const char *s) {
int len = strlen(s);
// This will likely not cause a realloc
buf_realloc(buf, buf->size + len);
// Start from the last char, copy includes the trailing zero
memcpy(buf->data + buf->size - 1, s, len + 1);
buf->size += len;
return;
}
void buf_putchar(buf_t *buf, char ch) {
buf_realloc(buf, buf->size + 1);
// Before this, buf[size - 1] is '\0'
buf->data[buf->size - 1] = ch;
buf->data[buf->size] = '\0';
buf->size++;
return;
}
// Concatenate the second arg after the first one and frees the second one
void buf_concat(buf_t *buf, buf_t *s) {
buf_append(buf, s->data);
buf_free(s);
return;
}
void buf_printf(buf_t *buf, const char *fmt, ...) {
va_list(args);
va_start(args, fmt);
char temp[BUF_INIT_SIZE];
int expected = vsnprintf(temp, BUF_INIT_SIZE, fmt, args);
if(expected >= 0 && expected < BUF_INIT_SIZE) {
buf_append(buf, temp);
return;
}
// Start a new arg, since the previous one may have been destroyed by the printf
va_list(args2);
va_start(args2, fmt);
char *temp2 = (char *)malloc(expected + 1);
SYSEXPECT(temp2 != NULL);
int expected2 = vsnprintf(temp2, expected + 1, fmt, args2);
assert(expected2 == expected);
buf_append(buf, temp2);
free(temp2);
return;
}
void buf_append_color(buf_t *buf, uint32_t color) {
char s[COLOR_STRLEN + 1];
color_str(color, s);
buf_append(buf, s);
return;
}
void buf_print(buf_t *buf, int content) {
printf("[buf] size %d cap %d data 0x%p\n", buf->size, buf->capacity, buf->data);
if(content == 1) {
printf("---------- contents ----------\n");
printf("%s\n", buf->data);
printf("------------ end -------------\n");
}
return;
}
void buf_dump(buf_t *buf, const char *filename) {
FILE *fp = fopen(filename, "w");
SYSEXPECT(fp != NULL);
// Do not write the trailing zero to the file
int ret = fwrite(buf->data, buf->size - 1, 1, fp);
if(ret != 1) {
printf("Error writing to the file %s\n", filename);
error_exit("Cannot write file\n");
}
fclose(fp);
return;
}
//* bar_t
bar_type_t *bar_type_init(const char *label) {
bar_type_t *type = (bar_type_t *)malloc(sizeof(bar_type_t));
SYSEXPECT(type != NULL);
memset(type, 0x00, sizeof(bar_type_t));
if(label != NULL) type->label = strclone(label);
return type;
}
void bar_type_free(bar_type_t *type) {
if(type->label != NULL) free(type->label);
free(type);
return;
}
// Duplicate the type object; Deep copy, if there is internal structure
// Except that "used" variable is set to zero
bar_type_t *bar_type_dup(bar_type_t *type) {
// This will perform a copy of the label string
bar_type_t *new_type = bar_type_init(type->label);
new_type->color = type->color;
new_type->hatch = type->hatch;
new_type->used = 0;
return new_type;
}
void bar_type_set_color(bar_type_t *type, uint32_t color) {
type->color = color;
return;
}
// Report error if invalid
void bar_type_set_hatch(bar_type_t *type, char hatch) {
if(hatch != HATCH_NONE && hatch_is_valid(hatch) == 0) {
error_exit("Invalid hatch: 0x%02X\n", (int)hatch);
} else {
type->hatch = hatch;
}
return;
}
void bar_type_print(bar_type_t *type) {
printf("[bar_type] label \"%s\" color 0x%08X hatch '%c' used %d anonymous %d\n",
type->label == NULL ? "[anonymous]" : type->label, type->color, type->hatch, type->used,
bar_type_is_anonymous(type));
return;
}
// Bar type object is init'ed to NULL, but it must be set before being drawn
bar_t *bar_init() {
bar_t *bar = (bar_t *)malloc(sizeof(bar_t));
SYSEXPECT(bar != NULL);
memset(bar, 0x00, sizeof(bar_t));
// This is to avoid having bar plotting params overwritten
bar->inited = 0;
return bar;
}
void bar_free(bar_t *bar) {
if(bar->text != NULL) free(bar->text);
free(bar);
return;
}
// Copies the text into a separate buffer and frees the previous one, if any
void bar_set_text(bar_t *bar, const char *text) {
if(bar->text != NULL) free(bar->text);
bar->text = strclone(text);
return;
}
void bar_print(bar_t *bar) {
printf("[bar] height %f width %f pos %f bottom %f text \"%s\" label \"%s\"\n",
bar->height, bar->width, bar->pos, bar->bottom,
bar->text == NULL ? "[N/A]" : bar->text,
bar->type ? (bar->type->label == NULL ? "[anonymous]" : bar->type->label) : "N/A");
printf(" inited %d stacked %d\n", bar->inited, bar->stacked);
return;
}
//* bargrp_t
bargrp_t *bargrp_init(const char *name) {
bargrp_t *grp = (bargrp_t *)malloc(sizeof(bargrp_t));
SYSEXPECT(grp != NULL);
memset(grp, 0x00, sizeof(bargrp_t));
if(name != NULL) grp->name = strclone(name);
grp->bars = vec_init();
return grp;
}
void bargrp_free(bargrp_t *grp) {
if(grp->name != NULL) free(grp->name);
// Free bars and the vector itself
for(int i = 0;i < vec_count(grp->bars);i++) {
bar_free(vec_at(grp->bars, i));
}
vec_free(grp->bars);
free(grp);
return;
}
void bargrp_print(bargrp_t *grp, int verbose) {
printf("[bargrp] name \"%s\" size %d anonymous %d\n",
grp->name == NULL ? "[anonymous]" : grp->name, vec_count(grp->bars), bargrp_is_anonymous(grp));
if(verbose == 1) {
for(int i = 0;i < vec_count(grp->bars);i++) {
bar_print(vec_at(grp->bars, i));
}
}
return;
}
//* plot_t
plot_param_t default_param = {
12.0, 6.0, // Width and Height
1, // legend_enabled
1, // legend_rows
28, // legend_font_size
"best", // Legend pos; Alternatives are: {lower, center, upper} x {left, center, right} or "center"
1, INFINITY, PLOT_DIRECTION_INSIDE, 24, 0, 1, // x tick enabled, length, dir, font size, rotation, label enabled
1, INFINITY, PLOT_DIRECTION_INSIDE, 24, 0, 1, // y tick enabled, length, dir, font size, rotation, label enabled
0, // x grid enabled
0, // y grid enabled
28, 28, // x/y title font size
26, 90, // bar text size, rotation
2, 1, // bar text decimals, rtrim
NULL, 0, // Hatch scheme/offset
NULL, 0, // Color scheme/offset
INFINITY, INFINITY, // xlimits
INFINITY, INFINITY, // ylimits
1.0, // bargrp space
0, // Dry run
1, // Info
};
void plot_param_copy(plot_param_t *dst, plot_param_t *src) {
if(dst->color_scheme != NULL) color_scheme_free(dst->color_scheme);
if(dst->hatch_scheme != NULL) hatch_scheme_free(dst->hatch_scheme);
memcpy(dst, src, sizeof(plot_param_t));
if(src->color_scheme != NULL) dst->color_scheme = color_scheme_dup(src->color_scheme);
if(src->hatch_scheme != NULL) dst->hatch_scheme = hatch_scheme_dup(src->hatch_scheme);
return;
}
void plot_param_print(plot_param_t *param, int verbose) {
printf("[param] width %f height %f\n", param->width, param->height);
printf("[param legend] enabled %d font size %d rows %d pos \"%s\"\n",
param->legend_enabled, param->legend_font_size, param->legend_rows, param->legend_pos);
printf("[param title] x font %d y font %d\n",
param->xtitle_font_size, param->ytitle_font_size);
printf("[param xtick] enabled %d len %f dir %d font %d rot %d label %d\n",
param->xtick_enabled, param->xtick_length, param->xtick_direction, param->xtick_font_size, param->xtick_rotation,
param->xtick_label_enabled);
printf("[param ytick] enabled %d len %f dir %d font %d rot %d label %d\n",
param->ytick_enabled, param->ytick_length, param->ytick_direction, param->ytick_font_size, param->ytick_rotation,
param->ytick_label_enabled);
printf("[param xgrid] enabled %d\n",
param->xgrid_enabled);
printf("[param ygrid] enabled %d\n",
param->ygrid_enabled);
printf("[param bar_text] font %d rotation %d\n", param->bar_text_font_size, param->bar_text_rotation);
printf("[param bar_text] decimals %d rtrim %d\n",
param->bar_text_decimals, param->bar_text_rtrim);
if(param->hatch_scheme != NULL) {
// There is no nwe line after this, if verbose is turned on
printf("[param hatch] Offset %d (usable %d) ",
param->hatch_offset, param->hatch_scheme->item_count - param->hatch_offset);
if(verbose == 1) hatch_scheme_print(param->hatch_scheme, verbose);
else putchar('\n');
}
if(param->color_scheme != NULL) {
printf("[param color] Offset %d (usable %d) ",
param->color_offset, param->color_scheme->item_count - param->color_offset);
if(verbose == 1) color_scheme_print(param->color_scheme, verbose);
else putchar('\n');
}
printf("[param x/y_lim] left %f right %f top %f bottom %f\n",
param->xlim_left, param->xlim_right, param->ylim_top, param->ylim_bottom);
printf("[param bargrp] space %f\n", param->bargrp_space);
printf("[debug] dry_run %d info %d\n", param->dry_run, param->info);
return;
}
//* plot_tick_t
plot_tick_t *plot_tick_init() {
plot_tick_t *tick = (plot_tick_t *)malloc(sizeof(plot_tick_t));
SYSEXPECT(tick != NULL);
memset(tick, 0x00, sizeof(plot_tick_t));
tick->poses = vec_init();
tick->labels = vec_init();
if(sizeof(double) != 8UL) error_exit("The size of a double must be 8 bytes\n");
return tick;
}
void plot_tick_free(plot_tick_t *tick) {
// Free label strings first
for(int i = 0;i < vec_count(tick->labels);i++) {
free((char *)vec_at(tick->labels, i));
}
vec_free(tick->labels);
vec_free(tick->poses);
free(tick);
return;
}
void plot_tick_append(plot_tick_t *tick, double pos, const char *str) {
uint64_t t = *(uint64_t *)&pos;
vec_append(tick->poses, (void *)t);
// Duplicate the string and push into the vector
vec_append(tick->labels, (void *)strclone(str));
assert(vec_count(tick->poses) == vec_count(tick->labels));
return;
}
double plot_tick_pos_at(plot_tick_t *tick, int index) {
assert(index >= 0 && index < vec_count(tick->poses));
// Must do this to let compiler perform binary conversion
uint64_t t = (uint64_t)vec_at(tick->poses, index);
return *(double *)&t;
}
char *plot_tick_label_at(plot_tick_t *tick, int index) {
assert(index >= 0 && index < vec_count(tick->poses));
return (char *)vec_at(tick->labels, index);
}
buf_t *plot_tick_pos_str(plot_tick_t *tick) {
buf_t *buf = buf_init();
buf_append(buf, "[");
for(int i = 0;i < vec_count(tick->poses);i++) {
buf_printf(buf, "%f, ", plot_tick_pos_at(tick, i));
}
buf_append(buf, "]");
return buf;
}
buf_t *plot_tick_label_str(plot_tick_t *tick) {
buf_t *buf = buf_init();
buf_append(buf, "[");
for(int i = 0;i < vec_count(tick->poses);i++) {
assert(plot_tick_label_at(tick, i) != NULL);
buf_printf(buf, "'%s', ", plot_tick_label_at(tick, i));
}
buf_append(buf, "]");
return buf;
}
void plot_tick_print(plot_tick_t *tick, int verbose) {
int count = vec_count(tick->poses);
printf("[plot_tick] count %d\n", count);
if(verbose == 1) {
for(int i = 0;i < count;i++) {
printf("[plot_tick] Index %d pos %f label \"%s\"\n",
i, plot_tick_pos_at(tick, i), plot_tick_label_at(tick, i));
}
}
return;
}
// We use "plot" as the root name of the plot; "fig" as the name of the figure object
const char *plot_preamble = \
"import sys\n"
"import matplotlib as mpl\n"
"import matplotlib.pyplot as plot\n"
"import matplotlib.ticker as ticker\n"
"\n"
"mpl.rcParams['ps.useafm'] = True\n"
"mpl.rcParams['pdf.use14corefonts'] = True\n"
"mpl.rcParams['text.usetex'] = True\n"
"mpl.rcParams['text.latex.preamble'] = [\n"
" r'\\usepackage{siunitx}',\n"
" r'\\sisetup{detect-all}',\n"
" r'\\usepackage{helvet}',\n"
" r'\\usepackage{sansmath}',\n"
" r'\\sansmath'\n"
"]\n"
"\n";
plot_t *plot_init() {
plot_t *plot = (plot_t *)malloc(sizeof(plot_t));
SYSEXPECT(plot != NULL);
memset(plot, 0x00, sizeof(plot_t));
// Initialize member variables
plot->py = py_init();
plot->buf = buf_init();
plot->bar_types = vec_init();
plot->drawn = 0;
plot->bargrps = vec_init();
plot->xtick = plot_tick_init();
plot->ytick = plot_tick_init();
buf_append(plot->buf, plot_preamble);
// Init param
memcpy(&plot->param, &default_param, sizeof(plot_param_t));
return plot;
}
void plot_free(plot_t *plot) {
buf_free(plot->buf);
py_free(plot->py);
// Frees type array
for(int i = 0;i < vec_count(plot->bar_types);i++) {
bar_type_free((bar_type_t *)vec_at(plot->bar_types, i));
}
vec_free(plot->bar_types);
// Free bar groups and the vector
for(int i = 0;i < vec_count(plot->bargrps);i++) {
bargrp_free(vec_at(plot->bargrps, i));
}
vec_free(plot->bargrps);
// Free current bar group if not NULL. This should not be normal, however
if(plot->curr_bargrp != NULL) {
printf("WARNING: curr_bargrp is not NULL. Some bargroups are not added for plotting\n");
bargrp_free(plot->curr_bargrp);
}
// Free ticks
plot_tick_free(plot->xtick);
plot_tick_free(plot->ytick);
// Note that parse can be NULL if it is not initialized
if(plot->parse != NULL) parse_free(plot->parse);
if(plot->xtitle) free(plot->xtitle);
if(plot->ytitle) free(plot->ytitle);
if(plot->fig_filename) free(plot->fig_filename);
if(plot->legend_filename) free(plot->legend_filename);
plot_param_t *param = &plot->param;
// Free color and hatch scheme if they are allocated
if(param->color_scheme != NULL) color_scheme_free(param->color_scheme);
if(param->hatch_scheme != NULL) hatch_scheme_free(param->hatch_scheme);
free(plot);
return;
}
// Open a script file for parsing
void plot_open(plot_t *plot, const char *filename) {
plot->parse = parse_init_file(filename);
return;
}
// The string will be copied into the parser
void plot_open_str(plot_t *plot, const char *s) {
plot->parse = parse_init(s);
return;
}