ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Tue, 19 Jul 2022 20:53:44 +0200how to write an expression in latex without it being transformed by sage/sagetexhttps://ask.sagemath.org/question/63309/how-to-write-an-expression-in-latex-without-it-being-transformed-by-sagesagetex/ For my lesson that I am trying to write in latex/sagetex, I need to write formulas without them being transformed by sage.
Here's an example :
sage: f(x) = -2*x^2+x+3
....: g(x) = -2*(x-1/4)^2+25/8
....: g(x)
-1/8*(4*x - 1)^2 + 25/8
sage:
but I want to keep the form `-2*(x-1/4)^2+25/8` to write it in latex.
I tried `hold` and `with hold:` and also some code with `.mul(` or `.add(` but I have a problem with the power.
My purpose is to do random exercises around quadratic equations, and I started writing this :
from random import sample
def signe():
signe = sample([Integer(i) for i in range(-1, 2, 1) if i != 0],1)
return(signe[0])
def calcul(amax, bmax, cmax):
a = randint(1,amax)*signe()
b = randint(0,bmax)*signe()
c = randint(0,cmax)*signe()
f(x) = a*x^2+b*x+c
alpha = -b/2/a
beta = f(x=alpha)
fcanonique(x) = a*(x-alpha)^2+beta
Delta = b**2-4*a*c
output = r"Soit $f$ le trinôme défini sur $\R$ par ~${}=0$.".format(latex(f(x)))
output += r"\medbreak"
output += r"\begin{enumerate}"
output += r"\item Déterminer une forme canonique de $f$."
output += r"\item Résoudre dans $\R$ l'équation $f(x)=0$ par la méthode de votre choix."
output += r"\item $f$ est-elle factorisable ? Si oui, déterminer en une forme factorisée."
output += r"\item Résoudre dans $\R$ l'équation $f(x)={}$.".format(c)
output += r"\item Résoudre dans $\R$ l'équation $f(x)={}$.".format(beta)
output += r"\end{enumerate}"
output += r"\medbreak\uline{Réponses} :\medbreak"
output += r"\begin{enumerate}"
output +=r"\item On a $f(x)={}$".format(latex(fcanonique(x)))
if Delta < 0:
output += r"\item On reconnaît une équation du second degré de discriminant $\Delta={}<0$, et donc cette équation n'a pas de solution réelle :".format(latex(Delta))
output += "\\bigbreak{}"
output += r"Ce trinôme admet une forme canonique : "
elif Delta == 0:
output += r"\item On reconnaît une équation du second degré de discriminant $\Delta={}$, et donc cette équation admet une unique solution $x_0={}$".format(latex(Delta), latex(alpha))
else:
x1 = simplify((-b-Delta^(1/2))/(2*a))
x2 = simplify((-b+Delta^(1/2))/(2*a))
ffactorisee(x) = a*(x-x1)*(x-x2)
output += r"\item On reconnaît une équation du second degré de discriminant $\Delta={}>0$, et donc cette équation admet deux solutions réelles $x_1$ et $x_2$ avec : \quad $\displaystyle x_1={}$ \quad et \quad $\displaystyle x_2={}$.".format(latex(Delta), latex(x1), latex(x2))
output += "\\bigbreak{}"
output += r"\end{enumerate}"
return(output)
and for example, `calcul(5, 5, 5)` return :
"Soit $f$ le trinôme défini sur $\\R$ par ~$-x^{2} + 4 \\, x - 2=0$.\\medbreak\\begin{enumerate}\\item Déterminer une forme canonique de $f$.\\item Résoudre dans $\\R$ l'équation $f(x)=0$ par la méthode de votre choix.\\item $f$ est-elle factorisable ? Si oui, déterminer en une forme factorisée.\\item Résoudre dans $\\R$ l'équation $f(x)=-2$.\\item Résoudre dans $\\R$ l'équation $f(x)=2$.\\end{enumerate}\\medbreak\\uline{Réponses} :\\medbreak\\begin{enumerate}\\item On a $f(x)=-x + 4$\\item On reconnaît une équation du second degré de discriminant $\\Delta=8>0$, et donc cette équation admet deux solutions réelles $x_1$ et $x_2$ avec : \\quad $\\displaystyle x_1=\\sqrt{2} + 2$ \\quad et \\quad $\\displaystyle x_2=-\\sqrt{2} + 2$.\\bigbreak{}\\end{enumerate}"
Before `if Delta < 0:` I would like `output +=r"\item On a $f(x)={}$".format(latex(fcanonique(x)))` to display the formula without transformation.
Thanks.ryssTue, 19 Jul 2022 20:53:44 +0200https://ask.sagemath.org/question/63309/Displaying and typesetting partitionshttps://ask.sagemath.org/question/62961/displaying-and-typesetting-partitions/ A partition can be viewed as a list or pretty-printed using ascii art. This works fine for me.
A partition can also be LaTeX-ed:
latex(Partition([2,2]))
produces
{\def\lr#1{\multicolumn{1}{|@{\hspace{.6ex}}c@{\hspace{.6ex}}|}{\raisebox{-.3ex}{$#1$}}}
\raisebox{-.6ex}{$\begin{array}[b]{*{2}c}\cline{1-2}
\lr{\phantom{x}}&\lr{\phantom{x}}\\\cline{1-2}
\lr{\phantom{x}}&\lr{\phantom{x}}\\\cline{1-2}
\end{array}$}
}
which typesets fine when inserted into a LaTeX document.
However:
1. When sagetex uses this, and produce the exakt same LaTex snippet, there are TeX errors (which does not stop the document from being typeset, but which are annoying):
(./part.sagetex.sout
./part.sagetex.sout:9: Illegal parameter number in definition of \r@@sageinline0.
2. The LaTex form of the partition does not render well with MathJax, so it is not displayed properly in a Jupyter notebook. I belive that the \cline is the culprit.
I hacked the LaTex output and got something which works well with sagetex, but since it uses the external package ytableu.sty, it does not work with MathJax.
if Partitions.options.convention == "English":
Partitions.options(latex=lambda mu: '\\ydiagram{%s}' % ','.join('%s'%m for m in mu._list))
Here is a kludge for skewpartitions:
def LatexSkew(S):
L = S._list[0]._list
M = S._list[1]._list
ut = '\\ydiagram{'
ut += ','.join([str(b) + '+' + str(a-b) for a,b in zip(L,M)] )
if len(L) > len(M):
ut += ',' + ','.join([str(a) for a in L[len(M):]] )
ut += '}'
return ut
if Partitions.options.convention == "English":
SkewPartitions.options(latex=LatexSkew)
So, at long last the question: how do you professionals typeset and display partitions?
JTSWed, 22 Jun 2022 20:25:29 +0200https://ask.sagemath.org/question/62961/How to break long line of code in sageblock environment (SageTeX)https://ask.sagemath.org/question/59202/how-to-break-long-line-of-code-in-sageblock-environment-sagetex/ So I have long codes written in `sageblock` which I would like to know if it's possible to implement line wraps? It seems the [the docs](http://mirrors.ibiblio.org/CTAN/macros/latex/contrib/sagetex/sagetex.pdf#section.6) suggests SageTeX is using `listings` which I thought according to [this TeX SE answer](https://tex.stackexchange.com/questions/116534/lstlisting-line-wrapping) I could set `breaklines=true` but still it doesn't work.
Do anyone know how to solve it?andrewygThu, 30 Sep 2021 14:26:10 +0200https://ask.sagemath.org/question/59202/How do you assign (different) LaTex names to elements of a list?https://ask.sagemath.org/question/57589/how-do-you-assign-different-latex-names-to-elements-of-a-list/Say I have the following list of variables.
v = {(i,j): var("v_{}{}".format(i, j), latex_name="v_{{}{}}") for i in range(2) for j in range(2)}
How do I make it so that when I use the
show(v[0,0])
command, I get $v_{0,0}$ as output? I've tried stuff like
v = {(i,j): var("v_{}{}".format(i, j), latex_name="v_{i,j}") for i in range(2) for j in range(2)}
and
v = {(i,j): var("v_{}{}".format(i, j), latex_name="v_{{i}{j}}") for i in range(2) for j in range(2)}
but it only ever give me stuff like $v_{i,j}$ where it's just the literal symbols $i$ and $j$, not the entries of
v[k,m]
for some $k$ and $m$ I plug in, like 0, 0.
sum8tionWed, 16 Jun 2021 21:52:17 +0200https://ask.sagemath.org/question/57589/Can attributes of sage classes be changed?https://ask.sagemath.org/question/53892/can-attributes-of-sage-classes-be-changed/ I want to change the way vectors are rendered in sagetex. For example, consider `v = vector([1, 2, 3])`. In sagetex, the command `$v=\sage{v}$` renders as
$$
v=(1, 2, 3)
$$
Instead, I want my vectors to take the form
$$
v=\left[\begin{array}{rrr}1&2&3\end{array}\right]^\intercal
$$
I thought I could do this by resetting the `_latex_` method of the `sage.modules.free_module_element.FreeModuleElement` class as follows.
def my_vector_latex(self):
return matrix(v)._latex_() + r'^\intercal'
setattr(sage.modules.free_module_element.FreeModuleElement, '_latex_', my_vector_latex)
However, this code throws the following error:
TypeError: can't set attributes of built-in/extension type 'sage.modules.free_module_element.FreeModuleElement'
So, it looks like I can't modify the methods of `FreeModuleElement` in this way. Is there anything else I could do?more_weightTue, 13 Oct 2020 19:37:51 +0200https://ask.sagemath.org/question/53892/Problems with SageTex on MacOShttps://ask.sagemath.org/question/52612/problems-with-sagetex-on-macos/I have follow the instructions according with the sage tutorial guide for install SageTex and for "LaTex to know Sage", to being able to use SageTex on MacOS, but although it's recognize the sage.sty file when I compile a document on each part of sage it displays "??", I have no more ideas what to do, I have use a lot of differents versions of Sage but no one works.emaspWed, 22 Jul 2020 09:01:02 +0200https://ask.sagemath.org/question/52612/SageTeX-Output: Possible simplification soughthttps://ask.sagemath.org/question/49374/sagetex-output-possible-simplification-sought/I created a minimal example for SageTeX:
x = 420 # Denominator
MyRange = 222
M = []
for n in range (1,MyRange):
if x == denominator(n/x):
M.append('$' + latex(n/x).replace(' ','') + '$')
else:
M.append('$' + '\\frac{' + "{}".format(n) + '}{' + "{}".format(x) + '}=' + latex(n/x).replace(' ','') + '$')
MyOut = ', '.join(M)
print(MyOut)
This gives:
![image description](https://matheplanet.de/matheplanet/nuke/html/uploads/b/50970_7_56555555.png)
It works! Just for interest, I wonder: does the 2nd else-output <br>
`M.append('$' + '\\frac{' + "{}".format(n) + '}{' + "{}".format(x) + '}=' + latex(n/x).replace(' ','') + '$')` <br>
really have to be so complicated or is there an easier way?
€dit: My SageTeX-MWE is:
\documentclass{article}
\usepackage{amsmath, amssymb, amsfonts}
\usepackage{sagetex}
\begin{document}
\section{In}
\begin{sageblock}
x = 420 # Denominator
MyRange = 222
M = []
for n in range (1,MyRange):
if x == denominator(n/x):
M.append('$' + latex(n/x).replace(' ','') + '$')
else:
M.append('$' + '\\frac{' + "{}".format(n) + '}{' + "{}".format(x) + '}=' + latex(n/x).replace(' ','') + '$')
MyOut = ', '.join(M)
#print MyOut
\end{sageblock}
\section{Out}
\baselineskip16pt \sagestr{MyOut}
\end{document}geroyxSun, 05 Jan 2020 16:32:29 +0100https://ask.sagemath.org/question/49374/Sagetex : how to capture sageblock output for future use.https://ask.sagemath.org/question/36422/sagetex-how-to-capture-sageblock-output-for-future-use/[ This is more, I think, a \LaTeX question than a Sagemath question. But since it's centered on the use of Sagetex, it is probably the right place to ask... ]
I'd like to be able to do some (boring but necessary) computation without printing it, use its results, *then*, in an appendix, show the computation (without re-running it).
The obvious solution would be to run the computation in a `sagesilent` block, use its results, then later insert a `sageverbatim` environment with the same code :
\begin{sagesilent}
## Boring computation
\end{sagesilent}
%% Lotsa discussion
\appendix
\begin{sageverbatim}
## Boring computation again
\end{sageverbatim}
The problem is that now, I have two copies of the same code, with no consistency guarantee (as illustrated in the example, BTW).
I tried :
\let\foo={\begin{sageblock}
## boring computation
\end{sageblock}}
% Lotsadiscussion
\appendix
\foo
But that doesn't work : The boring computation is still printed before the discussion and nothing is printed in the appendix.
I'm not really surprised : the \LaTeX `verbatim` environments are full of such traps. And, no, using `\protect` is not enough.
Any idea ?Emmanuel CharpentierWed, 01 Feb 2017 16:41:51 +0100https://ask.sagemath.org/question/36422/LatexMk and sagetex not workinghttps://ask.sagemath.org/question/39455/latexmk-and-sagetex-not-working/ According to the Sagetex github page (https://github.com/sagemath/sagetex/wiki) the following snippet code put into a .latexmkrc dotfile should make latexmk run sagetex.sage files if necessary:
add_cus_dep('sagetex.sage', 'sagetex.sout', 0, 'makesout');
$hash_calc_ignore_pattern{'sage'} = '^( _st_.goboom| ?_st_.current_tex_line|print .SageT)';
sub makesout {
system("sage '$_[0].sagetex.sage'");
}
But nothing seems to happen, when I run latexmk on the tex file, it gives no errors and does not run the sagetex.sage file, but compiles the pdf nontheless. If I run latexmk and sage manually I have no problems compiling the document with the sage math. Is the code outdated/can it be fixed to work properly?PoetastropheWed, 08 Nov 2017 20:48:45 +0100https://ask.sagemath.org/question/39455/Does sagetex require math environment around \sage{}?https://ask.sagemath.org/question/34713/does-sagetex-require-math-environment-around-sage/I have problems in typesetting the sagetex example file example.tex with the sage engine in TeXShop 3.71. Namely, the output of the command \sage{pascals_triangle(n)} near the end is a string containing LaTeX code, which should then be processed as LaTeX input by LaTeX. However, the typesetter complains that the $$ around the sage output are missing. Putting them results in the string be reproduced verbatim in the output, which is not the expected behavior. I checked that at least in my current version of sagetex.sty ALL output of \sage{} is expected to be placed in a math environment, otherwise a LaTeX error is raised. In the documentation, it is mentioned that it is useful, but not generally required, to put \sage{} commands in a math environment. I remember that the file was smoothly typeset a year or two ago. Has anything changed in the meantime?qwfwqSun, 04 Sep 2016 13:53:11 +0200https://ask.sagemath.org/question/34713/Converting sage output into static latex functionhttps://ask.sagemath.org/question/31414/converting-sage-output-into-static-latex-function/Hello!
I want to be able to use sagetex to do some work in sage, and then create a latex function with the result of that sage work, but without calling sage every time the function is called.
Here is an example of the current pseudo-code
\begin{sagesilent}
func1 = x - 3
func2 = x + 1
f = expand(func1*func2)
\end{sagesilent}
\newcommand{\foo}{\sage{f}}
Here, what would normally happen is sage silent runs sage, and creates the correct f = x^2 - 2x - 3. Then every time \foo is called, it reruns an instance of sage to go locate the definition of f in the sage file, and then sage will spit out the definition in text to \foo which then will display f. This is taking a lot of compute time unnecessarily, and when things get randomized it all goes to hell.
Is there any way to force a command to take in the (sage) definition when it's defined, and then save that definition as straight up text so that I don't have to rerun sage to go find the definition of f every time I want to call \foo?
Edit: It seems this could be accomplished if there is a way to define a latex command inside the sagesilent environment? From reading the sage doc it seems that this should be possible (there are examples doing it from a sage prompt) but I can't seem to figure out the correct syntax. Suggestions?Jason021Tue, 08 Dec 2015 17:05:53 +0100https://ask.sagemath.org/question/31414/Sagetex on Windows: Using miktex and sage on virtualbox. How to make it work?https://ask.sagemath.org/question/27264/sagetex-on-windows-using-miktex-and-sage-on-virtualbox-how-to-make-it-work/ Hello!
I've installed sagetex (2009-06-26) using the miktex package manager. I use Sage 6.7 on Oracle's Virtual Box, as recommended for windows users.
For me, the following code:
> \documentclass{article}
> \usepackage{sagetex}
>
> \begin{document}
>
> For example, there are
> $\sage{number_of_partitions(1269)}$
> integer partitions of $1269$.
>
> \end{document}
Gives this output:
> For example, there are ?? integer partitions of 1269.
All the sage commands just give "??" in the latex document. I've been looking at the documentation, but it doesn't seem to be for windows.
- Is sagetex supposed to work out of the box, just installing it on miktex and having sage installed on virtualbox?
- If not, is there an official procedure to make it work? e.g. documentation about sagetex on windows?
Thanks! eodMon, 06 Jul 2015 16:41:20 +0200https://ask.sagemath.org/question/27264/How to join function to grid scale?https://ask.sagemath.org/question/25639/how-to-join-function-to-grid-scale/ Dear friends, I'm trying to use latex+sagetex+tikz and it's really powerfull combination. But I don't understand how to join axes grid to function. If you see attached example you see first original plotting then another two with different axes grids. But function plot in 2,3 graphs the same as in first function plot! It should to stretch/collapse in accord with scale x/y axes. How to do it right way?
Update: I don't know why I can't to add .tex file so you can get this example from http://www.highschoolmathandchess.com/latex/plotting-with-sagetex/ (section "Sagetex and the tkz-fct package"). Changing axes doesn't affect to function plot. y023rusThu, 29 Jan 2015 20:48:04 +0100https://ask.sagemath.org/question/25639/tex distribution doesn't see sagetexhttps://ask.sagemath.org/question/10716/tex-distribution-doesnt-see-sagetex/Hi all,
So I've spent some time installing sage 5.12 on my machine (Ubuntu 12.04.3) and been trying to edit a latex document using sagetex that worked fine on another computer. I've found that despite copying
> SAGE_ROOT/sage/local/share/texmf/tex/
to
> /usr/local/share/texmf/
and running
> sudo texhash
I get a compile error. To be clear, I have a single sagesilent block and a single sagestr{} block, and the document compiles on my other machine. I have found that simply copying 'sagetex.sty' into the document directory will work, but this is not the permanent solution I was hoping for. I'm really confused because both my machines are running the same linux OS, so there should really be no difference between them. Any thoughts?
ThanksunderchemistSat, 09 Nov 2013 09:36:58 +0100https://ask.sagemath.org/question/10716/LaTeX, sagetex, Sagehttps://ask.sagemath.org/question/10649/latex-sagetex-sage/Hi there,
I'm new to Sage and new to the forum. I'm using MiKTex 29, the editor is Texmaker on a Win7 PC, Sage as 5.11 in VirtualBox. The .latexmkrc has been changed as advised here:
[Changing .latexmkrc when using Texmaker](https://bitbucket.org/ddrake/sagetex/wiki/UsingSageTeX)
The sagetex which is used by Sage and pdflatex are of the same version. Everything should do just fine, except it doesn't.
Using the example.tex given in the sagetex directory, I compile it with TeX and get example.sagetex.sage. Everything fine there.
Running it in Sage works quite well, too. Sage says, it's plotting and doing and so on. Then it comes to a point, where Sage says:
"[Errno 2] No sich file or directory: 'example.sagetex.sage'".
And the process breaks.
Here my question: Sage processes the example.sagetex.sage file in the given directory. Then it says "file not found / file not there". Both of the prompts seem to exclude eachother fairly well. But I get them anyway.
What am I doing wrong?
Regards.
H.HoedWed, 23 Oct 2013 06:11:58 +0200https://ask.sagemath.org/question/10649/implementing sagetex in latexhttps://ask.sagemath.org/question/8098/implementing-sagetex-in-latex/For calling SAGE from within LATEX-file there must be following
entry in line 1:
% !TEX TS-program = sage // (this creates undersome conditions I dont know a syntax error)
...
and
\usepackage{sagetex}
But I get in one tex-file a syntax error in Line 1.
Does anyone know a work around or how it really works?
Many thanks in advance for your hints.
GeraldpechocSun, 01 May 2011 13:22:00 +0200https://ask.sagemath.org/question/8098/SageTeX doesn't workhttps://ask.sagemath.org/question/9669/sagetex-doesnt-work/I'm using AUCTeX as my TeX editor. I created a TeX file loaded with SageTeX. When I run LaTeX on it I get the message that there are unresolved references. The output has question marks on the places I have put \sage. However, it seems to understand without any trouble the sageblock environment.
When I load the corresponding .sage file on Sage, I get at the following message:
VersionError: versions of .sty and .py files do not match.
stexample.sagetex.sage was generated by sagetex.sty version "None", but
is being processed by sagetex.py version "2012/01/16 v2.3.3-69dcb0eb93de".
Please make sure that TeX is using the sagetex.sty
from your current version of Sage; see
http://www.sagemath.org/doc/installation/sagetex.html.
I thought I had followed the instructions on the "Make SageTeX Known to TeX" section of the Sage installation guide but it's not working.
jdiosesMon, 31 Dec 2012 19:42:41 +0100https://ask.sagemath.org/question/9669/Sagetex from the notebook - feedback on how I automate thingshttps://ask.sagemath.org/question/8928/sagetex-from-the-notebook-feedback-on-how-i-automate-things/This isn't really a question, so please accept my apologies if non-questions are unwelcome here.
I am using sage with latex, but I am the kind of person who doesn't like leaving the notebook, so I tried to automate the process. You can see my code below. Any comments and suggestions are appreciated.
Also, if you think you will find this or a similar setup useful, please say so, because people who like staying within the notebook are probably underrepresented among the developers.
def load_cache(f): # so that we don't recompute for every latex change
try:f.cache=load(DATA+"/cache/"+f.f.func_name)
except IOError:pass
def export_code (list_of_functions, folder): # copy code to our latex folder
for func in list_of_functions:
try:
save(func.cache,DATA+"/cache/"+func.f.func_name)
func=func.f
except AttributeError:pass # in case the function isn't cached
sh.eval("cp " + func.func_code.co_filename + " " + folder + "/" + func.func_name + ".py")
def runsagelatex(latexfile):
def evalindir(cmd,path): # otherwise the output appears in the current directory
sh.eval("( cd "+os.path.dirname(path)+" ; "+cmd+" )")
evalindir("pdflatex --file-line-error "+latexfile,latexfile)
evalindir("sage "+os.path.splitext(latexfile)[0]+".sagetex.sage",latexfile)
evalindir("pdflatex --file-line-error "+latexfile,latexfile)
def sagelatex(name="project",export=[],cmd=""):
html(r'<div class="notruncate">') # for the output of pdflatex
try:os.mkdir(DATA+"/cache/")
except OSError:pass
try:os.mkdir(DATA+"/sagelatex/")
except OSError:pass
try:os.mkdir(DATA+"/sagelatex/sagenb-export/")
except OSError:pass
export_code(export,DATA+"/sagelatex/sagenb-export/")
f=open(DATA+"/sagelatex/"+name+".tex","wb")
f.write(cmd)
f.close()
runsagelatex(DATA+"/sagelatex/"+name+".tex")
html(r'</div>')
Example usage:
def f1(a,b):
return a+b
@cached_function
def f2(a):
return a^2
load_cache(f2)
And in a new cell (and change DATA below):
sagelatex(name="myproject",export=[f1,f2,load_cache],cmd=\
r"""
\documentclass{article}
\usepackage{sagetex}
\begin{document}
\begin{sagesilent}
DATA="/.../.sage/sage_notebook.sagenb/home/user/123/data/" # make it match the worksheet's DATA constant
execfile("sagenb-export/load_cache.py")
execfile("sagenb-export/f1.py")
execfile("sagenb-export/f2.py")
\end{sagesilent}
$\sage{f1(1,2)+f2(10)}$
\end{document}
""")
This should produce a pdf file in your DATA/sagelatex folder. That folder is accessible through your web browser.Tom DorrisWed, 25 Apr 2012 16:20:52 +0200https://ask.sagemath.org/question/8928/How do I change the default latex output of a vector?https://ask.sagemath.org/question/8107/how-do-i-change-the-default-latex-output-of-a-vector/I want a vector v=vector([1,2,3]) to be diplayed in sagetex as (1|2|3) an not as (1,2,3).
v=var('v',latex_name=latex(v).replace(',', '|')) does not work.Georg DammSun, 08 May 2011 09:21:01 +0200https://ask.sagemath.org/question/8107/