\frac{}{} won't work for me w/ pylab - python

I'm rather new at using python and especially numpy, and matplotlib. Running the code below (which works fine without the \frac{}{} part) yields the error:
Normalized Distance in Chamber ($
rac{x}{L}$)
^
Expected end of text (at char 32), (line:1, col:33)
The math mode seems to work fine for everything else I've tried (symbols mostly, e.g. $\mu$ works fine and displays µ) so I'm not sure what is happening here. I've looked up other peoples code for examples and they just seem to use \frac{}{} with nothing special and it works fine. I don't know what I'm doing differently. Here is the code. Thanks for the help!
import numpy as np
import math
import matplotlib.pylab as plt
[ ... bunch of calculations ... ]
plt.plot(xspace[:]/L,vals[:,60])
plt.axis([0,1,0,1])
plt.xlabel('Normalized Distance in Chamber ($\frac{x}{L}$)')
plt.savefig('test.eps')
Also, I did look up \f and it seems its an "escape character", but I don't know what that means or why it would be active within TeX mode.

In many languages, backslash-letter is a way to enter otherwise hard-to-type characters. In this case it's a "form feed". Examples:
\n — newline
\r — carriage return
\t — tab character
\b — backspace
To disable that, you either need to escape the backslash itself (backslash-backslash is a backslash)
'Normalized Distance in Chamber ($\\frac{x}{L}$)'
Or use "raw" strings where escape sequences are disabled:
r'Normalized Distance in Chamber ($\frac{x}{L}$)'
This is relevant to Python, not TeX.
Documentation on Python string literals

"\f" is a form-feed character in Python. TeX never sees the backslash because Python interprets the \f in your Python source, before the string is sent to TeX. You can either double the backslash, or make your string a raw string by using r'Normalized Distance ... etc.'.

You have to add an r front of the string to avoid parsing the \f.

Related

Why do I get different outputs with \r escape sequence in different IDLE?

When is used the \r in sublime, it behaved as a \n escape sequence.
carriage_return = "I will use a carriage\rreturn"
print (carriage_return)
I will use a carriage
return
But when I used it in the python 3.7.2 IDLE, the output was:
I will use a carriagereturn
Why is there's a different output?
How do you use the \r escape sequence?
A "carriage return" traditionally moved the cursor back to the beginning of the line so you should have seen the output as:
return use a carriage
because the i will would have been overwritten.
However, this tradition has now changed as standards have developed and there is no more uniform handling of a "carriage return". For example, HTML treats a \r as a whitespace.
Since I am new to stackoverflow please tell me how to improve my answer.

I know of f-strings, but what are r-strings? Are there others?

I started learning python for the first time in an accelerated course on data science a few weeks ago and we were introduced early on to f-strings.
The simple code:
name = 'Tim'
print(f'There are some who call me {name}...')
outputs the string "There are some who call me Tim..."
Through my browsing of various packages out of curiosity, I came upon pages like this one detailing a function you can call in matplotlib to render $\LaTeX$-like expressions within the generated images. In the example code they use something similar to f-strings but with an r instead of an f.
import matplotlib.pyplot as plt
plt.title(r'$\alpha > \beta$')
plt.show()
The resulting (otherwise empty) graph has a title using text which has been formatted similarly to how one would expect using MathJax or $\LaTeX$ with a greek character alpha and a greek character beta.
My questions are the following:
What precisely is an r-string and how does it compare to an f-string? Are r-strings specifically used for matplotlib's mathtext and usetex?
Apart from f-strings and r-strings, are there any other notable similar string variants or alternates that I should familiarize myself with or be made aware of?
An r-string is a raw string.
It ignores escape characters. For example, "\n" is a string containing a newline character, and r"\n" is a string containing a backslash and the letter n.
If you wanted to compare it to an f-string, you could think of f-strings as being "batteries-included." They have tons of flexibility in the ability to escape characters and execute nearly arbitrary expressions. The r-string on the other hand is stripped down and minimalist, containing precisely the characters between its quotation marks.
As far as actually using the things, typically you would use an r-string if you're passing the string into something else that uses a bunch of weird characters or does its own escaping so that you don't have to think too hard about how many backslashes you really need to get everything to work correctly. In your example, they at least needed r-strings to get the \a bit working correctly without double escapes. Note that '$\\alpha > \\beta$' is identical to r'$\alpha > \beta$'.
Since you're using f-strings, I'll assume you have at least Python 3.6. Not all of these options are supported for older versions but any of the following prefixes are valid in Python 3.6+ in any combination of caps and lowers: r, u, f, rf, fr, b, rb, br
The b-strings are binary literals. In Python 2 they do nothing and only exist so that the source code is compatible with Python 3. In Python 3, they allow you to create a bytes object. Strings can be thought of as a view of the underlying bytes, often restricted as to which combinations are allowed. The distinction in types helps to prevent errors from blindly applying text techniques to raw data. In Python 3, note that 'A'==b'A' is False. These are not the same thing.
The u-strings are unicode literals. Strings are unicode by default in Python 3, but the u prefix is allowed for backward compatibility with Python 2. In Python 2, strings are ASCII by default, and the u prefix allows you to include non-ASCII characters in your strings. For example, note the accented character in the French phrase u"Fichier non trouvé".
In the kind of code I write, I rarely need anything beyond r, u, f, and b. Even b is a bit out there. Other people deal with those prefixes every day (presumably). They aren't necessarily anything you need to familiarize yourself with, but knowing they exist and being able to find their documentation is probably a good skill to have.
Just so that it's in an answer instead of buried in a comment, Peter Gibson linked the language specification, and that's the same place I pulled the prefix list from. With your math background, a formal language specification might be especially interesting — depending a little on how much you like algebra and mathematical logic.
Even if it's just for a semantically trivial language like Forth, I think many programmers would enjoy writing a short interpreter and gain valuable insight into how their language of choice works.

LaTeX not working on matplotlib text

I've been having this trouble for a long time whenever I want to render LaTeX for plot labelling and text, it works sometimes for some symbols but not others. For example in my script shown here generates the plot below:
from matplotlib import rc
plt.rc('text', usetex=True)
plt.plot(a_t,asol[:,0],label ='$\psi$')
plt.plot(a_t,rho,label ="$\rho/\rho_c$")
plt.xlabel(r"$\xi$",fontsize=15)
from matplotlib.legend_handler import HandlerLine2D
plt.legend(loc='upper left',prop={'size':12},numpoints=1)
I've tried other symbols, $\pi$ works okay but $\theta$ only shows "heta" without the t. I'm confused by why some symbols works for LaTeX and some don't.
Thanks!
Remember that certain characters in Python strings have special meanings, e.g. \r for carriage return, \t for tab. That's why you're only getting the strange results some of the time, since \p doesn't have a special meaning. So either make sure your backslashes are treated as literal backslashes by escaping them:
plt.plot(a_t,rho,label = "$\\rho/\\rho_c$")
Or use raw strings:
plt.plot(a_t,rho,label = r"$\rho/\rho_c$")

How to do a fancy print in ipython using sympy.pprint()

I'm trying to pprint() in Sympy a variable that I call barphi. What I want to get is
$\bar{\phi}$
when printed as pprint(barphi).
I try
barphy = Symbol('\bar{phi}')
but it does not work. Any help? Thanks in advance.
This was answered on the SymPy mailing list.
There are two issues with what you wrote
First, Python converts \ + character in strings as escaping. The \b in your string becomes a backspace (see https://en.wikipedia.org/wiki/ASCII#ASCII_control_code_chart).
You need to either escape the \, i.e., use '\\bar{\\phi}$', or, much easier, if you don't care about escaping, use a raw string, which just means to put an r in front of the quotes, like r'\bar{\phi}'.
Second, if you want to get LaTeX, pprint() will not do it (pprint pretty prints to 2D text). You should use init_printing() to enable LaTeX printing in the notebook.
Finally, as pointed out by Julien Rioux on the mailing list, you can just name the symbol phibar, and SymPy will automatically render it as \bar{\phi}, as you can see here even in Unicode
In [11]: Symbol('phibar')
Out[11]: φ̅
If you still want to get the latex code rather than printing it, you can do so by:
In [2]: from sympy.printing.latex import latex, translate
In [3]: latex(translate('phibar'),mode='inline')
Out[3]: '$\\bar{\\phi}$'
you can see the documentation for latex function here
The documentation for translate function are
Check for a modifier ending the string. If present, convert the
modifier to latex and translate the rest recursively.
Given a description of a Greek letter or other special character,
return the appropriate latex.
Let everything else pass as given.
>>> from sympy.printing.latex import translate
>>> translate('alphahatdotprime')
"{\\dot{\\hat{\\alpha}}}'"

Python’s `str.format()`, fill characters, and ANSI colors

In Python 2, I’m using str.format() to align a bunch of columns of text I’m printing to a terminal. Basically, it’s a table, but I’m not printing any borders or anything—it’s simply rows of text, aligned into columns.
With no color-fiddling, everything prints as expected.
If I wrap an entire row (i.e., one print statement) with ANSI color codes, everything prints as expected.
However: If I try to make each column a different color within a row, the alignment is thrown off. Technically, the alignment is preserved; it’s the fill characters (spaces) that aren’t printing as desired; in fact, the fill characters seem to be completely removed.
I’ve verified the same issue with both colorama and xtermcolor. The results were the same. Therefore, I’m certain the issue has to do with str.format() not playing well with ANSI escape sequences in the middle of a string.
But I don’t know what to do about it! :( I would really like to know if there’s any kind of workaround for this problem.
Color and alignment are powerful tools for improving readability, and readability is an important part of software usability. It would mean a lot to me if this could be accomplished without manually aligning each column of text.
Little help? ☺
This is a very late answer, left as bread crumbs for anyone who finds this page while struggling to format text with built-in ANSI color codes.
byoungb's comment about making padding decisions on the length of pre-colorized text is exactly right. But if you already have colored text, here's a work-around:
See my ansiwrap module on PyPI. Its primary purpose is providing textwrap for ANSI-colored text, but it also exports ansilen() which tells you "how long would this string be if it didn't contain ANSI control codes?" It's quite useful in making formatting, column-width, and wrapping decisions on pre-colored text. Add width - ansilen(s) spaces to the end or beginning of s to left (or respectively, right) justify s in a column of your desired width. E.g.:
def ansi_ljust(s, width):
needed = width - ansilen(s)
if needed > 0:
return s + ' ' * needed
else:
return s
Also, if you need to split, truncate, or combine colored text at some point, you will find that ANSI's stateful nature makes that a chore. You may find ansi_terminate_lines() helpful; it "patch up" a list of sub-strings so that each has independent, self-standing ANSI codes with equivalent effect as the original string.
The latest versions of ansicolors also contain an equivalent implementation of ansilen().
Python doesn't distinguish between 'normal' characters and ANSI colour codes, which are also characters that the terminal interprets.
In other words, printing '\x1b[92m' to a terminal may change the terminal text colour, Python doesn't see that as anything but a set of 5 characters. If you use print repr(line) instead, python will print the string literal form instead, including using escape codes for non-ASCII printable characters (so the ESC ASCII code, 27, is displayed as \x1b) to see how many have been added.
You'll need to adjust your column alignments manually to allow for those extra characters.
Without your actual code, that's hard for us to help you with though.
Also late to the party. Had this same issue dealing with color and alignment. Here is a function I wrote which adds padding to a string that has characters that are 'invisible' by default, such as escape sequences.
def ljustcolor(text: str, padding: int, char=" ") -> str:
import re
pattern = r'(?:\x1B[#-_]|[\x80-\x9F])[0-?]*[ -/]*[#-~]'
matches = re.findall(pattern, text)
offset = sum(len(match) for match in matches)
return text.ljust(padding + offset,char[0])
The pattern matches all ansi escape sequences, including color codes. We then get the total length of all matches which will serve as our offset when we add it to the padding value in ljust.

Categories