Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add feature to fallback to stix font in mathtext #11644

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
(追記)
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 20 additions & 6 deletions lib/matplotlib/mathtext.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -758,7 +758,10 @@ class UnicodeFonts(TruetypeFonts):

def __init__(self, *args, **kwargs):
# This must come first so the backend's owner is set correctly
if rcParams['mathtext.fallback_to_cm']:
if rcParams['mathtext.fallback'] == 'stix':
self.cm_fallback = StixFonts(*args, **kwargs)
elif (rcParams['mathtext.fallback'] == 'cm' or
rcParams['mathtext.fallback_to_cm']):
self.cm_fallback = BakomaFonts(*args, **kwargs)
else:
self.cm_fallback = None
Expand All @@ -771,6 +774,13 @@ def __init__(self, *args, **kwargs):
prop = FontProperties('cmex10')
font = findfont(prop)
self.fontmap['ex'] = font
# include stix sized alternatives for glyphs if fallback is stix
if isinstance(self.cm_fallback, StixFonts):
stixsizedaltfonts = "STIXGeneral STIXSizeOneSym STIXSizeTwoSym "\
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would directly write this as a list stixsizedaltfonts = ["STIXGeneral", ...].
It's more readable than splitting a string. Also, you can wrap within the list and don't need the ugly line continuation char 😄. (追記ここまで)
See dict suggestion below.

"STIXSizeThreeSym STIXSizeFourSym STIXSizeFiveSym".split()
for i, stixfont in enumerate(stixsizedaltfonts):
font = findfont(stixfont)
self.fontmap[i] = font
Copy link
Member

@timhoffm timhoffm Jul 15, 2018
edited
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the numbering is essential, have you thought about turning stixsizedaltfonts into a dict, similar to what is done in DejaVuFonts?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went for splitting a string here because that is also done in line 770.

for texfont in "cal rm tt it bf sf".split():
# ...

But of course, there is no line break and the order does not matter. So, I agree that a dict is more appropriate here. I also made sure to add the STIX alternatives with their names to the fontmap

self.fontmap[name] = fullpath

Not sure whether this is really necessary, but it is also the case for the DejaVuFonts.


_slanted_symbols = set(r"\int \oint".split())

Expand Down Expand Up @@ -825,13 +835,17 @@ def _get_glyph(self, fontname, font_class, sym, fontsize, math=True):
warnings.warn(
"Substituting with a symbol from Computer Modern.",
MathTextWarning)
elif isinstance(self.cm_fallback, StixFonts):
warnings.warn("Substituting with a symbol from STIX.",
MathTextWarning)

if (fontname in ('it', 'regular') and
isinstance(self.cm_fallback, StixFonts)):
return self.cm_fallback._get_glyph(
'rm', font_class, sym, fontsize)
else:
return self.cm_fallback._get_glyph(
fontname, font_class, sym, fontsize)
fontname = 'rm'

return self.cm_fallback._get_glyph(
fontname, font_class, sym, fontsize)

else:
if (fontname in ('it', 'regular')
and isinstance(self, StixFonts)):
Expand Down
15 changes: 15 additions & 0 deletions lib/matplotlib/rcsetup.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,20 @@ def validate_font_properties(s):
return s


def validate_mathtext_fallback(s):
fallback_fonts = ['cm', 'stix']
if s is None:
return s

if isinstance(s, str):
Copy link
Member

@timhoffm timhoffm Jul 15, 2018
edited
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Valid values of s must be a string. This check can be left out and you can just if s.lower() in fallback_fonts:. If you want to provide a better error message in case the user passes some other object, it's better to explicitly

if not isinstance(s, str):
 raise ValueError("'mathtext.fallback' must be a string.")

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I changed this. Not sure, I understand this completely, since validate_fontsize has a similiar check/conversion. But maybe I am missing a subtle point here.

def validate_fontsize(s):
 fontsizes = ['xx-small', 'x-small', 'small', 'medium', 'large',
 'x-large', 'xx-large', 'smaller', 'larger']
 if isinstance(s, str):
 s = s.lower()
 if s in fontsizes:
 return s
 try:
 return float(s)
 except ValueError:
 raise ValueError("%s is not a valid font size. Valid font sizes "
 "are %s." % (s, ", ".join(fontsizes)))

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

validate_fontsizes does also accept numbers.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, I see. But I might want to go with your initial suggestion then. Currently, the following code

mpl.rcParams['mathtext.fallback'] = 1

leads to the error

AttributeError: 'int' object has no attribute 'lower'

Of course the user should only supply a string, but the error message might not be very helpful in finding a potential bug in your own code accessing mpl.rcParams['mathtext.fallback'].

I added the following

if not isinstance(s, str):
 raise ValueError("Must be a string or None.")

which yields the following error message

ValueError: Key mathtext.fallback: Must be a string or None.

I hope that's ok.

s = s.lower()

if s in fallback_fonts:
return s

raise ValueError("%s is not a valid fallback font name. Valid fallback "
"font names are %s." % (s, ", ".join(fallback_fonts)))

validate_fontset = ValidateInStrings(
'fontset',
['dejavusans', 'dejavuserif', 'cm', 'stix', 'stixsans', 'custom'])
Expand Down Expand Up @@ -1117,6 +1131,7 @@ def _validate_linestyle(ls):
'mathtext.fontset': ['dejavusans', validate_fontset],
'mathtext.default': ['it', validate_mathtext_default],
'mathtext.fallback_to_cm': [True, validate_bool],
'mathtext.fallback': [None, validate_mathtext_fallback],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs some documentation. In particular it seems fallback overrides fallback_to_cm if its set; there should be a comment in here.

Preferably, we would deprecate fallback_to_cm and make cm the default for mathtext.fallback.

This needs to be in matplotlibrc.template as well, right?

anntzer reacted with thumbs up emoji

'image.aspect': ['equal', validate_aspect], # equal, auto, a number
'image.interpolation': ['nearest', validate_string],
Expand Down

AltStyle によって変換されたページ (->オリジナル) /