superobs.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* File: superobs.c
  2. *
  3. * Created: 2 Sep 2008
  4. *
  5. * Last modified: 2 Sep 2008
  6. * Author: Pavel Sakov
  7. * NERSC
  8. *
  9. * Purpose: Sorting of observations according to model grid cells.
  10. *
  11. * Description: Given array of pivot indices for each observation, sort them
  12. * in such a way that observations within each model grid cell
  13. * will cluster together.
  14. *
  15. * Modifications: none
  16. */
  17. #include <math.h>
  18. #include "cfortran.h"
  19. #define IMAX 4096
  20. #define JMAX 4096
  21. typedef struct {
  22. int i;
  23. int j;
  24. int index;
  25. } indexedvalue;
  26. static int comp(const void* p1, const void* p2)
  27. {
  28. indexedvalue* v1 = (indexedvalue*) p1;
  29. indexedvalue* v2 = (indexedvalue*) p2;
  30. if (v1->i > v2->i)
  31. return 1;
  32. else if (v1->i < v2->i)
  33. return -1;
  34. else if (v1->j > v2->j)
  35. return 1;
  36. else if (v1->j < v2->j)
  37. return -1;
  38. return 0;
  39. }
  40. void sortgriddedobs(double pn, int ipiv[], int jpiv[], int sorted[])
  41. {
  42. int n = (int) pn;
  43. indexedvalue* iv = malloc(n * sizeof(indexedvalue));
  44. int i;
  45. for (i = 0; i < n; ++i) {
  46. int ii = ipiv[i];
  47. int jj = jpiv[i];
  48. if (ii <= 0 || ii > IMAX || jj <= 0 || jj > JMAX) {
  49. fprintf(stderr, "ERROR: superobs.c: sortgriddedobs(): ipiv(%d) = %d or jpiv(%d) = %d out of bounds\n", i, ii, i, jj);
  50. exit(1);
  51. }
  52. iv[i].i = ii;
  53. iv[i].j = jj;
  54. iv[i].index = i;
  55. }
  56. qsort(iv, n, sizeof(indexedvalue), comp);
  57. for (i = 0; i < n; ++i)
  58. sorted[i] = iv[i].index + 1;
  59. free(iv);
  60. }
  61. FCALLSCSUB4(sortgriddedobs, SORTGRIDDEDOBS, sortgriddedobs, DOUBLE, PINT, PINT, PINT)