Statistiques
| Branche: | Révision :

meplib / cCode / matrices / mpz / mpz-matrix.c @ master

Historique | Voir | Annoter | Télécharger (30,39 ko)

1
/* mpz_matrix.c */
2

    
3
#include <stdio.h>
4
#include <stdlib.h>
5
/*#include <string.>*/
6
#include <ctype.h>
7
#include <gmp.h>
8
#include <mpfr.h>
9

    
10
#include "mpz-matrix.h"
11

    
12
void
13
mpz_matrix_errormsg(char *f , char *msgname, char *msg);
14

    
15
/* 
16
 * Allocate space for matrix dimensioned by 'NbRows X NbColumns'.
17
 */
18
mpz_matrix* mpz_matrix_alloc(unsigned NbRows,unsigned NbColumns) {
19
  
20
  mpz_matrix *Mat;
21
  mpz_t *p, **q;
22
  int i,j;
23

    
24
  /* Deal with pathological parameter */
25
  if (NbRows < 0)
26
  {
27
    mpz_matrix_errormsg("mpz_matrix_alloc", "invalid parameter", "NbRows must be >= 0");
28
    return 0;
29
  }
30
  if (NbRows < 0)
31
  {
32
    mpz_matrix_errormsg("mpz_matrix_alloc", "invalid parameter", "NbColumns must be >= 0");
33
    return 0;
34
  }
35
  /* Create the matrix struct */
36
  Mat=(mpz_matrix *)malloc(sizeof(mpz_matrix));
37
  if(!Mat) {        
38
    mpz_matrix_errormsg("mpz_matrix_Alloc", "outofmem", "out of memory space");
39
    return 0;
40
  }
41
  Mat->NbRows=NbRows;
42
  Mat->NbColumns=NbColumns;
43
  /* NbRows == 0: created an "empty" matrix. */
44
  if(NbRows==0) 
45
  {
46
    Mat->p = (mpz_t **)0;
47
    Mat->p_Init= (mpz_t *)0;
48
  }  
49
  else 
50
  {
51
    /* NbColumns == 0: created an "empty" matrix. */
52
    if(NbColumns==0) 
53
    {
54
      Mat->p = (mpz_t **)0;
55
      Mat->p_Init= (mpz_t *)0;
56
    }
57
    else 
58
    {
59
      /* Create the elements array that holds the matrix elements */
60
      q = (mpz_t **)malloc(NbRows * sizeof(*q));
61
      if(!q) 
62
      {
63
        free(Mat);
64
        mpz_matrix_errormsg("mpz_matrix_Alloc", "outofmem", "out of memory space");
65
        return 0;
66
      }
67
      p = (mpz_t *)malloc(NbRows * NbColumns * sizeof(mpz_t));
68
      if(!p) 
69
      {
70
        free(q);
71
        free(Mat);
72
        mpz_matrix_errormsg("mpz_matrix_Alloc", "outofmem", "out of memory space");
73
        return 0;
74
      }
75
      Mat->p = q;
76
      Mat->p_Init = p;
77
      for (i=0;i<NbRows;i++) 
78
      {
79
        *q++ = p;
80
        for (j=0;j<NbColumns;j++)   
81
          mpz_init(*(p+j));
82
        p += NbColumns;
83
      }
84
    }
85
  }
86
  p = NULL;
87
  q = NULL;
88
  Mat->p_Init_size = NbColumns*NbRows;
89
  return Mat;
90
} /* mpz_matrix_Alloc */
91

    
92
/* 
93
 * Free the memory space occupied by mpz_matrix 'Mat' 
94
 */
95
void mpz_matrix_free(mpz_matrix *Mat) {
96
  
97
  int i;
98
  mpz_t *p;
99

    
100
  if( Mat->p )
101
  {
102
    p = *(Mat->p);
103
    for(i=0;i<Mat->p_Init_size;i++) {
104
      mpz_clear(*p++);
105
    }
106
  }
107

    
108
  if (Mat->p_Init)
109
    free(Mat->p_Init);
110
  if (Mat->p)
111
    free(Mat->p);
112
  free(Mat);
113

    
114
} /* mpz_matrix_Free */
115

    
116
/* 
117
 * Print the contents of the mpz_matrix 'Mat'.
118
 */
119
void mpz_matrix_print(FILE *Dst, int radix ,mpz_matrix *Mat) {
120
  
121
  mpz_t *p;
122
  int i, j;
123
  unsigned NbRows, NbColumns;
124
  
125
  fprintf(Dst,"%d %d\n", NbRows=Mat->NbRows, NbColumns=Mat->NbColumns);
126
  for (i=0;i<NbRows;i++) {
127
    p=*(Mat->p+i);
128
    for (j=0;j<NbColumns;j++) 
129
    {
130
      mpz_out_str(Dst, radix, *p++);
131
      fprintf(Dst, " ");
132
    }
133
    fprintf(Dst, "\n");
134
  }
135
} /* mpz_matrix_print */
136

    
137
/* 
138
 * Print the contents of the mpz_matrix 'Mat' without printing the
139
 * the dimensions.
140
 */
141
void mpz_matrix_print_no_dims(FILE *Dst, int radix ,mpz_matrix *Mat) {
142
  
143
  mpz_t *p;
144
  int i, j;
145
  unsigned NbRows, NbColumns;
146
  
147
  NbRows    = Mat->NbRows; 
148
  NbColumns = Mat->NbColumns;
149
  for (i=0 ; i<NbRows ; i++) 
150
  {
151
    p=*(Mat->p+i);
152
    for (j=0;j<NbColumns;j++) 
153
    {
154
      mpz_out_str(Dst, radix, *p++);
155
      fprintf(Dst, " ");
156
    }
157
    fprintf(Dst, "\n");
158
  }
159
} /* mpz_matrix_print_no_dims */
160

    
161
/* 
162
 * Print the contents of the mpz_matrix 'Mat' in the Matlab
163
 * input format.
164
 */
165
void mpz_matrix_print_matlab(FILE *Dst, int radix ,mpz_matrix *Mat) {
166
  
167
  mpz_t *p;
168
  int i, j;
169
  unsigned NbRows, NbColumns;
170
  
171
  NbRows    = Mat->NbRows; 
172
  NbColumns = Mat->NbColumns;
173
  fprintf(Dst, "[ ");
174
  for (i=0 ; i < NbRows ; i++) 
175
  {
176
    p=*(Mat->p+i);
177
    for (j=0 ; j < NbColumns ; j++) 
178
    {
179
      mpz_out_str(Dst, radix, *p++);
180
      if (j < (NbColumns - 1))
181
      {
182
        fprintf(Dst, ", ");
183
      }
184
      else
185
      {
186
        if (i < (NbRows - 1))
187
        {
188
          fprintf(Dst, "; ");
189
        }
190
        else
191
        {
192
          fprintf(Dst, " ]\n");
193
        }
194
      }
195
    }
196
  }
197
} /* mpz_matrix_print_matlab */
198

    
199
/* 
200
 * Read the contents of the mpz_matrix 'Mat' 
201
 */
202
void mpz_matrix_read_input(mpz_matrix *Mat, int radix) 
203
{
204
  
205
  mpz_t *p;
206
  int i,j,n;
207
  char *c, s[1024],str[1024];
208
  
209
  p = Mat->p_Init;
210
  for (i=0;i<Mat->NbRows;i++) {
211
    do {
212
      c = fgets(s, 1024, stdin);
213
      while(isspace(*c) && *c!='\n')
214
        ++c;
215
    } while(c && (*c =='#' || *c== '\n'));
216
    
217
    if (!c) {
218
      mpz_matrix_errormsg( "mpz_matrix_Read", "baddim", "not enough rows" );
219
      break;
220
    }
221
    for (j=0;j<Mat->NbColumns;j++) {
222
      if(!c || *c=='\n' || *c=='#') {
223
        mpz_matrix_errormsg("mpz_matrix_Read", "baddim", "not enough columns");
224
        break;
225
      }
226
      if (sscanf(c,"%s%n",str,&n) == 0) {
227
        mpz_matrix_errormsg( "mpz_matrix_Read", "baddim", "not enough columns" );
228
        break;
229
      }
230
      mpz_set_str(*(p++),str, radix);
231
      c += n;
232
    }
233
  }
234
} /* mpz_matrix_read_input */
235

    
236
/* 
237
 * Read the contents of the matrix 'Mat' from standard input. 
238
 * A '#' in the first column is a comment line 
239
 */
240
mpz_matrix *mpz_matrix_read(int radix) 
241
{
242
  
243
  mpz_matrix *Mat;
244
  unsigned NbRows, NbColumns;
245
  char s[1024];
246
  
247
  while(fgets(s, 1024, stdin)==0);
248
  while ((*s=='#' || *s=='\n') ||
249
         (sscanf(s, "%d %d", &NbRows, &NbColumns)<2))
250
    fgets(s, 1024, stdin);
251
  Mat = mpz_matrix_alloc(NbRows,NbColumns);
252
  if(!Mat) {
253
    mpz_matrix_errormsg("mpz_matrix_read", "outofmem", "out of memory space");
254
    return(NULL);
255
  }
256
  mpz_matrix_read_input(Mat, radix);
257
  return Mat;
258
} /* mpz_matrix_read */
259

    
260
mpz_t*
261
mpz_matrix_get_at(mpz_matrix* mat, unsigned int row, unsigned int column)
262
{
263
  mpz_t** matRow;
264
  if (mat == NULL)
265
  {
266
    mpz_matrix_errormsg("mpz_matrix_get_at", "null pointer parameter", "mat parameter is NULL");
267
    return(NULL);
268
  }
269
  if (mat->p_Init_size == 0)
270
  {
271
    mpz_matrix_errormsg("mpz_matrix_get_at", "empty matrix", "can't return an element from an empty matrix");
272
    return(NULL);
273
  }
274
  if (row >= mat->NbRows)
275
  {
276
    mpz_matrix_errormsg("mpz_matrix_get_at", "index out of range", "row index beyond bounds");
277
    return(NULL);
278
  }
279
  if (column >= mat->NbColumns)
280
  {
281
    mpz_matrix_errormsg("mpz_matrix_get_at", "index out of range", "column index beyond bounds");
282
    return(NULL);
283
  }
284
  matRow = mat->p + row; 
285
  return(*matRow + column);
286
} /* End mpz_matrix_get_at */
287

    
288
void 
289
mpz_matrix_set_at(mpz_matrix* mat, unsigned int row, unsigned int column, mpz_t value)
290
{
291
  mpz_t** matRow;
292
  if (mat == NULL)
293
  {
294
    mpz_matrix_errormsg("mpz_matrix_set_at", "null pointer parameter", "mat parameter is NULL");
295
  }
296
  if (mat->p_Init_size == 0)
297
  {
298
    mpz_matrix_errormsg("mpz_matrix_set_at", "empty matrix", "can't set an element from an empty matrix");
299
  }
300
  if (row >= mat->NbRows)
301
  {
302
    mpz_matrix_errormsg("mpz_matrix_set_at", "index out of range", "row index beyond bounds");
303
  }
304
  if (column >= mat->NbColumns)
305
  {
306
    mpz_matrix_errormsg("mpz_matrix_set_at", "index out of range", "column index beyond bounds");
307
  }
308
  matRow = mat->p + row; 
309
  mpz_set(*(*matRow + column), value);
310
} /* End mpz_matrix_set_at */
311

    
312
void 
313
mpz_matrix_errormsg(char *f , char *msgname, char *msg) 
314
{
315
  fprintf(stderr, "?%s: %s\n", f, msg);
316
}
317

    
318
#if 0
319
/* 
320
 * Basic hermite engine 
321
 */
322
static int hermite(mpz_matrix *H,mpz_matrix *U,mpz_matrix *Q) {
323
  
324
  int nc, nr, i, j, k, rank, reduced, pivotrow;
325
  mpz_t pivot,x,aux;
326
  mpz_t *temp1, *temp2;
327
  
328
  /*                     T                     -1   T */
329
  /* Computes form: A = Q H  and U A = H  and U  = Q  */
330
  
331
  if (!H) { 
332
    mpz_matrix_errormsg("Domlib", "nullH", "hermite: ? Null H");
333
    return -1;
334
  }
335
  nc = H->NbColumns;
336
  nr = H->NbRows;
337
  temp1 = (mpz_t *) malloc(nc * sizeof(mpz_t));
338
  temp2 = (mpz_t *) malloc(nr * sizeof(mpz_t));
339
  if (!temp1 ||!temp2) {
340
    mpz_matrix_errormsg("Domlib", "outofmem", "out of memory space");
341
    return -1;
342
  }
343
  
344
  /* Initialize all the 'mpz_t' variables */
345
  value_init(pivot); value_init(x); 
346
  value_init(aux);   
347
  for(i=0;i<nc;i++)
348
    value_init(temp1[i]);
349
  for(i=0;i<nr;i++)
350
    value_init(temp2[i]);
351
  
352
#ifdef DEBUG
353
  fprintf(stderr,"Start  -----------\n");
354
  mpz_matrix_Print(stderr,0,H);
355
#endif
356
  for (k=0, rank=0; k<nc && rank<nr; k=k+1) {
357
    reduced = 1;        /* go through loop the first time */
358
#ifdef DEBUG
359
    fprintf(stderr, "Working on col %d.  Rank=%d ----------\n", k+1, rank+1);
360
#endif
361
    while (reduced) {
362
      reduced=0;
363
      
364
      /* 1. find pivot row */
365
      value_absolute(pivot,H->p[rank][k]);
366
      
367
      /* the kth-diagonal element */
368
      pivotrow = rank;
369
      
370
      /* find the row i>rank with smallest nonzero element in col k */
371
      for (i=rank+1; i<nr; i++) {
372
        value_absolute(x,H->p[i][k]);
373
        if (value_notzero_p(x) &&
374
            (value_lt(x,pivot) || value_zero_p(pivot))) {
375
          value_assign(pivot,x);
376
          pivotrow = i;
377
        }
378
      }
379
      
380
      /* 2. Bring pivot to diagonal (exchange rows pivotrow and rank) */
381
      if (pivotrow != rank) {
382
        Vector_Exchange(H->p[pivotrow],H->p[rank],nc);
383
        if (U)
384
          Vector_Exchange(U->p[pivotrow],U->p[rank],nr);
385
        if (Q)
386
          Vector_Exchange(Q->p[pivotrow],Q->p[rank],nr);
387

    
388
#ifdef DEBUG
389
        fprintf(stderr,"Exchange rows %d and %d  -----------\n", rank+1, pivotrow+1);
390
        mpz_matrix_Print(stderr,0,H);
391
#endif
392
      }
393
      value_assign(pivot,H->p[rank][k]);        /* actual ( no abs() ) pivot */
394
      
395
      /* 3. Invert the row 'rank' if pivot is negative */
396
      if (value_neg_p(pivot)) {
397
        value_oppose(pivot,pivot); /* pivot = -pivot */
398
        for (j=0; j<nc; j++)
399
          value_oppose(H->p[rank][j],H->p[rank][j]);
400
        
401
        /* H->p[rank][j] = -(H->p[rank][j]); */
402
        if (U)
403
          for (j=0; j<nr; j++)
404
            value_oppose(U->p[rank][j],U->p[rank][j]);
405
        
406
        /* U->p[rank][j] = -(U->p[rank][j]); */
407
        if (Q)
408
          for (j=0; j<nr; j++)
409
            value_oppose(Q->p[rank][j],Q->p[rank][j]);
410
        
411
        /* Q->p[rank][j] = -(Q->p[rank][j]); */
412
#ifdef DEBUG
413
        fprintf(stderr,"Negate row %d  -----------\n", rank+1);
414
        mpz_matrix_Print(stderr,0,H);
415
#endif
416

    
417
      }      
418
      if (value_notzero_p(pivot)) {
419
        
420
        /* 4. Reduce the column modulo the pivot */
421
        /*    This eventually zeros out everything below the */
422
        /*    diagonal and produces an upper triangular matrix */
423
        
424
        for (i=rank+1;i<nr;i++) {
425
          value_assign(x,H->p[i][k]);
426
          if (value_notzero_p(x)) {            
427
            value_modulus(aux,x,pivot);
428
            
429
            /* floor[integer division] (corrected for neg x) */
430
            if (value_neg_p(x) && value_notzero_p(aux)) {
431
              
432
              /* x=(x/pivot)-1; */
433
              value_division(x,x,pivot);
434
              value_decrement(x,x);
435
            }        
436
            else 
437
              value_division(x,x,pivot);
438
            for (j=0; j<nc; j++) {
439
              value_multiply(aux,x,H->p[rank][j]);
440
              value_substract(H->p[i][j],H->p[i][j],aux);
441
            }
442
            
443
            /* U->p[i][j] -= (x * U->p[rank][j]); */
444
            if (U)
445
              for (j=0; j<nr; j++) {
446
                value_multiply(aux,x,U->p[rank][j]);
447
                value_substract(U->p[i][j],U->p[i][j],aux);
448
              }
449
            
450
            /* Q->p[rank][j] += (x * Q->p[i][j]); */
451
            if (Q)
452
              for(j=0;j<nr;j++) {
453
                value_multiply(aux,x,Q->p[i][j]);
454
                value_addto(Q->p[rank][j],Q->p[rank][j],aux);
455
              }
456
            reduced = 1;
457

    
458
#ifdef DEBUG
459
            fprintf(stderr,
460
                    "row %d = row %d - %d row %d -----------\n", i+1, i+1, x, rank+1);
461
            mpz_matrix_Print(stderr,0,H);
462
#endif
463
        
464
          } /* if (x) */
465
        } /* for (i) */
466
      } /* if (pivot != 0) */
467
    } /* while (reduced) */
468
    
469
    /* Last finish up this column */
470
    /* 5. Make pivot column positive (above pivot row) */
471
    /*    x should be zero for i>k */
472
    
473
    if (value_notzero_p(pivot)) {
474
      for (i=0; i<rank; i++) {
475
        value_assign(x,H->p[i][k]);
476
        if (value_notzero_p(x)) {           
477
          value_modulus(aux,x,pivot);
478
          
479
          /* floor[integer division] (corrected for neg x) */
480
          if (value_neg_p(x) && value_notzero_p(aux)) {
481
            value_division(x,x,pivot);
482
            value_decrement(x,x);
483
            
484
            /* x=(x/pivot)-1; */
485
          }
486
          else
487
            value_division(x,x,pivot);
488
          
489
          /* H->p[i][j] -= x * H->p[rank][j]; */
490
          for (j=0; j<nc; j++) {
491
            value_multiply(aux,x,H->p[rank][j]);
492
            value_substract(H->p[i][j],H->p[i][j],aux);
493
          }
494
          
495
          /* U->p[i][j] -= x * U->p[rank][j]; */
496
          if (U)
497
            for (j=0; j<nr; j++) {
498
              value_multiply(aux,x,U->p[rank][j]);
499
              value_substract(U->p[i][j],U->p[i][j],aux);
500
            }
501
          
502
          /* Q->p[rank][j] += x * Q->p[i][j]; */
503
          if (Q)
504
            for (j=0; j<nr; j++) {
505
              value_multiply(aux,x,Q->p[i][j]);
506
              value_addto(Q->p[rank][j],Q->p[rank][j],aux);
507
            }  
508
#ifdef DEBUG
509
          fprintf(stderr,
510
                  "row %d = row %d - %d row %d -----------\n", i+1, i+1, x, rank+1);
511
          mpz_matrix_Print(stderr,0,H);
512
#endif
513
        } /* if (x) */
514
      } /* for (i) */
515
      rank++;
516
    } /* if (pivot!=0) */
517
  } /* for (k) */
518
  
519
  /* Clear all the 'mpz_t' variables */
520
  value_clear(pivot); value_clear(x); 
521
  value_clear(aux); 
522
  for(i=0;i<nc;i++)
523
    value_clear(temp1[i]);
524
  for(i=0;i<nr;i++)
525
    value_clear(temp2[i]);
526
  free(temp2);
527
  free(temp1);
528
  return rank;
529
} /* Hermite */ 
530

    
531
void right_hermite(mpz_matrix *A,mpz_matrix **Hp,mpz_matrix **Up,mpz_matrix **Qp) {
532
  
533
  mpz_matrix *H, *Q, *U;
534
  int i, j, nr, nc, rank;
535
  mpz_t tmp;
536
  
537
  /* Computes form: A = QH , UA = H */  
538
  nc = A->NbColumns;
539
  nr = A->NbRows;
540
  
541
  /* H = A */
542
  *Hp = H = mpz_matrix_Alloc(nr,nc);
543
  if (!H) { 
544
    mpz_matrix_errormsg("DomRightHermite", "outofmem", "out of memory space");
545
    return;
546
  }
547
  
548
  /* Initialize all the 'mpz_t' variables */
549
  value_init(tmp);
550
  
551
  Vector_Copy(A->p_Init,H->p_Init,nr*nc);
552
  
553
  /* U = I */
554
  if (Up) {
555
    *Up = U = mpz_matrix_Alloc(nr, nr);
556
    if (!U) {
557
      mpz_matrix_errormsg("DomRightHermite", "outofmem", "out of memory space");
558
      value_clear(tmp);
559
      return;
560
    }
561
    Vector_Set(U->p_Init,0,nr*nr);             /* zero's */
562
    for(i=0;i<nr;i++)                          /* with diagonal of 1's */
563
      value_set_si(U->p[i][i],1);
564
  }
565
  else
566
    U = (mpz_matrix *)0;
567
  
568
  /* Q = I */
569
  /* Actually I compute Q transpose... its easier */
570
  if (Qp) {
571
    *Qp = Q = mpz_matrix_Alloc(nr,nr);
572
    if (!Q) {
573
      mpz_matrix_errormsg("DomRightHermite", "outofmem", "out of memory space");
574
      value_clear(tmp);
575
      return;
576
    }
577
    Vector_Set(Q->p_Init,0,nr*nr);            /* zero's */
578
    for (i=0;i<nr;i++)                      /* with diagonal of 1's */
579
      value_set_si(Q->p[i][i],1);
580
  }
581
  else
582
    Q = (mpz_matrix *)0;
583
  
584
  rank = hermite(H,U,Q);
585
  
586
  /* Q is returned transposed */ 
587
  /* Transpose Q */
588
  if (Q) {
589
    for (i=0; i<nr; i++) {
590
      for (j=i+1; j<nr; j++) {
591
        value_assign(tmp,Q->p[i][j]);
592
        value_assign(Q->p[i][j],Q->p[j][i] );
593
        value_assign(Q->p[j][i],tmp);
594
      }
595
    }
596
  }
597
  value_clear(tmp);
598
  return;
599
} /* right_hermite */
600

    
601
void left_hermite(mpz_matrix *A,mpz_matrix **Hp,mpz_matrix **Qp,mpz_matrix **Up) {
602
  
603
  mpz_matrix *H, *HT, *Q, *U;
604
  int i, j, nc, nr, rank;
605
  mpz_t tmp;
606
  
607
  /* Computes left form: A = HQ , AU = H , 
608
     T    T T    T T   T
609
     using right form  A  = Q H  , U A = H */
610
  
611
  nr = A->NbRows;
612
  nc = A->NbColumns;
613
  
614
  /* HT = A transpose */
615
  HT = mpz_matrix_Alloc(nc, nr);
616
  if (!HT) {
617
    mpz_matrix_errormsg("DomLeftHermite", "outofmem", "out of memory space");
618
    return;
619
  }
620
  value_init(tmp);
621
  for (i=0; i<nr; i++)
622
    for (j=0; j<nc; j++)
623
      value_assign(HT->p[j][i],A->p[i][j]);
624
  
625
  /* U = I */
626
  if (Up) {
627
    *Up = U = mpz_matrix_Alloc(nc,nc);
628
    if (!U) {
629
      mpz_matrix_errormsg("DomLeftHermite", "outofmem", "out of memory space");
630
      value_clear(tmp);
631
      return;
632
    }
633
    Vector_Set(U->p_Init,0,nc*nc);            /* zero's */
634
    for (i=0;i<nc;i++)                        /* with diagonal of 1's */
635
      value_set_si(U->p[i][i],1);
636
  }
637
  else U=(mpz_matrix *)0;
638
  
639
  /* Q = I */
640
  if (Qp) {
641
    *Qp = Q = mpz_matrix_Alloc(nc, nc);
642
    if (!Q) {
643
      mpz_matrix_errormsg("DomLeftHermite", "outofmem", "out of memory space");
644
      value_clear(tmp);
645
      return;
646
    }
647
    Vector_Set(Q->p_Init,0,nc*nc);            /* zero's */
648
    for (i=0;i<nc;i++)                        /* with diagonal of 1's */
649
      value_set_si(Q->p[i][i],1);
650
  }
651
  else Q=(mpz_matrix *)0;
652
  rank = hermite(HT,U,Q);
653
  
654
  /* H = HT transpose */
655
  *Hp = H = mpz_matrix_Alloc(nr,nc);
656
  if (!H) {
657
    mpz_matrix_errormsg("DomLeftHermite", "outofmem", "out of memory space");
658
    value_clear(tmp);
659
    return;
660
  }
661
  for (i=0; i<nr; i++)
662
    for (j=0;j<nc;j++)
663
      value_assign(H->p[i][j],HT->p[j][i]);
664
  mpz_matrix_Free(HT);
665
  
666
  /* Transpose U */
667
  if (U) {
668
    for (i=0; i<nc; i++) {
669
      for (j=i+1; j<nc; j++) {
670
        value_assign(tmp,U->p[i][j]);
671
        value_assign(U->p[i][j],U->p[j][i] );
672
        value_assign(U->p[j][i],tmp);
673
      }
674
    }
675
  }
676
} /* left_hermite */
677

    
678
/*
679
 * Given a integer matrix 'Mat'(k x k), compute its inverse rational matrix 
680
 * 'MatInv' k x (k+1). The last column of each row in matrix MatInv is used 
681
 * to store the common denominator of the entries in a row. The output is 1,
682
 * if 'Mat' is non-singular (invertible), otherwise the output is 0. Note:: 
683
 * (1) mpz_matrix 'Mat' is modified during the inverse operation.
684
 * (2) mpz_matrix 'MatInv' must be preallocated before passing into this function.
685
 */
686
int MatInverse(mpz_matrix *Mat,mpz_matrix *MatInv ) {
687
  
688
  int i, k, j, c;
689
  mpz_t x, gcd, piv;
690
  mpz_t m1,m2;
691
  
692
  if(Mat->NbRows != Mat->NbColumns) {
693
   fprintf(stderr,"Trying to invert a non-square matrix !\n");
694
    return 0;
695
  }
696
  
697
  /* Initialize all the 'mpz_t' variables */
698
  value_init(x);  value_init(gcd); value_init(piv);
699
  value_init(m1); value_init(m2);
700

    
701
  k = Mat->NbRows; 
702

    
703
  /* Initialise MatInv */
704
  Vector_Set(MatInv->p[0],0,k*(k+1));
705

    
706
  /* Initialize 'MatInv' to Identity matrix form. Each diagonal entry is set*/
707
  /* to 1. Last column of each row (denominator of each entry in a row) is  */
708
  /* also set to 1.                                                         */ 
709
  for(i=0;i<k;++i) {
710
    value_set_si(MatInv->p[i][i],1);        
711
    value_set_si(MatInv->p[i][k],1);        /* denum */
712
  }  
713
  /* Apply Gauss-Jordan elimination method on the two matrices 'Mat' and  */
714
  /* 'MatInv' in parallel.                                                */
715
  for(i=0;i<k;++i) {
716
    
717
    /* Check if the diagonal entry (new pivot) is non-zero or not */
718
    if(value_zero_p(Mat->p[i][i])) {           
719
      
720
      /* Search for a non-zero pivot down the column(i) */
721
      for(j=i;j<k;++j)      
722
        if(value_notzero_p(Mat->p[j][i]))
723
          break;
724
      
725
      /* If no non-zero pivot is found, the matrix 'Mat' is non-invertible */
726
      /* Return 0.                                                         */
727
      if(j==k) {
728
        
729
        /* Clear all the 'mpz_t' variables */
730
        value_clear(x);  value_clear(gcd); value_clear(piv);
731
        value_clear(m1); value_clear(m2);
732
        return 0;
733
      }        
734
      
735
      /* Exchange the rows, row(i) and row(j) so that the diagonal element */
736
      /* Mat->p[i][i] (pivot) is non-zero. Repeat the same operations on    */
737
      /* matrix 'MatInv'.                                                   */
738
      for(c=0;c<k;++c) {
739

    
740
        /* Interchange rows, row(i) and row(j) of matrix 'Mat'    */
741
        value_assign(x,Mat->p[j][c]);
742
        value_assign(Mat->p[j][c],Mat->p[i][c]);
743
        value_assign(Mat->p[i][c],x);
744
        
745
        /* Interchange rows, row(i) and row(j) of matrix 'MatInv' */
746
        value_assign(x,MatInv->p[j][c]);
747
        value_assign(MatInv->p[j][c],MatInv->p[i][c]);
748
        value_assign(MatInv->p[i][c],x);
749
      }
750
    }
751
    
752
    /* Make all the entries in column(i) of matrix 'Mat' zero except the */
753
    /* diagonal entry. Repeat the same sequence of operations on matrix  */
754
    /* 'MatInv'.                                                         */
755
    for(j=0;j<k;++j) {
756
      if (j==i) continue;                 /* Skip the pivot */
757
      value_assign(x,Mat->p[j][i]);
758
      if(value_notzero_p(x)) {
759
        value_assign(piv,Mat->p[i][i]);
760
        Gcd(x,piv,&gcd);
761
        if (value_notone_p(gcd) ) {
762
          value_division(x,x,gcd);
763
          value_division(piv,piv,gcd);
764
        }
765
        for(c=((j>i)?i:0);c<k;++c) {
766
          value_multiply(m1,piv,Mat->p[j][c]);
767
          value_multiply(m2,x,Mat->p[i][c]);
768
          value_substract(Mat->p[j][c],m1,m2); 
769
        }
770
        for(c=0;c<k;++c) {
771
          value_multiply(m1,piv,MatInv->p[j][c]);
772
          value_multiply(m2,x,MatInv->p[i][c]);
773
          value_substract(MatInv->p[j][c],m1,m2);
774
        }
775
              
776
        /* Simplify row(j) of the two matrices 'Mat' and 'MatInv' by */
777
        /* dividing the rows with the common GCD.                     */
778
        Vector_Gcd(&MatInv->p[j][0],k,&m1);
779
        Vector_Gcd(&Mat->p[j][0],k,&m2);
780
        Gcd(m1,m2,&gcd);
781
        if(value_notone_p(gcd)) {
782
          for(c=0;c<k;++c) {
783
            value_division(Mat->p[j][c],Mat->p[j][c],gcd);
784
            value_division(MatInv->p[j][c],MatInv->p[j][c],gcd);
785
          }
786
        }
787
      }
788
    }
789
  }
790
  
791
  /* Simplify every row so that 'Mat' reduces to Identity matrix. Perform  */
792
  /* the same sequence of operations on the matrix 'MatInv'.               */
793
  for(j=0;j<k;++j) {
794
    value_assign(MatInv->p[j][k],Mat->p[j][j]);
795
    
796
    /* Make the last column (denominator of each entry) of every row greater */
797
    /* than zero.                                                            */
798
    Vector_Normalize_Positive(&MatInv->p[j][0],k+1,k); 
799
  }
800
  
801
  /* Clear all the 'mpz_t' variables */
802
  value_clear(x);  value_clear(gcd); value_clear(piv);
803
  value_clear(m1); value_clear(m2);
804

    
805
  return 1;
806
} /* Mat_Inverse */
807

    
808
/*
809
 * Given (m x n) integer matrix 'X' and n x (k+1) rational matrix 'P', compute
810
 * the rational m x (k+1) rational matrix  'S'. The last column in each row of
811
 * the rational matrices is used to store the common denominator of elements
812
 * in a row.                              
813
 */
814
void rat_prodmat(mpz_matrix *S,mpz_matrix *X,mpz_matrix *P) {
815
  
816
  int i,j,k;
817
  int last_column_index = P->NbColumns - 1;
818
  mpz_t lcm, old_lcm,gcd,last_column_entry,s1,s2;
819
  mpz_t m1,m2;
820
  
821
  /* Initialize all the 'mpz_t' variables */
822
  value_init(lcm); value_init(old_lcm); value_init(gcd);
823
  value_init(last_column_entry); value_init(s1); value_init(s2);
824
  value_init(m1); value_init(m2);
825

    
826
  /* Compute the LCM of last column entries (denominators) of rows */
827
  value_assign(lcm,P->p[0][last_column_index]);        
828
  for(k=1;k<P->NbRows;++k) {
829
    value_assign(old_lcm,lcm);
830
    value_assign(last_column_entry,P->p[k][last_column_index]);
831
    Gcd(lcm,last_column_entry,&gcd);
832
    value_division(m1,last_column_entry,gcd);
833
    value_multiply(lcm,lcm,m1);
834
  }
835
  
836
  /* S[i][j] = Sum(X[i][k] * P[k][j] where Sum is extended over k = 1..nbrows*/
837
  for(i=0;i<X->NbRows;++i)
838
    for(j=0;j<P->NbColumns-1;++j) {
839
      
840
      /* Initialize s1 to zero. */
841
      value_set_si(s1,0);
842
      for(k=0;k<P->NbRows;++k) {
843
        
844
        /* If the LCM of last column entries is one, simply add the products */
845
        if(value_one_p(lcm)) {
846
          value_set_si(s2,0);
847
          value_multiply(s2,X->p[i][k],P->p[k][j]);
848
          value_addto(s1,s1,s2);
849
        }  
850
        
851
        /* Numerator (num) and denominator (denom) of S[i][j] is given by :- */
852
        /* numerator  = Sum(X[i][k]*P[k][j]*lcm/P[k][last_column_index]) and */
853
        /* denominator= lcm where Sum is extended over k = 1..nbrows.        */
854
        else {
855
          value_multiply(m1,X->p[i][k],P->p[k][j]);
856
          value_division(m2,lcm,P->p[k][last_column_index]);
857
          value_multiply(s2,m1,m2);
858
          value_addto(s1,s1,s2);
859
        }
860
      }        
861
      value_assign(S->p[i][j],s1);
862
    }
863
  
864
  for(i=0;i<S->NbRows;++i) {
865
    value_assign(S->p[i][last_column_index],lcm);
866

    
867
    /* Normalize the rows so that last element >=0 */
868
    Vector_Normalize_Positive(&S->p[i][0],S->NbColumns,S->NbColumns-1);
869
  }
870
  
871
  /* Clear all the 'mpz_t' variables */
872
  value_clear(lcm); value_clear(old_lcm); value_clear(gcd);
873
  value_clear(last_column_entry); value_clear(s1); value_clear(s2);
874
  value_clear(m1); value_clear(m2);
875
 
876
  return;
877
} /* rat_prodmat */
878

    
879
/*
880
 * Given a matrix 'Mat' and vector 'p1', compute the matrix-vector product 
881
 * and store the result in vector 'p2'. 
882
 */
883
void mpz_matrix_Vector_Product(mpz_matrix *Mat,mpz_t *p1,mpz_t *p2) {
884

    
885
  int NbRows, NbColumns, i, j;
886
  mpz_t **cm, *q, *cp1, *cp2;
887
  mpz_t s;
888
  
889
  value_init(s);
890
  NbRows=Mat->NbRows;
891
  NbColumns=Mat->NbColumns;
892
  
893
  cm = Mat->p;
894
  cp2 = p2;
895
  for(i=0;i<NbRows;i++) {
896
    q = *cm++;
897
    cp1 = p1;
898
    value_multiply(*cp2,*q,*cp1);
899
    q++;
900
    cp1++;
901
    
902
    /* *cp2 = *q++ * *cp1++ */
903
    for(j=1;j<NbColumns;j++) {
904
      
905
      value_set_si(s,0);
906
      value_multiply(s,*q, *cp1);
907
      value_addto(*cp2,*cp2,s);
908
      q++;
909
      cp1++;
910
    }
911
    cp2++;
912
  }
913
  value_clear(s);
914
  return;
915
} /* mpz_matrix_Vector_Product */
916

    
917
/*
918
 * Given a vector 'p1' and a matrix 'Mat', compute the vector-matrix product 
919
 * and store the result in vector 'p2'
920
 */
921
void Vector_mpz_matrix_Product(mpz_t *p1,mpz_matrix *Mat,mpz_t *p2) {
922
  
923
  int NbRows, NbColumns, i, j;
924
  mpz_t **cm, *cp1, *cp2;
925
  mpz_t s;
926
  
927
  value_init(s);
928
  NbRows=Mat->NbRows;
929
  NbColumns=Mat->NbColumns;
930
  cp2 = p2;
931
  cm  = Mat->p;
932
  for (j=0;j<NbColumns;j++) {
933
    cp1 = p1;
934
    value_multiply(*cp2,*(*cm+j),*cp1);
935
    cp1++;
936
    
937
    /* *cp2= *(*cm+j) * *cp1++; */
938
    for (i=1;i<NbRows;i++) {
939
      
940
      value_set_si(s,0);
941
      value_multiply(s,*(*(cm+i)+j),*cp1);
942
      value_addto(*cp2,*cp2,s);
943
      cp1++;
944
    }
945
    cp2++;
946
  }
947
  value_clear(s);
948
  return;
949
} /* Vector_mpz_matrix_Product */
950

    
951
/* 
952
 * Given matrices 'Mat1' and 'Mat2', compute the matrix product and store in 
953
 * matrix 'Mat3' 
954
 */
955
void mpz_matrix_Product(mpz_matrix *Mat1,mpz_matrix *Mat2,mpz_matrix *Mat3) {
956
  
957
  int Size, i, j, k;
958
  unsigned NbRows, NbColumns;
959
  mpz_t **q1, **q2, *p1, *p3,sum,s;
960
  
961
  NbRows    = Mat1->NbRows;
962
  NbColumns = Mat2->NbColumns;
963
  
964
  Size      = Mat1->NbColumns;
965
  if(Mat2->NbRows!=Size||Mat3->NbRows!=NbRows||Mat3->NbColumns!=NbColumns) {
966
    fprintf(stderr, "? mpz_matrix_Product : incompatable matrix dimension\n");
967
    return;
968
  }     
969
  value_init(sum); value_init(s);
970
  p3 = Mat3->p_Init;
971
  q1 = Mat1->p;
972
  q2 = Mat2->p;
973
  
974
  /* Mat3[i][j] = Sum(Mat1[i][k]*Mat2[k][j] where sum is over k = 1..nbrows */
975
  for (i=0;i<NbRows;i++) {
976
    for (j=0;j<NbColumns;j++) {
977
      p1 = *(q1+i);
978
      value_set_si(sum,0);
979
      for (k=0;k<Size;k++) {
980
        
981
        /* sum+=*p1++ * *(*(q2+k)+j); */
982
        value_set_si(s,0);
983
        value_multiply(s,*p1, *(*(q2+k)+j));
984
        value_addto(sum,sum,s);
985
        p1++;
986
      }
987
      value_assign(*p3,sum);
988
      p3++;
989
    }
990
  }
991
  value_clear(sum); value_clear(s);
992
  return;
993
} /* mpz_matrix_Product */
994
  
995
/*
996
 * Given a rational matrix 'Mat'(k x k), compute its inverse rational matrix 
997
 * 'MatInv' k x k. The last column of each row in matrix MatInv is used 
998
 * to store the common denominator of the entries in a row. The output is 1,
999
 * if 'Mat' is non-singular (invertible), otherwise the output is 0. Note:: 
1000
 * (1) mpz_matrix 'Mat' is modified during the inverse operation.
1001
 * (2) mpz_matrix 'MatInv' must be preallocated before passing into this function.
1002
 */
1003
int mpz_matrix_Inverse(mpz_matrix *Mat,mpz_matrix *MatInv ) {
1004
  
1005
  int i, k, j, c;
1006
  mpz_t x, gcd, piv;
1007
  mpz_t m1,m2;
1008
  mpz_t *den;
1009
  
1010
  if(Mat->NbRows != Mat->NbColumns) {
1011
   fprintf(stderr,"Trying to invert a non-square matrix !\n");
1012
    return 0;
1013
  }
1014
  
1015
  /* Initialize all the 'mpz_t' variables */
1016
  value_init(x);  value_init(gcd); value_init(piv);
1017
  value_init(m1); value_init(m2);
1018

    
1019
  k = Mat->NbRows; 
1020

    
1021
  /* Initialise MatInv */
1022
  Vector_Set(MatInv->p[0],0,k*k);
1023

    
1024
  /* Initialize 'MatInv' to Identity matrix form. Each diagonal entry is set*/
1025
  /* to 1. Last column of each row (denominator of each entry in a row) is  */
1026
  /* also set to 1.                                                         */ 
1027
  for(i=0;i<k;++i) {
1028
    value_set_si(MatInv->p[i][i],1);        
1029
    // value_set_si(MatInv->p[i][k],1);        /* denum */
1030
  }  
1031
  /* Apply Gauss-Jordan elimination method on the two matrices 'Mat' and  */
1032
  /* 'MatInv' in parallel.                                                */
1033
  for(i=0;i<k;++i) {
1034
    
1035
    /* Check if the diagonal entry (new pivot) is non-zero or not */
1036
    if(value_zero_p(Mat->p[i][i])) {           
1037
      
1038
      /* Search for a non-zero pivot down the column(i) */
1039
      for(j=i;j<k;++j)      
1040
        if(value_notzero_p(Mat->p[j][i]))
1041
          break;
1042
      
1043
      /* If no non-zero pivot is found, the matrix 'Mat' is non-invertible */
1044
      /* Return 0.                                                         */
1045
      if(j==k) {
1046
        
1047
        /* Clear all the 'mpz_t' variables */
1048
        value_clear(x);  value_clear(gcd); value_clear(piv);
1049
        value_clear(m1); value_clear(m2);
1050
        return 0;
1051
      }        
1052
      
1053
      /* Exchange the rows, row(i) and row(j) so that the diagonal element */
1054
      /* Mat->p[i][i] (pivot) is non-zero. Repeat the same operations on    */
1055
      /* matrix 'MatInv'.                                                   */
1056
      for(c=0;c<k;++c) {
1057

    
1058
        /* Interchange rows, row(i) and row(j) of matrix 'Mat'    */
1059
        value_assign(x,Mat->p[j][c]);
1060
        value_assign(Mat->p[j][c],Mat->p[i][c]);
1061
        value_assign(Mat->p[i][c],x);
1062
        
1063
        /* Interchange rows, row(i) and row(j) of matrix 'MatInv' */
1064
        value_assign(x,MatInv->p[j][c]);
1065
        value_assign(MatInv->p[j][c],MatInv->p[i][c]);
1066
        value_assign(MatInv->p[i][c],x);
1067
      }
1068
    }
1069
    
1070
    /* Make all the entries in column(i) of matrix 'Mat' zero except the */
1071
    /* diagonal entry. Repeat the same sequence of operations on matrix  */
1072
    /* 'MatInv'.                                                         */
1073
    for(j=0;j<k;++j) {
1074
      if (j==i) continue;                 /* Skip the pivot */
1075
      value_assign(x,Mat->p[j][i]);
1076
      if(value_notzero_p(x)) {
1077
        value_assign(piv,Mat->p[i][i]);
1078
        Gcd(x,piv,&gcd);
1079
        if (value_notone_p(gcd) ) {
1080
          value_division(x,x,gcd);
1081
          value_division(piv,piv,gcd);
1082
        }
1083
        for(c=((j>i)?i:0);c<k;++c) {
1084
          value_multiply(m1,piv,Mat->p[j][c]);
1085
          value_multiply(m2,x,Mat->p[i][c]);
1086
          value_substract(Mat->p[j][c],m1,m2); 
1087
        }
1088
        for(c=0;c<k;++c) {
1089
          value_multiply(m1,piv,MatInv->p[j][c]);
1090
          value_multiply(m2,x,MatInv->p[i][c]);
1091
          value_substract(MatInv->p[j][c],m1,m2);
1092
        }
1093
              
1094
        /* Simplify row(j) of the two matrices 'Mat' and 'MatInv' by */
1095
        /* dividing the rows with the common GCD.                     */
1096
        Vector_Gcd(&MatInv->p[j][0],k,&m1);
1097
        Vector_Gcd(&Mat->p[j][0],k,&m2);
1098
        Gcd(m1,m2,&gcd);
1099
        if(value_notone_p(gcd)) {
1100
          for(c=0;c<k;++c) {
1101
            value_division(Mat->p[j][c],Mat->p[j][c],gcd);
1102
            value_division(MatInv->p[j][c],MatInv->p[j][c],gcd);
1103
          }
1104
        }
1105
      }
1106
    }
1107
  }
1108
  
1109
  /* Find common denom for each row */ 
1110
   den = (mpz_t *)malloc(k*sizeof(mpz_t));
1111
   value_set_si(x,1);
1112
   for(j=0 ; j<k ; ++j) {
1113
     value_init(den[j]);
1114
     value_assign(den[j],Mat->p[j][j]);
1115
     
1116
     /* gcd is always positive */
1117
     Vector_Gcd(&MatInv->p[j][0],k,&gcd);
1118
     Gcd(gcd,den[j],&gcd);
1119
     if (value_neg_p(den[j])) 
1120
       value_oppose(gcd,gcd); /* make denominator positive */
1121
     if (value_notone_p(gcd)) {
1122
       for (c=0; c<k; c++) 
1123
         value_division(MatInv->p[j][c],MatInv->p[j][c],gcd); /* normalize */
1124
       value_division(den[j],den[j],gcd);
1125
     }  
1126
     Gcd(x,den[j],&gcd);
1127
     value_division(m1,den[j],gcd);
1128
     value_multiply(x,x,m1);
1129
   }
1130
   if (value_notone_p(x)) 
1131
     for(j=0 ; j<k ; ++j) {       
1132
       for (c=0; c<k; c++) {
1133
         value_division(m1,x,den[j]);
1134
         value_multiply(MatInv->p[j][c],MatInv->p[j][c],m1);  /* normalize */
1135
       }
1136
     }
1137

    
1138
   /* Clear all the 'mpz_t' variables */
1139
   for(j=0 ; j<k ; ++j) {
1140
     value_clear(den[j]);
1141
   }  
1142
   value_clear(x);  value_clear(gcd); value_clear(piv);
1143
   value_clear(m1); value_clear(m2);
1144
   free(den);
1145
   
1146
   return 1;
1147
} /* mpz_matrix_Inverse */
1148

    
1149
#endif /* #if 0 */
1150

    
1151

    
1152

    
1153

    
1154

    
1155