connorferster / handcalcs

Python library for converting Python calculations into rendered latex.
Apache License 2.0
5.54k stars 425 forks source link

pint and siunitx #113

Open jtplaarj opened 2 years ago

jtplaarj commented 2 years ago

I am trying to use handcals with pint and siunitx.

The main problem is that in latex_repr it checks if the object has a _repr_latex_. Pint has that attribute but it is standard LaTeX, not siunitx. For that str()or printshould be used. A minimal example:

from handcalcs.decorator import handcalc
from pint import UnitRegistry

ureg = UnitRegistry(auto_reduce_dimensions=True)
ureg.default_format = "Lx"

@handcalc()
def test_hand(a: str, b: str) -> str:
    c = a / b
    return c

r = test_hand(3.0 * ureg.meter, 5.0 * ureg.second ** 2)

print(r[0])
print(r[1])

The result is:

\begin{aligned}
c &= \frac{ a }{ b }  = \frac{ 3.0\ \mathrm{meter} }{ 5.0\ \mathrm{second}^{2} } &= 0.6\ \frac{\mathrm{meter}}{\mathrm{second}^{2}}  
\end{aligned}

\SI[]{0.6}{\meter\per\second\squared}

As you can see the result is using siunitx but the latex representation by handcalc, its not.

One solution would be to detect a pint object and use the str() method if default format is set to Lx, otherwise _repr_latex.

Is there anything I am missing to work around this question?

connorferster commented 2 years ago

For clarity, are you saying that the output of __repr_latex__() on pint objects outputs a Latex str that includes commands for siunitx?

jtplaarj commented 2 years ago

No, the repr.latex is plain latex text. Since no str or print are invoked, it will never output siunitx.

connorferster commented 2 years ago

Sorry for the delayed response. I am prioritizing working better with pint. siunitx is not utilized at all in either MathJax or Katex (although it is an asked-for feature) so this would only be useful when outputting text to a .tex file for external rendering which I consider to be a secondary use for handcalcs. The tex output from handcalcs is intended to work across all latex rendering environments and using the siunitx code would be limited to a latex environment with the siunitx package installed.

So, while I will be focusing on having better interaction with pint, I don't know if I will have a flag or trigger for outputting the siunitx tex code since it is such a special use case.

connorferster commented 2 years ago

This will now work in the upcoming version by specifying the preferred string formatter in the global config. Default setting is "L" but you can specify "Lx" if you are working with pint objects and want to use the "Lx" formatter.