csFkeep.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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;
  22. // columns
  23. var n = asize[1];
  24. // nonzero items
  25. var nz = 0;
  26. // loop columns
  27. for (var j = 0; j < n; j++) {
  28. // get current location of col j
  29. var p = aptr[j];
  30. // record new location of col j
  31. aptr[j] = nz;
  32. for (; p < aptr[j + 1]; p++) {
  33. // check we need to keep this item
  34. if (callback(aindex[p], j, avalues ? avalues[p] : 1, other)) {
  35. // keep A(i,j)
  36. aindex[nz] = aindex[p];
  37. // check we need to process values (pattern only)
  38. if (avalues) {
  39. avalues[nz] = avalues[p];
  40. }
  41. // increment nonzero items
  42. nz++;
  43. }
  44. }
  45. }
  46. // finalize A
  47. aptr[n] = nz;
  48. // trim arrays
  49. aindex.splice(nz, aindex.length - nz);
  50. // check we need to process values (pattern only)
  51. if (avalues) {
  52. avalues.splice(nz, avalues.length - nz);
  53. }
  54. // return number of nonzero items
  55. return nz;
  56. }