connorferster / handcalcs

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

Problems with @handcalc and errorhandling #198

Open DonCammne opened 7 months ago

DonCammne commented 7 months ago

I'm exploring this beautiful library, pushing the limits to get its limitations (if any). For the moment, I can achieve almost anything that I need, except this: using correctly the @handcalcs for functions.

I noted that the comments inside the function (and outside if indented) raise errors, but this can be easily solved by using ""'comments"'" (thanks @ernest505). On the other hand, if I check for exceptions (see below for an example), an error occurs:

Cell 1:

from handcalcs.decorator import handcalc
import handcalcs.render
import re
import forallpeople as si
si.environment('structural', top_level=False)

class WrongUnits(Exception):
    """Exception class for the "wrong units" error.
    """
    pass

def checkSameUnits(a, b):
    """Return True if the two parameters have the same units.

    @param a (float): First parameters with forallpeople units.
    @param b (float): First parameters with forallpeople units.

    @returns bool: Are the two parameters with the same units?
    """
    regex_string = '(?<=Dimensions\()(.*?)(?=\))'
    a_units_info = re.findall(regex_string, a.repr)[0]
    b_units_info = re.findall(regex_string, b.repr)[0]

    return a_units_info == b_units_info

@handcalc(jupyter_display=True)
def computeA_IShapeWithoutFillets(d, b_f, t_f, t_w):
    """Compute the area of a double symmetric I-profile section without fillets included in the calculation (simplification).
    WARNING: foarallpeople required!

    @param d (float): Depth
    @param b_f (float): Flange's width
    @param t_f (float): Flange's thickness
    @param t_w (float): Web's thickness

    @exception WrongUnits: d needs to be a length unit.
    @exception WrongUnits: b_f needs to be a length unit.
    @exception WrongUnits: t_f needs to be a length unit.
    @exception WrongUnits: t_w needs to be a length unit.

    @returns float: The area.
    """
    if not checkSameUnits(d, si.m): raise WrongUnits()
    if not checkSameUnits(b_f, si.m): raise WrongUnits()
    if not checkSameUnits(t_f, si.m): raise WrongUnits()
    if not checkSameUnits(t_w, si.m): raise WrongUnits()

    A_IShape = b_f*t_f*2.0 + t_w*(d-2.0*t_f)
    return A_IShape

Cell 2:

%%render params 2

d = 200*si.mm
b_f = 120*si.mm
t_f = 12*si.mm
t_w = 20*si.mm

Cell 3:

A = computeA_IShapeWithoutFillets(d, b_f, t_f, t_w)

The error is quite long, so I guess it's easier to just replicate it.

It would be incredible, if the section of a function that is rendered could be controlled (by a flag maybe?), so that for example preliminary calculation are not included.

Any help or advice is appreciated, thanks!