handcalcs icon indicating copy to clipboard operation
handcalcs copied to clipboard

pint and siunitx

Open jtplaarj opened this issue 3 years ago • 4 comments

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?

jtplaarj avatar Jan 24 '22 17:01 jtplaarj

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

connorferster avatar Jan 24 '22 19:01 connorferster

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

jtplaarj avatar Jan 24 '22 19:01 jtplaarj

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 avatar May 17 '22 04:05 connorferster

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.

connorferster avatar Jul 04 '22 03:07 connorferster