csFkeep.js (1716B)
1 /** 2 * Keeps entries in the matrix when the callback function returns true, removes the entry otherwise 3 * 4 * @param {Matrix} a The sparse matrix 5 * @param {function} callback The callback function, function will be invoked with the following args: 6 * - The entry row 7 * - The entry column 8 * - The entry value 9 * - The state parameter 10 * @param {any} other The state 11 * 12 * @return The number of nonzero elements in the matrix 13 * 14 * Reference: http://faculty.cse.tamu.edu/davis/publications.html 15 */ 16 export function csFkeep(a, callback, other) { 17 // a arrays 18 var avalues = a._values; 19 var aindex = a._index; 20 var aptr = a._ptr; 21 var asize = a._size; // columns 22 23 var n = asize[1]; // nonzero items 24 25 var nz = 0; // loop columns 26 27 for (var j = 0; j < n; j++) { 28 // get current location of col j 29 var p = aptr[j]; // record new location of col j 30 31 aptr[j] = nz; 32 33 for (; p < aptr[j + 1]; p++) { 34 // check we need to keep this item 35 if (callback(aindex[p], j, avalues ? avalues[p] : 1, other)) { 36 // keep A(i,j) 37 aindex[nz] = aindex[p]; // check we need to process values (pattern only) 38 39 if (avalues) { 40 avalues[nz] = avalues[p]; 41 } // increment nonzero items 42 43 44 nz++; 45 } 46 } 47 } // finalize A 48 49 50 aptr[n] = nz; // trim arrays 51 52 aindex.splice(nz, aindex.length - nz); // check we need to process values (pattern only) 53 54 if (avalues) { 55 avalues.splice(nz, avalues.length - nz); 56 } // return number of nonzero items 57 58 59 return nz; 60 }