ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Wed, 05 Apr 2023 01:44:02 +0200Proper inheritance method for initializing specific instance of parent classhttps://ask.sagemath.org/question/67326/proper-inheritance-method-for-initializing-specific-instance-of-parent-class/I want to create a class that is a type of graph, together with some additional information. As a simple example, let's say we want to create a class `MyCayleyGraph` that, when initialized on a group and a set of generators, returns the Cayley DiGraph, but also has attributes storing the group and the generators used to make that Cayley graph. I've found a way of doing this, but I fear it's not the best, and I'd like to know if there is a preferred way.
**My attempt**:
class MyCayleyGraph():
def __init__(self, group, gens):
self._graph = group.cayley_graph(generators = gens)
self._group = group
self._gens = gens
def __getattr__(self, attr):
return getattr(self._graph, attr)
def group(self):
return self._group
def gens(self):
return self._gens
**What I'm concerned about**:
Ideally, I think this should be done by inheriting from the graph class, but I couldn't figure out how to make `MyCayleyGraph` inherit from `DiGraph`, and make the initialized graph actually be the Cayley graph of group and gens, rather than just an empty graph. What bothers me about the solution above is that I seem to be "sneakily" making a DiGraph object, because I can call DiGraph attributes on the resulting Cayley Graph, but the resulting object isn't actually of type DiGraph.
What's the correct way to do this?
stillconfusedWed, 05 Apr 2023 01:44:02 +0200https://ask.sagemath.org/question/67326/Count GF(q) arithmeticshttps://ask.sagemath.org/question/51967/count-gfq-arithmetics/ Hi, I was trying to count the number of basic arithmetics happened in a GF(q)[x] or GF(q)[x].quo(irr) operation. I turned to define a wrapper class
Fq = GF(q)
class probeFq(Fq):
def __init__(self,*p,**kw):
self._cnt = 0
super(probeFq,self).__init__(*p,**kw)
def __add__(self, *p,**kw):
self._cnt += 1
return super(probeFq,self).__add__(*p,**kw)
However, I turns out that GF(q) in sage is not a class. Instead it is some sort of factory object. Is there any way to count the number of arithmetics happened to an element?Taylor HuangSun, 14 Jun 2020 16:26:02 +0200https://ask.sagemath.org/question/51967/Attempting to enrich quiver class yields "unexpected keyword argument" errorhttps://ask.sagemath.org/question/49636/attempting-to-enrich-quiver-class-yields-unexpected-keyword-argument-error/ I would like to do some computations with preprojective algebras, variations on the path algebra of a quiver in which every arrow has a partner going the other direction. I will want to construct representations of the "double quiver" in which I can conveniently compare the linear map associated to each arrow to that of its partner.
I figured I should create a class (something I haven't done in Python before) inheriting from DiGraph which has the extra data of a dictionary pairing the edges. My code to do this, with the constructor taking an arbitrary quiver and adding reversed copies of all the edges, is as follows:
class DoubleQuiver(sage.graphs.digraph.DiGraph):
def __init__(self, digraph):
edges = []
self._edgePairs = {}
for e in digraph.edges():
self._edgePairs[(e[0], e[1], e[2] + '0')] = (e[1], e[0], e[2] + '1')
self._edgePairs[(e[1], e[0], e[2] + '1')] = (e[0], e[1], e[2] + '0')
edges.append((e[0], e[1], e[2] + '0'))
edges.append((e[1], e[0], e[2] + '1'))
super(DoubleQuiver, self).__init__(edges, multiedges=True)
def flip(self, edge):
assert edge in self.edges()
return self._edgePairs[edge]
If I make a test digraph and run
DoubleQuiver(test)
it runs fine, and running methods like edges() or vertices() produces the results I expected. However, when I attempt to evaluate
DoubleQuiver(test).path_semigroup()
I get an error:
Error in lines 1-1
Traceback (most recent call last):
File "/cocalc/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 1234, in execute
flags=compile_flags), namespace, locals)
File "", line 1, in <module>
File "/ext/sage/sage-8.9_1804/local/lib/python2.7/site-packages/sage/graphs/digraph.py", line 2511, in path_semigroup
return PathSemigroup(self)
File "sage/misc/classcall_metaclass.pyx", line 335, in sage.misc.classcall_metaclass.ClasscallMetaclass.__call__ (build/cythonized/sage/misc/classcall_metaclass.c:1741)
return cls.classcall(cls, *args, **kwds)
File "/ext/sage/sage-8.9_1804/local/lib/python2.7/site-packages/sage/quivers/path_semigroup.py", line 118, in __classcall__
Q = Q.copy(immutable=True, weighted=True)
File "/ext/sage/sage-8.9_1804/local/lib/python2.7/site-packages/sage/graphs/generic_graph.py", line 1206, in copy
data_structure=data_structure)
TypeError: __init__() got an unexpected keyword argument 'weighted'
How should I modify my class definition to avoid this error, or is there a better way of accomplishing what I'm trying to do? (Also, is it relevant that I'm trying this on CoCalc?)Will DanaWed, 22 Jan 2020 01:03:17 +0100https://ask.sagemath.org/question/49636/How can I override the __call__ method of a matrixhttps://ask.sagemath.org/question/34296/how-can-i-override-the-__call__-method-of-a-matrix/I'd like to override the __call__ method of a matrix so that M(v) returns M*v. That is, I'd like to use functional notation. So I tried the following:
class MyMatrix(Matrix):
def __call__(self, v):
return self*v
but this doesn't work. Here is the error message I get when I try the above code in sage:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-88-e8d789594dd8> in <module>()
----> 1 class MyMatrix(Matrix):
2 def __call__(self, v):
3 return self*v
4
TypeError: Error when calling the metaclass bases
object() takes no parameters
I don't know anything about metaclasses. After banging my head against various walls, trying to learn, I am asking here.Saul SchleimerTue, 02 Aug 2016 19:16:44 +0200https://ask.sagemath.org/question/34296/[style] Choose between multiple inheritancehttps://ask.sagemath.org/question/10692/style-choose-between-multiple-inheritance/Dear Sage people,
I want to create a new (mathematical) object that sometimes is an Expression and sometimes a SymbolicFunction, depending on the arguments. You can think of this for example like $f(a, b, t) = \int_0^t a^b e^{-x^2} dx$. For special values of $t$ I would like to see it as an Expression ($t=0$ or $t=\infty$), but in all other cases I want it to be a BuiltinFunction (or something alike).
In Sage I can do something like:
class MyObjectExpression(Expression):
def __init__(self, a, b, t):
Expression.__init__(self, integral(a**b*e**(-x**2), x, 0, t))
# More (override) stuff below
class MyObjectFunction(BuiltinFunction):
def __init__(self, a, b, t):
BuiltinFunction.__init__(self, 'f(a,b,t)', nargs=1)
# More (override) stuff below
def MyObject(a, b, t):
if t == 0 or t == infty:
return MyObjectExpression(a, b, t)
else:
return MyObjectFunction(a, b, t)
Is it possible to combine these three things into one class? So I want to create a class which is sometimes an Expression and sometimes an much more abstract class, is this possible?
Best,
Noud
**Edit:**
What I actually want to do is programming Askey-Wilson polynomials and give them extra options, like a three term recurrence relation. But this depends on $n$. I already programmed this.
class Askey_Wilson(SageObject):
def __init__(self, SR, n, z, a, b, c, d, q):
self.n = n
self.z = z
self.q = q
self.a = a
self.b = b
self.c = c
self.d = d
self.param = [a, b, c, d]
if self.n in ZZ:
self.I = self.evaluate()
else:
self.I = var('askey_wilson')
def __repr__(self):
return 'p_%i(%s;%s,%s,%s,%s|%s)' % (
self.n, self.z, self.a, self.b, self.c, self.d, self.q
)
def evaluate(self):
n, q, z, a, b, c, d = [self.n, self.q, self.z] + self.param
lc = qPochhammerSymbol(SR, [a*b, a*c, a*d], q, n) / a**n
poly = BasicHypergeometricSeries(SR,
[q**(-n), a*b*c*d*q**(n-1), a*z, a*z**(-1)],
[a*b, a*c, a*d], q, q)
return lc*poly
def three_term_recurrence(self):
A, B, C = 0, 0, 0
# compute three term recurrence relation
return A, B, C
But now every time I want to know the explicit value of the Askey-Wilson polynomials I have to call askey_wilson.I. I want to get rid of the I.NoudSun, 03 Nov 2013 14:22:42 +0100https://ask.sagemath.org/question/10692/subclass from a sage vectorhttps://ask.sagemath.org/question/9510/subclass-from-a-sage-vector/Hello all,
I have another question regarding the vector class shipped with sage. I would like
to add some properties to a vector to store some additional information. But I
am not sure which class I should choose as a base class, since there are a lot of
different vector classes:
sage: type(vector([1.123,324.1]))
<type 'sage.modules.free_module_element.FreeModuleElement_generic_dense'>
sage: type(vector([1,2]))
<type 'sage.modules.vector_integer_dense.Vector_integer_dense'>
sage: type(vector([1,6/2]))
<type 'sage.modules.vector_rational_dense.Vector_rational_dense'>
Do I have to pick one of those classes (I excpect a real vector would do OK) or
is it possible to subclass in such a way that I can have different base_ring()s
for my class?
MathmonWed, 07 Nov 2012 15:04:38 +0100https://ask.sagemath.org/question/9510/inheriting from CombinatorialFreeModulehttps://ask.sagemath.org/question/9281/inheriting-from-combinatorialfreemodule/I am trying to write a class that inherits from CombinatorialFreeModule. My problem is correctly inheriting from the element class. I have the following code:
from sage.sets.family import Family
from sage.categories.all import GradedAlgebrasWithBasis
from sage.combinat.free_module import CombinatorialFreeModule, CombinatorialFreeModuleElement
from sage.categories.all import tensor
class TestRing(CombinatorialFreeModule):
def __init__(self, R, G):
super(TestRing, self).__init__(R, G)
class TestRingElement(CombinatorialFreeModuleElement):
def __init__(self, M, x):
super(TestRingElement, self).__init__(M, x)
self.data = x
I can create a TestRing object and get its basis elements as follows:
sage: R = TestRing(QQ, ('a','b'))
sage: a,b = R.basis()
My problem is that `a` and `b` have no `data` attribute. They are not instances of the `TestRingElement` class:
sage: a.d
a.db a.dump a.dumps
sage: isinstance( a, TestRingElement )
False
I want to be able to add more attributes to the elements of my module. Can someone tell me the correct way to do this?
Incidentally, this code breaks when I call `TestRing` with a list as its second argument, instead of a tuple. Though, if I create a list inside the constructor (based on input to the constructor) and use that when I call the parent constructor, everything runs fine. Can anyone tell me why the code breaks in the first instance? Or, why does it work in the second instance?
Thanks!shacsmugglerThu, 30 Aug 2012 21:08:46 +0200https://ask.sagemath.org/question/9281/using inheritance to create a new Parent classhttps://ask.sagemath.org/question/8258/using-inheritance-to-create-a-new-parent-class/I have an algebra (and a group as well) I would like to represent in Sage. In fact, the code for doing this is already written, but the structures do not inherit from any existing Sage structures, and lately I have also been finding bugs in the algebraic manipulations. I would like to make this code compatible with the larger Sage framework by correctly using inheritance. I found this article: http://flask.sagenb.org/home/pub/82/, from which I understand that there is a way to inherit from a generic "algebra" parent and thus get a lot of bug-free structure. My problem is that this article discusses only the specific example of a field, and I don't know where to begin with my algebra. In particular, the article says, "When implementing a parent in Sage, one should start with a class that inherits from :class:`sage.structure.parent.Parent`," - where can I find a list of such classes? The example inherits from the derived class "sage.rings.field.Field". I do not know where to find the class analogous to this for algebras (or groups). I also need lots of documentation explaining what the algebra (and group) parent comes with.
Thank you!shacsmugglerWed, 03 Aug 2011 15:44:42 +0200https://ask.sagemath.org/question/8258/