Exemple #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)
    def section_1_introduction():
        sec = Subsection(title='Introduction')

        sec.append(
            NoEscape(
                'Calculation documented herein follows Annex B in '
                '"Eurocode 3: Design of steel structures — Part 1-2: General rules — Structural fire design" '
                '(BS EN 1991-1-3). '
                'This method allows the determination of the average temperature of an external steel member.\\par'
            ))

        sec.append(
            NoEscape(
                'The determination of the temperature of the compartment fire, the dimensions and temperature of the '
                'flames projecting from the openings, and the radiation and convection parameters should be performed '
                'according to annex B of BS EN 1991-1-2.\\par'))

        sec.append(
            NoEscape(
                'Units, symbols and abbreviations are consistent with BS EN 1991-1-3 unless stated.\\par'
            ))

        sec.append(
            NoEscape(
                'Numerical values shown in this document are rounded as appropriate for readability, however, calculations '
                'are carried out based on the actual values.\\par'))

        sec.append(
            NoEscape(
                'This assessment is specific to an external steel beam which is fully or partially engulfed in flame '
                'in accordance with Clause B.5 in BS EN 1993-1-2.'))

        return sec
Exemple #3
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
 def section_2_inputs(input_kwargs: dict):
     sec = Subsection(title='Inputs')
     symbols = [
         # user defined parameters
         'w_t',
         'h_eq',
         'd_1',
         'd_2',
         # user defined parameters specific to BS EN 1993-1-2 Annex B, beam calcs
         'lambda_4',
         'd_aw',
         'C_1',
         'C_2',
         'C_3',
         'C_4',
         # derived parameters, i.e. from BS EN 1991-1-2 Annex B
         'L_H',
         'L_L',
         'T_f',
         'T_o',
         'T_z_1',
         'T_z_2',
         'T_z',
         'alpha',
         'w_f',
     ]
     sec.append(
         make_summary_table(symbols=symbols,
                            units=UNITS,
                            descriptions=DESCRIPTIONS,
                            values=input_kwargs))
     return sec
 def section_3_calculation(output_kwargs):
     latex_equation_header = output_kwargs['_latex_equation_header']
     latex_equation_content = output_kwargs['_latex_equation_content']
     sec = Subsection(title='Calculation')
     for i in range(len(latex_equation_header)):
         sec.append(NoEscape(latex_equation_header[i]))
         sec.append(make_alginat_equations(latex_equation_content[i]))
     return sec
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
 def latex(self, numero_ejercicio):
     ejercicio = Subsection('Ejercicio {}.'.format(numero_ejercicio))
     ejercicio.append(
         NoEscape('\\begin{flushleft}' +
                  self.problema.replace('\n', '\linebreak \n') +
                  '\end{flushleft}'))
     with ejercicio.create(
             Enumerate(enumeration_symbol=r"\alph*)")) as enum:
         for opcion in self.opciones:
             enum.add_item(NoEscape(opcion.replace('\n', '\linebreak \n')))
     return ejercicio
 def section_4_summary(output_kwargs: dict):
     sec = Subsection(title='Summary')
     sec.append('Results are summarised below.')
     symbols = [
         'I_z_1', 'I_z_2', 'I_z_3', 'I_z_4', 'I_z', 'I_f_1', 'I_f_2',
         'I_f_3', 'I_f_4', 'I_f', 'T_m_1', 'T_m_2', 'T_m_3', 'T_m_4', 'T_m'
     ]
     sec.append(
         make_summary_table(symbols=symbols,
                            units=UNITS,
                            descriptions=DESCRIPTIONS,
                            values=output_kwargs))
     return sec
Exemple #9
0
 def section_2_inputs(input_kwargs: dict):
     section_2 = Subsection(title='Inputs')
     symbols = [
         'W_1', 'W_2', 'A_f', 'h_eq', 'w_t', 'A_v', 'd_ow', 'DW_ratio',
         'q_fk', 'q_fd', 'L_x', 'tau_F', 'u', 'Omega', 'O', 'Q', 'd_eq',
         'T_f', 'L_L', 'L_H', 'L_f', 'T_w', 'T_z'
     ]
     section_2.append(
         make_summary_table(symbols=symbols,
                            units=UNITS,
                            descriptions=DESCRIPTIONS,
                            values=input_kwargs))
     return section_2
Exemple #10
0
 def section_4_summary(output_kwargs: dict):
     section_4 = Subsection(title='Summary')
     section_4.append('Results of this assessment are summarised below.')
     symbols = [
         'Q', 'T_f', 'L_L', 'L_H', 'L_f', 'T_w', 'T_z', 'epsilon_f',
         'alpha_c'
     ]
     section_4.append(
         make_summary_table(symbols=symbols,
                            units=UNITS,
                            descriptions=DESCRIPTIONS,
                            values=output_kwargs))
     return section_4
Exemple #11
0
 def section_2_inputs(input_kwargs: dict):
     sec = Subsection(title='Inputs')
     symbols = [
         'w_t', 'h_eq', 'd_1', 'd_2',
         'lambda_1', 'lambda_3', 'C_1', 'C_2', 'C_3', 'C_4',
         'L_H', 'L_L', 'T_f', 'T_o', 'T_z', 'alpha', 'w_f',
     ]
     sec.append(make_summary_table(
         symbols=symbols,
         units=UNITS,
         descriptions=DESCRIPTIONS,
         values=input_kwargs
     ))
     return sec
Exemple #12
0
    def discover_experiment_data(self, experiment_name, experiment_type, tasks,
                                 task_counts, nodes: List[Node], description,
                                 start_time):
        if experiment_name not in self.sections.keys():
            self.sections[experiment_name] = Section(experiment_name)
            self.sections[experiment_name].append(description)
            self.sections[experiment_name].append(
                '\nExperiment start time: {}'.format(
                    datetime.fromtimestamp(start_time)))
        if experiment_type not in self.experiment_types:
            self.experiment_types.append(experiment_type)
        workloads_results = Subsection('')
        # create table with results
        table = self.create_table()
        for task in tasks:
            task_name = self._strip_task_name(task)
            task_count = task_counts[task_name]
            average_latency, average_throughput, q09_latency, q09_throughput,\
                numa_nodes, mbw_local, mbw_remote = self.get_metrics(tasks[task])
            table.add_row(
                (tasks[task].name.replace('default/', ''), average_latency,
                 average_throughput, q09_latency, q09_throughput,
                 numa_nodes[0], numa_nodes[1], numa_nodes[2], numa_nodes[3],
                 mbw_local, mbw_remote))
            table.add_hline()
            self._keep_task_results(task, task_name, task_count,
                                    experiment_type, average_latency,
                                    average_throughput, q09_latency,
                                    q09_throughput)

        # create table with node metrics
        node_table = self.create_nodes_table()
        for node in nodes:
            for socket in [0, 1]:
                row = [node.name, socket]
                for metric in metrics.platform_metrics:
                    row.append(
                        self.round_metric(
                            float(
                                node.performance_metrics[socket][metric.name])
                            / float(metrics.MetricLegends[metric]['helper'])))
                node_table.add_row(row)
                node_table.add_hline()

        workloads_results.append(table)
        workloads_results.append(VerticalSpace("10pt"))
        workloads_results.append(LineBreak())
        workloads_results.append(node_table)
        self.sections[experiment_name].append(workloads_results)
Exemple #13
0
    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)
Exemple #14
0
 def _TCauxHeader(self):
     """
     Fills the aux header section for TC
     """
     subsection = Subsection('Auxiliary Header and Data')
     subsection.append("No auxiliary header.")
     subsection.append(NewLine())
     subsection.append("The data field is the "\
                       "octet-concatenation of telecommand input "\
                       "parameters, as per telecommands documentation.")
     return subsection
Exemple #15
0
 def _TMauxHeader(self):
     """
     Fills the aux header section for TM
     """
     subsection = Subsection('Auxiliary Header and Data')
     subsection.append("The auxiliary header and data fields definitions "\
                       "depend on the payload flag and the packet "\
                       "category.")
     subsection.append(NewLine())
     subsection.append("Refer to Sections Packet Category OBC and Payload")
     return subsection
Exemple #16
0
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')
Exemple #17
0
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)
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)
table3.add_hline()

table4 = Tabular('|c|c|c|')
table4.add_hline()
col1_cell = MultiRow(4, data='span-4')
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/
Exemple #20
0
doc = Document(filename="multirow")
section = Section('Multirow Test')

test1 = Subsection('Multicol')
test2 = Subsection('Multirow')

table1 = Table('|c|c|')
table1.add_hline()
table1.add_multicolumn(2, '|c|', 'Multicol')
table1.add_hline()
table1.add_row((1, 2))
table1.add_hline()
table1.add_row((3, 4))
table1.add_hline()

table2 = Table('|cc|c|c|')
table2.add_hline()
table2.add_multirow(2, '*', 'Multirow', cells=((1, 2), (3, 4)))
table2.add_hline()

test1.append(table1)
test2.append(table2)

section.append(test1)
section.append(test2)

doc.append(section)
doc.generate_tex()
doc.generate_pdf()
Exemple #21
0
    def update(self, i):
        i = int(i)
        self.parent.matrix = np.array(
            (self.parent.i_vector, self.parent.j_vector,
             self.parent.k_vector)).T
        self.parent.plus_matrix = np.array(
            (self.parent.i_plus_vector, self.parent.j_plus_vector,
             self.parent.k_plus_vector)).T

        if self.canvasFigure != None:
            try:
                self.parent.quiver.remove()
                self.parent.plus_quiver.remove()
            except:
                print("do nothing")
            self.parent.matrix = (1 - self.parent.sigmoid(i)) * np.array(
                (self.parent.i_origin, self.parent.j_origin, self.parent.
                 k_origin)) + self.parent.sigmoid(i) * self.parent.matrix
            self.parent.plus_matrix = (1 - self.parent.sigmoid(i)) * np.array(
                (self.parent.i_origin, self.parent.j_origin, self.parent.
                 k_origin)) + self.parent.sigmoid(i) * self.parent.plus_matrix
        else:
            self.parent.matrix = np.array(
                (self.parent.i_origin, self.parent.j_origin,
                 self.parent.k_origin)) + self.parent.matrix
            self.parent.plus_matrix = np.array(
                (self.parent.i_origin, self.parent.j_origin,
                 self.parent.k_origin)) + self.parent.plus_matrix
        # Compute a matrix that is in the middle between the full transformation matrix and the identity

        self.parent.vector_location = np.array(
            (self.parent.matrix.dot(self.parent.i_origin),
             self.parent.matrix.dot(self.parent.j_origin),
             self.parent.matrix.dot(self.parent.k_origin))).T
        self.parent.quiver = self.parent.ax.quiver(
            0,
            0,
            0,
            self.parent.vector_location[0],
            self.parent.vector_location[1],
            self.parent.vector_location[2],
            length=1,
            color='r',
            arrow_length_ratio=0.1)
        self.parent.plus_vector_location = np.array(
            (self.parent.plus_matrix.dot(self.parent.i_origin),
             self.parent.plus_matrix.dot(self.parent.j_origin),
             self.parent.plus_matrix.dot(self.parent.k_origin))).T
        self.parent.plus_quiver = self.parent.ax.quiver(
            0,
            0,
            0,
            self.parent.plus_vector_location[0],
            self.parent.plus_vector_location[1],
            self.parent.plus_vector_location[2],
            length=1,
            color='y',
            arrow_length_ratio=0.1)
        # Set vector location - must transpose since we need U and V representing x and y components
        # of each vector respectively (without transposing, e  ach column represents each unit vector)
        self.parent.transform = np.array(
            [self.parent.matrix.dot(k) for k in self.parent.x])

        #ax.view_init((1 - self.parent.sigmoid(i)) * elevation, (1 - self.parent.sigmoid(i)) * angle)
        if self.canvasFigure != None:
            self.parent.scat._offsets3d = [
                self.parent.transform[:, 0], self.parent.transform[:, 1],
                self.parent.transform[:, 2]
            ]
            self.canvasFigure.draw()
            a = self.parent.plus_vector_location
            #with pylatex.config.active.change(indent=False):
            doc = Document()
            doc.packages.append(
                Package('geometry',
                        options=['paperwidth=6in', 'paperheight=2.5in']))
            section = Section('Linear Combination')

            subsection = Subsection('Using the dot product')
            V1 = np.transpose(np.array([[1, 1]]))
            M1 = np.array((self.parent.i_vector, self.parent.j_vector)).T
            math = Math(data=[
                Matrix(M1), 'dot',
                Matrix(V1), '=',
                Matrix(np.dot(M1, V1))
            ])
            subsection.append(math)
            section.append(subsection)

            subsection = Subsection('Using vector addition')
            V1 = np.array([self.parent.i_vector])
            V2 = np.array([self.parent.j_vector])
            math = Math(
                data=[Matrix(V1), '+',
                      Matrix(V2), '=',
                      Matrix(V1 + V2)])
            subsection.append(math)
            section.append(subsection)
            #doc.append(section)
            '''
            subsection = Subsection('Product')

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

            section.append(subsection)
            doc.append(section)
            '''
            doc.append(section)
            latex = doc.dumps_as_content()
            print(latex)
            self.strvar.set(latex)
            #self.strvar.set("\prod_{p\,\mathrm{prime}}\\frac1{1-p^{-s}} = \sum_{n=1}^\infty \\frac1{n^s}")
            self.on_latex()
Exemple #22
0
    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()
Exemple #23
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)
    def discover_experiment_data(self, experiment_name, experiment_type, tasks,
                                 task_counts, description):
        if experiment_name not in self.sections.keys():
            self.sections[experiment_name] = Section(experiment_name)
            self.sections[experiment_name].append(description)
        if experiment_type not in self.experiment_types:
            self.experiment_types.append(experiment_type)

        workloads_results = Subsection('')
        # create table with results
        table = Tabular('|c|c|c|c|c|')
        table.add_hline()
        table.add_row(('name', 'avg latency', 'avg throughput', 'q0.9 latency',
                       'q0.9 throughput'))
        table.add_hline()

        for task in tasks:
            task_name = self._strip_task_name(task)
            task_count = task_counts[task_name]
            average_latency = round(
                float(
                    tasks[task].performance_metrics[Metric.TASK_LATENCY][AVG]),
                3)
            average_throughput = round(
                float(tasks[task].performance_metrics[Metric.TASK_THROUGHPUT]
                      [AVG]), 3)
            q09_latency = round(
                float(
                    tasks[task].performance_metrics[Metric.TASK_LATENCY][Q09]),
                3)
            q09_throughput = round(
                float(tasks[task].performance_metrics[Metric.TASK_THROUGHPUT]
                      [Q09]), 3)
            table.add_row((tasks[task].name.replace('default/',
                                                    ''), average_latency,
                           average_throughput, q09_latency, q09_throughput))
            table.add_hline()

            task_metrics = {
                AVG_LATENCY: average_latency,
                AVG_THROUGHPUT: average_throughput,
                Q09_LATENCY: q09_latency,
                Q09_THROUGHPUT: q09_throughput
            }

            task_index = self._get_task_index(task)
            task_name_with_index = task_name + '-' + task_index
            task_name_with_index = self._strip_memory_suffix(
                task_name_with_index)
            for metric_name, metric_value in task_metrics.items():
                if task_count in self.metric_values[metric_name]:
                    if task_name_with_index in self.metric_values[metric_name][
                            task_count]:
                        self.metric_values[metric_name][task_count][
                            task_name_with_index].update(
                                {experiment_type: metric_value})
                    else:
                        self.metric_values[metric_name][task_count][task_name_with_index] = \
                            {experiment_type: metric_value}
                else:
                    self.metric_values[metric_name][task_count] = \
                        {task_name_with_index: {experiment_type: metric_value}}

        workloads_results.append(table)
        self.sections[experiment_name].append(workloads_results)
Exemple #25
0
                    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()
    def write_netork_parameters(self, doc, dta_holder):
        with doc.create(Section("Network Parameters",
                                numbering=True)) as section1:
            section1.append(
                "Here you can get information about the network parameters.")
            with doc.create(Subsection("Definitions", numbering=False)):
                with doc.create(Itemize()) as definitions:
                    definitions.add_item(
                        "Average degree: The degree of a node is the number of edges connected to it. It measures the number of connections to other characters. Average degree is calculated\
                        on a probability of two nodes being connected.")
                    definitions.add_item(
                        "SD degree: Standard deviation of all degrees.")
                    definitions.add_item(
                        "Density: Graph density is the ratio of the number of edges to the number of possible edges."
                    )
                    definitions.add_item(
                        "Weighted degree: Sum of weights of incident edges. Measures the number of interactions of a character."
                    )
            with doc.create(
                    Subsection("Current network parameters", numbering=False)):
                with doc.create(Itemize()) as itmize:
                    itmize.add_item("average degree: %s" %
                                    dta_holder["network_parameters"][0])
                    itmize.add_item("sd degree: %s" %
                                    dta_holder["network_parameters"][1])
                    itmize.add_item("density: %s" %
                                    dta_holder["network_parameters"][2])
                # itmize.add_item("degrees for single characters: %s" %dta_holder["network_parameters"][3])

        # pdf_latex().write_table_degrees(doc, dta_holder)

        subsection1 = Subsection("Degrees", numbering=False)

        # table1 = Tabular('|c|c|c|c|')
        table1 = Tabular('|c|c|c|')

        table1.add_hline()
        table1.add_row(("Character (Node)", "degree", "weighted degree"))
        table1.add_hline()
        degree_list_weigthed_degree_tuple = zip(
            dta_holder["network_parameters"][3],
            dta_holder["network_parameters"][4])
        sorted_degree_list_weigthed_degree_tuple = sorted(
            degree_list_weigthed_degree_tuple,
            key=lambda x: x[1][1],
            reverse=True)
        #for degree_list, weigthed_degree_tuple in zip(dta_holder["network_parameters"][3],
        #                                              dta_holder["network_parameters"][4]):
        for degree_list, weigthed_degree_tuple in sorted_degree_list_weigthed_degree_tuple:
            if degree_list[0] == weigthed_degree_tuple[0]:
                table1.add_row(degree_list[0], degree_list[1],
                               weigthed_degree_tuple[1])
                table1.add_hline()
            else:
                print("characters for degree and weighted degree don't match!")

        subsection1.append(table1)
        doc.append(subsection1)

        subsection2 = Subsection("Weights for Edges", numbering=False)
        table2 = Tabular("|c|c|")
        table2.add_hline()
        table2.add_row("Character Pair (Edge)", "Weight")
        table2.add_hline()
        #print(dta_holder["character_relations"])
        sorted_relations = sorted(dta_holder["character_relations"],
                                  key=operator.itemgetter(4),
                                  reverse=True)
        #print(sorted_relations)
        #for relation in dta_holder["character_relations"]:
        for relation in sorted_relations[0:50]:
            if sorted_relations[4] != 0:
                table2.add_row("%s -- %s" % (relation[2][0], relation[2][1]),
                               len(relation[3]))
                table2.add_hline()

        subsection2.append(table2)
        doc.append(subsection2)
Exemple #27
0
            for o in options:
                coords[o].clear()
            k = 0
        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])

    if solutions[0][3] == 'SAT':
        solutions.sort(key=lambda x: (x[3], x[1]))
        table = Table('l|r|l|r|r')
        subsubsection.append(table)
        table.add_hline()
        table.add_row(("Param.", 'Status', "\#Sol", 'Time(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][2]))
Exemple #28
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())
Exemple #29
0
    def peripheral_fill(self, periph, periph_name):
        self.doc.append(NewPage())
        periph_subsection = Section(periph_name, numbering=True)
        periph_subsection.append(periph.get_description().replace('""', ''))
        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:

            #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: {} bytes".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()),
                         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 40
                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())
Exemple #30
0
    def _trousseau2subsection(self, subname, T, catnum=None, pldflag=None):
        """
        Takes a whole trousseau and generates the document latex for it

        Args:
          * subname (str): name of the subsection
          * T (trousseau): the trousseau to generate code on
          * catnum (None, int): None if the trousseau is not a
            category, or the category number
          * pldflag (None, bool): None if the trousseau is not a
            category, or bool corresponding to the payload flag
        """
        subsection = Subsection(str(subname))
        if catnum is not None:
            subsection.append('Payload flag: {}'.format(pldflag))
            subsection.append(NewLine())
            subsection.append('Packet Category number: {:d}'.format(catnum))
            subsection.append(NewLine())
        desc = self._trousseau2desc(T)
        for item in desc:
            subsection.append(item)
        table = self._trousseau2table(T)
        for item in table:
            subsection.append(item)
        detail = self._trousseau2allfields(T)
        for item in detail:
            subsection.append(item)
        return subsection
Exemple #31
0
    doc = Document()
    section = Section('Quantity tests')

    subsection = Subsection('Scalars with units')
    G = pq.constants.Newtonian_constant_of_gravitation
    moon_earth_distance = 384400 * pq.km
    moon_mass = 7.34767309e22 * pq.kg
    earth_mass = 5.972e24 * pq.kg
    moon_earth_force = G * moon_mass * earth_mass / moon_earth_distance**2
    q1 = Quantity(moon_earth_force.rescale(pq.newton),
                  options={
                      'round-precision': 4,
                      'round-mode': 'figures'
                  })
    math = Math(data=['F=', q1])
    subsection.append(math)
    section.append(subsection)

    subsection = Subsection('Scalars without units')
    world_population = 7400219037
    N = Quantity(world_population,
                 options={
                     'round-precision': 2,
                     'round-mode': 'figures'
                 },
                 format_cb="{0:23.17e}".format)
    subsection.append(Math(data=['N=', N]))
    section.append(subsection)

    subsection = Subsection('Scalars with uncertainties')
    width = pq.UncertainQuantity(7.0, pq.meter, .4)
Exemple #32
0
    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()
Exemple #33
0
import numpy as np

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)
Exemple #34
0
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')
Exemple #35
0
from pylatex import Document, Section, Subsection, Math, Quantity

if __name__ == '__main__':
    doc = Document()
    section = Section('Quantity tests')

    subsection = Subsection('Scalars with units')
    G = pq.constants.Newtonian_constant_of_gravitation
    moon_earth_distance = 384400 * pq.km
    moon_mass = 7.34767309e22 * pq.kg
    earth_mass = 5.972e24 * pq.kg
    moon_earth_force = G * moon_mass * earth_mass / moon_earth_distance**2
    q1 = Quantity(moon_earth_force.rescale(pq.newton),
                  options={'round-precision': 4, 'round-mode': 'figures'})
    math = Math(data=['F=', q1])
    subsection.append(math)
    section.append(subsection)

    subsection = Subsection('Scalars without units')
    world_population = 7400219037
    N = Quantity(world_population, options={'round-precision': 2,
                                            'round-mode': 'figures'},
                 format_cb="{0:23.17e}".format)
    subsection.append(Math(data=['N=', N]))
    section.append(subsection)

    subsection = Subsection('Scalars with uncertainties')
    width = pq.UncertainQuantity(7.0, pq.meter, .4)
    length = pq.UncertainQuantity(6.0, pq.meter, .3)
    area = Quantity(width*length, options='separate-uncertainty',
                    format_cb=lambda x: "{0:.1f}".format(float(x)))
    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)
Exemple #37
0
doc = Document(filename="multirow")
section = Section('Multirow Test')

test1 = Subsection('Multicol')
test2 = Subsection('Multirow')

table1 = Table('|c|c|')
table1.add_hline()
table1.add_multicolumn(2, '|c|', 'Multicol')
table1.add_hline()
table1.add_row((1, 2))
table1.add_hline()
table1.add_row((3, 4))
table1.add_hline()

table2 = Table('|c|c|c|')
table2.add_hline()
table2.add_multirow(3, '*', 'Multirow', cells=((1, 2), (3, 4), (5, 6)))
table2.add_hline()
table2.add_multirow(3, '*', 'Multirow2')
table2.add_hline()

test1.append(table1)
test2.append(table2)

section.append(test1)
section.append(test2)

doc.append(section)
doc.generate_pdf()