IndexVector::IndexVector(const IndexVector &rhs){ _length=rhs.length(); if(_length>0) { _data = new int[_length]; memcpy(_data,rhs.data(),_length*sizeof(int) ); } else{ _data=0; } }
CRSIndexMatrix::CRSIndexMatrix(IndexVector &row, IndexVector &col, IndexVector &values){ int idx, rowidx, datalen, rowdiff, offset, length=row.length(); /* *** determine number of rows and cols */ int nRow=0,nCol=0; for(int k=0;k<length;k++){ if(row(k)>nRow) nRow=row(k); if(col(k)>nCol) nCol=col(k); } nRow+=1; nCol+=1; /* row and col index start with 0... */ /* *** initialize temporary variables */ int* data = new int[length]; int* colindex = new int[length]; int* rowptr = new int[nRow+1]; int* rowoff = new int[nRow]; memset(rowptr,0,(nRow+1)*sizeof(int)); /* *** create rowptr */ for(int k=0 ; k<length ; k++){ rowptr[row(k)+1]++; } for(int k=1 ; k<nRow ; k++){ rowptr[k+1] = rowptr[k+1]+rowptr[k]; } memcpy(rowoff,rowptr,nRow*sizeof(int)); /* *** copy column index and values */ for(int k=0;k<length;k++){ idx = rowoff[ row(k) ]; rowoff[row(k) ]++; data[idx] = values(k); colindex[idx] = col(k); } /* *** sort values of each row */ for(int k=0;k<nRow;k++){ if(rowptr[k+1]>rowptr[k] ){ insort(colindex+rowptr[k],data+rowptr[k],rowptr[k+1]-rowptr[k]); } } /* *** sum up entries with same indices and compress the data structures */ idx=0; rowidx=0; rowdiff=0; for(int k=0;k<length;){ while(rowptr[rowidx+1]==k){ rowidx++; rowptr[rowidx]-=rowdiff; } /* *** sum upp values with similar row and column indices */ offset=1; while(k+offset < rowptr[rowidx+1] && colindex[k] == colindex[k+offset]){ data[k] += data[k+offset]; offset+=1; } if(data[k] != 0){ data[idx] = data[k] ; colindex[idx] = colindex[k]; idx++; rowdiff+=(offset-1); }else{ /* *** ignore values that are 0 */ rowdiff+=offset; } k+=offset; } datalen=idx; for(int k=rowidx+1;k<nRow+1;k++) rowptr[k]= datalen; /* *** set private variables */ _data = new int[datalen]; memcpy(_data, data, datalen*sizeof(int) ); _colindex = new int[datalen]; memcpy(_colindex, colindex, datalen*sizeof(int) ); _rowptr = rowptr; _cols = nCol; _rows = nRow; _nonZeros = datalen; delete []data; delete []colindex; }
void IndexVector::add(IndexVector &x, int alpha){ assert(_length==x.length()); for(int k=0;k<_length;k++) _data[k]+=alpha*x(k); }
/* *** math operations *******************************************/ int IndexVector::dot(IndexVector &x){ assert(_length==x.length()); int tmp=0; for(int k=0;k<_length;k++) tmp+= _data[k]*x(k); return tmp; }