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)
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
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 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 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))}')
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)
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()
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])
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')
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_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 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'))
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')
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
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 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)
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)}')
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 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 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_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))}')
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)}")
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')
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))
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') '''
def append_centroid(self, doc, tpdf): with doc.create(Section(tpdf.step_centroid)): with doc.create(Subsection(tpdf.centroid_x)): self.pdf.add_equation(r'X_{cg} = \frac{Ms_y}{A_{total}}') self.pdf.add_equation(r'X_{{cg}} = {}$ $m'.format( append_step(self.calc.total_cg_x))) self.pdf.add_equation(r'X_{{cg}} = {}$ $m'.format( append_result(self.calc.total_cg_x))) with doc.create(Subsection(tpdf.centroid_y)): self.pdf.add_equation(r'Y_{cg} = \frac{Ms_x}{A_{total}}') self.pdf.add_equation(r'Y_{{cg}} = {}$ $m'.format( append_step(self.calc.total_cg_y))) self.pdf.add_equation(r'Y_{{cg}} = {}$ $m'.format( append_result(self.calc.total_cg_y)))
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
def _loop_tables(self, start: int, classes: Union[type, Tuple[type, ...]], name: str, model_ids: Set[FEID], datasets: Dict[FEID, Tuple[Set[str], Any]]) -> int: """Iterate through tables grouping them into subsections. Args: start: What index to start searching from. classes: What classes are acceptable for this subsection. name: What to call this subsection. model_ids: The ids of any known models. datasets: A mapping like {ID: ({modes}, dataset)}. Useful for augmenting the displayed information. Returns: The new start index after traversing as many spaces as possible along the list of tables. """ stop = start while stop < len(self.config_tables): if classes == Any or issubclass(self.config_tables[stop].type, classes): stop += 1 else: break if stop > start: self.doc.append(NoEscape(r'\FloatBarrier')) with self.doc.create(Subsection(name)): self._write_tables(self.config_tables[start:stop], model_ids, datasets) return stop
def _document_fe_graph(self) -> None: """Add FE execution graphs into the traceability document. """ with self.doc.create(Section("FastEstimator Architecture")): for mode in self.system.pipeline.data.keys(): scheduled_items = self.system.pipeline.get_scheduled_items( mode) + self.system.network.get_scheduled_items(mode) + self.system.traces signature_epochs = get_signature_epochs(scheduled_items, total_epochs=self.system.epoch_idx, mode=mode) epochs_with_data = self.system.pipeline.get_epochs_with_data(total_epochs=self.system.epoch_idx, mode=mode) if set(signature_epochs) & epochs_with_data: self.doc.append(NoEscape(r'\FloatBarrier')) with self.doc.create(Subsection(mode.capitalize())): for epoch in signature_epochs: if epoch not in epochs_with_data: continue self.doc.append(NoEscape(r'\FloatBarrier')) with self.doc.create( Subsubsection(f"Epoch {epoch}", label=Label(Marker(name=f"{mode}{epoch}", prefix="ssubsec")))): diagram = self._draw_diagram(mode, epoch) ltx = d2t.dot2tex(diagram.to_string(), figonly=True) args = Arguments(**{'max width': r'\textwidth, max height=0.9\textheight'}) args.escape = False with self.doc.create(Center()): with self.doc.create(AdjustBox(arguments=args)) as box: box.append(NoEscape(ltx))
def add_result(self, image_id, quest_id, im_path, answer, questions): with self._doc.create(Section('quest_id: %d' % quest_id)): # add figure with self._doc.create(Figure(position='h!')) as fig: fig.add_image(im_path, width='%dpx' % _compute_width(im_path)) fig.add_caption('Image: %d' % image_id) # add answer with self._doc.create(Subsection('%s' % answer)): if len(questions) % 2 == 1: questions.append('') with self._doc.create(Tabular(table_spec='|l|l|')) as table: num = int(len(questions) * 0.5) table.add_hline() for i in range(num): a = '%s' % questions[2 * i].capitalize() a = textwrap.fill(a, width=45).split('\n') len_a = len(a) b = '%s' % questions[2 * i + 1].capitalize() b = textwrap.fill(b, width=45).split('\n') len_b = len(b) max_len = max(len_a, len_b) a += [''] * (max_len - len_a) b += [''] * (max_len - len_b) for a_i, b_i in zip(a, b): table.add_row((a_i, b_i)) table.add_hline() # table.add_hline() # questions # for q in questions: # self._doc.append('\n%s' % q.capitalize()) # with self._doc.create(Itemize()) as item: # for q in questions: # item.add_item(q.capitalize()) self._doc.append(NewPage())