ASKSAGE: Sage Q&A Forum - Latest question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Tue, 25 Jun 2019 12:40:19 -0500wrapping vector classhttp://ask.sagemath.org/question/46995/wrapping-vector-class/I am trying to wrap the vector class to add some extra cases, but I am having trouble doing so. This is the code I have:
def lower_triangular_entries(dim,x,y):
return upper_triangular_entries(dim,y,x)
def upper_triangular_entries(dim,x,y):
if y<=x:
return 1
else:
return 0
class OneParamSubgroup(vector):
#TO DO: define scalar multiplication
def __init__(self, data, type_A=False):
if type_A:
BasisChange=matrix(ZZ, len(data)-1, len(data)-1,
lambda x,y: lower_triangular(len(data)-1,x,y))
v=vector(data[0:len(data)-1])
v=tuple(BasisChange*v)
#data given in terms of basis T
else:
v=data
vector.__init__(self, v)
def __repr__(self):
return self
However, I get the following error when running on terminal
Traceback (most recent call last):
File "test.sage.py", line 7, in <module>
load("GIT/Group.sage")
File "sage/structure/sage_object.pyx", line 1057, in sage.structure.sage_object.load (build/cythonized/sage/structure/sage_object.c:12915)
File "/opt/sagemath-8.1/local/lib/python2.7/site-packages/sage/repl/load.py", line 247, in load
exec(preparse_file(open(fpath).read()) + "\n", globals)
File "<string>", line 3, in <module>
ImportError: cannot import name vector
and the following on the Notebook
TypeError Traceback (most recent call last)
<ipython-input-1-ec2394617192> in <module>()
8 return Integer(0)
9
---> 10 class OneParamSubgroup(vector):
11 #TO DO: define scalar multiplication
12 def __init__(self, data, type_A=False):
TypeError: Error when calling the metaclass bases
cannot create 'builtin_function_or_method' instances
Any idea of what I am doing wrong?Jesus Martinez GarciaTue, 25 Jun 2019 12:40:19 -0500http://ask.sagemath.org/question/46995/Explicitly clean all memory usagehttp://ask.sagemath.org/question/46810/explicitly-clean-all-memory-usage/class State():
def __init__(self):
self.value = []
state0 = State()
state0.value = range(10^8)
At this point, a huge memory is located. After processing state0.value, I set it back to empty to continue another process.
state0.value = []
However, the memory is not fully cleaned. Therefore, I cannot continue another process due to my limitation of memory on my computer, and I have to close Sagemath 8.4 to get back to the fresh memory. It is better to iterate, instead of using memory like this; however, I hope that an explicit memory clean exists in Sagemath. Besides it, I use `range(10^8)` to illustrate my actual 10^8 data in type of set to ease the understanding, so please do not support on re-formulating this usage of `range`.imnvshWed, 05 Jun 2019 10:45:28 -0500http://ask.sagemath.org/question/46810/Redefine Method in Sage classhttp://ask.sagemath.org/question/45102/redefine-method-in-sage-class/I am using the a class to manipulate vector fields of $\mathbb{R}^n$.
I am using an other convention on the lie brackets : to compute $XY=[X,Y]$ I have to enter $XY=-X.bracket(Y)$.
**I would like to redefine the method "bracket()"** so that I include this minus sign in the redefinition.
Of course I can each time put a minus sign in front all my definition or call Y.bracket(X) to compute [X,Y] but I don't want to use them (the display is then not adapted ...).
Here is my code
from sage import *
reset()
def mybracket(A,B):
return B.bracket(A)
M.<x,y> = EuclideanSpace()
X = M.vector_field(0,1-y*x^2, name='X')
Y = M.vector_field(-(y-1),x, name='Y')
YX = Y.mybracket(X)
*AttributeError: 'VectorFieldFreeModule_with_category.element_class' object has no attribute 'mybracket'*
ThankssagenotdeadSat, 19 Jan 2019 07:42:20 -0600http://ask.sagemath.org/question/45102/may an object in sage lose its type in a method within a class ?http://ask.sagemath.org/question/44242/may-an-object-in-sage-lose-its-type-in-a-method-within-a-class/Many thanks to @slelievre for his response and to @tmonteil for his comments.
Here is the original Sage code. It and a little bit long but perhaps all these are
useful to see what goes wrong:
class CCODEPARAM:
def __init__(self, liste_ent, prem, em):
self.liste_ent = liste_ent
self.prem = prem
self.em = em
def qu(CyclicCodeParam):
q = (CyclicCodeParam.prem)^(CyclicCodeParam.em)
return q
def long(CyclicCodeParam):
NN = CyclicCodeParam.liste_ent
r = len(NN)
n = 1
for i in range(r):
n = n * NN[i]
return n
def epsilon(CyclicCodeParam):
NN = CyclicCodeParam.liste_ent
from sage.arith.functions import LCM_list
eps = LCM_list(NN)
return eps
def t(CyclicCodeParam):
NN = CyclicCodeParam.liste_ent
p = CyclicCodeParam.prem
r = len(NN)
m = CyclicCodeParam.em
q = p^m
eps = CyclicCodeParam.epsilon()
k = 1
while not(mod(q^k-1, eps) == 0):
k += 1
return k
def cardn(CyclicCodeParam):
return (CyclicCodeParam.qu())^(CyclicCodeParam.long())
def Gqu(CyclicCodeParam):
Q = (CyclicCodeParam.qu())^(CyclicCodeParam.t())
return Q
def liste_groupes(CyclicCodeParam):
NN = CyclicCodeParam.liste_ent
r = len(NN)
Groupes = []
for i in range(r):
Groupes.append(Set(IntegerModRing(NN[i])))
return Groupes
def prod_groupes(CyclicCodeParam):
GR = CyclicCodeParam.liste_groupes()
GG = list(cartesian_product(tuple(GR)))
return GG
def corps(CyclicCodeParam):
F = GF((CyclicCodeParam.qu()))
FF = GF(CyclicCodeParam.Gqu())
return [F, FF]
def prim(CyclicCodeParam):
K = CyclicCodeParam.corps()
L = K[1]
a = L.multiplicative_generator()
return a
def primorderb(CyclicCodeParam):
Q = CyclicCodeParam.Gqu()
eps = CyclicCodeParam.epsilon()
a = CyclicCodeParam.prim()
b = a^((Q - 1) / eps)
return b
def primuroots(CyclicCodeParam):
NN = CyclicCodeParam.liste_ent
r = len(NN)
eps = CyclicCodeParam.epsilon()
b = CyclicCodeParam.primorderb()
e = []
for i in range(r):
e.append(b^(eps/NN[i]))
return e
def galois(CyclicCodeParam):
t = CyclicCodeParam.t()
q = CyclicCodeParam.qu()
MM = list(Set({q^nu for nu in range(t)}))
return MM
def orbites(CyclicCodeParam):
GG = CyclicCodeParam.prod_groupes()
MM = CyclicCodeParam.galois()
NN = CyclicCodeParam.liste_ent
O = orb(GG, MM, NN)
return O
def ambspace(CyclicCodeParam):
F = CyclicCodeParam.corps()[0]
n = CyclicCodeParam.long()
K = list(cartesian_product([F]*n))
return K
def zeros(PAR, A):
O = PAR.orbites()
Z = Set({O[i][0] for i in A})
return Z
def CCODE(PAR, A, Vars):
# order = 'lex'
CORPS = PAR.ambspace()
print type(CORPS)
Z = PAR.zeros(A)
# print Z
Exp = PAR.orbites()
# print Exp
e = PAR.epsilon()
print e
CODE = {Zvalpol2(c, Vars, Exp, e, Z) for c in CORPS}
return CODE
def oneorb(g, MM, NN):
O = Set({})
r = len(NN)
for u in MM:
B = []
for i in range(r):
B.append(mod((g[i])*u,NN[i]))
O = O.union(Set({tuple(B)}))
return O
def orb(GG, MM, NN):
Orb = Set({})
GG = Set(GG)
for g in GG:
t = oneorb(g,MM,NN)
Orb = Orb.union(Set({t}))
GG = GG.difference(Orb)
return Orb
def pol(c, Vars, Exp):
n = len(c)
m = len(Vars)
P = 0
M = []
for i in range(n):
M.append(0)
M = list(M)
for i in range(n):
M[i] = 1
for j in range(m):
M[i] *= Vars[j]**Exp[i][j]
for i in range(n):
P += c[i] * M[i]
return P
def Zvalpol2(c, Vars, Exp, e, Z):
P = pol(c, Vars, Exp)
print('poly')
r = len(Vars)
V = Set({})
for h in Z:
E = []
for i in range(r):
E.append(e[i]**h[i])
V = V + Set({P(tuple(E))})
if V == Set({0}):
mes2 = 'mot de code'
print mes2
In the fonction "CCODE", when constructing the objet "CORPS" by `CORPS =PAR.ambspace()`, Sage return "none" for its type, even though the fonction "ambspace" return the object "K", which is of type "list". As a consequence, when executing the function CCODE, Sage returns an error by saying that objet of nonetype (which is CORPS) is not iterable. This happens on the instruction above the "return CODE" in the function CCODE.andriamSun, 11 Nov 2018 13:24:27 -0600http://ask.sagemath.org/question/44242/Type error in matrix of differential formshttp://ask.sagemath.org/question/41230/type-error-in-matrix-of-differential-forms/I'm having problems tracing the exact problem in my code: I have matrices of differential forms and at some point I get type errors.
Consider the following example:
class Test:
def __init__(self):
self.z = var('z')
self.U = CoordinatePatch([self.z])
self.D = DifferentialForms(self.U)
self.d = self.D.gens()
self.M = Matrix(self.D,2)
print self.M
self.M[0,0] = self.d[0]
print self.M
print (self.M.base_ring() is self.D)
The first instance works without error, from the second onward I get a type error:
┌────────────────────────────────────────────────────────────────────┐
│ SageMath version 7.5.1, Release Date: 2017-01-15 │
│ Type "notebook()" for the browser-based notebook interface. │
│ Type "help()" for help. │
└────────────────────────────────────────────────────────────────────┘
sage: load('bugtest.sage')
sage: Test()
[0 0]
[0 0]
[dz 0]
[ 0 0]
True
<__main__.Test instance at 0x1edc7cbd8>
sage: Test()
[0 0]
[0 0]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-d1e5fd9e553c> in <module>()
----> 1 Test()
<string> in __init__(self)
/Applications/sage-7.5.1/src/sage/matrix/matrix0.pyx in sage.matrix.matrix0.Matrix.__repr__ (/Applications/sage-7.5.1/src/build/cythonized/sage/matrix/matrix0.c:11464)()
1664 """
1665 if self._nrows < max_rows and self._ncols < max_cols:
-> 1666 return self.str()
1667 if self.is_sparse():
1668 s = 'sparse'
/Applications/sage-7.5.1/src/sage/matrix/matrix0.pyx in sage.matrix.matrix0.Matrix.str (/Applications/sage-7.5.1/src/build/cythonized/sage/matrix/matrix0.c:13504)()
1876 rep = rep_mapping.get(x)
1877 else:
-> 1878 rep = repr(x)
1879 S.append(rep)
1880
/Applications/sage-7.5.1/src/sage/structure/sage_object.pyx in sage.structure.sage_object.SageObject.__repr__ (/Applications/sage-7.5.1/src/build/cythonized/sage/structure/sage_object.c:2691)()
190 return str(type(self))
191 else:
--> 192 result = repr_func()
193 if isinstance(result, unicode):
194 # Py3 compatibility: allow _repr_ to return unicode
/Applications/sage-7.5.1/local/lib/python2.7/site-packages/sage/tensor/differential_form_element.pyc in _repr_(self)
1006 format = DifferentialFormFormatter(self.parent().base_space())
1007 output = [format.repr(comp, fun) \
-> 1008 for (comp, fun) in self._components.items()]
1009 return ' + '.join(output)
1010
/Applications/sage-7.5.1/local/lib/python2.7/site-packages/sage/tensor/differential_form_element.pyc in repr(self, comp, fun)
161 [('d%r' % self._space.coordinate(c)) for c in comp])
162
--> 163 if fun == 1 and len(comp) > 0:
164 # We have a non-trivial form whose component function is 1,
165 # so we just return the formatted form part and ignore the 1.
/Applications/sage-7.5.1/src/sage/symbolic/expression.pyx in sage.symbolic.expression.Expression.__nonzero__ (/Applications/sage-7.5.1/src/build/cythonized/sage/symbolic/expression.cpp:17020)()
2574 return self.operator()(self.lhs().pyobject(), self.rhs().pyobject())
2575
-> 2576 pynac_result = decide_relational(self._gobj)
2577 if pynac_result == relational_undecidable:
2578 raise ValueError('undecidable relation: ' + repr(self))
/Applications/sage-7.5.1/src/sage/structure/element.pyx in sage.structure.element.Element.__add__ (/Applications/sage-7.5.1/src/build/cythonized/sage/structure/element.c:11198)()
1234 # Left and right are Sage elements => use coercion model
1235 if BOTH_ARE_ELEMENT(cl):
-> 1236 return coercion_model.bin_op(left, right, add)
1237
1238 try:
/Applications/sage-7.5.1/src/sage/structure/coerce.pyx in sage.structure.coerce.CoercionModel_cache_maps.bin_op (/Applications/sage-7.5.1/src/build/cythonized/sage/structure/coerce.c:10496)()
1105 # We should really include the underlying error.
1106 # This causes so much headache.
-> 1107 raise bin_op_exception(op, x, y)
1108
1109 cpdef canonical_coercion(self, x, y):
TypeError: unsupported operand parent(s) for '+': 'Algebra of differential forms in the variables z' and 'Integer Ring'
Maybe the symbolic variable is not "safe" inside a class?JonathanThu, 22 Feb 2018 03:07:48 -0600http://ask.sagemath.org/question/41230/Making a collection of functionshttp://ask.sagemath.org/question/40811/making-a-collection-of-functions/I have a somewhat large collection of functions that I wrote myself to make some computations. They are all very much dependent on each other so if I ever want to use some subset of them, say when I'm working in some Jupyter notebook, I have to copy paste the whole bunch of them into a cell and evaluate it. This makes the notebook really bulky and ugly. Is there anyway I can make these functions into a package so that I can just import it in any jupyter notebook that's in the same folder to use those functions?r2d2Sat, 27 Jan 2018 13:25:00 -0600http://ask.sagemath.org/question/40811/Problem with Sequence commandhttp://ask.sagemath.org/question/34956/problem-with-sequence-command/ Computation of gcd of objects of a class a created fails. I investigated the case and traced down that the problem lies in Sequence command. Consider the following example class:
class foo(object) :
def __init__(self, L_) :
self.L = deepcopy(L_)
def __getitem__(self, j) :
return self.L[j]
def size(self) :
return len(self.L)
Create and example object:
a = foo( [1,2,3] )
print a.size()
>> 3
Build a nested object:
A = foo([ foo([1,2,3]), foo([2,4,8]), foo([1,1]), foo([1]) ])
print A.size()
>> 4
Everything works as expected. So let's iterate over A:
for a in A :
print a.size()
>> 3
>> 3
>> 2
>> 1
So far so good. Let's use Sequence as gcd internally does:
S = Sequence(A)
for s in S :
print s.size()
>> `TypeError: object of type 'foo' has no len()`
And boom! Something went wrong. Try to call len explicitly:
for s in S :
print len(s.L)
>> `TypeError: object of type 'foo' has no len()`
The same error! Surprisingly the following code actually works (but IMHO it should not):
for s in S :
print len(s.L.L)
>> 3
>> 3
>> 2
>> 1
It seems like something strange happens in initialization. When creating a sequence, all objects get initialized by themselves.
Ok. So here is my question: what's up? Do I do something wrong or is this a bug in `Sequence`? I know that Python does not provide copy constructors, hence how to initialize objects to avoid this kind of problems?
Thanks in advance,
Przemek
_pkMon, 26 Sep 2016 11:24:23 -0500http://ask.sagemath.org/question/34956/Is it possible to subclass a sage class?http://ask.sagemath.org/question/34978/is-it-possible-to-subclass-a-sage-class/I want to subclass the sage `Polyhedra` class.
Basically, I have a bunch of functions I have written for polyhedra and I want to organize them in a class. Is this possible in sage? done_with_fishWed, 28 Sep 2016 01:15:25 -0500http://ask.sagemath.org/question/34978/Smart set (database?)http://ask.sagemath.org/question/32217/smart-set-database/Hi,
What I would like is to define a smart hierarchical set (or database) like:
example_set={(0,0,0):[4,[7,11,0]], (0,0,1):[-5,[8,-3,6]], (0,1,0):[4,[7,11,-1]]}
The lefthand side is an hierarchy (a,b,c,d,e,...); the righthand side is some structure [*, [*,*,*,...]] consisting of nested lists. How can I quickly -via a smart design- determine for instance the sum for a higher level? For instance example_set.sum[(0,0)] would yield [4-5, [7,11,0] + [8,-3,6]] and example_set.sum[(0,)] yields [4-5+4, [7,11,0] + [8,-3,6] + [7,11,-1]].
The setting is that we have a few thousand hierarchical elements with unknown depth, but always the same structure on the righthand side. The structure could contain many nested lists with in total several hunderd values (flattened). I like to have (fast) basic operators for the lists within the structure such as addition and index.
Another example.
next_example={(0,0,0):[(5,6)], (0,0,1):[(8,9),(3,4)], (0,1,0):[(2,6)], (0,1,1):[(8,16)]}
(wanted) print next_example.sum[(0, 0)]
[(5, 6), (8, 9), (3, 4)]
I considered to define a class and I looked at [database](http://doc.sagemath.org/html/en/reference/databases/index.html). But that didn't help me much :(
To complicate matters, I would also like to connect hierarchical levels (one-direction). For instance in the first example assume (0,0,0) is connected to (0,1,1). How to store and display such a connection? For connections I looked for instance at [igraph](http://doc.sagemath.org/html/en/reference/graphs/sage/graphs/generic_graph.html#sage.graphs.generic_graph.GenericGraph.igraph_graph). But it isn't clear to me whether it would be helpful in combination with the above mentioned set design.
To summarize: it would be awesome if a routine 'smart_set(n, structure)' would define a n-level hierarchy whereby operations like .sum(input) and .sum.connected(input) and .show_graph() would work.
Suggestions how to move forward in Sage are much appreciated!
Roland
RolandbFri, 15 Jan 2016 14:46:28 -0600http://ask.sagemath.org/question/32217/Twisted Polynomial Ring(Construct new Class)http://ask.sagemath.org/question/31584/twisted-polynomial-ringconstruct-new-class/ I would like to implement a class of twisted polynomial rings, which assigns to ring $K$ in characterstic $p$ a ring $K[\tau]$, whose underlying additive structure is just an ordinary polynomial ring in $\tau$, but with the multiplication defined by $\tau x=x^p \tau$.
Is it possible to construct this as a usual polynomial ring and modify the multiplication in some way?
I am totally new to Sage and Python, and I couldn't even figure out the parent/element dynamics, i.e. what exactly I have to specify for my object to fit with the usual Sage classes. The thematic tutorials on the documentation page don't really specify a general way to deal with this, so I am lost where to start. Nick123Tue, 15 Dec 2015 08:06:27 -0600http://ask.sagemath.org/question/31584/Publishing a worksheet that uses moduleshttp://ask.sagemath.org/question/30377/publishing-a-worksheet-that-uses-modules/ I wrote a worksheet in the Sage Notebook. Since it was large, I split it into several modules. So now my worksheet looks like this:
load ("/home/erelsgl/git/myproject/ClassA.sage")
... Do some things with class A ...
The file ClassA.sage looks like this:
load ("/home/erelsgl/git/myproject/ClassB.sage")
... Define class A based on class B ...
This works on my computer, but of course it will not work when I publish it on the cloud.
What is the correct way to write my notebook and its modules such that it will be publishable in the Sage cloud?
Erel Segal-HaleviSat, 31 Oct 2015 14:01:35 -0500http://ask.sagemath.org/question/30377/How to define a smart class using cython?http://ask.sagemath.org/question/7749/how-to-define-a-smart-class-using-cython/Hi,
I managed to rewrite my problem so I only have to represent numbers in the following way:
[(2,3),(3,3),(13,1)] like in list(factor(8*27*13)). Thus [(prime,exponent), (prime,exponent), ...].
With such a representation multiplying is easy, and I can skip to factor numbers (again).
What I'm looking for is a fast cython approach with a class where I can define a function for multiplying, but also where I'm able to store and retrieve a large set of numbers efficiently (within the program).
I looked for examples in the Cython Tutorial et cetera, but I could not find an approach which helped me.
Maybe someone is willing and able to share his/her expertise? Thanks in advance! Roland
rolandMon, 01 Nov 2010 20:08:45 -0500http://ask.sagemath.org/question/7749/question about hilbert_class_polynomialhttp://ask.sagemath.org/question/11041/question-about-hilbert_class_polynomial/I run sagecell hilbert_class_polynomial sqrt(-5),but different with below:
http://echidna.maths.usyd.edu.au/kohel/dbs/class_polynomials/hilbert_class_poly.html
http://sagenb.skku.edu/home/pub/155/
cjshSat, 15 Feb 2014 20:42:59 -0600http://ask.sagemath.org/question/11041/why K.ideal(1/2,a) not in all 6 ideal classes of Q[-26] ?http://ask.sagemath.org/question/10893/why-kideal12a-not-in-all-6-ideal-classes-of-q-26/why K.ideal(1/2,a) not in all 6 ideal classes of Q[-26] ?
K.ideal(3,a+2) should be in C1,but still in C2......
K.<a> = NumberField(x^2 +26);K;html(table(K.class_group(),frame=true).transpose());show(K.class_number());C0=K.class_group()[0];C0;C1=K.class_group()[1];C1;C2=K.class_group()[2];C2;C3=K.class_group()[3];C3;C4=K.class_group()[4];C4;C5=K.class_group()[5];C5
C0=K.class_group()[0].list(); show(C0);C1=K.class_group()[1].list(); show(C1);C2=K.class_group()[2].list(); show(C2);C3=K.class_group()[3].list(); show(C3);C4=K.class_group()[4].list(); show(C4);C5=K.class_group()[5].list(); show(C5);
II = K.ideal(1/2,a);II in C0;II in C1;II in C2;II in C3;II in C4;II in C5
III = K.ideal(2);III in C0;III in C1;III in C2;III in C3;III in C4;III in C5
I = K.ideal(5/2,a);III in C0;III in C1;III in C2;III in C3;III in C4;III in C5
I = K.ideal(3,a+2);III in C0;III in C1;III in C2;III in C3;III in C4;III in C5
I = K.ideal(5,a+2);III in C0;III in C1;III in C2;III in C3;III in C4;III in C5
I = K.ideal(6,a^3+2,a^5,a^123);III in C0;III in C1;III in C2;III in C3;III in C4;III in C5cjshTue, 07 Jan 2014 21:25:53 -0600http://ask.sagemath.org/question/10893/How to get a Boolean from the type of an object?http://ask.sagemath.org/question/9933/how-to-get-a-boolean-from-the-type-of-an-object/I am trying to define the `__init__` of a class, where I would like to support different types of input; in my case the input could be a either a list of pairs or a matrix. How do I write a Boolean function to test which kind of input I have? In the example code, I want to know how I should define the Boolean functions `is_a_matrix(A)` and `is_a_tuple_of_pairs(A)` (and of course more generally testing `A` to be of some other type)
class someclass():
def __init__(self, A):
if is_a_matrix(A):
self._matrix = A
if is_a_tuple_of_pairs(A):
self._matrix = somefunction(A)AmriFri, 22 Mar 2013 01:02:18 -0500http://ask.sagemath.org/question/9933/How can I re-code a function into a method?http://ask.sagemath.org/question/8482/how-can-i-re-code-a-function-into-a-method/I have the following simple function 'add4' stored in a file 'foo.sage':
def add4(x):
"""Adds 4 to x"""
return x + 4
I can use this in sage by:
sage: attach 'foo.sage'
sage: add4?
Type: function
Base Class: <type 'function'>
String Form: <function add4 at 0x4f332a8>
Namespace: Interactive
File: Dynamically generated function. No source code available.
Definition: add4(x)
Docstring:
Adds 4 to x
sage: var('x')
x
sage: add4(x)
x + 4
How can I change my function to a method so that I can call it using the x.add4() syntax? I still want the method to reside in an external file.
rtrwalkerWed, 16 Nov 2011 11:57:28 -0600http://ask.sagemath.org/question/8482/pickling extension classeshttp://ask.sagemath.org/question/8376/pickling-extension-classes/What is the right way to pickle a cython extension class? Consider the example
cdef class Stuff:
def __init__(self):
pass
then
a = Stuff()
a == loads(dumps(a))
gives the result **False** because the address of the new object generated by *loads* is different from the original object *a*.
Hartmut MonienThu, 13 Oct 2011 17:47:27 -0500http://ask.sagemath.org/question/8376/cython stl classhttp://ask.sagemath.org/question/8225/cython-stl-class/sage complains about importing the following spyx file:
from libcpp.vector cimport vector as vec
cdef test_vector():
cdef vec[int] vect
cdef int i
for i in range(10):
vect.push_back(i)
for i in range(10):
print vect[i]
I have no problem translating a pyx file with the same contents with cython and generating a module with test_vector ... . What is the right way to access the stl cpp vector class in a pyx file?
Hartmut MonienThu, 14 Jul 2011 10:07:05 -0500http://ask.sagemath.org/question/8225/Making my own special type of variablehttp://ask.sagemath.org/question/8109/making-my-own-special-type-of-variable/I want to create an object that I can take formal products and sums of, and also that remembers some extra data. I'd like to use sage's symbolic tools to do it without reimplementing multiplication, etc. For example, I'd like to make a class `myVar` that behaves something like this:
sage: a = myVar("some data about a")
sage: b = myVar("other important stuff")
sage: p = ((a + b)^2).expand()
a^2 + 2*a*b + b^2
sage: p.operands()
[a^2, 2a*b, b^2]
sage: p.operands()[0].operands[0]
a
sage: p.operands()[0].operands[0].get_data()
"some data about a"
I've tried subclassing Expression, but it seems like whenever I try to do some sums or products it just turns my thing into an Expression and forgets that it was a myVar.
Is something like this possible in sage?paragonWed, 11 May 2011 06:35:18 -0500http://ask.sagemath.org/question/8109/How do instantiate a new class properly?http://ask.sagemath.org/question/8013/how-do-instantiate-a-new-class-properly/## Background ##
I have created a new class `FeynmanGraph` that is a subclass of `Graph`. It has some extra methods, and the module in which it lives also has some extra functions. The most important method for my purposes searches for possible colorings of the vertices that satisfy certain combinatorial criteria that have to do with spanning trees. (The details are not important here.)
The code works. I should mention that I'm editing `feynman.sage` in a text editor and attaching it to a sage session in a terminal. Once a I create an instance of the class via
> `G = FeynmanGraph(...)`
everything seems to work.
Now, I created a module in which I would like to define specific graphs, with specific labeling of the vertices and edges, as well as plot positioning information. Shouldn't I be able to import the module `feynman` and make definitions such as the following?
> `from feynman import *`<br>
> `def FatY(): # a particular graph`<br>
> `G = FeynmanGraph(...)`<br>
> `...`<br>
> `return G`
When I do this, the methods for `FeynmanGraph` raise all kinds of errors of the type where they don't recognize various functions, such as `max` or `partitions_set`.
## Question ##
How do I structure the modules and classes so that I can instantiate the class properly?Sammy BlackFri, 18 Mar 2011 21:23:26 -0500http://ask.sagemath.org/question/8013/