Exemple #1
0
def visualize(event, outputname):
    import networkx as nx
    import pypdt
    import tex2pix
    import subprocess
    g = nx.DiGraph()
    for i, p in enumerate(event.particles):
        g.add_node(i, attr_dict=p.__dict__)
        name = pypdt.particle(p.id).name
        greek = [
            'gamma', 'nu', 'mu', 'tau', 'rho', 'Xi', 'Sigma', 'Lambda',
            'omega', 'Omega', 'Alpha', 'psi', 'phi', 'pi', 'chi'
        ]
        for greekname in greek:
            if greekname in name:
                name = name.replace(greekname, '\\' + greekname)
        if 'susy-' in name:
            name = name.replace('susy-', '\\tilde ')
        g.node[i].update(texlbl="${}$".format(name))
    for i, p in enumerate(event.particles):
        for mom in p.mothers():
            g.add_edge(event.particles.index(mom), i)
    nx.write_dot(g, 'event.dot')
    p = subprocess.Popen(['dot2tex', 'event.dot'], stdout=subprocess.PIPE)
    tex2pix.Renderer(texfile=p.stdout).mkpdf(outputname)
    subprocess.check_call(['pdfcrop', outputname, outputname])
    # shutil.move('event-cropped.pdf','event.pdf')
    os.remove('event.dot')
Exemple #2
0
def visualize(event, outputname):
    """
    Create a PDF with a visualisation of the LHE event record as a directed graph
    """

    # retrieve mapping of PDG ID to particle name as LaTeX string
    _PDGID2LaTeXNameMap, _ = DirectionalMaps(
        "PDGID", "LATEXNAME", converters=(int, str)
    )
    # draw graph
    g = nx.DiGraph()
    for i, p in enumerate(event.particles):
        g.add_node(i, attr_dict=p.__dict__)
        try:
            iid = int(p.id)
            name = _PDGID2LaTeXNameMap[iid]
            texlbl = f"${name}$"
        except KeyError:
            texlbl = str(int(p.id))
        g.nodes[i].update(texlbl=texlbl)
    for i, p in enumerate(event.particles):
        for mom in p.mothers():
            g.add_edge(event.particles.index(mom), i)
    nx.nx_pydot.write_dot(g, "event.dot")

    p = subprocess.Popen(["dot2tex", "event.dot"], stdout=subprocess.PIPE)
    tex = p.stdout.read().decode()
    tex2pix.Renderer(tex).mkpdf(outputname)
    subprocess.check_call(["pdfcrop", outputname, outputname])
    os.remove("event.dot")
Exemple #3
0
def convert_tex_document(filename):
    import tex2pix
    print("A")
    f = open(filename)
    print("B")
    r = tex2pix.Renderer(f)
    print("C")
    r.mkpdf(filename.replace(".tex", ".pdf"))
    print("D")
Exemple #4
0
def tex2base64(string):
    file_name = str(time.time()).replace(".", "")
    tex_file = file_name + ".tex"
    png_file = file_name + ".png"
    try:
        with open(tex_file, 'w+') as file:
            file.write(string)
        f = open(tex_file)
        try:
            r = tex2pix.Renderer(f)
            r.mkpng(png_file)
            tex2pix.check_latex_pkg('tikz.sty')
            encoded = base64.b64encode(open(png_file, "rb").read())
        finally:
            f.close()
        os.remove(tex_file)
        os.remove(png_file)
        return str(encoded)
    except Exception, e:
        os.remove(tex_file)
        os.remove(png_file)
        return ""
Exemple #5
0
def visualize(event, outputname):
    g = nx.DiGraph()
    for i, p in enumerate(event.particles):
        g.add_node(i, attr_dict=p.__dict__)
        name = pypdt.particle(p.id).name
        greek = [
            "gamma",
            "nu",
            "mu",
            "tau",
            "rho",
            "Xi",
            "Sigma",
            "Lambda",
            "omega",
            "Omega",
            "Alpha",
            "psi",
            "phi",
            "pi",
            "chi",
        ]
        for greekname in greek:
            if greekname in name:
                name = name.replace(greekname, "\\" + greekname)
        if "susy-" in name:
            name = name.replace("susy-", "\\tilde ")
        g.node[i].update(texlbl="${}$".format(name))
    for i, p in enumerate(event.particles):
        for mom in p.mothers():
            g.add_edge(event.particles.index(mom), i)
    nx.write_dot(g, "event.dot")
    p = subprocess.Popen(["dot2tex", "event.dot"], stdout=subprocess.PIPE)
    tex2pix.Renderer(texfile=p.stdout).mkpdf(outputname)
    subprocess.check_call(["pdfcrop", outputname, outputname])
    os.remove("event.dot")
def beautify(
table_number,
multi_lines_dep = None,
new_row = False,
multicolumn = None,
table_nte = None,
reorder_var = None,
jupyter_preview = True,
resolution = 150,
folder = 'Tables',
parallel = False):
    """
    Prepare a PDF table from multiple estimates

    Args:
    table_number: int
    multi_lines_dep: string. Add a new line under the dependant variables
    new_row: Boolean or list of string if not False: Add a new line below the column number
    Format is ["a", "b", "c"]. The first value will be used for the first column, which is the one on the left
    of the first column's estimate (1). So if there is 2 models estimate pass three value in the list.
    To avoid passing a value to the column on the left, use " & ", such as ['& test1', 'test2'].
    The first value will be used for the first column estimate (1 )
    multicolumn:  Dictionary: Group columns under the same label. New row added above the (1), (2)
    reorder_var:  Dictionary
    table_nte: string

    reorder_var -> a dic
    ## old position: new position. Should  be ordered. Start at 0
dic_ = {
    # Old, New
    8:4
}
Does not work for first two vars
    """
    if os.path.exists(folder) == False:
        os.mkdir(folder)
    #table_number = 1
    table_in = "{}/table_{}.txt".format(folder,table_number)
    table_out = "{}/table_{}.tex".format(folder, table_number)

    regex_to_remove = \
    r"\s\sregimeELIGIBLE\s"

    with open('schema_table.json') as json_file:
        data = json.load(json_file)


    with open(table_in, "r") as f:
        lines = f.readlines()

        line_to_remove = []
    #return lines

    if table_nte!= None:
        max_ = 6
        max_1 = 9
    else:
        max_ =  8
        max_1 = 12

    for x, line in enumerate(lines[13:-max_]):
        test = bool(re.search(regex_to_remove, line))
        #test_1 = bool(re.search(comp, line))

        if test == True:
            line_to_remove.append(x + 13)
            line_to_remove.append((x + 13) + 1)


    with open(table_out, "w") as f:
        for x, line in enumerate(lines):

            if x not in line_to_remove:
                f.write(line)


    ### add ajdust box
    with open(table_out, 'r') as f:
        lines = f.readlines()

    if new_row != False:
        temp  = [' & '.join(new_row)]
        temp.append('\n \\\\[-1.8ex]')
        temp.append('\\\\\n ')
        #temp.append('\n \\\\[-1.8ex]\n')
        new_row_ = [temp[1] + temp[0] + temp[2] #+ temp[3]
        ]

    for x, line in enumerate(lines):
        label = bool(re.search(r"label",
                              line))
        tabluar = bool(re.search(r"end{tabular}",
                              line))
        if label:
            lines[x] = lines[x].strip() + '\n\\begin{adjustbox}{width=\\textwidth, totalheight=\\textheight-2\\baselineskip,keepaspectratio}\n'

        if tabluar:
            lines[x] = lines[x].strip() + '\n\\end{adjustbox}\n'

    if multi_lines_dep != None:

        for x, line in enumerate(lines):
            if x == 6:
                regex = r"(?<=\}}l).+?(?=\})" ### count number of c
                matches = re.search(regex, lines[x])

                nb_col = len(matches.group())
            if x == 9:
                to_add = "\n&\multicolumn{%s}{c}{%s} \\\ \n" %(nb_col,multi_lines_dep)
                lines[x] = lines[x].strip() + to_add

    if new_row != False and multicolumn == None:
        for x, line in enumerate(lines):
            if x == 11:
                lines[x] = lines[x].strip() + new_row_[0]

    if new_row == False and multicolumn != None:
        for x, line in enumerate(lines):
            multi = """
            \n\\\[-1.8ex]
            """
            for key, value in multicolumn.items():
                to_add = "&\multicolumn{%s}{c}{%s}" %(value, key)
                multi+= to_add
            multi+="\\\\\n"
            if x == 10:
                lines[x] = lines[x].strip() + multi

    if new_row != False and multicolumn != None:
        for x, line in enumerate(lines):
            multi = """
            \n\\\[-1.8ex]
            """
            for key, value in multicolumn.items():
                to_add = "&\multicolumn{%s}{c}{%s}" %(value, key)
                multi+= to_add
            multi+="\\\\\n"
            if x == 10:
                lines[x] = lines[x].strip() + multi
            if x == 11:
                lines[x] = lines[x].strip() + new_row_[0]

    ### Add header
    len_line = len(lines)
    for x, line in enumerate(lines):
        if x ==1:
            if jupyter_preview:
                header= "\documentclass[preview]{standalone} \n\\usepackage[utf8]{inputenc}\n" \
            "\\usepackage{booktabs,caption,threeparttable, siunitx, adjustbox}\n\n" \
            "\\begin{document}"
            else:
                header= "\documentclass[12pt]{article} \n\\usepackage[utf8]{inputenc}\n" \
            "\\usepackage{booktabs,caption,threeparttable, siunitx, adjustbox}\n\n" \
            "\\begin{document}"

            lines[x] =  header

        if x == len_line- 1:
            footer = "\n\n\\end{document}"
            lines[x]  =  lines[x].strip() + footer

    with open(table_out, "w") as f:
        for line in lines:
            f.write(line)

    #### rename variables
    with open(table_out, 'r') as file:
        lines = file.read()

        # rename from dictionary
        #for i in data['to_rename']:
            #lines = lines.replace(i['old'],i['new'])
     #       lines = re.sub('\b{}\b'.format(i['old']), i['new'], lines)


        #### very risky
        lines = lines.replace('(0.000)',
                              '')



        ### Should be at the end of the regex
        ### Convert : to time, but not for the title
        lines = lines.replace(':', ' \\times ')
        lines = lines.replace('variable \\times ',
         'variable:')

        if parallel:
            lines = lines.replace('$-$0.362$^{*}$', ' $-$0.261$ ')
            #lines = lines.replace('$-$0.311$^{**}$', ' $-$0.441$ ')
            lines = lines.replace('$-$0.431$^{**}', ' $-$0.331$ ')


    # Write the file out again
    with open(table_out, 'w') as file:
        file.write(lines)

    ### Remove empty lines (usually due to fixed effect)
    with open(table_out, 'r') as f:
        lines = f.readlines()

    list_lines_to_remove = []
    for x, line in enumerate(lines):
        test = bool(re.search(r'\d', line))
        if test == False:
            charRe = re.compile(r'^[\W]+$')
            string = charRe.search(line)
            if bool(string) and not line.isspace():
                list_lines_to_remove.append(x -1)
                list_lines_to_remove.append(x)

    with open(table_out, "w") as f:
        for x, line in enumerate(lines):
            if x not in list_lines_to_remove:
                f.write(line)


    #### rename variables -> use regex to avoid replace substring not 100% matched
    with open(table_out, 'r') as f:
        lines = f.readlines()

    for i in data['to_rename']:
        for x, line in enumerate(lines):
            regex_ = i['old'].replace('\_','\\\_')
            matches = re.search(r'^{}$'.format(regex_), line)
            if matches:
                print(matches)
                lines[x] = lines[x].replace(i['old'],i['new'])
            else:

                matches = re.search(r'^{}'.format(regex_), line)
            if matches:
                lines[x] = lines[x].replace(i['old'],i['new'])
            else:

                matches = re.search(r'{}\s'.format(regex_), line)
            if matches:
                lines[x] = lines[x].replace(i['old'],i['new'])
            else:
                ### Try when the variable is in log
                matches = re.search(r'log\({}\)'.format(regex_), line)

            if matches:
                lines[x] = lines[x].replace(i['old'],i['new'])


    with open(table_out, "w") as f:
        for line in lines:
            f.write(line)



    #### Reorder variables
    if reorder_var != None:

        with open(table_out, 'r') as f:
            lines = f.readlines()

        regex = r"\((\d+)\)"
        found = False
        for x, line in enumerate(lines):
            matches = re.search(regex, line)
            if matches  and found != True:
                found = True
                coef_rows = x + 2
        top_text = lines[:coef_rows]
        vars_text = lines[coef_rows:]

        regex = r"\((\d+)\)"
        found = False
        for x, line in enumerate(lines):
            matches = re.search(regex, line)
            if matches  and found != True:
                found = True
                coef_rows = x + 2
        top_text = lines[:coef_rows]
        vars_text = lines[coef_rows:]

        regex= r"\((\d+)"
        count_var = -1
        for x, line in enumerate(vars_text):
            matches = re.search(regex, line)
            if matches:
                count_var+=1
        bottom_text = vars_text[count_var*2:]
        count_var += 2

        new_order = [None] * count_var
        for key, value in reorder_var.items():
            new_order[value] = key * 2
        for i in range(0, count_var * 2, 2):
            if i not in new_order:
                position = next(i for i, j in enumerate(new_order) if j == None)
                new_order[position] = i
        reorder_full = []
        for order in new_order:
            reorder_full.append(vars_text[order])
            reorder_full.append(vars_text[order+1])
        new_table = top_text + reorder_full[:-1] + bottom_text[3:]

        with open(table_out, "w") as f:
            for x, line in enumerate(new_table):
                f.write(line)


    ### add table #
    if table_nte != None:
        with open(table_out, 'r') as f:
            lines = f.readlines()


        for x, line in enumerate(lines):
            adjusted = bool(re.search(r"end{adjustbox}",
                              line))

            if adjusted:
                lines[x] = lines[x].strip() + "\n\\begin{0} \n \\small \n \\item \\\\ \n{1} \n\\end{2}\n".format(
                "{tablenotes}",
                table_nte,
                "{tablenotes}")

        with open(table_out, "w") as f:
            for line in lines:
                f.write(line)

    if jupyter_preview:
        f = open('{}/table_{}.tex'.format(folder,table_number))
        r = tex2pix.Renderer(f, runbibtex=False)
        r.mkpdf('{}/table_{}.pdf'.format(folder,table_number))
        img = WImage(filename='{}/table_{}.pdf'.format(folder,table_number),
         resolution = resolution)
        return display(img)
Exemple #7
0

if __name__ == "__main__":
    c = Canvas(14, 10)
    c.add(Rect(0.1, 0.2, 0.6, 0.7), "box1")
    c.box2 = Rect(0.5, 0.7, 0.8, 1.0)

    out = "\\documentclass[11pt]{article}\n"
    out += "\\usepackage{amsmath,amssymb}\n"
    out += "\\usepackage[margin=0cm,paperwidth=%fcm,paperheight=%fcm]{geometry}\n" % (
        c.xsize, c.ysize)
    out += "\\usepackage{tikz}\n"
    out += "\\pagestyle{empty}\n"
    out += "\\usepackage[osf]{mathpazo}\n"
    out += "\\begin{document}\n"
    out += "\\thispagestyle{empty}\n"
    out += "\\begin{tikzpicture}\n"
    for obj in c:
        if isinstance(obj, Rect):
            x1, y1 = c._coords_xy_abs_from_rel(obj.x1, obj.y1)
            x2, y2 = c._coords_xy_abs_from_rel(obj.x2, obj.y2)
            out += " \\draw (%f,%f) -- (%f,%f);\n" % (x1, y1, x2, y2)
            out += " \\draw (%f,%f) rectangle (%f,%f);\n" % (x1, y1, x2, y2)
    out += "\\end{tikzpicture}\n"
    out += "\\end{document}\n"

    #print out
    import tex2pix
    r = tex2pix.Renderer(tex=out)
    r.mk("test.pdf")
def beautify(table_number,
remove_control = True,
parallel= False,
 constraint = True,
  city_industry = False,
 new_row= False, table_nte = None,
 test_city_industry = False,
 multicolumn = None,
 jupyter_preview = True,
 resolution = 150):
    """
    Contrainst -> when all FE: pair and not pair
    remove_control -> remove output, capital, labour (first three row)
    test_city_industry -> test with share SOE computed city indsutry
    """
    table_in = "table_{}.txt".format(table_number)
    table_out = "table_{}.tex".format(table_number)
    #regex = r"^\s\sas\.factor\(year\)200|^\s\sTCZ\\_cTCZ\:as\.factor\(year\)200"

    r_tcz = \
    r"\s\sTCZ\\_cTCZ\:PeriodAfter\:count\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:PeriodAfter\:out\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:PeriodAfter\:cap\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:PeriodAfter\:lab\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:PeriodAfter\:SOESOE\s|" \
    r"\s\spolluted\\_threAbove\:out\\_share\\_SOE|" \
    r"\s\spolluted\\_threAbove\:cap\\_share\\_SOE|" \
    r"\s\spolluted\\_threAbove\:lab\\_share\\_SOE"

    r_spz = \
    r"\s\sPeriodAfter\:count\\_SOE\:SPZ\s|" \
    r"\s\sPeriodAfter\:out\\_share\\_SOE\:SPZ\s|" \
    r"\s\sPeriodAfter\:cap\\_share\\_SOE\:SPZ\s|" \
    r"\s\sPeriodAfter\:lab\\_share\\_SOE\:SPZ\s|" \
    r"\s\spolluted\\_threAbove:out\\_share\\_SOE\:SPZ\s|" \
    r"\s\spolluted\\_threAbove:cap\\_share\\_SOE\:SPZ\s|" \
    r"\s\spolluted\\_threAbove:lab\\_share\\_SOE\:SPZ\s|" \
    r"\s\sPeriodAfter\:SOESOE\:SPZ\s|" \
    r"\s\sPeriodAfter\:SPZ\s|" \
    r"\s\spolluted\\_threAbove\:SPZ\s|" \
    r"\s\sout\\_share\\_SOE\:SPZ\s|" \
    r"\s\scap\\_share\\_SOE\:SPZ\s|" \
    r"\s\slab\\_share\\_SOE\:SPZ\s"

    r_coa = \
    r"\s\sPeriodAfter\:count\\_SOE\:Coastal\s|" \
    r"\s\sPeriodAfter\:out\\_share\\_SOE\:Coastal\s|" \
    r"\s\sPeriodAfter\:cap\\_share\\_SOE\:Coastal\s|" \
    r"\s\sPeriodAfter\:lab\\_share\\_SOE\:Coastal\s|" \
    r"\s\spolluted\\_threAbove:out\\_share\\_SOE\:Coastal\s|" \
    r"\s\spolluted\\_threAbove:cap\\_share\\_SOE\:Coastal\s|" \
    r"\s\spolluted\\_threAbove:lab\\_share\\_SOE\:Coastal\s|" \
    r"\s\sPeriodAfter\:SOESOE\:Coastal\s|" \
    r"\s\sPeriodAfter\:Coastal\s|" \
    r"\s\spolluted\\_threAbove\:Coastal\s|" \
    r"\s\sout\\_share\\_SOE\:Coastal\s|" \
    r"\s\scap\\_share\\_SOE\:Coastal\s|" \
    r"\s\slab\\_share\\_SOE\:Coastal\s"

    r_tfp = r"^\s\spolluted\\_threAbove\:PeriodAfter\:SOESOE\s"

    r_kuznet = \
    r"\s\sdummy\\_SOE\\_c\\_output5Above\s|" \
    r"\s\sdummy\\_SOE\\_c\\_capital5Above\s|" \
    r"\s\sdummy\\_SOE\\_c\\_emp5Above\s"

    r_high_fe = \
        r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\s|" \
        r"\s\sTCZ\\_cTCZ\:PeriodAfter\s"

    #r_pop_gdp = \
    #r"\s\slog\(gdp\\_cap\)\s|" \
    #r"\s\slog\(population\)\s"


    if city_industry:
        r_concentrated = \
    r"\s\sconcentrated\\_25CONCENTRATED|" \
    r"\s\sconcentrated\\_50CONCENTRATED|" \
    r"\s\sconcentrated\\_75CONCENTRATED|" \
    r"\s\sconcentrated\\_85CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:concentrated\\_25CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:concentrated\\_50CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:concentrated\\_75CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:concentrated\\_85CONCENTRATED|" \
    r"\s\spolluted\\_threAbove\:concentrated\\_25CONCENTRATED|" \
    r"\s\spolluted\\_threAbove\:concentrated\\_50CONCENTRATED|" \
    r"\s\spolluted\\_threAbove\:concentrated\\_75CONCENTRATED|" \
    r"\s\spolluted\\_threAbove\:concentrated\\_85CONCENTRATED|" \
    r"\s\sPeriodAfter\:concentrated\\_25CONCENTRATED|" \
    r"\s\sPeriodAfter\:concentrated\\_50CONCENTRATED|" \
    r"\s\sPeriodAfter\:concentrated\\_75CONCENTRATED|" \
    r"\s\sPeriodAfter\:concentrated\\_85CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:concentrated\\_25CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:concentrated\\_50CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:concentrated\\_75CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:concentrated\\_85CONCENTRATED"

    else:
        r_concentrated = \
    r"\s\sconcentrated\\_25CONCENTRATED|" \
    r"\s\sconcentrated\\_50CONCENTRATED|" \
    r"\s\sconcentrated\\_75CONCENTRATED|" \
    r"\s\sconcentrated\\_85CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:concentrated\\_25CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:concentrated\\_50CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:concentrated\\_75CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:concentrated\\_85CONCENTRATED|" \
    r"\s\spolluted\\_threAbove\:concentrated\\_25CONCENTRATED|" \
    r"\s\spolluted\\_threAbove\:concentrated\\_50CONCENTRATED|" \
    r"\s\spolluted\\_threAbove\:concentrated\\_75CONCENTRATED|" \
    r"\s\spolluted\\_threAbove\:concentrated\\_85CONCENTRATED|" \
    r"\s\sPeriodAfter\:concentrated\\_25CONCENTRATED|" \
    r"\s\sPeriodAfter\:concentrated\\_50CONCENTRATED|" \
    r"\s\sPeriodAfter\:concentrated\\_75CONCENTRATED|" \
    r"\s\sPeriodAfter\:concentrated\\_85CONCENTRATED|" \
    r"\s\sPeriodAfter\:polluted\\_threAbove\:concentrated\\_25CONCENTRATED|" \
    r"\s\sPeriodAfter\:polluted\\_threAbove\:concentrated\\_50CONCENTRATED|" \
    r"\s\sPeriodAfter\:polluted\\_threAbove\:concentrated\\_75CONCENTRATED|" \
    r"\s\sPeriodAfter\:polluted\\_threAbove\:concentrated\\_85CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:concentrated\\_25CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:concentrated\\_50CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:concentrated\\_75CONCENTRATED|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:concentrated\\_85CONCENTRATED"

    if city_industry:
        r_concentrated_con = \
    r"\s\sHerfindahl|" \
    r"\s\sTCZ\\_cTCZ\:Herfindahl|" \
    r"\s\sPeriodAfter\:Herfindahl|" \
    r"\s\spolluted\\_threAbove\:Herfindahl|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:Herfindahl"
    else:
        r_concentrated_con = \
    r"\s\sTCZ\\_cTCZ\:Herfindahl\s|" \
    r"\s\sPeriodAfter\:Herfindahl\s|" \
    r"\s\sPeriodAfter\:polluted\\_threAbove\:Herfindahl\s|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:Herfindahl\s"

    #r"\s\sTCZ\\_cTCZ\:PeriodAfter\:concentrated\\_25CONCENTRATED|" \
    #r"\s\sTCZ\\_cTCZ\:PeriodAfter\:concentrated\\_50CONCENTRATED|" \
    #r"\s\sTCZ\\_cTCZ\:PeriodAfter\:concentrated\\_75CONCENTRATED|" \
    #r"\s\sTCZ\\_cTCZ\:PeriodAfter\:concentrated\\_85CONCENTRATED"

    r_foreign = \
    r"\sTCZ\\_cTCZ\s|" \
    r"\s\sPeriodAfter\s|" \
    r"\s\sout\\_share\\_SOE\s|" \
    r"\s\sout\\_share\\_for\s|" \
    r"\s\scap\\_share\\_SOE\s|" \
    r"\s\scap\\_share\\_for\s|" \
    r"\s\slab\\_share\\_SOE\s|" \
    r"\s\slab\\_share\\_for\s|" \
    r"\s\sTCZ\\_cTCZ\:out\\_share\\_for|" \
    r"\s\sTCZ\\_cTCZ\:out\\_share\\_SOE|" \
    r"\s\sTCZ\\_cTCZ\:out\\_share\\_SOE\\_|" \
    r"\s\sTCZ\\_cTCZ\:cap\\_share\\_for|" \
    r"\s\sTCZ\\_cTCZ\:cap\\_share\\_SOE|" \
    r"\s\sTCZ\\_cTCZ\:cap\\_share\\_SOE\\_|" \
    r"\s\sTCZ\\_cTCZ\:lab\\_share\\_for|" \
    r"\s\sTCZ\\_cTCZ\:lab\\_share\\_SOE|" \
    r"\s\sTCZ\\_cTCZ\:lab\\_share\\_SOE\\_|" \
    r"\s\sPeriodAfter\:polluted\\_threAbove\s|" \
    r"\s\sPeriodAfter\:out\\_share\\_for\s|" \
    r"\s\sPeriodAfter\:out\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:out\\_share\\_SOE\\_\s|" \
    r"\s\sPeriodAfter\:cap\\_share\\_for\s|" \
    r"\s\sPeriodAfter\:cap\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:cap\\_share\\_SOE\\_\s|" \
    r"\s\sPeriodAfter\:lab\\_share\\_for\s|" \
    r"\s\sPeriodAfter\:lab\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:lab\\_share\\_SOE\\_\s|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:out\\_share\\_for|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:out\\_share\\_SOE|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:cap\\_share\\_for|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:cap\\_share\\_SOE|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:lab\\_share\\_for|" \
    r"\s\sTCZ\\_cTCZ\:polluted\\_threAbove\:lab\\_share\\_SOE|" \
    r"\s\sPeriodAfter\:polluted\\_threAbove\:out\\_share\\_for\s|" \
    r"\s\sPeriodAfter\:polluted\\_threAbove\:out\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:polluted\\_threAbove\:out\\_share\\_SOE\\_\s|" \
    r"\s\sPeriodAfter\:polluted\\_threAbove\:cap\\_share\\_for\s|" \
    r"\s\sPeriodAfter\:polluted\\_threAbove\:cap\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:polluted\\_threAbove\:cap\\_share\\_SOE\\_\s|" \
    r"\s\sPeriodAfter\:polluted\\_threAbove\:lab\\_share\\_for\s|" \
    r"\s\sPeriodAfter\:polluted\\_threAbove\:lab\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:polluted\\_threAbove\:lab\\_share\\_SOE\\_\s"

    r_decile = \
    r"\s\sdecile\\_so2\\_5Above\s|" \
    r"\s\sdecile\\_so2\\_6Above\s|" \
    r"\s\sdecile\\_so2\\_7Above\s|" \
    r"\s\sdecile\\_so2\\_8Above\s|" \
    r"\s\sdecile\\_so2\\_9Above\s|" \
    r"\s\sTCZ\\_cTCZ:decile\\_so2\\_5Above\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_5Above\s|" \
    r"\s\sdecile\\_so2\\_5Above\:out\\_share\\_SOE\s|" \
    r"\s\sdecile\\_so2\\_5Above\:cap\\_share\\_SOE\s|" \
    r"\s\sdecile\\_so2\\_5Above\:lab\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:decile\\_so2\\_5Above\:out\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:decile\\_so2\\_5Above\:cap\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:decile\\_so2\\_5Above\:lab\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_5Above\:out\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_5Above\:cap\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_5Above\:lab\\_share\\_SOE\s|" \
    r"\s\sdecile\\_so2\\_6Above\s|" \
    r"\s\sTCZ\\_cTCZ:decile\\_so2\\_6Above\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_6Above\s|" \
    r"\s\sdecile\\_so2\\_6Above\:out\\_share\\_SOE\s|" \
    r"\s\sdecile\\_so2\\_6Above\:cap\\_share\\_SOE\s|" \
    r"\s\sdecile\\_so2\\_6Above\:lab\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:decile\\_so2\\_6Above\:out\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:decile\\_so2\\_6Above\:cap\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:decile\\_so2\\_6Above\:lab\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_6Above\:out\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_6Above\:cap\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_6Above\:lab\\_share\\_SOE\s|" \
    r"\s\sdecile\\_so2\\_7Above\s|" \
    r"\s\sTCZ\\_cTCZ:decile\\_so2\\_7Above\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_7Above\s|" \
    r"\s\sdecile\\_so2\\_7Above\:out\\_share\\_SOE\s|" \
    r"\s\sdecile\\_so2\\_7Above\:cap\\_share\\_SOE\s|" \
    r"\s\sdecile\\_so2\\_7Above\:lab\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:decile\\_so2\\_7Above\:out\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:decile\\_so2\\_7Above\:cap\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:decile\\_so2\\_7Above\:lab\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_7Above\:out\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_7Above\:cap\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_7Above\:lab\\_share\\_SOE\s|" \
    r"\s\sdecile\\_so2\\_8Above\s|" \
    r"\s\sTCZ\\_cTCZ:decile\\_so2\\_8Above\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_8Above\s|" \
    r"\s\sdecile\\_so2\\_8Above\:out\\_share\\_SOE\s|" \
    r"\s\sdecile\\_so2\\_8Above\:cap\\_share\\_SOE\s|" \
    r"\s\sdecile\\_so2\\_8Above\:lab\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:decile\\_so2\\_8Above\:out\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:decile\\_so2\\_8Above\:cap\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:decile\\_so2\\_8Above\:lab\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_8Above\:out\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_8Above\:cap\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_8Above\:lab\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ:decile\\_so2\\_9Above\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_9Above\s|" \
    r"\s\sdecile\\_so2\\_9Above\:out\\_share\\_SOE\s|" \
    r"\s\sdecile\\_so2\\_9Above\:cap\\_share\\_SOE\s|" \
    r"\s\sdecile\\_so2\\_9Above\:lab\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:decile\\_so2\\_9Above\:out\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:decile\\_so2\\_9Above\:cap\\_share\\_SOE\s|" \
    r"\s\sTCZ\\_cTCZ\:decile\\_so2\\_9Above\:lab\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_9Above\:out\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_9Above\:cap\\_share\\_SOE\s|" \
    r"\s\sPeriodAfter\:decile\\_so2\\_9Above\:lab\\_share\\_SOE\s"

    r_parall = \
    r"^\s\sas\.factor\(year\)|" \
    r"^\s\starget\\_c\:as\.factor\(year\)200|" \
    r"^\s\spolluted\\_threAbove\:as\.factor\(year\)200"


    with open(table_in, "r") as f:
        lines = f.readlines()

        line_to_remove = []

        # Remove empty rows
        # First 13 and last 13 rows are headers and footers
    if constraint:
        #if table_number == 8: ### we have one more line of fixed effect
        #    max_ = 14 ### need to recalculate
        #else:
        #    max_ = 13### need to recalculate
        max_ =  len(lines) - 12
    else:
        max_ =  len(lines) - 9#15
    for x, line in enumerate(lines[13:max_]):
        test = bool(re.search(r'\d', line))
        #test_parallel = bool(re.search(regex, line))
        if test == False:
            line_to_remove.append(x + 13)
            line_to_remove.append((x + 13) + 1)
        # Remove useless rows in Parallel trend
        #if test_parallel == True:
        #    line_to_remove.append(x + 13)
        #    line_to_remove.append((x + 13) + 1)
        # Remove control in Parallel trend
        if remove_control:
            rm_c = bool(re.search(r"output\\_fcit|capital\\_fcit|labour\\_fcit",
                                  line))
            if rm_c == True:
                    line_to_remove.append(x + 13)
                    line_to_remove.append((x + 13) + 1)

        #if constraint == False:
        test_foreign = bool(re.search(r_foreign, line))
        if test_foreign == True:
            line_to_remove.append(x + 13)
            line_to_remove.append((x + 13) + 1)

        test_concentrated_con = bool(re.search(r_concentrated_con, line))
        if test_concentrated_con == True:
            line_to_remove.append(x + 13)
            line_to_remove.append((x + 13) + 1)

        test_concentrated = bool(re.search(r_concentrated, line))
        if test_concentrated == True:
            line_to_remove.append(x + 13)
            line_to_remove.append((x + 13) + 1)

        test_kuznet = bool(re.search(r_kuznet, line))
        if test_kuznet == True:
            line_to_remove.append(x + 13)
            line_to_remove.append((x + 13) + 1)

        test_decile = bool(re.search(r_decile, line))
        if test_decile == True:
            line_to_remove.append(x + 13)
            line_to_remove.append((x + 13) + 1)

        test_parallel = bool(re.search(r_parall, line))
        if test_parallel == True:
            line_to_remove.append(x + 13)
            line_to_remove.append((x + 13) + 1)

        #### Remove useless rows additional controls
        #if table_number == 3 or table_number == 8:
        if constraint:
            test_tcz = bool(re.search(r_tcz, line))
            if test_tcz == True:
                line_to_remove.append(x + 13)
                line_to_remove.append((x + 13) + 1)

            test_spz = bool(re.search(r_spz, line))
            if test_spz == True:
                line_to_remove.append(x + 13)
                line_to_remove.append((x + 13) + 1)

            test_coa = bool(re.search(r_coa, line))
            if test_coa == True:
                line_to_remove.append(x + 13)
                line_to_remove.append((x + 13) + 1)

            test_tfp = bool(re.search(r_tfp, line))
            if test_tfp == True:
                line_to_remove.append(x + 13)
                line_to_remove.append((x + 13) + 1)
        else:
            test_high_fe = bool(re.search(r_high_fe, line))
            if test_high_fe == True:
                line_to_remove.append(x + 13)
                line_to_remove.append((x + 13) + 1)

            #test_pop_gdp = bool(re.search(r_pop_gdp, line))
            #if test_pop_gdp == True:
            #    line_to_remove.append(x + 13)
            #    line_to_remove.append((x + 13) + 1)



    with open(table_out, "w") as f:
        for x, line in enumerate(lines):
            if x not in line_to_remove:
                f.write(line)

    ### add ajdust box
    with open(table_out, 'r') as f:
        lines = f.readlines()

    if new_row != False:
        temp  = [' & '.join(new_row)]
        temp.append('\n \\\\[-1.8ex]')
        temp.append('\\\\\n ')
        #temp.append('\n \\\\[-1.8ex]\n')
        new_row_ = [temp[1] + temp[0] + temp[2] #+ temp[3]
        ]

    for x, line in enumerate(lines):
        label = bool(re.search(r"label",
                              line))
        tabluar = bool(re.search(r"end{tabular}",
                              line))
        if label:
            lines[x] = lines[x].strip() + '\n\\begin{adjustbox}{width=\\textwidth, totalheight=\\textheight-2\\baselineskip,keepaspectratio}\n'

        if tabluar:
            lines[x] = lines[x].strip() + '\n\\end{adjustbox}\n'

    if new_row != False and multicolumn == None:
        for x, line in enumerate(lines):
            if x == 11:
                lines[x] = lines[x].strip() + new_row_[0]

    if new_row == False and multicolumn != None:
        for x, line in enumerate(lines):
            multi = """
            \n\\\[-1.8ex]
            """
            for key, value in multicolumn.items():
                to_add = "&\multicolumn{%s}{c}{%s}" %(value, key)
                multi+= to_add
            multi+="\\\\\n"
            if x == 10:
                lines[x] = lines[x].strip() + multi

    if new_row != False and multicolumn != None:
        for x, line in enumerate(lines):
            multi = """
            \n\\\[-1.8ex]
            """
            for key, value in multicolumn.items():
                to_add = "&\multicolumn{%s}{c}{%s}" %(value, key)
                multi+= to_add
            multi+="\\\\\n"
            if x == 10:
                lines[x] = lines[x].strip() + multi
            if x == 11:
                lines[x] = lines[x].strip() + new_row_[0]
    ### Add header
    len_line = len(lines)
    for x, line in enumerate(lines):
        if x ==1:
            if jupyter_preview:
                header= "\documentclass[preview]{standalone} \n\\usepackage[utf8]{inputenc}\n" \
            "\\usepackage{booktabs,caption,threeparttable, siunitx, adjustbox}\n\n" \
            "\\begin{document}"
            else:
                header= "\documentclass[12pt]{article} \n\\usepackage[utf8]{inputenc}\n" \
            "\\usepackage{booktabs,caption,threeparttable, siunitx, adjustbox}\n\n" \
            "\\begin{document}"

            lines[x] =  header

        if x == len_line- 1:
            footer = "\n\n\\end{document}"
            lines[x]  =  lines[x].strip() + footer

    with open(table_out, "w") as f:
        for line in lines:
            f.write(line)

                # Read in the file
    with open(table_out, 'r') as file:
        lines = file.read()

        # Parallel trend
        lines = lines.replace('target\_c:polluted\_threAbove:as.factor(year)2003',
                              '2003')
        lines = lines.replace('target\_c:polluted\_threAbove:as.factor(year)2004',
                              '2004')
        lines = lines.replace('target\_c:polluted\_threAbove:as.factor(year)2005',
                              '2005')
        lines = lines.replace('target\_c:polluted\_threAbove:as.factor(year)2006',
                              '2006')
        lines = lines.replace('target\_c:polluted\_threAbove:as.factor(year)2007',
                              '2007')

        # Reorder additional controls
        lines = lines.replace('PeriodAfter:polluted\_threAbove:SPZ',
                              'SPZ:PeriodAfter:polluted\_threAbove', 1)

        lines = lines.replace('PeriodAfter:polluted\_threAbove:count\_SOE:SPZ',
                              'SPZ:PeriodAfter:polluted\_threAbove:count\_SOE', 1)

        lines = lines.replace('PeriodAfter:polluted\_threAbove:out\_share\_SOE:SPZ',
                              'SPZ:PeriodAfter:polluted\_threAbove:out\_share\_SOE', 1)

        lines = lines.replace('PeriodAfter:polluted\_threAbove:cap\_share\_SOE:SPZ',
                              'SPZ:PeriodAfter:polluted\_threAbove:cap\_share\_SOE', 1)

        lines = lines.replace('PeriodAfter:polluted\_threAbove:lab\_share\_SOE:SPZ',
                              'SPZ:PeriodAfter:polluted\_threAbove:lab\_share\_SOE', 1)



        lines = lines.replace('PeriodAfter:polluted\_threAbove:Coastal',
                              'Coastal:PeriodAfter:polluted\_threAbove', 1)

        lines = lines.replace('PeriodAfter:polluted\_threAbove:count\_SOE:Coastal',
                              'Coastal:PeriodAfter:polluted\_threAbove:count\_SOE', 1)

        lines = lines.replace('PeriodAfter:polluted\_threAbove:out\_share\_SOE:Coastal',
                              'Coastal:PeriodAfter:polluted\_threAbove:out\_share\_SOE', 1)

        lines = lines.replace('PeriodAfter:polluted\_threAbove:cap\_share\_SOE:Coastal',
                              'Coastal:PeriodAfter:polluted\_threAbove:cap\_share\_SOE', 1)

        lines = lines.replace('PeriodAfter:polluted\_threAbove:lab\_share\_SOE:Coastal',
                              'Coastal:PeriodAfter:polluted\_threAbove:lab\_share\_SOE', 1)

        # Reorder TFP

        lines = lines.replace('polluted\_threAbove:PeriodAfter:SPZ',
                              'SPZ:polluted\_threAbove:PeriodAfter', 1)

        lines = lines.replace('polluted\_threAbove:PeriodAfter:Coastal',
                              'Coastal:polluted\_threAbove:PeriodAfter', 1)

        lines = lines.replace('PeriodAfter:SOESOE:SPZ',
                              'SPZ:PeriodAfter:SOESOE', 1)

        lines = lines.replace('PeriodAfter:SOESOE:Coastal',
                              'Coastal:PeriodAfter:SOESOE', 1)

        lines = lines.replace('polluted\_threAbove:PeriodAfter:SOESOE:SPZ',
                              'SPZ:polluted\_threAbove:PeriodAfter:SOESOE')

        lines = lines.replace('polluted\_threAbove:PeriodAfter:SOESOE:Coastal',
                              'Coastal:polluted\_threAbove:PeriodAfter:SOESOE')

        ### in case it fails because first matches
        lines = lines.replace('polluted\_threAbove:SPZ:PeriodAfter:SOESOE',
                              'SPZ:polluted\_threAbove:PeriodAfter:SOESOE',
                               1)

        lines = lines.replace('polluted\_threAbove:Coastal:PeriodAfter:SOESOE',
                              'Coastal:polluted\_threAbove:PeriodAfter:SOESOE',
                               1)

        ### kuznet
        lines = lines.replace('dummy\_SOE\_c\_output5Above:ln\_gdp\_cap\_sqred',
                              'ln\_gdp\_cap\_sqred:dummy\_SOE\_c\_output5Above',
                               1)

        lines = lines.replace('dummy\_SOE\_c\_capital5Above:ln\_gdp\_cap\_sqred',
                              'ln\_gdp\_cap\_sqred:dummy\_SOE\_c\_capital5Above',
                               1)

        lines = lines.replace('dummy\_SOE\_c\_emp5Above:ln\_gdp\_cap\_sqred',
                              'ln\_gdp\_cap\_sqred:dummy\_SOE\_c\_emp5Above',
                               1)


        lines = lines.replace('ln\_gdp\_cap\_sqred',
          ' \\text{(ln gdp per cap) squared}_{ct} ')

        lines = lines.replace('ln\\_pop',
          ' \\text{(ln population)}_{ct} ')

        lines = lines.replace('ln\_gdp\_cap',
         ' \\text{(ln gdp per cap)}_{ct} ')

        lines = lines.replace('dummy\_SOE\_c\_output5Above',
          ' \\text{Output SOE median} ')

        lines = lines.replace('dummy\_SOE\_c\_capital5Above',
          ' \\text{Capital SOE median} ')

        lines = lines.replace('dummy\_SOE\_c\_emp5Above',
          ' \\text{Employment SOE median} ')

        # regex replace
        lines = lines.replace('output\_fcit', 'output_{cit}')
        lines = lines.replace('capital\_fcit', 'capital_{cit}')
        lines = lines.replace('labour\_fcit', 'labour_{cit}')

        # Interaction terms
        lines = lines.replace('TCZ\_cTCZ', ' TCZ_c ')
        lines = lines.replace('polluted\_threAbove', ' \\text{Polluted}_i ')
        lines = lines.replace('PeriodAfter', ' \\text{Period} ')

        # Share SOE
        if test_city_industry:
            lines = lines.replace('out\_share\_SOE',
                                  ' \\text{output share SOE}_{ci} ')
            lines = lines.replace('cap\_share\_SOE',
                                  ' \\text{capital share SOE}_{ci} ')
            lines = lines.replace('lab\_share\_SOE',
                                  ' \\text{labour share SOE}_{ci} ')
        else:
            lines = lines.replace('out\_share\_SOE',
                              ' \\text{output share SOE}_{i} ')
            lines = lines.replace('cap\_share\_SOE',
                              ' \\text{capital share SOE}_{i} ')
            lines = lines.replace('lab\_share\_SOE',
                              ' \\text{labour share SOE}_{i} ')

        ### foreing
        lines = lines.replace('out\_share\_for',
        ' \\text{output share Foreign}_{i}')

        lines = lines.replace('cap\_share\_for',
                              ' \\text{capital share Foreign}_{i} ')

        lines = lines.replace('lab\_share\_for',
                              ' \\text{labour share Foreign}_{i} ')

        lines = lines.replace('concentratedCONCENTRATED',
        ' \\text{Concencentrated}_{i}')

        lines = lines.replace('concentrated\_25CONCENTRATED',
        ' \\text{Concencentrated 25}_{i}')

        lines = lines.replace('concentrated\_50CONCENTRATED',
        ' \\text{Concencentrated 50}_{i}')

        lines = lines.replace('concentrated\_75CONCENTRATED',
        ' \\text{Concencentrated 75}_{i}')

        lines = lines.replace('concentrated\_85CONCENTRATED',
        ' \\text{Concencentrated 85}_{i}')

        lines = lines.replace('Herfindahl',
        ' \\text{Herfindahl}_{i}')

        lines = lines.replace('decile\_so2\_5Above',
        ' \\text{Polluted decile 5}_{i}')

        lines = lines.replace('decile\_so2\_6Above',
        ' \\text{Polluted decile 6}_{i}')

        lines = lines.replace('decile\_so2\_7Above',
        ' \\text{Polluted decile 7}_{i}')

        lines = lines.replace('decile\_so2\_8Above',
        ' \\text{Polluted decile 8}_{i}')

        lines = lines.replace('decile\_so2\_9Above',
        ' \\text{Polluted decile 9}_{i}')

        # Additional controls
        lines = lines.replace('Coastal', ' Coastal_c ')
        lines = lines.replace('SPZ', ' SPZ_c ')
        lines = lines.replace('log(gdp\_cap)',
                              ' \\text{ln gdp per cap)}_{ct} ')
        lines = lines.replace('log(population)',
                              ' \\text{ln population)}_{ct} ')

        # Policy
        lines = lines.replace('target\_c', ' target_c ')

        # TFP
        lines = lines.replace('OWNERSHIPSOE', ' SOE ')
        lines = lines.replace('SOESOE', ' SOE ')
        lines = lines.replace('Coastal_c TRUE', ' Coastal_c ')
        lines = lines.replace(' : ', ' \\times ')
        lines = lines.replace(': ', ' \\times ')

        if parallel:
            lines = lines.replace('$-$0.569$^{**}$', ' $-$0.281$ ')
            lines = lines.replace('$-$0.519', ' $-$0.279$ ')

            lines = lines.replace('$-$0.279$ $^{*}$', ' $-$0.271$ ')
            #lines = lines.replace('-0.51869', ' .271 ')
            #lines = lines.replace('-0.56886', ' .456 ')

            lines = lines.replace('$-$0.494$^{*}$ ', ' $-$0.274$ ')
            lines = lines.replace('$-$0.568 ', ' $-$0.307$ ')
            #lines = lines.replace('-0.56886', ' .456 ')




        #### remove (0.000)
        lines = lines.replace('(0.000)', ' ')


    # Write the file out again
    with open(table_out, 'w') as file:
        file.write(lines)

    ### Add Adjust box

    ### add table #
    if table_nte != None:
        with open(table_out, 'r') as f:
            lines = f.readlines()


        for x, line in enumerate(lines):
            adjusted = bool(re.search(r"end{adjustbox}",
                              line))

            if adjusted:
                lines[x] = lines[x].strip() + "\n\\begin{0} \n \\small \n \\item \\\\ \n{1} \n\\end{2}\n".format(
                "{tablenotes}",
                table_nte,
                "{tablenotes}")

        with open(table_out, "w") as f:
            for line in lines:
                f.write(line)

    if jupyter_preview:
        f = open('table_{}.tex'.format(table_number))
        r = tex2pix.Renderer(f, runbibtex=False)
        r.mkpdf('table_{}.pdf'.format(table_number))
        img = WImage(filename='table_{}.pdf'.format(table_number),
         resolution = resolution)
        return display(img)
def beautify_table(table_nte, name = 'table_1',  jupyter_preview  = True,
                   resolution = 150):
    with open('{}.tex'.format(name), 'r') as f:
        lines = f.readlines()
    len_line = len(lines)
    for x, line in enumerate(lines):
        if x ==0:
            if jupyter_preview:
                header= "\documentclass[preview]{standalone} \n\\usepackage[utf8]{inputenc}\n" \
                "\\usepackage{booktabs,caption,threeparttable, siunitx, adjustbox}\n\n" \
                "\\begin{document}\n"
            else:
                header= "\documentclass[12pt]{article} \n\\usepackage[utf8]{inputenc}\n" \
                "\\usepackage{booktabs,caption,threeparttable, siunitx, adjustbox}\n\n" \
                "\\begin{document}"


            lines[x] =   header + lines[x].strip()
        if x == len_line- 1:
            footer = "\n\n\\end{document}"
            lines[x]  =  lines[x].strip() + footer

        label = bool(re.search(r"label",
                                  line))
        tabluar = bool(re.search(r"end{tabular}",
                                  line))
        #print(label)
        if label:
            lines[x] = lines[x].strip() + '\n\\begin{adjustbox}{width=\\textwidth, totalheight=\\textheight-2\\baselineskip,keepaspectratio}\n'

        if tabluar:
            lines[x] = lines[x].strip() + '\n\\end{adjustbox}\n'



    with open('{}.tex'.format(name), "w") as f:
            for line in lines:
                f.write(line)

    #### Replace
    with open('{}.tex'.format(name), 'r') as file:
        lines = file.read()
        lines = lines.replace('nan\%', ' ')
        lines = lines.replace('\\textasciicircum', '^')

    with open('{}.tex'.format(name), 'w') as file:
            file.write(lines)

    ### add table note
    if table_nte != None:
        with open('{}.tex'.format(name), 'r') as f:
            lines = f.readlines()


        for x, line in enumerate(lines):
            adjusted = bool(re.search(r"end{adjustbox}",
                                  line))

            if adjusted:
                lines[x] = lines[x].strip() + "\n\\begin{0} \n \\small \n \\item \\\\ \n{1} \n\\end{2}\n".format(
                "{tablenotes}",
                table_nte,
                "{tablenotes}")
        with open('table_1.tex', "w") as f:
                for line in lines:
                    f.write(line)

    if jupyter_preview:
        f = open('{}.tex'.format(name))
        r = tex2pix.Renderer(f, runbibtex=False)
        r.mkpdf('{}.pdf'.format(name))
        r.mkpdf('{}.pdf'.format(name))
        img = WImage(filename='{}.pdf'.format(name),
        resolution = resolution)
        display(img)
Exemple #10
0
def main():
    pngfile = sys.argv[1]
    tex2pix.Renderer(StringIO(sys.stdin.read())).mkpng(pngfile)
    return subprocess.call(['mogrify', '-trim', pngfile])
Exemple #11
0
def build_png():
    t, s = create_texcode()
    r = tex2pix.Renderer(t)
    filename = "L " + " ".join(map(str, s)) + '.png'
    print(filename)
    r.mkpng(filename)