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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from future.utils import raise_from, string_types
from builtins import (bytes, str, open, super, range,
                      zip, round, input, int, pow, object)

import io
import re
import traceback
from itertools import chain

import gslab_make.private.messages as messages
from gslab_make.private.exceptionclasses import CritError, ColoredError
from gslab_make.private.utility import convert_to_list, norm_path, format_message


def _parse_tag(tag):
    """.. Parse tag from input."""

    if not re.match('<Tab:(.*)>\n', tag, flags = re.IGNORECASE):
        raise Exception
    else:
        tag = re.sub('<Tab:(.*?)>\n', r'\g<1>', tag, flags = re.IGNORECASE)
        tag = tag.lower()
        
    return(tag)
    
    
def _parse_data(data, null):
    """.. Parse data from input.
    
    Parameters
    ----------
    data : list
        Input data to parse.
    null : str
        String to replace null characters.

    Returns
    -------
    data : list
        List of data values from input.
    """
    null_strings = ['', '.', 'NA']
     
    data = [row.rstrip('\r\n') for row in data]
    data = [row for row in data if row]
    data = [row.split('\t') for row in data]
    data = chain(*data)
    data = list(data)
    data = [null if value in null_strings else value for value in data]
        
    return(data)
        
    
def _parse_content(file, null):
    """.. Parse content from input."""
        
    with io.open(file, 'r', encoding = 'utf-8') as f:
        content = f.readlines()
    try:
        tag = _parse_tag(content[0])
    except:
        raise_from(CritError(messages.crit_error_no_tag % file), None)   
    data = _parse_data(content[1:], null)
    
    return(tag, data)
    
    
def _insert_value(line, value, type, null):
    """.. Insert value into line.
    
    Parameters
    ----------
    line : str
        Line of document to insert value.
    value : str
        Value to insert.
    type : str
        Formatting for value.

    Returns
    -------
    line : str
        Line of document with inserted value.
    """
    
    if (type == 'no change'):
        line = re.sub('\\\\?#\\\\?#\\\\?#', value, line)
                          
    elif (type == 'round'):
        if value == null:
            line = re.sub('(.*?)\\\\?#[0-9]+\\\\?#', r'\g<1>' + value, line)
        else:
            try:
                value = float(value)
            except:
                raise_from(CritError(messages.crit_error_not_float % value), None)
            digits = re.findall('\\\\?#([0-9]+)\\\\?#', line)[0]
            rounded_value = format(value, '.%sf' % digits)
            line = re.sub('(.*?)\\\\?#[0-9]+\\\\?#', r'\g<1>' + rounded_value, line)
                      
    elif (type == 'comma + round'):
        if value == null:
            line = re.sub('(.*?)\\\\?#[0-9]+,\\\\?#', r'\g<1>' + value, line)
        else:
            try:
                value = float(value)
            except:
                raise_from(CritError(messages.crit_error_not_float % value), None)
            digits = re.findall('\\\\?#([0-9]+),\\\\?#', line)[0]
            rounded_value = format(value, ',.%sf' % digits)
            line = re.sub('(.*?)\\\\?#[0-9]+,\\\\?#', r'\g<1>' + rounded_value, line)

    return(line)


def _insert_tables_lyx(template, tables, null):
    """.. Fill tables for LyX template.
    
    Parameters
    ----------
    template : str
        Path of LyX template to fill.
    tables : dict
        Dictionary ``{tag: values}`` of tables.

    Returns
    -------
    template : str
        Filled LyX template.
    """

    with io.open(template, 'r', encoding = 'utf-8') as f:
        doc = f.readlines()
      
    is_table = False

    for i in range(len(doc)):
        # Check if table
        if not is_table and re.match('name "tab:', doc[i]):
            tag = doc[i].replace('name "tab:','').rstrip('"\n').lower()      
            try:
                values = tables[tag]
                entry_count = 0
                is_table = True
            except KeyError:
                raise_from(CritError(messages.crit_error_no_input_table % tag), None)

        # Fill in values if table
        if is_table:
            try:
                if re.match('.*###', doc[i]):
                    doc[i] = _insert_value(doc[i], values[entry_count], 'no change', null)
                    entry_count += 1
                elif re.match('.*#[0-9]+#', doc[i]):
                    doc[i] = _insert_value(doc[i], values[entry_count], 'round', null)
                    entry_count += 1
                elif re.match('.*#[0-9]+,#', doc[i]):
                    doc[i] = _insert_value(doc[i], values[entry_count], 'comma + round', null)
                    entry_count += 1
                elif re.match('</lyxtabular>', doc[i]):
                    is_table = False
                    if entry_count != len(values):
                        raise_from(CritError(messages.crit_error_too_many_values % tag), None)
            except IndexError:
                raise_from(CritError(messages.crit_error_not_enough_values % tag), None)
                
    doc = '\n'.join(doc)
    
    return(doc)


def _insert_tables_latex(template, tables, null):
    """.. Fill tables for LaTeX template.
    
    Parameters
    ----------
    template : str
        Path of LaTeX template to fill.
    tables : dict
        Dictionary ``{tag: values}`` of tables.

    Returns
    -------
    template : str
        Filled LaTeX template.
    """

    with io.open(template, 'r', encoding = 'utf-8') as f:
        doc = f.readlines()

    is_table = False

    for i in range(len(doc)):
        # Check if table
        if not is_table and re.search('label\{tab:', doc[i]):
            tag = doc[i].split(':')[1].rstrip('}\n').strip('"').lower()
            try:
                values = tables[tag]
                entry_count = 0
                is_table = True
            except KeyError:
                raise_from(CritError(messages.crit_error_no_input_table % tag), None)

        # Fill in values if table
        if is_table:
            try:
                line = doc[i].split("&")
    
                for j in range(len(line)):
                    if re.search('.*\\\\#\\\\#\\\\#', line[j]):
                        line[j] = _insert_value(line[j], values[entry_count], 'no change', null)
                        entry_count += 1
                    elif re.search('.*\\\\#[0-9]+\\\\#', line[j]):
                        line[j] = _insert_value(line[j], values[entry_count], 'round', null)                  
                        entry_count += 1
                    elif re.search('.*\\\\#[0-9]+,\\\\#', line[j]):
                        line[j] = _insert_value(line[j], values[entry_count], 'comma + round', null)
                        entry_count += 1
                   
                doc[i] = "&".join(line)
    
                if re.search('end\{tabular\}', doc[i], flags = re.IGNORECASE):
                    is_table = False
                    if entry_count != len(values):
                        raise_from(CritError(messages.crit_error_too_many_values % tag), None)
            except IndexError:
                raise_from(CritError(messages.crit_error_not_enough_values % tag), None)

    doc = '\n'.join(doc)

    return(doc)


def _insert_tables(template, tables, null):
    """.. Fill tables for template.
    
    Parameters
    ----------
    template : str
        Path of template to fill.
    tables : dict
        Dictionary ``{tag: values}`` of tables.

    Returns
    -------
    template : str
        Filled template.
    """
    
    template = norm_path(template)

    if re.search('\.lyx', template):
        doc = _insert_tables_lyx(template, tables, null)
    elif re.search('\.tex', template):
        doc = _insert_tables_latex(template, tables, null)

    return(doc)


def tablefill(inputs, template, output, null = '.'):
    """.. Fill tables for template using inputs.
    
    Fills tables in document ``template`` using files in list ``inputs``. 
    Writes filled document to file ``output``. 
    Null characters in ``inputs`` are replaced with value ``null``.

    Parameters
    ----------
    inputs : list
        Input or list of inputs to fill into template.
    template : str
        Path of template to fill.
    output : str
        Path of output.
    null : str
        Value to replace null characters (i.e., ``''``, ``'.'``, ``'NA'``). Defaults to ``'.'``.

    Returns
    -------
    None
    
    Example
    -------

    .. code-block::

        #################################################################
        #  tablefill_readme.txt - Help/Documentation for tablefill.py
        #################################################################

        Description:
        tablefill.py is a Python module designed to fill LyX/Tex tables with output 
        from text files (usually output from Stata or Matlab).

        Usage:
        Tablefill takes as input a LyX (or Tex) file containing empty tables (the template 
        file) and text files containing data to be copied to  these tables (the 
        input  files), and produces a LyX (or Tex) file with filled tables (the output file). 
        For brevity, LyX will be used to denote LyX or Tex files throughout.

        Tablefill must first be imported to make.py.  This is typically achieved 
        by including the following lines:

        ```
        from gslab_fill.tablefill import tablefill
        ```

        Once the module has been imported, the syntax used to call tablefill is 
        as follows:

        ```
        tablefill(input = 'input_file(s)', template = 'template_file', 
                  output = 'output_file')
        ```

        The argument 'template' is the user written LyX file which contains the 
        tables to be filled in. The argument 'input' is a list of the text files 
        containing the output to be copied to the LyX tables. If there are multiple 
        input text files, they are listed as: input = 'input_file_1 input_file_2'. 
        The argument 'output' is the name of the filled LyX file to be produced.  
        Note that this file is created by tablefill.py and should not be edited 
        manually by the user.

        ###########################
        Input File Format:
        ###########################

        The data needs to be tab-delimited rows of numbers (or characters), 
        preceeded by  `<label>`.  The < and > are mandatory. The numbers can be 
        arbitrarily long, can be negative, and can also be in scientific notation.

        Examples:
        ----------

        ```
        <tab:Test>
        1   2   3
        2   3   1
        3   1   2
        ```

        ```
        <tab:FunnyMat>
        1   2   3   23  2
        2   3
        3   1   2   2
        1
        ```
        (The rows do not need to be of equal length.)

        Completely blank (no tab) lines are ignored.
        If a "cell" is merely "." or "[space]", then it is treated as completely 
        missing. That is, in the program:

        ```
        <tab:Test>
        1   2   3
        2   .   1   3
        3       1   2
        ```

        is equivalent to:
        ```
        <tab:Test>
        1   2   3
        2   1   3
        3   1   2
        ```

        This feature is useful as Stata outputs missing values in numerical 
        variables as ".", and missing values in string variables as "[space]".

        ................................
         Scientific Notation Notes:
        ................................
        The scientific notation ihas to be of the form:
        [numbers].[numbers]e(+/-)[numbers]

        Examples:
        ```
        23.2389e+23
        -2.23e-2
        -0.922e+3
        ```

        ###########################
        Template LyX Format:
        ###########################

        The LyX template file determines where the numbers from the input files are placed.

        Every table in the template file (if it is to be filled) must appear within a float. 
        There must  be one, and only one, table object inside the float, and the table name 
        must include a label  object that corresponds to the label of the required table in 
        the input file.

        Note that table names cannot be duplicated.  For a single template file, each table 
        to be filled must have a unique label, and there must be one, and only one, table with 
        that same label in the text files used as input. Having multiple tables with the
        same name in the input files or in the template file will cause errors.  

        Note also that labels are NOT case-sensitive. That is, <TAB:Table1> is considered
         the same as `<tab:table1>`.

        In the LyX tables, "cells" to be filled with entries from the input text files are 
        indicated by the following tags: 

        `"###"  (no quotes)`
        or 
        `"#[number][,]#"  (no quotes)`

        The first case will result in a literal substitution.  I.e. whatever is in the text 
        tables for that  cell will be copied over. The second case will convert the data 
        table's number (if in scientific notation) and will truncate this converted number 
        to [number] decimal places.  It will automatically round while doing so.

        If a comma appears after the number (within #[number]#), then it will add commas 
        to the digits to the left of the decimal place.

        Examples:
        ---------
        ```
        2309.2093 + ### = 2309.2093
        2309.2093 + #4# = 2309.2093
        2309.2093 + #5# = 2309.20930
        2309.2093 + #20# = 2309.20930000000000000000
        2309.2093 + #3# = 2309.209
        2309.2093 + #2# = 2309.21
        2309.2093 + #0# = 2309
        2309.2093 + #0,# = 2,309
        ```

        ```
        -2.23e-2  + #2# = -0.0223 + #2# = -0.02
        -2.23e-2  + #7# = -0.0223 + #7# = -0.0223000
        -2.23e+10  + #7,# = -22300000000 + #7,# = -22,300,000,000.000000
        ```

        Furthermore, only ###/#num# will be replaced, allowing you to put things around 
        ###/#num# to alter the final output:

        Examples:
        --------

        ```
        2309.2093 + (#2#) = (2309.21)
        2309.2093 + #2#** = 2309.21**
        2309.2093 + ab#2#cd = ab2309.21cd
        ```

        If you are doing exact substitution, then you can use characters:

        Examples:
        ---------
        `abc + ### = abc`

        ................................
         Intentionally blank cells:
        ................................

        If you would like to display a blank cell, you can use "---":

        Examples:
        ---------
        ```
        --- + ### = ---
        --- + #3# = ---
        ```

        ######################
        # Example Combinations 
        #   Of input + template
        ######################


        Example 1 (Simple)
        ----------
        ```
        Input: <tab:Test>
        1   2   3
        2   1   3
        3   1   2

        Template: `<tab:Test> ` (pretend this is what you see in LyX)

        ### ### ###
        ### ### ###
        ### ### ###

        Result:<tab:Test>
        1   2   3
        2   1   3
        3   1   2
        ```

        Example 2 (More Complicated)
        ----------
        ```
        Input: <tab:Test>
        1   .   3
        2e-5    1   3.023
        .   -1  2   3

        Template: <tab:Test>  (pretend this is what you see in LyX)
        (###)   2   ###
        #3# ### #1#
        NA  ### ### ###

        Result:<tab:Test>
        (1) 2   3
        0.000   1   3.0
        NA  -1  2   3
        ```

        ===================
        ====Important======
        ===================
        By design, missings in input table and "missings" in template do not have to 
        line up.

        Example 3 (LyX)
        ----------
        ```
        Input: <tab:Test>
        1   .   3
        2e-5    .   3.023
        .   -1  2

        Template: <tab:Test> 
        ### ### abc
        abc #2# #3#
        NA  ### ###

        Result:<tab:Test>
        1   3   abc
        abc 0.00    3.023
        NA  -1  2

        Recall that to the program, the above input table is no different from:
        1   3
        2e-5    3.023
        -1  2
        ```

        It doesn't "know" where the numbers should be placed within a row, only what 
        the next number to place should be.

        Similarly:

        Example 4 (LyX)
        ----------
        ```
        Input: <tab:Test>
        1   1   2
        1   1   3
        2   -1  2

        Template: <tab:Test>  
        ### ### ###
        abc abc abc
        ### #2# #3#
        ### ### ###

        Result:<tab:Test>
        1   1   2
        abc abc abc
        1   1.00    3.000
        2   -1  2
        ```

        If a row in the template has no substitutions, then it's not really a row from 
        the program's point of view.


        ######################
        # Error Logging
        ######################

        If an error occurs during the call to tablefill, it will be displayed in the 
        command window.  When make.py finishes, the user will be able to scroll up 
        through the output and examine any  error messages.  Error messages, which 
        include a description of the error type and a traceback to the line of code 
        where the error occured, can also be retuned as a string object using the 
        following syntax:

        exitmessage = tablefill( input = 'input_file(s)', template = 'template_file', 
                                 output = 'output_file' )

        Lines can then be added to make.py to output this string to a log file using 
        standard Python and built in gslab_make commands.


        ######################
        # Common Errors
        ######################

        Common mistakes which can lead to errors include:

        - Mismatch between the length of the LyX table and the corresponding text table.  
        If the LyX table has more entries to be filled than the text table has entries to
        fill from, this will cause an error and the table will not be filled.

        - Use of numerical tags (e.g. #1#) to fill non-numerical data.  This will cause 
        an error. Non-numerical data can only be filled using "###", as it does not make 
        sense to round or truncate this data.

        - Multiple table objects in the same float.  Each table float in the template LyX 
        file can only contain one table object.  If a float contains a second table object, 
        this table will not be filled.


        ######################
        # Boldfacing entries
        ######################

        It is straightforward to develop functions that conditionally write entries of 
        tables in boldface; functions may do so by inserting '\series bold' in the lines
        of the filled LyX file immeadiately before phrases that the user wishes to make bold.
    """

    try:
        inputs = convert_to_list(inputs, 'file')
        inputs = [norm_path(file) for file in inputs]
        content = [_parse_content(file, null) for file in inputs]
        tables = {tag:data for (tag, data) in content}
        if (len(content) != len(tables)):
            raise_from(CritError(messages.crit_error_duplicate_tables), None)

        doc = _insert_tables(template, tables, null)  

        with io.open(output, 'w', encoding = 'utf-8') as f:
            f.write(doc)
    except:
        error_message = 'Error with `tablefill`. Traceback can be found below.' 
        error_message = format_message(error_message) 
        raise_from(ColoredError(error_message, traceback.format_exc()), None)


__all__ = ['tablefill']