On 5/20/11 4:52 PM, drewj wrote:
Sage can use the symbolic ring to create formal sums and products of
variables. I would like to make my own objects (with some extra
attributes and methods) behave like these without reimplementing the
distributive law, etc. For example this would work if they could be
part of sage Expressions which I could then retrieve using
Expression.operands(). I would like to do something like this:
sage: a = myVar(a, some data about a)
sage: b = myVar(b, foo)
sage: p = ((a+b)^2).expand()
a^2 + 2*a*b + b^2
sage: p.operands()[0]
a^2
sage: p.operands()[0].operands()[0]
a
sage: _.get_data()
some data about a
I tried using something like
sage: a = SR._force_pyobject(myInstance)
but then there is an error when I try to use a in an expression
because the operators aren't defined for my class. I could use a
dictionary with traditional variables as keys, but this is awkward
because there isn't a natural place for the dictionary to be if I am
passing these things to functions, etc. and also because I sometimes
want two variables with the same name but different extra data. I
also looked at subclassing Expression, but that didn't seem to work
either. Any ideas? Is there a more natural way to do something like
this?
My guess is that the easiest way to do things is to maintain a dict of
variable names that map to your objects (I think you're already doing
this?). Then just do the symbolic manipulation on the variables, but
when you want your special objects, just reference your dict.
Here is another hack to do this, based on the symbolic units
functionality. I think the key is creating a subclass of Expression as
a python class, so the subclass can have arbitrary attributes.
class MyObject(Expression):
pass
To instantiate the class:
myobject=MyObject(SR, SR.var('my_variable_name'))
Then I can do arithmetic using myobject:
sage: myobject^2+myobject*2+myobject
my_variable_name^2 + 3*my_variable_name
or assign arbitrary attributes to myobject instances:
sage: myobject.mystuff={'custom': 45}
However, I was having problems getting the mystuff back out of an
expression. Indeed, the units class (in
devel/sage/sage/symbolic/units.py) just indexes a dict by string keys,
like above, and then uses the expr.variables() to get the units out.
Jason
--
To post to this group, send email to sage-support@googlegroups.com
To unsubscribe from this group, send email to
sage-support+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org