def get_latex_table_type1( doc, results=None, method_names=["OSSN", "RKO", "SVCM", "BCOP"], config_names=["Clean", "Robust"], eps=["1.58", "0.1411764706"], ): dataset_names = [MNISTRepr, CIFAR10Repr] arch_names = ["Small", "Large"] num_archs = len(arch_names) num_configs = len(config_names) num_methods = len(method_names) fmt = "c|cc|" + "c" * num_methods num_cols = 3 + num_methods with doc.create(Tabularx(fmt)) as data_table: headers = tuple( map( lambda x: NoEscape(boldify(x)), ("Dataset", "", "") + tuple(method_names), )) data_table.add_row(headers) cmidrule(data_table, 1, num_cols) for dataset_name, ep in zip(dataset_names, eps): multi_row_outer = MultiRow(num_archs * num_configs, data=NoEscape(dataset_name)) for i, arch_name in enumerate(arch_names): multi_row_inner = MultiRow(num_configs, data=NoEscape(boldify(arch_name))) for j, config_name in enumerate(config_names): row = () if i == 0 and j == 0: row += (multi_row_outer, ) else: row += ("", ) if j == 0: row += (multi_row_inner, ) else: row += ("", ) row += (config_name, ) row += populate_numbers([ results[( dataset_name, arch_name, method_name, None, config_name, ep, )] for method_name in method_names ]) data_table.add_row(row) if i != num_archs - 1: cmidrule(data_table, 2, num_cols) cmidrule(data_table, 1, num_cols)
def InsDatosEscolares(hasImage): with self.doc.create( Tabular( NoEscape("m{0.8in}m{0.6in}m{0.9in}m{1.5in}m{2.3in}")) ) as table: if hasImage: image = MultiRow( 3, data=Command( "includegraphics", NoEscape(self.data["Foto"] [self.data["Foto"].rfind("/") + 1:][:self.data["Foto"].rfind(".")]), ["width=1.5in", "height=1in"])) else: image = "" table.add_row(("", "", "", "", "")) table.add_row(("", "", "", "", image)) table.add_row( (bold("Matrícula: "), self.data["Matrícula"], bold("Licenciatura: "), self.data["Licenciatura"], "")) table.add_row( (bold("Semestre: "), self.data["Semestre"], bold("Generación: "), self.data["Generación"], ""))
def test_table(): # Tabular t = Tabular(table_spec='|c|c|', data=None, pos=None) t.add_hline(start=None, end=None) t.add_row(cells=(1, 2), escape=False) t.add_multicolumn(size=2, align='|c|', content='Multicol', cells=None, escape=False) t.add_multirow(size=3, align='*', content='Multirow', hlines=True, cells=None, escape=False) # MultiColumn/MultiRow. t.add_row((MultiColumn(size=2, align='|c|', data='MultiColumn'), )) t.add_row((MultiRow(size=2, width='*', data='MultiRow'), ))
def get_latex_table_type3( doc, results=None, dataset_name=WDEReprSTL10, arch_names=["MaxMin", "ReLU"], lr="0.0001", ): method_names = ["OSSN", "RKO", "BCOP"] num_archs = len(arch_names) num_methods = len(method_names) fmt = "cc" + "c" * num_methods num_cols = 2 + num_methods with doc.create(Tabularx(fmt)) as data_table: headers = tuple( map(lambda x: NoEscape(boldify(x)), ("", "") + tuple(method_names))) data_table.add_row(headers) cmidrule(data_table, 1, num_cols) multi_row_outer = MultiRow(num_archs, data=NoEscape(dataset_name)) for i, arch_name in enumerate(arch_names): if i == 0: row = (multi_row_outer, ) else: row = ("", ) row += (NoEscape(boldify(arch_name)), ) row += populate_numbers([ results[(dataset_name, arch_name, method_name, lr, "Loss", None)] for method_name in method_names ]) data_table.add_row(row)
def quadro_epis(self, fichas_exposicao): with self.create(LongTabu("|X[l]|X[l]|")) as tabela_epi: tabela_epi.add_hline() tabela_epi.add_row( (MultiColumn(2, align='|c|', data=bold('Quadro Demonstrativo de EPIs')), )) tabela_epi.add_hline() tabela_epi.add_row((bold('Função'), bold('EPIs Indicados'))) tabela_epi.add_hline() tabela_epi.end_table_header() tabela_epi.add_row( (MultiColumn(2, align='|c|', data='Continua na próxima página'), )) tabela_epi.add_hline() tabela_epi.end_table_footer() tabela_epi.end_table_last_footer() for ficha in fichas_exposicao: epis = ficha['epis'] if not len(epis): continue col_cargo = MultiRow(len(epis), data=ficha['cargo']) row = [col_cargo, epis[0]] tabela_epi.add_row(row) for epi in epis[1:]: tabela_epi.add_row(('', epi)) tabela_epi.add_hline()
def quadro_planejamento(self, planejamento_acoes): with self.create( LongTabu("|X[1,l]|X[3,l]|X[6,l]|")) as tabela_planejamento: tabela_planejamento.add_hline() tabela_planejamento.add_row( (MultiColumn(3, align='|c|', data=bold('Cronograma de Ações')), )) tabela_planejamento.add_hline() tabela_planejamento.add_row( (bold('Prazo'), bold('Ação'), bold('Prioridade'))) tabela_planejamento.add_hline() tabela_planejamento.end_table_header() tabela_planejamento.add_hline() tabela_planejamento.add_row( (MultiColumn(3, align='|r|', data='Continua na próxima página'), )) tabela_planejamento.add_hline() tabela_planejamento.end_table_footer() tabela_planejamento.end_table_last_footer() for acao in planejamento_acoes: metas = acao['metas'] if not len(metas): continue col_meta = MultiRow(len(metas), data=acao['prazo'].capitalize()) row = [col_meta, acao['acao'], '1. ' + metas[0]] tabela_planejamento.add_row(row) for meta in metas[1:]: tabela_planejamento.add_row( ('', '', (str(metas.index(meta) + 1) + '. ' + meta))) tabela_planejamento.add_hline()
def quadro_funcionarios(self, quadro_funcionarios, total_masc, total_fem, total_fun): with self.create( LongTabu("|X[3,c]|X[c]|X[c]|")) as tabela_funcionarios: tabela_funcionarios.add_hline() tabela_funcionarios.add_row( (MultiRow(2, data=bold('Função')), MultiColumn(2, align='c|', data=bold('Número de Funcionários')))) tabela_funcionarios.add_hline(2, 3) tabela_funcionarios.add_row( ('', bold('Masculino'), bold('Feminino'))) tabela_funcionarios.end_table_header() tabela_funcionarios.add_row( (MultiColumn(3, align='|r|', data='Continua na próxima página'), )) tabela_funcionarios.add_hline() tabela_funcionarios.end_table_footer() tabela_funcionarios.add_hline() tabela_funcionarios.add_row( (MultiRow(2, data=bold('Total Funcionários')), bold(total_masc), bold(total_fem))) tabela_funcionarios.add_hline(2, 3) tabela_funcionarios.add_row( ('', MultiColumn(2, align='c|', data=bold(total_fun)))) tabela_funcionarios.add_hline() tabela_funcionarios.end_table_last_footer() for funcao in quadro_funcionarios: row = [ funcao['funcao'], funcao['qtdMasculino'], funcao['qtdFeminino'] ] tabela_funcionarios.add_hline() tabela_funcionarios.add_row(row)
def test_table(): # Tabular t = Tabular(table_spec='|c|c|', data=None, pos=None, width=2) t.add_hline(start=None, end=None) t.add_row((1, 2), escape=False, strict=True, mapper=[bold]) t.add_row(1, 2, escape=False, strict=True, mapper=[bold]) # MultiColumn/MultiRow. t.add_row((MultiColumn(size=2, align='|c|', data='MultiColumn'), ), strict=True) # One multiRow-cell in that table would not be proper LaTeX, # so strict is set to False t.add_row((MultiRow(size=2, width='*', data='MultiRow'), ), strict=False) repr(t) # TabularX tabularx = Tabularx(table_spec='X X X', width_argument=NoEscape(r"\textwidth")) tabularx.add_row(["test1", "test2", "test3"]) # Long Table longtable = LongTable(table_spec='c c c') longtable.add_row(["test", "test2", "test3"]) longtable.end_table_header() # Colored Tabu coloredtable = Tabu(table_spec='X[c] X[c]') coloredtable.add_row(["test", "test2"], color="gray", mapper=bold) # Colored Tabu with 'spread' coloredtable = Tabu(table_spec='X[c] X[c]', spread="1in") coloredtable.add_row(["test", "test2"], color="gray", mapper=bold) # Colored Tabu with 'to' coloredtable = Tabu(table_spec='X[c] X[c]', to="5in") coloredtable.add_row(["test", "test2"], color="gray", mapper=bold) # Colored Tabularx coloredtable = Tabularx(table_spec='X[c] X[c]') coloredtable.add_row(["test", "test2"], color="gray", mapper=bold) # Column column = ColumnType("R", "X", r"\raggedleft", parameters=2) repr(column)
def test_table(): # Tabular t = Tabular(table_spec='|c|c|', data=None, pos=None) t.add_hline(start=None, end=None) t.add_row(cells=(1, 2), escape=False, strict=True) # MultiColumn/MultiRow. t.add_row((MultiColumn(size=2, align='|c|', data='MultiColumn'), ), strict=True) # One multiRow-cell in that table would not be proper LaTeX, # so strict is set to False t.add_row((MultiRow(size=2, width='*', data='MultiRow'), ), strict=False) repr(t)
def get_latex_table_type1b( doc, results=None, method_arch_names=[ ("BCOP", "Large"), ("FC", "3"), ("KW", "Large "), ("KW", "Resnet"), ], eps=["1.58", "0.1411764706"], config_names=["Clean", "Robust"], ): dataset_names = [MNISTRepr, CIFAR10Repr] num_configs = len(config_names) num_methods = len(method_arch_names) fmt = "c|c|" + "c" * num_methods num_cols = 2 + num_methods with doc.create(Tabularx(fmt)) as data_table: headers = (NoEscape(boldify("Dataset")), "") + tuple( map(lambda x: NoEscape(boldify("{}-{}".format(*x))), method_arch_names)) data_table.add_row(headers) cmidrule(data_table, 1, num_cols) for dataset_name, ep in zip(dataset_names, eps): multi_row_outer = MultiRow(num_configs, data=NoEscape(dataset_name)) for j, config_name in enumerate(config_names): row = () if j == 0: row += (multi_row_outer, ) else: row += ("", ) row += (config_name, ) row += populate_numbers([ results[( dataset_name, arch_name, method_name, None, config_name, ep, )] for method_name, arch_name in method_arch_names ]) data_table.add_row(row) cmidrule(data_table, 1, num_cols)
doc.append(NoEscape(r'\tableofcontents')) doc.append(NewPage()) #Summary Chapter 1 doc.append(NoEscape(r'\chapter{Executive Summary}')) doc.append(NewPage()) #The recent data table #central debt section 1.1 with doc.create(Section('Central Government Debt')): with doc.create(Tabular('l|l|r|r')) as table: table.add_row(('Date', 'Type', 'USD bn (Total)','ARS bn (Total)')) table.add_hline() #Sep table.add_row(MultiRow(4,data='Sep 2019'),'By Currency [Domestic (ARS); External]',dfUSDSep['Total'].values[0],dfARSSep['Total'].values[0]) table.add_row('', 'By Currency [ARS; EUR; JPY; USD; SDR]', dfCurUSDSep['Total'].values[0], dfCurARSSep['Total'].values[0]) table.add_row('', 'By Legislation Type [Domestic; External]', dfLegUSDSep['deuda bruta'].values[0], dfLegARSSep['deuda bruta'].values[0]) table.add_row('','FX Reserves', dfFXUSDSep['Total'].values[0], dfFXARSSep['Total'].values[0]) table.add_hline() #June table.add_row(MultiRow(2,data='Jun 2019'), 'By Holder[Resident; Non-Resident]', dflastResUSD['Total'].values[0], dflastResARS['Total'].values[0]) #table.add_row('', 'By Currency [ARS; EUR; JPY; USD; SDR]', dflastCurUSD['Total'].values[0], dflastCurARS['Total'].values[0]) #table.add_row('', 'By Legislation Type [Domestic; External]', dflastLegUSD['deuda bruta'].values[0], dflastLegARS['deuda bruta'].values[0]) #table.add_row('', 'By Holder[resident; nonresident]', dflastResUSD['Total'].values[0], dflastResARS['Total'].values[0]) table.add_row('', 'Foreign Holdings of Domestic Currency Bonds', dflastExtUSD['Total'].values[0], dflastExtARS['Total'].values[0]) #table.add_row('','FX Reserves', dfJunFXUSD['Total'].values[0], dfJunFXARS['Total'].values[0]) NO JUNE VALUE #Mendoza Debt section 1.2 with doc.create(Section('Other Public Debt')): with doc.create(Tabular('l|l|r|r')) as table:
def doit(self): is_multirow = self.num_metrics > 1 and self.spec.multirow def render_metric(value, best, second, decimals, format_string, highlight_top, relative_to): if isinstance(value, numbers.Number): if relative_to is None or relative_to == 0 or not np.isfinite( relative_to): # absolute number rendered = format_string.format(value, prec=decimals) else: # percent rendered = format_ratio_percent(value, relative_to, decimals=decimals) if highlight_top: if value == best: rendered = bold(rendered) elif value == second: rendered = italic(rendered) return rendered else: return value if self.spec.export_latex: row_height = None else: row_height = 0.65 if is_multirow and self.num_metrics >= 3 else 1 column_spec = '|r' if self.spec.vertical_bars else 'r' t = Tabular('l' + column_spec * self.num_exps, row_height=row_height, pos=['t']) escape_header_fun = lambda text: text if self.spec.escape_latex_header else NoEscape( text) if self.spec.rotate_header: t.add_row([''] + [ NoEscape(r"\rotatebox{90}{%s}" % escape_latex( escape_header_fun(s.display_name(self.exps[s.name])))) for s in self.experiment_specs ]) else: t.add_row([''] + [ escape_header_fun(s.display_name(self.exps[s.name])) for s in self.experiment_specs ]) t.add_hline() for seq in self.seq_names: fails = [ self.is_failed(self.exps[s.name], seq) for s in self.experiment_specs ] failure_strings = [ self.render_failure(self.exps[s.name], seq) for s in self.experiment_specs ] values = np.array([ self.get_metrics(self.exps[s.name], seq, s.it) for s in self.experiment_specs ]) top_values = list(range(self.num_metrics)) for c, m in enumerate(self.metrics): try: values[:, c] = np.around(values[:, c], m.decimals) except IndexError: pass non_excluded_values = np.array(values[:, c]) for i in m.exclude_columns_highlight: non_excluded_values[i] = math.nan top_values[c] = best_two_non_repeating( non_excluded_values, reverse=m.larger_is_better) if is_multirow: rows = [[ MultiRow(self.num_metrics, data=self.seq_displayname(seq)) ]] + [list(['']) for _ in range(1, self.num_metrics)] else: rows = [[self.seq_displayname(seq)]] for c, (fail, failure_str, value_col) in enumerate(zip(fails, failure_strings, values)): if failure_str is not None: if self.spec.color_failed: failure_str = TextColor(self.spec.color_failed, failure_str) if is_multirow: rows[0].append( MultiRow(self.num_metrics, data=failure_str)) for r in range(1, self.num_metrics): rows[r].append('') else: rows[0].append(failure_str) else: tmp_data = [None] * self.num_metrics for r, m in enumerate(self.metrics): if m.failed_threshold and value_col[ r] > m.failed_threshold: obj = "x" if self.spec.color_failed: obj = TextColor(self.spec.color_failed, obj) else: relative_to = None if m.relative_to_column is not None and m.relative_to_column != c: relative_to = values[m.relative_to_column, r] obj = render_metric(value_col[r], top_values[r][0], top_values[r][1], m.effective_display_decimals(), m.format_string, m.highlight_top, relative_to=relative_to) if fail and self.spec.color_failed: obj = TextColor(self.spec.color_failed, obj) tmp_data[r] = obj if self.num_metrics == 1 or is_multirow: for r, obj in enumerate(tmp_data): rows[r].append(obj) else: entry = [] for v in tmp_data: entry.append(v) entry.append(NoEscape("~/~")) entry.pop() rows[0].append(dumps_list(entry)) for row in rows: t.add_row(row) if is_multirow: t.add_hline() if self.spec.export_latex: os.makedirs(self.export_basepath, exist_ok=True) t.generate_tex( os.path.join(self.export_basepath, self.spec.export_latex)) with self.create(Subsection(self.spec.name, numbering=False)) as p: if self.spec.metrics_legend: legend = Tabular('|c|', row_height=row_height, pos=['t']) legend.add_hline() legend.add_row(["Metrics"]) legend.add_hline() for m in self.metrics: legend.add_row([m.display_name]) legend.add_hline() tab = Tabular("ll") tab.add_row([t, legend]) content = tab else: content = t if True: content = FootnoteText(content) p.append(content)
doc.append(r'\begin{table*}') doc.append(r'\begin{preview}') doc.append(r'{\footnotesize') doc.append(r'\centering') #Declare table with doc.create(Table('l c c c c c c c')) as tab: row1 = ['Date' , 'Spectral range', 'Disp.' , 'R$^a_{\rm{FWHM}}$', 'Spatial res.' , 'PA', 'Exposure Time' , r'{seeing $_{\rm{FWHM}}$}'] row2 = [' ' , '(\AA\,px$^{-1}$)', ' ' , ' ', '("\,px$^{-1}$)' , '($ ^{o} $)', '(sec)' , '($"$)'] row3 = ['2000 February 4' , '4779-5199','0.21', '$\sim$\,12500' , '0.38' , '50' , '3\,$\cdot$\,1200' , '{1.2}'] row4 = ['', '8363-8763','0.39', '$\sim$\,12200' , '0.36' , '50' , '3\,$\cdot$\,1200' , ' '] row5 = ['2000 February 5' , '4779-5199','0.21', '$\sim$\,12500' , '0.38' , '50' , '3\,$\cdot$\,1200' , '{1.2}'] row6 = ['', '8363-8763','0.39', '$\sim$\,12200' , '0.36' , '50' , '3\,$\cdot$\,1200' , ' '] row7 = MultiRow(7, '|l|', '$^a$R$_{\rm{FWHM}}$\,=\,$\lambda$/$\Delta\lambda_{\rm{FWHM}}$') tab.add_hline() tab.add_row(row1) tab.add_row(row2) tab.add_hline() tab.add_row(row3) tab.add_row(row4) tab.add_row(row5) tab.add_row(row6) tab.add_hline() tab.add_row(row7) #Declare table after comands doc.append('}') doc.append(r'\end{preview}')
n_estimators=estimator, max_samples=samp, max_features=feat)) clfs.append(temp2_clf) for data in dataset: db = getattr(importdata, 'load_' + data)() print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") print('Zbior danych: %s' % data) importdata.print_info(db.target) # obliczanie wynikow for id, (clfs_, name) in enumerate(zip(clfs, estimators_name)): rows = [] if id == 0: col = MultiRow(5, data=data) else: col = '' for i in range(5): rows.append([col, name]) for clf in clfs_: scores = [] for iteration in range(iterations): clf_ = clone(clf) # sprawdzian krzyzowy testpredict, testtarget = cross_val_pred2ict(clf_, db.data, db.target, cv=folds, n_jobs=-1) scores.append(accsespf1g(testpredict, testtarget))
def tabela_previsao_orcamentaria(doc, enum, previsao_orcamentaria): item(doc, enum, NoEscape(r'PREVISÃO ORÇAMENTÁRIA: \\')) # TODO: blank=True para os DecimalField inscricoes = previsao_orcamentaria.inscricoes or 0 convenios = previsao_orcamentaria.convenios or 0 patrocinios = previsao_orcamentaria.patrocinios or 0 fonte_financiamento = previsao_orcamentaria.fonte_financiamento or 0 honorarios = previsao_orcamentaria.honorarios or 0 passagens = previsao_orcamentaria.passagens or 0 alimentacao = previsao_orcamentaria.alimentacao or 0 hospedagem = previsao_orcamentaria.hospedagem or 0 divulgacao = previsao_orcamentaria.divulgacao or 0 material_consumo = previsao_orcamentaria.material_consumo or 0 xerox = previsao_orcamentaria.xerox or 0 certificados = previsao_orcamentaria.certificados or 0 outros = previsao_orcamentaria.outros or 0 outros_especificacao = previsao_orcamentaria.outros_especificacao or '' # TODO: não estão sendo usadas # fundacao = previsao_orcamentaria.fundacao or '' # outro_orgao_gestor = previsao_orcamentaria.outro_orgao_gestor or '' total_receitas = (inscricoes + convenios + patrocinios + fonte_financiamento) total_despesas = (honorarios + passagens + alimentacao + hospedagem + divulgacao + material_consumo + xerox + certificados + outros) with doc.create(Tabularx('|' + 'X|' * 4, width_argument=WIDTH_ARGUMENT)) as tab: tab.add_hline() tab.add_row(MultiColumn(2, data=bold('Receitas'), align='|c|'), MultiColumn(2, data=bold('Despesas'), align='c|')) tab.add_hline() tab.add_row('Inscrições', inscricoes, 'Honorários', honorarios) tab.add_hline() tab.add_row('Convênios', convenios, 'Passagens', passagens) tab.add_hline() tab.add_row('Patrocínios', patrocinios, 'Alimentação', alimentacao) tab.add_hline() tab.add_row('Fonte(s) de financiamento', fonte_financiamento, 'Hospedagem', hospedagem) tab.add_hline() tab.add_row('', '', 'Divulgação', divulgacao) tab.add_hline() tab.add_row('', '', 'Material de consumo', material_consumo) tab.add_hline() tab.add_row('', '', 'Xerox', xerox) tab.add_hline() tab.add_row('', '', 'Certificados', certificados) tab.add_hline() tab.add_row('', '', 'Outros (especificar)', '{}\n{}'.format(str(outros), outros_especificacao)) tab.add_hline() tab.add_row(bold('Total'), total_receitas, MultiRow(2, data=bold('Total')), MultiRow(2, data=total_despesas)) doc.append(UnsafeCommand('cline', '1-2')) # TODO: não tem atributo para saldo previsto na classe PrevisaoOrcamentaria_CursoExtensao tab.add_row(bold('Saldo previsto'), '', '', '') tab.add_hline()
def generateTex(filepath=None): #read all score files for different triple size and store them in lists #scores ordered in list as: BLEU METEOR TER # get Astronaut score mdBase_Athlete = searchScores('Athlete_score.txt') flat_Athlete = searchScores('flat_Athlete_score.txt') # get City score mdBase_Artist = searchScores('Artist_score.txt') flat_Artist = searchScores('flat_Artist_score.txt') # get Food score mdBase_Politician = searchScores('Politician_score.txt') flat_Politician = searchScores('flat_Politician_score.txt') geometry_options = {"tmargin": "1cm", "lmargin": "5cm"} doc = Document(geometry_options=geometry_options) with doc.create( Section( 'The evaluation scores for different DBpedia categories of Unseen dataset:' )): doc.append(italic('=============================================\n')) doc.append( 'Comparing the evaluation scores between two model: (flat, modify baseline) according to different DBpedia categories, which are:Athlete,Artist,Politician \n' ) doc.append( italic( 'We mean by "flat" one model from the extended system which contains 3 model:flat,str1,str2\n' )) doc.append( italic( 'Where we evaluate just this model in term of different DBpedia categories, because the result of other models i.e. str1&str2 for the whole dataset unseen and unseen not very good comparing by this model\n' )) doc.append( italic( 'We mean by "Modify baseline" the modified baseline of webnlg challeng \n' )) with doc.create(Subsection('Table of Evaluation in term of BLEU \n')): with doc.create(Tabular('|c|c|c|')) as table: table.add_hline() table.add_row(bold("Category Name"), bold("Model"), bold("BLEU")) table.add_hline() table.add_row((MultiRow(3, data='Athlete'), "Modify Baseline", mdBase_Athlete[0])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flat_Athlete[0]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Artist'), "Modify Baseline", mdBase_Artist[0])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flat_Artist[0]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Politician'), "Modify Baseline", mdBase_Politician[0])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flat_Politician[0]))) table.add_hline() table.add_hline() # Generate METEOR score table with doc.create( Subsection('Table of Evaluation in term of METEOR \n')): with doc.create(Tabular('|c|c|c|')) as table: table.add_hline() table.add_row(bold("Category Name"), bold("Model"), bold("METEOR")) table.add_hline() table.add_row((MultiRow(3, data='Athlete'), "Modify Baseline", mdBase_Athlete[1])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flat_Athlete[1]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Artist'), "Modify Baseline", mdBase_Artist[1])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flat_Artist[1]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Politician'), "Modify Baseline", mdBase_Politician[1])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flat_Politician[1]))) table.add_hline() table.add_hline() # Generate TER score table with doc.create(Subsection('Table of Evaluation in term of TER \n')): with doc.create(Tabular('|c|c|c|')) as table: table.add_hline() table.add_row(bold("Category Name"), bold("Model"), bold("TER")) table.add_hline() table.add_row((MultiRow(3, data='Athlete'), "Modify Baseline", mdBase_Athlete[2])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flat_Athlete[2]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Artist'), "Modify Baseline", mdBase_Artist[2])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flat_Artist[2]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Politician'), "Modify Baseline", mdBase_Politician[2])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flat_Politician[2]))) table.add_hline() table.add_hline() doc.generate_pdf('Category_Unseen_Evaluation ', clean_tex=False)
section = Section('Multirow Test') test1 = Subsection('MultiColumn') test2 = Subsection('MultiRow') test3 = Subsection('MultiColumn and MultiRow') test4 = Subsection('Vext01') DAYS = ['TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'] tabular = '|' tabular = tabular + '|'.join([''.join('c') for x in range(len(DAYS) + 1)]) + '|' table4 = Tabular(tabular) table4.add_hline() table4.add_row((MultiColumn(1, align='|c|', data=''), *DAYS)) table4.add_hline() col1_cell = MultiRow(2, data='WEEK 1') table4.add_row((col1_cell, *DAYS)) table4.add_hline(start=2) table4.add_row("1", "2", "3", "4", "5", "6", "7") table4.add_hline() #for x in DAYS: # table2.add_empty_row() # table2.add_hline() test2.append(table4) section.append(table4) #test2.append(table_week_header) #test2.append(table_week1_row) #section.append(table_week_header) #section.append(table_week1_row)
#1.1 with doc.create(Section('Central Government Debt')): with doc.create(Tabular('l|l|r')) as table: table.add_row(('Date', 'Type', 'USD bn (Total)')) table.add_hline() #Sep table.add_row('Mar 2019', 'By Legal Jurisdiction', dfResUSDMar['Total'].values[0]) #1.2 with doc.create(Section('Other Public Debt')): #1.2.1 with doc.create(Subsection('Gross Debt')): with doc.create(Tabular('l|l|r')) as table: table.add_row(('Date', 'Type', 'USD bn (Total)')) table.add_hline() table.add_row(MultiRow(5, data='Mar 2019'), 'By Issuer', dfGrByIssuerUSDMar['Total'].values[0]) table.add_row('', 'By Instrument', dfGrByInstrUSDMar['Total'].values[0]) table.add_row('', 'By Currency', dfGrByCurUSDMar['Total'].values[0]) table.add_row('', 'By Residency', dfGrByHoldResUSDMar['Total'].values[0]) table.add_row('', 'By Interest', dfGrByIntrUSDMar['Total'].values[0]) #1.2.2 with doc.create(Subsection('Consolidated Debt')): with doc.create(Tabular('l|l|r')) as table: table.add_row(('Date', 'Type', 'USD bn (Total)')) table.add_hline() table.add_row(MultiRow(4, data='Mar 2019'), 'By Issuer',
def save_latex(self, uiObj, Design_Check, reportsummary, filename, rel_path, Disp_2d_image, Disp_3d_image, module=''): companyname = str(reportsummary["ProfileSummary"]['CompanyName']) companylogo = str(reportsummary["ProfileSummary"]['CompanyLogo']) groupteamname = str(reportsummary["ProfileSummary"]['Group/TeamName']) designer = str(reportsummary["ProfileSummary"]['Designer']) projecttitle = str(reportsummary['ProjectTitle']) subtitle = str(reportsummary['Subtitle']) jobnumber = str(reportsummary['JobNumber']) client = str(reportsummary['Client']) does_design_exist = reportsummary['does_design_exist'] osdagheader = '/ResourceFiles/images/Osdag_header_report.png' # Add document header geometry_options = { "top": "5cm", "hmargin": "2cm", "headheight": "100pt", "footskip": "100pt", "bottom": "5cm" } doc = Document(geometry_options=geometry_options, indent=False) doc.packages.append(Package('amsmath')) doc.packages.append(Package('graphicx')) doc.packages.append(Package('needspace')) doc.append(pyl.Command('fontsize', arguments=[8, 12])) doc.append(pyl.Command('selectfont')) doc.add_color('OsdagGreen', 'RGB', '153,169,36') doc.add_color('PassColor', 'RGB', '153,169,36') doc.add_color('Red', 'RGB', '255,0,0') doc.add_color('Green', 'RGB', '0,200,0') doc.add_color('FailColor', 'HTML', '933A16') header = PageStyle("header") # Create center header with header.create(Head("C")): with header.create(Tabularx('|l|p{4cm}|l|X|')) as table: table.add_hline() # MultiColumn(4) table.add_row(( MultiColumn( 2, align='|c|', data=('' if companylogo is '' else StandAloneGraphic( image_options="height=0.95cm", filename=companylogo))), MultiColumn(2, align='|c|', data=[ 'Created with', StandAloneGraphic( image_options="width=4.0cm,height=1cm", filename=rel_path + osdagheader) ]), )) table.add_hline() table.add_row(('Company Name', companyname, 'Project Title', projecttitle), color='OsdagGreen') table.add_hline() table.add_row( ('Group/Team Name', groupteamname, 'Subtitle', subtitle), color='OsdagGreen') table.add_hline() table.add_row(('Designer', designer, 'Job Number', jobnumber), color='OsdagGreen') table.add_hline() table.add_row( ('Date', time.strftime("%d /%m /%Y"), 'Client', client), color='OsdagGreen') table.add_hline() # Create right footer with header.create(Foot("R")): header.append(NoEscape(r'Page \thepage')) # # doc.preamble.append(header) # doc.change_document_style("header") # Add Heading # with doc.create(MiniPage(align='c')): doc.preamble.append(header) doc.change_document_style("header") with doc.create(Section('Input Parameters')): with doc.create( LongTable('|p{5cm}|p{2.5cm}|p{1.5cm}|p{3cm}|p{3.5cm}|', row_height=1.2)) as table: table.add_hline() for i in uiObj: # row_cells = ('9', MultiColumn(3, align='|c|', data='Multicolumn not on left')) if i == "Selected Section Details" or i == KEY_DISP_ANGLE_LIST or i == KEY_DISP_TOPANGLE_LIST or i == KEY_DISP_CLEAT_ANGLE_LIST: # if type(uiObj[i]) == list: continue if type(uiObj[i]) == dict: table.add_hline() sectiondetails = uiObj[i] image_name = sectiondetails[KEY_DISP_SEC_PROFILE] Img_path = '/ResourceFiles/images/' + image_name + '.png' if (len(sectiondetails)) % 2 == 0: # merge_rows = int(round_up(len(sectiondetails),2)/2 + 2) merge_rows = int((len(sectiondetails) / 2)) + 2 else: merge_rows = round_up((len(sectiondetails) / 2), 2) if (len(sectiondetails)) % 2 == 0: sectiondetails[''] = '' a = list(sectiondetails.keys()) # index=0 for x in range(1, (merge_rows + 1)): # table.add_row("Col.Det.",i,columndetails[i]) if x == 1: table.add_row(( MultiRow( merge_rows, data=StandAloneGraphic( image_options= "width=5cm,height=5cm", filename=rel_path + Img_path)), MultiColumn(2, align='|c|', data=a[x]), MultiColumn(2, align='|c|', data=sectiondetails[a[x]]), )) elif x <= 4: table.add_row(( '', MultiColumn(2, align='|c|', data=NoEscape(a[x])), MultiColumn(2, align='|c|', data=NoEscape( sectiondetails[a[x]])), )) else: table.add_row(( '', NoEscape(a[x]), sectiondetails[a[x]], NoEscape(a[merge_rows + x - 4]), sectiondetails[a[merge_rows + x - 4]], )) table.add_hline(2, 5) elif uiObj[i] == "TITLE": table.add_hline() table.add_row((MultiColumn( 5, align='|c|', data=bold(i), ), )) table.add_hline() elif i == 'Section Size*': table.add_hline() table.add_row(( MultiColumn( 3, align='|c|', data=i, ), MultiColumn(2, align='|c|', data="Ref List of Input Section"), )) table.add_hline() elif len(str(uiObj[i])) > 55 and type( uiObj[i]) != pyl.math.Math: str_len = len(str(uiObj[i])) loop_len = round_up((str_len / 55), 1, 1) for j in range(1, loop_len + 1): b = 55 * j + 1 if j == 1: table.add_row(( MultiColumn(3, align='|c|', data=MultiRow(loop_len, data=i)), MultiColumn(2, align='|c|', data=uiObj[i][0:b]), )) else: table.add_row(( MultiColumn(3, align='|c|', data=MultiRow(loop_len, data="")), MultiColumn(2, align='|c|', data=uiObj[i][b - 55:b]), )) table.add_hline() else: table.add_hline() table.add_row(( MultiColumn(3, align='|c|', data=NoEscape(i)), MultiColumn(2, align='|c|', data=uiObj[i]), )) table.add_hline() for i in uiObj: if i == 'Section Size*' or i == KEY_DISP_ANGLE_LIST or i == KEY_DISP_TOPANGLE_LIST or i == KEY_DISP_CLEAT_ANGLE_LIST: with doc.create(Subsection("List of Input Section")): # with doc.create(LongTable('|p{8cm}|p{8cm}|', row_height=1.2)) as table: with doc.create(Tabularx('|p{4cm}|X|', row_height=1.2)) as table: table.add_hline() table.add_row(( MultiColumn( 1, align='|c|', data=i, ), MultiColumn(1, align='|X|', data=uiObj[i].strip("[]")), )) # str_len = len(uiObj[i]) # loop_len = round_up((str_len/100),1,1) # table.add_hline() # for j in range(1,loop_len+1): # b= 100*j+1 # if j ==1: # table.add_row((MultiColumn(1, align='|c|', data=i, ), # MultiColumn(1, align='|X|', data=uiObj[i][0:b]),)) # else: # table.add_row((MultiColumn(1, align='|c|', data=" ", ), # MultiColumn(1, align='|X|', data=uiObj[i][b-100:b]),)) table.add_hline() doc.append( pyl.Command('Needspace', arguments=NoEscape(r'10\baselineskip'))) doc.append(NewPage()) count = 0 with doc.create(Section('Design Checks')): with doc.create( Tabularx( r'|>{\centering}p{12.5cm}|>{\centering\arraybackslash}X|', row_height=1.2)) as table: table.add_hline() # Fail = TextColor("FailColor", bold("Fail")) # Pass = TextColor("PassColor", bold("Pass")) if does_design_exist != True: table.add_row(bold('Design Status'), color_cell("Red", bold("Fail"))) else: table.add_row(bold('Design Status'), color_cell("OsdagGreen", bold("Pass"))) table.add_hline() for check in Design_Check: if check[0] == 'SubSection': if count >= 1: # doc.append(NewPage()) doc.append( pyl.Command( 'Needspace', arguments=NoEscape(r'10\baselineskip'))) with doc.create(Subsection(check[1])): ######################### # if uiObj== "WELDImage": # table.add_hline() # table.add_row((MultiColumn(5, align='|c|', data=bold(i), ),)) # table.add_hline() # else: ######################### with doc.create(LongTable(check[2], row_height=1.2) ) as table: # todo anjali remove table.add_hline() table.add_row( ('Check', 'Required', 'Provided', 'Remarks'), color='OsdagGreen') table.add_hline() table.end_table_header() table.add_hline() count = count + 1 elif check[0] == "Selected": if count >= 1: # doc.append(NewPage()) doc.append( pyl.Command( 'Needspace', arguments=NoEscape(r'10\baselineskip'))) with doc.create(Subsection(check[1])): with doc.create(LongTable(check[2], row_height=1.2)) as table: table.add_hline() for i in uiObj: # row_cells = ('9', MultiColumn(3, align='|c|', data='Multicolumn not on left')) print(i) if type( uiObj[i] ) == dict and i == 'Selected Section Details': table.add_hline() sectiondetails = uiObj[i] image_name = sectiondetails[ KEY_DISP_SEC_PROFILE] Img_path = '/ResourceFiles/images/' + image_name + '.png' if (len(sectiondetails)) % 2 == 0: # merge_rows = int(round_up(len(sectiondetails),2)/2 + 2) merge_rows = int( round_up((len(sectiondetails) / 2), 1, 0) + 2) else: merge_rows = int( round_up((len(sectiondetails) / 2), 1, 0) + 1) print('Hi', len(sectiondetails) / 2, round_up(len(sectiondetails), 2) / 2, merge_rows) if (len(sectiondetails)) % 2 == 0: sectiondetails[''] = '' a = list(sectiondetails.keys()) # index=0 for x in range(1, (merge_rows + 1)): # table.add_row("Col.Det.",i,columndetails[i]) if x == 1: table.add_row(( MultiRow( merge_rows, data=StandAloneGraphic( image_options= "width=5cm,height=5cm", filename=rel_path + Img_path)), MultiColumn(2, align='|c|', data=NoEscape( a[x])), MultiColumn( 2, align='|c|', data=NoEscape( sectiondetails[a[x]])), )) elif x <= 4: table.add_row(( '', MultiColumn(2, align='|c|', data=NoEscape( a[x])), MultiColumn( 2, align='|c|', data=sectiondetails[a[x]]), )) else: table.add_row(( '', NoEscape(a[x]), sectiondetails[a[x]], NoEscape(a[merge_rows + x - 4]), sectiondetails[a[merge_rows + x - 4]], )) table.add_hline(2, 5) table.add_hline() count = count + 1 else: if check[3] == 'Fail': table.add_row((NoEscape(check[0])), check[1], check[2], TextColor("Red", bold(check[3]))) else: table.add_row((NoEscape(check[0])), check[1], check[2], TextColor("OsdagGreen", bold(check[3]))) table.add_hline() # 2D images if len(Disp_2d_image) != 0: if module == KEY_DISP_BCENDPLATE or module == KEY_DISP_BB_EP_SPLICE: if does_design_exist and sys.platform != 'darwin': doc.append(NewPage()) weld_details = rel_path + Disp_2d_image[0] detailing_details = rel_path + Disp_2d_image[1] stiffener_details = rel_path + Disp_2d_image[2] with doc.create(Section('2D Drawings (Typical)')): with doc.create(Figure()) as image: image.add_image(weld_details, width=NoEscape(r'0.7\textwidth'), placement=NoEscape(r'\centering')) image.add_caption( 'Typical Weld Details -- Beam to End Plate Connection' ) # doc.append(NewPage()) with doc.create(Figure()) as image_2: image_2.add_image( detailing_details, width=NoEscape(r'0.7\textwidth'), placement=NoEscape(r'\centering')) image_2.add_caption('Typical Detailing') # doc.append(NewPage()) with doc.create(Figure()) as image_3: image_3.add_image( stiffener_details, width=NoEscape(r'0.9\textwidth'), placement=NoEscape(r'\centering')) image_3.add_caption('Typical Stiffener Details') # doc.append(NewPage()) elif module == KEY_DISP_BASE_PLATE: if does_design_exist and sys.platform != 'darwin': doc.append(NewPage()) bp_sketch = rel_path + Disp_2d_image[0] bp_detailing = rel_path + Disp_2d_image[1] bp_weld = rel_path + Disp_2d_image[2] bp_anchor = rel_path + Disp_2d_image[3] bp_key = rel_path + Disp_2d_image[4] with doc.create(Section('2D Drawings (Typical)')): with doc.create(Figure()) as image_1: image_1.add_image( bp_sketch, width=NoEscape(r'1.0\textwidth'), placement=NoEscape(r'\centering')) image_1.add_caption('Typical Base Plate Details') # doc.append(NewPage()) with doc.create(Figure()) as image_2: image_2.add_image( bp_detailing, width=NoEscape(r'1.0\textwidth'), placement=NoEscape(r'\centering')) image_2.add_caption('Typical Base Plate Detailing') # doc.append(NewPage()) with doc.create(Figure()) as image_3: image_3.add_image( bp_weld, width=NoEscape(r'1.0\textwidth'), placement=NoEscape(r'\centering')) image_3.add_caption('Typical Weld Details') # doc.append(NewPage()) with doc.create(Figure()) as image_4: image_4.add_image( bp_anchor, width=NoEscape(r'0.5\textwidth'), placement=NoEscape(r'\centering')) image_4.add_caption('Typical Anchor Bolt Details') # doc.append(NewPage()) if len(Disp_2d_image[-1]) > 0: with doc.create(Figure()) as image_5: image_5.add_image( bp_key, width=NoEscape(r'0.9\textwidth'), placement=NoEscape(r'\centering')) image_5.add_caption( 'Typical Shear Key Details') # doc.append(NewPage()) if does_design_exist and sys.platform != 'darwin': doc.append(NewPage()) Disp_top_image = "/ResourceFiles/images/top.png" Disp_side_image = "/ResourceFiles/images/side.png" Disp_front_image = "/ResourceFiles/images/front.png" view_3dimg_path = rel_path + Disp_3d_image view_topimg_path = rel_path + Disp_top_image view_sideimg_path = rel_path + Disp_side_image view_frontimg_path = rel_path + Disp_front_image with doc.create(Section('3D Views')): with doc.create( Tabularx( r'|>{\centering}X|>{\centering\arraybackslash}X|', row_height=1.2)) as table: view_3dimg_path = rel_path + Disp_3d_image view_topimg_path = rel_path + Disp_top_image view_sideimg_path = rel_path + Disp_side_image view_frontimg_path = rel_path + Disp_front_image table.add_hline() table.add_row([ StandAloneGraphic(image_options="height=4cm", filename=view_3dimg_path), StandAloneGraphic(image_options="height=4cm", filename=view_topimg_path) ]) table.add_row('(a) 3D View', '(b) Top View') table.add_hline() table.add_row([ StandAloneGraphic(image_options="height=4cm", filename=view_sideimg_path), StandAloneGraphic(image_options="height=4cm", filename=view_frontimg_path) ]) table.add_row('(c) Side View', '(d) Front View') table.add_hline() # with doc.create(Figure(position='h!')) as view_3D: # view_3dimg_path = rel_path + Disp_3d_image # # view_3D.add_image(filename=view_3dimg_path, width=NoEscape(r'\linewidth')) # # view_3D.add_image(filename=view_3dimg_path,width=NoEscape(r'\linewidth,height=6.5cm')) # # view_3D.add_caption('3D View') with doc.create(Section('Design Log')): doc.append( pyl.Command('Needspace', arguments=NoEscape(r'10\baselineskip'))) logger_msgs = reportsummary['logger_messages'].split('\n') for msg in logger_msgs: if ('WARNING' in msg): colour = 'blue' elif ('INFO' in msg): colour = 'OsdagGreen' elif ('ERROR' in msg): colour = 'red' else: continue doc.append(TextColor(colour, '\n' + msg)) try: doc.generate_pdf(filename, compiler='pdflatex', clean_tex=False) except: pass
def generateTex(filepath=None): #read all score files for different triple size and store them in lists #scores ordered in list as: BLEU METEOR TER # get triple1 score mdBaseTripl1 = searchScores('baseTriple1_score.txt') flatTripl1 = searchScores('flattriple1_score.txt') # get triple2 score mdBaseTripl2 = searchScores('baseTriple2_score.txt') flatTripl2 = searchScores('flattriple2_score.txt') # get triple3 score mdBaseTripl3 = searchScores('baseTriple3_score.txt') flatTripl3 = searchScores('flattriple3_score.txt') # get triple4 score mdBaseTripl4 = searchScores('baseTriple4_score.txt') flatTripl4 = searchScores('flattriple4_score.txt') # get triple5 score mdBaseTripl5 = searchScores('baseTriple5_score.txt') flatTripl5 = searchScores('flattriple5_score.txt') geometry_options = {"tmargin": "1cm", "lmargin": "5cm"} doc = Document(geometry_options=geometry_options) with doc.create( Section( 'The evaluation scores for input data of various length for Unseen dataset' )): doc.append(italic('========================================\n')) doc.append( 'Comparing the evaluation scores between two model: (flat, modify baseline) according to different triple size in Unseen dataset.\n' ) doc.append( italic( 'We mean by flat one model from the extended system which contains 3 model:flat,str1,str2\n' )) doc.append( italic( 'Where we evaluate just this model in term of different triple size, because the result of other models i.e. str1&str2 for the dataset seen and unseen not very good comparing by this model\n' )) doc.append( italic( 'We mean by "Modify baseline" the modified baseline of webnlg challeng \n' )) with doc.create(Subsection('Table of Evaluation in term of BLEU \n')): with doc.create(Tabular('|c|c|c|')) as table: table.add_hline() table.add_row(bold("Triple size"), bold("Model"), bold("Bleu")) table.add_hline() table.add_row((MultiRow(3, data='Triple 1'), "Modify Baseline", mdBaseTripl1[0])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flatTripl1[0]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Triple 2'), "Modify Baseline", mdBaseTripl2[0])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flatTripl2[0]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Triple 3'), "Modify Baseline", mdBaseTripl3[0])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flatTripl3[0]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Triple 4'), "Modify Baseline", mdBaseTripl4[0])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flatTripl4[0]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Triple 5'), "Modify Baseline", mdBaseTripl5[0])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flatTripl5[0]))) table.add_hline() table.add_hline() # Generate METEOR score table with doc.create( Subsection('Table of Evaluation in term of METEOR \n')): with doc.create(Tabular('|c|c|c|')) as table: table.add_hline() table.add_row(bold("Triple size"), bold("Model"), bold("METEOR")) table.add_hline() table.add_row((MultiRow(3, data='Triple 1'), "Modify Baseline", mdBaseTripl1[1])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flatTripl1[1]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Triple 2'), "Modify Baseline", mdBaseTripl2[1])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flatTripl2[1]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Triple 3'), "Modify Baseline", mdBaseTripl3[1])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flatTripl3[1]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Triple 4'), "Modify Baseline", mdBaseTripl4[1])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flatTripl4[1]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Triple 5'), "Modify Baseline", mdBaseTripl5[1])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flatTripl5[1]))) table.add_hline() table.add_hline() # Generate TER score table with doc.create(Subsection('Table of Evaluation in term of TER \n')): with doc.create(Tabular('|c|c|c|')) as table: table.add_hline() table.add_row(bold("Triple size"), bold("Model"), bold("TER")) table.add_hline() table.add_row((MultiRow(3, data='Triple 1'), "Modify Baseline", mdBaseTripl1[2])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flatTripl1[2]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Triple 2'), "Modify Baseline", mdBaseTripl2[2])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flatTripl2[2]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Triple 3'), "Modify Baseline", mdBaseTripl3[2])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flatTripl3[2]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Triple 4'), "Modify Baseline", mdBaseTripl4[2])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flatTripl4[2]))) table.add_hline() table.add_hline() table.add_row((MultiRow(3, data='Triple 5'), "Modify Baseline", mdBaseTripl5[2])) table.add_hline(2, 3) table.add_row(('', "Flat", bold(flatTripl5[2]))) table.add_hline() table.add_hline() doc.generate_pdf('TripleSize_Unseen_SetEvaluation ', clean_tex=False)
def to_tex(self): tab = self._create_tabular() tab.add_hline() for i in range(self.sheet.nrows): line = [] merge_set = set() for j in range(self.sheet.ncols): res, mindex = self.in_merge_cell(i, j) if res == -1: line.append(self.cell(i, j)) else: merge_set.add(mindex) cres, cnum = self.ismulticol(mindex) rres, rnum = self.ismultirow(mindex) if res == 0: if cres: if rres: line.append( MultiColumn( cnum, align=self._cacu_multicol_align(j), data=MultiRow(rnum, data=self.cell(i, j)))) else: line.append( MultiColumn( cnum, align=self._cacu_multicol_align(j), data=self.cell(i, j))) else: line.append(MultiRow(rnum, data=self.cell(i, j))) elif res == 1: # 不同行同列 if cres and rres: line.append( MultiColumn(cnum, align=self._cacu_multicol_align(j), data="")) else: line.append("") elif res == 2: # 不同列同行 pass tab.add_row(line) all_range = [[0, self.sheet.ncols - 1]] for mi in merge_set: merge_range = self.merge_col[mi] if merge_range[1] - merge_range[0] > 0 and merge_range[ 1] - i > 0: all_range = self._extract_range(all_range, merge_range[2:4]) if all_range[0][0] == 0 and all_range[0][1] == self.sheet.ncols - 1: tab.add_hline() else: for r in all_range: tab.add_hline(r[0] + 1, r[1] + 1) table = TexTable(position=self.params["position"]) table.append(tab) res = table if self.params["center"]: c = Center() c.append( NoEscape( r"% \newlength\tablewidth % if haven't define the length 'tablewidth'" )) c.append( NoEscape( rf"\setlength\tablewidth{{\dimexpr (\textwidth -{2*self.sheet.ncols}\tabcolsep)}}" )) c.append(table) res = c return self._format_tex(res.dumps())
temp2_clf.append( AdaBoostClassifier(tree.DecisionTreeClassifier(max_depth=depth), n_estimators=estimator)) clfs.append(temp2_clf) # obliczanie wynikow for data in dataset: db = getattr(importdata, 'load_' + data)() print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") print('Zbior danych: %s' % data) importdata.print_info(db.target) for id, (clfs_, name) in enumerate(zip(clfs, depths_name)): rows = [] if id == 0: col = MultiRow(len(depths), data=data) else: col = '' for i in range(len(depths) + 1): rows.append([col, name]) # obliczenia dla kazdego klasyfikatora for clf in clfs_: scores = [] # powtarzanie klasyfikacji for iteration in range(iterations): clf_ = clone(clf) # sprawdzian krzyzowy testpredict, testtarget = cross_val_pred2ict(clf_, db.data, db.target, cv=folds,
#1.1 with doc.create(Tabular('l|l|r|r')) as table: table.add_row(('Date', 'Type', 'USD bn (Total)', 'COP bn (Total)')) table.add_hline() table.add_row('Aug 2019', 'By Residency', dfResUSDAug['Total'].values[0], dfResCOPAug['Total'].values[0]) table.add_row('Mar 2019', 'By Currency', dfUSDMar['Total'].values[0], dfCOPMar['Total'].values[0]) with doc.create(Section('Other Public Debt')): #1.1 with doc.create(Tabular('l|l|r|r')) as table: table.add_row(('Date', 'Type', 'USD bn (Total)', 'COP bn (Total)')) table.add_hline() table.add_row(MultiRow(2, data='Oct 2019'), 'Stock', dfForHolStUSDOct['foreign holdings'].values[0], dfForHolStCOPOct['foreign holdings'].values[0]) table.add_row('', 'Flow', dfForHolFlUSDOct['foreign holdings'].values[0], dfForHolFlCOPOct['foreign holdings'].values[0]) with doc.create(Section('External Sector')): #1.1 with doc.create(Tabular('l|l|r|r')) as table: table.add_row(('Date', 'Type', 'USD bn (Total)', 'COP bn (Total)')) table.add_hline() table.add_row('Jun 2019', 'Portfolio Liabilities', dfPortUSDJun['Total'].values[0], dfPortCOPJun['Total'].values[0]) #table.add_row('Mar 2019','By Currency',dfUSDMar['Total'].values[0],dfCOPMar['Total'].values[0])
def build_latex(metrics: List[Metric], invert=False, caption=""): models, metric_labels, splits = {}, {}, {} score_map = defaultdict(lambda: "-") for metric in metrics: metric_vals = metric() score, metric_label, model_name, split_name = ( metric_vals[SCORE], metric_vals[METRIC_LABEL], metric_vals[MODEL_NAME], metric_vals[SPLIT_NAME], ) metric_labels[metric_label] = 1 models[model_name] = 1 splits[split_name] = 1 score_map[(metric_label, model_name, split_name)] = ("-" if math.isnan(score) else score) models = list(models.keys()) splits = list(splits.keys()) metric_labels = list(metric_labels.keys()) if not invert: model_split_cols = "".join( ["c|" for _ in range(len(models) * len(splits))]) table = Tabular("|c|" + model_split_cols) table.add_hline() row = (MultiRow( 2, data="Metric"), ) if len(splits) > 1 else ("Metric", ) for model_name in models: row += (MultiColumn(len(splits), align="|c|", data=model_name), ) table.add_row(row) table.add_hline(1 if len(splits) == 1 else 2) if (len(splits)) > 1: row = ("", ) for _ in range(len(models)): for split_name in splits: row += (split_name, ) table.add_row(row) table.add_hline() for metric_label in metric_labels: row = (metric_label, ) for model_name in models: for split_name in splits: row += (score_map[(metric_label, model_name, split_name)], ) table.add_row(row) table.add_hline() else: metric_split_labels = "".join( ["c|" for _ in range(len(metric_labels))]) table = Tabular("|c|" if len(splits) == 1 else "|c|c|" + metric_split_labels) table.add_hline() row = (MultiColumn(2, align="|c|", data=""), ) if len(splits) > 1 else ("", ) for metric_label in metric_labels: row += (metric_label, ) table.add_row(row) table.add_hline() for model_name in models: row = (MultiRow(len(splits), data=model_name), ) for split_name in splits: row += (split_name, ) for metric_label in metric_labels: row += (score_map[(metric_label, model_name, split_name)], ) table.add_row(row) if len(splits) > 1: table.add_hline(start=2) row = ("", ) table.add_hline() latex_table = Table(position="h") latex_table.append(table) latex_table.add_caption(caption) return latex_table
axis=1, join_axes=[acc_table_RGDP_1Y.index]) # create table object tabl = Table() tabl.add_caption( "Performance of forecast combinations of ECB SPF forecasts using the training window of the length: " + str(w)) tabl.append(NoEscape('\label{tab: spf_comb_perf_' + str(w) + '}')) # create tabular object tabr = Tabular(table_spec="c|l" + 6 * "|ccc") tabr.add_hline() tabr.add_hline() # header row tabr.add_row( (MultiRow(3, data="Class"), MultiRow(3, data="Forecast Combination Method"), MultiColumn(6, align='|c|', data="RGDP"), MultiColumn(6, align='|c|', data="HICP"), MultiColumn(6, align='|c', data="UNEM"))) tabr.add_hline(start=3, end=20, cmidruleoption="lr") tabr.add_row(("", "", MultiColumn(3, align='|c|', data="1Y"), MultiColumn(3, align='|c|', data="2Y"), MultiColumn(3, align='|c|', data="1Y"), MultiColumn(3, align='|c|', data="2Y"), MultiColumn(3, align='|c|', data="1Y"), MultiColumn(3, align='|c|', data="2Y")))
align='|c|', content='Multicol', cells=None, escape=False) t.add_multirow(size=3, align='*', content='Multirow', hlines=True, cells=None, escape=False) # MultiColumn/MultiRow. t.add_row((MultiColumn(size=2, align='|c|', data='MultiColumn'), )) t.add_row((MultiRow(size=2, width='*', data='MultiRow'), )) # Command c = Command(command='documentclass', arguments=None, options=None, packages=None) # Figure f = Figure(data=None, position=None) f.add_image(filename='', width=r'0.8\textwidth', placement=r'\centering') f.add_caption(caption='') # Subfigure s = SubFigure(data=None,
table1 = Tabular('|c|c|c|c|') table1.add_hline() table1.add_row((MultiColumn(4, align='|c|', data='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, align='|c|', data='Multicolumn not on left')) table1.add_row(row_cells) table1.add_hline() table2 = Tabular('|c|c|c|') table2.add_hline() table2.add_row((MultiRow(3, data='Multirow'), 1, 2)) table2.add_hline(2, 3) table2.add_row(('', 3, 4)) table2.add_hline(2, 3) table2.add_row(('', 5, 6)) table2.add_hline() table2.add_row((MultiRow(3, data='Multirow2'), '', '')) table2.add_empty_row() table2.add_empty_row() table2.add_hline() table3 = Tabular('|c|c|c|') table3.add_hline() table3.add_row((MultiColumn(2, align='|c|', data=MultiRow(2, data='multi-col-row')), 'X'))
]) # create table object tabl = Table() tabl.add_caption( "Descriptive statistics of the SPF target macroeconomic variables for the euro area" ) tabl.append(NoEscape('\label{tab: spf_Desc_Stats}')) # create tabular object tabr = Tabular(table_spec="l|cc|cc|cc") tabr.add_hline() tabr.add_hline() # header row tabr.add_row( (MultiRow(2, data="Statistic"), MultiColumn(2, align='|c|', data="RGDP"), MultiColumn(2, align='|c|', data="HICP"), MultiColumn(2, align='|c', data="UNEM"))) tabr.add_hline(start=2, end=3, cmidruleoption="lr") tabr.add_hline(start=4, end=5, cmidruleoption="lr") tabr.add_hline(start=6, end=7, cmidruleoption="lr") tabr.add_row([""] + ["1Y", "2Y"] + ["1Y", "2Y"] + ["1Y", "2Y"]) tabr.add_hline() # fill in the rows of tabular for i in range(9): tabr.add_row([ds_stats[i]] + ["{:.2f}".format(item) for item in spf_desc_stat.iloc[i, :]]) # end of table tabr.add_hline() # add tabular to table tabl.append(tabr)
def latex_report(system, curves, grid, filename): lines = system.lines trafos = system.trafos buses = system.buses geometry_options = {"tmargin": "1cm", "lmargin": "1cm", "rmargin": "1cm", "bmargin": "1cm", "includeheadfoot": True} doc = Document(page_numbers=True, geometry_options=geometry_options) doc.preamble.append(Command('usepackage', 'cmbright')) doc.preamble.append(Command('usepackage', 'tikz')) doc.preamble.append(Command('usepackage', 'amsmath')) doc.preamble.append(Command('usepackage', 'graphicx')) now = datetime.datetime.now() doc.append(f'Report auto-generated by Elegant at ' f'{now.day:02d}/{now.month:02d}/{now.year:02d} ' f'{now.hour:02d}:{now.minute:02d}:{now.second:02d}') wye_comm = UnsafeCommand( 'newcommand', '\\wye', extra_arguments=r'\mathbin{\text{\begin{tikzpicture}' r'[x=1pt, y=1pt, scale=2]' r'\draw ' r'(-0.9, 0) -- (0.9, 0) ' r'(-0.6, -0.5) -- (0.6, -0.5) ' r'(-0.3, -1) -- (0.3, -1) ' r'(0, 0) -- ++(0, 1.5) -- ++(1.2, 0) coordinate (tmp)' r'-- +(0, -2) ' r'(tmp) +(45:2) -- (tmp) -- +(135:2) ;' r'\end{tikzpicture}}}' ) why_comm = UnsafeCommand( 'newcommand', '\\why', extra_arguments=r'\mathbin{\text{\begin{tikzpicture}' r'[x=1pt, y=1pt, scale=2]' r'\draw ' r'(1.2, 1.5) coordinate (tmp)' r'-- +(0, -2) ' r'(tmp) +(45:2) -- (tmp) -- +(135:2) ;' r'\end{tikzpicture}}}' ) doc.append(wye_comm) doc.append(why_comm) doc.add_color(name="lightgray", model="gray", description="0.80") with doc.create(Section('Buses')): with doc.create(Subsection('Load-Flow Solution')): with doc.create(LongTable('c|ccccccc')) as tbl: tbl.add_hline() tbl.add_row(('Bus', NoEscape('$|V|$ (pu)'), NoEscape('$\\delta$ (deg)'), NoEscape('$P_G$ (MW)'), NoEscape('$Q_G$ (Mvar)'), NoEscape('$P_L$ (MW)'), NoEscape('$Q_L$ (Mvar)'), NoEscape('$Z_L$ (pu)'))) tbl.add_hline() tbl.end_table_header() tbl.add_hline() tbl.add_row((MultiColumn(8, align='r', data='Continued on Next Page'),)) tbl.add_hline() tbl.end_table_footer() tbl.add_hline() tbl.end_table_last_footer() for i, b in enumerate(buses): if i % 2 == 0: color = 'lightgray' else: color = None tbl.add_row((b.bus_id + 1, NoEscape('{:.04f}'.format(b.v)), NoEscape('${:.02f}$'.format(b.delta * 180 / np.pi)), NoEscape('{:.02f}'.format(b.pg * 100)), NoEscape('{:.02f}'.format(b.qg * 100)), NoEscape('{:.02f}'.format(b.pl * 100)), NoEscape('{:.02f}'.format(b.ql * 100)), safe_repr(b.Z)), color=color) with doc.create(Subsection('Fault Calculations')): with doc.create(LongTable('c|cccccccccc')) as tbl: tbl.add_hline() tbl.add_row((MultiRow(2, data='Bus'), MultiColumn(2, align='c', data=NoEscape('TPG')), MultiColumn(2, align='c', data=NoEscape('SLG')), MultiColumn(4, align='c', data=NoEscape('DLG')), MultiColumn(2, align='c', data=NoEscape('LL')))) tbl.add_hline(2, 11) tbl.add_row(('', NoEscape('$I_A$ (pu)'), NoEscape('$\\delta_A$ (deg)'), NoEscape('$I_A$ (pu)'), NoEscape('$\\delta_A$ (deg)'), NoEscape('$I_B$ (pu)'), NoEscape('$\\delta_B$ (deg)'), NoEscape('$I_C$ (pu)'), NoEscape('$\\delta_C$ (deg)'), NoEscape('$I_B$ (pu)'), NoEscape('$\\delta_B$ (deg)'))) tbl.add_hline() tbl.end_table_header() tbl.add_hline() tbl.add_row((MultiColumn(11, align='r', data='Continued on Next Page'),)) tbl.add_hline() tbl.end_table_footer() tbl.add_hline() tbl.end_table_last_footer() for i, b in enumerate(buses): if i % 2 == 0: color = 'lightgray' else: color = None tbl.add_row((b.bus_id + 1, safe_repr(np.abs(b.iTPG)), NoEscape('${:.02f}$'.format(np.angle(b.iTPG) * 180 / np.pi)), safe_repr(np.abs(b.iSLG)), NoEscape('${:.02f}$'.format(np.angle(b.iSLG) * 180 / np.pi)), safe_repr(np.abs(b.iDLGb)), NoEscape('${:.02f}$'.format(np.angle(b.iDLGb) * 180 / np.pi)), safe_repr(np.abs(b.iDLGc)), NoEscape('${:.02f}$'.format(np.angle(b.iDLGc) * 180 / np.pi)), safe_repr(np.abs(b.iLL)), NoEscape('${:.02f}$'.format(np.angle(b.iLL) * 180 / np.pi))), color=color) with doc.create(Section('Lines')): with doc.create(LongTable('c|cccccccc')) as tbl: tbl.add_hline() tbl.add_row((MultiRow(2, data='Line'), MultiColumn(3, align='c', data='Parametrization'), MultiColumn(2, align='c', data='Loss'), MultiColumn(3, align='c', data='Flow'))) tbl.add_hline(2, 9) tbl.add_row(('', NoEscape('$R$ (\\%pu)'), NoEscape('$X_L$ (\\%pu)'), NoEscape('$B_C$ (\\%pu)'), NoEscape('$P_{loss}$ (MW)'), NoEscape('$Q_{loss}$ (Mvar)'), NoEscape('$P$ (MW)'), NoEscape('$Q$ (Mvar)'), NoEscape('$I/I_{max}$ (\\%)'))) tbl.add_hline() tbl.end_table_header() tbl.add_hline() tbl.add_row((MultiColumn(9, align='r', data='Continued on Next Page'),)) tbl.add_hline() tbl.end_table_footer() tbl.add_hline() tbl.end_table_last_footer() for i, lt in enumerate(lines): if i % 2 == 0: color = 'lightgray' else: color = None tbl.add_row((NoEscape('{} -- {}'.format(lt.orig.bus_id + 1, lt.dest.bus_id + 1)), NoEscape('{:.04f}'.format(lt.Zpu.real * 100)), NoEscape('{:.04f}'.format(lt.Zpu.imag * 100)), NoEscape('{:.04f}'.format(lt.Ypu.imag * 100)), NoEscape('{:.02f}'.format(lt.Sper.real * 100)), NoEscape('{:.02f}'.format(lt.Sper.imag * 100)), NoEscape('{:.02f}'.format(lt.S2.real * 100)), NoEscape('{:.02f}'.format(lt.S2.imag * 100)), NoEscape('{:.02f}'.format(np.abs(lt.Ia) / lt.imax * 100))), color=color) with doc.create(Section('Trafos')): with doc.create(LongTable('c|ccccccc')) as tbl: tbl.add_hline() tbl.add_row((MultiRow(2, data='Trafo'), MultiColumn(3, align='c', data='Parametrization'), MultiColumn(1, align='c', data='Loss'), MultiColumn(3, align='c', data='Flow'))) tbl.add_hline(2, 8) tbl.add_row(('', NoEscape('$x^+$ (\\%pu)'), NoEscape('$x^0$ (\\%pu)'), 'Configuration', NoEscape('$Q_{loss}$ (Mvar)'), NoEscape('$P$ (MW)'), NoEscape('$Q$ (Mvar)'), NoEscape('$S/S_N$ (\\%)'))) tbl.add_hline() tbl.end_table_header() tbl.add_hline() tbl.add_row((MultiColumn(8, align='r', data='Continued on Next Page'),)) tbl.add_hline() tbl.end_table_footer() tbl.add_hline() tbl.end_table_last_footer() for i, tr in enumerate(trafos): if i % 2 == 0: color = 'lightgray' else: color = None tbl.add_row((NoEscape('{} -- {}'.format(tr.orig.bus_id + 1, tr.dest.bus_id + 1)), NoEscape('{:.02f}'.format(tr.Z1.imag * 100)), NoEscape('{:.02f}'.format(tr.Z0.imag * 100)), get_scheme(tr), NoEscape('{:.02f}'.format(tr.Sper.imag * 100)), NoEscape('{:.02f}'.format(tr.S2.real * 100)), NoEscape('{:.02f}'.format(tr.S2.imag * 100)), NoEscape('{:.02f}'.format(np.abs(tr.S2) * 1e8 / tr.snom * 100))), color=color) filepath = filename.strip('.pdf') make_system_schematic(curves, grid, initial_fontsize=9) doc.append(NewPage()) with doc.create(Section('System')): with doc.create(Figure(position='h')) as system_pic: system_pic.add_plot(bbox_inches='tight', width=NoEscape('\\textwidth')) doc.generate_pdf(filepath, clean_tex=True, compiler='latexmk', compiler_args=['-pdf'])
table1 = Tabular('|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() table2 = Tabular('|c|c|c|') table2.add_hline() table2.add_row((MultiRow(3, '*', 'Multirow'), 1, 2)) table2.add_hline(2, 3) table2.add_row(('', 3, 4)) table2.add_hline(2, 3) table2.add_row(('', 5, 6)) table2.add_hline() table2.add_row((MultiRow(3, '*', 'Multirow2'), '', '')) table2.add_empty_row() table2.add_empty_row() table2.add_hline() table3 = Tabular('|c|c|c|') table3.add_hline() table3.add_row((MultiColumn(2, '|c|', MultiRow(2, '*', 'multi-col-row')), 'X')) table3.add_row((MultiColumn(2, '|c|', ''), 'X')) table3.add_hline()