2023-08-24

Latex & Python Tricks in Org

Table of Contents

1. Functions To use in file

#+NAME: function
#+begin_src python :var x=10
return 12 + x
#+end_src

2. Latex Snippets

Define a source block called flexibilityMatrix.

#+NAME: flexibilityMatrix
#+begin_src latex
\ensuremath{
    \begin{bmatrix}
      \delta_{11} & \delta_{12}  \\
      \delta_{21} & \delta_{22}
    \end{bmatrix}
}
#+end_src

3. Latex

Use noweb to expand source blocks

#+begin_src latex :noweb yes
\begin{align}
x &= <<function(20)>> \\
\delta &=
<<flexibilityMatrix>>
\end{align}
#+end_src

#+RESULTS:
#+begin_export latex
\begin{align}
x &= 32 \\
\delta &=
\ensuremath{
    \begin{bmatrix}
      \delta_{11} & \delta_{12}  \\
      \delta_{21} & \delta_{22}
    \end{bmatrix}
}
\end{align}
#+end_export
what is 1 + 20 ? src_elisp{(+ 1 20)} {{{results(=21=)}}}

what is 1 + 20 ? 21

4. Computation in Python

You can assign values to variables in Python. And also define a pyeval source block that can evaluate those variables.

#+begin_src python :session threenumbers :exports none
  a = 12
  b = 18
  c = 29
#+end_src

#+NAME: pyeval
#+begin_src elisp :var code="a" session="threenumbers" :exports none
  (org-babel-execute:python code `((:session . ,session) (:result-type . value)))
#+end_src

5. Using results assigned to variables in Latex

Now using the noweb feature, you can use that pyeval evaluator to insert the values from python into your source blocks.

#+begin_src latex :noweb yes :exports both :eval no-export
\begin{align}
  a &= <<pyeval("a")>> \\
  b &= <<pyeval("b")>> \\
  c &= <<pyeval("c")>>
\end{align}
#+end_src

#+RESULTS:
#+begin_export latex
\begin{align}
  a &= 12 \\
  b &= 18 \\
  c &= 29
\end{align}
#+end_export

Backlinks


You can send your feedback, queries here