def __init__(self, row, col, mycolor, seqStrings=None): print "draw cluster", row, col, mycolor print seqStrings filename = "sequences" + ` row ` + ` col ` + ".png" matplotlib.rc('image', origin='upper') parser = mathtext.MathTextParser("Bitmap") h = 10 #.15 * len(self.seqdata) #3 w = 20 fig = plt.figure(figsize=(w, h), facecolor='w') #fig.savefig(filename) mydpi = 200 line = 0 for seq in seqStrings: print seq fsize = 8 rgba1, depth1 = parser.to_rgba(seq, color=mycolor, fontsize=fsize, dpi=mydpi) x = 10 y = 10 + (22 * line) #1100 - (5*i) fig.figimage(rgba1.astype(float) / 255., x, y) line += 1 plt.savefig(filename, dpi=mydpi)
def test_mathtext_exceptions(): errors = [ (r'$\hspace{}$', r'Expected \hspace{n}'), (r'$\hspace{foo}$', r'Expected \hspace{n}'), (r'$\frac$', r'Expected \frac{num}{den}'), (r'$\frac{}{}$', r'Expected \frac{num}{den}'), (r'$\stackrel$', r'Expected \stackrel{num}{den}'), (r'$\stackrel{}{}$', r'Expected \stackrel{num}{den}'), (r'$\binom$', r'Expected \binom{num}{den}'), (r'$\binom{}{}$', r'Expected \binom{num}{den}'), (r'$\genfrac$', r'Expected \genfrac{ldelim}{rdelim}{rulesize}{style}{num}{den}'), (r'$\genfrac{}{}{}{}{}{}$', r'Expected \genfrac{ldelim}{rdelim}{rulesize}{style}{num}{den}'), (r'$\sqrt$', r'Expected \sqrt{value}'), (r'$\sqrt f$', r'Expected \sqrt{value}'), (r'$\overline$', r'Expected \overline{value}'), (r'$\overline{}$', r'Expected \overline{value}'), (r'$\leftF$', r'Expected a delimiter'), (r'$\rightF$', r'Unknown symbol: \rightF'), (r'$\left(\right$', r'Expected a delimiter'), (r'$\left($', r'Expected "\right"') ] parser = mathtext.MathTextParser('agg') for math, msg in errors: try: parser.parse(math) except ValueError as e: exc = str(e).split('\n') print(e) assert exc[3].startswith(msg) else: assert False, "Expected '%s', but didn't get it" % msg
def latex_to_png_mpl(s, wrap, color='Black', scale=1.0): try: from matplotlib import figure, font_manager, mathtext from matplotlib.backends import backend_agg from pyparsing import ParseFatalException except ImportError: return None # mpl mathtext doesn't support display math, force inline s = s.replace('$$', '$') if wrap: s = u'${0}$'.format(s) try: prop = font_manager.FontProperties(size=12) dpi = 120 * scale buffer = BytesIO() # Adapted from mathtext.math_to_image parser = mathtext.MathTextParser("path") width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop) fig = figure.Figure(figsize=(width / 72, height / 72)) fig.text(0, depth / height, s, fontproperties=prop, color=color) backend_agg.FigureCanvasAgg(fig) fig.savefig(buffer, dpi=dpi, format="png", transparent=True) return buffer.getvalue() except (ValueError, RuntimeError, ParseFatalException): return None
def __init__ (self, row, col, mapcolors, clusterid, seqdata, ids) : import numpy as np import matplotlib.mathtext as mathtext import matplotlib.pyplot as plt import matplotlib self.mapcolors = mapcolors self.clusterid = clusterid self.seqdata = seqdata self.seqids = ids matplotlib.rc('image', origin='upper') parser = mathtext.MathTextParser("Bitmap") filename = "sequences" + `row` + `col` + ".png" print filename #filename = 'sequences.png' # "sequences" + num +".png" #'sequences.png' #'sequences', str(k), '.png' #parser.to_png(filename, r'$\left[\left\lfloor\frac{5}{\frac{\left(3\right)}{4}} y\right)\right]$', color='green', fontsize=14, dpi=100) print len(self.seqdata) h = 10#.15 * len(self.seqdata) #3 w = 20 fig = plt.figure(figsize=(w,h), facecolor='w') #fig.savefig(filename) i = 0 line = 0 for seq in self.seqdata: if clusterid[i][0] == row and clusterid[i][1]== col: print self.seqids[i] str = self.seqids[i] + ' ' for elem in seq: #if elem == "-": elem = " " if elem != "-": str = str + elem #print str #print i, self.clusterid[i], " ", self.clusterid[i][0], " ", self.clusterid[i][1] c = self.getColor(self.clusterid[i][0], self.clusterid[i][1]) #print "row ", self.clusterid[i][0] #print "col", self.clusterid[i][1] fsize = 2 rgba1, depth1 = parser.to_rgba(str, color=c, fontsize=fsize, dpi=300) #fig.figimage(rgba1.astype(float)/255., 10, 300 - (10*i)) x = 10 y = 10 + (10*line) #1100 - (5*i) fig.figimage(rgba1.astype(float)/255., x, y) line += 1 i += 1 if line > 0: print "save file" plt.savefig(filename, dpi=100)
def on_tex_changed(self): try: parser = math_text.MathTextParser('svg') parser.parse(r"$" + self.tex.text() + r"$") except ValueError: self.label.setText("TeX语法不正确") else: self.label.setText('') self.generate_svg(self.tex.text())
def formula(self, formula): """ This function create a png picture to render mathematical formula """ parser = mathtext.MathTextParser("Bitmap") rgba1, depth1 = parser.to_rgba(formula, fontsize=8, dpi=200) fig = pyplot.figure(facecolor='white', figsize=(3, 0.2)) fig.figimage(rgba1.astype(float) / 255., 0, 0) pyplot.savefig(Main.Script_Path + "\\formula.png")
def latex_to_png_mpl(s): try: from matplotlib import mathtext except ImportError: return None mt = mathtext.MathTextParser('bitmap') f = StringIO() mt.to_png(f, s, fontsize=12) return f.getvalue()
def __init__(self, s): self.s = s if HAS_MATPLOTLIB: self.parser = mathtext.MathTextParser("Pdf") else: log.error( "Math support not available," " some parts of this document will be rendered incorrectly." " Install matplotlib.") Flowable.__init__(self)
def latex_to_png_mpl(s, wrap): try: from matplotlib import mathtext except ImportError: return None if wrap: s = '${0}$'.format(s) mt = mathtext.MathTextParser('bitmap') f = BytesIO() mt.to_png(f, s, fontsize=12) return f.getvalue()
def renderFormula(self): # Render the formula into a png image import matplotlib.mathtext as mathtext parser = mathtext.MathTextParser("Bitmap") # Note: the baseline returned by to_png() is not completely accurate! # baseline = parser.to_png('math.png', r'${}$'.format(self.formula), color='black', fontsize=12, dpi=100) self.image = QImage('math.png')
def __init__(self, s, label=None, fontsize=12, color='black'): self.s = s self.label = label self.fontsize = fontsize self.color = color if HAS_MATPLOTLIB: self.parser = mathtext.MathTextParser("Pdf") else: log.error( "Math support not available," " some parts of this document will be rendered incorrectly." " Install matplotlib.") Flowable.__init__(self) self.hAlign = 'CENTER'
def latex_to_png_mpl(s, wrap): try: from matplotlib import mathtext except ImportError: return None # mpl mathtext doesn't support display math, force inline s = s.replace('$$', '$') if wrap: s = u'${0}$'.format(s) mt = mathtext.MathTextParser('bitmap') f = BytesIO() mt.to_png(f, s, fontsize=12) return f.getvalue()
def latex_to_png(s, encode=True): """Render a LaTeX string to PNG using matplotlib.mathtext. Parameters ---------- s : str The raw string containing valid inline LaTeX. encode : bool, optional Should the PNG data bebase64 encoded to make it JSON'able. """ from matplotlib import mathtext mt = mathtext.MathTextParser('bitmap') f = StringIO() mt.to_png(f, s, fontsize=12) bin_data = f.getvalue() if encode: bin_data = encodestring(bin_data) return bin_data
def __init__(self, row, col, mycolors, clusterid, seqdate, ids): import numpy as np import matplotlib.mathtext as mt import matplotlib.pyplot as plt import matplotlib self.mycolors = mycolors self.clusterid = clusterid self.seqdate = seqdate self.seqids = ids matplotlib.rc('image', origin='upper') parser = mt.MathTextParser('Bitmap') filename = 'sequence' + 'row' + 'col' + '.png' print(len(self.seqdate)) h = 10 w = 20 fig = plt.figure(figsize=(w, h), facecolor='w') i = 0 line = 0 for seq in self.seqdate: if clusterid[i][0] == row and clusterid[i][1] == col: print(self.seqids[i]) str = self.seqids[i] + ' ' for elem in seq: if elem != '-': str = str + elem c = self.getcolor(self.clusterid[i][0], self.clusterid[i][1]) fsize = 2 rgba1, depth1 = parser.to_rgba(str, color=c, fontsize=fsize, dpi=300) x = 10 y = 10 + (10 * line) fig.figimage(rgba1.astype(float) / 255., x, y) line += 1 i += 1 if line > 0: print("save file") plt.savefig(filename, dpi=100)
def latex_to_png_mpl(s, wrap, color="Black", scale=1.0): try: from matplotlib import mathtext from pyparsing import ParseFatalException except ImportError: return None # mpl mathtext doesn't support display math, force inline s = s.replace("$$", "$") if wrap: s = u"${0}$".format(s) try: mt = mathtext.MathTextParser("bitmap") f = BytesIO() dpi = 120 * scale mt.to_png(f, s, fontsize=12, dpi=dpi, color=color) return f.getvalue() except (ValueError, RuntimeError, ParseFatalException): return None
def __init__ (self,row,col,mycolor,seqStrings=None):#类属性参数,在类中传入参数 print("draw cluster",row,col,mycolor) print(seqStrings) filename="sequence"+str(row)+str(col)+".png" mpl.rc('image',origin='upper')#利用关键字参数对数值进行修改,生成图像的位置。 parse=mt.MathTextParser('Bitmap') h=10 w=20 fig=plt.figure(figsize=(w,h),facecolor='w')#facecolor为背景颜色,w=white mydpi=200 line=0 for seq in seqStrings: print(seq) fsize=8 rgba1,depth1=parse.to_rgba(seq,color=mycolor,fontsize=fsize,dpi=mydpi)#to_rgba用于16进制颜色之间转换 x=10 y=10+(22*line) fig.figimage(rgba1.astype(float)/255.,x,y) line+=1 plt.savefig(filename,dpi=mydpi)
def __init__(self, s, label=None, style=None): Flowable.__init__(self) self.s = s.strip() self.label = label self.fontsize = 10 self.color = (0, 0, 0) self.hAlign = 'LEFT' if style: self.style = style self.fontsize = style.fontSize self.color = style.textColor.rgb() self.hAlign = style.alignment if HAS_MATPLOTLIB: self.parser = mathtext.MathTextParser("Path") else: log.error( "Math support not available," " some parts of this document will be rendered incorrectly." " Install matplotlib.") if "\n" in s: log.error( "rst2pdf's math directive does not support multiple lines'")
class MenuItem(artist.Artist): parser = mathtext.MathTextParser("Bitmap") padx = 5 pady = 5 def __init__(self, fig, labelstr): artist.Artist.__init__(self) self.set_figure(fig) x, self.depth = self.parser.to_rgba(labelstr, color='black', fontsize=14, dpi=100) xHover, depth = self.parser.to_rgba(labelstr, color='white', fontsize=14, dpi=100) self.labelwidth = x.shape[1] self.labelheight = x.shape[0] print 'h', self.labelheight self.label = image.FigureImage(fig) self.label.set_array(x.astype(float) / 255.) self.labelHover = image.FigureImage(fig) self.labelHover.set_array(xHover.astype(float) / 255.) # we'll update these later self.rect = patches.Rectangle((0, 0), 1, 1, facecolor='yellow', alpha=0.2) self.rectHover = patches.Rectangle((0, 0), 1, 1, facecolor='blue', alpha=0.2) def set_extent(self, x, y, w, h): print x, y, w, h self.rect.set_x(x) self.rect.set_y(y) self.rect.set_width(w) self.rect.set_height(h) self.rectHover.set_x(x) self.rectHover.set_y(y) self.rectHover.set_width(w) self.rectHover.set_height(h) self.label.ox = x + self.padx self.label.oy = y - self.depth + self.pady / 2. self.rect._update_patch_transform() self.rectHover._update_patch_transform() self.labelHover.ox = x + self.padx self.labelHover.oy = y - self.depth + self.pady / 2. self.hover = False self.activeRect = self.rect self.activeLabel = self.label def draw(self, renderer): self.activeRect.draw(renderer) self.activeLabel.draw(renderer) def set_hover(self, event): 'check the hover status of event and return true if status is changed' b, junk = self.rect.contains(event) if b: self.activeRect = self.rectHover self.activeLabel = self.labelHover else: self.activeRect = self.rect self.activeLabel = self.label h = self.hover self.hover = b return b != h
Name : 4375OS_07_34_math_formulae.py Book : Python for Finance Publisher: Packt Publishing Ltd. Author : Yuxing Yan Date : 12/26/2013 email : [email protected] [email protected] """ import numpy as np import matplotlib.mathtext as mathtext import matplotlib.pyplot as plt import matplotlib matplotlib.rc('image', origin='upper') parser = mathtext.MathTextParser("Bitmap") r'$\left[\left\lfloor\frac{5}{\frac{\left(3\right)}{4}} y\right)\right]$' rgba1, depth1 = parser.to_rgba( r' $d_2=\frac{ln(S_0/K)+(r-\sigma^2/2)T}{\sigma\sqrt{T}}=d_1-\sigma\sqrt{T}$', color='blue', fontsize=12, dpi=200) rgba2, depth2 = parser.to_rgba( r'$d_1=\frac{ln(S_0/K)+(r+\sigma^2/2)T}{\sigma\sqrt{T}}$', color='blue', fontsize=12, dpi=200) rgba3, depth3 = parser.to_rgba(r' $c=S_0N(d_1)- Ke^{-rT}N(d_2)$', color='red', fontsize=14, dpi=200)
def test_mathtext_to_png(tmpdir): with _api.suppress_matplotlib_deprecation_warning(): mt = mathtext.MathTextParser('bitmap') mt.to_png(str(tmpdir.join('example.png')), '$x^2$') mt.to_png(io.BytesIO(), '$x^2$')
def test_mathtext_exceptions(math, msg): parser = mathtext.MathTextParser('agg') match = re.escape(msg) if isinstance(msg, str) else msg with pytest.raises(ValueError, match=match): parser.parse(math)
class MenuItem(artist.Artist): parser = mathtext.MathTextParser("Bitmap") padx = 5 pady = 5 def __init__(self, fig, labelstr, props=None, hoverprops=None, on_select=None): artist.Artist.__init__(self) self.set_figure(fig) self.labelstr = labelstr if props is None: props = ItemProperties() if hoverprops is None: hoverprops = ItemProperties() self.props = props self.hoverprops = hoverprops self.on_select = on_select x, self.depth = self.parser.to_mask(labelstr, fontsize=props.fontsize, dpi=fig.dpi) if props.fontsize != hoverprops.fontsize: raise NotImplementedError( 'support for different font sizes not implemented') self.labelwidth = x.shape[1] self.labelheight = x.shape[0] self.labelArray = np.zeros((x.shape[0], x.shape[1], 4)) self.labelArray[:, :, -1] = x / 255. self.label = image.FigureImage(fig, origin='upper') self.label.set_array(self.labelArray) # we'll update these later self.rect = patches.Rectangle((0, 0), 1, 1) self.set_hover_props(False) fig.canvas.mpl_connect('button_release_event', self.check_select) def check_select(self, event): over, junk = self.rect.contains(event) if not over: return if self.on_select is not None: self.on_select(self) def set_extent(self, x, y, w, h): print(x, y, w, h) self.rect.set_x(x) self.rect.set_y(y) self.rect.set_width(w) self.rect.set_height(h) self.label.ox = x + self.padx self.label.oy = y - self.depth + self.pady / 2. self.rect._update_patch_transform() self.hover = False def draw(self, renderer): self.rect.draw(renderer) self.label.draw(renderer) def set_hover_props(self, b): if b: props = self.hoverprops else: props = self.props r, g, b = props.labelcolor_rgb self.labelArray[:, :, 0] = r self.labelArray[:, :, 1] = g self.labelArray[:, :, 2] = b self.label.set_array(self.labelArray) self.rect.set(facecolor=props.bgcolor, alpha=props.alpha) def set_hover(self, event): 'check the hover status of event and return true if status is changed' b, junk = self.rect.contains(event) changed = (b != self.hover) if changed: self.set_hover_props(b) self.hover = b return changed
def test_mathtext_to_png(tmpdir): mt = mathtext.MathTextParser('bitmap') mt.to_png(str(tmpdir.join('example.png')), '$x^2$') mt.to_png(io.BytesIO(), '$x^2$')
sections = document.sections for section in sections: section.top_margin = Cm(1) section.bottom_margin = Cm(1) section.left_margin = Cm(1) section.right_margin = Cm(1) t = document.add_table(df.shape[0] + 1, df.shape[1]) # add the header rows. for j in range(df.shape[-1]): t.cell(0, j).text = df.columns[j] # add the rest of the data frame for i in range(df.shape[0]): for j in range(df.shape[-1]): t.cell(i + 1, j).text = str(df.values[i, j]) t.style = 'Table Grid' t.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER inline_obj = document.add_picture("grafica.png") #return Inline object inline_obj.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER parser = mathtext.MathTextParser('bitmap') offset = parser.to_png("modelo.png", modelo, fontsize=12) inline_obj = document.add_picture("modelo.png") #return Inline object inline_obj.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER document.save('grafica.docx')
def create_pb_from_mathtext(text, align='center', weight='heavy', color='b', style='normal'): """ Create a Gdk.Pixbuf from a mathtext string """ global pbmt_cache global dpi if not text in pbmt_cache: parts, fontsize = _handle_customs(text) pbs = [] width = 0 height = 0 # heights = [] # Temporarily set font properties: old_params = rcParams["font.weight"], rcParams["text.color"], rcParams[ "font.style"] rcParams["font.weight"] = weight rcParams["text.color"] = color rcParams["font.style"] = style # Create parser and load png fragments parser = mathtext.MathTextParser("Bitmap") for part in parts: png_loader = GdkPixbuf.PixbufLoader.new_with_type( 'png') # @UndefinedVariable parser.to_png(png_loader, part, dpi=dpi, fontsize=fontsize) png_loader.close() pb = png_loader.get_pixbuf() w, h = pb.get_width(), pb.get_height() width = max(width, w) height += h pbs.append((pb, w, h)) # Restore font properties rcParams["font.weight"], rcParams["text.color"], rcParams[ "font.style"] = old_params surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) cr = cairo.Context(surface) cr.save() cr.set_operator(cairo.OPERATOR_CLEAR) cr.paint() cr.restore() cr.save() offsetx = 0 offsety = 0 for pb, w, h in pbs: if align == 'center': offsetx = int((width - w) / 2) if align == 'left': offsetx = 0 if align == 'right': offsetx = int(width - w) Gdk.cairo_set_source_pixbuf(cr, pb, offsetx, offsety) cr.rectangle(offsetx, offsety, w, h) cr.paint() offsety += h del pbs cr.restore() pbmt_cache[text] = Gdk.pixbuf_get_from_surface(surface, 0, 0, width, height) return pbmt_cache[text]
def draw_line7(): parser = mathtext.MathTextParser("Bitmap") parser.to_png('line7.png', '123', color='red', fontsize=20, dpi=100) return
def make_fraction_img(denomitor, numerator, name): parser = mathtext.MathTextParser("Bitmap") parser.to_png(name, r'$\frac{' + str(denomitor) +r'}{' + str(numerator)+ r' }$ ', color='gold', fontsize=120, dpi=300)
def test_mathtext_exceptions(math, msg): parser = mathtext.MathTextParser('agg') with pytest.raises(ValueError, match=re.escape(msg)): parser.parse(math)
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Provides a smart dictionary "Adapter" class, which handles conversion between the raw strings POST-ed to the service and Python objects. """ import numpy as np from matplotlib import mathtext MATH_PARSER = mathtext.MathTextParser('agg') def remove_none(dct): """ Remove entries from a dict whose value is None. """ tmp = dict((x, y) for (x, y) in dct.iteritems() if y is not None) dct.clear() dct.update(tmp) class Terminals(dict): """ Python-side representation of a VI's terminals. To access data on a particular terminal, call the method corresponding to the terminal's type, with the name of the