Package: handcalcs
Covert art byJoshua Hoiberghandcalcs:Python calculations in Jupyter,as though you wrote them by hand.handcalcsis a library to render Python calculation code automatically in Latex, but in a manner that mimics how one might format their calculation if it were written with a pencil:  write the symbolic formula,followed by numeric substitutions, and then the result.Becausehandcalcsshows the numeric substitution, the calculations become significantly easier to check and verify by hand.ContentsBasic DemoInstallationBasic UsageEnhanced UsageFeaturesPDF Printing in JupyterExpected BehavioursGotchas and DisclaimerYouTube TutorialsApplications and Compatibility with Other Libraries (wiki)Basic DemoInstallingYou can install using pip:pip install handcalcsBasic Usage 1: As a Jupyter cell magic (%%render)handcalcsis intended to be used with either Jupyter Notebook or Jupyter Lab as acell magic.First, import the module and run the cell:importhandcalcs.renderNote: This will import both%%texand%%rendermagics in the Jupyter Notebook.Then, in any cell that you want to render withhandcalcs, just use the render cell magic at the top of your cell:%%renderFor example:%%rendera=2b=3c=2*a+b/3That is it!Once rendered, you can then export your notebook as a PDF, provided you have a Latex environment installed on your system. If you are new to working with Latex and would like to install it on your system so you can use this functionality, please see the sectionInstalling Tex, in the wiki.You can also use the%%texcommand to convert any Python code snippet into a valid LaTex. For Example:First importhandcalcs. We are also importing a few properties/functions frommathpackage for the
example below.importhandcalcs.renderfrommathimportsqrt,piNow, you can use the%%texmagic!%%texa=2/3*sqrt(pi)This will produce a LaTeX output as follows.\[\begin{aligned}a &=\frac{2}{3}\cdot\sqrt{\pi}=\frac{2}{3}\cdot\sqrt{3.142} &=1.182\end{aligned}\]Basic Usage 2: As a decorator on your functions,@handcalc()Shout-out to @eriknw for developinginnerscopeand proactively integrating it intohandcalcs. Thank you!Start by importing the@handcalc()decorator:fromhandcalcs.decoratorimporthandcalc@handcalc([override:str="",precision:int=3,left:str="",right:str="",jupyter_display:bool=False])Returns a tuple consisting of(latex_code: str, locals: dict), wherelocalsis a dictionary of all variables in the scope of the function namespace.overrideis a str representing one of the acceptable override tags (see below)precisionis an int to alter the of decimal precision displayedleftandrightare strings that can precede and follow the encoded Latex string, such as\\[and\\]or$and$jupyter_display, when True, will return only thelocalsdictionary and instead will display the encoded Latex string rendering withdisplay(Latex(latex_code))fromIPython.display. Will return an error if not used withinIn your decorated function, everything betweendef my_calc(...)and a return statement (if any) is now like the code in a Jupyter cell, except it's a standard Python function.Used in this way, you can use@handcalc()to dynamically generate Latex code for display in Jupyter and non-Jupypter Python environments (e.g. streamlit).Override tagshandcalcsmakes certain assumptions about how you would like your calculation formatted and does not allow for a great deal of customization in this regard. However, there are currentlyfourcustomizations you can make using# override tagsas an argument after the%%rendercell magic. Additionally, you can also specify the number of decimals of precision to display. You can only useoneoverride tag per cellbutyou can combine an override tag with a precision setting.Override tags can be used with both the Jupyter cell magic and the function decorator. To use a override tag with the decorator, you just supply it as an argument, e.g.@handcalc(override='params', precision=2)I will compare a basic rendering of the quadratic formula (below) with the change achieved with each override tag.Basic rendering:params:handcalcsrenders lines of code vertically, one after the other. However, when you are assigning variables, or displaying resulting variables, you may not want to waste all of that vertical space.Using theparamsoverride tag, your list of parameters will instead render in three columns, thereby saving vertical space. Additionally, onsly the result will be shown, no calculations.Adjust precision:The number of decimal places in a cell can be adjusted by providing an integer after%%renderto indicate the decimal precision to be displayed. Can be combined with another override tag.longandshort:To save vertical space,handcalcsattemptsto figure out how long your calculation is and, if it is short enough, renders it out fully on one line.Ifhandcalcs's internal test deems the calculation as being too long to fit onto one line, it breaks it out into multiple lines.Use the# longor# shortoverride tags to override the length check and display the calculation in the "Long" format or the "Short" format for all calculations in the cell. e.g.long: Spans multiple lines as though you had a long equationshort: Forced to a single line as though you had a short equation# Format for "short" calculations (can fit on one line):c=2*a+b/3=2*(2)+(3)/3=5# Format for "long" calculations (requires multi-line format)c=2*a+b/3=2*(2)+(3)/3=5symbolicThe primary purpose ofhandcalcsis to render the full calculation with the numeric substitution. This allows for easy traceability and verification of the calculation.However, there may be instances when it is preferred to simply display calculations symbolically. For example, you can use thesymbolictag to usehandcalcsas a fast way to render Latex equations symbolically.Alternatively, you may prefer to render out all of input parameters in one cell, your formulae symbolically in the following cell, and then all the final values in the last cell, skipping the numeric substitution process entirely.Keep in mind that even if you use thesymbolictag with your calculations, you still need to declare those variables (by assigning values to them) ahead of time in order for your calculation to be valid Python.sympyThis is intended to be used only withsympyloaded. Sympy allows for symbolic manipulation, solving, and integration of algebraic expressions. Sympy will render its own objects in Latex without handcalcs.If you are manipulating a sympy expression or sympy equation for the purpose of calculation, you can usehandcalcsto handle the substitution and calculation of your resulting expression.Note: Re-assigning your symbolic variables to numbers will clobber them as sympy variables. However, you are done with these now, right? So, it's no problem. If you need to work symbolically again, just re-run your notebook cells from the top.Units Packages Compatibilityhandcalcswas designed to be used with the units package,forallpeople(andforallpeoplewas designed to be compatible withhandcalcs). However, it has been recently reported thatpintcan work to good effect, also.For potential compatibility with other units packages, please seethe wiki.FeaturesQuickly display the values of many variablesNo moreprintstatements needed. Just plop your variables onto a line and they will all be displayed.Get Just the Latex Code, without the renderIf you just want to generate the rendered Latex code directly to use in your own Latex files, you can use the%%texcell magic instead:%%texa=2b=3c=2*a+b/3Then you can just copy and paste the result into your own LaTeX document.Subscripts (and sub-subscripts, etc.)Subscripts in variable names are automatically created when_is used in the variable name. Sub-subscripts are nested for each separate_used in series.Greek symbolsAny variable name that contains a Greek letter (e.g. "pi", "upsilon", "eta", etc.) as a string or substring will be replaced by the appropriate Latex code to represent that Greek letter.symbolsubstitutionsymbolsubstitutionalphaαAlphaΑbetaβBetaΒgammaγGammaΓdeltaδDeltaΔepsilonεEpsilonΕzetaζZetaΖetaηEtaΗthetaθThetaΘiotaιIotaΙkappaκKappaΚlambλLambΛmuμMuΜnuνNuNxiξXiΞomicronοOmicronΟpiπPiΠrhoρRhoΡsigmaσSigmaΣtauτTauΤupsilonυUpsilonΥphiφPhiΦchiχChiΧpsiψPsiΨomegaωOmegaΩUsing lower case letters as your variable name will make a lower case Greek letter.Using a Capitalized Name for your variable will render it as an upper case Greek letter.Functions, built-in or customIf you are using Python functions in your calculation, eg.min()ortan(), they will be replaced with Latex code to represent that function in Latex.If you are creating your own functions, then they will be rendered in Latex as a custom operator.If you are using a function with the namesqrt(whether your own custom implementation or frommath.sqrt), then it will be rendered as the radical sign.Rendered in-line CommentsAny comments placed after a line of calculation will be rendered as an inline comment in the Latex.This makes it convenient to make notes along side your calculations to briefly explain where you may have acquired or derived a particular value.Skip the substitutionAny calculation entirely wrapped in parentheses,(), will be rendered as justparam = result, without the substitution.This can be convient when you want to calculate a parameter on the fly and not have it be the focus of the calculation.Conditional statementsMany calculations in the "real world" are dependent on context.handcalcsallows for the inclusion of some simple conditional statements into its code in a way that makes it easier to understand the context of the calculation.Note: Multiple "lines" of calculations can be used after the conditional expression provided that they are all on the same line and separated with ";". SeeExpected Behavioursfor more context.Numeric integrationYou can usescipy.quadto perform numeric integration on a pre-defined function and havehandcalcsperform a basic rendering of it.This behaviour is triggered if you use a function with eitherintegrateorquadin the name."Prime" notationSometimes you need to write "prime" on your variables:PDF Printing in JupyterNote:Withnbconvertv6.0, installing templates (as shown in older YouTube videos) is no longer required. AnExporterfor Jupyter Notebook/Lab is
installed whenhandcalcsis installed which gives you access to two new File -> Save and Export as options:ExportHTML_NoInputExportLaTeX_NoInputExportPDF_NoInputThese options suppress all input cells so you only see rendered outputs in your Jupyter notebooks.By using these three options, you can create PDF exports either by HTML (and then PDF print from your browser) or via LaTex (whether directly or through
your own LaTeX environment).Expected Behaviourshandcalcsis intended to render arithmetical calculations written in Python code. It is not intended to render arbitrary Python into Latex.Given that, handcalcs only renders a small subset of Python and there is a lot that will not work, especially anything that happens over multiple lines (e.g. function definitions,forloops,withstatements, etc.).handcalcsworks by parsing individuallinesof Python within a cell. It does not parse the cell as a whole. Therefore all statements to be rendered must be contained on a single line.Accepted datatypeshandcalcswill make an attempt to render all datatypes. However, it cannot yet render all "collection" based data types, e.g.listanddict. If you are using a collection to hold argument functions, e.g.sum((23, 123, 45)), use atupleto ensure it is rendered properly. Alternatively, you can use one-dimensionalnumpyarrays (vectors) with handcalcs.Objects are rendered into Latex by two main approaches:If the object has a_repr_latex_()method defined, then that method is used.a) If the object has some alternate method for rendering itself into Latex code, e.g..latex()or.to_latex(), that will be attempted as well.In order for the representation to be rendered properly, the object's Latex represention must use commands that are implemented with MathJax and/or Katex.If the object does not have a Latex method, thenstr()is used.If you are using object types which have str methods that render as<MyObject: value=34>, then that's what the Latex interpreter will see and attempt to render.Arithmetic operators+renders as+-renders as-*renders as the "dot operator" (Latex: \cdot)/always renders as a fraction**renders as superscripts%renders as the "mod function" (Latex: \mod)Currently//is not rendered but you can easily usemath.flooras a function instead (asfloor).forloops and other iterationsShowing rendered iterations is not supported. The intention for use is that you perform your iterations in a cell that is not rendered and then, once the iteration has produced the desired resulting value, you render the result in a separate cell.GotchasBecausehandcalcsis designed for use within the Jupyter environment, and because Jupyter cells can be run out of order, there exists the possibility of having a big mess of beautifully rendered butcompletely incorrectcalculations if youre-use variable names throughout your notebook.handcalcsuses the notebook's user namespace dictionary to look up values for all variables in the namespace. If your calculations are re-using variable names throughout the notebook, then the dictionary entry for that name may not be what you think it is when you run cells out of the order originally intended.Youcanre-use variable names to good effect throughout a notebook,IFFthe cells are run in the correct order (easier if this is just top to bottom).On this note: if you are usinghandcalcsfor any kind of reporting that may become a legal document (e.g. design engineering calculations), it is up to YOU to ensure that the results are what you expect them to be.handcalcsis free and open-source software and the author(s) are not responsible for incorrect calculations that result from its use.That being said, the very purpose for the wayhandcalcsrenders its math is to make it very easy to confirm and verify calculations by hand.YouTube TutorialsGetting Started with handcalcs (assumes zero Python knowledge)https://www.youtube.com/watch?v=ZNFhLCWqA_gEngineering Calculations: handcalcs-on-Jupyter vs. Excelhttps://www.youtube.com/watch?v=n9Uzy3Eb-XIApplications and Compatibility with OPP (Other People's Packages)** Please seethe wikifor applications ofhandcalcsin education and engineering, in addition to examples of usinghandcalcswith other Python libraries suchstreamlitandpapermill.