Example #1
0
    def LED_report(self):
        self.doc.append(NoEscape(r'\clearpage'))
        with self.doc.create(Section('LEDs')):
            with self.doc.create(Subsection('Description')):
                self.doc.append(
                    'This test asserts the correct assembly of the 4 LEDs on RFFEuC\'s edge.\n'
                )
                self.doc.append(
                    'A large LDR (20mm) is positioned in front of all LEDs and is connected to one of the Analogic-to-Digital converter ports - routed through the TestBoard Jn connector.\n'
                )
                self.doc.append(
                    'Each LED is activated separately and the LDR voltage is read and compared to a predefined mask.\n'
                )

            with self.doc.create(Subsection('Results')):
                with self.doc.create(Center()) as centered:
                    with centered.create(Tabular('|c|c|c|',
                                                 row_height=1.2)) as tbl:
                        tbl.add_hline()
                        tbl.add_row(bold('LED'), bold('LDR read [V]'),
                                    bold('Result'))
                        tbl.add_hline()
                        for key, val in self.test_results['led'].items():
                            if isinstance(val, dict):
                                tbl.add_row(
                                    bold(key), (val['value']),
                                    ('Pass' if val['result'] else 'Fail'),
                                    color=('green'
                                           if val['result'] else 'red'))
                                tbl.add_hline()
    def append_matrix_calculation(self):
        with self.gen.doc.create(Section(self.gen.tpdf.calculation)):
            with self.gen.doc.create(Subsection(self.gen.tpdf.matrix_subs)):
                self.gen.doc.append(NoEscape(r'\['))
                self.gen.doc.append(NoEscape(r'\begin{vmatrix}'))
                self.gen.doc.append(
                    NoEscape(f'{self.res.sigma_x} -' + r'\lambda' + f'& {self.res.tau_xy} & {self.res.tau_xz}' r'\\'
                             f'{self.res.tau_xy} & {self.res.sigma_y}' + r' - \lambda' + f'& {self.res.tau_yz}' r'\\'
                             f'{self.res.tau_xz} & {self.res.tau_yz} & {self.res.sigma_z}' + r' - \lambda'))
                self.gen.doc.append(NoEscape(r'\end{vmatrix}'))
                self.gen.doc.append(NoEscape(r' =0\]'))

                with self.gen.doc.create(Subsection(self.gen.tpdf.determinant_calculation)):
                    string = f"({self.res.sigma_x} -" + r'\lambda' + f") \\cdot ({self.res.sigma_y} -" + r'\lambda' + \
                             f") \\cdot ({self.res.sigma_z} -" + r'\lambda' + f") + {self.res.tau_xy} \\cdot " \
                             f"{self.res.tau_yz} \\cdot {self.res.tau_xz} + {self.res.tau_xz} \\cdot {self.res.tau_xy}" \
                             + f" \\cdot {self.res.tau_yz} - {self.res.tau_xz} \\cdot ({self.res.sigma_y} -" \
                             + r'\lambda' + f") \\cdot {self.res.tau_xz} - {self.res.tau_yz} \\cdot {self.res.tau_yz}" \
                             f" \\cdot ({self.res.sigma_x} -" + r'\lambda' + f") - ({self.res.sigma_z} -" + \
                             r'\lambda' + f") \\cdot {self.res.tau_xy} \\cdot {self.res.tau_xy}"

                    lam = Symbol(r'\lambda')
                    numeric = (self.res.sigma_x - lam) * (self.res.sigma_y - lam) * (self.res.sigma_z - lam) + \
                              self.res.tau_xy * self.res.tau_yz * self.res.tau_xz + self.res.tau_xz * \
                              self.res.tau_xy * self.res.tau_yz - self.res.tau_xz * (self.res.sigma_y - lam) * \
                              self.res.tau_xz - self.res.tau_yz * self.res.tau_yz * (self.res.sigma_x - lam) - \
                              (self.res.sigma_z - lam) * self.res.tau_xy * self.res.tau_xy

                    self.gen.pdf.add_equation('det = ' + string)
                    self.gen.pdf.add_equation('det = ' + latex(numeric))
                    self.gen.pdf.add_equation('det = ' + latex(simplify(numeric)))
                    self.gen.doc.append(NoEscape(self.gen.tpdf.subs_3_in_1))
                    self.gen.pdf.add_equation(latex(simplify(numeric)) + r'=0')
Example #3
0
    def append_solution(self, solution_id, problem, solution):
        with self.doc.create(Multicols(arguments=[2])):
            image_filename = os.path.join(
                os.path.dirname('.'), 'images/solution_%d.png' % solution_id)
            with self.doc.create(
                    Section('Problem with solution %d' % solution_id,
                            label="problem%d" % solution_id)):
                with self.doc.create(
                        Subsection('TSNE representation',
                                   label="tsne%d" % solution_id)):
                    with self.doc.create(Figure(position='H')) as tsne:
                        tsne.add_image(image_filename, width=NoEscape(r'11cm'))
                        tsne.add_caption('TSNE 2d feature space')

                self.doc.append(VerticalSpace(NoEscape(r"\fill")))

                with self.doc.create(
                        Subsection('Problem and Solution',
                                   label="solution%d" % solution_id)):
                    self.doc.append(problem)
                    with self.doc.create(Verbatim()):
                        self.doc.append(solution)
                self.doc.append(VerticalSpace(NoEscape(r"\fill")))
                self.doc.append(NewPage())

        return self.doc
Example #4
0
 def write_data_input(self, doc, dta_holder):
     ts = time.time()
     st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
     with doc.create(Section("Data Input", numbering=True)):
         with doc.create(Subsection("Statistics", numbering=False)):
             with doc.create(Itemize()) as itmize:
                 itmize.add_item("timestamp: %s" % st)
                 itmize.add_item('analyzed text: "%s"' %
                                 dta_holder["text_file"].split('/')[-1])
                 itmize.add_item("length of text: %s tokens" %
                                 len(dta_holder["tokenized_text"]))
                 # itmize.add_item("number of characters: %s" % len(dta_holder["characters"]))
                 characters_with_at_least_one_degree = 0
                 for degree_list in dta_holder["network_parameters"][3]:
                     if degree_list[1] != 0:
                         characters_with_at_least_one_degree += 1
                 itmize.add_item(
                     "number of characters (with at least one degree): %s" %
                     str(characters_with_at_least_one_degree))
         with doc.create(Subsection("Input parameters", numbering=False)):
             with doc.create(Itemize()) as itmize:
                 itmize.add_item("distance measure: %s" %
                                 dta_holder["parameter"][0])
                 itmize.add_item(
                     "context measure 1 (words before Character 1): %s" %
                     dta_holder["parameter"][1])
                 itmize.add_item(
                     "context measure 2 (words after Character 2): %s" %
                     dta_holder["parameter"][2])
Example #5
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_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 calculations_fixed(self):
        fixed_reactions = self.ss.reaction_forces.get(
            self.ss.supports_fixed[0].id)
        with self.doc.create(Subsection(self.tpdf.step_supports_fixed)):
            self.pdf.add_equation(r'\sum{M} = 0 \\')
            self.pdf.add_equation(r'M = F \cdot d \\')
            self.pdf.add_equation(
                NoEscape(f'{append_step(self.sr.moments_sum)}'
                         f' {get_signal(fixed_reactions.Ty)} M = 0 \\\\'))
            self.pdf.add_equation(
                NoEscape(f'M = {append_result(abs(fixed_reactions.Ty))}'))

        with self.doc.create(Subsection(self.tpdf.fixed_EFY)):
            self.pdf.add_equation(r'\sum{Fy} = 0 \\')
            self.pdf.add_equation(
                f'{append_step(self.sr.point_sum_y)} {get_signal(fixed_reactions.Fz)} Fy = 0'
                r'\\')
            self.pdf.add_equation(
                f'Fy = {append_result(abs(fixed_reactions.Fz))}')

        with self.doc.create(Subsection(self.tpdf.fixed_EFX)):
            self.pdf.add_equation(r'\sum{Fx} = 0 \\')
            self.pdf.add_equation(
                f'{append_step(self.sr.point_sum_x)} {get_signal(fixed_reactions.Fx)} Fx = 0'
                r'\\')
            self.pdf.add_equation(
                f'Fx = {append_result(abs(fixed_reactions.Fx))}')
Example #8
0
def notes(doc):
    doc.append(Command('newgeometry', 'top=1in,bottom=1in'))
    with doc.create(Section('Modeling Notes')):
        with doc.create(Subsection('Tax-Calculator')):
            doc.append(tax_calculator_string)
            with doc.create(Subsection('Modeling Assumptions')):
                doc.append(modeling_assumptions_string)
Example #9
0
def test():
    doc = Document("multirow_cm")

    with doc.create(Section('Multirow Test')):
        with doc.create(Subsection('Multicol')):
            # we need to keep track of the object here
            with doc.create(Tabular('|c|c|')) as table1:
                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()

        with doc.create(Subsection('Multirow')):
            with doc.create(Tabular('|c|c|c|')) as table2:
                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()

    doc.generate_pdf()
Example #10
0
    def PowerSupply_report(self):
        self.doc.append(NoEscape(r'\clearpage'))
        with self.doc.create(Section('Power Supply')):
            with self.doc.create(Subsection('Description')):
                self.doc.append(
                    'This test asserts the correct assembly of the Voltage regulation circuit.\n'
                )
                self.doc.append(
                    'Both power supply lines (5V and 3.3V) are tested using a simple voltage divider circuit present on the TestBoard. Given that the voltage divider provides a half of the real value to the RFFEuC ADC circuit, the following convertion is applied: \n'
                )
                with self.doc.create(Alignat(numbering=False,
                                             escape=False)) as agn:
                    agn.append(r'V_{PS} = ADC_{read} * 3.3 * 2 \\')

            with self.doc.create(Subsection('Results')):
                with self.doc.create(Center()) as centered:
                    with centered.create(Tabular('|c|c|c|',
                                                 row_height=1.2)) as tbl:
                        tbl.add_hline()
                        tbl.add_row(bold('Power Supply'), bold('Measured [V]'),
                                    bold('Result'))
                        tbl.add_hline()
                        for key, val in self.test_results['powerSupply'].items(
                        ):
                            if isinstance(val, dict):
                                tbl.add_row(
                                    bold(key + 'V'),
                                    val['value'],
                                    ('Pass' if val['result'] else 'Fail'),
                                    color=('green'
                                           if val['result'] else 'red'))
                                tbl.add_hline()
    def append_formulas(self):
        with self.gen.doc.create(Section(self.gen.tpdf.formula_for_math)):
            with self.gen.doc.create(Subsection(self.gen.tpdf.main_stress_formula)):
                self.gen.doc.append(NoEscape(self.gen.tpdf.main_stress_tip))
                self.gen.pdf.add_equation(r'det(M - I\lambda) = 0')

                self.gen.doc.append(NoEscape(r'\[det('))
                self.gen.doc.append(NoEscape(r'\begin{bmatrix}'))
                self.gen.doc.append(NoEscape(
                    r'\sigma_x & \tau_{xy} & \tau_{xz}\\ \tau_{xy} & \sigma_y & \tau_{yz}\\' +
                    r' \tau_{xz} & \tau_{yz} & \sigma_z'
                ))
                self.gen.doc.append(NoEscape(r'\end{bmatrix}'))
                self.gen.doc.append(NoEscape(r' - '))
                self.gen.doc.append(NoEscape(r'\begin{bmatrix}'))
                self.gen.doc.append(NoEscape(r'1 & 0 & 0\\ 0 & 1 & 0\\ 0 & 0 & 1'))
                self.gen.doc.append(NoEscape(r'\end{bmatrix}'))
                self.gen.doc.append(NoEscape(r' \cdot \lambda) = 0 \Rightarrow'))
                self.gen.doc.append(NoEscape(r'\begin{vmatrix}'))
                self.gen.doc.append(NoEscape(
                    r'\sigma_x - \lambda & \tau_{xy} & \tau_{xz}\\ \tau_{xy} & \sigma_y - \lambda & \tau_{yz}\\ ' +
                    r'\tau_{xz} & \tau_{yz} & \sigma_z - \lambda'
                ))
                self.gen.doc.append(NoEscape(r'\end{vmatrix}'))
                self.gen.doc.append(NoEscape(r' = 0\]'))

            with self.gen.doc.create(Subsection(self.gen.tpdf.max_shear_formula)):
                self.gen.doc.append(NoEscape(self.gen.tpdf.max_shear_tip_head))
                self.gen.doc.append(NoEscape(r'\begin{enumerate}'))
                self.gen.doc.append(NoEscape(self.gen.tpdf.max_shear_tip_body_1))
                self.gen.doc.append(NoEscape(self.gen.tpdf.max_shear_tip_body_2))
                self.gen.doc.append(NoEscape(r'\end{enumerate}'))
                self.gen.pdf.add_equation(self.gen.tpdf.radius_var + r' \frac{\sigma_1 - \sigma_3}{2}')
                self.gen.doc.append(NoEscape(r'\newpage'))
Example #12
0
    def GPIOLoopback_report(self):
        self.doc.append(NoEscape(r'\clearpage'))
        with self.doc.create(Section('GPIO Loopback')):
            with self.doc.create(Subsection('Description')):
                self.doc.append(
                    'This test asserts the correct assembly of the GPIO pins on both RFFEuC\'s headers.'
                )
                self.doc.append(
                    'In the TestBoard all GPIO pins are connected in pairs via a 1K1 resistor, so they\'re logically binded.\n'
                )
                self.doc.append(
                    'Each pin in the loopback pair is tested as an Input and Output, changing the logic level of its pair to assert the electrical connection.\n'
                )

            with self.doc.create(Subsection('Results')):
                with self.doc.create(Center()) as centered:
                    with centered.create(Tabular('|c|c|c|',
                                                 row_height=1.2)) as tbl:
                        tbl.add_hline()
                        tbl.add_row((MultiColumn(2,
                                                 align='|c|',
                                                 data=bold('Loopback Pair')),
                                     bold('Result')))
                        tbl.add_hline()
                        for key, val in self.test_results['gpio'].items():
                            if isinstance(val, dict):
                                tbl.add_row(
                                    val['pin1'],
                                    val['pin2'],
                                    ('Pass' if val['result'] else 'Fail'),
                                    color=('green'
                                           if val['result'] else 'red'))
                                tbl.add_hline()
    def append_shear_stress(self, doc, tpdf):
        with doc.create(Section(tpdf.step_shear_stress)):
            with doc.create(Subsection(tpdf.shear_stress_formula_str)):
                self.pdf.add_equation(tpdf.shear_stress_var +
                                      r' \frac{V \cdot Q}{I_x \cdot t}')

            for i in range(len(self.mng.shear_stress_data_list)):
                with doc.create(
                        Subsection(
                            NoEscape(
                                f'{tpdf.calculating_for} V = {self.mng.shear_stress_data_list[i].shear_force} N, '
                                +
                                f'Q = {append_result(self.mng.shear_stress_data_list[i].static_moment)} m'
                                + r'\textsuperscript{3}, I\textsubscript{x}' +
                                f' = {append_result(self.mng.shear_stress_data_list[i].moment_inertia_x)} m'
                                + r'\textsuperscript{4}, ' +
                                f't = {self.mng.shear_stress_data_list[i].thickness} m'
                            ))):

                    self.pdf.add_equation(
                        tpdf.shear_stress_var +
                        f'{append_step(self.mng.shear_stress_data_list[i].shear_stress)}'
                    )

                    self.pdf.add_equation(
                        tpdf.shear_stress_var +
                        f'{append_result(self.mng.shear_stress_data_list[i].shear_stress)}'
                        + r'$ $Pa')
Example #14
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 append_normal_stress(self, doc, tpdf):
        with doc.create(Section(tpdf.step_normal_stress)):
            with doc.create(Subsection(tpdf.normal_stress_formula)):
                self.pdf.add_equation(
                    tpdf.normal_stress_var +
                    r' \frac{N}{A} - \frac{My}{Iy} \cdot z - \frac{Mz}{Iz} \cdot y'
                )
            for i in range(len(self.mng.normal_stress_data_list)):
                with doc.create(
                        Subsection(
                            f'{tpdf.calculating_for} N = {self.mng.normal_stress_data_list[i].normal_force} N, '
                            f'My = {append_result(self.mng.normal_stress_data_list[i].moment_y)} Nm, '
                            f'Mz = {append_result(self.mng.normal_stress_data_list[i].moment_x)} Nm, '
                            f'y = {self.mng.normal_stress_data_list[i].y} m, '
                            f'z = {self.mng.normal_stress_data_list[i].z} m')):
                    with doc.create(Subsubsection(tpdf.step_normal_stress)):
                        self.pdf.add_equation(
                            tpdf.normal_stress_var +
                            f'{append_step(self.mng.normal_stress_data_list[i].normal_stress)}'
                        )

                        self.pdf.add_equation(
                            tpdf.normal_stress_var +
                            f'{append_result(self.mng.normal_stress_data_list[i].normal_stress)}$ $Pa'
                        )
def render(img_filepath, output_list):
    image_filename = img_filepath.split('/')[-1]
    cwd = os.getcwd() + '/' + output_list[2]
    shutil.copy2(img_filepath, cwd)

    #print(image_filename)

    geometry_options = {"tmargin": "1cm", "lmargin": "1cm"}
    doc = Document(geometry_options=geometry_options)
    #creates image section in LaTeX

    with doc.create(Section("Xcos")):
        with doc.create(Figure(position='h!')) as abs_pic:
            abs_pic.add_image(image_filename, width='450px')
            doc.append("\n\n\n")
    #creates Context section in LaTeX if context exists
    if output_list[1]:
        with doc.create(Subsection("Context")):
            with doc.create(Itemize()) as itemize:
                for data in output_list[1]:
                    itemize.add_item(data)
    #creates Block section in LaTeX
    with doc.create(Subsection("Blocks")):
        for i in output_list[0]:
            if i is not None:
                doc.append("\n\n\n")
                with doc.create(Tabular('|c|c|')) as table:
                    table.add_hline()
                    for key, value in i.parameters().items():
                        table.add_row(key, value)
                        table.add_hline()

    file_path = output_list[2] + '/' + output_list[2]
    doc.generate_pdf(file_path, clean_tex=False)
Example #17
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
Example #18
0
    def _document_test_result(self) -> None:
        """Document test results including test summary, passed tests, and failed tests.
        """
        self.test_id = 1
        instance_pass_tests, aggregate_pass_tests, instance_fail_tests, aggregate_fail_tests = [], [], [], []

        for test in self.json_summary["tests"]:
            if test["test_type"] == "per-instance" and test["passed"]:
                instance_pass_tests.append(test)
            elif test["test_type"] == "per-instance" and not test["passed"]:
                instance_fail_tests.append(test)
            elif test["test_type"] == "aggregate" and test["passed"]:
                aggregate_pass_tests.append(test)
            elif test["test_type"] == "aggregate" and not test["passed"]:
                aggregate_fail_tests.append(test)

        with self.doc.create(Section("Test Summary")):
            with self.doc.create(Itemize()) as itemize:
                itemize.add_item(
                    escape_latex("Execution time: {:.2f} seconds".format(
                        self.json_summary['execution_time(s)'])))

            with self.doc.create(Table(position='H')) as table:
                table.append(NoEscape(r'\refstepcounter{table}'))
                self._document_summary_table(
                    pass_num=len(instance_pass_tests) +
                    len(aggregate_pass_tests),
                    fail_num=len(instance_fail_tests) +
                    len(aggregate_fail_tests))

        if instance_fail_tests or aggregate_fail_tests:
            with self.doc.create(Section("Failed Tests")):
                if len(aggregate_fail_tests) > 0:
                    with self.doc.create(Subsection("Failed Aggregate Tests")):
                        self._document_aggregate_table(
                            tests=aggregate_fail_tests)
                if len(instance_fail_tests) > 0:
                    with self.doc.create(
                            Subsection("Failed Per-Instance Tests")):
                        self._document_instance_table(
                            tests=instance_fail_tests,
                            with_id=bool(self.data_id))

        if instance_pass_tests or aggregate_pass_tests:
            with self.doc.create(Section("Passed Tests")):
                if aggregate_pass_tests:
                    with self.doc.create(Subsection("Passed Aggregate Tests")):
                        self._document_aggregate_table(
                            tests=aggregate_pass_tests)
                if instance_pass_tests:
                    with self.doc.create(
                            Subsection("Passed Per-Instance Tests")):
                        self._document_instance_table(
                            tests=instance_pass_tests,
                            with_id=bool(self.data_id))

        self.doc.append(NoEscape(r'\newpage'))  # For QMS report
 def append_radius_and_max_shear(self):
     with self.gen.doc.create(Section(self.gen.tpdf.radius_and_max_shear)):
         with self.gen.doc.create(Subsection(self.gen.tpdf.radius_and_max_shear_formula)):
             self.gen.pdf.add_equation(
                 self.gen.tpdf.radius_var + r' \sqrt{(\frac{\sigma_x-\sigma_y}{2})^2 + \tau_xy ^ 2)}')
         with self.gen.doc.create(Subsection(self.gen.tpdf.radius_and_max_shear_solving)):
             self.gen.pdf.add_equation(
                 self.gen.tpdf.radius_var + r' \sqrt{(\frac{' + fr'{self.res.sigma_x}-{self.res.sigma_y}' +
                 '}{2})^2 +' + f'{self.res.tau_xy}' + '^ 2)}')
             self.gen.pdf.add_equation(self.gen.tpdf.radius_var + f'{append_result(self.res.max_shear)}')
Example #20
0
def build_all(subdirs, preamble="preamble.tex"):
    doc = d = make_doc(preamble)
    for subdir in subdirs:
        chap = re.search(r"\d+", subdir).group(0)
        with d.create(Section(chap, numbering=False)):
            exos, probs = build_chap(chap, preamble)
            d.append(Subsection("Exercises", numbering=False, data=exos))
            if len(probs) > 0:
                d.append(Subsection("Problems", numbering=False, data=probs))
    return doc
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
Example #22
0
def complexStuff(doc):
    with doc.create(Section('The simple stuff')):
        doc.append('Some regular text and some')
        doc.append(italic('italic text. '))
        doc.append('\nAlso some crazy characters: $&#{}')
        with doc.create(Subsection('Math that is incorrect')):
            doc.append(Math(data=['2*3', '=', 9]))

        with doc.create(Subsection('Table of something')):
            with doc.create(Tabular('rc|cl')) as table:
                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))

    a = np.array([[100, 10, 20]]).T
    M = np.matrix([[2, 3, 4], [0, 0, 1], [0, 0, 2]])

    with doc.create(Section('The fancy stuff')):
        with doc.create(Subsection('Correct matrix equations')):
            doc.append(Math(data=[Matrix(M), Matrix(a), '=', Matrix(M * a)]))

        with doc.create(Subsection('Alignat math environment')):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(r'\frac{a}{b} &= 0 \\')
                agn.extend([Matrix(M), Matrix(a), '&=', Matrix(M * a)])

        with doc.create(Subsection('Beautiful graphs')):
            with doc.create(TikZ()):
                plot_options = 'height=4cm, width=6cm, grid=major'
                with doc.create(Axis(options=plot_options)) as plot:
                    plot.append(Plot(name='model', func='-x^5 - 242'))

                    coordinates = [
                        (-4.77778, 2027.60977),
                        (-3.55556, 347.84069),
                        (-2.33333, 22.58953),
                        (-1.11111, -493.50066),
                        (0.11111, 46.66082),
                        (1.33333, -205.56286),
                        (2.55556, -341.40638),
                        (3.77778, -1169.24780),
                        (5.00000, -3269.56775),
                    ]

                    plot.append(Plot(name='estimate', coordinates=coordinates))

        # with doc.create(Subsection('Cute kitten pictures')):
        #     with doc.create(Figure(position='h!')) as kitten_pic:
        #         kitten_pic.add_image(image_filename, width='120px')
        #         kitten_pic.add_caption('Look it\'s on its back')

    doc.generate_pdf('full', clean_tex=False)
    def append_center(self):
        with self.gen.doc.create(Section(self.gen.tpdf.center_solving)):
            with self.gen.doc.create(Subsection(self.gen.tpdf.center_formula)):
                self.gen.pdf.add_equation(self.gen.tpdf.center + r' = \frac{\sigma_x + \sigma_y}{2}')

            with self.gen.doc.create(Subsection(self.gen.tpdf.center_solving)):
                self.gen.pdf.add_equation(
                        self.gen.tpdf.center + r' = \frac{' + f'{self.res.sigma_x} +' + f'{self.res.sigma_y}' + '}{2}')
                self.gen.pdf.add_equation(
                    f'{self.gen.tpdf.center} = {append_result((self.res.sigma_x + self.res.sigma_y) / 2)}'
                )
 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 append_angle(self):
        with self.gen.doc.create(Section(self.gen.tpdf.angle_solving)):
            with self.gen.doc.create(Subsection(self.gen.tpdf.angle_formula)):
                self.gen.pdf.add_equation(r'\theta = \frac{arctan(\frac{\tau_{xy}}{\sigma_x - ' +
                                          f'{self.gen.tpdf.center} ' + '})}{2}')

            with self.gen.doc.create(Subsection(self.gen.tpdf.doing_math)):
                self.gen.pdf.add_equation(
                    r'\theta = \frac{arctan(\frac{' + f'{self.res.tau_xy}' + '}{' + f'{self.res.sigma_x}' +
                    f' - {(self.res.sigma_x + self.res.sigma_y) / 2}' + '}' + ')}{2}')
                self.gen.pdf.add_equation(f'\\theta = {append_result(abs(self.res.angle * 180 / numpy.pi))}')
                self.gen.doc.append(NoEscape(self.gen.tpdf.angle_tip))
                self.gen.pdf.add_equation(f'\\theta = {append_result(abs(self.res.angle * 90 / numpy.pi))}')
Example #26
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
 def append_results(self):
     with self.gen.doc.create(Section(self.gen.tpdf.results)):
         with self.gen.doc.create(Subsection(self.gen.tpdf.main_stress)):
             self.gen.doc.append(NoEscape(self.gen.tpdf.main_stress_roots_tip))
             self.gen.pdf.add_equation(r"\sigma_1 = " + f"{append_result(self.res.sigma_1)}")
             self.gen.pdf.add_equation(r"\sigma_2 = " + f"{append_result(self.res.sigma_2)}")
             self.gen.pdf.add_equation(r"\sigma_3 = " + f"{append_result(self.res.sigma_3)}")
         with self.gen.doc.create(Subsection(self.gen.tpdf.max_shear)):
             self.gen.doc.append(NoEscape(self.gen.tpdf.subs_1_in_3))
             self.gen.pdf.add_equation(
                 self.gen.tpdf.radius_var +
                 r' \frac{' + f'{append_result(self.res.sigma_1)} - {append_result(self.res.sigma_3)}' + r'}{2}')
             self.gen.pdf.add_equation(self.gen.tpdf.radius_var + f" {append_result(self.res.max_shear)}")
Example #28
0
    def add_alignment(self):

        if len(self.report[self.analysis.alignment_title][
                self.analysis.contig_alignment_title]) > 0:
            alignments = self.report[self.analysis.alignment_title][
                self.analysis.contig_alignment_title]
        else:
            return

        self.doc.append(NewPage())

        with self.doc.create(
                Section(self.analysis.alignment_title, numbering=False)):

            with self.doc.create(
                    Subsection(self.analysis.snp_indel_title,
                               numbering=False)):

                with self.doc.create(Tabular('ll', width=2)) as table:
                    table.add_row(
                        ('SNPs',
                         '{:,}'.format(self.analysis.quast_mismatches)))
                    table.add_row(('Small indels',
                                   '{:,}'.format(self.analysis.quast_indels)))
                self.doc.append(LineBreak())

            if len(self.report[self.analysis.alignment_title][
                    self.analysis.alignment_notes_title]) > 0:

                with self.doc.create(
                        Subsection(self.analysis.alignment_notes_title,
                                   numbering=False)):

                    left = FlushLeft()
                    for note in self.report[self.analysis.alignment_title][
                            self.analysis.alignment_notes_title]:
                        left.append(note)
                        left.append(LineBreak())
                    self.doc.append(left)

            for contig in alignments.index.tolist():

                contig_title = 'Alignment to ' + contig
                self.doc.append(
                    Command('graphicspath{{../circos/' + contig + '/}}'))
                image_png = os.path.basename(alignments[contig])

                with self.doc.create(Subsection(contig_title,
                                                numbering=False)):
                    with self.doc.create(Figure(position='H')) as figure:
                        figure.add_image(image_png, width='5in')
Example #29
0
    def add_alignment(self):

        if len(self.analysis.contig_alignment) > 0:
            alignments = self.analysis.contig_alignment
        else:
            return

        self.doc.append(NewPage())

        with self.doc.create(Section(self.alignment_title, numbering=False)):

            with self.doc.create(
                    Subsection(self.snp_indel_title, numbering=False)):

                with self.doc.create(Tabular('ll', width=2)) as table:
                    table.add_row(
                        ('SNPs',
                         '{:,}'.format(self.analysis.quast_mismatches)))
                    table.add_row(('Small indels',
                                   '{:,}'.format(self.analysis.quast_indels)))
                self.doc.append(LineBreak())

            if len(self.analysis.alignment_notes) > 0:

                with self.doc.create(
                        Subsection(self.alignment_notes_title,
                                   numbering=False)):

                    left = FlushLeft()
                    for note in self.analysis.alignment_notes:
                        left.append(note)
                        left.append(LineBreak())
                    self.doc.append(left)

            for contig in alignments.index.tolist():

                contig_title = 'Alignment to ' + contig
                self.doc.append(
                    Command('graphicspath{{../circos/' + contig + '/}}'))
                image_png = os.path.basename(alignments[contig])

                with self.doc.create(Subsection(contig_title,
                                                numbering=False)):
                    with self.doc.create(Figure(position='H')) as figure:
                        figure.add_image(image_png, width='5in')


        method = 'The genome assembly was aligned against the reference sequencing using dnadiff (v ' \
            + self.analysis.versions['dnadiff'] + ').'
        self.methods[self.reference_methods_title] = self.methods[
            self.reference_methods_title].append(pd.Series(method))
Example #30
0
    def gen_summary(self, score):
        '''
        - function generates the first part of the doc the summary of the final model
        - inputs are booleans to decide whether to show then in the report or not.
        '''
        with self.doc.create(Section('Summary', numbering=False)):
            # -------- Final Model Description --------#
            '''
            final model:- single: learner name, parameters
                        - ensemble: type, models(parameters, scores)
            '''
            self.doc.append(NoEscape(r'\leftskip=20pt'))
            with self.doc.create(
                    Subsection('Final Model Description', numbering=False)):
                self.doc.append(NoEscape(r'\leftskip=40pt'))
                # check if ensemble or single model from its name #
                #edit
                #if self.is_ensemble(self.experiments.iloc[0][0]):
                #    self.print_ensemble_models(self.experiments.iloc[0])
                if self.experiments.iloc[0][0] == "ensembleSelection":
                    self.print_ensemble(self.experiments.iloc[0])
                else:
                    model_name = self.get_model_name(
                        self.experiments.iloc[0][0])
                    self.doc.append(model_name + ": ")
                    self.print_param(self.experiments.iloc[0])

            # ----------- Number OF iterations -----------#
            self.doc.append(NoEscape(r'\leftskip=20pt'))
            with self.doc.create(
                    Subsection('Number of iterations', numbering=False)):
                self.doc.append(NoEscape(r'\leftskip=40pt'))
                self.doc.append(str(self.num_of_iter))

            # ----------- Number Of Features -------------#
            self.doc.append(NoEscape(r'\leftskip=20pt'))
            with self.doc.create(
                    Subsection('Number of features', numbering=False)):
                self.doc.append(NoEscape(r'\leftskip=40pt'))
                self.doc.append(str(self.num_of_features))

            # ---------- Classification / Regression ------#
            self.doc.append(NoEscape(r'\leftskip=20pt'))
            with self.doc.create(Subsection('Task type', numbering=False)):
                self.doc.append(NoEscape(r'\leftskip=40pt'))
                if self.regression:
                    self.doc.append('Regression')
                else:
                    self.doc.append('Classification')
            '''
Example #31
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
Example #32
0
#!/usr/bin/python3

import numpy as np

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)
Example #33
0
                addTimePlots(doc, options, coords)
                for o in options:
                    coords[o].clear()
                k = 0
                if len(objs)>0:
                    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':
Example #34
0
#!/usr/bin/python

from pylatex import (
    Document,
    Section,
    Subsection,
    Table,
    MultiColumn,
    MultiRow
)

doc = Document("multirow")
section = Section('Multirow Test')

test1 = Subsection('MultiColumn')
test2 = Subsection('MultiRow')
test3 = Subsection('MultiColumn and MultiRow')
test4 = Subsection('Vext01')

table1 = Table('|c|c|c|c|')
table1.add_hline()
table1.add_row((MultiColumn(4, '|c|', 'Multicolumn'),))
table1.add_hline()
table1.add_row((1, 2, 3, 4))
table1.add_hline()
table1.add_row((5, 6, 7, 8))
table1.add_hline()
row_cells = ('9', MultiColumn(3, '|c|', 'Multicolumn not on left'))
table1.add_row(row_cells)
table1.add_hline()
Example #35
0
#!/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]])
Example #36
0
#!/usr/bin/python3

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(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)
Example #37
0
This example shows quantities functionality.

..  :copyright: (c) 2014 by Jelte Fennema.
    :license: MIT, see License for more details.
"""

# begin-doc-include
import quantities as pq

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'},
Example #38
0
def main():
    img = imread('trui.png')

    if not os.path.isfile('d.npy'):
        sum_mat = np.zeros((m*m, m*m), np.int)
        mean_sum_vec = np.zeros((m*m, 1), np.int)

        for i in range(n-m+1):
            for j in range(n-m+1):
                detail = img[i:i+m, j:j+m].reshape((m*m, 1))

                sum_mat += detail * detail.T
                mean_sum_vec += detail

        mean_vec = mean_sum_vec / float(n*n)
        mean_mat = n * mean_vec * mean_vec.T

        S = (sum_mat - mean_mat) / ((m*m)-1)

        d, U = sorted_eig(S)

        np.save('d', d)
        np.save('U', U)
        np.save('mean_vec', mean_vec)
    else:
        d = np.load('d.npy')
        U = np.load('U.npy')
        mean_vec = np.load('mean_vec.npy')

    plt.bar(range(6), abs(d[:6]))
    # plt.show()

    with open('scree.tex', 'w') as f:
        plot = Plt(position='htbp')
        plot.add_plot(plt)
        plot.add_caption('Scree diagram')

        plot.dump(f)

    sec = Subsection('Gereconstrueerde foto\'s')
    with sec.create(Figure(position='htbp')) as fig:
        fig.add_image('trui.png')
        fig.add_caption('Origineel')

    for k in [0, 1, 3, 5, 7, 10, 20, 30, 50, 80, 120, 170,
              220, 300, 370, 450, 520, 590, 625]:
        reconstructed = np.zeros((n, n))

        for i in range(0, 232, 25):
            for j in range(0, 232, 25):
                subimg = compare(img, (i, j), mean_vec, d, U, k)
                reconstructed[i:i+25, j:j+25] = subimg.reshape((25, 25))

        plt.imshow(reconstructed, cmap=cm.Greys_r)
        plt.title('k = ' + str(k))
        # plt.show()

        with sec.create(Plt(position='htbp')) as plot:
            plot.add_plot(plt)
            plot.add_caption('k = ' + str(k))

    with open('images.tex', 'w') as f:
        sec.dump(f)
Example #39
0
########NEW FILE########
__FILENAME__ = numpy_ex
#!/usr/bin/python

import numpy as np

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])