-
Notifications
You must be signed in to change notification settings - Fork 1
/
p-psql2latex.py
executable file
·1063 lines (884 loc) · 36.8 KB
/
p-psql2latex.py
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Ignoring warnings about "Used * or ** magic (star-args)"
# pylint: disable=W0142
# Author: Peter Moser <pitiz29a@gmail.com)
r"""## LaTex table and image generator for timelines and temporal tables
Generate LaTex and TIKZ files from PostgreSQL's `psql` command output
![Screenshot of Latex document](https://github.com/Piiit/pwScripts/blob/master/res/pgsql2latex-screen01.jpg)
Download
--------
* [pw_pgsql2latex.py](https://github.com/Piiit/pwScripts/blob/master/pw_pgsql2latex.py)
Usage
-----
(automatically printed from `argparse` module)
Introduction
------------
Reads an PostgreSQL (`psql --echo-all`, see man-page of psql for further
details) output, and creates a standalone TIKZ tex-figure, or combined
table/figure LaTex file to be used with `\input{filename}`. To configure each
output table or timeline a SQL comment starting with `TIKZ:` must be provided.
In addition this script needs the following prerequisites for the input:
1. There must be at least 2 columns for VALID TIME for each table
2. Each relation must have a TIKZ config line as SQL comment (see below)
3. A single timeline can be defined with `TIKZ: timeline, from, to, desc`
This is optional.
NB: Since version 0.8 it also supports TSV files, instead of PostgreSQL output.
We do not use some Python PostgreSQL libs here, because TEMPORAL OPERATORS are
not supported yet. Another reason is that we can create output files manually,
if we do not have a (TEMPORAL) POSTGRESQL instance running.
TIKZ-comment syntax
-------------------
First argument after `TIKZ:` is the type of drawing. The following lines
describe which types are supported:
1. `-- TIKZ: relation[-table], [abbrev], start column, [end column], [ypos],
description` <br>
If you put `relation-table` as drawing-type, a table and a diagram will be
printed.
The abbreviation is optional (it is used for tuple names). If you want to
suppress it, do not forget to put the comma separator anyway.
If `end column` is empty, the parser assumes a PostgreSQL rangetype at
`start column`, or a point representation if the rangetype parsing failes.
The optional `ypos` defines the y-position of each tuple inside the figure.
2. `-- TIKZ: timeline, from, to, step, description`
3. `-- TIKZ: config, key, value` <br>
The key and value of this line is used for the combined table/figure
picture, or for the standalone tikzpicture file. You can configure the
label and caption of figures for instance.
```
Possible configurations by key/value:
key value
------------------------------------------------------------------------
label TEX label \label
caption TEX figure caption
subfigure-left left subfigure column's width
subfigure-right right subfigure column's width. Both subfigure widths
should sum up to 0.9 (0.1 space in between is fixed).
However, I keep it configurable in order to not be too
restrictive.
tablecaption subfigure's table caption
tablelabel subfigure's table label
graphcaption subfigure's graph caption
graphlabel subfigure's graph label
xscale scale of the tikzpicture (on the x-axis)
yscale scale of the tikzpicture (on the y-axis)
```
Example
-------
If you run the following code as a file with `psql -a -d DBNAME -f FILENAME`...
```
-- TIKZ: relation, r, ts, te,, Input relation r
TABLE r;
-- TIKZ: relation, s, ts, te,, Input relation s
SELECT * FROM s WHERE a='B';
-- TIKZ: timeline, 0, 10, 1, time
-- TIKZ: config, figure01, This is a caption (latex-syntax possible)
```
...then you get the following output, which serves as input to
**pw_pgsql2latex.py**.
```
-- TIKZ: relation, r, ts, te,, Input relation r
TABLE r;
a | ts | te
---+----+----
B | 1 | 7
B | 3 | 9
G | 8 | 10
-- TIKZ: relation, s, ts, te,, Input relation s
SELECT * FROM s WHERE a='B';
a | ts | te
---+----+----
B | 2 | 5
B | 3 | 4
B | 7 | 9
-- TIKZ: timeline, 0, 10, 1, time
-- You can refer to this figure with \ref{fig:input001}
-- TIKZ: config, label, input001
-- TIKZ: config, caption, Input relations \textbf{r} and \textbf{s}
```
You can also use TSV for relations, instead of PostgreSQL outputs. If you want to do
so, add `-- TIKZ: TSV` as very first line of your input file. The first non-comment
line will be interpreted as beginning of a table, that is, the header followed by
some lines representing tuples. NB: Separate each header or tuple with tabulators.
The full piped command is then: `psql -a -d DBNAME -f FILENAME |
pgsql2latex.py -o OUTPUTFILE -`.
To use the `OUTPUTFILE` inside a LaTex document, just add a input-command
`\input{OUTPUTFILE}`.
Changelog
---------
* 0.9thesis
- xscale/yscale for tikz pictures
- point representation (cross) if only one scalar value is given as time
- steps on the time line can now be configured
- Fast hacks for thesis: to adjust ypos of tuples given by an input attribute
* 0.8
- Tab-separated-values (TSV) support
- Support for different input types (currently only Postgres and TSV)
- Periods instead of single attributes as time point start/end (boundary
types ignored, i.e., always closed intervals used)
* 0.7
- Table above graphs representation with -A or --All
* 0.6
- Port to Python 3
- Inclusive intervals as option
* 0.5
- TIKZ-config lines are now key/value pairs
- Additional config parameters to tweak the TEX output, i.e., subfigure
column widths
* 0.4.1
- BUGFIX: captions are no longer truncated if a comma is found
* 0.4
- config line added to provide "label" and "caption" to LaTex
- command line arguments (see usage output for details; i.e., `--help`)
* 0.3
- Parser becomes a generator (i.e., we use yield)
- Parser simplified, returns only tokens to reuse it later for other
projects
- String formatting unified
* 0.2
- Reads configs from SQL comments with prefix `-- TIKZ`
- Checks if TIKZ configs and data input matches
- Different string formatting techniques tested (just for fun!)
- Skips SQL commands
- pylint errors and warnings fixed (most)
* 0.1
- Creates a standalone tikz picture from a PostgreSQL output
- Skips comments and empty lines
- Restriction: Hard-coded configuration
"""
import re
import os
import stat
import sys
import argparse
import io
__version__ = "0.9thesis"
def main():
"""Main, nothing more to say :-)"""
parser = argparse.ArgumentParser(conflict_handler='resolve')
parser.add_argument(
'--manual',
action='store_true',
help='Print a short manual showing the module docstring of ' +
os.path.basename(__file__))
parser.add_argument(
'FILE',
default='-',
type=argparse.FileType('r'),
help='Input files taken from the "psql --echo-all" output\n'
'Use a dash, i.e. -, if you want to use STDIN.')
parser.add_argument(
'-o',
'--output',
metavar='FILE',
help='Put output into FILE; default is STDOUT')
parser.add_argument(
'-s',
'--standalone',
action='store_true',
dest='output_standalone',
help='Output the TIKZ figures and tables as a standalone LaTex file.')
group = parser.add_mutually_exclusive_group()
group.add_argument(
'-a',
'--all',
action='store_const',
dest='output_type',
const='all',
help='OUTPUT TYPE: Output the LaTex table and the TIKZ figure '
'side-by-side. This is the default.')
group.add_argument(
'-A',
'--All',
action='store_const',
dest='output_type',
const='All',
help='OUTPUT TYPE: Output the LaTex table above the TIKZ figure.')
group.add_argument(
'-t',
'--table-only',
action='store_const',
dest='output_type',
const='table-only',
help='OUTPUT TYPE: Output the LaTex table only.')
group.add_argument(
'-f',
'--figure-only',
action='store_const',
dest='output_type',
const='figure-only',
help='OUTPUT TYPE: Output the TIKZ figure only.')
parser.set_defaults(output_type='all')
# We must capture this option before we parse the arguments, because the
# last positional argument FILE is mandatory. Hence, the parser would exit
# with an error (There is no meaningful exception to catch, except for
# SystemExit).
if len(sys.argv) == 2 and sys.argv[1] == '--manual':
docparts = __doc__.split("Usage\n-----\n(automatically printed from `argparse` module)\n", 1)
# Print title and section before "usage"
print (docparts[0])
# Print usage information
sys.stdout.write("Usage\n-----\n```\n")
parser.print_help()
print ("```")
# Print the rest
#print "\n".join(__doc__.split('\n', 1)[1:])
print (docparts[1])
sys.exit(0)
# Now parse regular command line arguments
args = parser.parse_args()
# Stdin file stats to see if it is a pipe or redirection...
mode = os.fstat(sys.stdin.fileno()).st_mode
# Input files are explicitely given as a filename list
#if type(args.FILE) is file:
if isinstance(args.FILE, io.IOBase):
input_file = args.FILE
input_text = input_file.readlines()
# We have a piped or redirected STDIN at disposal...
elif stat.S_ISFIFO(mode) or stat.S_ISREG(mode):
print ("READING FROM STDIN\n")
input_text = sys.stdin.readlines()
# No stdin, no input files... shutdown!
else:
parser.error("No input files, nor stdin given (i.e., a dash).")
try:
parse_result = pgsql_parser(input_text)
figure = ""
table = ""
cfg = {}
if args.output_type in ['all', 'All', 'table-only']:
table_type = 1
if args.output_type == 'all':
table_type = 2
if args.output_type == 'All':
table_type = 3
for line in parse_result:
if line['type'] == 'relation-table':
if table == "":
table = format_latex_table(line, "", table_type)
else:
table += " \hspace{2cm}" + format_latex_table(line, "", table_type)
if line['type'] == 'config':
cfg[line['key']] = line['value']
# If we print the whole figure/table combination, we need a "label" and
# "caption" below the two sub-figures.
if args.output_type in ['all', 'All']:
if not 'label' in cfg:
raise_error_cfgline(
'label',
"We do not know which 'label' to use for figures.")
if not 'caption' in cfg:
raise_error_cfgline(
'caption',
"We do not know which 'caption' to use for figures.")
if args.output_type in ['all', 'All', 'figure-only']:
figure = format_tikz_figure(parse_result, cfg)
# TODO Create text first in memory, and write it at last. Otherwise, we
# could get half-made output files, when an error occurs
outfile = sys.stdout
if args.output != None:
if os.path.isfile(args.output):
raise_error("File '%s' already exists! Exiting..." % args.output)
outfile = open(args.output, 'w')
outfile.write(format_latex_header("".join(input_text)))
if args.output_type == 'all':
# Subfigures have a left and right column with a certain width
# If it is not configured explicitely, we will take these defaults:
subfigure_left = list_get(cfg, 'subfigure-left', 0.27)
subfigure_right = list_get(cfg, 'subfigure-right', 0.63)
out = format_latex_figure_and_table(table,
figure,
cfg['caption'],
cfg['label'],
subfigure_left,
subfigure_right)
elif args.output_type == 'All':
out = format_latex_figure_and_table_top(table, figure,
cfg['caption'],
cfg['label'],
cfg['tablecaption'],
cfg['tablelabel'],
cfg['graphcaption'],
cfg['graphlabel'])
elif args.output_type == 'table-only':
out = table
elif args.output_type == 'figure-only':
out = figure
else:
raise_error("Unknown output type specified")
if args.output_standalone:
out = format_latex_standalone(out)
outfile.write(out)
except ValueError as valerr:
print ("\n".join(valerr.args) + "\n")
sys.exit(3)
def format_tikz_desc(pos, desc):
"""Prints the description of each found table on the left-hand-side of the
tuple time lines in a standalone tikz figure"""
return TEMPLATE_TIKZ_DESC.format(pos=pos,
desc=desc)
def format_tikz_tupleline(tup, relation, tupid, ypos):
"""Prints the tuple time lines in a standalone tikz figure"""
template = TEMPLATE_TIKZ_TUPLE
valid_time_ts = relation.getTupleTS(tup)
valid_time_te = relation.getTupleTE(tup)
# Single point detected: Generate point representation
if valid_time_te == -1:
valid_time_te = valid_time_ts + 1
template = TEMPLATE_TIKZ_POINT
# Concatenate all non-temporal (non-meta) attributes as description above the line
attribs = ""
for key, value in enumerate(relation.getTupleB(tup)):
attribs += r"%s," % value
if len(attribs) == 0:
out = template + "{{${name}_{{{id}}}$}};\n"
else:
if relation.name == "":
out = template + "{{({attribs})}};\n"
else:
out = template + "{{${name}_{{{id}}}$=({attribs})}};\n"
return out.format(name=relation.name,
id=tupid,
ts=valid_time_ts,
te=valid_time_te,
posx=float(valid_time_ts+valid_time_te) / 2,
posy=ypos,
attribs=attribs.rstrip(','))
def format_tikz_timeline(cfg, pos):
"""Prints a timeline in a standalone tikz figure"""
# pos_numbers = 0
# if 'inclusive' in cfg and cfg['inclusive']:
# pos_numbers = 5
pos_numbers = 5
if 'step' in cfg and cfg['step']:
return TEMPLATE_TIKZ_TIMELINE2.format(start=int(cfg['from']),
end=int(cfg['to']),
step=int(cfg['step']),
desc=cfg['desc'],
posno=pos_numbers,
pos=pos)
return TEMPLATE_TIKZ_TIMELINE.format(start=int(cfg['from']),
end=int(cfg['to']),
desc=cfg['desc'],
posno=pos_numbers,
pos=pos)
def raise_error(msg, hint=""):
"""Print an error message and a hint to solve the issue. The text is
automatically indented behind "ERROR: " and "HINT : " strings."""
if hint != "":
hint = "HINT : " + hint
raise ValueError("ERROR: " + os.path.basename(__file__) + ": " + msg, hint)
def raise_error_cfgline(key, msg):
"""Print an error message like raise_error, but for TIKZ: config, ...
lines. """
raise_error(
"No config line with key '" + key + "' found!\n" + msg,
"Define a configuration string of type 'config' and key '" + key + "'\n"
"For example:\n"
"-- TIKZ: config, " + key + ", value")
def pgsql_tokenizer(lines):
"""We parse the input lines with a simple state machine, and generate a
token (i.e., 2-element list, with key and value) that we give back at each
iteration"""
input_type = INPUT_TYPE_POSTGRES
value_sep = '|'
state = STATE_FIRSTLINE
for line in lines:
line = line.lstrip()
if state == STATE_FIRSTLINE:
state = STATE_OUTSIDE
match = re.search(r'--\s*TIKZ: TSV', line)
if match:
input_type = INPUT_TYPE_TSV
value_sep = '\t'
continue
# Skip empty lines
# This ends a table parsing, and returns to the STATE_OUTSIDE state
if line.rstrip() == "":
state = STATE_OUTSIDE
continue
# Skip SQL comments (except if they start with the keyword TIKZ)
if line.startswith('--'):
# We have found a SQL config line
if state == STATE_OUTSIDE:
yield ['COMMENT', line.lstrip("-- ").rstrip()]
# If we have seen an header line already, this is a table
# horizontal line which starts tuple lines, i.e., ----+----+-----
if state == STATE_HEADER:
state = STATE_TUPLES
continue
# Not skipped and currently in STATE_OUTSIDE state, hence it could be a
# header line, or SQL command. Since we must have at least two temporal
# columns, we can search for columns delimiters, i.e., |.
if state == STATE_OUTSIDE:
# PostgreSQL output: Search for table headers first, if not found, skip it...
# TSV output: First line (not a comment), must be a table header...
if input_type == INPUT_TYPE_POSTGRES:
if None == re.search(r'\s*[^\|]+?\s*\|\s*[^\|]+?', line):
yield ['COMMAND', line.rstrip()]
continue
state = STATE_HEADER
headers = []
for head in line.split(value_sep):
headers.append(head.strip())
yield ['HEADER', headers]
if input_type == INPUT_TYPE_TSV:
state = STATE_TUPLES
continue
# Not skipped and currently in a tuple state, therefore the next data
# line must be another tuple, or tuple count, i.e., (3 rows)
if state == STATE_TUPLES:
# PostgreSQL: We skip tuple count rows at the end of each table. This ends a table block.
match = re.search(r'\((\d+?)\s\w*\)', line)
if match:
state = STATE_OUTSIDE
yield ['TUPLECOUNT', match.group(1)]
continue
values = []
for value in line.split(value_sep):
values.append(value.strip())
yield ['TUPLE', values]
def pgsql_parser(text):
"""We parse the input lines with a simple state machine"""
configs = []
tables = []
table_count = 0 # How many table with header and tuples have been found in the input?
configs_count_relation = 0
configs_count_timeline = 0
for token in pgsql_tokenizer(text):
# First, search for a TIKZ comment line, which looks as follows:
# -TIKZ: name, config-list-comma-separated
# Depending on "name" we get a different number of parameters in
# "config-list-comma-separated". The last entry therein is either
# a description or a caption, which can contain commas which will
# be kept.
if token[0] == 'COMMENT':
match = re.search(r'TIKZ:\s*([a-z\-]+?)\s*,\s*(.*)+?', token[1])
if match:
comment_type = match.group(1)
comment_body = match.group(2)
if comment_type == 'config':
listitems = [comment_type] + re.split(r'\s*,\s*', comment_body, 1)
configs.append(dict(zip(['type', 'key', 'value'], listitems)))
elif comment_type in ['relation', 'relation-table']:
listitems = [comment_type] + re.split(r'\s*,\s*', comment_body, 4)
if len(listitems) != 6:
raise_error("Not enough parameters for TIKZ relation or TIKZ relation-table given.\n" +
"For example:\n--TIKZ: relation, R, ts, te, ypos, Description string\n" +
"Instead the following was given: --" + token[1])
if configs_count_relation < table_count:
relation = tables[table_count]
else:
relation = Relation()
tables.append(relation)
configs_count_relation += 1
relation.setMetaData(listitems[1:])
configs.append({'type' : listitems[0], 'relation' : relation})
elif comment_type == 'timeline':
if configs_count_timeline == 1:
raise_error(
"More than one TIKZ timeline string found",
"Define a single configuration string for the " +
"timeline.\n For example:\n" +
"-- TIKZ: timeline, from, to, step, time line " +
"description")
else:
listitems = [comment_type] + re.split(r'\s*,\s*', comment_body, 3)
if len(listitems) != 5:
raise_error(
"Wrong TIKZ timeline string found: '%s'" % token[1],
"Define a correct configuration string for the " +
"timeline.\n For example: " +
"-- TIKZ: timeline, from, to, step, time line " +
"description")
configs_count_timeline += 1
configs.append(dict(zip(['type', 'from', 'to', 'step', 'desc'], listitems)))
elif token[0] == 'HEADER':
if configs_count_relation > table_count:
relation = tables[table_count]
else:
relation = Relation()
tables.append(relation)
table_count += 1
relation.setSchema(token[1])
elif token[0] == 'TUPLE':
relation = tables[table_count - 1]
relation.addTuple(token[1])
if configs_count_relation == 0:
raise_error(
"No tables found! Is this a valid input file?")
# The amount of relation config strings and table outputs must match!
if configs_count_relation < len(tables):
raise_error(
"We do not have enough TIKZ relation config strings",
"Define a configuration string for each table.\n" +
"For example:\n" +
"-- TIKZ: relation, table_name, ts, te, relation description")
if configs_count_relation > len(tables):
raise_error(
"We do not have enough table outputs compared to the amount of " +
"TIKZ relation config strings",
"Either delete a configuration string for a table, or provide\n" +
"an additional SQL-command to produce a table output.\n" +
"For example:\n" +
"-- TIKZ: relation, table_name, ts, te, relation description")
return configs
def format_tikz_figure(parse_result, cfg):
"""
Draw a TIKZ figure with an optional timeline, tuple-lines for each tuple in
all given tables, and description on the right-hand-side of each table.
"""
# Count tuples above the timeline. We do this, because we need to count
# backwards while creating lines above the timeline. However, it is not
# necessary below, because there we count starting from 1, s.t., the
# index 1 is always close to the timeline in the middle.
posy = 0
out = ""
xscale = float(list_get(cfg, 'xscale', 0.65))
yscale = float(list_get(cfg, 'yscale', 0.4))
ystep = float(list_get(cfg, 'ystep', 1))
offset = 0
for line in parse_result:
# Print the timeline
if line['type'] == 'timeline':
iout = format_tikz_timeline(line, offset)
offset -= 2
out += iout
continue
if line['type'] in ['relation', 'relation-table']:
relation = line['relation']
# Print tuples of each table as lines from ts to te. The description of
# each tuple is a list of explicit attributes (i.e., non-temporal
# columns), and optionally a tuple identifier "relation_tuplecount"
posy = offset
for tuple_count, tup in enumerate(relation.values, 1):
if relation.ypos != -1:
posy = offset + float(relation.getTupleYPOS(tup) - relation.getYMax())
out += format_tikz_tupleline(tup, relation, tuple_count, posy)
posy -= 1
offset = offset - (relation.getYMax() - relation.getYMin()) - ystep
# Print description on the left-hand-side of each relation
if relation.desc.strip() != "":
p = (offset + ystep) + (relation.getYMax() - relation.getYMin()) / 2
out += format_tikz_desc(p, relation.desc)
return TEMPLATE_TIKZ_PICTURE.format(content=out, xscale=xscale, yscale=yscale)
def format_latex_header(raw_data):
"""Prints a TEX comment header including a version, this app's name, and
the input text."""
return TEMPLATE_HEADER.format(
appname=os.path.basename(__file__),
appversion=__version__,
input="".join("%% %s\n" % x for x in raw_data.strip().split("\n")))
def format_latex_standalone(content):
"""Creates a TIKZ standalone latex document"""
return TEMPLATE_TIKZ_DOC.format(content=content)
def format_latex_table(line, label, table_type=1):
"""Print a single table from a relation-config-line"""
if line['type'] not in ['relation', 'relation-table']:
raise_error("Latex Print Table: Provided config-line has wrong " \
"type '%s' (type 'relation' expected)" % line['type'])
relation = line['relation']
# We skip the first element inside a table. It is the header.
header = relation.getSchemaTemporal()
tuples = relation.getTuplesTB()
# Concatenate all non-temporal attributes as description above the line
attribs = r" & ".join(header)
rows = ""
for row_count, row in enumerate(tuples, 1):
rows += " " * 12 + "$%s_{%d}$ & %s \\\\\n" % (relation.name,
row_count,
r" & ".join(row))
if table_type == 1:
return TEMPLATE_LATEX_TABLE.format(
caption=relation.desc,
label=label,
length=len(header) + 1,
header_cfg="c" * len(header),
header=attribs.rstrip(" &"),
rows=rows.rstrip("\n"))
if table_type == 2:
return TEMPLATE_LATEX_TABLE2.format(
header_cfg="c" * len(header),
header=attribs.rstrip(" &"),
rows=rows.rstrip("\n"),
relation=relation.name)
return TEMPLATE_LATEX_TABLETOP.format(
header_cfg="c" * len(header),
header=attribs.rstrip(" &"),
rows=rows.rstrip("\n"),
relation=relation.name)
def format_latex_figure_and_table(table_str, tikz_str, caption, label, subfigure_left, subfigure_right):
"""Prints a figure and a table side-by-side as sub-figures"""
return TEMPLATE_LATEX_TIKZTABLE.format(table=table_str,
tikzpicture=tikz_str,
caption=caption,
label=label,
subfigureleft=subfigure_left,
subfigureright=subfigure_right)
def format_latex_figure_and_table_top(table_str, tikz_str, caption, label, tablecaption, tablelabel, graphcaption, graphlabel):
"""Prints a figure and a table side-by-side as sub-figures"""
return TEMPLATE_LATEX_TIKZTABLETOP.format(table=table_str,
tikzpicture=tikz_str,
caption=caption,
label=label,
tablecaption=tablecaption,
tablelabel=tablelabel,
graphcaption=graphcaption,
graphlabel=graphlabel)
def list_get (l, idx, default):
try:
return l[idx]
except:
return default
# STATES of the tokenizer, which is implemented as a state machine...
STATE_FIRSTLINE = 0
STATE_OUTSIDE = 1 # We have not found a table yet
STATE_HEADER = 2 # We have found a table STATE_HEADER (attribute names)
STATE_TUPLES = 3 # We have already parsed the table header, and are
# reading in tuples now
INPUT_TYPE_POSTGRES = 0
INPUT_TYPE_TSV = 1
TEMPLATE_HEADER = r"""% This file has been automatically generated by...
%
% {appname} v{appversion} written by Peter Moser <pitiz29a@gmail.com>
% Source code can be found under: https://github.com/Piiit/pwScripts
%
% From input:
% _______________________________________________________________INPUT-START__
{input}% _______________________________________________________________INPUT-END____
"""
TEMPLATE_TIKZ_DOC = r"""
\documentclass{{article}}
\usepackage{{subcaption}}
\usepackage{{tikz}}
\usetikzlibrary{{
arrows,
decorations,
positioning,
shapes,
fit,
calc,
matrix
}}
\begin{{document}}
{content}
\end{{document}}
"""
TEMPLATE_TIKZ_PICTURE = r"""
\begin{{tikzpicture}}[xscale={xscale},yscale={yscale}]
{content}
\end{{tikzpicture}}
"""
# Prints the description of each found table on the left-hand-side of the
# tuple time lines in a standalone tikz figure
TEMPLATE_TIKZ_DESC = r"""
% Description
\node[align=left, font=\scriptsize] at (0,{pos}) {{{desc}}};
"""
# Regular timeline representation with a number on each step
TEMPLATE_TIKZ_TIMELINE = r"""
% Time line
\draw[->, line width = 0.9] ({start},{pos})--({end}+1,{pos});
\foreach \t in {{{start},...,{end}}}
{{
\draw ($(\t cm,-1mm)+(0cm,{pos})$)--($(\t cm,1mm)+(0cm,{pos})$);
\draw ($(\t {posno}mm,{pos})$) node[below,font=\scriptsize \bfseries]{{\t}};
}}
\draw ($({end}+1,{pos})+(3mm,-1mm)$) node[below,font=\bfseries]{{$\mathrm{{{desc}}}$}};
"""
# Time line with number at each {step}.
TEMPLATE_TIKZ_TIMELINE2 = r"""
% Time line
\draw[->, line width = 0.9] ({start},{pos})--({end}+1,{pos});
\foreach \t in {{{start},...,{end}}}
{{
\draw ($(\t cm,-1mm)+(0cm,{pos})$)--($(\t cm,1mm)+(0cm,{pos})$);
\pgfmathparse{{Mod(\t, {step}) == 0 ? 1 : 0}}
\ifnum\pgfmathresult>0
\draw ($(\t {posno}mm,{pos})$) node[below,font=\scriptsize \bfseries]{{\t}};
\fi
}}
\draw ($({end}+1,{pos})+(3mm,-1mm)$) node[below,font=\bfseries]{{$\mathrm{{{desc}}}$}};
"""
TEMPLATE_TIKZ_TUPLE = r"""
% Tuple {name}_{id}
\draw[-] ({ts},{posy})--({te},{posy});
\draw[-] ({posx},{posy}-0.2) node[above,font=\tiny]"""
TEMPLATE_TIKZ_POINT = r"""
% Point {name}_{id}
\draw ({ts}+0.5,{posy}) node[cross] {{}};
\draw[-] ({posx},{posy}-0.2) node[above,font=\tiny]"""
TEMPLATE_LATEX_TABLE = r"""
\begin{{table}}
\renewcommand{{\arraystretch}}{{1.3}}
\caption{{{caption}}}
\label{{tab:{label}}}
\centering
\begin{{tabular}}{{c|{header_cfg}|}}
\cline{{2-{length}}}
~ & {header} \\
\cline{{2-{length}}}
{rows}
\cline{{2-{length}}}
\end{{tabular}}
\end{{table}}
"""
TEMPLATE_LATEX_TABLE2 = r"""
\begin{{tabular}}{{|c|{header_cfg}|}}
\hline
\bfseries {relation} & {header} \\
\hline
{rows}
\hline
\end{{tabular}}
"""
TEMPLATE_LATEX_TIKZTABLE = r"""
\begin{{figure}}[htb]
\centering
\hfills = []
\begin{{subfigure}}[c]{{{subfigureleft}\textwidth}}
{table}
\end{{subfigure}}
\hspace{{10pt}}
\begin{{subfigure}}[c]{{{subfigureright}\textwidth}}
{tikzpicture}
\end{{subfigure}}
\caption{{{caption}}}
\label{{fig:{label}}}
\end{{figure}}"""
TEMPLATE_LATEX_TABLETOP = r"""
\begin{{tabular}}[t]{{|c|{header_cfg}|}}
\hline
\bfseries {relation} & {header} \\
\hline
{rows}
\hline
\end{{tabular}}
"""
TEMPLATE_LATEX_TIKZTABLETOP = r"""
\begin{{figure}}[htb]
\centering
\begin{{subfigure}}{{\textwidth}}
\centering
{table}
\caption{{{tablecaption}}}
\label{{sfig:{tablelabel}}}
\end{{subfigure}}
\begin{{subfigure}}{{\textwidth}}
\centering
{tikzpicture}
\caption{{{graphcaption}}}
\label{{sfig:{graphlabel}}}
\end{{subfigure}}
\caption{{{caption}}}
\label{{fig:{label}}}
\end{{figure}}
"""
RELATION_TYPE_INTERVAL = 0
RELATION_TYPE_POINT = 1
class Relation:
def __init__(self):
self.schema = []
self.values = []
self.tsid = -1
self.teid = -1
self.ypos = -1
self.tsname = ""
self.tename = ""
self.yposname = ""
self.name = ""
self.relType = RELATION_TYPE_INTERVAL
self._ymax = -1
self._ymin = -1
self._offset = 0
def __findSchemaIds__(self):
for i, a in enumerate(self.schema):
if a == self.tsname:
self.tsid = i
elif a == self.tename:
self.teid = i
elif a == self.yposname:
self.ypos = i
def __findYRange__(self):
if self.ypos == -1:
self._ymin = 0
self._ymax = len(self.values) - 1
return
self._ymin = 1000000
self._ymax = 0
for tup in self.values:
self._ymin = min(self._ymin, int(tup[self.ypos]))
self._ymax = max(self._ymax, int(tup[self.ypos]))
def getYMin(self):
if self._ymin == -1:
self.__findYRange__()
return self._ymin
def getYMax(self):
if self._ymax == -1:
self.__findYRange__()
return self._ymax
def setSchema(self, schema):
self.schema = schema
self.__findSchemaIds__()
def addTuple(self, tup):
if len(tup) == len(self.schema):
self.values.append(tup)
else:
raise_error("Too many tuple columns for the actual schema: " + ", ".join(self.schema))
def getTupleTS(self, tup):
return self.getTupleT(tup)[0]
def getTupleTE(self, tup):
return self.getTupleT(tup)[1]
def getTupleYPOS(self, tup):
return float(tup[self.ypos])