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.Mon, 22 Jul 2019 09:15:08 -0500interact PB on W10 notebook SageMath 8.7http://ask.sagemath.org/question/47221/interact-pb-on-w10-notebook-sagemath-87/HI
on W10 Sagemath 8.7 notebook.
I get an error every time I click on the run button, but the error disappears if I change one of the three values in the little boxes. It looks like the vector is not initialized a first run, what do I need to change ?
@interact
def _(v=('vector', input_grid(1, 3, default=[[1,2,3]], to_value=lambda x: vector(matrix(flatten(x)))))):
print(v.norm())
TypeError: unable to convert ['vector', Grid(value=['vector', Grid(value=[...], children=(Label(value=u'vector'), VBox(children=(EvalText(value=u'1', layout=Layout(max_width=u'5em')),)), VBox(children=(EvalText(value=u'2', layout=Layout(max_width=u'5em')),)), VBox(children=(EvalText(value=u'3', layout=Layout(max_width=u'5em')),))))], children=(Label(value=u'vector'), VBox(children=(EvalText(value=u'1', layout=Layout(max_width=u'5em')),)), VBox(children=(EvalText(value=u'2', layout=Layout(max_width=u'5em')),)), VBox(children=(EvalText(value=u'3', layout=Layout(max_width=u'5em')),))))] to a matrix
but this code above produce no error every time I click on evaluate on https://sagecell.sagemath.org/
my complete code:
from sage.plot.plot3d.plot3d import axes
aL=[2,1,3] # coordinates list of the vector a on which b will be projeted
bL=[3,7,5] # coordinates list vector b (vector example to be projeted)
lL=5/2 # factor expansion to display red line in vector a direction
# here I adopt the convention a vector is a column matrix
A=matrix(QQ,aL).transpose() # matrix(2x1)
print( "P is the B projected vector on vector A ")
print("below all Capital letters are matrices(vectors are matrices),tiny letters are scalars ")
print("E=B-P with P=k*A " ,"E=B-k*A as E perpendicular to A => dot product(A,E)) = 0 means A.transpose()*E=0 " )
print("then A^T*(B-k*A)=0 so k*A^T*A)=A^T*B and k*(A^T*A)^-1 *A^T*A=(A^T*A)^-1 * A^T*B " )
print("so k=(A^T*A)^-1 * A^T*B")
@interact
def _(v=('vector', input_grid(1, 3, default=[[3,7,5]], to_value=lambda x: vector(matrix(flatten(x)))))):
print("vector to be projected x,y,z values",v.row())
print("vector to be projected on vector A norm",v.norm())
bL=v.row()
B=matrix(QQ,bL).transpose() # matrix(2x1)
# Projection Matrix , called Pr
#The general formula for the orthogonal projection onto the column space of a matrix A is
# P = A (A^T A)^(−1) A^T
Pr_num=A * (A.transpose()) # matrix 3x3
Pr_den=(( (A.transpose()) * A ).det()) # scalar
#Pr_den=1 # scalar
#Pr=Pr_num/Pr_den # matrix(3x3)
# other compact form
Pr=A*((A.transpose()*A).inverse() * A.transpose())
show(" A : ",A, " B : ",B, " Pr_num : ",Pr_num, " Pr_den : ",Pr_den, " Pr : ",Pr)
g1=line([[-lL*e for e in A.list()],[lL*e for e in A.list()]], legend_label=' a projection line', legend_color='red',color='red')
g2=plot(vector(B),color="green",width=20,legend_label=' vector b', legend_color='green')
g3=plot(vector(A),color="black",width=3,legend_label=' vector A', legend_color='black')
aT = text3d("a",vector(A)*1.1,color='black',fontsize=20)
bT = text3d("b",vector(B),color='green',fontsize=20)
# projected vector P
P=Pr*B # matrix 3x1
show(" A : ",A, " B : ",B, " projected vector P : ",P )
print "verify that k=(A^T*A)^(-1) * A^T*B = ||P|| / ||A||"
k0=((A.transpose()*A).inverse() * A.transpose()*B).det()
k1=sqrt(((P.transpose()*P).det()/(A.transpose()*A).det()))
print " so P=A*k= A*(A^T*A)^-1 * A^T*B "
show ("P also equals to : A*(A^T*A)^(-1) * A^T*B : ",A*((A.transpose()*A).inverse() * A.transpose())*B )
show( "P= Projection Matrix * B= Pr*B so PR=A*((A.transpose()*A).inverse() * A.transpose() :",A*((A.transpose()*A).inverse() * A.transpose()))
show ( " sqrt(((P.transpose()*P).det()/(A.transpose()*A).det())) = ||P|| / ||A|| : ",k1)
g4=plot(vector(P),color='blue',width=20,legend_label=' projected vector P', legend_color='blue',fontsize=20)
pT = text3d("p",vector(P)*1.1,color='blue',fontsize=40)
E=B-P # matrix 2x1
g5=plot(arrow(P.coefficients(),B.coefficients(),color='pink',width=5,legend_label=' vector e', legend_color='pink'))
eT = text3d("e",vector(E)/2+vector(P)*1.05,color='pink',fontsize=20)
# unit vectors
gx=plot(vector([1,0,0]),color='black',width=5,legend_label='x', legend_color='black')
xT = text3d("x",vector([1,0.1,0.1])*1.1,color='black',fontsize=20)
gy=plot(vector([0,1,0]),color='black',width=5,legend_label='x', legend_color='black')
yT = text3d("y",vector([0.1,1,0.1])*1.1,color='black',fontsize=20)
gz=plot(vector([0,0,1]),color='black',width=5,legend_label='x', legend_color='black')
zT = text3d("z",vector([0.1,0.1,1])*1.1,color='black',fontsize=20)
show(g1+g2+g3+g4+g5+aT+bT+pT+eT+gx+xT+gy+yT+gz+zT+axes(7, color='black') \
,figsize=(6, 6),xmin=-vector(B)[0],xmax=vector(B)[0]+3,ymax=vector(A)[1]+1,ymin=-1,zmax=vector(A)[2]+1,zmin=-1)ortolljSat, 20 Jul 2019 01:40:29 -0500http://ask.sagemath.org/question/47221/Memory leak in Polyhedron?http://ask.sagemath.org/question/47243/memory-leak-in-polyhedron/If I run the following code:
import gc
while True:
P = Polyhedron([[1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1]])
faces = P.faces(3)
del P, faces
print "memory usage: " + str(get_memory_usage()) + ", gc: " + str(gc.collect())
the memory usage keeps increasing.
Do you know what is the cause and how to avoid this problem?GioveMon, 22 Jul 2019 09:15:08 -0500http://ask.sagemath.org/question/47243/Base field of Residue fieldhttp://ask.sagemath.org/question/47239/base-field-of-residue-field/Let $K$ be a number field, $O_K$ be its ring of integers, $p$ prime ideal in $\mathbb{Z}$ and $\mathfrak{p}$ be a prime ideal above $p$. I am trying to construct the $\mathbb{Z}/p\mathbb{Z}$ vector space $O_K/\mathfrak{p}$, and a $\mathbb{Z}/p\mathbb{Z}$ subspace spanned by certain images of elements of $O_K$.
For constructing the prime, I am able to use Q=K.primes_above(p)[0], but I do not know how to view the residue field F=K.residue_field(Q) as the vector space over $\mathbb{Z}/p\mathbb{Z}$.
The command V,fr,to=F.vector_space() indicates $\textbf{ValueError: too many values to unpack}$. Here K= $\mathbb{Q}(\zeta_{11})$ and $p=3$. Can someone suggest me alternative commands for the same.AbhishekMon, 22 Jul 2019 03:22:45 -0500http://ask.sagemath.org/question/47239/Problem with integrating the expression of Mhttp://ask.sagemath.org/question/47240/problem-with-integrating-the-expression-of-m/ Hi. I have the following code that I want to integrate and differentiate, but I am stuck at the expression of M, where it is unable to integrate. Is my coding wrong?
c,t = var('c t')
Pi = RR.pi()
G=integrate(sqrt(1-t^2)*(t+c),t,-0.9,0.9);G
H=G.diff(c);H
L=integrate(-(t+c)/(sqrt(1-t^2)),t,-0.9,0.9);L
M=integrate(1/(sqrt(1-t^2)*(t-c)),t,-0.9,0.9);M #cannot seem to integrate this wrt to t
I=(c^2-1)*(L+(1-c^2)*M);I #equation I that involves M
P=I.diff(c);P #differentiate I wrt to c to obtain equation P
I have tried integrating M by hand which gives me a closed-form involving log function, but I can't seem to integrate it here using Sage.ShaMon, 22 Jul 2019 03:43:22 -0500http://ask.sagemath.org/question/47240/How to use sagemath to generate inequalitieshttp://ask.sagemath.org/question/47238/how-to-use-sagemath-to-generate-inequalities/ In cryptography, sbox is used to substitute a number with another for hiding the original one. For a 4 bit sbox, there will be 16 inputs and 16 outputs. I need to get the inequalities for the sboxjithendrakbMon, 22 Jul 2019 01:26:12 -0500http://ask.sagemath.org/question/47238/How to use sagemath to generate inequalitieshttp://ask.sagemath.org/question/47237/how-to-use-sagemath-to-generate-inequalities/ In cryptography sbox is used to substitute a number with another number(which doesn't have a linear relation to the previous one). So for a 4 bit sbox 16 different inputs give 16 different outputs. I need to get the inequalities of the sbox while giving all the inputs and outputs jithendrakbMon, 22 Jul 2019 01:21:48 -0500http://ask.sagemath.org/question/47237/Plot concave polyhedron defined by inequalities or vertices?http://ask.sagemath.org/question/47235/plot-concave-polyhedron-defined-by-inequalities-or-vertices/I have several sets of 72 inequalities in 3 variables whose solution sets define a possibly concave polyhedron, which I want to visualize. I also have a set of points which defines a concave polyhedron, which I also want to visualize. Is there any way Sage can handle this natively, or at least a direction someone could point me in to accomplish this? I know Sage has a Polyhedron function, but is seems this only plots convex polyhedra.melendezdSun, 21 Jul 2019 17:17:48 -0500http://ask.sagemath.org/question/47235/Generate all the monic polynomials up to degree n with coefficients in Zp(p prime number) field and find all the irriducible polynomialshttp://ask.sagemath.org/question/47178/generate-all-the-monic-polynomials-up-to-degree-n-with-coefficients-in-zpp-prime-number-field-and-find-all-the-irriducible-polynomials/My code.
def POLYNOMIAL_OBTAINED_BY_RECURSION(p,n):
R=Zmod(p)
Z.<x>=PolynomialRing(R)
All=[]
if n==1:
h=[]
for i in range(0,p):
pol=x+i
h.append(pol)
return(pol)
All.append(Set(h))
else :
h=[]
for i in range(0,p):
Pol=POLYNOMIAL_OBTAINED_BY_RECURSION(p,n-1)+i*(x^(n-1))+x^n
h.append(Pol)
return(Pol)
All.append(Set(h))
return(All)
def MYSIEVE(n,All)
for d in range(1,floor(n/2)+1):
for j in range(d+1,n+1):
for polinomio1 in All[j]:
for polinomio2 in All[d]:
if polinomio1%polinomio2==0:
k={polinomio1}
All[j].difference(k)
return(All)
def project(p,n):
if not(is_prime(p)):
print('p is not prime',p)
R=Zmod(p)
Z.<x>=PolynomialRing(R)
All=[]
All=POLYNOMIAL_OBTAINED_BY_RECURSION(p,n)
All=MYSIEVE(n,All)
return(All)AlessandroDeSantisTue, 16 Jul 2019 04:57:01 -0500http://ask.sagemath.org/question/47178/Is there a way to temporarily turn off sage's type checking?http://ask.sagemath.org/question/47227/is-there-a-way-to-temporarily-turn-off-sages-type-checking/ I'm having some difficulties writing sage code to solve linear programming problems using "natural variables", by substituting for them the variables required for MixedIntegerLinearProgram.
The code for "minimize_desired" is what I'd like to do, but it fails during the substitution with the error message "TypeError: no canonical coercion from Linear functions over Real Double Field to Symbolic Ring". What I'd like is for sage to just do the substitution and ignore the lack of coercion.
The code for "minimize_works" works, but I got past the type checking by changing everything to strings and then back into a sage object, which feels like a terrible kludge. However this does illustrate that, despite sage's worries about coercion, everything ends up fine for MixedIntegerLinearProgram.
Is there a way to turn off sage's type checking and just do the substitution?
Thanks,
Mike
Note: I simplified the examples below by eliminating all the code that dealt with constraints.
def minimize_desired(objective):
p = MixedIntegerLinearProgram(maximization=false)
pvar = p.new_variable(real=True, nonnegative=True)
variables=set(objective.arguments())
translation={v:pvar[v] for v in variables}
objective=objective.subs(translation) # FAILS HERE
p.set_objective(objective)
print p.solve()
def minimize_works(objective):
p = MixedIntegerLinearProgram(maximization=false)
pvar = p.new_variable(real=True, nonnegative=True)
variables=set(str(v) for v in objective.arguments())
translation={v:pvar[v] for v in variables}
objective=sageobj(str(objective), translation)
p.set_objective(objective)
print p.solve()
var('x y')
minimize_works(x+y)
print
minimize_desired(x+y)
millermjSat, 20 Jul 2019 19:24:18 -0500http://ask.sagemath.org/question/47227/Why do computations with pi default to symbolic?http://ask.sagemath.org/question/47217/why-do-computations-with-pi-default-to-symbolic/Hello, Sage community,
It is known fact that SageMath uses symbolic computations by default. For example,
sqrt(8)
returns `2*sqrt(2)`. But it is also known that this behavior can be easily changed using decimals, like in the following case:
sqrt(8.0)
which returns `2.82842712474619`.
However, this technique doesn't seem to work with symbolic constants like `pi` and `e`. For example,
80 / pi
returns the expected `80/pi`, but
80.0 / pi
returns `80.0000000000000/pi` instead of the numerical value `25.4647908947033`.
I was wondering why is this the case.
Thanks in advance for your answers!dsejasFri, 19 Jul 2019 16:58:44 -0500http://ask.sagemath.org/question/47217/Why does .remove() seem to take every element out of a list?http://ask.sagemath.org/question/47219/why-does-remove-seem-to-take-every-element-out-of-a-list/I've found that if I define a list
Sage: list1 = [1,2,3]
and then try to remove an element
Sage: list2 = list1.remove(2)
but then
Sage: print(list2)
returns
Nonesum8tionFri, 19 Jul 2019 20:56:46 -0500http://ask.sagemath.org/question/47219/help doesn't show function callhttp://ask.sagemath.org/question/47214/help-doesnt-show-function-call/ Hi,
When I look up matrix.add_multiple_of_row in Sage reference, I get:
> **add_multiple_of_column(i, j, s, start_row=0)**
>
> Add s times column j to column i.
>
> EXAMPLES: ...
If I do ?A.add_multiple_of_row in SageMath (in Jupyter, with the variable A = matrix(...)), I get
> Docstring:
>
> Add s times row j to row i.
>
> EXAMPLES: ...
Note the critical line **add_multiple_of_column(i, j, s, start_row=0)** missing. Is it possible to see the function arguments and usage when using the ? form of help?
Thanks,
ManojmanojtThu, 18 Jul 2019 23:09:26 -0500http://ask.sagemath.org/question/47214/Latex text in notebook and return lineshttp://ask.sagemath.org/question/47202/latex-text-in-notebook-and-return-lines/Hi
is there a way to display a text in notebook with return lines out of this heavy way ?:
show(LatexExpr(r" \
\text{ Late at night, guards on the battlements of Denmark's Elsinore castle}\\ \
\text{are met by Horatio, Prince Hamlet's friend from school.}\\ \
\text{The guards describe a ghost they have seen that resembles Hamlet's father,}\\ \
\text{the recently-deceased king. At that moment, the Ghost reappears,}\\ \
\text{and the guards and Horatio decide to tell Hamlet.}\
"))
ortolljThu, 18 Jul 2019 03:35:03 -0500http://ask.sagemath.org/question/47202/Concatenate two sparse matrices over a Polynomial Ringhttp://ask.sagemath.org/question/47205/concatenate-two-sparse-matrices-over-a-polynomial-ring/ Hi all,
I am wondering if there is a way to concatenate two sparse matrices over a polynomial ring. Here is a toy example that I am testing with:
S.<x,y> = PolynomialRing(QQ,2)
udict = {(0,0):1, (0,1):x, (1,1):y}
vdict = {(0,0):2*x,(1,0):y}
U = matrix(4,4,ud,sparse=True)
V = matrix(4,2,vd,sparse=True)
I would like to make a larger matrix that is $4 \times 6$, that has the block form $[U|V]$. I attempted to use the block_matrix command, but it said that the given number of rows and columns were incompatible with the number of submatrices.
In Python, for a sparse matrix (csr_matrix or coo_matrix), there is the command hstack from scipy.sparse. Is there a similar command where I can concatenate a list of these sparse matrices? This would be ideal for my general problem.
Thank you for your time!BarkThu, 18 Jul 2019 07:00:49 -0500http://ask.sagemath.org/question/47205/How to increase ECL/maxima memory limits in SageMath?http://ask.sagemath.org/question/47203/how-to-increase-eclmaxima-memory-limits-in-sagemath/ I am looking for a symbolic solution of a linear system 10x10. The coefficients and the right-hand sides are symbolic expressions, and it is critical for my. After one hour run with ~5 GB memory consumption I get an error message:
"TypeError: ECL says: Memory limit reached. Please jump to an outer pointer, quit program and enlarge the memory limits before executing the program again."
My Windows-10 PC has 64 GB, so it is definitely not the physical memory limitation. According to my Google search results, there are deliberately tight default memory limits in the Embeddable Common Lisp (ECL), which is used in Maxima. This page
"https://trac.sagemath.org/ticket/6772"
suggests to increase the ECL heap size to 1 GB by adding a line
"(ext:set-limit 'ext:heap-size (* 1024 1024 1024))"
to the file "maxima/src/ecl-port.lisp". I have found this file under "C:\Program Files\SageMath 8.7\runtime\opt\sagemath-8.7\local\share\maxima\5.41.0\src" and added such line with the 8 GB limit (* 2048 2048 2048). This had absolutely no effect, the same error message appeared after the same run time.
I see two such questions answered in this forum. However both answers suggest to reformulate the original problem, which is not what I need. I will appreciate an explanation of how to increase the ECL memory limits in SageMath. Is there something like ".eclrc" configuration file in SageMath? May be, I have to install Maxima standalone and try it there?SevasThu, 18 Jul 2019 04:15:50 -0500http://ask.sagemath.org/question/47203/'Error: Could not fork child process' while opening Sagehttp://ask.sagemath.org/question/47187/error-could-not-fork-child-process-while-opening-sage/ Hello,
SageMath 8.8 worked just fine but for a few days now whenever I open the console I get the following error:
Error: Could not fork child process: Resource temporarily unavailable (-1).
DLL rebasing may be required; see 'rebaseall / rebase --help'.
I reinstalled a few times with no luck. My Windows 10 has been updated recently so perhaps it is something in the latest update that interferes? Appreciate if anyone got around this.
Robert HTue, 16 Jul 2019 13:23:49 -0500http://ask.sagemath.org/question/47187/Sage graph backendhttp://ask.sagemath.org/question/47191/sage-graph-backend/A Sage graph `G` has a backend graph (say `GG`) accessible with the private `_backend` attribute. The later graph refers to two "C-graphs" (say `G1` and `G2`) accessibles via the `c-graph` attribute.
Some code with a weighted graph `G` to illustrate my question :
import string
ALPHA = string.ascii_uppercase
n = 10
wedges = [(0, 1, 7.0), (0, 3, 1.0), (0, 9, 9.0), (1, 7, 6.0), (2, 8, 7.0),
(2, 9, 2.0), (3, 6, 7.0), (4, 9, 5.0), (5, 9, 6.0), (6, 9, 9.0),
(6, 7, 1.0), (7, 8, 9.0), (7, 9, 5.0), (8, 9, 3.0)]
wedges = [(ALPHA[i], ALPHA[j], 10 * w) for (i, j, w) in wedges]
G = Graph()
G.add_edges(wedges)
G.weighted(True)
for v in G:
print v, ''.join(G[v])
print
print "G type:", type(G)
print "-----------------------------"
GG = G._backend
print "GG type:", type(GG)
print list(GG.iterator_verts())
print "-----------------------------"
G1, G2 = GG.c_graph()
print "G1 type:", type(G1)
print
for i in range(n):
print i, ''.join(map(str, G1.out_neighbors(i)))
outputting:
A BDJ
C JI
B AH
E J
D AG
G DJH
F J
I JHC
H BJIG
J AHCIGEF
G type: <class 'sage.graphs.graph.Graph'>
-----------------------------
GG type: <type 'sage.graphs.base.sparse_graph.SparseGraphBackend'>
['A', 'C', 'B', 'E', 'D', 'G', 'F', 'I', 'H', 'J']
-----------------------------
G1 type: <type 'sage.graphs.base.sparse_graph.SparseGraph'>
0 123
1 04
2 07
3 0456789
4 1367
5 36
6 345
7 234
8 3
9 3
The graphs above `G`, `GG` and `G1` have `n=10` vertices. The difference is that G1's vertices are labelled from 0 to `n-1`. As you can imagine, the two graph `G` and `G1` are isomorphic.
So my question is simple: does anybody know how to access the mapping between the vertice sets?
The documentation explains that two dictionaries `vertex_ints` and `vertex_labels` are available to make translation from vertices id to integers and vice-versa, unfortunately, `GG.vertex_ints` and `GG.vertex_labels` cause an attribute error.
As you may see, and contrary to what I was expecting, the correpondance is not $i\mapsto G[i]$.elasticaTue, 16 Jul 2019 14:53:34 -0500http://ask.sagemath.org/question/47191/Matrix multiplication of sparse matrix with matrix over polynomial ringhttp://ask.sagemath.org/question/47196/matrix-multiplication-of-sparse-matrix-with-matrix-over-polynomial-ring/ Hi all,
I would like to know how to multiply the following matrices I have constructed in Sage. Here is my code for a toy example:
from scipy.sparse import csr_matrix
row = [0,0,1]
col = [0,1,1]
data = [1,-1,1]
A = csr_matrix((data,(row,col)),shape=(4,4))
R.<x,y> = PolynomialRing(QQ,2)
B = matrix(R,2,2,[1,x,1,y])
When I try to multiply the matrices using A.dot(B), I end up with the error: "No supported conversion for types: (dtype('int64'), dtype('O'))"
Is there a way I can multiply these matrices and yield an output that is a csr_matrix? (I suspect I would want to convert the entries of my A matrix to be the same data type, but I am unaware of how to do this)
Thank you for your time!
BarkWed, 17 Jul 2019 10:49:28 -0500http://ask.sagemath.org/question/47196/Plotting derivative of bump functionhttp://ask.sagemath.org/question/47169/plotting-derivative-of-bump-function/ I wish to plot the derivative of the piecewise function equal to $\exp((1 - x^2)^{-1})$ on (-1, 1) and 0 everywhere else (just as an example). I attempted this by defining to define in sage
`f(x) = piecewise([(-oo, -1), 0], [(-1, 1), exp(-1/(1 - x^2)), [(1, oo), 0]]`
and then let `g = diff(f(x), x))`. When i try to evaluate g at various values (for example 0.3), I get 0.333237077156224*(0, 0, 0) + 0.333237077156224, and the number that appears is not only incorrect (in that it is not the derivative it ought to equal), but the expression that appears can't be turned into a single number. My ultimate objective is to obtain plots of various linear combinations of such expressions, so what would be the best way to go about doing this? In addition, what exactly is going on here?alpha0Mon, 15 Jul 2019 10:58:12 -0500http://ask.sagemath.org/question/47169/How to define polynomial p(x_i, x_j) while x_i, x_j runs over available variables?http://ask.sagemath.org/question/47167/how-to-define-polynomial-px_i-x_j-while-x_i-x_j-runs-over-available-variables/Let's say I have variables x_1, x_2, ..., x_d, where d is some integer. Let's say I have a polynomial p(a,b) defined. How could I get a list of p(x_i, x_j) where i, j runs over 1, 2, ..., d, possibly with some other qualifiers (i.e. we must have i inequal to j)? I want to define an ideal in this way, but when I get a list I know how to proceed.
Thank you in advance! AnteCMon, 15 Jul 2019 07:42:51 -0500http://ask.sagemath.org/question/47167/Create Matrix in RREF with indeterminateshttp://ask.sagemath.org/question/47185/create-matrix-in-rref-with-indeterminates/Hi all,
I would like to be able to create a Matrix over a multivariable polynomial ring (in particular over R = PolynomialRing(QQ, 'x',(n-k)*n)) in Sage that has a particular form. I would like to create a $k \times n$ matrices that is in RREF form, where I can choose where the pivots should be and fill in the rest with variables from my polynomial ring. (I am assuming full rank, so there will be $k$ pivots with $n \choose k$ possible choices)
$\begin{bmatrix} 1 & x1 & 0 & x2 & \cdots\\\
0 & 0 & 1 & x3 & \cdots\\\
0 & 0 & 0 & 0 &\cdots \\\
\vdots & \vdots & \vdots & \vdots & \ddots \end{bmatrix}$
Is there any way I can do this in Sage by just indicating which columns I want to have the pivots in?BarkTue, 16 Jul 2019 10:36:05 -0500http://ask.sagemath.org/question/47185/sagetex with conda installhttp://ask.sagemath.org/question/47184/sagetex-with-conda-install/ Hi folks, I have sage installed using conda. I can't seem to find the sagetex.sty file on my system which makes me think it wasn't installed. Any suggestions? rhaynes74Tue, 16 Jul 2019 09:08:53 -0500http://ask.sagemath.org/question/47184/make sage use \dfrac instead of \frachttp://ask.sagemath.org/question/47175/make-sage-use-dfrac-instead-of-frac/ For example:
Is it possible to make `latex( (2*x+3) / (2*x) )` return `\dfrac{2 \, x + 3}{2 \, x}` instead of `\frac{2 \, x + 3}{2 \, x}` ?OrangeMon, 15 Jul 2019 19:49:00 -0500http://ask.sagemath.org/question/47175/elliptic curve point multiplicative inversehttp://ask.sagemath.org/question/47179/elliptic-curve-point-multiplicative-inverse/ is that possible to calculate the multiplicative inverse for an elliptic curve point . for example X is a point i need to calculate inverse of X such that X*X^-1 give me unity.Hassan MostafaTue, 16 Jul 2019 05:06:46 -0500http://ask.sagemath.org/question/47179/Numerical approximationhttp://ask.sagemath.org/question/47022/numerical-approximation/ How to write codes for Euler Method, Improved Eulers Method and Runge - Kutta Method in sage for Numerical Approximation
Adil RashidSun, 30 Jun 2019 19:59:46 -0500http://ask.sagemath.org/question/47022/Factorization of multivariate polynomials over complex fieldhttp://ask.sagemath.org/question/47061/factorization-of-multivariate-polynomials-over-complex-field/ Is it possible to factorize multivariate polynomials over complex field?swisti10Thu, 04 Jul 2019 04:46:51 -0500http://ask.sagemath.org/question/47061/(f(g(x)) in Sage? How?http://ask.sagemath.org/question/47148/fgx-in-sage-how/ Hi everybody ! I am a total beginner and want to learn to use Sagemath. How do I write a script that calculates the following (f(g(x)). I thank you in advance for helping me.
Ulfjamt1961Sat, 13 Jul 2019 02:55:35 -0500http://ask.sagemath.org/question/47148/Boost implementation of Dijkstra's algorithmhttp://ask.sagemath.org/question/47138/boost-implementation-of-dijkstras-algorithm/I have benchmarked Dijkstra's algorithm using the Boost Graph library interface provided by SageMath against a basic and academic one but written in pure Python. And the later performs always better. This is very surprising since Boost Graph library is a templated C++ library. Perphaps I'using it in the wrong way. Here is the code :
from time import clock
from heapq import heappush, heappop
def make_graph(n, p):
import networkx as nx
G=nx.erdos_renyi_graph(n, p)
G=nx.relabel_nodes(G, lambda k:'v'+str(k))
edges=list(G.edges())
wedges=[]
for u, v in edges:
w=float(randrange(1, 10))
G[u][v]["weight"]=w
wedges.append((u, v, w))
return G, wedges
def wedges2adjw(nodes, wedges):
"From weighted wedges to weighted adjacency list"
n=len(nodes)
node2int={node:i for (i,node) in enumerate(nodes)}
adj=[[] for _ in range(n)]
for a, b,w in wedges:
i=node2int[a]
j=node2int[b]
adj[i].append((j,w))
adj[j].append((i,w))
return adj, node2int
def dijkstra_int(adj, src):
"""
adj: weighted adjacency lists of a graph with n nodes
vertices indexed fropm 0 to n-1
Returns shortest path list from src to all vertices"""
n=len(adj)
processed=[0]*n
processed[src]=1
distances=[(0,src)]
INF=float("inf")
dist=[INF]*n
dist[src]=0
while distances:
d, u=heappop(distances)
if processed[u]==1:
processed[u]=2
for v,w in adj[u]:
dd=d+w
if processed[v]==0 or dd<dist[v]:
heappush(distances, (dd,v))
dist[v]=dd
if processed[v]==0:
processed[v]=1
return dist
def dijkstra(nodes, wedges, n, src):
adj, node2int=wedges2adjw(nodes, wedges)
int2node={i:node for (node,i) in node2int.items()}
src_int=node2int[src]
return {int2node[i]:d for (i, d) in enumerate(dijkstra_int(adj, src_int)) if d!=float("inf")}
print("------------ Generating Graph --------------------")
debut=clock()
n=3000
p=0.3
Gnx, wedges=make_graph(n, p)
src=sample(Gnx.nodes(),1)[0]
nodes=Gnx.nodes()
gtime=(clock()-debut)
print "Number of nodes:", len(Gnx)
print "Number of edges:", len(Gnx.edges())
print("Graph generation: %.2fs" %gtime)
print("------------ Boost --------------------")
G = Graph()
G.add_vertices(nodes)
G.add_edges(wedges)
G.weighted(True)
debut=clock()
dist_boost = G.shortest_path_lengths(src,by_weight = True, algorithm='Dijkstra_Boost')
boost=(clock()-debut)
print("Boost: %.2fs" %boost)
print("------------ Pure Python --------------------")
debut=clock()
dist_pp=dijkstra(nodes, wedges, n, src)
py_time=(clock()-debut)
print("Pure Python: %.2fs" %py_time)
print"----------"
print "Checking:", dist_boost==dist_pp
Output :
------------ Generating Graph --------------------
Number of nodes: 3000
Number of edges: 1350005
Graph generation: 11.76s
------------ Boost --------------------
Boost: 1.61s
------------ Pure Python --------------------
Pure Python: 1.48s
----------
Checking: True
EDIT
Now, the tested functions have the same interface:
from time import clock
from heapq import heappush, heappop
def make_graph(n, p):
G = Graph()
G.add_vertices(range(n))
G.add_edges([(u, v, float(randrange(1, 10)))
for (u, v, _) in graphs.RandomGNP(n, p).edges()])
G.weighted(True)
return G
def dijkstra(G, src):
adj = [[] for _ in range(len(G))]
for i, j, w in G.edges():
adj[i].append((j, w))
adj[j].append((i, w))
n = len(adj)
processed = [0] * n
processed[src] = 1
distances = [(0, src)]
INF = float("inf")
dist = [INF] * n
dist[src] = 0
while distances:
d, u = heappop(distances)
if processed[u] == 1:
processed[u] = 2
for v, w in adj[u]:
dd = d + w
if processed[v] == 0 or dd < dist[v]:
heappush(distances, (dd, v))
dist[v] = dd
if processed[v] == 0:
processed[v] = 1
return {i: dist[i] for i in G if dist[i] != INF}
print("------------ Generating Graph --------------------")
debut = clock()
n = 3000
p = 0.3
G = make_graph(n, p)
src = randrange(n)
nodes = G.vertices()
gtime = (clock() - debut)
print "Number of nodes:", len(G)
print "Number of edges:", len(G.edges())
print("Graph generation: %.2fs" % gtime)
print("------------ Sage --------------------")
debut = clock()
dist_sage = G.shortest_path_lengths(
src, by_weight=True)
default_time = (clock() - debut)
print("Default: %.2fs" % default_time)
print("------------ Boost --------------------")
debut = clock()
dist_boost = G.shortest_path_lengths(
src, by_weight=True, algorithm='Dijkstra_Boost')
boost_time = (clock() - debut)
print("Boost: %.2fs" % boost_time)
print("------------ Pure Python --------------------")
debut = clock()
dist_pp = dijkstra(G, src)
py_time = (clock() - debut)
print("Pure Python: %.2fs" % py_time)
print "----------"
print "Checking:", dist_sage == dist_boost == dist_pp
print "Time ratio: %.2f" %(py_time/boost_time)
output:
------------ Generating Graph --------------------
Number of nodes: 3000
Number of edges: 1349390
Graph generation: 7.74s
------------ Sage --------------------
Default: 2.23s
------------ Boost --------------------
Boost: 1.53s
------------ Pure Python --------------------
Pure Python: 2.54s
----------
Checking: True
Time ratio: 1.66
By the way, the docs explain about the default implementation:
> (default): Sage chooses the best algorithm: 'BFS' if by_weight is False, 'Dijkstra_Boost' if all weights are positive, 'Bellman-Ford_Boost' otherwise.
This is not consistent with the timing above.
[As explained by David Coudert in the comments, the difference is due to sign checking]elasticaFri, 12 Jul 2019 07:08:13 -0500http://ask.sagemath.org/question/47138/Convert existing notebook to Jupyterhttp://ask.sagemath.org/question/47140/convert-existing-notebook-to-jupyter/ Hi, I try to pass from sagenb to jupyter. I follow the recommandation on trac.sagemath.org
When I run the command
> sage -n export --list
I obtain the following error.
Traceback (most recent call last):
File "/usr/bin/sage-notebook", line 266, in <module>
launcher(unknown)
File "/usr/bin/sage-notebook", line 135, in __init__
os.execvp(SAGENB_EXPORT, [SAGENB_EXPORT] + argv)
File "/usr/lib/python2.7/os.py", line 346, in execvp
_execvpe(file, args)
File "/usr/lib/python2.7/os.py", line 382, in _execvpe
func(fullname, *argrest)
OSError: [Errno 2] No such file or directory
Thanks for your helpfylouFri, 12 Jul 2019 07:09:40 -0500http://ask.sagemath.org/question/47140/How to change the unreadable dark blue colour in the SageMath command line window under Windows-10?http://ask.sagemath.org/question/47136/how-to-change-the-unreadable-dark-blue-colour-in-the-sagemath-command-line-window-under-windows-10/ I have just installed SageMath 8.7 on my Windows-10 laptop and want to learn it. The font colour of the prompt and of the typed numbers is dark blue on the black background, totally unreadable. Google search delivers tons of such complaints about bash/pythin/mintty/cygwin command lines. All suggest to edit some configuration files, which are hardly possible to locate in SageMath, neither in the SageMath installation directory, nor in my user home directory. There is a file ".sage\profile_default\ipython_config.py" in my Windows home, containing the line
c.TerminalInteractiveShell.colors = 'Linux'
Changing this line has no effect.SevasFri, 12 Jul 2019 05:59:10 -0500http://ask.sagemath.org/question/47136/