o_distrib.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include <stdlib.h>
  2. #include <unistd.h>
  3. #include <grass/gis.h>
  4. #include <grass/glocale.h>
  5. #include "method.h"
  6. #define STATS "r.stats"
  7. /* function prototypes */
  8. static int o_out(FILE *, long, long);
  9. int o_distrib(const char *basemap, const char *covermap, const char *outputmap, int usecats)
  10. {
  11. char *me = "o_distrib";
  12. char command[1024];
  13. long csum, area, catb, basecat, covercat;
  14. double sum, tot;
  15. long stat, cat, total_count;
  16. char *tempfile1, *tempfile2;
  17. FILE *fd1, *fd2;
  18. tempfile1 = G_tempfile();
  19. tempfile2 = G_tempfile();
  20. sprintf(command, "%s -cn input=\"%s,%s\" fs=space > %s", STATS, basemap,
  21. covermap, tempfile1);
  22. if (stat = system(command)) {
  23. unlink(tempfile1);
  24. G_fatal_error(_("%s: running %s command"), me, STATS);
  25. }
  26. fd1 = fopen(tempfile1, "r");
  27. fd2 = fopen(tempfile2, "w");
  28. if (fd1 == NULL || fd2 == NULL) {
  29. unlink(tempfile1);
  30. unlink(tempfile2);
  31. G_fatal_error(_("%s: unable to open temporary file"), me);
  32. }
  33. o_out(fd2, 0L, 0); /* force at least one reclass rule */
  34. catb = 0;
  35. csum = 0;
  36. /* fprintf(stderr,"***** Stage 1 - Calculating sums ****\n"); */
  37. while (fscanf(fd1, "%ld %ld %ld", &basecat, &covercat, &area) == 3) {
  38. if (catb != basecat) {
  39. o_out(fd2, catb, csum);
  40. csum = 0;
  41. catb = basecat;
  42. }
  43. csum += area;
  44. }
  45. o_out(fd2, catb, csum);
  46. rewind(fd1);
  47. freopen(tempfile2, "r", fd2);
  48. /* fprintf(stderr,"***** Stage 2 - Calculating percents of values in cover ****\n"); */
  49. catb = 0;
  50. tot = 0;
  51. total_count = 0;
  52. while (fscanf(fd1, "%ld %ld %ld", &basecat, &covercat, &area) == 3) {
  53. if (catb != basecat && basecat > 0) {
  54. if (fscanf(fd2, "%ld %ld", &cat, &total_count) != 2)
  55. return (1);
  56. catb = basecat;
  57. /* fprintf(stderr,"Total (must be 100): %lf\n",tot); */
  58. tot = 0;
  59. }
  60. if (basecat) {
  61. sum = (double)(100.0 * area) / total_count;
  62. fprintf(stderr, "%8ld %8ld %f\n", basecat, covercat, sum);
  63. /*tot+=sum;
  64. fprintf(stderr,"Area: %ld Tot: %ld totsum: %lf\n",area,total_count,tot); */
  65. }
  66. }
  67. fclose(fd1);
  68. fclose(fd2);
  69. unlink(tempfile1);
  70. unlink(tempfile2);
  71. return (stat);
  72. }
  73. static int o_out(FILE * fd, long cat, long sum)
  74. {
  75. if (sum == 0 || cat == 0)
  76. return -1;
  77. fprintf(fd, "%ld %ld\n", cat, sum);
  78. return 0;
  79. }