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.Sun, 26 Nov 2023 21:13:32 +0100Indexes in Linear programminghttps://ask.sagemath.org/question/74509/indexes-in-linear-programming/If you look at the output of this linear program
bomb = MixedIntegerLinearProgram(maximization=True, solver = "GLPK");
x = bomb.new_variable(integer=True, nonnegative=True);
bomb.add_constraint(0.9*x[1]>=200);
bomb.add_constraint(0.9*x[0]+0.27*x[6]>= 0.9*x[1])
bomb.add_constraint(0.8*x[3]+0.24*x[8]>= 0.9*x[1])
bomb.add_constraint(0.135*x[4] + 0.9*x[10]>= 0.9*x[1])
bomb.add_constraint(0.25*x[5] + 0.9*x[11]>= 0.9*x[1])
bomb.add_constraint(x[0]+x[1]+x[2]+x[3]+x[4]+x[5]<=800);
bomb.add_constraint(x[6]+0*x[7]+x[8]+x[9]+x[10]+x[11]<=500);
bomb.set_objective(0.9*x[1])
bomb.show()
you will see that Sagemath doesn't respect the index of the $x[i]$. It enumerate the variables in the order of encounter.
This is terribly perturbating. Is there a way to impose the respect of the indexes ?CyrilleSun, 26 Nov 2023 21:13:32 +0100https://ask.sagemath.org/question/74509/call SageMath from Chttps://ask.sagemath.org/question/69124/call-sagemath-from-c/I wrote a little Graph Theory / Group Theory function in SageMath (using stuff from GAP, mostly), and now I want to call that from a simulation that I have in C. I have worked out how to call Python from C (here, basically: https://docs.python.org/3/extending/embedding.html) but I can't quite get the sage to work. I've tried things like starting the .py file with
#!/usr/local/bin/sage -python
import sage.all
and that got some things running, but it seems like many jobs were being created all at once, and then it just seg faulted. Anyone have experience with this?
[ I will note there is another question just like this on this site: https://ask.sagemath.org/question/54161/to-call-sagemath-program-jupyter-notebook-from-c-program/ ....although I already have a Sage script, so I don't want to actually run a notebook, just the script, and then grab some values back into C]
MWE follows....it doesn't work, but this is what's giving me the behavior. Previously, when this was a .py file instead of .sage (and that "import.sage" was missing), it ran fine.
#include <Python.h>
int main(int argc,char *argv[])
{
float res;
res=(float)call(2,3);
printf("Result of Python script: %f\n",res);
}
int call(int int1,int int2){
long res;
Py_Initialize();
/* Two added lines to get the path right */
PyRun_SimpleString("import sys");
/*PyRun_SimpleString("import sage.all");*/
PyRun_SimpleString("sys.path.append(\".\")");
PyObject* moduleName = PyUnicode_FromString("test_multiply_test");
PyObject* module = PyImport_Import(moduleName);
Py_DECREF(moduleName);
PyObject* functionName = PyObject_GetAttrString(module, "multiply");
PyObject* args =PyTuple_New(2);
PyObject* arg1 = PyLong_FromLong(int1);
PyObject* arg2 = PyLong_FromLong(int2);
PyTuple_SetItem(args, 0, arg1);
PyTuple_SetItem(args, 1, arg2);
PyObject* result = PyObject_CallObject(functionName, args);
/* Check if the call was successful */
if (result != NULL) {
/* Convert the result to a C string */
res = PyLong_AsLong(result);
printf("%ld\n", res);
/* Clean up the result object */
Py_DECREF(result);
} else {
/* Handle the error */
PyErr_Print();
}
Py_DECREF(arg1);
Py_DECREF(arg2);
Py_DECREF(args);
Py_DECREF(result);
Py_DECREF(functionName);
Py_DECREF(module);
Py_Finalize();
return res;
}
Oh, and the python file is
def multiply(a,b):
print("Will compute", a, "times", b)
c = 0
for i in range(0, a):
c = c + b
return ccdustonMon, 12 Jun 2023 17:14:52 +0200https://ask.sagemath.org/question/69124/Code for guessing formula for integer sequencehttps://ask.sagemath.org/question/68486/code-for-guessing-formula-for-integer-sequence/ Hey everyone,
I was wondering if there already exists some code in SageMath for solving a problem of the shape:
Given a sequence A_n of numbers/polynomials/etc, guess a formula for A_n.
E.g. a very basic use-case would be something like
sage: n = SR('n')
sage: guess({1:1,2:4,3:9,4:16,5:25,6:36,7:49}, n)
n^2
sage: R.<a,b> = PolynomialRing(QQ)
sage: guess({1:a+b, 2:a^2 + a*b + b^2, 3:a^3 + a^2*b + a*b^2 + b^3}, n)
(a^(n + 1) - b^(n + 1))/(a - b)
Of course for integer sequences, one approach is to query the Online Encyclopedia of Integer Sequences with the oeis-function. But this will not return a symbolic expression/SageMath function, and would also fail if A_n is e.g. a random polynomial of degree 5 in n.
Apart from finding a symbolic expression as above, other possible outputs could be a generating function or even a Python function.
I have seen that both maple ([example](https://www.maplesoft.com/support/help/maple/view.aspx?path=gfun%2Fguessgf)) and Mathematica ([example](https://reference.wolfram.com/language/ref/FindSequenceFunction.html)) have similar functionality. In this context, I would also be interested in any references to descriptions of algorithms that can be used for such a task.
I realize this is a very open-ended question, so I am very grateful for any pointers to software/literature/etc.Johannes SchmittWed, 17 May 2023 16:27:15 +0200https://ask.sagemath.org/question/68486/How to get selective outputs printedhttps://ask.sagemath.org/question/67158/how-to-get-selective-outputs-printed/After running my code
> -------------------
-------------------
if................
show((x,y,z))
The output is a collection of list of triplets of square matrices of same order.
I want only those output to be printed which contain same set of three matrices, keeping the first matrix fixed.
That is, for example, suppose I am getting the following outputs:
1.[A1,P,Q]
2.[A1,Q,P]
3.[P,Q,A1]
4.[A2,L,M]
5.[A2,M,L]
6.[A2,X,Y]
7.[Q,L,A1]
Now consider the first three outputs . The first two outputs are to be considered same. But the third output is to be considered different, though all three outputs contain same set of matrices. So, first and third need only be printed.. Similarly , as fourth and fifth outputs are same, I want only fourth output to be printed and not the fifth one. And so on…
mak3521Thu, 30 Mar 2023 08:34:25 +0200https://ask.sagemath.org/question/67158/Regarding remove() functionhttps://ask.sagemath.org/question/66881/regarding-remove-function/ I want to remove all symmetric matrices from the list of all possible 0,1 matrices of (say) 2nd order.
When I run this code, not all symmetric matrices are removed. Where am I wrong?`
>
T=Tuples((0,1),4)
W=[matrix(2,2,v) for v in T]
[W.remove(s) for s in W if s.is_symmetric() is true]
show(W)
mak3521Sat, 11 Mar 2023 13:11:21 +0100https://ask.sagemath.org/question/66881/Is there a function for negacyclic matrices?https://ask.sagemath.org/question/66766/is-there-a-function-for-negacyclic-matrices/ I know that circulant matrices are defined in sagemath. I don't know if negacyclic matrices are defined in sagemath.
If not, then how to construct them?sgmthSat, 04 Mar 2023 04:42:38 +0100https://ask.sagemath.org/question/66766/How to speed up this codehttps://ask.sagemath.org/question/65274/how-to-speed-up-this-code/Given a square matrix M, to find (say) five sets of, (say) 4 matrices A1,A2,A3,A4 such that
(i) each Ai is a unique 0,1 or 0,-1 matrix
(ii) each Ai is not - all zeroes or all ones or all minus ones matrix(that is, matrices with all entries same are not allowed)
(iii) M= A1+A2+A3+A4
(iv) Each matrix product AiAj (i,j=1,2,3,4)is a linear combination of A1,A2,A3,A4 with integer coefficients.
This is the same problem which was discussed in :
https://ask.sagemath.org/question/64286/cant-find-error-in-my-code/
But there we wanted “all possible combinations” satisfying the required conditions. There we basically discussed the process for first getting all combinations satisfying (iii) and then checked condition(iv). But for 3rd order and above no output even after one week.
So thought that rather than first collecting all combinations satisfying(iii) it would be better to check (iv) alongside individually and after say, five outputs , the program ends, as even this much would also help me for my work .
I have made the following code:
#Given Matrix
M = matrix(2,2, [1, 2, 2, -1])
show("M=",M)
n = int(input("Enter the order of the matrix M : "))
T = Tuples((0,1),(n^2))
#Removing all-zero and all-one tuples as not needed for our case"
R=T.list()[1:-1]
#Forming n by n matrices from list in R. Contains all {0,1 }matrices.
P = []
for v in R:
P.append(matrix(ZZ,n,n,v))
#Forming all n by n , {0,-1} matrices.
N=[]
for a in P:
b=-a
N.append(b)
test_sum = int(input("In how many matrices you want to break M :"))
num_nonneg = int(input("How many matrices with non-negative entries you want :"))
num_nonpos = (test_sum)-(num_nonneg)
nonneg_comb = Combinations(P, num_nonneg)
nonpos_comb = Combinations(N, num_nonpos )
#Defining a function which converts matrix to vector
def mat_to_vector(m):
return vector( sum(map(list,m.rows()), []), immutable=True )
Counter=0
X = ZZ^(n^2)
for a in nonneg_comb:
for b in nonpos_comb:
flag=0
V = X.span(mat_to_vector((a+b)[i]) for i in range(len((a+b))))
for i in range(test_sum):
for j in range(test_sum):
if( (sum(a+b)!=M) or (mat_to_vector((a+b)[i]*(a+b)[j]) not in V)):
flag=1
if(flag==0):
Counter+=1
show("(",Counter,").", a+b)
if Counter==5:
break;
But this is also time taking for higher orders. So, wanted to know how it can be speeded up or how the code given by Max Alekseyev in the above link can accordingly be edited.sgmthThu, 08 Dec 2022 06:13:33 +0100https://ask.sagemath.org/question/65274/Forming unique collections of matriceshttps://ask.sagemath.org/question/64630/forming-unique-collections-of-matrices/I am facing following two similar kind of problems:
Problem(1) Suppose I have the following code:
A=matrix(2,2,[1,1,1,1])
B=matrix(2,2,[2,2,2,2])
C=matrix(2,2,[3,3,3,3])
D=matrix(2,2,[4,4,4,4])
L1=[A,B,C]
L2=[C,B,A]
L3=[A,C,D]
show(L1,L2,L3)
Then in the output I want L1 and L3 only, as L1 and L2 contain same matrices.
Problem(2): Now suppose we have the following code:
P=matrix(2,2,[5,5,5,5])
Q=matrix(2,2,[6,6,6,6])
R=matrix(2,2,[7,7,7,7])
S=matrix(2,2,[8,8,8,8])
T1=[P,P,Q]
T2=[Q,P,P]
T3=[P,R,S]
show(T1,T2,T3)
Here also, in the output I want T1 and T3 only, as T1 and T2 contain same matrices. Note that I want T1 as it is, that is, P should be there twice.mak3521Wed, 26 Oct 2022 18:51:02 +0200https://ask.sagemath.org/question/64630/How to speed up the code?https://ask.sagemath.org/question/64373/how-to-speed-up-the-code/Given a matrix M, to find all 1,-1 matrices which satisfy the condition given in the code.
For n=3, I am getting the outputs easily. For n=6, it ran for around 12 hours and got "flint exception error".
I understand that len(T) is huge so there might be some memory issues. Is there anyway to get over it?
> n=3
T=Tuples((1,-1),n^2)
A=[matrix(n,n,t) for t in T]
for a in A:
if 3*a^2==M:
show(a)
mak3521Mon, 10 Oct 2022 16:59:47 +0200https://ask.sagemath.org/question/64373/Can't find error in my codehttps://ask.sagemath.org/question/64286/cant-find-error-in-my-code/Please refer to my question at
https://ask.sagemath.org/question/63878/making-code-faster-by-splitting-and-use-of-supercomputer/
According to the suggestion given in the end by Max Alekseyev I have made a complete code. Here I am showing only the initial part , as problem lies in it . I don't know what I am missing or what mistake I have made.
> M = matrix(3,3, [1, 1, 1, -1, 1, 1, -1, -1, 1])
List_S=[M^0,M^1,M^2]
n = 3
V = GF(2)^(n^2)
VL1=V.list()[1:]
# Removing the all-zero list because not needed for our purpose
VL2=VL1[:-1]
#Removing the all-ones list because not needed for our purpose
P=[]
for v in VL2:
P.append(matrix(ZZ,n,n,v))
#Forming n by n matrices from list in VL2. Contains all 0,1 matrices.
N=[]
for p in P:
k=-p
N.append(k)
#Forming n by n matrices from P by taking their negative. Contains all 0,-1 matrices
U = []
for a in P:
U.append(a)
for b in N:
U.append(b)
#Taking union of P and N
show("U=",len(U))
def mat_to_vector(m):
temp = []
for i in range(m.ncols()):
for j in range(m.nrows()):
temp.append(m[i][j])
return(vector(temp))
#Defining a function which converts matrix to vector
CAND=[]
for i in range(len(U)):
List_U=[U[i]]
List_SU=List_S+List_U
W=U[:]
W.remove(W[i])
T=tuple(List_SU)
X = ZZ^(n^2)
Y = X.span(mat_to_vector(T[i]) for i in range(len(T)))
for w in W:
if mat_to_vector(w) in Y:
CAND.append(mat_to_vector(w))
VTM=[matrix(ZZ,n,n,u) for u in CAND]
for b in VTM:
b.set_immutable()
B = set(VTM)
show("B=",len(B))
According to the suggestion, len(B) should come out to be less than len(U).
But it is coming out to be same as len(U). Kindly find the error.sgmthMon, 03 Oct 2022 16:34:28 +0200https://ask.sagemath.org/question/64286/Forming Combinations with conditionshttps://ask.sagemath.org/question/64104/forming-combinations-with-conditions/Suppose B is a finite collection of distinct square matrices of nth order.
And , A a subcollection of B.
I want unique combinations of four distinct elements -three from A and one from B.
I tried this
X=Combinations(A,3)
Y=Combinations(B,1)
for i in range(len(X)):
for j in range(3):
for k in range(len(Y)):
if ((X[i])[j])!=(Y[k]):
show(X[i]+Y[k])
I know problem is with my "if" command.
My question is how to change the “if” command so that none of the matrices in X[i] equals Y[k], so that we get distinct matrices in a combination.
Further, how to get unique combinations.
Thanks.
sgmthTue, 20 Sep 2022 06:47:18 +0200https://ask.sagemath.org/question/64104/Making code faster by splitting and use of supercomputerhttps://ask.sagemath.org/question/63878/making-code-faster-by-splitting-and-use-of-supercomputer/Please refer to my question at the following link:
https://ask.sagemath.org/question/63305/writing-a-matrix-as-a-sum-of-matrices/
There John Palmieri has written a very good code. As the output is huge and hence time-taking(No output even for 4th order matrices with 4 summands even after many days), so I tried to split the code in parts according to the logic given in the following link:
https://ask.sagemath.org/question/45606/divide-combinationsnk-into-multiple-parts-n-1110/
and hence have this code:
def sum_list(length, total):
"""
INPUT:
- length -- how many terms
- total -- desired total
Return list of lists, each of which has ``length`` entries chosen
from {0, 1, -1} and adds up to ``total``.
"""
C = IntegerListsLex(length=length, n=length+total, min_part=0, max_part=2)
return [[a-1 for a in L] for L in C]
def mat_list_NEW(mat, length):
"""
INPUT:
- mat -- matrix, assumed to have entries in {1, -1}
- length -- how many terms
Return list of lists, each of which has ``length`` entries and
adds up to ``mat``, and each entry is either a `(0, 1)` or a `(0,
-1)` matrix.
"""
sum_plus = sum_list(length, 1)
sum_minus = sum_list(length, -1)
old_attempts = []
for x in mat.list():
if x == 1:
sums = sum_plus
elif x == -1:
sums = sum_minus
else:
raise ValueError('each entry of matrix should be 1 or -1')
if not old_attempts: # initial step
new_attempts = set(tuple([(s,) for s in S]) for S in sums)
else:
new_attempts = set()
for mats in old_attempts:
NEW = set()
for S in sums:
new_M = tuple(sorted(M + (s,) for (M, s) in zip(mats, S)))
# keep only entries that correspond to (0,1) or (0,-1) matrices
if all(max(entries) - min(entries) < 2 for entries in new_M):
NEW.add(new_M)
new_attempts.update(NEW)
old_attempts = new_attempts
LOA=list(old_attempts)
P=len(LOA)
N=floor(P/5)
R = range(0,P , N)
c0 = LOA[R[0]:R[0]+N]
#c1 = LOA[R[1]:R[1]+N]
#c2 = LOA[R[2]:R[2]+N]
#c3 = LOA[R[3]:R[3]+N]
#c4 = LOA[R[4]:R[4]+N]
#c5 = LOA[R[5]:R[5]+N]
matrices = [[matrix(mat.base_ring(), mat.nrows(), mat.ncols(), entries) for entries in L] for L in c0]
return (matrices)
mat=matrix(3,3, [1, 1, 1, -1, 1, 1, -1, -1, 1])#Enter your matrix
mat_list_NEW(mat,4)#Specify in how many matrices you want to break it up
In the above link it mentions storing of c0,c1,c2,….in csv file because of memory limitations. I have no idea of csv files. So thought of writing each of ci’s individually (as I have written above in the code) and run codes separately. Kindly guide me how to use csv files to further help in running this code.
Note that in the above code for 3rd order matrix with 4 summands P is 73261 and for 5 summands P is 11740316. And we need for higher order matrices(upto say 30) and summands(upto say10) for which P will be very very huge. Somebody told me that if code is written in parallel, then it will run faster.
Also, I will be using supercomputing facility with the following details:
>
OS: CentOS 7 Hardware Specifications
Type I: Total no. of compute nodes: 420
CPU only nodes: 259
CPU Architecture : Haswell
2x Intel Xeon E5-2680 v3/12-Core(24 cores each)
RAM: 64 GB
-----------------------------------
GPU accelerated nodes: 161
(CPU config same as above + GPU cards)
GPU Architecture : 2x NVIDIA K40 (each)
(12GB, 2880 CUDA cores)
-----------------------------------
High Memory Nodes : 512 GB RAM
12 CPU, 8 GPU nodes
TYPE II:Total no. of compute nodes: 184
CPU only nodes: 144
CPU Architecture : Skylake
2x Intel Xeon G-6148/20 cores(40 cores per node)
RAM: 96 GB
--------------------------------------------
GPU accelerated nodes: 40 (CPU conﬁg same )
GPU Architecture : NVIDIA V100
(32GB,5120 CUDA cores)
1 Nvidia V100 card each GPU node: 17
2 Nvidia V100 cards each GPU node:23
High Memory Nodes : 192 GB RAM
8 CPU, 40 GPU nodes
Requesting for resources will be clear with following examples:
1.Request for 2 chunks with 20 cpus, 2 gpu cards for 2 hrs by mentioning as follows:
" -lselect=2: ncpus=20: ngpus=2 : -lwalltime=02:00:00"
2. Request for 2 chunks i.e. full skylake nodes, 1gpu card for 3 hours by mentioning as follows:
" -lselect=2: ncpus=40: ngpus=1: centos=skylake: -l walltime=03:00:00"
Kindly guide me how to choose the resources viz. lselect, ncpus, ngpus for my code(Please note that the time limit is 168 hours per code)
So kindly guide with respect to the above mentioned points. Thanks.sgmthThu, 01 Sep 2022 17:15:41 +0200https://ask.sagemath.org/question/63878/How to serially number the output ?https://ask.sagemath.org/question/63693/how-to-serially-number-the-output/I want the output of the following code to be serially numbered as
(1)A combination is-------
(2)A combination is -------
(3)A combination is-------
and so on.
The code is :
# Write your matrix
H = matrix(2,2, [1, 1,1, -1])
n = 2 # Enter the order of the matrix H
V = GF(2)^(n^2)
R1=V.list()[1:]
#We are removing the all-zero list because not needed for our purpose
R2=R1[:-1]
#We are removing the all-ones list because not needed for our purpose
A = []
for v in R2:
A.append(matrix(ZZ,n,n,v))
# Forming n by n matrices from list in R2. Contains all 0,1 matrices.
B=[]
for a in A:
b=-a # Forming n by n matrices from A by taking their negative. Contains all 0,-1 matrices
B.append(b)
C = []
for a in A:
C.append(a)
for b in B:
C.append(b) #Union of A and B
test_sum = 4
test_comb = Combinations(C,test_sum)
# Here we are forming all "test_sum"-set combinations from C".
# That is, if test_sum =3, then test_comb, gives all 3 set combinations from C"
for t in test_comb:
if (sum(t)==H):
#Checking which combinations in test_sum give the sum = H and printing those
print("A combination is: ")
show(t)
print("\n")sgmthFri, 19 Aug 2022 04:59:03 +0200https://ask.sagemath.org/question/63693/Is there any way to form combinations in parts ?https://ask.sagemath.org/question/63742/is-there-any-way-to-form-combinations-in-parts/What I want to say will be clear from this.
Suppose I run this code:
T = Tuples((0,1),4)
comb= Combinations(T,5)
show(comb.cardinality())
The output is
4368
My concern is this that I have to use these combinations further in my code.
The problem is that for 4-tuples of (0,1) the processing is instant(because only 4368 combinations), but for 300-tuples
of (0,1) even after many hours it is still processing. So, I was thinking that is it possible to form combinations in parts in different
codes and run these codes separately so that output is faster.
What I mean to say is that, in the above code for example, is it possible that only first, say 10% (that is 437) of the combinations are formed.
Then in another code the next 10%(that is 438th to 974th) combinations are formed and so on. Or is there any other way to make this fastersgmthWed, 24 Aug 2022 13:05:25 +0200https://ask.sagemath.org/question/63742/How to copy huge output in another code?https://ask.sagemath.org/question/63640/how-to-copy-huge-output-in-another-code/ My code gives an output containing lakhs of matrices. I want to use that output in another code.
By "print(sage_input())" command I get the output in the form, which I can manually copy and use it in another code. But the problem is , it is taking a lot of time to manually select the output as the output is huge. Is there any simpler way to do so?sgmthFri, 12 Aug 2022 07:00:19 +0200https://ask.sagemath.org/question/63640/If statement to avoid running GAP structure_descriptionhttps://ask.sagemath.org/question/62818/if-statement-to-avoid-running-gap-structure_description/ I am using the operation structure_description to see if a finitely presented group can be recognized and labeled by Sage. Sometimes, this works fine, for example:
G1=H1/[H1(Rel[i]) for i in range(g+g*len(Y)+len(GG))];G1
Finitely presented group < x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17 | x4*x0^-1*x3, x2*x1*x0, x5^-1*x2^-1*x4^-1, x5*x3^-1*x1^-1, x10*x12^-1*x15, x8*x7*x12, x11^-1*x8^-1*x10^-1, x11*x15^-1*x7^-1, x16*x6^-1*x9, x14*x13*x6, x17^-1*x14^-1*x16^-1, x17*x9^-1*x13^-1, 1, x0, x0^2, x0, x6*x12, x1, x7*x13, x2, x8, x14, x3, x9*x15, x4, x10, x16, x5, x11, x17 >
G1.structure_description()
'C0'
However, in other cases it fails, for example:
G1=H1/[H1(Rel[i]) for i in range(g+g*len(Y)+len(GG))];G1
Finitely presented group < x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17 | x4*x6^-1*x9, x2*x1*x12, x17^-1*x8^-1*x4^-1, x5*x15^-1*x1^-1, x10*x12^-1*x15, x8*x13*x6, x5^-1*x2^-1*x10^-1, x11*x3^-1*x7^-1, x16*x0^-1*x3, x14*x7*x0, x11^-1*x14^-1*x16^-1, x17*x9^-1*x13^-1, 1, x0, x0*x12, x0*x12, x6, x1*x13*x7, x2, x8*x14, x3*x15*x9, x4*x10, x16, x5*x11*x17 >
G1.structure_description()
GAPError: Error, no method found! Error, no 4th choice method found for `StructureDescription' on 1 arguments
So the fact that this happens is very understandable - I understand it as being somehow related to the word problem. But I am running this script for many finite groups, and if this information is available, I want Sage to find it and print it - otherwise skip it. Right now, every time the script hits a case, it just fails and exits.
Is there some kind of if ...structure_description=TRUE I could wrap this line in, so that it only executes if it's going to actually work?thethinkerMon, 13 Jun 2022 16:26:01 +0200https://ask.sagemath.org/question/62818/function changing input valuehttps://ask.sagemath.org/question/59336/function-changing-input-value/The following code is supposed to implement a basic percolation process on a matrix of 0's and 1's. For some reason, it's changing the value of the matrix I input, and I can't figure out why. I'm sure it's a basic error on my part, but if someone can set me straight, I'd appreciate it!
Here's the function I defined:
<pre><code>
n = 4;
def percolate(B):
update = B;
for i in [0..n-1]:
for j in [0..n-1]:
nbr_sum = 0;
if (i==0):
nbr_sum += B[i+1,j];
elif (i==n-1):
nbr_sum += B[i-1,j];
else:
nbr_sum += B[i-1,j]+B[i+1,j];
if (j==0):
nbr_sum += B[i,j+1];
elif (j==n-1):
nbr_sum += B[i,j-1];
else:
nbr_sum += B[i,j-1]+B[i,j+1];
if (nbr_sum > 1):
update[i,j] = 1;
return update;
</code></pre>
When I execute
<pre><code>
Bid = matrix.identity(n);
percolate(Bid)
</code></pre>
I get the expected output
<pre><code>
[1 1 0 0]
[1 1 1 0]
[0 1 1 1]
[0 0 1 1]
</code></pre>
but the value of <code>Bid</code> also changes to the same value (as opposed to continuing to be the n x n identity matrix, as desired).Kyle OrmsbyTue, 12 Oct 2021 19:31:54 +0200https://ask.sagemath.org/question/59336/Mapping points on a cylinder to points on a cone.https://ask.sagemath.org/question/56745/mapping-points-on-a-cylinder-to-points-on-a-cone/My question has two parts.
1) How to map (not project) 3D coordinates from the surface of a cylinder to the surface of a sphere.
In this image the red squares are projections, the blue square is a (one of many possible) mapping.
![Contrasting projection with mapping](https://i.imgur.com/VLo7Nm6.png)
2) How to do this when the cylinder and cone are not concentric; and when their axes are not in the same plane.
By way of better explanation, this view represents a cutting tool (brown; middle left) rotating around its axis (black double-dashed; right) cutting the sides (orange; upper left) into the workpiece blank (green; left).
(The yellow shadow shows the resulting gear after 30 cuts and indexing.)
![Close up view showing the problem](https://i.imgur.com/OJFdQlV.jpg)
This one shows the same thing from the top and side to emphasise the non-orthogonal relationship between the cutting plane and the workpiece.
![Top and front views establishing context](https://i.imgur.com/FnlRsqo.jpg)
Given that I have a set of 3D points that represent the boundary of the cutting tool, I want to mathematically sweep those points around the axis through the workpiece and then map them into the coordinate space of the workpiece.
I've found a paper ([12MB pdf](https://core.ac.uk/display/10365043) that I believe develops the equations to do this, but my math education was long ago and never covered the Differential geometry used in that paper; and is therefore not strong enough to understand enough to be sure.
I would like help to verify that it does what I think it does; and if so, in working out which of the equations therein I need to program to apply the required transformation(s).
I realise that this problem is ill-defined mathematically as presented; and it is asking a lot for people to read a 16 page paper; but any help offered would be most gratefully received.
(I'm a retired engineer and a competent programmer and this project is a purely personal one with no commercial affiliations.)
Thanks Buk.BukTue, 20 Apr 2021 20:55:34 +0200https://ask.sagemath.org/question/56745/Cython / Sage: how to use Static Typing (cdef)?https://ask.sagemath.org/question/56519/cython-sage-how-to-use-static-typing-cdef/I'm looking at Sage developer guide for Cython:
https://doc.sagemath.org/html/en/developer/coding_in_cython.html
But I cannot find information about how to use static typing, which is what enables Cython (not necessarily in the context of Sage) to reach C-like performance. Since objects in Sage often have complicated types (expressions, polynomials), how would type declarations (cdef in Cython) work?
P.S. Does Cython have some type inference capability (like the "auto" keyword in C++) so the user can avoid typing long type names?greatpetTue, 06 Apr 2021 13:01:20 +0200https://ask.sagemath.org/question/56519/Error with matrix definition of a linear programhttps://ask.sagemath.org/question/55970/error-with-matrix-definition-of-a-linear-program/ According to the folloing tract `https://trac.sagemath.org/ticket/16714`
this command works
p = MixedIntegerLinearProgram()
x = p.new_variable()
p.add_constraint(A_matrix*x <= a_vector)
so why the following code returns an error ?
A=[[1,0,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,0,0,1,0,0,0,0,0],[0,0,1,0,0,0,0,0,0,1,0,0],[0,0,0,0,1,0,0,1,0,0,0,0],[0,0,0,0,0,1,0,0,0,0,1,0],[0,0,0,0,0,0,0,0,1,0,0,1]]
U1=[1,1,1,1,1,1]
show(matrix(A))
show(vector(U1))
p = MixedIntegerLinearProgram(binary = true)
x = p.new_variable()
p.add_constraint(A*x <= U1)
p.show()
CyrilleMon, 01 Mar 2021 12:04:34 +0100https://ask.sagemath.org/question/55970/Integer programming bi-indexed variables.https://ask.sagemath.org/question/55872/integer-programming-bi-indexed-variables/Many integer programming programs as the following needed for Kemeny ranking
$$
\begin{array}{c}
\text{minimiser} \sum_{i,j \in \mathcal{A}}\omega_{i,j} x_{i,j}+\omega_{j,i} x_{j,i}\\\\
\text{sous les contraintes} \\\\
x_{i,j}+ x_{j,i} = 1, \forall i \not=j\\\\
x_{i,j}+ x_{j,k}+ x_{k,i}\geq 1, \forall i \not=j\not=k\not=i
\end{array}
$$
I want to construct a function wich takes the vector or the list $\omega$ and return the solution. But to construct such a function iot will be safer for me not to be obliged to assign on variable with a index to all two indexed variables.
Is there a way ? My problem is in the enumeration of the constraints for high indexes.CyrilleWed, 24 Feb 2021 10:41:01 +0100https://ask.sagemath.org/question/55872/Warning against a deprecated functionhttps://ask.sagemath.org/question/51576/warning-against-a-deprecated-function/ When programming the following code
def varelmat(M) :
return sum((vector(M)).apply_map((x-(sum(vector(M)))/len(vector(M)))^2))/len(vector(M))
and applying it
B= random_matrix(QQ, 7,7)
varelmat(B)
I end with the following warning
`/opt/sagemath-9.0/local/lib/python3.7/site-packages/sage/repl/ipython_kernel/__main__.py:3: DeprecationWarning: Substitution using function-call syntax and unnamed arguments is deprecated and will be removed from a future release of Sage; you can use named arguments instead, like EXPR(x=..., y=...)
See http://trac.sagemath.org/5930 for details.
IPKernelApp.launch_instance(kernel_class=SageKernel'
Could some one explain me how to keep my code save ?CyrilleWed, 27 May 2020 11:33:48 +0200https://ask.sagemath.org/question/51576/Some code gives error in sagemath 9 but OK in 8.9https://ask.sagemath.org/question/50204/some-code-gives-error-in-sagemath-9-but-ok-in-89/After I upgraded to sagemath 9.0 some of the code that used to work now gives error. The code was used to obtain an estimate of size of expression.
>sage --version
SageMath version 9.0, Release Date: 2020-01-01
>which sage
/bin/sage
It looks like sagemath 9 now uses python 3.0 while 8.9 used python 2 (since I had to change all my print statements to use () to make them work.
Here is an example of function that now gives an error. This is in file, say `bug_sage.py`
#!/usr/bin/env sage
from sage.all import *
def tree(expr):
if expr.operator() is None:
return expr
else:
return [expr.operator()]+map(tree, expr.operands())
var('x')
tree(x*e**((x*log(x) + 1)/log(x)))
Now from command line at Linux, I type `sage ./bug_sage.py` and it gives the error
Traceback (most recent call last):
File "./bug_sage.py", line 12, in <module>
print (tree(x*e**((x*log(x) + 1)/log(x))))
File "./bug_sage.py", line 9, in tree
return [expr.operator()]+map(tree, expr.operands())
TypeError: can only concatenate list (not "map") to list
In 8.9, no error is generated.
It looks like this is due to change in Python itself? This function is meant to generate list of all operands in expression in order to estimate the size of the expression. It is later used as follows
len(flatten(tree(anti)))
Any idea how to fix it? Or do you suggest better way to obtain size of expression (called leaf count in other CAS systems).
NasserMon, 09 Mar 2020 21:52:26 +0100https://ask.sagemath.org/question/50204/Should I avoid using unicode in names of variables?https://ask.sagemath.org/question/49370/should-i-avoid-using-unicode-in-names-of-variables/ Hello, Sage community!
Since Sage now supports Python 3, the possibility of using tildes and other unicode letters in names of variables is real. For example, I could define a constant `Gauß` instead of `Gauss` (with a "ß" instead of "ss"); or I could define a function called `Müller` (with two dots over the "u"). In Spanish and other languages, this is a more pressing matter. If I defined a function `design(howMany)`, in Spanish it would be `diseño(cuántos)`.
However, it seems quite strange to have tildes, betas, etc. in variable names. Is it a good programming behavior to avoid this kind of names?, or, should I use them sparely?
Thanks in advance!dsejasSun, 05 Jan 2020 02:23:51 +0100https://ask.sagemath.org/question/49370/Running Python code from Jupyter and transforming it in a Sage functionhttps://ask.sagemath.org/question/48995/running-python-code-from-jupyter-and-transforming-it-in-a-sage-function/ I would like to know if it is possible to run a python code directly within a notebook and transform it in a sagemath function. The problem is that I am nearly sure that is possible, but I do not know how to install it --- I am under windows an a poor programmer.
For instance if some one has to kindness to take as an exemple https://github.com/fordc5/PrisonersDilemmaCSWorkshop, it will be great.CyrilleWed, 11 Dec 2019 10:01:06 +0100https://ask.sagemath.org/question/48995/Functions in GAPhttps://ask.sagemath.org/question/48711/functions-in-gap/ How can i write special numbers(Mersenne, Fibonacci etc.) or the average or the GCD's two different algorithm in GAP(Group, Algebra and Programming)?
hayyambeyTue, 12 Nov 2019 21:30:04 +0100https://ask.sagemath.org/question/48711/How do I write and implement a program in Sage for Windows?https://ask.sagemath.org/question/48422/how-do-i-write-and-implement-a-program-in-sage-for-windows/ I downloaded Sage 8.9 for Windows and want to use it to do some matrix computations. I do not have any prior experience in programming. So far I've been able to use the SageMath 8.9 Console to declare variables, define matrices, and multiply them together. But I want to write a program which does these computations successively and have SAGE implement it, rather than me typing in the commands one at a time.
I haven't been able to find how to do this in any tutorials. I don't understand where exactly I should be writing the code, how to save the file, how to get SAGE to read the program I wrote and implement it. D_SSat, 19 Oct 2019 05:29:30 +0200https://ask.sagemath.org/question/48422/Adapt the nauty_directg functionhttps://ask.sagemath.org/question/48275/adapt-the-nauty_directg-function/Dear reader,
For a research interest, I would like to generate the collection of non-isomorphic digraphs on a given graph, with a given subset of the edges fixed. Naturally, simply generating the full collection using digraphs.nauty_directg() and removing the undesirable members of the obtained collection would be functional, but it's quite the waste of computing time to take this approach. Hence, I was wondering whether I'd be able to get under the hood of the nauty_directg function to create my own adapted version, which simply skips over the orientation of the edges listed in some input argument. Would anyone be able to help me get started with this endeavor?
Best,
PepijnPepijnWissingFri, 11 Oct 2019 13:01:38 +0200https://ask.sagemath.org/question/48275/How to create a "sage program" with command line inputhttps://ask.sagemath.org/question/44708/how-to-create-a-sage-program-with-command-line-input/I am completely new to Sage and Pyhton, so this is probably a very trivial question, but I am not able to find any answer. I have a file script.sage
N=10
sage_command1
sage_command2
sage_command3
print(result)
I use this script via `sage script.sage` and it does what I want. How can I modify this so that I can pass the variable `N` in the command line? Something like `sage script.sage 10` and then it prints the result.
Thank you!RiccardoTue, 18 Dec 2018 23:35:35 +0100https://ask.sagemath.org/question/44708/Using multiple lines of pari/gp code in a Sage notebookhttps://ask.sagemath.org/question/41758/using-multiple-lines-of-parigp-code-in-a-sage-notebook/I am struggling to get multiple lines of pari/gp code working in a Jupyter Sage notebook.
When I enter:
%%gp
for(x=1,10,print(x))
it all works fine, however when I for instance write:
%%gp
for(x=1,10,{
print(x);
})
the system just 'hangs' and doesn't return any output. The same issue occurs in the Cocalc Sage cloud environment. I also tried 'pari/gp in your browser' and there it works fine.
Am I doing something wrong or isn't the multi-line pari/gp option supported in Sage?RuudHSun, 25 Mar 2018 22:58:41 +0200https://ask.sagemath.org/question/41758/