xref: /petsc/src/mat/utils/matstash.c (revision 416022c9818a71eecdf06d41c1abd586feaab60e)
1 #include "vec/vecimpl.h"
2 #include "matimpl.h"
3 
4 #define CHUNCKSIZE   100
5 /*
6    This stash is currently used for all the parallel matrix implementations.
7    Perhaps this code ultimately should be moved elsewhere.
8 
9    This is a simple minded stash. Do a linear search to determine if
10    in stash, if not add to end.
11 */
12 
13 int StashInitialize_Private(Stash *stash)
14 {
15   stash->nmax  = 0;
16   stash->n     = 0;
17   stash->array = 0;
18   stash->idx   = 0;
19   stash->idy   = 0;
20   return 0;
21 }
22 
23 int StashBuild_Private(Stash *stash)
24 {
25   stash->nmax  = CHUNCKSIZE; /* completely arbitrary number */
26   stash->n     = 0;
27   stash->array = (Scalar *) PETSCMALLOC( stash->nmax*(2*sizeof(int) +
28                             sizeof(Scalar))); CHKPTRQ(stash->array);
29   stash->idx   = (int *) (stash->array + stash->nmax); CHKPTRQ(stash->idx);
30   stash->idy   = (int *) (stash->idx + stash->nmax); CHKPTRQ(stash->idy);
31   return 0;
32 }
33 
34 int StashDestroy_Private(Stash *stash)
35 {
36   stash->nmax = stash->n = 0;
37   if (stash->array) {PETSCFREE(stash->array); stash->array = 0;}
38   return 0;
39 }
40 
41 int StashValues_Private(Stash *stash,int row,int n, int *idxn,
42                         Scalar *values,InsertMode addv)
43 {
44   int    i,j,N = stash->n,found,*n_idx, *n_idy;
45   Scalar val,*n_array;
46 
47   for ( i=0; i<n; i++ ) {
48     found = 0;
49     val = *values++;
50     for ( j=0; j<N; j++ ) {
51       if ( stash->idx[j] == row && stash->idy[j] == idxn[i]) {
52         /* found a match */
53         if (addv == ADD_VALUES) stash->array[j] += val;
54         else stash->array[j] = val;
55         found = 1;
56         break;
57       }
58     }
59     if (!found) { /* not found so add to end */
60       if ( stash->n == stash->nmax ) {
61         /* allocate a larger stash */
62         n_array = (Scalar *) PETSCMALLOC( (stash->nmax + CHUNCKSIZE)*(
63                                      2*sizeof(int)+sizeof(Scalar)));CHKPTRQ(n_array);
64         n_idx = (int *) (n_array + stash->nmax + CHUNCKSIZE);
65         n_idy = (int *) (n_idx + stash->nmax + CHUNCKSIZE);
66         PetscMemcpy(n_array,stash->array,stash->nmax*sizeof(Scalar));
67         PetscMemcpy(n_idx,stash->idx,stash->nmax*sizeof(int));
68         PetscMemcpy(n_idy,stash->idy,stash->nmax*sizeof(int));
69         if (stash->array) PETSCFREE(stash->array);
70         stash->array = n_array; stash->idx = n_idx; stash->idy = n_idy;
71         stash->nmax += CHUNCKSIZE;
72       }
73       stash->array[stash->n]   = val;
74       stash->idx[stash->n]     = row;
75       stash->idy[stash->n++]   = idxn[i];
76     }
77   }
78   return 0;
79 }
80