コード例 #1
0
def produce_table():
    # create document structure
    doc = Document("testtable")
    section = Section('Produce accessories table')
    test1 = Subsection('Test accessories table production')

    # test input code
    bench = [('Incline BP (4 x 12)'), ('Pull up (4 x Max)')]

    # test code
    accesory = bench
    table = Tabular('|c|c|c|c|c|c|c|c|c|')
    table.add_hline()
    table.add_row((MultiColumn(9, align='|c|', data='Accessories'), ))
    table.add_hline()
    table.add_row(('Exercise', 'Weight', 'Reps', 'Weight', 'Reps', 'Weight',
                   'Reps', 'Weight', 'Reps'))
    table.add_hline()
    for i in range(len(accesory)):
        table.add_row((str(accesory[i]), '', '', '', '', '', '', '', ''))
        table.add_hline()

    # append table to document
    test1.append(table)
    section.append(test1)
    doc.append(section)
    doc.generate_pdf(clean_tex=True)
コード例 #2
0
def build_document(transcript):
    """
    Processes a Transcript object to build a LaTeX document.
    """
    # Open temporary file
    doc = Document(documentclass='scrartcl',
                   title=transcript.title,
                   subtitle=transcript.school,
                   author=transcript.student,
                   date=transcript.date.strftime('%d %B %Y'),
                   temporary=True)

    doc.packages.append(Package('geometry', option='margin=1.0in'))
    doc.preamble.append(
        Command('renewcommand', argument=['\\familydefault', '\\sfdefault']))

    doc.append(Command('maketitle'))

    # Iterate through each transcript section
    for t_section in transcript.sections:
        # Create new section
        s = Section(escape_latex(t_section.title))
        # Add content to section
        for s_line in t_section.content:
            s_line = '\t'.join(s_line)
            s.append(escape_latex(s_line) + ' \\\n')

        # Add subsections to section
        for t_subsection in t_section.subsections:
            ss = Subsection(escape_latex(t_subsection.title))
            num_cols = max(len(l) for l in t_subsection.content)
            ss_table = Table(' l ' * num_cols)
            # Add content to subsection
            for ss_line in t_subsection.content:

                ss_line = '\t'.join(ss_line)
                if ss_line.startswith('Course Topic'):
                    ss_table.append('&')
                    ss_table.add_multicolumn(num_cols - 1, 'l',
                                             escape_latex(ss_line))
                    ss_table.append(r'\\')
                elif not ss_line[:3].isupper() and not ss_line.startswith(
                        'Test'):
                    ss_table.add_multicolumn(num_cols, 'l',
                                             escape_latex(ss_line))
                    ss_table.append(r'\\')
                else:
                    if ss_line.startswith('TERM'):
                        ss_table.add_hline()
                    filled = escape_latex(ss_line).split('\t')
                    filled += (num_cols - len(filled)) * ['']
                    ss_table.add_row(filled)

            ss.append(ss_table)
            s.append(ss)

        doc.append(s)
    doc.generate_pdf(clean=True)

    return doc
コード例 #3
0
def test():
    doc = Document("utils_escape_latex")
    section = Section('Escape LaTeX characters test')

    text = escape_latex('''\
    & (ampersand)
    % (percent)
    $ (dollar)
    # (number)
    _ (underscore)
    { (left curly brace)
    } (right curly brace)
    ~ (tilde)
    ^ (caret)
    \\ (backslash)
    --- (three minuses)
    a\xA0a (non breaking space)
    [ (left bracket)
    ] (right bracket)
    ''')

    section.append(text)
    doc.append(section)

    doc.generate_pdf()
コード例 #4
0
def test():
    doc = Document("utils_escape_latex")
    section = Section('Escape LaTeX characters test')

    text = escape_latex('''\
    & (ampersand)
    % (percent)
    $ (dollar)
    # (number)
    _ (underscore)
    { (left curly brace)
    } (right curly brace)
    ~ (tilde)
    ^ (caret)
    \\ (backslash)
    --- (three minuses)
    a\xA0a (non breaking space)
    [ (left bracket)
    ] (right bracket)
    ''')

    section.append(text)
    doc.append(section)

    doc.generate_pdf()
コード例 #5
0
ファイル: Relatorio.py プロジェクト: Israelmath/Profnotas
    def cria_relatorio(self):
        margens = {'margin': '1.5cm', 'tmargin': '1cm'}
        doc = Document(f'Relatórios/{self.resumo[1]} {self.resumo[2]}',
                       geometry_options=margens,
                       page_numbers=False)

        # Definindo marcações e cabeçalhos
        cabecalho_trimestre = [
            '1ª redação', '2ª redação', '3ª redação', '4ª redação'
        ]
        cabecalho_ano = ['Média 1º tri', 'Média 2º tri', 'Média 3º tri']

        doc.preamble.append(Command('title', 'Relatório escolar'))
        doc.preamble.append(Command('author', 'Profª Joice da Silva Moreli'))
        doc.append(NoEscape(r'\maketitle'))

        # Definindo Seções e Subseções
        section_1 = Section('Informações do aluno:', numbering=False)
        section_2 = Section('Comparação com todos os alunos:', numbering=False)

        subsec_1tri = Subsection('1º Trimestre:', numbering=False)
        subsec_2tri = Subsection('2º Trimestre:', numbering=False)
        subsec_3tri = Subsection('3º Trimestre:', numbering=False)

        # Criando conteúdo da primeira seção
        primeira_secao = self.cria_primeira_secao(cabecalho_ano)

        # Criando conteúdo da primeira subseção
        subsec_1tri.append(
            self.cria_subsecao(cabecalho=cabecalho_trimestre, tri=0))

        # Criando conteúdo da segunda subseção
        subsec_2tri.append(
            self.cria_subsecao(cabecalho=cabecalho_trimestre, tri=1))

        # Criando conteúdo da terceira subseção
        subsec_3tri.append(
            self.cria_subsecao(cabecalho=cabecalho_trimestre, tri=2))

        # Criando conteúdo para segunda seção
        rows_segunda_secao = self.cria_segunda_secao()

        # Adicionando coluna e subseções à primeira seção
        section_1.append(primeira_secao)
        for row in reversed(rows_segunda_secao):
            section_2.append(row)
            section_2.append(NewLine())
        section_1.append(subsec_1tri)
        section_1.append(subsec_2tri)
        section_1.append(subsec_3tri)

        doc.append(section_1)
        doc.append(section_2)

        doc.generate_pdf(
            f'Relatórios/{self.resumo[1].strip()} {self.resumo[2].strip()}',
            clean_tex=False)
コード例 #6
0
def build_document(transcript):
    """
    Processes a Transcript object to build a LaTeX document.
    """
    # Open temporary file
    doc = Document(documentclass='scrartcl', title=transcript.title,
                   subtitle=transcript.school,
                   author=transcript.student,
                   date=transcript.date.strftime('%d %B %Y'), temporary=True)

    doc.packages.append(Package('geometry', option='margin=1.0in'))
    doc.preamble.append(Command('renewcommand', argument=['\\familydefault', '\\sfdefault']))

    doc.append(Command('maketitle'))

    # Iterate through each transcript section
    for t_section in transcript.sections:
        # Create new section
        s = Section(escape_latex(t_section.title))
        # Add content to section
        for s_line in t_section.content:
            s_line = '\t'.join(s_line)
            s.append(escape_latex(s_line) + ' \\\n')

        # Add subsections to section
        for t_subsection in t_section.subsections:
            ss = Subsection(escape_latex(t_subsection.title))
            num_cols = max(len(l) for l in t_subsection.content)
            ss_table = Table(' l ' * num_cols)
            # Add content to subsection
            for ss_line in t_subsection.content:

                ss_line = '\t'.join(ss_line)
                if ss_line.startswith('Course Topic'):
                    ss_table.append('&')
                    ss_table.add_multicolumn(num_cols-1, 'l',
                                             escape_latex(ss_line))
                    ss_table.append(r'\\')
                elif not ss_line[:3].isupper() and not ss_line.startswith('Test'):
                    ss_table.add_multicolumn(num_cols, 'l', escape_latex(ss_line))
                    ss_table.append(r'\\')
                else:
                    if ss_line.startswith('TERM'):
                        ss_table.add_hline()
                    filled = escape_latex(ss_line).split('\t')
                    filled += (num_cols - len(filled)) * ['']
                    ss_table.add_row(filled)

            ss.append(ss_table)
            s.append(ss)

        doc.append(s)
    doc.generate_pdf(clean=True)

    return doc
コード例 #7
0
    def write_prgramm_statments(self, doc):
        section1 = Section("rCat, v.0.1", numbering=False)
        section1.append(
            "This program is developed by Florian Barth and Evgeny Kim with the help of Roman Klinger and Sandra Murr. It is part of the Center for Reflected Text Analytics (CRETA) at the Universtiy of Stuttgart.\n\nFeel free to contact us:"
        )

        list = Itemize()
        list.add_item("*****@*****.**")

        section1.append(list)
        doc.append(section1)
コード例 #8
0
def test():
    doc = Document()
    section = Section('Multirow Test')
    figure = Figure()
    image_filename = os.path.join(os.path.dirname(__file__),
                                  '../examples/kitten.jpg')
    figure.add_image(image_filename)
    figure.add_caption('Whoooo an imagage of a pdf')
    section.append(figure)
    doc.append(section)

    doc.generate_pdf()
コード例 #9
0
def test():
    doc = Document()
    Subsection('Only a single string', data='Some words')

    sec1 = Section('Only contains one subsection', data='Subsection')

    sec2 = Section('Only a single italic command', data=Command('textit',
                                                                'Hey'))
    sec2.append('something else that is not italic')
    doc.append(sec1)
    doc.append(sec2)

    doc.generate_pdf()
コード例 #10
0
def test():
    doc = Document()
    Subsection('Only a single string', data='Some words')

    sec1 = Section('Only contains one subsection', data='Subsection')

    sec2 = Section('Only a single italic command',
                   data=Command('textit', 'Hey'))
    sec2.append('something else that is not italic')
    doc.append(sec1)
    doc.append(sec2)

    doc.generate_pdf()
コード例 #11
0
def create_latex_file(pokemon, list_of_normal_ivs, list_of_boosted_ivs):
    geometry_options = {
        "landscape": True,
        "margin": "0.5in",
        "headheight": "20pt",
        "headsep": "10pt",
        "includeheadfoot": True
    }

    doc = Document(page_numbers=True, geometry_options=geometry_options)

    doc.add_color('color100', 'rgb', rgb_to_dumb_string(0, 207, 194))
    doc.add_color('color98', 'rgb', rgb_to_dumb_string(60, 141, 1))
    doc.add_color('color96', 'rgb', rgb_to_dumb_string(72, 165, 6))
    doc.add_color('color93', 'rgb', rgb_to_dumb_string(242, 183, 8))
    doc.add_color('color91', 'rgb', rgb_to_dumb_string(246, 96, 0))

    section = Section(f'{pokemon.name} IV Chart')

    table = Tabular('|c|c|c|c|c|c|', row_height=1.5)
    table.add_hline()
    table.add_row((MultiColumn(
        6, align='|c|', data=TextColor('white',
                                       pokemon.name), color='black'), ), )

    table.add_row(
        (MultiColumn(1, align='|c',
                     data='Lv20'), MultiColumn(1, align='c|', data='Lv25'),
         MultiColumn(3, align='c|',
                     data='IV'), MultiColumn(1, align='|c|', data='%')))

    for index in range(len(list_of_normal_ivs)):
        n_iv = list_of_normal_ivs[index]
        b_iv = list_of_boosted_ivs[index]

        row_data = (f'{n_iv.cp}', f'{b_iv.cp}', f'{n_iv.attack}',
                    f'{n_iv.defense}', f'{n_iv.stamina}',
                    f'{n_iv.perfection_percent_rounded}')

        table.add_hline()
        table.add_row(row_data,
                      color=color_by_iv(n_iv.perfection_percent_rounded))

    section.append(table)
    doc.append(section)

    doc.generate_tex(f'latex/{pokemon.name}')
    doc.generate_pdf(f'pdf/{pokemon.name}')
コード例 #12
0
def generate_comparison(dims, algorithm_names, algorithm_results, mode='COST'):

    # Creating the document
    from_mode = ''
    if mode == 'COST':
        doc = Document('latex_tables/generated_table_cost_comparison')
        section = Section("Table of Costs")
        from_mode = "{:.2f}"
    if mode == 'TIME':
        doc = Document('latex_tables/generated_table_time_comparison')
        section = Section("Table of Times")
        from_mode = "{:.2e}"

    # Setting tabular property
    tabular_header = 'c'
    for i in algorithm_names:
        tabular_header += 'c'

    # Creation of the Table
    table = Tabular(tabular_header)
    table.add_row((MultiColumn(len(algorithm_names) + 1,
                               align='c',
                               data='Costs'), ))
    table.add_hline()
    table.add_hline()
    table.add_row(['Nodi'] + algorithm_names)
    table.add_hline()

    for i in range(len(dims)):

        table.add_row((dims[i], from_mode.format(algorithm_results[0][i]),
                       from_mode.format(algorithm_results[1][i]),
                       from_mode.format(algorithm_results[2][i]),
                       from_mode.format(algorithm_results[3][i]),
                       from_mode.format(algorithm_results[4][i])))

    # We close the table
    table.add_hline()

    # And finally we compose and generate the new document with the embedded table
    section.append(table)
    doc.append(section)
    doc.generate_tex()
コード例 #13
0
ファイル: latex_doc.py プロジェクト: ai-systems/poly-nlp
 def build_latex(
         evaluations: Dict[str, List[Metric]],
         file_name: str,
         invert_map: Dict[str, bool] = defaultdict(lambda: False),
         **kwargs,
 ):
     logger.info("Building LaTex Document")
     doc = Document("")
     section = Section("Evaluations")
     tables = [
         MetricTable.build_latex(evals,
                                 invert=invert_map[caption],
                                 caption=caption)
         for caption, evals in evaluations.items()
     ]
     doc.append(section)
     for table in tables:
         section.append(table)
     doc.generate_tex(filepath=file_name)
     logger.success("LaTex Document build success")
     return doc
コード例 #14
0
ファイル: log2pdf.py プロジェクト: chocoteam/choco-parsers
fbest = 0
tbest = 0
for fname in fnames:
    solutions = optPerSol[fname]
    gbest = maxobj
    if fname in bestever :
        if len(bestever[fname]) > 1:
            fbest += 1
        if 'C' in bestever[fname][0]:
            proof += 1
table.add_hline()
table.add_hline()
table.add_row(('syb', sat, unsat, fbest, proof, "--"))

table.add_hline()
section.append(table)

if args.details:
    # Third problem per problem
    k = 0
    for fname in fnames:
        parts = fname.split("+")
        solutions = optPerSol[fname]
        if parts[0] != presec:
            presec = parts[0]
            if k > 0:
                addTimePlots(doc, options, coords)
                for o in options:
                    coords[o].clear()
                k = 0
                if len(objs)>0:
コード例 #15
0
ファイル: numpy_ex.py プロジェクト: ChrisStevens/PyLaTeX
from pylatex import Document, Section, Subsection, Table, Math
from pylatex.numpy import Matrix, format_vec


a = np.array([[100, 10, 20]]).T

doc = Document()
section = Section('Numpy tests')
subsection = Subsection('Array')

vec = Matrix(a)
vec_name = format_vec('a')
math = Math(data=[vec_name, '=', vec])

subsection.append(math)
section.append(subsection)

subsection = Subsection('Matrix')
M = np.matrix([[2, 3, 4],
               [0, 0, 1],
               [0, 0, 2]])
matrix = Matrix(M, mtype='b')
math = Math(data=['M=', matrix])

subsection.append(math)
section.append(subsection)


subsection = Subsection('Product')

math = Math(data=['M', vec_name, '=', Matrix(M*a)])
コード例 #16
0
ファイル: PDFCreator.py プロジェクト: sbahrin3/choco-solver
    def __detailsFZN(self, doc, options, optPerSol, fnames, maxtime, bestever):
        coords = {}
        objs = {}
        for o in options:
            coords[o] = []
            objs[o] = []
        objs['syb'] = []
        pol = 'SAT'
        presec = ""
        prevsubsec = ""
        section = None
        subsection = None
        # Third problem per problem
        k = 0
        for fname in fnames:
            parts = fname.split("+")
            solutions = optPerSol[fname]
            if parts[0] != presec:
                presec = parts[0]
                if k > 0:
                    self.__addTimePlots(doc, options, coords)
                    for o in options:
                        coords[o].clear()
                    k = 0
                    if len(objs) > 0:
                        self.__addObjPlots(doc, options, objs, pol)
                        for o in objs.keys():
                            objs[o].clear()

                section = Section('%s' % (presec))  # .replace("_", "\_")))
                doc.append(section)
                print("create section: " + presec)

            if parts[1] != prevsubsec:
                prevsubsec = parts[1]
                subsection = Subsection('%s' %
                                        (prevsubsec))  # .replace("_", "\_")))
                section.append(subsection)
                print("create subsection: " + prevsubsec)

            if len(parts) > 2:
                subsubsection = Subsubsection(
                    '%s' % (parts[2]))  # .replace("_", "\_")))
                subsection.append(subsubsection)
                print("create subsubsection: " + parts[2])
            else:
                subsubsection = Subsubsection(
                    '%s' % (parts[1]))  # .replace("_", "\_")))
                subsection.append(subsubsection)
                print("create subsubsection: " + parts[1])

            pol = solutions[0][3]
            if solutions[0][3] == 'SAT':
                solutions.sort(key=lambda x: (x[3], x[1]))
                table = Tabular('l|r|l|r|r|r')
                subsubsection.append(table)
                table.add_hline()
                table.add_row(("Config.", 'Status', "#Sol", 'Time(sec)',
                               'Build(sec)', 'Nodes'))
                table.add_hline()
                for i in range(0, len(solutions)):
                    table.add_row(
                        (solutions[i][6], solutions[i][5], solutions[i][0],
                         solutions[i][1], solutions[i][7], solutions[i][2]))
                    coords[solutions[i][6]].append((k, solutions[i][1]))
                table.add_hline()
                table.add_hline()
                # add syb
                if fname in bestever:
                    table.add_row("syb", bestever[fname][0], "--", "--", "--",
                                  "--")
                table.add_hline()
            else:
                # sort for MIN
                type = 'MIN'
                solutions.sort(key=lambda x: (x[3], x[4], x[1]))
                best = solutions[0][4]
                # check first row and last row
                if solutions[0][3] == 'MAX' or solutions[len(solutions) -
                                                         1][3] == 'MAX':
                    solutions.sort(key=lambda x: (x[3], -x[4], x[1]))
                    best = solutions[0][4]
                    type = 'MAX'

                table = Tabular('l|r|l|r|r|r|r')
                subsubsection.append(table)

                table.add_hline()
                table.add_row(("Config.", type, 'Status', "#Sol", 'Time(sec)',
                               'Build(sec)', 'Nodes'))
                table.add_hline()
                for i in range(0, len(solutions)):
                    table.add_row(
                        (solutions[i][6], solutions[i][4], solutions[i][5],
                         solutions[i][0], solutions[i][1], solutions[i][7],
                         solutions[i][2]))
                    if solutions[i][4] == best:
                        coords[solutions[i][6]].append((k, solutions[i][1]))
                    else:
                        coords[solutions[i][6]].append((k, maxtime))
                    if int(solutions[i][0]) > 0:
                        objs[solutions[i][6]].append((k, solutions[i][4]))
                table.add_hline()
                table.add_hline()
                # add syb
                if fname in bestever:
                    if len(bestever[fname]) > 1:
                        table.add_row("syb", bestever[fname][1],
                                      bestever[fname][0], "--", "--", "--",
                                      "--")
                        objs['syb'].append((k, bestever[fname][1]))
                    else:
                        table.add_row("syb", "--", bestever[fname][0], "--",
                                      "--", "--", "--")
                table.add_hline()

            k += 1
        if k > 0:
            self.__addTimePlots(doc, options, coords)
            for o in options:
                coords[o].clear()
            k = 0
            if len(objs) > 0:
                self.__addObjPlots(doc, options, objs, pol)
                for o in objs.keys():
                    objs[o].clear()
コード例 #17
0
ファイル: compare_alg.py プロジェクト: kob22/pracamgr
        scores = []
        # powtarzanie klasyfikacji
        for iteration in range(iterations):
            clf_ = clone(clf)
            # sprawdzian krzyzowy
            testpredict, testtarget = cross_val_pred2ict(clf_,
                                                         db.data,
                                                         db.target,
                                                         cv=folds,
                                                         n_jobs=-1)
            scores.append(accsespf1g(testpredict, testtarget))
            print(str(clf))
            print_scores(testpredict, testtarget)
        # usrednanie wynikow
        avgscores = avgaccsespf1g(scores)
        to_decimal = print_to_latex_two_decimal(avgscores)
        for i, score in enumerate(to_decimal):
            rows[i].append(score)
    for table, row in zip(tables, rows):
        print(row)
        table.add_row(row)
        table.add_hline()

doc = Document("porownanie-meta-metod")
for i, tab, in enumerate(tables):
    section = Section(str(i))
    section.append(tab)
    doc.append(section)
doc.generate_tex(os.path.join(path, 'wyniki/pliki_tex/'))
doc.generate_pdf(os.path.join(path, 'wyniki/pliki_pdf/'))
コード例 #18
0
def GEPP(A, b):

    section = Section('The first section')
    
    n =  len(A)
    if b.size != n:
        raise ValueError("Invalid argument: incompatible sizes between A & b.", b.size, n)
    for k in range(n-1):
        section.append("Considering Column " + (str)(k+1))

        #Choose largest pivot element below (and including) k
        maxindex = abs(A[k:,k]).argmax() + k
        if A[maxindex, k] == 0:
            raise ValueError("Matrix is singular.")
        #Swap rows
        if maxindex != k:
            A[[k,maxindex]] = A[[maxindex, k]]
            b[[k,maxindex]] = b[[maxindex, k]]
        for row in range(k+1, n):
            
            section.append(italic("Row" +(str)(row+1)))
            section.append(Subsection('\t', data=[Math(data=["\tmultiplier", '=', A[row][k], " / ", A[k][k]])]))

            multiplier = A[row][k]/A[k][k]
            multiplier = round(multiplier,2)
            section.append(Math(data=["\t\tmultiplier", '=', multiplier]))
            section.append("\n")
            #the only one in this column since the rest are zero
            section.append("\tapplying multiplier to the row")
            section.append(Math(data=[
                NoEscape("\t\tr_"+(str)(row+1))," - ", multiplier,NoEscape("r_"+(str)(k+1))
            ]))

            for col in range(k, n):
                section.append(Math(data=["\t\t", A[row][col]," - (", multiplier, " x ", A[k][col], ")"]))
                A[row][col] = A[row][col] - multiplier * A[k][col]
                section.append(Math(data=["\t\t\t = ", A[row][col]]))
            #Equation solution column
            b[row] = b[row] - multiplier*b[k]
            section.append(Math(data=["\t\t", b[row]," - (", multiplier, " x ", b[k], ")"]))
            b[row] = b[row] - multiplier * b[k]
            section.append(Math(data=['=', b[row]]))

            section.append(Math(data=['A', '=', Matrix(A)]))
            section.append(Math(data=['b', '=', b]))
            section.append("\n")
    
    section.append("Performing back substitution")
    x = np.zeros(n)
    k = n-1
    x[k] = b[k]/A[k,k]

    section.append(Math(data=[NoEscape("\tr_"+(str)(k+1)),"=", b[k], " / ", A[k,k]]))
    x[k] = round(b[k]/A[k,k],2)
    section.append(Math(data=["\t\t= ", x[k]]))

    k-=1

    while k >= 0:
        eqn = [NoEscape("\tr_"+(str)(k+1)),"=", b[k], " - "]
        eqn.extend(print_dot(A[k,k+1:],x[k+1:]))
        eqn.extend([" / ", A[k,k]])
        section.append(Math(data=eqn))

        x[k] = (b[k] - np.dot(A[k,k+1:],x[k+1:]))/A[k,k]
        section.append(Math(data=["\t\t= ", x[k]]))
        k = k-1
    return x
コード例 #19
0
ファイル: multirow_test.py プロジェクト: Rsullivan00/PyLaTeX
table3.add_row((MultiColumn(2, '|c|', ''), 'X'))
table3.add_hline()
table3.add_row(('X', 'X', 'X'))
table3.add_hline()

table4 = Table('|c|c|c|')
table4.add_hline()
col1_cell = MultiRow(4, '*', 'span-4')
col2_cell = MultiRow(2, '*', 'span-2')
table4.add_row((col1_cell, col2_cell, '3a'))
table4.add_hline(3)
table4.add_row(('', '', '3b'))
table4.add_hline(2)
table4.add_row(('', col2_cell, '3c'))
table4.add_hline(3)
table4.add_row(('', '', '3d'))
table4.add_hline()

test1.append(table1)
test2.append(table2)
test3.append(table3)
test4.append(table4)

section.append(test1)
section.append(test2)
section.append(test3)
section.append(test4)

doc.append(section)
doc.generate_pdf(clean=False)
コード例 #20
0
def generate_loss_wrt_optimum():

    # Creating the document
    from_mode = ''
    doc = Document('latex_tables/generated_loss_wrt_optimum')
    section = Section("Table of Costs")
    from_mode = "{:.2f}"

    # Setting tabular property
    tabular_header = 'cccccc'

    # Creation of the Table
    table = Tabular(tabular_header)
    table.add_row((MultiColumn(6, align='c', data='Costs'), ))
    table.add_hline()
    table.add_hline()
    table.add_row(['ID'] + supported_algorithms)
    table.add_hline()

    # Iterating for each map with respect to the wind
    map_index = 1

    for current_map in maps:
        for current_wind in winds:

            # We catch the correct algorithm to use
            tot_cost_0, _, _ = sweep(current_map,
                                     generate_costs(current_map, current_wind),
                                     plot=False)
            tot_cost_1, _, _ = kNN(generate_costs(current_map, current_wind),
                                   0)
            tot_cost_2, _, _ = opt_kNN(
                generate_costs(current_map, current_wind))
            tot_cost_3, _, _ = nearest_insertion(
                generate_costs(current_map, current_wind))
            tot_cost_4, _, _ = farthest_insertion(
                generate_costs(current_map, current_wind))

            # The row with the data is written onto a new row and the index is incremented
            print(map_index)
            table.add_row(
                (map_index, "{:.2f}".format(
                    ((tot_cost_0 / real_optimum[map_index - 1]) - 1) * 100) +
                 '%', "{:.2f}".format(
                     ((tot_cost_1 / real_optimum[map_index - 1]) - 1) * 100) +
                 '%', "{:.2f}".format(
                     ((tot_cost_2 / real_optimum[map_index - 1]) - 1) * 100) +
                 '%', "{:.2f}".format(
                     ((tot_cost_3 / real_optimum[map_index - 1]) - 1) * 100) +
                 '%', "{:.2f}".format(
                     ((tot_cost_4 / real_optimum[map_index - 1]) - 1) * 100) +
                 '%'))

            map_index += 1

    # We close the table
    table.add_hline()

    # And finally we compose and generate the new document with the embedded table
    section.append(table)
    doc.append(section)
    doc.generate_tex()
コード例 #21
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
__FILENAME__ = example
#!/usr/bin/python

import numpy as np

from pylatex import Document, Section, Subsection, Table, Math, TikZ, Axis, \
    Plot
from pylatex.numpy import Matrix
from pylatex.utils import italic

doc = Document()
section = Section('Yaay the first section, it can even be ' + italic('italic'))

section.append('Some regular text')

math = Subsection('Math that is incorrect', data=[Math(data=['2*3', '=', 9])])

section.append(math)
table = Table('rc|cl')
table.add_hline()
table.add_row((1, 2, 3, 4))
table.add_hline(1, 2)
table.add_empty_row()
table.add_row((4, 5, 6, 7))

table = Subsection('Table of something', data=[table])

section.append(table)

a = np.array([[100, 10, 20]]).T
M = np.matrix([[2, 3, 4],
コード例 #22
0
    def fill(self):
        # with self.doc.create(Section("{} library.".format(self.config['hdl_library_name']))):
        # with self.doc.create(Section("{} library".format(self.periph_lib_name))):
        # main_section = Section("{} library".format(self.periph_lib_name))
        # self.doc.append(LargeText(bold('{} library'.format(self.periph_lib_name))))
        # periph_section = Section("Peripherals", numbering = False)
        # i = 1
        # for periph_name in self.periph_lib['peripherals'].keys():
        # self.doc.append("{} {}".format(str(i), periph_name))
        # i = i+1
        # self.doc.append(NewLine())
        # with self.doc.create(Section("Peripherals")):
        added_instances = []
        # for peri_info in self.config['peripherals']:
        # peri_class = Peripheral(peri_info)
        for periph_name, periph in self.periph_lib['peripherals'].items():
            if periph_name in added_instances:
                continue
            added_instances.append(periph_name)

            # with self.doc.create(Section(periph_name, numbering=True)):
            # with self.doc.create(Subsection(periph_name, numbering=True)):
            # self.doc.append(peri_class.get_kv('peripheral_description').replace('"', ''))
            self.doc.append(NewPage())
            periph_subsection = Section(periph_name, numbering=True)
            periph_subsection.append(periph.get_description().replace(
                '""', ''))

            # Peripheral System Map Table
            periph_subsection.append(NewLine())
            periph_subsection.append(NewLine())
            periph_subsection.append(MediumText(bold('Local Slave Port Map')))
            periph_subsection.append(NewLine())
            periph_subsection.append(NewLine())
            periph_system_table = Tabular('|c|c|c|c|')
            # periph_system_table.add_row((MultiColumn(4,data=MediumText(bold('System Map'))),))
            periph_system_table.add_hline()
            periph_system_table.add_row(
                ('Hex', 'Range (Bytes)', 'Slave Port', 'Protocol'))
            periph_system_table.add_hline()

            # peripheral system address map
            dummyFPGA = FPGA(None)
            dummyFPGA.peripherals.update({periph_name: periph})
            dummyFPGA.create_address_map()
            # for slave in periph.slaves:
            for slave_port, slave_dict in dummyFPGA.address_map.items():
                periph_system_table.add_row(
                    (str(hex(slave_dict['base'])), str(slave_dict['span']),
                     slave_port, slave_dict['type']))
                periph_system_table.add_hline()
            periph_subsection.append(periph_system_table)

            # self.doc.append(periph.get_description().replace('""',''))
            # self.doc.append(NewLine())

            #self.doc.append(MediumText(bold("slave ports.")))

            # for val_info, val_type in ((periph.registers, 'Registers'),
            # (periph.rams, 'Rams'),
            # (periph.fifos, 'Fifos')):
            periph_reg_section = Subsection(
                "{} register slave".format(periph_name), numbering=False)
            periph_reg_table = Tabular('|c|c|c|c|')
            periph_reg_table.add_hline()
            periph_reg_table.add_row(('Base Address', 'Range',
                                      'Register group', 'Number of Slaves'))
            periph_reg_table.add_hline()
            # slave_subsections = ("{} slaves".format(periph_name), numbering=False)
            # slave_subsections = []
            # slave_subsections.append(NewLine())
            # slave_subsections.append(MediumText(bold("Slave Ports for peripheral " + periph_name + "\n")))
            slave_subsections = Subsection(
                "Slave Ports for peripheral \'{}\'".format(periph_name),
                numbering=False)
            for slave in periph.slaves:

                # if len(val_info) == 0: # not sure what this is for
                # continue

                #self.doc.add(text=val_type, size="medium")

                # added_val_types = []
                # for key, val in sorted(val_info.items()):
                # if val.name() in added_val_types:
                # continue
                # added_val_types.append(val.name())
                slave_subsection = Subsection("Slave Port: {} ({})".format(
                    slave.name(),
                    'Register block' if isinstance(slave, Register) else
                    'RAM' if isinstance(slave, RAM) else 'FIFO'),
                                              numbering=True)
                slave_subsection.append(slave.get_kv('slave_description'))
                slave_subsection.append(NewLine())
                # slave_subsection.append("Slave Type: {}".format('REGISTER' if isinstance(slave, Register) else 'RAM' if isinstance(slave, RAM) else 'FIFO'))
                slave_subsection.append(NewLine())
                slave_subsection.append("Address Length: {}".format(
                    str(slave.address_length())))
                slave_subsection.append(NewLine())
                slave_subsection.append("Number of Slaves: {}".format(
                    str(slave.number_of_slaves())))
                slave_subsection.append(NewLine())
                slave_subsection.append(NewLine())

                # if val_type == 'Registers':
                if isinstance(slave, Register):  # expand registers and fields
                    for ram in slave.rams:
                        periph_reg_table.add_row(
                            (str(ram.base_address()),
                             str(ram.number_of_fields() * WIDTH_IN_BYTES),
                             ram.name() + ' (RAM)',
                             str(slave.number_of_slaves())))
                        periph_reg_table.add_hline()
                    periph_reg_table.add_row(
                        (str(slave.base_address()),
                         str(slave.address_length()), slave.name(),
                         str(slave.number_of_slaves())))
                    periph_reg_table.add_hline()
                    added_field_groups = []
                    # with self.doc.create(Subsection("{} Register Fields".format(val.name().lower()), numbering=True)):
                    # if val.get_kv('slave_description') is not None:
                    # slave_subsection.append(val.get_kv('slave_description').replace('"', ''))

                    # generate register table i.e. by word
                    group_address = -1
                    group_list = []
                    for field in slave.fields:
                        if field.address_offset() != group_address:
                            group_address = field.address_offset()
                            group_list.append(field)
                            # addr_name = field.group_name() if field.group_name() != "None" else field.name()

                            # slave_table.add_row(str(hex(field.address_offset())), addr_name)
                            # slave_table.add_hline()
                    c_max_rows = 30
                    nof_cols = ceil(
                        len(group_list) / c_max_rows
                    )  # register table has max length of c_max_rows
                    nof_rows = min(len(group_list), c_max_rows)
                    slave_table = Tabular('|c|c|' * nof_cols)
                    slave_table.add_hline()
                    slave_table.add_row(['Hex', 'Field Group'] * nof_cols)
                    # slave_table.add_row((*['Hex','Field Group']*nof_cols))
                    slave_table.add_hline()
                    for i in range(nof_rows):
                        row = []
                        for j in range(nof_cols):
                            if i + c_max_rows * j < len(group_list):
                                field.group_name() if field.group_name(
                                ) != "None" else field.name()
                                row.extend([
                                    str(
                                        hex(group_list[i + c_max_rows *
                                                       j].address_offset())),
                                    group_list[i + c_max_rows * j].name()
                                ])
                            else:
                                row.extend(['', ''])
                        slave_table.add_row(row)
                        # slave_table.add_row(*row)
                        slave_table.add_hline()

                    slave_subsection.append(slave_table)
                    slave_subsection.append(NewPage())

                    group_address = -1
                    for field in slave.fields:
                        # if field.group_name() is None or field.group_name() != last_group: # base on group_address instead
                        # print("field {} address {} bit{}".format(field.name(), str(field.address_offset()), str(field.bit_offset())))
                        if field.address_offset() != group_address:
                            group_address = field.address_offset()
                            # group_page = MiniPage()
                            group_subsection = Subsection('{} {}'.format(
                                str(hex(field.address_offset())),
                                field.name() if field.group_name() == 'None'
                                else field.group_name()),
                                                          numbering=False)
                            group_fields = [
                                field for field in slave.fields
                                if field.address_offset() == group_address
                            ]
                            if len(group_fields) > 10:
                                slave_subsection.append(NewPage())
                            group_subsection = gen_reg_tables(
                                group_subsection, group_fields)
                            for field in group_fields[::-1]:
                                field_name = field.name() if field.group_name(
                                ) == 'None' else field.name().split(
                                    field.group_name() + '_')[-1]
                                bit_string = "Bit {}".format(
                                    str(field.bit_offset())) if field.width(
                                    ) == 1 else "Bits {}:{}".format(
                                        str(field.bit_offset() +
                                            field.width() -
                                            1), str(field.bit_offset()))
                                group_subsection.append(
                                    bold("{}\t\t{} ({}):".format(
                                        bit_string, field_name,
                                        field.access_mode())))
                                group_subsection.append("\t\t{}".format(
                                    field.field_description()))
                                group_subsection.append(NewLine())
                                group_subsection.append(NewLine())
                            # group_page.append(group_subsection)
                            slave_subsection.append(group_subsection)
                else:  # RAM or FIFO
                    slave_subsection.append("Data width: {}".format(
                        slave.width()))
                    slave_subsection.append(NewLine())
                    if isinstance(slave, RAM):
                        slave_subsection.append("User data width: {}".format(
                            slave.user_width()))

                slave_subsections.append(slave_subsection)
            periph_reg_section.append(periph_reg_table)
            self.doc.append(periph_subsection)
            if any([isinstance(slave, Register) for slave in periph.slaves]):
                self.doc.append(periph_reg_section)
            # for i in range(len(slave_subsections)):
            # self.doc.append(slave_subsections[i])
            self.doc.append(slave_subsections)

            # self.doc.append(periph_section)
            self.doc.append(NewPage())
コード例 #23
0
ファイル: pictures.py プロジェクト: sovelten/PyLaTeX
#!/usr/bin/env python

from pylatex import Document, Section
from pylatex.graphics import Figure

doc = Document()
section = Section('Multirow Test')
figure = Figure()
figure.add_image('docs/static/screenshot.png')
figure.add_caption('Whoooo an imagage of a pdf')
section.append(figure)
doc.append(section)

doc.generate_pdf()
コード例 #24
0
def generate_tables(args):

    if args.change_directory:
        os.chdir(args.change_directory)

    config = load_experiments_config(args.config, args)

    exps = Experiment.load_all(config.experiments,
                               config_file=args.config,
                               base_path=config.options.base_path,
                               cache_dir=config.options.cache_dir,
                               seq_name_mapping=config.seq_name_mapping)

    doc = Document(geometry_options={"tmargin": "1cm", "lmargin": "1cm"})

    export_basepath = "{}-export".format(config.options.output_path)

    curr = doc

    hide_all = False
    for spec in config.results:
        if spec.show:

            if spec["class"] == "section":
                if spec.clearpage:
                    curr.append(NewPage())
                if spec.pagewidth:
                    curr.append(
                        Command("SetPageScreenWidth",
                                Arguments(spec.pagewidth)))
                else:
                    curr.append(Command("RestorePageScreenWidth"))
                hide_all = False
                curr = Section(spec.name)
                doc.append(curr)
                continue

            if hide_all:
                continue

            if spec.clearpage:
                curr.append(NewPage())

            elif spec["class"] == "results_table":
                elem = ResultsTable(
                    exps,
                    spec,
                    show_values_failed_runs=config.options.
                    show_values_failed_runs,
                    seq_displayname_mapping=config.seq_displayname_mapping,
                    export_basepath=export_basepath)
            elif spec["class"] == "summarize_sequences_table":
                elem = SummarizeSequencesTable(
                    exps,
                    spec,
                    show_values_failed_runs=config.options.
                    show_values_failed_runs,
                    seq_displayname_mapping=config.seq_displayname_mapping,
                    export_basepath=export_basepath)
            elif spec["class"] == "plot":
                elem = Plot(
                    exps,
                    spec,
                    seq_displayname_mapping=config.seq_displayname_mapping,
                    export_basepath=export_basepath)
            else:
                raise RuntimeError("Invalid results class {}".format(
                    spec["class"]))

            curr.append(elem)
        else:
            if spec["class"] == "section":
                hide_all = True
                continue

    # generate auxiliary tex files
    if config.options.screenread:
        output_dir = os.path.dirname(config.options.output_path)
        screenread_path = output_dir + "/screenread.sty"
        with open(screenread_path, "w") as f:
            f.write(screenread_sty)
        doc.packages.add(Package('screenread'))

    # create nofloatfigure environment
    doc.preamble.append(
        Command(
            "newenvironment",
            Arguments("nofloatfigure",
                      Command("captionsetup", Arguments(type="figure")), "")))
    doc.packages.add(Package('caption'))
    doc.packages.add(Package('mathtools'))

    # render latex
    doc.generate_pdf(config.options.output_path,
                     clean_tex=not args.dont_clean_tex)

    # cleanup
    if config.options.screenread and not args.dont_clean_tex:
        os.remove(screenread_path)

    # open the generated pdf
    if args.open:
        os_open_file(config.options.output_path + ".pdf")
コード例 #25
0
        if solutions[0][3] == 'MIN':
            gbest = min(gbest, solutions[i][4])
        else:
            gbest = max(gbest, solutions[i][4])

    if p > 0:
        proof += 1
    if b > 0:
        fbest += 1
    if gtime < maxtime:
        tbest += 1
table.add_hline()
table.add_row(('VBS', proof, fbest, tbest))

table.add_hline()
section.append(table)


# Third problem per problem
k = 0
for fname in fnames:
    parts = fname.split("+")
    solutions = optPerSol[fname]
    if parts[0] != presec:
        presec = parts[0]
        if k > 0:
            addPlots(doc, options, coords)
            for o in options:
                coords[o].clear()
            k = 0
        section = Section('%s' % (presec.replace("_", "\_")))
コード例 #26
0
ファイル: example.py プロジェクト: ChrisStevens/PyLaTeX
#!/usr/bin/python3

import numpy as np

from pylatex import Document, Section, Subsection, Table, Math
from pylatex.numpy import Matrix
from pylatex.utils import italic

doc = Document()
section = Section('Yaay the first section, it can even be ' + italic('italic'))

section.append('Some regular text')

math = Subsection('Math', data=[Math(data=['2*3', '=', 6])])

section.append(math)
table = Table('rc|cl')
table.add_hline()
table.add_row((1, 2, 3, 4))
table.add_hline(1, 2)
table.add_empty_row()
table.add_row((4, 5, 6, 7))

table = Subsection('Table of something', data=[table])

section.append(table)

a = np.array([[100, 10, 20]]).T
M = np.matrix([[2, 3, 4],
               [0, 0, 1],
               [0, 0, 2]])
コード例 #27
0
def generate_table_all_16(algorithm):

    # If the algorithm is not supported we do not create anything
    if algorithm not in supported_algorithms:
        print("We cannot generate the table!")
    else:
        # Creating the document
        doc = Document('latex_tables/generated_table_all_16_' + algorithm)
        section = Section(algorithm_name_dict[algorithm] + " Table")

        # Creation of the Table
        table = Tabular('ccc')
        table.add_row((MultiColumn(3,
                                   align='c',
                                   data=algorithm_name_dict[algorithm]), ))
        table.add_hline()
        table.add_hline()
        table.add_row(("ID", "Soluzione", "Tempo"))
        table.add_hline()

        # Iterating for each map with respect to the wind
        map_index = 1
        for current_map in maps:
            for current_wind in winds:
                tot_cost = 0
                tot_time = 0

                # We catch the correct algorithm to use
                if algorithm == 'sweep':
                    tot_cost, tot_time, path = sweep(current_map,
                                                     generate_costs(
                                                         current_map,
                                                         current_wind),
                                                     plot=False)

                if algorithm == 'knn':
                    tot_cost, tot_time, path = kNN(
                        generate_costs(current_map, current_wind), 0)

                if algorithm == 'knn-opt':
                    tot_cost, tot_time, path = opt_kNN(
                        generate_costs(current_map, current_wind))

                if algorithm == 'nearest_insertion':
                    tot_cost, tot_time, path = nearest_insertion(
                        generate_costs(current_map, current_wind))

                if algorithm == 'farthest_insertion':
                    tot_cost, tot_time, path = farthest_insertion(
                        generate_costs(current_map, current_wind))

                # The row with the data is written onto a new row and the index is incremented
                table.add_row((map_index, "{:.2f}".format(tot_cost),
                               "{:.2e}".format(tot_time)))
                map_index += 1

        # We close the table
        table.add_hline()

        # And finally we compose and generate the new document with the embedded table
        section.append(table)
        doc.append(section)
        doc.generate_tex()
コード例 #28
0
def generate_latex(results_list):
    doc = Document("LatexTables")
    section = Section('LatexTables')
    subsection = Subsection('Tables')

    ############################
    #######EVALUATION 1#########
    ############################
    table1 = Tabular('|c|c|c|c|c|c|c|c|c|c|')
    table1.add_hline()
    table1.add_row(
        'percentile',
        (MultiColumn(3, align='|c|', data='Model_A')),
        (MultiColumn(3, align='|c|', data='Model_B')),
        (MultiColumn(3, align='|c|', data='Model_C')),
    )
    table1.add_hline()
    table1.add_row(('', 'T', 'O', 'R', 'T', 'O', 'R', 'T', 'O', 'R'))
    table1.add_hline()
    table1.add_row((90, 1, 2, 3, 4, 5, 6, 7, 8, 9))
    table1.add_hline()
    table1.add_row((95, 1, 2, 3, 4, 5, 6, 7, 8, 9))
    table1.add_hline()
    row_cells = (99, 1, 2, 3, 4, 5, 6, 7, 8, 9)
    #row_cells = ('9', MultiColumn(3, align='|c|', data='Multicolumn not on left'))
    table1.add_row(row_cells)
    table1.add_hline()

    ############################
    #######EVALUATION 2#########
    ############################
    table2 = Tabular('|c|c|c|c|c|c|c|c|c|c|')
    table2.add_hline()
    table2.add_row(
        'distance',
        (MultiColumn(3, align='|c|', data='Model_A')),
        (MultiColumn(3, align='|c|', data='Model_B')),
        (MultiColumn(3, align='|c|', data='Model_C')),
    )

    table2.add_hline()
    table2.add_row(('', 'T', 'O', 'R', 'T', 'O', 'R', 'T', 'O', 'R'))
    table2.add_hline()
    table2.add_row((0.2, 1, 2, 3, 4, 5, 6, 7, 8, 9))
    table2.add_hline()
    table2.add_row((0.1, 1, 2, 3, 4, 5, 6, 7, 8, 9))
    table2.add_hline()
    table2.add_row((0.05, 1, 2, 3, 4, 5, 6, 7, 8, 9))
    table2.add_hline()
    row_cells = (0.01, 1, 2, 3, 4, 5, 6, 7, 8, 9)
    #row_cells = ('9', MultiColumn(3, align='|c|', data='Multicolumn not on left'))
    table2.add_row(row_cells)
    table2.add_hline()

    subsection.append(table1)
    subsection.append(table2)

    section.append(subsection)

    doc.append(section)
    doc.generate_pdf(clean_tex=False)
コード例 #29
0
ファイル: no_list_as_data.py プロジェクト: Hydex/PyLaTeX
from pylatex import Document, Section, Subsection
from pylatex.command import Command

doc = Document()
sub_sec1 = Subsection('Only a single string', data='Some words')

sec1 = Section('Only contains one subsection', data='Subsection')

sec2 = Section('Only a single italic command', data=Command('textit', 'Hey'))
sec2.append('something else that is not italic')
doc.append(sec1)
doc.append(sec2)

doc.generate_pdf()
コード例 #30
0
def GENP(A, b):
    
    section = Section('The first section')

    n =  len(A)
    if b.size != n:
        raise ValueError("Invalid argument: incompatible sizes between A & b.", b.size, n)
    for pivot_row in range(n-1):
        section.append("Considering Column " + (str)(pivot_row+1))

        for row in range(pivot_row+1, n):
            section.append(italic("Row" +(str)(row+1)))
            section.append(Subsection('\t', data=[Math(data=["\tmultiplier", '=', A[row][pivot_row], " / ", A[pivot_row][pivot_row]])]))

            multiplier = A[row][pivot_row]/A[pivot_row][pivot_row]
            multiplier = round(multiplier,2)
            section.append(Math(data=["\t\tmultiplier", '=', multiplier]))
            section.append("\n")
            #the only one in this column since the rest are zero
            section.append("\tapplying multiplier to the row")
            section.append(Math(data=[
                NoEscape("\t\tr_"+(str)(row+1))," - ", multiplier,NoEscape("r_"+(str)(pivot_row+1))
            ]))

            for col in range(pivot_row, n):
                section.append(Math(data=["\t\t", A[row][col]," - (", multiplier, " x ", A[pivot_row][col], ")"]))
                A[row][col] = A[row][col] - multiplier * A[pivot_row][col]
                section.append(Math(data=["\t\t\t = ", A[row][col]]))
            #Equation solution column
            section.append(Math(data=["\t\t", b[row]," - (", multiplier, " x ", b[pivot_row], ")"]))
            b[row] = b[row] - multiplier * b[pivot_row]
            section.append(Subsection('\t\t\t', data=[Math(data=['=', b[row]])]))

            section.append(Math(data=['A', '=', Matrix(A)]))
            section.append(Math(data=['b', '=', b]))
            section.append("\n")

    section.append("Performing back substitution")
    x = np.zeros(n)
    k = n-1

    section.append(Math(data=[NoEscape("\tr_"+(str)(k+1)),"=", b[k], " / ", A[k,k]]))
    x[k] = round(b[k]/A[k,k],2)
    section.append(Math(data=["\t\t= ", x[k]]))

    k-=1

    while k >= 0:
        eqn = [NoEscape("\tr_"+(str)(k+1)),"=", b[k], " - "]
        eqn.extend(print_dot(A[k,k+1:],x[k+1:]))
        eqn.extend([" / ", A[k,k]])
        section.append(Math(data=eqn))

        x[k] = round((b[k] - np.dot(A[k,k+1:],x[k+1:]))/A[k,k],2)
        section.append(Math(data=["\t\t= ", x[k]]))
        k = k-1

    return section
コード例 #31
0
    def visualize_zeta(self,
                       doc,
                       zeta_edge_pair_results,
                       path,
                       top_n_results=10):
        # def visualize_zeta(self, edge_pair_result, top_n_results=10):

        section = Section("Zeta Scores for Pairs with highest edge weights")
        section.append(
            "Zeta score is a stylometry measure that measures preferred and avoided terms in the context of character pairs."
        )

        for index, edge_pair_result in enumerate(zeta_edge_pair_results):
            #features().visualize_zeta(zeta_results[index], name_for_figure="zeta_pair_%s" %index, path=dirpath)

            #subsection = Subsection("Zeta Scores for Pairs with highest edge weights", numbering=False)

            subsection = Subsection("Edge Pair: %s -- %s" %
                                    (edge_pair_result["name_target"],
                                     edge_pair_result["name_comparison"]),
                                    numbering=False)

            #Target (Character A)

            # the following index [::-1] inverts the list for the figure
            objects = [
                el[0] for el in edge_pair_result["zeta_scores_target_sorted"]
                [0:top_n_results]
            ][::-1]
            y_pos = np.arange(len(objects))
            performance = [
                el[1] for el in edge_pair_result["zeta_scores_target_sorted"]
                [0:top_n_results]
            ][::-1]

            plt.barh(y_pos, performance, align='center', alpha=0.5)
            plt.yticks(y_pos, objects)
            plt.xlabel('Zeta Score')
            plt.title('%s-context' % edge_pair_result["name_target"])
            # plt.show()
            # plt.savefig("zeta.pdf", bbox_inches='tight')

            #print(path)
            plt.savefig("%s/zeta_pair_%s_a_target.pdf" % (path, index),
                        bbox_inches='tight')

            target_pic = Figure(position="H")
            target_pic.add_image(os.path.join(
                path, "zeta_pair_%s_a_target.pdf" % index),
                                 width='240px')
            target_pic.add_caption(
                "Prefered terms in context of %s (compared to %s)" %
                (edge_pair_result["name_target"],
                 edge_pair_result["name_comparison"]))
            #wordcloud_pic.add_caption('word cloud of "%s -- %s"' % (

            subsection.append(target_pic)

            ################ Comparison (Character B)

            objects = [
                el[0]
                for el in edge_pair_result["zeta_scores_comparison_sorted"]
                [0:top_n_results]
            ][::-1]
            y_pos = np.arange(len(objects))
            performance = [
                el[1]
                for el in edge_pair_result["zeta_scores_comparison_sorted"]
                [0:top_n_results]
            ][::-1]

            plt.barh(y_pos, performance, align='center', alpha=0.5)
            plt.yticks(y_pos, objects)
            plt.xlabel('Zeta Score')
            plt.title('%s-context' % edge_pair_result["name_comparison"])
            # plt.show()
            # plt.savefig("zeta.pdf", bbox_inches='tight')
            plt.savefig("%s/zeta_pair_%s_b_comparison.pdf" % (path, index),
                        bbox_inches='tight')

            comparison_pic = Figure(position="H")
            comparison_pic.add_image(os.path.join(
                path, "zeta_pair_%s_b_comparison.pdf" % index),
                                     width='240px')
            comparison_pic.add_caption(
                "Prefered terms in context of %s (compared to %s)" %
                (edge_pair_result["name_comparison"],
                 edge_pair_result["name_target"]))

            subsection.append(comparison_pic)

            #subsection.append(subsubsection)

            section.append(subsection)
        doc.append(section)
コード例 #32
0
    def generate(self, clean_tex=True):
        """
        Generates the document and saves it to disk

        Args:.path
          * clean_tex (bool): whether to delete the .tex file after
            compiling
        """
        HEADER = open(param_all.Pathing('ctrl', 'mgmt', 'header.tex').path,
                      mode='r').read()
        HEADER2 = open(param_all.Pathing('ctrl', 'mgmt', 'header-2.tex').path,
                       mode='r').read()
        doc = Document(self.docname)
        for k, v in REPL.items():
            HEADER = HEADER.replace(k, v)
            HEADER2 = HEADER2.replace(k, v)
        doc.preamble.append(NoEscape(HEADER))
        doc.append(NoEscape(HEADER2))
        section = Section('Principles')
        section.append(
            """The Telecommand (TC) and Telemetry (TM) packets format specifications are based on the CCSDS format: the concatenation of a primary header, secondary header, (optional) auxiliary header, (optional) data field.

TC are composed of a 6 octets primary header and a 18 octets secondary header. There is no auxiliary header. The data field contains values which depend on the command ID, that are treated by the satelite as input parameters.

TM are composed of a 6 octets primary header and a 6 octets secondary header. The TM category defines what type of TM is transmitted (e.g. beacon, house keeping) and how the auxiliary header and data field are encoded.

This document covers the content of headers for TC, and headers and data fields for TM.

This documents does not cover the content of data field for TC, and the content of auxiliary header and data fields for the TM category 'TC Answer'. This information is available in the dedicated TC-TM communication document."""
        )
        doc.append(section)
        # Telecommands
        section = Section('Telecommands')
        subsection = self._trousseau2subsection('Primary Header',
                                                param_ccsds.HEADER_P_KEYS)
        section.append(subsection)
        subsection = self._trousseau2subsection(
            'Secondary Header', param_ccsds.HEADER_S_KEYS_TELECOMMAND)
        section.append(subsection)
        subsection = self._TCauxHeader()
        section.append(subsection)
        doc.append(section)
        # Telemetries
        section = Section('Telemetries')
        subsection = self._trousseau2subsection('Primary Header',
                                                param_ccsds.HEADER_P_KEYS)
        section.append(subsection)
        subsection = self._trousseau2subsection(
            'Secondary Header', param_ccsds.HEADER_S_KEYS_TELEMETRY)
        section.append(subsection)
        subsection = self._TMauxHeader()
        section.append(subsection)
        doc.append(section)
        # Packet Categories
        sectionname = {
            0: 'Packet Categories for OBC',
            1: 'Packet Categories for Payload'
        }
        for idx, pldflag in ([0, False], [1, True]):
            section = Section(sectionname[idx])
            for catnum, cat in param_category.\
                                    CATEGORIES[idx].items():
                subsection = self._trousseau2subsection(
                    '{} ({:d}) - Auxiliary Header'.format(cat.name, catnum),
                    cat.aux_trousseau,
                    catnum=catnum,
                    pldflag=pldflag)
                section.append(subsection)
                # case of TC answer, dedicated doc
                if catnum == param_category.TELECOMMANDANSWERCAT:
                    subsection = Subsection('{} ({:d}) - Data'\
                                                .format(cat.name, catnum))
                    subsection.append("Refer to the dedicated TC-TM "\
                                      "communication document")
                    section.append(subsection)
                # case of meta-trousseau
                elif isinstance(cat.data_trousseau, CCSDSMetaTrousseau):
                    for mtpart, mtT in cat.data_trousseau.TROUSSEAUDIC.items():
                        subsection = self._trousseau2subsection(
                            '{} ({:d}) [part {:d}] - Data'.format(
                                cat.name, catnum, mtpart),
                            mtT,
                            catnum=catnum,
                            pldflag=pldflag)
                        section.append(subsection)
                else:  # normal case
                    subsection = self._trousseau2subsection(
                        '{} ({:d}) - Data'.format(cat.name, catnum),
                        cat.data_trousseau,
                        catnum=catnum,
                        pldflag=pldflag)
                    section.append(subsection)
            doc.append(section)
        self._compile(doc, clean_tex=clean_tex)
コード例 #33
0
#!/usr/bin/env python

from pylatex import Document, Section
from pylatex.utils import escape_latex

doc = Document(default_filename="utils_escape_latex")
section = Section('Escape LaTeX characters test')

text = escape_latex('''\
& (ampersand)
% (percent)
$ (dollar)
# (number)
_ (underscore)
{ (left curly brace)
} (right curly brace)
~ (tilde)
^ (caret)
\\ (backslash)
--- (three minuses)
a\xA0a (non breaking space)
''')

section.append(text)
doc.append(section)

doc.generate_pdf()
コード例 #34
0
ファイル: PDFCreator.py プロジェクト: sbahrin3/choco-solver
    def __sybil(self, doc, options, optPerSol, fnames, maxtime, bestever):
        # Second summary
        section = Section('Summary : %d problems, %d configurations.' %
                          (len(fnames), len(options)))
        doc.append(section)
        table = Tabular('|l||c|c||c|c||c|')
        table.color = True  # to deal with colors in table

        table.add_hline()
        table.add_row(("", MultiColumn(2, align='c||', data="CSP"),
                       MultiColumn(2, align='c||', data='COP'), "Times best"))
        table.add_row(
            ("Config.", 'sat', "unsat", "best", "proof", "< %.1f" % maxtime))
        table.add_hline()
        for opt in options:
            sat = 0
            unsat = 0
            proof = 0
            fbest = 0
            tbest = 0
            for fname in fnames:
                print(opt + '->' + fname)
                solutions = optPerSol[fname]
                if len(solutions) == 0:
                    continue
                gbest = solutions[0][4]
                mybest = gbest
                gtime = solutions[0][1]
                mytime = gtime
                b = 0
                for i in range(0, len(solutions)):
                    if solutions[i][6] == opt:
                        if solutions[i][5] == 'proof':
                            proof += 1
                            b += 1
                            if solutions[i][3] is 'SAT':
                                if int(solutions[i][0]) == 0:
                                    unsat += 1
                                elif int(solutions[i][0]) == 1:
                                    sat += 1
                        elif solutions[i][5] != 'unknown':
                            b += 1
                        mybest = solutions[i][4]
                        mytime = solutions[i][1]
                    gtime = min(gtime, solutions[i][1])
                    if solutions[0][3] is 'MIN':
                        gbest = min(gbest, solutions[i][4])
                    elif solutions[0][3] is 'MAX':
                        gbest = max(gbest, solutions[i][4])
                if gbest == mybest and b > 0:
                    fbest += 1
                if gtime == mytime and mytime < maxtime:
                    tbest += 1
            table.add_row((opt, sat, unsat, fbest, proof, tbest), color=opt)
        # now VBS
        sat = 0
        unsat = 0
        proof = 0
        fbest = 0
        tbest = 0
        for fname in fnames:
            solutions = optPerSol[fname]
            if len(solutions) == 0:
                continue
            gbest = solutions[0][4]
            gtime = solutions[0][1]
            p = 0
            b = 0
            for i in range(0, len(solutions)):
                if solutions[i][5] == 'proof':
                    p += 1
                    b += 1
                    if solutions[i][3] is 'SAT':
                        if int(solutions[i][0]) == 0:
                            unsat += 1
                        elif int(solutions[i][0]) == 1:
                            sat += 1
                elif solutions[i][5] != 'unknown':
                    b += 1
                gtime = min(gtime, solutions[i][1])
                if solutions[0][3] is 'MIN':
                    gbest = min(gbest, solutions[i][4])
                elif solutions[0][3] is 'MAX':
                    gbest = max(gbest, solutions[i][4])

            if p > 0:
                proof += 1
            if b > 0:
                fbest += 1
            if gtime < maxtime:
                tbest += 1
        table.add_hline()
        table.add_hline()
        table.add_row(('VBS', sat, unsat, fbest, proof, tbest))
        # now Sybille
        sat = 0
        unsat = 0
        proof = 0
        fbest = 0
        for fname in fnames:
            if fname in bestever:
                if len(bestever[fname]) > 1:
                    fbest += 1
                if 'C' in bestever[fname][0]:
                    proof += 1
        table.add_hline()
        table.add_hline()
        table.add_row(('syb', sat, unsat, fbest, proof, "--"))

        table.add_hline()
        section.append(table)
コード例 #35
0
ファイル: pictures.py プロジェクト: jornpeters/PyLaTeX
#!/usr/bin/env python

from pylatex import Document, Section
from pylatex.graphics import Figure

doc = Document()
section = Section("Multirow Test")
figure = Figure()
figure.add_image("docs/static/screenshot.png")
figure.add_caption("Whoooo an imagage of a pdf")
section.append(figure)
doc.append(section)

doc.generate_pdf()
コード例 #36
0
ファイル: PDFCreator.py プロジェクト: sbahrin3/choco-solver
    def __detailsXCSP(self, doc, options, optPerSol, fnames, maxtime,
                      bestever):
        section = Section('Details')
        doc.append(section)
        print("create section: \"Details\"")

        coords = {}
        objs = {}
        for o in options:
            coords[o] = []
            objs[o] = []
        objs['syb'] = []
        # Third problem per problem
        k = 0
        for fname in fnames:
            solutions = optPerSol[fname]
            if len(solutions) == 0:
                continue
            subsection = Subsection('%s' % (fname))  # .replace("_", "\_")))
            section.append(subsection)
            print("create subsection: " + fname)
            if solutions[0][3] == 'SAT':
                solutions.sort(key=lambda x: (x[3], x[1]))
                table = Tabular('l|r|l|r|r|r')
                table.color = True  # to deal with colors in table
                subsection.append(table)
                table.add_hline()
                table.add_row(("Config.", 'Status', "#Sol", 'Time(sec)',
                               'Build(sec)', 'Nodes'))
                table.add_hline()
                for i in range(0, len(solutions)):
                    table.add_row(
                        (solutions[i][6], solutions[i][5], solutions[i][0],
                         solutions[i][1], solutions[i][7], solutions[i][2]),
                        color=solutions[i][6])
                    coords[solutions[i][6]].append((k, solutions[i][1]))
                table.add_hline()
                table.add_hline()
                # add syb
                if fname in bestever:
                    table.add_row("syb", bestever[fname][0], "--", "--", "--",
                                  "--")
                table.add_hline()
            else:
                # sort for MIN
                type = 'MIN'
                solutions.sort(key=lambda x: (x[3], x[4], x[1]))
                best = solutions[0][4]
                # check first row and last row
                if solutions[0][3] == 'MAX' or solutions[len(solutions) -
                                                         1][3] == 'MAX':
                    solutions.sort(key=lambda x: (x[3], -x[4], x[1]))
                    best = solutions[0][4]
                    type = 'MAX'

                table = Tabular('l|r|l|r|r|r|r')
                table.color = True  # to deal with colors in table
                subsection.append(table)

                table.add_hline()
                table.add_row(("Config.", type, 'Status', "#Sol", 'Time(sec)',
                               'Build(sec)', 'Nodes'))
                table.add_hline()
                for i in range(0, len(solutions)):
                    table.add_row(
                        (solutions[i][6], solutions[i][4], solutions[i][5],
                         solutions[i][0], solutions[i][1], solutions[i][7],
                         solutions[i][2]),
                        color=solutions[i][6])
                    if solutions[i][4] == best:
                        coords[solutions[i][6]].append((k, solutions[i][1]))
                    else:
                        coords[solutions[i][6]].append((k, maxtime))
                    if int(solutions[i][0]) > 0:
                        objs[solutions[i][6]].append((k, solutions[i][4]))
                table.add_hline()
                table.add_hline()
                # add syb
                if fname in bestever:
                    if len(bestever[fname]) > 1:
                        table.add_row("syb", bestever[fname][1],
                                      bestever[fname][0], "--", "--", "--",
                                      "--")
                        objs['syb'].append((k, bestever[fname][1]))
                    else:
                        table.add_row("syb", "--", bestever[fname][0], "--",
                                      "--", "--", "--")
                table.add_hline()

            # self.__addTimePlots(doc, options, coords)
            for o in options:
                coords[o].clear()
コード例 #37
0
__author__ = 'Michael'

from  final_ode_8_com_plot_2 import  Respostas

from pylatex import Document,Section,Subsection,Table,Math,Plot


doc = Document()

section = Section("Este e o primeiro relatorio em PDF para eqs diferenciais v01:")

section.append("Importante notar que essa bagaca esta em fase de testes, pode bugar tudo")


doc.append(section)

doc.generate_pdf()





コード例 #38
0
    def write_word_cloud(self,
                         doc,
                         dta_holder,
                         tpath,
                         number_of_wc,
                         head_of_file_name="wordcloud",
                         wc_context_selection="MFW",
                         words_in_word_cloud=12):

        # import float package for -> Figure(position="H")
        doc.packages.append(Package('float'))

        #section = Section("Word Cloud for character pairs", numbering=True)

        if wc_context_selection == "PMI":
            section = Section(
                "Word Cloud for character pairs (method: pointwise mutual information",
                numbering=True)
            section.append(
                "These word clouds were constructed based on pointwise mutual information (PMI). PMI is a measure of how strongly each term is associated with the character pair. "
            )
        if wc_context_selection == "MFW":
            section = Section(
                "Word Cloud for character pairs (method: most frequent contexts words",
                numbering=True)
            section.append(
                "These word clouds were constructed based on most frequent words. They show the most frequent words that appear in the context of the character pair. "
            )

        network_parameters = dta_holder["network_parameters"]
        edge_weights = network_parameters[6]
        edge_weights_sorted = sorted(edge_weights,
                                     key=operator.itemgetter(2),
                                     reverse=True)

        ### here we iterate over all context_terms in "character_relations_context"
        ### it is done with the index since a numbering for the word cloud file is necessary
        # for relation in dta_holder["character_relations_context"]:

        if wc_context_selection == "PMI":
            #print(dta_holder["character_relations_context"])
            PMI_all_pairs = features().PMI(
                context_words=dta_holder["character_relations_context"])
            #print(PMI_all_pairs[0:3])
            # for i in PMI_all_pairs[0:3]:
            #     print(i)

            for edge_pair_list in edge_weights_sorted[0:number_of_wc]:
                for index, character_context_dic in enumerate(PMI_all_pairs):
                    #print(index)
                    if character_context_dic["character_names"][
                            0] == edge_pair_list[0] and character_context_dic[
                                "character_names"][1] == edge_pair_list[1]:
                        #print(index, character_context_dic["character_names"], character_context_dic["PMI"])

                        if len(character_context_dic["PMI"]
                               [0:words_in_word_cloud]) == 0:
                            text_string = "<<empty_word_cloud>>"
                        if len(character_context_dic["PMI"]
                               [0:words_in_word_cloud]) > 0:
                            text_string = str()
                            # for word_freq_tuple in relation["tf_sorted_list"][0:10]:
                            #print(index,character_context_dic["character_names"],character_context_dic["PMI"][0:12])
                            for word_freq_list in character_context_dic["PMI"][
                                    0:words_in_word_cloud]:

                                if round(word_freq_list[1]) < 10:
                                    if round(word_freq_list[1]) > 0:
                                        for i in range(round(
                                                word_freq_list[1])):
                                            text_string += "%s " % word_freq_list[
                                                0]
                                    if round(word_freq_list[1]) <= 0:
                                        text_string += "%s " % word_freq_list[0]

                                if round(word_freq_list[1]) >= 10:
                                    for i in range(9):
                                        text_string += "%s " % word_freq_list[0]

                            #print(text_string)

                        word_cloud.generate_wordcloud_simple(
                            text=text_string,
                            ending_number=index,
                            temppath=tpath,
                            file_name_head=head_of_file_name)
                        # wc = word_cloud.generate_wordcloud_simple(text=str(text_string))

                        #######

                        wordcloud_pic = Figure(position="H")
                        wordcloud_pic.add_image(
                            os.path.join(tpath, "wordcloud%s.png" % index),
                            width='240px')  # , placement="center")
                        # wordcloud_pic.add_image(wc, width='240px')#, placement="center")

                        # wordcloud_pic.add_caption('word cloud of "%s -- %s"' % (relation["character_names"][0], relation["character_names"][1]))
                        wordcloud_pic.add_caption(
                            'word cloud of "%s -- %s"' %
                            (dta_holder["character_relations_context"][index]
                             ["character_names"][0],
                             dta_holder["character_relations_context"][index]
                             ["character_names"][1]))

                        # subs.append(wordcloud_pic)
                        # section.append(subs)

                        section.append(wordcloud_pic)

            doc.append(section)

        if wc_context_selection == "MFW":

            #BETTER WITH ENUMERATE (CHANGE, IF HAVE SOME TIME)
            # for edge_pair_list in edge_weights_sorted[0:number_of_wc]:
            #     for index, character_context_dic in enumerate(dta_holder["character_relations_context"]):
            #         #print(index)
            #         if character_context_dic["character_names"][0] == edge_pair_list[0] and character_context_dic["character_names"][1] == edge_pair_list[1]:
            #             print(index, character_context_dic["character_names"], character_context_dic["tf_sorted_list"])
            #

            for edge_pair_list in edge_weights_sorted[0:number_of_wc]:

                for index in range(
                        len(dta_holder["character_relations_context"])):
                    if dta_holder["character_relations_context"][index][
                            "character_names"][0] == edge_pair_list[
                                0] and dta_holder[
                                    "character_relations_context"][index][
                                        "character_names"][
                                            1] == edge_pair_list[1]:

                        #print(dta_holder["character_relations_context"][index]["tf_sorted_list"][0:12])

                        if len(dta_holder["character_relations_context"][index]
                               ["tf_sorted_list"][0:words_in_word_cloud]) == 0:
                            text_string = "<<empty_word_cloud>>"
                        if len(dta_holder["character_relations_context"][index]
                               ["tf_sorted_list"][0:words_in_word_cloud]) > 0:
                            text_string = str()
                            # for word_freq_tuple in relation["tf_sorted_list"][0:10]:
                            for word_freq_tuple in dta_holder[
                                    "character_relations_context"][index][
                                        "tf_sorted_list"][
                                            0:words_in_word_cloud]:

                                if word_freq_tuple[1] < 10:
                                    for i in range(word_freq_tuple[1]):
                                        text_string += "%s " % word_freq_tuple[
                                            0]

                                if word_freq_tuple[1] >= 10:
                                    for i in range(9):
                                        # print(i)
                                        text_string += "%s " % word_freq_tuple[
                                            0]

                        #print(text_string)

                        word_cloud.generate_wordcloud_simple(
                            text=text_string,
                            ending_number=index,
                            temppath=tpath,
                            file_name_head=head_of_file_name)
                        # wc = word_cloud.generate_wordcloud_simple(text=str(text_string))

                        #######

                        wordcloud_pic = Figure(position="H")
                        wordcloud_pic.add_image(
                            os.path.join(tpath, "wordcloud%s.png" % index),
                            width='240px')  # , placement="center")
                        # wordcloud_pic.add_image(wc, width='240px')#, placement="center")

                        # wordcloud_pic.add_caption('word cloud of "%s -- %s"' % (relation["character_names"][0], relation["character_names"][1]))
                        wordcloud_pic.add_caption(
                            'word cloud of "%s -- %s"' %
                            (dta_holder["character_relations_context"][index]
                             ["character_names"][0],
                             dta_holder["character_relations_context"][index]
                             ["character_names"][1]))

                        # subs.append(wordcloud_pic)
                        # section.append(subs)

                        section.append(wordcloud_pic)

            doc.append(section)
コード例 #39
0
col2_cell = MultiRow(2, data='span-2')
table4.add_row((col1_cell, col2_cell, '3a'))
table4.add_hline(start=3)
table4.add_row(('', '', '3b'))
table4.add_hline(start=2)
table4.add_row(('', col2_cell, '3c'))
table4.add_hline(start=3)
table4.add_row(('', '', '3d'))
table4.add_hline()

test1.append(table1)
test2.append(table2)
test3.append(table3)
test4.append(table4)

section.append(test1)
section.append(test2)
section.append(test3)
section.append(test4)

doc.append(section)
doc.generate_pdf(clean_tex=False)
"""
rishikesh agrawani@DESKTOP-8AATOO4 MINGW64 /d/projects/Python/PyLaTex (master)
$ cd 11_multirow_multicolumn_example/

rishikesh agrawani@DESKTOP-8AATOO4 MINGW64 /d/projects/Python/PyLaTex/11_multirow_multicolumn_example (master)
$ ls
multirow_multicolumn_example.py

rishikesh agrawani@DESKTOP-8AATOO4 MINGW64 /d/projects/Python/PyLaTex/11_multirow_multicolumn_example (master)
コード例 #40
0
    def write_word_cloud_single_character(
            self,
            doc,
            dta_holder,
            tpath,
            number_of_wc,
            head_of_file_name="wordcloud_for_single_character",
            wc_context_selection="MFW",
            words_in_word_cloud=12):

        doc.packages.append(Package('float'))
        if wc_context_selection == "PMI":
            section = Section(
                "Word Cloud for single characters (method: pointwise mutual information",
                numbering=True)
            section.append(
                "These word clouds were constructed based on pointwise mutual information (PMI). PMI is a measure of how strongly each term is associated with each character mention. "
            )
        if wc_context_selection == "MFW":
            section = Section(
                "Word Cloud for single characters (method: most frequent contexts words",
                numbering=True)
            section.append(
                "These word clouds were constructed based on most frequent words. They show the most frequent words that appear around character mention. "
            )

        network_parameters = dta_holder["network_parameters"]
        weighted_degrees = network_parameters[5]
        weighted_degrees_sorted = sorted(weighted_degrees,
                                         key=operator.itemgetter(1),
                                         reverse=True)

        if wc_context_selection == "PMI":

            character_names_with_highest_degree = list()
            for weighted_degree in weighted_degrees_sorted[0:number_of_wc]:
                character_names_with_highest_degree += [weighted_degree[0]]

            for index, context_dic in enumerate(
                    dta_holder["single_character_context"]):

                if dta_holder["single_character_context"][index][
                        "character_names"] in character_names_with_highest_degree:

                    if len(context_dic["tf_sorted_list"]
                           [0:words_in_word_cloud]) == 0:
                        text_string = "<<empty_word_cloud>>"
                    if len(context_dic["tf_sorted_list"]
                           [0:words_in_word_cloud]) > 0:
                        #print(context_dic)
                        text_string = str()
                        # for word_freq_tuple in relation["tf_sorted_list"][0:10]:
                        for word_freq_tuple in context_dic["tf_sorted_list"][
                                0:words_in_word_cloud]:

                            if word_freq_tuple[1] < 10:
                                for i in range(word_freq_tuple[1]):
                                    text_string += "%s " % word_freq_tuple[0]

                            if word_freq_tuple[1] >= 10:
                                for i in range(9):
                                    # print(i)
                                    text_string += "%s " % word_freq_tuple[0]
                                    # print(text_string)

                    word_cloud.generate_wordcloud_simple(
                        text=text_string,
                        ending_number=index,
                        temppath=tpath,
                        file_name_head=head_of_file_name)
                    #wc = word_cloud.generate_wordcloud_simple(text=str(text_string))

                    wordcloud_pic = Figure(position="H")
                    wordcloud_pic.add_image(
                        os.path.join(
                            tpath,
                            "wordcloud_for_single_character%s.png" % index),
                        width='240px')  # , placement="center")

                    wordcloud_pic.add_caption(
                        'word cloud of "%s"' %
                        (dta_holder["single_character_context"][index]
                         ["character_names"]))

                    section.append(wordcloud_pic)

            doc.append(section)

        if wc_context_selection == "MFW":

            character_names_with_highest_degree = list()
            for weighted_degree in weighted_degrees_sorted[0:number_of_wc]:
                character_names_with_highest_degree += [weighted_degree[0]]

            for index in range(0, len(dta_holder["single_character_context"])):

                if dta_holder["single_character_context"][index][
                        "character_names"] in character_names_with_highest_degree:

                    if len(dta_holder["single_character_context"][index]
                           ["tf_sorted_list"][0:words_in_word_cloud]) == 0:
                        text_string = "<<empty_word_cloud>>"
                    if len(dta_holder["single_character_context"][index]
                           ["tf_sorted_list"][0:words_in_word_cloud]) > 0:
                        #print(dta_holder["single_character_context"][index]["tf_sorted_list"][0:12])

                        text_string = str()
                        # for word_freq_tuple in relation["tf_sorted_list"][0:10]:
                        for word_freq_tuple in dta_holder[
                                "single_character_context"][index][
                                    "tf_sorted_list"][0:words_in_word_cloud]:

                            #print(word_freq_tuple)

                            # for i in range(word_freq_tuple[1]):
                            #     text_string += "%s " % word_freq_tuple[0]

                            if word_freq_tuple[1] < 10:
                                for i in range(word_freq_tuple[1]):
                                    text_string += "%s " % word_freq_tuple[0]

                            if word_freq_tuple[1] >= 10:
                                for i in range(9):
                                    #print(i)
                                    text_string += "%s " % word_freq_tuple[0]

                    #print(text_string)

                    word_cloud.generate_wordcloud_simple(
                        text=text_string,
                        ending_number=index,
                        temppath=tpath,
                        file_name_head=head_of_file_name)
                    # wc = word_cloud.generate_wordcloud_simple(text=str(text_string))

                    #######

                    wordcloud_pic = Figure(position="H")
                    wordcloud_pic.add_image(
                        os.path.join(
                            tpath,
                            "wordcloud_for_single_character%s.png" % index),
                        width='240px')  # , placement="center")

                    wordcloud_pic.add_caption(
                        'word cloud of "%s"' %
                        (dta_holder["single_character_context"][index]
                         ["character_names"]))

                    # subs.append(wordcloud_pic)
                    # section.append(subs)

                    section.append(wordcloud_pic)

            doc.append(section)
コード例 #41
0
ファイル: analyze_db.py プロジェクト: kob22/pracamgr
    outlier = 0
    rare = 0
    for target, neighbors in zip(miniority_target, neighbors_list):

        same_neighbors = np.count_nonzero(neighbors == target) - 1
        if same_neighbors > 3:
            safe += 1
        elif same_neighbors > 1:
            border += 1
        elif same_neighbors == 1:
            outlier += 1
        else:
            rare += 1

    count_all = np.count_nonzero(miniority_target)

    safeT = float("{0:.2f}".format((float(safe) / count_all) * 100))
    borderT = float("{0:.2f}".format((float(border) / count_all) * 100))
    rareT = float("{0:.2f}".format((float(rare) / count_all) * 100))
    outlierT = float("{0:.2f}".format((float(outlier) / count_all) * 100))

    table.add_row([data, safeT, borderT, rareT, outlierT])

doc = Document("analiza_danych")

section = Section("Analiza danych klasy mniejszosciowej")
section.append(table)
doc.append(section)
doc.generate_tex(os.path.join(path, 'wyniki/pliki_tex/'))
doc.generate_pdf(os.path.join(path, 'wyniki/pliki_pdf/'))
コード例 #42
0
ファイル: numpy_ex.py プロジェクト: sovelten/PyLaTeX
from pylatex import Document, Section, Subsection, Math
from pylatex.numpy import Matrix, VectorName

a = np.array([[100, 10, 20]]).T

doc = Document()
section = Section('Numpy tests')
subsection = Subsection('Array')

vec = Matrix(a)
vec_name = VectorName('a')
math = Math(data=[vec_name, '=', vec])

subsection.append(math)
section.append(subsection)

subsection = Subsection('Matrix')
M = np.matrix([[2, 3, 4], [0, 0, 1], [0, 0, 2]])
matrix = Matrix(M, mtype='b')
math = Math(data=['M=', matrix])

subsection.append(math)
section.append(subsection)

subsection = Subsection('Product')

math = Math(data=['M', vec_name, '=', Matrix(M * a)])
subsection.append(math)

section.append(subsection)
コード例 #43
0
ファイル: auswertung.py プロジェクト: rixx/dbcluster
#section.append(table)
#doc.append(section)
#doc.generate_tex()

result_ms = get_coordinates("master-slave")
result_drbd = get_coordinates("drbd")
result_galera = get_coordinates("galera")


doc = Document()
section = Section('yay')

tikz = TikZ()
axis = Axis(options='height=6cm, width=6cm, grid=major')

plot1 = Plot(name='read', coordinates=result_ms[2])
plot2 = Plot(name='write', coordinates=result_drbd[2])
plot3 = Plot(name='read-write', coordinates=result_galera[2])

axis.append(plot1)
axis.append(plot2)
axis.append(plot3)

tikz.append(axis)

plot_section = Subsection('Random graph', data=[tikz])
section.append(plot_section)
doc.append(section)
doc.generate_tex()