我的情况是我必须为最终用户将 python 表达式转换为 Latex 位图(他们有足够的信心自己编写 python 函数,但更喜欢在 Latex 中观看结果)。
我正在使用 Matplotlib.mathtext 使用以下代码完成这项工作(来自翻译的 latex 原始字符串)。
import wx
import wx.lib.scrolledpanel as scrolled
import matplotlib as mpl
from matplotlib import cm
from matplotlib import mathtext
class LatexBitmapFactory():
""" Latex Expression to Bitmap """
mpl.rc('image', origin='upper')
parser = mathtext.MathTextParser("Bitmap")
mpl.rc('text', usetex=True)
DefaultProps = mpl.font_manager.FontProperties(family = "sans-serif",\
style = "normal",\
weight = "medium",\
size = 6)
# size is changed from 6 to 7
#-------------------------------------------------------------------------------
def SetBitmap(self, _parent, _line, dpi = 150, prop = DefaultProps):
bmp = self.mathtext_to_wxbitmap(_line, dpi, prop = prop)
w,h = bmp.GetWidth(), bmp.GetHeight()
return wx.StaticBitmap(_parent, -1, bmp, (80, 50), (w, h))
#-------------------------------------------------------------------------------
def mathtext_to_wxbitmap(self, _s, dpi = 150, prop = DefaultProps):
ftimage, depth = self.parser.parse(_s, dpi, prop)
w,h = ftimage.get_width(), ftimage.get_height()
return wx.BitmapFromBufferRGBA(w, h, ftimage.as_rgba_str())
EXP = r'$\left(\frac{A \cdot \left(vds \cdot rs + \operatorname{Vdp}\left(ri, Rn, Hr, Hd\right) \cdot rh\right) \cdot \left(rSurf + \left(1.0 - rSurf\right) \cdot ft\right) \cdot \left(1.0 - e^{- \left(\left(lr + \frac{\operatorname{Log}\left(2\right)}{tem \cdot 86400.0}\right)\right) \cdot tFr \cdot 3600.0}\right)}{rc \cdot \left(lr + \frac{\operatorname{Log}\left(2\right)}{tem \cdot 86400.0}\right) \cdot tFr \cdot 3600.0} + 1\right)$'
class aFrame(wx.Frame):
def __init__(self, title="Edition"):
wx.Frame.__init__(self, None, wx.ID_ANY, title=title, size=(600,400),
style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
self.SetBackgroundColour(wx.Colour(255,255,255))
sizer = wx.FlexGridSizer(cols=25, vgap=4, hgap=4)
panel = scrolled.ScrolledPanel(self)
image_latex = LatexBitmapFactory().SetBitmap(panel, EXP)
sizer.Add(image_latex, flag=wx.EXPAND|wx.ALL)
panel.SetSizer(sizer)
panel.SetAutoLayout(1)
panel.SetupScrolling()
app = wx.App(redirect=True, filename="latexlog.txt")
frame = aFrame()
frame.Show()
app.MainLoop()



最佳答案
TL;DR mathtext.py的下一行有一个错误Line 727 .它涉及大小 Bigg 处的右括号到索引 '\x21' ,但这是感叹号的索引。带有一点上下文的行读取
_size_alternatives = {
'(' : [('rm', '('), ('ex', '\xa1'), ('ex', '\xb3'),
('ex', '\xb5'), ('ex', '\xc3')],
')' : [('rm', ')'), ('ex', '\xa2'), ('ex', '\xb4'),
('ex', '\xb6'), ('ex', '\x21')],
mathtext.py 的本地副本。阅读如下:_size_alternatives = {
'(' : [('rm', '('), ('ex', '\xa1'), ('ex', '\xb3'),
('ex', '\xb5'), ('ex', '\x28')],
')' : [('rm', ')'), ('ex', '\xa2'), ('ex', '\xb4'),
('ex', '\xb6'), ('ex', '\x29')]
bigg 中替换尺码 - '\xb5'和 'xb6'size=6 重现这个问题使用提供的代码size = 7 重现“修复” ,但如果我去size = 8我可以或更高 - 表明这可能是一个令人讨厌的边缘案例错误,并且可能与系统有关......matplotlib唯一的例子产生了一个非常好的 import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rc('image', origin='upper')
mpl.rc('text', usetex=True)
DefaultProps = mpl.font_manager.FontProperties(family = "sans-serif",\
style = "normal",\
weight = "medium",\
size = 6)
EXP = r'$\left(\frac{A \cdot \left(vds \cdot rs + \operatorname{Vdp}\left(ri, Rn, Hr, Hd\right) \cdot rh\right) \cdot \left(rSurf + \left(1.0 - rSurf\right) \cdot ft\right) \cdot \left(1.0 - e^{- \left(\left(lr + \frac{\operatorname{Log}\left(2\right)}{tem \cdot 86400.0}\right)\right) \cdot tFr \cdot 3600.0}\right)}{rc \cdot \left(lr + \frac{\operatorname{Log}\left(2\right)}{tem \cdot 86400.0}\right) \cdot tFr \cdot 3600.0} + 10589 \right)$'
plt.title(EXP, fontsize=6)
plt.gca().set_axis_off() # Get rid of the plotting axis for clarity
plt.show()

wxPythonsize = 6 上运行良好。 ,但在 size = 3 处再次开始失败.这意味着问题在于其中一个库认为它不能以一定数量的像素呈现元素。 self.parser.to_png('D:\\math_out.png', _s, color=u'black', dpi=150)
mathtext_to_wxbitmap(self, _s, dpi = 150, prop = DefaultProps)的第一行.这给出了一个不错的输出 png ,让我觉得可能不是 matplotlib 解析器有问题... 编辑 基于 @Baptiste's useful answer ,我对此进行了更多测试。实际上 - 如果我明确传入 fontsize对于这个调用,我可以复制感叹号的外观。另外,dpi传递给这个调用被忽略 - 所以在我的测试中,我实际上处理的是 300 dpi 的图像。所以,重点应该放在MathTextParser这可能是 dpi 问题。print(result)直接拨打 parseString() 后here .使用运行良好并打印出文本表示的工作表达式。在错误的场景中,我看到:Traceback (most recent call last):
File "D:\baptiste_test.py", line 9, in <module>
parser.to_png(filename, s, fontsize=size)
File "C:\Python27\lib\site-packages\matplotlib\mathtext.py", line 3101, in to_
png
rgba, depth = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize)
File "C:\Python27\lib\site-packages\matplotlib\mathtext.py", line 3066, in to_
rgba
x, depth = self.to_mask(texstr, dpi=dpi, fontsize=fontsize)
File "C:\Python27\lib\site-packages\matplotlib\mathtext.py", line 3039, in to_
mask
ftimage, depth = self.parse(texstr, dpi=dpi, prop=prop)
File "C:\Python27\lib\site-packages\matplotlib\mathtext.py", line 3012, in par
se
box = self._parser.parse(s, font_output, fontsize, dpi)
File "C:\Python27\lib\site-packages\matplotlib\mathtext.py", line 2339, in par
se
print(result[0])
File "C:\Python27\lib\site-packages\matplotlib\mathtext.py", line 1403, in __r
epr__
' '.join([repr(x) for x in self.children]))
File "C:\Python27\lib\site-packages\matplotlib\mathtext.py", line 1403, in __r
epr__
' '.join([repr(x) for x in self.children]))
File "C:\Python27\lib\site-packages\matplotlib\mathtext.py", line 1403, in __r
epr__
' '.join([repr(x) for x in self.children]))
File "C:\Python27\lib\site-packages\matplotlib\mathtext.py", line 1403, in __r
epr__
' '.join([repr(x) for x in self.children]))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb3' in position 1:
ordinal not in range(128)
N 的情况下进行复制。 Baptiste 的最小例子中的字母。print('Getting glyph for symbol',repr(unicode(sym)))
print('Returning',cached_font, num, symbol_name, fontsize, slanted)
_size_alternatives = {
'(' : [('rm', '('), ('ex', '\xa1'), ('ex', '\xb3'),
('ex', '\xb5'), ('ex', '\xc3')],
')' : [('rm', ')'), ('ex', '\xa2'), ('ex', '\xb4'),
('ex', '\xb6'), ('ex', '\x21')], ## <---- Incorrect line.
'\x21'是错的 - 但我不知道什么是正确的 '\x29'很接近,但“太弯曲了”。我猜在 '\xc4'遵循模式,但这是一个向下的箭头。希望其中一位核心开发人员可以根据它呈现的字形轻松查找此数字(十进制 195)并进行更正。
关于python - 为什么 matplotlib 在 latex 表达式中用 "!"替换右括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32826091/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar
在我的应用程序中,我需要能够找到所有数字子字符串,然后扫描每个子字符串,找到第一个匹配范围(例如5到15之间)的子字符串,并将该实例替换为另一个字符串“X”。我的测试字符串s="1foo100bar10gee1"我的初始模式是1个或多个数字的任何字符串,例如,re=Regexp.new(/\d+/)matches=s.scan(re)给出["1","100","10","1"]如果我想用“X”替换第N个匹配项,并且只替换第N个匹配项,我该怎么做?例如,如果我想替换第三个匹配项“10”(匹配项[2]),我不能只说s[matches[2]]="X"因为它做了两次替换“1fooX0barXg