[AstroPy] Obscure question on subclassing units.Quantity

Livesey, Nathaniel J (US 3290) nathaniel.j.livesey at jpl.nasa.gov
Sat Sep 26 23:57:43 EDT 2020


Dear all,

   I’ve subclassed astropy.Quantity (following, I believe, the various rules discussed for that in the astropy and numpy documentation).  Specifically, I’m implementing “dual algebra" (for computing values and Jacobians simultaneously, see the Wikipedia article on automatic differentiation if you’re curious).

   It’s mostly working pretty well.  However, I’m having trouble getting it to invoke my __array_ufunc__ under certain circumstances, and I think it’s defaulting to the units.Quantity method.  Specifically, if “x” is an instance of my new “dual” class, then, saying:

y = x * units.m

(where units is astropy.units), my __array_ufunc__ is not invoked, thus I never get to my class’ multiply or rmultiply method. The consequence is that the Jacobian information attached to x doesn’t get handled correctly before being transferred to y.

   If instead I do

y = x * (1.0*units.m)
or
y = units.m * x

then my __array_ufunc__ does get invoked, and everything works fine.  However, while this is arguably a workaround it’s unsatisfactory, and highly undesirable to require any “users” of my new class (mostly me I admit) to remember to do it that way. The consequences of forgetting are such that it’s hard to track down the place where the mistake was made.
(I’ve not yet gotten round to overloading <<, but I still want the above to work.)

Does anyone have a suggestion of how I can get my __array_ufunc__ to be invoked in this case?

Thanks,

Nathaniel

P.S. Many thanks, again, for astropy.units/astropy.Quantity.

Nathaniel Livesey
Mail Stop 183-701, Jet Propulsion Laboratory
4800 Oak Grove Drive, Pasadena, California 91109.
Phone: +1 818 354-4214   Fax: +1 818 393-5065



More information about the AstroPy mailing list