-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdr.mpl
More file actions
1880 lines (1594 loc) · 72.7 KB
/
dr.mpl
File metadata and controls
1880 lines (1594 loc) · 72.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Dixon Resultant Package
# Author: Manfred Minimair
# E-mail: manfred@minimair.org
# Released under GPL Version 3
# Copyright (C) Manfred Minimair, 2015";
DR := module()
export DixonResultant, DixonPolynomial, DixonMatrix, RankSubMatrix, DixonExtract,
#Sub-modules
Info, Extract, DF, DRes, GenPoly, Samples;
local MonomialCoeff, PolynomialToMatrix;
description
"Dixon Resultant Computation.",
"Date: 10/9/15, Version 2.1",
"Author: Manfred Minimair",
"Additional contributors: Arthur Cherba, Hoon Hong",
"E-mail: manfred@minimair.org",
"Released under GPL Version 3",
"Copyright (C) Manfred Minimair, 2015";
DixonResultant := proc(pols::list(polynom), vars::list(symbol))
description
"Compute the Dixon resultant.",
"pols::list(polynom) ... list of (d+1) polynomials",
"vars::list(symbol) ... list d variables of pols"
"Return the Dixon resultant of pols.";
return DRes:-RankMaxMinorPivotRow(pols, vars);
end proc;
DixonExtract := proc(M::Matrix)
description
"Extract the Dixon resultant from a Dixon matrix."
"M ... Dixon matrix",
"Return message, expression. If message is empty then the expression is the Dixon resultant of pols Otherwise message is an error message and the expression is only a factor of the Dixon resultant.";
return Extract:-MaxMinorElim(M);
end proc;
RankSubMatrix := proc(M::Matrix, {params::list:=[]})
description
"Extract a maximal-rank minor of a parametric matrix.",
"M ... parametric matrix",
"params ... parameters of M",
"Return a maximal-rank minor of the parametric matrix M with high likelihood. If params is empty, the parameters will be automatically determined.";
return Extract:-RankSubMatrix(M, parameters=params);
end proc;
DixonPolynomial := proc(pols::list(polynom), vars::list(symbol), auxVars::list(symbol):=[])
local nVars, nPols, new_vars, CM, i, j, dv, dixp;
description
"Compute the Dixon polynomial.",
"pols ... list of (d+1) polynomials (different order just changes sign)",
"vars ... list d variables (different order produce completely different polynomials!)",
"auxVars ... list of d new variables. If it is empty, the new variables will be automatically generated.",
"Returns dixPol,newVarList, vars,",
"where dixPol is the expanded Dixon polynomial, vars is copied from the input parameter vars and newVarList is the list of d new variables used by the Dixon polynomial.";
#Implementation:
#Expands cancelation matrix using maple LinearAlgebra, det function.
#Examples:
# dixPol, newVarList, vars := DixonPolynomial(myPolSystem, [x, y]);
# (inewVarList = [x_, y_], vars = [x, y])
# dixPol, newVarList, vars := DixonPolynomial(myPolSystem, [x, y],[alpha, beta]);
# (newVarList = [alpha, beta], vars = [x, y])
# Author: A. Cherba, 2003
# Modified: M. Minimair, 5/18/2015
nPols := nops(pols);
nVars := nops(vars);
if not(nPols = nVars + 1) then
ERROR(`Number of equations should be number of variables plus one, but number of equations is %1 and number of vairables is %2`, nPols, nVars);
end if;
if auxVars=[] then
new_vars := [seq(cat(vars[i],`_`),i=1..nVars)];
else
new_vars := auxVars;
end if;
#print(new_vars);
# Construct Cancelation Matrix
CM := Matrix(nPols,nPols);
for i from 1 to nPols do
for j from 1 to nPols do
if (i = 1) then
CM[i,j] := pols[j];
else
CM[i,j] := subs(vars[i-1]=new_vars[i-1], CM[i-1,j]);
end if;
end do;
end do;
# Now, divide the determinant by the product of (vars[i-1] - new_vars[i-1]).
# This is accomplished by subtracting ith row from the (i+1)^th, and
# dividing the result by (vars[i-1] - new_vars[i-1]).
for i from nPols by -1 to 2 do
dv := (vars[i-1] - new_vars[i-1]);
for j from 1 to nPols do
CM[i, j] := simplify((CM[i, j] - CM[i-1, j])/dv);
end do;
end do;
#print("CM", CM);
#dixp := expand(LinearAlgebra:-Determinant(CM), method=fracfree): # Dixon Polynomial
dixp := expand(LinearAlgebra:-Determinant(CM)): # Dixon Polynomial, let Maple choose the most appropriate method
return dixp, new_vars, vars;
end proc:
MonomialCoeff := proc(f, vs, m)
local v, i, n, zero, x, k;
description
"Coefficient of a monomial in a polynomial.",
"f ... polynomial",
"vs ... list of variables of f or a single variable",
"m ... monomial in variables vs",
"Return the coefficient of m in f.";
if type(vs, list) then
v := vs;
else
v := [vs];
end if;
k := [];
for x in v do
k := [op(k), degree(m, x)];
end do;
n := nops(v);
zero := [seq(0, i=1..n)];
return coeftayl(f, v=zero, k);
end proc:
PolynomialToMatrix := proc(pol::polynom, rowVars::list(name), colVars::list(name), roworder, colorder)
local rowPols, nRows, nCols, rowMon, colMon, rowMonS, colMonS,
Arow, Acol, Trow, Tcol,
M, i, j, allVars, p, mon;
description
"Convert a polynomial to a coefficient matrix.",
"pol ... polynomial to be converted",
"rowVars ... polynomial variables for the row indices of the matrix",
"colVars ... polynomial variables for the collumn indices of the matrix",
"roworder ... polynomial ordering for the row monomials, compatible with Groebner:-MonomialOrder",
"colorder ... polynomial ordering for the column monomials, compatible with Groebner:-MonomialOrder",
"Returns matrix, rowMons, colMons,",
"where matrix is the coefficient matrix, rowMons and colMons are the monomials indexing the rows and respectively columns of the matrix.";
p := pol;
rowPols := [coeffs(collect(p, rowVars, distributed), rowVars, 'rowMon')];
nRows := nops(rowPols);
rowMon := [rowMon];
coeffs(collect(p, colVars, distributed), colVars, 'colMon');
colMon := [colMon];
nCols := nops(colMon);
Arow := Ore_algebra:-poly_algebra(op(rowVars));
Trow:=Groebner:-MonomialOrder(Arow, roworder(op(rowVars)));
Acol := Ore_algebra:-poly_algebra(op(colVars));
Tcol:=Groebner:-MonomialOrder(Acol, colorder(op(colVars))):
colMonS := sort(colMon, (t1,t2)->Groebner:-TestOrder(t1,t2, Tcol));
rowMonS := sort(rowMon, (t1,t2)->Groebner:-TestOrder(t1,t2, Trow));
allVars := [op(rowVars), op(colVars)];
p := collect(p, allVars, distributed);
M := Matrix(nRows, nCols);
for i from 1 to nRows do
for j from 1 to nCols do
mon := rowMonS[i] * colMonS[j];
M[i, j] := MonomialCoeff(p, allVars, mon);
end do;
end do;
return M, rowMonS, colMonS;
end:
DixonMatrix := proc(dixonPoly, rowVars, colVars, roworder:=tdeg, colorder:=tdeg)
local dixMat, rowMons, colMons, outRowMons, outColMons, outRowVars, outColVars;
description
"Compute the Dixon matrix of a Dixon polynomial.",
"dixonPoly ... Dixon polynomial",
"rowVars ... variables for monomials to index the Dixon matrix rows",
"colVars ... variables for monomials to index the Dixon matrix columns",
"roworder ... ordering of the row monomials indexing the Dixon matrix, compatible with Groebner:-MonomialOrder",
"colorder ... ordering of the column monomials indexing the Dixon matrix, compatible with Groebner:-MonomialOrder",
"Return matrix, rowMons, rowVars, colMons, colVars,",
"where matrix is the Dixon matrix, rowMons and colMons are the monomials indexing the rows and respectively columns of the matrix";
dixMat, rowMons, colMons := PolynomialToMatrix(dixonPoly, rowVars, colVars, roworder, colorder);
if type(infolevel[DR], numeric) and infolevel[DR]>=2 then
printf(" %a: Dixon matrix of size %d x %d.\n", procname, LinearAlgebra:-RowDimension(dixMat), LinearAlgebra:-ColumnDimension(dixMat));
end if;
return dixMat, rowMons, rowVars, colMons, colVars;
end proc:
###########################################################################################################################
Info := module()
export System, OpenFile, SaveStart, SaveEnd, RunMeasure, DixonMatrix, Extraction, Measure, Rank;
description
"Various functions to gather information about the computation.",
"Author: Manfred Minimair",
"E-mail: manfred@minimair.org",
"Released under GPL Version 3",
"Copyright (C) Manfred Minimair, 2015";
OpenFile := proc(fname::string, {header::truefalse:=true, discard::truefalse:=true})::filedesc;
local fh;
description
"OPen file to write computational data.",
"fname ... name of the file",
"header ... if true, print a csv header into the file",
"discard ... if true, delete the file if it exists before opening a new file",
"Return the file descriptor of the file.";
if discard then
if FileTools:-Exists(fname) then
#printf("%s found\n", fname);
fclose(fname);
FileTools:-Remove(fname);
end if;
end if;
fh := fopen(fname, APPEND, TEXT);
if header then
fprintf(fh, "\"name\",\"numVars\",\"degrees\",\"numParams\",\"paramDegrees\",\"extractor1\",\"extractor2\",\"rows\",\"columns\",\"rank\",\"memory\",\"time\"");
fflush(fh);
end if;
return fh;
end proc;
SaveStart := proc(fh::filedesc, t::table)
description
"Save initial data.",
"fh ... file descriptor of output file",
"t ... table wit data";
fprintf(fh, "\n\"%s\",%d,\"%s\",%d,\"%s\"",
t["system"]["name"],
t["system"]["numVars"],
convert(t["system"]["degrees"], string),
t["system"]["numParams"],
convert(t["system"]["paramDegrees"], string));
fflush(fh);
end proc;
SaveEnd := proc(fh::filedesc, t::table)
local extr2;
description
"Save remaining data.",
"fh ... file descriptor of output file",
"t ... table wit data";
if nops(t["DixonExtraction"]["extractor"])>1 then
extr2 := t["DixonExtraction"]["extractor"][2];
else
extr2 := "None";
end if;
fprintf(fh, ",\"%s\",\"%s\",%d,%d,%d,%.3f,%.6f",
t["DixonExtraction"]["extractor"][1],
extr2,
t["DixonMatrix"]["rows"],
t["DixonMatrix"]["columns"],
t["DixonMatrix"]["rank"],
t["DixonExtraction"]["memory"],
t["DixonExtraction"]["time"]);
fflush(fh);
end proc;
System := proc(sysName::string, numVars::integer, degrees, numParams::integer:=undefined, paramDegrees:=undefined)
local measures;
description
"Polynomial system information.",
"numVars ... number of variables",
"degrees ... list of degrees or degree vectors of the system",
"numParams ... number of parameters",
"paramDegrees ... list of degrees or degree vectors of the parameters of the system",
"Return a table with the inormation.";
measures["system"] := table();
measures["system"]["name"] := sysName;
measures["system"]["numVars"] := numVars;
measures["system"]["degrees"] := degrees;
if numParams=undefined then
measures["system"]["numParams"] := 0;
else
measures["system"]["numParams"] := numParams;
end if;
if paramdDgrees=undefined then
measures["system"]["paramDegrees"] := 0;
else
measures["system"]["paramDegrees"] := paramDegrees;
end if;
return measures;
end proc;
RunMeasure := proc(fh::filedesc, fun::{procedure, function}, sysName::string, f::list, deg::{list, integer}, vars::list, paramDeg::integer, params::list)
local t, dr;
description
"Run a function and store performance measures in a file.",
"fh ... file descriptor of csv file to append peformance measures, according to SaveStart and SaveEnd",
"sysName ... name of the polynomial system",
"fun ... function to run, usually Dixon resultant computation",
"f ... polynomial system",
"deg ... degree list or degree in the variables of the system",
"vars ... list of variables of the system",
"paramDeg ... total degree of the parameters of the system",
"params ... list of parameters of the system",
"Return a table with the performace measure, as prduced by DRes:-ComposeDixon.";
printf("%s\n", convert(fun, string));
t := DR:-Info:-System(sysName, nops(vars), deg, nops(params), paramDeg):
DR:-Info:-SaveStart(fh, t):
dr := fun(f, vars, t):
DR:-Info:-SaveEnd(fh, t):
printf("%.6f\n", t["DixonExtraction"]["time"]);
unassign('dr'):
gc();
return eval(t);
end proc:
DixonMatrix := proc(measures::{undefined, name, table}:=undefined)
description
"Gather and store information about the Dixon matrix.",
"measures ... table where the information about the Dixon matrix will be stored: number of rows and columns and rank",
"Return a function with input matrix M that returns M.";
return
proc(M::Matrix)
description
"M ... Dixon matrix",
"Return the matrix M.";
if measures<>undefined then
measures["DixonMatrix"]["rows"] := LinearAlgebra:-RowDimension(M);
measures["DixonMatrix"]["columns"] := LinearAlgebra:-ColumnDimension(M);
measures["DixonMatrix"]["rank"] := Rank(M);
end if;
return M;
end proc;
end proc;
Extraction := proc(extractorList::list, measures::{undefined, name, table}:=undefined)
description
"Store the extraction time and the name of the function used for Dixon resultant extraction.",
"extractorList ... list of functions that are composed to extract the Dixon resultant from the Dixon matrix.",
"measures ... table where the information about the Dixon matrix will be stored: number of rows and columns and rank",
"Return a function that returns its own input.";
return
proc()
description
"Return the sequence of inputs to this function.";
local e, extractorName;
if measures<>undefined then
measures["DixonExtraction"] := table();
measures["DixonExtraction"]["time"] := 0.0;
measures["DixonExtraction"]["memory"] := 0.0;
measures["DixonExtraction"]["extractor"] := [];
for e in extractorList do
extractorName := convert(e, string);
measures["DixonExtraction"]["time"] := measures["DixonExtraction"]["time"] + measures[extractorName]["time"];
measures["DixonExtraction"]["memory"] := measures["DixonExtraction"]["memory"] + measures[extractorName]["memory"];
measures["DixonExtraction"]["extractor"] := [op(measures["DixonExtraction"]["extractor"]), extractorName];
measures["DixonExtraction"][extractorName] := table(measures[extractorName]);
measures[extractorName] := evaln(measures[extractorName]);
end do;
end if;
return _rest;
end proc;
end proc;
Measure := proc(fun, measures::{undefined, name, table}:=undefined)
description
"fun ... procedure to be timed and whose byte usage is to be collected",
"Measure the execution time of a function.",
"measures ... output parameter, a table. If measures is a name then a table will be assigned to it. If measures is undefined then no timing will be produced.",
"other paramters ... will be passed as inputs to fun",
"Return a function that returns the output of fun and assigns the timing to the table measures with key convert(fun, string).";
return
proc()
local result, usageResults, usedTime, usedBytes, funName;
if measures=undefined then
result := fun(_passed);
else
usageResults := CodeTools:-Usage(fun(_passed), output = ['cputime', 'bytesused', 'output'], quiet = true);
usedTime := usageResults[1];
usedBytes := usageResults[2];
result := usageResults[3..nops([usageResults])];
funName := convert(fun, string);
measures[funName]["time"] := usedTime/60.0;
measures[funName]["memory"] := usedBytes/(1024.0*1024.0);
end if;
#print([result]);
return result;
end proc;
end proc;
Rank := proc(M::Matrix, tries::integer:=10, params::list(name):=[])
local rows, cols, maxseq, count, varLst, rk, ultimateRank, Ms;
description
"Determine the rank of a parametric matrix.",
"M ... matrix with parametric entries",
"tries ... number of times the matrix parameters should be instantiated with random numbers and instantiated matrix should have the same rank",
"params ... optional list of parameters of matrix, if absent then automatically determined",
"Return the rank (with high probability) of the parametric matrix M";
(rows, cols) := LinearAlgebra:-Dimension(M);
maxseq := tries;
if params=[] then
varLst := indets(M);
else
varLst := params;
end if;
randomize();
ultimateRank := -1;
count := 0;
while count<=maxseq do
Ms := Extract:-InstantiateMatrix(M, varLst);
#printf("Ms; %a\n", Ms);
rk := LinearAlgebra:-Rank(Ms);
#printf("rk: %a\n", rk);
if rk <> ultimateRank then
ultimateRank := rk;
count := 0;
else
count := count + 1;
end if;
end do;
return ultimateRank;
end proc:
end module;
###########################################################################################################################
Extract := module()
export RankSubMatrix, MapleDet, MaxMinorElim, MaxMinorElimFull, InstantiateMatrix;
local notFullRankMsg, IsNonZeroRow, PermutationFromMatrix,
ColNumersFactors, ColDenomsFactors, RowNumersFactors, RowDenomsFactors;
description
"Various functions used in extracting the Dixon resultant from the Dixon matrix.",
"Author: Manfred Minimair",
"E-mail: manfred@minimair.org",
"Released under GPL Version 3",
"Copyright (C) Manfred Minimair, 2015";
RankSubMatrix := proc(M::Matrix, {parameters::list:=[]})
local rows, cols, varLst, substLst, i, j, Ms, Um, Pm, perm, indepRows, indepCols;
description
"Extract a maximal-rank minor of a parametric matrix.",
"M ... parametric matrix",
"parameters ... parameters of M",
"Return a maximal-rank minor of the parametric matrix M with high likelihood. If params is empty, the parameters will be automatically determined.";
# Author: M. Minimair, 5/18/2015
# Based on function RSC by A. Chtcherba, 2003
(rows, cols) := LinearAlgebra:-Dimension(M);
if parameters = [] then
varLst := indets(M);
else
varLst := [op(parameters)];
end if;
#printf("varLst: %a\n", varLst);
#printf("Rank of M: %d\n", Info:-Rank(M));
Ms := InstantiateMatrix(M, varLst);
#printf("Rank of Ms: %d\n", LinearAlgebra:-Rank(Ms));
Pm, Um := LinearAlgebra:-LUDecomposition(Ms, output=['P', 'U']);
#printf("Rank of Um: %d\n", LinearAlgebra:-Rank(Um));
perm := PermutationFromMatrix(Pm);
indepRows := [];
indepCols := [];
for i from 1 to rows do
j := IsNonZeroRow(Um, i, i);
if j>0 then
indepRows := [op(indepRows), perm(i)];
indepCols := [op(indepCols), j];
else
#Matrix is upper triangular
break;
end if;
end do;
#return indepRows, indepCols;
return LinearAlgebra:-SubMatrix(M, indepRows, indepCols);
end proc:
notFullRankMsg := "Dixon sub-matrix does not have full rank. Rerun the computation.\n";
MapleDet := proc(A::Matrix)
local n, m, det;
description
"Compute the determinant of a matrix with Maple's determinant function.",
"A ... given matrix",
"Return lowerRank::string, the determinant of A. non-empty message iff the determinant is 0 and A is not empty.";
n, m := LinearAlgebra:-Dimension(A);
if n=0 or m=0 then
return "", 0;
else
det := LinearAlgebra:-Determinant(A);
if det=0 then
return notFullRankMsg, 0;
else
return "", det;
end if;
end if;
end proc;
ColNumersFactors := proc(B, d, r, n, c, m)
local jj, g, ii, updated;
description
"Extract common factors from numerators of enries in matrix columns."
"B ... matrix to work on",
"d ... partial determinant",
"r ... first row to work on",
"n ... number of rows of B",
"c ... first column to work on",
"m ... last column to work on",
"Return d multiplied with the common factors in factored form.";
updated := d;
for jj from c to m do
g := 0;
for ii from 1 to n do
#printf("ii: %d, jj: %d\n", ii, jj);
#if ii=2 and jj=2 then
# print(B[ii, jj]);
#end if;
g := gcd(g, numer(B[ii, jj]));
end do;
if g=0 then
next;
end if;
g := factor(g);
for ii from r to n do
B[ii, jj] := normal(B[ii, jj]/g);
end do;
updated := updated * g;
end do;
return updated;
end proc;
ColDenomsFactors := proc(B, d, r, n, c, m)
local jj, g, ii, updated;
description
"Extract common factors from denominators of enries in matrix columns."
"B ... matrix to work on",
"d ... partial determinant",
"r ... first row to work on",
"n ... number of rows of B",
"c ... first column to work on",
"m ... last column to work on",
"Return d multiplied with the common factors in factored form.";
updated := d;
for jj from c to m do
g := 0;
for ii from 1 to n do
#printf("ii: %d, jj: %d\n", ii, jj);
#if ii=2 and jj=2 then
# print(B[ii, jj]);
#end if;
g := gcd(g, denom(B[ii, jj]));
end do;
if g=0 then
next;
end if;
g := factor(g);
for ii from r to n do
B[ii, jj] := normal(B[ii, jj]*g);
end do;
updated := updated / g;
end do;
return updated;
end proc;
RowNumersFactors := proc(B, d, r, n, c, m)
local ii, g, jj, updated;
description
"Extract common factors from numerators of enries in a matrix row."
"B ... matrix to work on",
"d ... partial determinant",
"r ... row to work on",
"n ... last row to work on",
"c ... first column to work on",
"m ... last column to work on",
"Return d multiplied with the common factors in factored form.";
updated := d;
for ii from r to n do
g := 0;
for jj from c to m do
g := gcd(g, numer(B[ii, jj]));
end do;
if g<>0 then
g := factor(g);
for jj from c to m do
B[ii, jj] := normal(B[ii, jj]/g);
end do;
updated := updated * g;
end if;
end do;
return updated;
end proc;
RowDenomsFactors := proc(B, d, r, n, c, m)
local ii, h, jj, updated;
description
"Extract common factors from denominators of enries in a matrix row."
"B ... matrix to work on",
"d ... partial determinant",
"r ... row to work on",
"n ... last row to work on",
"c ... first column to work on",
"m ... last column to work on",
"Return d divided by the common factors in factored form.";
updated := d;
for ii from r to n do
h := 0;
for jj from c to m do
h := gcd(h, denom(B[ii, jj]));
end do;
if h<>0 then
h := factor(h);
for jj from c to m do
B[ii, jj] := normal(B[ii, jj]*h);
end do;
updated := updated / h;
end if;
end do;
return updated;
end proc;
PermutationFromMatrix := proc(P::Matrix)
local size, perm, i, j;
description
"Generate a permutation function from a permutation matrix.",
"P ... permutation matrix",
"Returns a procedure that implements the permutation given by P";
size := LinearAlgebra:-RowDimension(P);
for i from 1 to size do
for j from 1 to size do
if P[i,j]<>0 then
perm(j):=i;
break;
end if;
end do;
end do;
return eval(perm);
end proc:
InstantiateMatrix := proc(M::Matrix, varLst)
local substLst, p, v, i, j, Ms, rows, cols;
description
"Randomly instantiate a parametric matrix."
"M ... matrix with parametric entries",
"varLst ... list of variables in M",
"Return M with parameters varLst randomly specialized.";
(rows,cols) := LinearAlgebra:-Dimension(M);
# Create Substitution List
substLst := []:
#p := 137;
for v in varLst do
#p := nextprime(p);
p := rand(1..10000)();
#p := rand(1..100)();
substLst := [op(substLst),v=p]:
end do:
# Create Numeric Matrix
Ms := Matrix(rows,cols);
for i from 1 to rows do
for j from 1 to cols do
Ms[i,j] := subs(substLst,M[i,j]);
end do:
end do:
#return eval(Ms);
return Ms;
end proc:
IsNonZeroRow := proc(M::Matrix, rowIndex, startColIndex)
local startIndex, j, cols, nonZeroIndex;
description
"Find first non-zero entry in matrix row.",
"M",
"rowIndex ... index of row",
"startColIndex ... optional column index",
"Return col index of first non-zero entry of M in row rowIndex; 0 iff row is zero",
"If column index startColIndex is present then start checking row from index startColIndex.";
if _npassed>2 then
startIndex := startColIndex;
else
startIndex := 1;
end if;
nonZeroIndex := 0;
cols := LinearAlgebra:-ColumnDimension(M);
for j from startIndex to cols do
if M[rowIndex, j]<>0 then
nonZeroIndex := j;
break;
end if;
end do;
return nonZeroIndex;
end proc:
MaxMinorElimFull := proc(A::Matrix)
description
"Compute a maximal-rank minor of a matrix via Gaussian elimination.",
"A ... given matrix",
"Named optional arguments: like MaxMinorElim, except tellFullrank which is not allowed.",
"Return lowerRank::string, output from MaxMinorElim",
"If lowerRank is empty then return a maximal minor of full rank. lowerRank is not empty iff A is not square of full rank and is not empty.";
return MaxMinorElim(A, detFactor, tellFullrank=true, _options);
end proc;
MaxMinorElim := proc(A::Matrix,
{tellFullrank::truefalse:=false, moreRows::truefalse:=true,
preColNumers::truefalse:=false, preColDenoms::truefalse:=false,
preRowNumers::truefalse:=false, preRowDenoms::truefalse:=false,
colNumers::truefalse:=false, colDenoms::truefalse:=false,
pivotRowNumers::truefalse:=false, pivotRowDenoms::truefalse:=false,
restRowNumers::truefalse:=false, restRowDenoms::truefalse:=false})
local n, m, tmp_n, rankCount, r, c, d, dr, B, i, j, t, det;
description
"Compute a maximal-rank minor of a matrix via Gaussian elimination.",
"A ... given matrix",
"Named optional arguments:",
"return_fullrank ... indicate whether a non-zero minor of full rank was found",
"moreRows ... transpose A such that it has at least as many rows as columns",
"*row* ... extract common factors of rows",
"*col* ... extract common factors of columns",
"*Numers ... extract common factors from numerators of matrix entries",
"*Denoms ... extract common factors from denominators of matrix entries",
"pre* ... extract common factors before the Gaussian elimination starts",
"pivot* ... extract common factors from the pivot row during Gaussian elimination",
"rest* ... extract common factors from rows other than the pivot row during Gaussian elimination",
"Return lowerRank::string, a maximal-rank minor of A.",
"If moreRows=false and rest* is activated then the output can be a multiple of a maximal-rank minor, because the output may contain factors of rows that are not needed for the determinant computation.";
"If tellFullrank is true and lowerRank is empty then return a maximal minor of full rank. lowerRank is not empty iff A is not square of full rank and is not empty.",
"If tellFullrank is false then lowerRank is empty and any maximal minor is returned.";
#Original version: Hoon Hong (procedure drsm).
#Modified: M. Minimair, 5/19/2015
# Various options added, such as factor detection (DF) during elimination.
#print([_options]);
(n, m) := LinearAlgebra:-Dimension(A);
rankCount := 0;
if n=0 or m=0 then
return "", 0;
end if;
# Make sure that there are at least as many rows as columns.
# It may result in fewer factors in the output if rest* is activiated.
if n<m and moreRows then
B := LinearAlgebra:-Transpose(A);
tmp_n := n;
n := m;
m := tmp_n;
else
B := copy(A);
end if;
r := 1;
d := 1;
#Special case of Matrix([0])
if m=1 and n=1 and B[1,1]=0 then
if tellFullrank then
return notFullRankMsg, 0;
else
return "", 0;
end if;
end if;
#Other cases
# Remove factors of the numerators of the matrix entries along the columns
if preColNumers then
d := ColNumersFactors(B, d, 1, n, 1, m);
end if;
# Remove factors of the denominators of the matrix entries along the columns
if preColDenoms then
d := ColDenomsFactors(B, d, 1, n, 1, m);
end if;
# Remove factors of the numerators of the matrix entries along the rows
if preRowNumers then
d := RowNumersFactors(B, d, 1, n, 1, m);
end if;
# Remove factors of the denominators of the matrix entries along the rows
if preRowDenoms then
d := RowDenomsFactors(B, d, 1, n, 1, m);
end if;
for c from 1 to m while r <= n do
if type(infolevel[DR], numeric) and infolevel[DR]>=2 then
printf(" %a: Working on column %d................\n", procname, c);
end if;
# Column numerator DF
if colNumers then
d := ColNumersFactors(B, d, r, n, c, m);
end if;
# Column denominator DF
if colDenoms then
d := ColDenomsFactors(B, d, r, n, c, m);
end if;
#--- Find a pivot ----
for i from r to n while B[i,c] = 0 do end do;
if i > n then
#printf(` no pivot\n`);
next;
else
rankCount := rankCount + 1;
end if;
for j from i+1 to n do
if B[j,c] = 0 then next end if;
if length(B[j,c]) < length(B[i,c]) then i := j end if
end do;
#--- Swap rows ----
if i <> r then
for j from c to m do
t := B[i,j]; B[i,j] := B[r,j]; B[r,j] := t
end do
end if;
# r is the row and c is the column index of the pivot
# Pivot row numerator DF
if pivotRowNumers then
d := RowNumersFactors(B, d, r, r, c, m);
end if;
# Pivot row denominator DF
if pivotRowDenoms then
d := RowDenomsFactors(B, d, r, r, c, m);
end if;
# Rest row numerator DF
if restRowNumers then
d := RowNumersFactors(B, d, r+1, n, c, m);
end if;
# Rest row denominator DF
if restRowDenoms then
d := RowDenomsFactors(B, d, r+1, n, c, m);
end if;
#--- Update determinant ---
B[r,c] := factor(B[r,c]);
d := d * B[r,c];
#print(B[r,c]);
#print(`-----------------`);
#print(d);
#--- Eliminate ---
for i from r+1 to n do
if B[i,c] = 0 then next end if;
t := normal(B[i,c]/B[r,c]);
for j from c+1 to m do
B[i,j] := normal(B[i,j]-t*B[r,j]);
end do;
B[i,c] := 0
end do;
r := r+1
end do;
det := normal(d);
if tellFullrank then
if rankCount=n and rankCount=m then
return "", det;
else
return notFullRankMsg, det;
end if;
else
return "", det;
end if;
end;
end module;
###########################################################################################################################
DF := module()
export ColNumers, ColDenoms, Col, PivotRowNumers, PivotRowDenoms, PivotRow, ColPivotRow, Row, ColRow,
RowFull, ColRowFull, PivotRowFull, ColPivotRowFull;
description
"Versions of maximal minor with factor computation during elimination. DF = Factor Detection",
"See also: Lewis, Rober H., Heuristics to accelerate the Dixon resultant, Mathematics and Computers in Simulation, 77, 4 (2008), 400-407"
"All functions work accordingly:",
"Compute a maximal-rank minor of a matrix via Gaussian elimination.",
"A ... given matrix",
"Return a maximal-rank minor of A.",
"Author: Manfred Minimair",
"E-mail: manfred@minimair.org",
"Released under GPL Version 3",
"Copyright (C) Manfred Minimair, 2015";
ColNumers := proc(A) return Extract:-MaxMinorElim(A, colNumers=true) end proc;
ColDenoms := proc(A) return Extract:-MaxMinorElim(A, colDenoms=true) end proc;
Col := proc(A) return Extract:-MaxMinorElim(A, colNumers=true, colDenoms=true) end proc;
PivotRowNumers := proc(A) return Extract:-MaxMinorElim(A, pivotRowNumers=true) end proc;
PivotRowDenoms := proc(A) return Extract:-MaxMinorElim(A, pivotRowDenoms=true) end proc;
PivotRow := proc(A) return Extract:-MaxMinorElim(A, pivotRowNumers=true, pivotRowDenoms=true) end proc;
ColPivotRow := proc(A) return Extract:-MaxMinorElim(A, colNumers=true, colDenoms=true, pivotRowNumers=true, pivotRowDenoms=true) end proc;
Row := proc(A) return Extract:-MaxMinorElim(A, pivotRowNumers=true, pivotRowDenoms=true,
restRowNumers=true, restRowDenoms=true) end proc;
ColRow := proc(A) return Extract:-MaxMinorElim(A, preColNumers=true, preRowNumers=true,
colNumers=true, colDenoms=true, pivotRowNumers=true, pivotRowDenoms=true,
restRowNumers=true, restRowDenoms=true) end proc;
PivotRowFull := proc(A) return Extract:-MaxMinorElimFull(A, pivotRowNumers=true, pivotRowDenoms=true) end proc;
ColPivotRowFull := proc(A) return Extract:-MaxMinorElimFull(A, colNumers=true, colDenoms=true, pivotRowNumers=true, pivotRowDenoms=true) end proc;
RowFull := proc(A) return Extract:-MaxMinorElimFull(A, pivotRowNumers=true, pivotRowDenoms=true,
restRowNumers=true, restRowDenoms=true) end proc;
ColRowFull := proc(A) return Extract:-MaxMinorElimFull(A, preColNumers=true, preRowNumers=true,
colNumers=true, colDenoms=true, pivotRowNumers=true, pivotRowDenoms=true,
restRowNumers=true, restRowDenoms=true) end proc;
end module;
###########################################################################################################################
DRes := module()
export ComposeDixon, MaxMinor, RankMaxMinor, RankMapleDet, RankFactorsMapleDet,
MaxMinorColNumers, MaxMinorColDenoms, MaxMinorCol, MaxMinorPivotRowNumers, MaxMinorPivotRowDenoms, MaxMinorPivotRow, MaxMinorColPivotRow, MaxMinorColRow,
RankRow, RankColRow, RankMaxMinorPivotRow, RankMaxMinorColPivotRow, GetFirst, DetectFail;
description
"Versions of Dixon resultant computation.",
"All functions work accordingly:",
" pols ... list of (d+1) polynomials",
" vars ... list d variables of pols"
" measures ... output parameter, a table. If measures is a name then a table will be assigned to it. If measures is undefined then no timing will be produced.",
" Return the Dixon resultant of pols.",
" If randomized maximal-rank submatrix extraction is used, it is possible, however extremely unlikely, that Dixon resultant computation fails.",
" In this case, the computation terminates with an error message indicating to run the computation again or not to use randomized maximal-rank submatrix extraction.",
"Author: Manfred Minimair",
"E-mail: manfred@minimair.org",
"Released under GPL Version 3",
"Copyright (C) Manfred Minimair, 2015";
GetFirst := proc()
description
"Return the first argument passed to the function.";
return _passed[1]
end proc;
DetectFail := proc(msg::string)
description
"Detect failure case.",
"msg ... error message",
"Return rest arguments or, if msg is a non-empty string with the error message msg.";
if msg<>"" then
error msg;