def draw(self): self.page_1 = Document(f'calendar_{self.year}_page1', documentclass='standalone') first_side = [5, 6, 4, 2, 10] with self.page_1.create(TikZ()) as self.pic: self.draw_face(1) for i, m in enumerate(first_side): if self.debug: print(f'ON CELL {m}') self.next_cell(i) self.draw_face(m) self.draw_folds(1, 4) self.prev_cell() self.page_2 = Document(f'calendar_{self.year}_page2', documentclass='standalone') second_side = [3, 11, 9, 7, 8] with self.page_2.create(TikZ()) as self.pic: self.draw_face(12) for i, m in enumerate(second_side): if self.debug: print(f'ON CELL {m}') self.next_cell(i) self.draw_face(m) self.draw_folds(1, 4) self.prev_cell() self.page_1.generate_pdf(f'calendar_{self.year}_page1', clean_tex=True) self.page_2.generate_pdf(f'calendar_{self.year}_page2', clean_tex=True)
def addPlots(doc, options, coords): with doc.create(Subsection('Plot')): with doc.create(TikZ()): with doc.create(Axis( options='height=5cm, width=10cm, legend style ={legend pos=outer north east}')) as plot: for opt in options: plot.append(Plot(name=opt, coordinates=list(coords[opt])))
def addTimePlots(doc, options, coords): with doc.create(Subsection('CPU Time')): with doc.create(TikZ()): with doc.create(Axis( options='xlabel=Instances, ylabel=CPU time (s), height=5cm, width=10cm,legend pos=outer north east')) as plot: for opt in options: plot.append(Plot(name=opt, coordinates=list(coords[opt])))
def test_tikz(): # PGFPlots TikZ(data=None) Axis(data=None, options=None) Plot(name=None, func=None, coordinates=None, error_bar=None, options=None)
def stuff(fname, width, *args, **kwargs): x = [0, 1, 2, 3, 4, 5, 6] y = [15, 2, 7, 1, 5, 6, 9] plt.plot(x, y) geometry_options = {"tmargin": "1cm", "lmargin": "10cm"} doc = Document(geometry_options=geometry_options) #with doc.create(Subsection('Beautiful graphs')): with doc.create(TikZ()): plot_options = 'height=6cm, 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)) print doc.dumps_content()
def _build_drawing(self): doc = Document() with doc.create(TikZ()) as tikz_pic: # create a node node_options = { 'align': 'center', 'inner sep': '20pt', 'label': '{{270:{}}}'.format(self.module.name) } box = TikZNode(handle='module', options=TikZOptions('draw', 'rounded corners', **node_options)) tikz_pic.append(box) for port in self.module.ports: if port.direction == 'in': tikz_pic.append( TikZNode(text=port.name, options=TikZOptions(anchor='west'), at=TikZCoordinate(-1, 1))) break doc.generate_tex('test') return doc
def addObjPlots(doc, options, objs, pol): with doc.create(Subsection('Objective')): with doc.create(TikZ()): with doc.create(Axis( options='log basis y=10,xlabel=Instances, ylabel=Objective (%s), height=5cm, width=10cm,legend pos=outer north east' % pol)) as plot: for opt in options: plot.append(Plot(name=opt, coordinates=list(objs[opt]))) plot.append(Plot(name='syb', coordinates=list(objs['syb'])))
def plotty(ord, asc, Name, end=5): with doc.create(TikZ()): plot_options = 'height=6cm, width=10cm' with doc.create(Axis(options=plot_options)) as plot: cordinates = [] for x in range(0, end): z = (ord[x], asc[x]) cordinates.append(z) plot.append(Plot(name=Name, coordinates=cordinates)) Command('xlabel', 'ciaone').dumps()
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 test_tikz(): # PGFPlots t = TikZ(data=None) repr(t) a = Axis(data=None, options=None) repr(a) p = Plot(name=None, func=None, coordinates=None, error_bar=None, options=None) repr(p)
def addPlots(doc, coords, name): with doc.create(Section(name)): for c in coords: # with doc.create(Subsection('Plots')): doc.append('') with doc.create(TikZ()): with doc.create( Axis( options= 'height=5cm, width=12cm, legend style ={legend pos=outer north east}' )) as plot: plot.append(Plot(coordinates=list(c)))
def generate_organigram(schema: PLDSchema, locale: LocaleDictionary, document: Document) -> Document: document.append(NewPage()) with document.create(Figure()) as figure: figure: Figure with figure.create(Section(title=locale.organigram)) as section: section: Section section.append(Command("centering")) with section.create(Center()) as center: center: Center with center.create(TikZ()) as forest: forest: TikZ node_kwargs = {'align': 'center', 'minimum size': '20pt'} # noinspection PyTypeChecker top_box = TikZNode(text=schema.title, handle=f"project-box", options=TikZOptions( 'draw', 'rounded corners', **node_kwargs)) forest.append(top_box) last_box_handle = top_box.handle for n_deliverable, deliverable in enumerate( schema.deliverables, start=1): # noinspection PyTypeChecker box = TikZNode( text=f"{n_deliverable}. {deliverable.name}", handle=f"deliverable-box-{n_deliverable}", options=TikZOptions( 'draw', 'rounded corners', f'below = of {last_box_handle}' if top_box.handle == last_box_handle else f'right = of {last_box_handle}', **node_kwargs)) last_box_handle = box.handle # noinspection PyTypeChecker path = TikZDraw( TikZPathList(top_box.get_anchor_point("south"), "--", box.get_anchor_point("north"))) forest.append(box) forest.append(path) document.append(VerticalSpace("2cm")) return document
def dud(self): with self.q_doc.create(TikZ()) as pic: # options for our node node_kwargs = { 'align': 'center', 'minimum size': '100pt', 'fill': 'black!20' } # create our test node box = TikZNode(text='My block', handle='box', options=TikZOptions('draw', 'rounded corners', **node_kwargs)) # add to tikzpicture pic.append(box) # draw a few paths pic.append( TikZDraw([ TikZCoordinate(0, -6), 'rectangle', TikZCoordinate(2, -8) ], options=TikZOptions(fill='red'))) # show use of anchor, relative coordinate pic.append(TikZDraw([box.west, '--', '++(-1,0)'])) # demonstrate the use of the with syntax with pic.create(TikZDraw()) as path: # start at an anchor of the node path.append(box.east) # necessary here because 'in' is a python keyword path_options = {'in': 90, 'out': 0} path.append( TikZUserPath('edge', TikZOptions('-latex', **path_options))) path.append(TikZCoordinate(1, 0, relative=True))
def get_latex_question(self, question): latex_question = TikZ() with latex_question.create(Axis(options=question.axis_options)) as ax: ax.append( Plot(options=question.plot_options, coordinates=question.coords)) # TODO: check for class type better if hasattr(question, 'small_left_node_text'): # MatrixFivePoints ax.append( self.node(at=('axis cs: 0', question.small_node_y), options=question.small_node_options, text=question.small_left_node_text)) ax.append( self.node(at=('axis cs: 6', question.small_node_y), options=question.small_node_options, text=question.small_right_node_text)) latex_question.append( self.node(at=question.question_node_at, text=question.question_title, options=question.node_options)) return latex_question
def paste_pdfs_base(inpaths, outpath, title='', flow='below'): print("--------", title, "-----------") if isinstance(inpaths, str): inpaths = [inpaths] print("--------", inpaths, "-----------") prefix = os.path.splitext(outpath)[0] infiles = [latex_tolerate(os.path.abspath(path)) for path in inpaths] doc = Document(documentclass='standalone') doc.preamble.append(NoEscape(r'\usetikzlibrary{chains}')) with doc.create( TikZ(options=NoEscape( f'start chain = going {flow}, node distance=0'))) as pic: for infile in infiles: pic.append( TikZNode(text=NoEscape(f'\includegraphics{{{infile}}}'), options='on chain')) top = TikZNode(text=NoEscape('\\large\\bfseries ' + latex_tolerate(title)), options='above', at=TikZCoordinate(0, 0)) top._position = '(current bounding box.north)' pic.append(top) doc.generate_pdf(NoEscape(prefix), clean_tex=False)
def pdf_matrix(big, small, title='', row=None, col=None): prefix = os.path.splitext(small['path'].tolist()[0])[0] if isinstance(row, str): row = [row] if isinstance(col, str): col = [col] df = big[row + col + ['path']].set_index(row + col) for cl in col: df = df.unstack(cl) df = df['path'] df = df.applymap(os.path.abspath) df = df.applymap(latex_tolerate) doc = Document(documentclass='standalone') doc.preamble.append(NoEscape(r'\usetikzlibrary{matrix}')) with doc.create(TikZ()) as pic: mbody = """\\tikzset{mylabel/.style={color=blue, font=\\large \\bfseries \\ttfamily}} \\matrix (m) [matrix of nodes, row sep = 2ex] { """ mbody += ' \\\\\n'.join([ r' & '.join([ f'\includegraphics{{{df.iloc[r,c]}}}' for c in range(df.shape[1]) ]) for r in range(df.shape[0]) ]) mbody += '\\\\\n};\n' for r in range(df.shape[0]): for c in range(df.shape[1]): tmp = df.iloc[r:r + 1, c:c + 1] names = tmp.index.names + tmp.columns.names vals = tmp.index.values.tolist() + tmp.columns.values.tolist() label = ','.join([f'{k}~{v}' for k, v in zip(names, vals)]) label = latex_tolerate(label) mbody += f'\\node[above, mylabel] at (m-{r+1}-{c+1}.north) {{{label}}};\n' pic.append(NoEscape(mbody)) top = TikZNode(text=NoEscape(latex_tolerate(title)), options=['above', 'mylabel'], at=TikZCoordinate(0, 0)) top._position = '(current bounding box.north)' pic.append(top) doc.generate_pdf(NoEscape(prefix), clean_tex=False)
def create_tex_file(doc_name, card_group): geometry_options = {"margin":"6mm","top":"5mm"} doc = Document(f"output", document_options=["a4paper", "portait"], geometry_options=geometry_options) title = bold(doc_name) page_title = LargeText(title) all_cards = 0 with doc.create(Center()): doc.append(page_title) with doc.create(Center()): # doc.change_page_style("empty") img, tex_cmd, cards = card_group for i, card in enumerate(cards): all_cards += i quantity = card.get("Quantity", 1) for c in range(int(quantity)): if all_cards % 3 == 0 and all_cards != 0: doc.append(VerticalSpace('2mm', star=False)) with doc.create(TikZ()) as pic: pic.append(CardBackground(img)) pic.append(tex_cmd(doc_name)) if not doc_name == "Project": pic.append(CardTitle(card["Name"])) pic.append(CardContent(arguments=[card["Description/illustration"], card["Effect"]])) else: pic.append(CardTitle( card["Requirements"])) pic.append(CardContent(arguments=[card["Project"],card["Description"]])) price = card.get("Development Value") if price: pic.append(CardPrice(price)) pic.append(CardBorder()) if not (all_cards + 1 % 3 == 0) or all_cards == 0: doc.append(HorizontalSpace('5mm',star=False)) all_cards += c doc.generate_pdf(f"{doc_name}", clean_tex=True) move_docs2output(doc_name)
def draw(): data = request.get_json() doc = Document() doc.append(Command('fontsize', arguments=['15', '12'])) doc.append(Command('selectfont')) user, intentname = data['intent']['intentName'].split(':') if intentname == 'matrix': if data.get('operation') == 'matrix_mult': commands.append(draw_multiply_matrix(data)) elif data.get('operation') == 'matrix_inverse': commands.append(draw_inverse_matrix(data)) else: commands.append(draw_matrix(data)) elif intentname == 'random-matrix': if data.get('operation') == 'matrix_mult': commands.append(draw_random_multiply_matrix(data)) else: commands.append(draw_random_matrix(data)) elif intentname == 'polynomial': f = Polynomial(data.get('coef')) op = data.get('operation') if op == 'integral': commands.append(draw_integral(data, f.parse())) elif op == 'derivate': commands.append(draw_derivative(data, f.parse())) elif op == 'plot': with doc.create(TikZ()): plot_options = 'height=10cm, width=10cm' with doc.create(Axis(options=plot_options)) as plot: plot.append(Plot(func=f.toPlot())) else: commands.append(draw_polynomial(f.parse())) elif intentname == 'trigfunc': f = Trig(data.get('trigfunc'), data.get('var'), data.get('auxoper')) op = data.get('operation') if op == 'integral': commands.append(draw_integral(data, f.parse(), render=False)) elif op == 'derivate': commands.append(draw_derivative(data, f.parse(), render=False)) else: commands.append(draw_trig(f.parse())) try: for c in commands: doc.append(c) doc.append(NewLine()) doc.append(NewLine()) doc.generate_pdf(OUT_PATH, clean_tex=False) except Exception as e: print(e) try: requests.get(RENDERER_URL).json() except: pass return "ok"
def details(): if __name__ == '__main__': image_filename = os.path.join(os.path.dirname(__file__), 'kitten.jpg') logo_file = os.path.join(os.path.dirname(__file__),'sample-logo.png') geometry_options = {"tmargin": "1cm", "lmargin": "3cm"} doc = Document(geometry_options=geometry_options) header = PageStyle("header") with header.create(Head("R")): header.append(simple_page_number()) with header.create(Foot("C")): header.append("Center Footer") first_page = PageStyle("firstpage") with first_page.create(Head("L")) as header_left: with header_left.create(MiniPage(width=NoEscape(r"0.49\textwidth"),pos='c')) as logo_wrapper with doc.create(MiniPage(align='l')): doc.append(LargeText(bold("INVESTMENT PROPERTY - BUY & HOLD"))) doc.append(LineBreak()) doc.append(MediumText(bold(" "))) logo_wrapper.append(StandAloneGraphic(image_options="width=120px", filename=logo_file)) with doc.create(Section('Home Adress')): 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)
mask = np.zeros((num_partitions, S), dtype=np.bool) gumbel_noise = np.random.gumbel(size=mask.shape) idx = gumbel_noise.argsort()[:, :S // 2] np.put_along_axis(mask, idx, True, -1) mask_flat = mask.reshape(-1) dt = 6 dz = 6 dsize = "1.5pt" ssize = "0.5pt" doc = Document() with doc.create(TikZ()) as pic: # dropout mask # edges for t0, t1, z0, z1 in edgegrid: in0 = (z0 // S) == partitions[t0] in1 = (z1 // S) == partitions[t1] in0 = True in1 = True #on0 = mask[partitions[t0], z0 % S] #on1 = mask[partitions[t1], z1 % S] #if in0 and in1 and on0 and on1: if in0 and in1: #import pdb; pdb.set_trace() pt0 = dt * t0 / T pz0 = dz * z0 / C
def test_tikz(): # PGFPlots t = TikZ(data=None) repr(t) a = Axis(data=None, options=None) repr(a) p = Plot(name=None, func=None, coordinates=None, error_bar=None, options=None) repr(p) opt = TikZOptions(None) repr(opt) scope = TikZScope(data=None) repr(scope) c = TikZCoordinate.from_str("(0,0)") c = TikZCoordinate(x=0, y=0, relative=False) d = c + (0, 1) e = c - (0, 1) f = (0, 1) + c c.distance_to(d) repr(c) repr(d) repr(e) repr(f) bool(c == (1, 1)) bool(c == TikZCoordinate(1, 1)) bool(TikZCoordinate(1, 1, relative=True) == (1, 1)) bool(TikZCoordinate(1, 1, relative=False) == (1, 1)) bool( TikZCoordinate(1, 1, relative=True) == TikZCoordinate( 1, 1, relative=False)) # test expected to fail try: g = TikZCoordinate(0, 1, relative=True) +\ TikZCoordinate(1, 0, relative=False) repr(g) raise Exception except ValueError: pass a = TikZNodeAnchor(node_handle=None, anchor_name=None) repr(a) n = TikZNode(handle=None, options=None, at=None, text=None) repr(n) p = n.get_anchor_point("north") repr(p) p = n.get_anchor_point('_180') repr(p) p = n.west repr(p) up = TikZUserPath(path_type="edge", options=TikZOptions('bend right')) repr(up) pl = TikZPathList('(0, 1)', '--', '(2, 0)') pl.append((0.5, 0)) repr(pl) # generate a failure, illegal start try: pl = TikZPathList('--', '(0, 1)') raise Exception except TypeError: pass # fail with illegal path type try: pl = TikZPathList('(0, 1)', 'illegal', '(0, 2)') raise Exception except ValueError: pass # fail with path after path try: pl = TikZPathList('(0, 1)', '--', '--') raise Exception except ValueError: pass # other type of failure: illegal identifier after path try: pl = TikZPathList('(0, 1)', '--', 'illegal') raise Exception except (ValueError, TypeError): pass pt = TikZPath(path=None, options=TikZOptions("->")) pt.append(TikZCoordinate(0, 1, relative=True)) repr(pt) pt = TikZPath(path=[n.west, 'edge', TikZCoordinate(0, 1, relative=True)]) repr(pt) pt = TikZPath(path=pl, options=None) repr(pt) dr = TikZDraw(path=None, options=None) repr(dr)
pyplot.plot(x, y) plot.add_plot(plt=pyplot, width=r'0.8\textwidth', placement=r'\centering') plot.add_caption(caption='I am a caption.') # Numpy v = VectorName(name='') M = np.matrix([[2, 3, 4], [0, 0, 1], [0, 0, 2]]) m = Matrix(matrix=M, name='', mtype='p', alignment=None) # Package p = Package(name='', base='usepackage', options=None) # PGFPlots tikz = TikZ(data=None) a = Axis(data=None, options=None) p = Plot(name=None, func=None, coordinates=None, options=None) # Utils escape_latex(s='') fix_filename(path='') dumps_list(l=[], escape=False, token='\n') bold(s='') italic(s='')
table = Subsection('Table of something', data=[table]) section.append(table) a = np.array([[100, 10, 20]]).T M = np.matrix([[2, 3, 4], [0, 0, 1], [0, 0, 2]]) math = Math(data=[Matrix(M), Matrix(a), '=', Matrix(M*a)]) equation = Subsection('Matrix equation', data=[math]) section.append(equation) tikz = TikZ() axis = Axis(options='height=6cm, width=6cm, grid=major') plot1 = 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), ]
anchor = 'north west' pic_opts = TikZOptions( 'shorten >= 0pt', 'shorten <= {}cm'.format(-.1 * global_scale), **{ 'draw': 'black', # 'line width': .05, 'inner sep': '0pt', 'node distance': '{}cm'.format(1 * global_scale), 'anchor': anchor, 'x': '{}cm'.format(global_scale), 'y': '{}cm'.format(global_scale) }) with doc.create(TikZ(options=pic_opts)) as pic: # def c(x, y): # return TikZCoordinate(x*global_scale, y*global_scale) c = TikZCoordinate nodes = [] node_opts = TikZOptions( 'circle', **{ 'line width': 3 * global_scale, 'draw opacity': 0, 'fill opacity': 0, 'minimum size': '.7cm', 'inner sep': 3 * global_scale }) annot_opts = TikZOptions(
def __globals(self, doc, options, timPerOpt, maxtime): # First global view section = Section('Global') doc.append(section) options.append('GOD') with doc.create(TikZ()): with doc.create( Axis( options= 'xlabel=Instances (ordered wrt to increasing resolution time),' 'ylabel=CPU time (s),height=20cm, width=15cm,legend pos=outer north east' )) as plot: for opt in options: times = [x for x in timPerOpt[opt] if x <= maxtime] times.sort() coords = [] print("%s" % (opt), end=";") for i in range(0, len(times)): coords.append((i, times[i])) print("%d" % (times[i]), end=";") print("\n") plot.append(Plot(name=opt, coordinates=coords)) # Second zoom section = Section('Global + zoom') doc.append(section) with doc.create(TikZ()): with doc.create( Axis( options= 'xlabel=Instances (ordered wrt to increasing resolution time),' 'ylabel=CPU time (s),height=20cm, width=15cm,legend pos=outer north east' )) as plot: for opt in options: times = timPerOpt[opt].copy() times.sort() if maxtime in times: id = times.index(maxtime) else: id = len(times) coords = [] for i in range(max(0, id - 30), min(id + 1, len(times))): coords.append((i, times[i])) plot.append(Plot(name=opt, coordinates=coords)) options.remove('GOD') # First global view for o1 in range(0, len(options) - 1): for o2 in range(o1 + 1, len(options)): opt1 = options[o1] opt2 = options[o2] section = Section('%s vs. %s' % (opt1, opt2)) doc.append(section) subsection = Subsection("1st view") doc.append(subsection) with doc.create(TikZ()): with doc.create( Axis(options=( 'xlabel=time(%s) - time(%s),' 'ylabel=CPU time diff. (s),height=15cm, width=15cm,legend pos=outer north east' ) % (opt1, opt2))) as plot: times1 = timPerOpt[opt1] times2 = timPerOpt[opt2] times = [ times1[i] - times2[i] for i in range(0, len(times1)) ] times.sort() coords1 = [] coords2 = [] for i in range(0, len(times)): if times[i] < 0: coords1.append((i, -times[i])) coords2.append((i, 0)) elif times[i] > 0: coords1.append((i, 0)) coords2.append((i, times[i])) plot.append(Plot(name=opt2, coordinates=coords1)) plot.append(Plot(name=opt1, coordinates=coords2)) subsection = Subsection("2nd view") doc.append(subsection) with doc.create(TikZ()): with doc.create( Axis(options=( 'xmode=log, ymode=log, xlabel=%s,' 'ylabel=%s,height=15cm, width=15cm,legend pos=outer north east' ) % (opt1, opt2))) as plot: times1 = timPerOpt[opt1] times2 = timPerOpt[opt2] coords = [] for i in range(0, len(times1)): coords.append((times1[i], times2[i])) plot.append( Plot(name="Instance", coordinates=coords, options='only marks, mark=+')) plot.append( Plot(func="x", options=("domain=0.001:%s") % (maxtime)))
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), ]
def general_report(complete, fails, matchIsolates, metadata, metaDf, args): newisolates = list(set(matchIsolates).difference(set(complete))) """ todo input dict of id to isolates cclis = get_merge_cclis(conn,cc,level,args.appname).split(",") """ doc = Multistrain('tgbonum') # Call function to add text # doc.fill_document() tp = "" lev = "" if args.stlev: tp = "ST" lev = args.stlev if args.cclev: tp = "CC" lev = args.cclev if args.odclev: tp = "ODC" lev = args.odclev search_restrictions = searchRestrictionList(args) # Add stuff to the document timerange="all",year="all",country="all",continent="all"postcode="all",source="all",sourcetype="all",host="all",disease="all" if not args.identifier: with doc.create(Section('Search Settings')): doc.append( 'Database was searched using {type} at level {lev}{restrict}'. format(type=tp, lev=lev, restrict=search_restrictions)) if args.list or args.file: with doc.create(Subsection('Input Isolates')): doc.append( 'Successfully processed isolates:\n {}\n'.format( ", ".join(complete))) doc.append('Failed isolates:\n') if len(list(fails.keys())) != 0: fmt = "X[l] X[l]" with doc.create(Tabu(fmt, spread="1pt", pos=["l"])) as data_table: header_row1 = ["Isolate", "Failure Reason"] data_table.add_row(MultiColumn(1, data=header_row1)) data_table.add_hline() for reason in fails: for isolate in fails[reason]: d = [isolate, reason] data_table.add_row(MultiColumn(2, data=d)) else: doc.append('None\n') with doc.create(Subsection('Matching Isolates')): if len(newisolates) > 40: doc.append( 'The above isolates matched to {no} other isolates \n'. format(no=len(newisolates))) else: doc.append( 'The above isolates matched to the following {no} isolates \n' .format(no=len(newisolates))) fmt = "X[l]X[l]" with doc.create(Tabu(fmt, spread="1pt", pos=["l"])) as data_table: search_level = tp + lev header_row1 = ["Name", search_level] data_table.add_row(MultiColumn(2, data=header_row1)) data_table.add_hline() sorted_isolates = sorted( newisolates, key=lambda i: int(metadata['used_id'][i])) print(newisolates) print(sorted_isolates) for i in sorted_isolates: isolate_used_id = metadata['used_id'][i] data = [i, isolate_used_id] data_table.add_row(MultiColumn(2, data=data)) else: with doc.create(Section('Search Settings')): doc.append( 'Database was searched using {type}={ident} at level {lev}{restrict}' .format(type=tp, ident=args.identifier, lev=lev, restrict=search_restrictions)) with doc.create(Subsection('Matching Isolates')): if len(newisolates) > 40: doc.append( 'The above settings matched to {no} other isolates \n'. format(no=len(newisolates))) else: doc.append( 'The above settings matched to the following {no} isolates \n' .format(no=len(newisolates))) doc.append(", ".join(newisolates)) fmt = "X[l]X[l]" with doc.create(Tabu(fmt, spread="1pt", pos=["l"])) as data_table: search_level = tp + lev header_row1 = ["Name", search_level] data_table.add_row(MultiColumn(2, data=header_row1)) data_table.add_hline() sorted_isolates = sorted( newisolates, key=lambda i: int(metadata['used_id'][i])) print(newisolates) print(sorted_isolates) for i in sorted_isolates: isolate_used_id = metadata['used_id'][i] data = [i, isolate_used_id] data_table.add_row(MultiColumn(2, data=data)) with doc.create(Section('Graph By Year')): 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')) plot.append(Plot(name='estimate', coordinates=coordinates)) # Generate data table with 'tight' columns # with doc.create(Center()) as centered: # with centered.create(Tabu("X[r] X[r]", spread="1in")) as data_table: # header_row1 = ["X", "Y"] # data_table.add_row(header_row1, mapper=[bold]) # data_table.add_hline() # row = [randint(0, 1000), randint(0, 1000)] # for i in range(4): # data_table.add_row(row) # # with doc.create(Center()) as centered: # with centered.create(Tabu("X[r] X[r]", to="4in")) as data_table: # header_row1 = ["X", "Y"] # data_table.add_row(header_row1, mapper=[bold]) # data_table.add_hline() # row = [randint(0, 1000), randint(0, 1000)] # for i in range(4): # data_table.add_row(row) doc.generate_pdf('MGT report', clean_tex=False) # make pdf tex = doc.dumps() # make latex file