def _append2latexdoc(doc, content): if isinstance(content, list): for item in content: if item.get('title'): doc.append(_get_section(**item)) _append2latexdoc(doc, item['content']) else: _append2latexdoc(doc, item) else: section = _get_last_section(doc) if content.get('text'): if isinstance(content['text'], dict): section.append(open(content['text']['filename']).read()) else: temp = '' if isinstance(content['text'],list): for subtext in content['text']: temp += subtext elif isinstance(content['text'],str): temp = content['text'] else: raise Exception(f'Did not understand format of text string: \n {content["text"]}') section.append(temp) if content.get('latex_code'): if isinstance(content['latex_code'], dict): section.append(NoEscape(open(content['latex_code']['filename']).read())) else: section.append(NoEscape(content['latex_code'])) if content.get('table'): for table in content['table']: section.append(NoEscape('\\begin{table}[H]')) # note require float latex package for H command if table.get('filename'): df = pd.read_excel(table['filename'], **table['kwargs']) elif isinstance(table.get('dataframe'),pd.DataFrame): df = table.get('dataframe') section.append(NoEscape(df.to_latex(longtable=True,multicolumn_format='c'))) section.append(NoEscape('\\end{table}')) if content.get('image'): for image in content.get('image'): section.append(NoEscape('\\begin{figure}[H]')) # note require float latex package for H command Figure.add_image(section, image['filename']) section.append(NoEscape('\\end{figure}')) if content.get('subimage'): figure = Figure(position='H') for i, subimage in enumerate(content['subimage']): subfigure = SubFigure(width=NoEscape( r'{}\linewidth'.format(np.round(1. / subimage.get('nr_horizontal_subimages', 2), 2) - 0.01))) subfigure.add_image(subimage['filename']) if subimage.get('caption', False): subfigure.add_caption(subimage['caption']) if subimage.get('figure_caption', False) and i == 0: figure.add_caption(subimage['figure_caption']) figure.append(subfigure) if (i + 1) % subimage.get('nr_horizontal_subimages', 2) == 0 and i != 0 or subimage.get( 'nr_horizontal_subimages', 2) == 1: section.append(figure) figure = Figure(arguments=NoEscape('\ContinuedFloat'), position='H') section.append(figure) if content.get('packages'): [doc.packages.append(Package(package)) for package in content['packages']]
def _document_training_graphs(self) -> None: """Add training graphs to the traceability document. """ with self.doc.create(Section("Training Graphs")): log_path = os.path.join(self.resource_dir, f'{self.report_name}_logs.png') visualize_logs(experiments=[self.system.summary], save_path=log_path, verbose=False, ignore_metrics={'num_device', 'logging_interval'}) with self.doc.create(Figure(position='h!')) as plot: plot.add_image( os.path.relpath(log_path, start=self.save_dir), width=NoEscape( r'1.0\textwidth,height=0.95\textheight,keepaspectratio' )) for idx, graph in enumerate(self.system.custom_graphs.values()): graph_path = os.path.join( self.resource_dir, f'{self.report_name}_custom_graph_{idx}.png') visualize_logs(experiments=graph, save_path=graph_path, verbose=False) with self.doc.create(Figure(position='h!')) as plot: plot.add_image( os.path.relpath(graph_path, start=self.save_dir), width=NoEscape( r'1.0\textwidth,height=0.95\textheight,keepaspectratio' ))
def test_graphics(): f = Figure(data=None, position=None) f.add_image(filename='', width=r'0.8\textwidth', placement=r'\centering') f.add_caption(caption='') repr(f) # Subfigure s = SubFigure(data=None, position=None, width=r'0.45\linewidth') s.add_image(filename='', width='r\linewidth', placement=None) s.add_caption(caption='') repr(s) # Matplotlib plot = Figure(data=None, position=None) x = [0, 1, 2, 3, 4, 5, 6] y = [15, 2, 7, 1, 5, 6, 9] pyplot.plot(x, y) plot.add_plot(width=r'0.8\textwidth', placement=r'\centering') plot.add_caption(caption='I am a caption.') repr(plot) # StandAloneGraphic stand_alone_graphic = StandAloneGraphic( filename='', image_options=r"width=0.8\textwidth") repr(stand_alone_graphic)
def graphs(fname, width, *args, **kwargs): with doc.create(Section(fname)): with doc.create(Figure(position='h')) as plot1: plot1.add_plot(width=NoEscape(width), *args, **kwargs) line_graph(single_data, ylabel="Single Effective Marginal Tax Rate") with doc.create(Figure(position='h')) as plot2: plot2.add_plot(width=NoEscape(width), *args, **kwargs) line_graph(joint_data, ylabel="Joint Effective Marginal Tax Rate")
def makeImages(self, section, fileInfos): figure = Figure(position="h") for index, infos in enumerate(fileInfos): image = self.createImage(infos.filename, infos.caption) figure.append(image) if index % 2 == 1: section.append(figure) figure = Figure(position="h") if index == len(fileInfos) - 1: section.append(figure)
def test_graphics(): 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, position=None, width=r'0.45\linewidth', seperate_paragraph=False) s.add_image(filename='', width='r\linewidth', placement=None) s.add_caption(caption='') # Matplotlib plot = MatplotlibFigure(data=None, position=None) x = [0, 1, 2, 3, 4, 5, 6] y = [15, 2, 7, 1, 5, 6, 9] pyplot.plot(x, y) plot.add_plot(width=r'0.8\textwidth', placement=r'\centering') plot.add_caption(caption='I am a caption.') # Quantities Quantity(quantity=1 * pq.kg) Quantity(quantity=1 * pq.kg, format_cb=lambda x: str(int(x)))
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())
def createParagraph(self, doc, line): # Normal Line if line.lineType == "normal": doc.append(line.content) # Line with formula if line.lineType == "math": with doc.create(Alignat(numbering=True, escape=False)) as math_eq: math_eq.append(line.content) # Example Lines if line.lineType == "example": if not line.title == "": doc.append(bold(line.title+"\n")) else: doc.append(italic(line.content)) if line.lineType == "image": imgPath = self.findImageAndConvert( line.content) if not imgPath == None: with doc.create(Figure(position='H')) as image: image.add_image( imgPath) return doc
def add_structure_figure(self): with self.doc.create(Section(self.tpdf.step_figure_image)): with self.doc.create(Figure(position='H')) as fig_estrutura: fig_estrutura.add_image("figs\\structure", width='500px') fig_estrutura.add_caption( NoEscape(self.tpdf.step_figure_image_label))
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 addFig2Doc(self, figpath): """Add a figure by name to the end of the latex document, if it exists in the folder, by referencing the configurations of the figure as described in the self.figures dictionary. Arguments: figpath {str} -- file path of the figure to be added to the document. """ fig = os.path.basename(figpath) inPath = os.path.join(self.fpath, 'figures', fig) outPath = os.path.join('../figures', fig) if not os.path.exists(figpath): print('Error: File does not exist!') else: # self.doc.append(NoEscape(r'\input{' + outPath + r'}')) with self.doc.create(Figure(position='ht')) as fig_: ## To adjust image size given specified options: if fig in self.figures: # added via saveFigure(): if 'option' in self.figures[fig]: fig_.append(NoEscape(r'\centering')) fig_.append( Command('includegraphics', options=NoEscape( self.figures[fig]['option']), arguments=outPath)) else: fig_.add_image(outPath) # default uses 0.8\textwidth if 'caption' in self.figures[fig]: fig_.append(LineBreak()) fig_.add_caption(self.figures[fig]['caption']) else: fig_.add_image(outPath) print(f'Added {fig} to the tex doc obj') return
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 de_image(s: lines.Image): img_path = ImageTool.verify(s.link, config.cacheimg_dir) if img_path is None: c = Center() c.append(NoEscape('Link or path not found: {}'.format(s.link))) return c if config.give_rele_path: img_path = os.path.relpath(img_path, config.output_dir) img_path = norm_path(img_path) c = Center() if isinstance(s.parent, env.Quote): c.append( NoEscape( r"\includegraphics[width=0.8\textwidth]{{{img_path}}}".format( img_path=img_path))) else: fig = Figure(position=config.fig_position) fig.add_image(img_path, placement='') if len(s.desc.strip()) > 0: fig.add_caption(s.desc) c.append(fig) return c
def add_sections_to_doc(ncl_list, clustering_type, doc, statfile, nd): for nclust in ncl_list: # generate a new subsection section_title = '%s results, Ncl=%d' % (clustering_type, nclust) # find the relevant plots glob_str = '%s*_%dcl*' % (clustering_type, nclust) all_plots = glob(glob_str) # extract the relevant parts of statfile and insert if nd == 3: tmptex, junk = get_stats(statfile, clustering_type, oldcols_3d_stats, newcols_3d_stats, 'total_clust', nclust) elif nd == 2: tmptex, junk = get_stats(statfile, clustering_type, oldcols_2d_stats, newcols_2d_stats, 'total_clust', nclust) # insert table and plots into the LaTex document with doc.create(Subsection(section_title)): doc.append(tmptex) for image_filename in all_plots: with doc.create(Figure()) as fig: fig.add_image(image_filename) fig.add_caption(image_filename) doc.append(NewPage()) return
def add_image(self, image_filename, title_name): from pylatex import Subsection, Figure with self.doc.create(Subsection(title_name)): with self.doc.create(Figure(position='h!')) as kitten_pic: kitten_pic.add_image(image_filename, width='360px') kitten_pic.add_caption('image_description')
def addPic(self): """ This function can randomly insert an image with random size The image can be either single-row or across two rows The caption of an image will be a lorem-ipsum sentence """ mod = random.choice([0, 1]) scale_width = random.choice([0.5, 0.75, 1]) scale_height = random.choice([0.5, 0.75, 1, 1.5, 2]) with open('./lorem-ipsum-caption.txt', 'r', encoding='UTF-8') as f: all = f.readlines() caption_name = random.choice(all) for root, dirnames, filenames in os.walk('./img'): img = os.path.join(root + '/', random.choice(filenames)) if mod == 0: with self.doc.create(Figure(position='htbp')) as fig: fig.add_image(img, width=NoEscape(r'%f\linewidth' % scale_width)) fig.add_caption(caption=caption_name) else: img_name = '{.' + img.split('.')[1] + '}.' + img.split('.')[2] with self.doc.create(MyFigure(options='hb')): self.doc.append(Command('centering')) self.doc.append( Command( 'includegraphics', options=Options( NoEscape( r'width=%f\textwidth, height=%f\textwidth' % (scale_width, scale_height * 0.3))), arguments=NoEscape(img_name))) self.doc.append(Command('caption', caption_name))
def generate_cover2(doc): doc.append(NoEscape(r"\begin{titlepage}")) doc.append(NoEscape(r"\begin{center}")) with doc.create(Figure(position='t')) as logo: logo.add_image("../../forms/jupedsim.png") doc.append( NoEscape(r"\textsc{\LARGE J\"ulich Pedestrian Simulator}\\[1.5cm]")) doc.append( NoEscape(r"\textsc{\small Forschungszentrum J\"ulich GmbH}\\[0.5cm]")) doc.append(NoEscape(r"\hrule \vspace{1.5mm}")) doc.append( NoEscape(r"{ \huge \bfseries RiMEA-Projekt Analyse Report}\\[0.4cm]")) doc.append(NoEscape(r"\hrule \vspace{5.5cm}")) author = get_git_status()[1] + "\par" date = get_git_status()[2] + "\par" branch = "Branch: " + get_git_status()[0] + "\par" commit = "Commit: " + get_git_status()[3] + "\par" InfoBlock = MiniPage(width=NoEscape(r"1\textwidth"), align='c') today = "Date: " + datetime.datetime.now().strftime( "%d - %m - %Y (%H:%M)") + "\par" InfoBlock.append(NoEscape(today)) InfoBlock.append(NoEscape(branch)) InfoBlock.append(NoEscape(commit)) doc.append(InfoBlock) doc.append(NoEscape(r"\end{center}")) doc.append(NoEscape(r"\end{titlepage}"))
def add_sub_figure(doc, graphics_dir, image_names=[], captioning="Metrics"): """ Helper function to create multiple sub figures Arguments: doc: document to add figure graphics_dir: directory containing .png image image_names: the list of image names without extension captioning: global captioning for the figure """ num_figures = len(image_names) scale = 1.0 / num_figures sub_width = str(scale) + r"\linewidth" with doc.create(Figure(position="h!")) as fig: for image in image_names: image_filename = os.path.join(os.path.dirname(__file__), graphics_dir, image + ".png") with doc.create(SubFigure(position="b", width=NoEscape(sub_width))) as sub_fig: sub_fig.add_image(image_filename, width=NoEscape(r"\linewidth")) sub_fig.add_caption(image) fig.add_caption(captioning)
def format_latex(title, soup): # create document doc = Document() # set preamble doc.preamble.append(Command('title', title)) doc.append(NoEscape(r'\maketitle')) # get the main content body main_content = soup.body.find('div').find('div') elements = main_content.find_all(True) # iterate over elements for ele in elements: if ele.name == 'h1': doc.append(Section(ele.text)) elif ele.name == 'h2': doc.append(Subsection(ele.text)) elif ele.name == 'h3': doc.append(Subsubsection(ele.text)) elif ele.name == 'h4': doc.append(Paragraph(ele.text)) elif ele.name == 'h5': doc.append(Subparagraph(ele.text)) elif ele.name == 'p': doc.append(ele.text + '\n') elif ele.name == 'ul': with doc.create(Itemize()) as item: for li in ele.find_all('li'): item.add_item(li.text) elif ele.name == 'ol': with doc.create(Enumerate()) as enum: for li in ele.find_all('li'): enum.add_item(li.text) elif ele.name == 'img': with doc.create(Figure(position='h!')) as fig: # create tmp directory for images pathlib.Path('build/images').mkdir(parents=True, exist_ok=True) # check if source is using // shorthand for http:// src = ele['src'] if src.startswith('//'): src = 'http:' + src # generate image path image_path = 'images/' + src.split('/')[-1] # retrieve image print('downloading image ' + src) headers = {'User-Agent': USER_AGENT} response = requests.get(src, stream=True, headers=headers) with open('build/' + image_path, 'wb') as f: response.raw.decode_content = True shutil.copyfileobj(response.raw, f) # append image fig.add_image(image_path) return doc
def add_free_body_diagram(self): with self.doc.create(Section(self.tpdf.step_free_body_diagram_0)): with self.doc.create(Figure(position='H')) as fig_corpolivre: if self.sr.hinged and self.sr.roll: fig_corpolivre.add_image("figs\\diagram1", width='500px') elif self.sr.fixed: fig_corpolivre.add_image("figs\\diagram2", width='500px') fig_corpolivre.add_caption( NoEscape(self.tpdf.free_body_diagram_0_label))
def create_tex(self, doc): print('Generating latex!') with doc.create(Section('The year 2018')): doc.append('Here are some cool images from 2018!') for i, image in enumerate(self.photos.photos): with doc.create(Figure(position='h!')) as figure: figure.add_image(image.filepath, width='400px') figure.add_caption(f'Image nr {i} taken {image.timestampstr}') return doc
def network_figure(self, doc, temp_path, method="graphvis_col"): if method == "networkx": with doc.create(Figure(position='h!')) as network_pic: network_pic.add_image(os.path.join(temp_path, "graph_networkx.png"), width='240px') network_pic.add_caption('Network') if method == "graphvis": with doc.create(Figure(position='h!')) as network_pic: network_pic.add_image(os.path.join(temp_path, "network.pdf")) network_pic.add_caption('Network') if method == "graphvis_col": with doc.create(Figure(position='h!')) as network_pic: network_pic.add_image(os.path.join(temp_path, "network.pdf")) #network_pic.add_image("network.pdf") network_pic.add_caption('Network')
def middle_fork(self): with self.create(Section('Middle Fork')) as section_mf: df = self.capacity.models['middle_fork'] mask = (df['prod_date'] >= self.dt_start) & (df['prod_date'] < self.dt_end) table_df = df.loc[mask] summary_table_mf = Tabular('ccc|ccc|ccc', row_height=.40, width=9, booktabs=True) avg_tablemaker(summary_table_mf, table_df, self.month1, self.month2, self.month3) self.append(summary_table_mf) with self.create(Figure(position='h!')) as mf_plot: mf_fig, (ax1) = plt.subplots(nrows=1, ncols=1, sharex=True, sharey=False, squeeze=True, figsize=(14, 4)) self.append(NoEscape(r'')) ax1.stackplot(self.x, df.base_volume, df.wedge_volume, df.offload_volume, df.gas_lift_volume, df.berry_volume, df.garden_gulch_volume, labels=[ 'Base', 'Wedge', 'Offload', 'Gas Lift', 'Berry', 'Garden Gulch' ], colors=[ 'blue', 'cornflowerblue', 'orange', 'gold', 'goldenrod', 'red' ]) ax1.plot(self.x, df.max_volume, label='Capacity') ax1.legend(loc='upper left') ax1.tick_params(labelsize=14) mf_plot.add_plot(width=NoEscape(r'1\textwidth')) table_mf = Tabular('ccc|ccc|ccc', row_height=.10, width=9, booktabs=True) table_mf.add_row('Date', 'Gas, MCF', 'Delta', 'Date', 'Gas, MCF', 'Delta', 'Date', 'Gas, MCF', 'Delta') table_mf.add_hline() tablemaker(table_mf, table_df.prod_date.astype(str).tolist(), table_df.forecast.values.tolist(), table_df.report_overflow.values.tolist(), self.month1, self.month2, self.month3) section_mf.append(table_mf) self.append(NewPage())
def word_field_curve(self, doc, wf_cat=str()): #print(wf_cat) if wf_cat == "None": pass else: with doc.create(Figure(position='H')) as emoarc: print(os.getcwd()) emoarc.add_image("/".join( ([os.getcwd(), "data/temp_folder/word_field.pdf"]))) emoarc.add_caption( "Word field development in the current text")
def img_tag(element,document,picture_iterator,pic_width): with document.create(Figure(position='h!')) as picture: if element.parent.name == 'a' and element.parent['href'].endswith('.jpg'): file_pic = wget.download(element.parent['href'],str(picture_iterator) +'.jpg') picture.add_image(file_pic, width=pic_width) elif 'data-src' in element.attrs: file_pic = wget.download(element['data-src'], str(picture_iterator) + '.jpg') picture.add_image(file_pic, width=pic_width) else: file_pic = wget.download(element['src'], str(picture_iterator) + '.jpg') picture.add_image(file_pic, width=pic_width)
def PCAfigures(doc, pca, nb): doc.append( 'The representation of the projections of the data along the three axes is then performed as represented in the Figure 1.' ) with doc.create(Figure(position='H')) as pca_pic: for i in range(nb): if (i % 3 == 0 and i > 0): pca_pic.append(LineBreak()) pca_pic.add_image(pca[i], width='150px') pca_pic.add_caption( 'representation of PC scores of the body variables')
def create_fm_figure(reference, query): ref_mat = [list(reference), [str(i) for i in range(len(reference))]] ref_fig = tikz_matrix("ref", body(ref_mat)) reference = reference + "$" idxs, suffices = sort_suffices(reference) bwt = [s[-1] for s in suffices] occ = get_occurance_matrix(bwt) counts = get_char_counts([s[0] for s in suffices]) + 1 matrix = matrix1(idxs, suffices, occ, counts).replace("#", "\$") query_fig = tikz_matrix("query", body([query]), "below=of fm") Figure("fma", "fm").write("\n".join((ref_fig, matrix, query_fig)))
def latex(self): width = "auto" height = "auto" self._parse_attr_latex() if 'width' in self.attrs: width = self.attrs['width'] if 'height' in self.attrs: width = self.attrs['height'] _figure = Figure(position = 'h') _figure.add_image(self.uri, width = NoEscape(width), placement= NoEscape('\centering')) _figure.add_caption(self.caption) return _figure
def add_figure(self, file=None, caption=None, width='240px'): """ 添加图形 :param str file: 图形文件路径 :param str caption: 图形标题 :param str width: 图形宽度 :return: 无返回值 """ graph = Figure(position='h!') graph.add_image(file, width=width) if caption is not None: graph.add_caption(caption) self.doc.append(graph)
def build_histograms(self): if not self.histograms: return fig = plt.figure(tight_layout=True, figsize=self.figure_size) gs = gridspec.GridSpec(len(self.histograms), 2) for i, hist_dict in enumerate(self.histograms): ax = fig.add_subplot(gs[i, :]) ax.bar(x=hist_dict['data'], height=hist_dict['height']) ax.set_xlabel(hist_dict['name']) with self.doc.create(Section('DP Histograms')): with self.doc.create(Figure(position='htbp')) as plot: plot.add_plot() plot.add_caption('DP Histograms')