incr-set prlevel 1
if #0>=2 START
incr-set prlevel -1
;;; Usage:
;;; 	<sort_by_degree m n [cchange]
;;;
;;; 	Rearranges columns of m so that the degrees 
;;; are in increasing order ; n is set to the resulting matrix.
;;; 	If present, cchange is set to the permutation matrix
;;; giving the column change: that is, 
;;; such that n is the composition
;;;        n = m cchange
;;;      
incr-set prlevel 1
jump END
;;; Parameters:
;;;         m a matrix
;;; Output values:
;;;         n a matrix
;;;        cchange a permutation matrix
;;;
;;; Strategy:
;;; Find the mimimal column degree that occurs, 
;;; and split the matrix m into those 
;;; cols having the minimal degree and a 
;;; residual matrix.
;;; Iterate till the residual matrix is empty.
;;;
;;; Remark:  We could just produce cchange, and
;;; multiply; but matrix multiplication can be slow...
; created 5/15/90 DE
START:
copy #1 @m

;initialize
;make a matrix with the right row degrees but no cols
row-degs @m @n

;an identity matrix with the same column degrees
;as #1 from which to make cchange.
<idencoldegs @m @I

;and a matrix without columns but with the same
;degree structure as @I
ncols @I @ncols
<zeromat @ncols 0 @cchange
setdegs @cchange
@I
;

COLS:
;Find the minimal column degree that occurs:
transpose @m @m'
max @m' @mincoldeg
int @mincoldeg -@mincoldeg

;loop through cols
int @i 0

loop_cols:
int @i @i+1

no_increment:
ncols @m @ncols
if @i>@ncols done_cols

col-deg @m @i @deg
if @deg>@mincoldeg loop_cols 
submat @m @m1
	;
	@i
concat @n @m1
submat @I @I1
	;
	@i
concat @cchange @I1
submat @m @m
	;
	1..(@i-1) (@i+1)..@ncols
submat @I @I
	;
	1..(@i-1) (@i+1)..@ncols
jump no_increment

done_cols:

if @ncols=0 output
jump COLS

output:
copy @n #2
if #0=2 cleanup
copy @cchange #3

cleanup:
kill @n @cchange @m' @mincoldeg 
kill @i @deg @m1 @I1 @m @I @ncols 

END:
incr-set prlevel -1

$;;;;;;;; EXAMPLE SECTION ;;;;;;;;;;;;;;;;;;;;;;;;;
reset
<ring 3 a-z r
<ideal i a2 b c a3
col-degs i
;2 1 1 3

<sort_by_degree i j c

type j
; b c a2 a3 
col-degs j
;1 1 2 3

type c
; 0 0 1 0 
; 1 0 0 0 
; 0 1 0 0 
; 0 0 0 1 
col-degs c
row-degs c

mult i c test
type test
; b c a2 a3 
col-degs test
;1 1 2 3

betti i
; total:      1     4 
; --------------------
;     0:      1     2 
;     1:      -     1 
;     2:      -     1 
betti c
; total:      4     4 
; --------------------
;     0:      -     2 
;     1:      2     1 
;     2:      1     1 
;     3:      1     - 

listvars

; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;To order the ROWS of m in order of ascending degree:
<ring 3 a-z r
<ideal i a2 b c a3
diag i i
setdegs i
1 4 3 2
;
col-degs i
row-degs i

<idenrowdegs i I
<sort_by_degree I I crows
<inverse crows crows1

mult crows1 i J

col-degs J
row-degs J

