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 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 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 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 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 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 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 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 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)
# 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='') verbatim(s='', delimiter='|') # Lists
# Добавляем формулу умножения матриц agn.extend([Matrix(M), Matrix(a), '=', Matrix(M * a)]) # Создаём многоуровневую секцию 2.3. with doc.create(Subsection('Beautiful graphs')): # Создаём движок для графика (TikZ) with doc.create(TikZ()): # Создаём настройки для графика # width - ширина # height - высота # grid - сетка (major - основные, minor - все деления) plot_options = 'width=6cm, height=4cm, grid=major' # Создаём пустой график с осями with doc.create(Axis(options=plot_options)) as plot: # Добавляем точки с помощью функции, выводя в легенду название plot.append(Plot(name='Function', func='-x^5 - 242')) # Создаём список координат coords = [ (-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='By hand', coordinates=coords))
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 __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)))
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
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)
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), ] plot2 = Plot(name='estimate', coordinates=coordinates) axis.append(plot1)
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))
prevsubsec = "" section = None subsection = None # First global view section = Section('Global') doc.append(section) with doc.create(TikZ()): with doc.create(Axis(options='height=20cm, width=15cm, legend style ={legend pos=outer north east}')) as plot: for opt in options: times = timPerOpt[opt] times.sort() coords = [] for i in range(0, len(times)): coords.append((i, times[i])) plot.append(Plot(name=opt, coordinates=coords)) coords = {} for o in options: coords[o] = [] # Second summary section = Section('Summary : %d problems, %d configurations.' % (len(fnames), len(options))) doc.append(section) table = Tabular('l|l|l|l') table.add_hline() table.add_row(("Param.", 'Proofs', "Found best", "Times best (< %.1f)" % maxtime)) table.add_hline() for opt in options: proof = 0 fbest = 0