readweights.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include <string.h>
  2. #include <stdio.h>
  3. #include <math.h>
  4. #include <grass/gis.h>
  5. #include <grass/glocale.h>
  6. #include "ncb.h"
  7. #include "local_proto.h"
  8. void read_weights(const char *filename)
  9. {
  10. FILE *fp = fopen(filename, "r");
  11. int i, j;
  12. ncb.weights = G_malloc(ncb.nsize * sizeof(DCELL *));
  13. for (i = 0; i < ncb.nsize; i++)
  14. ncb.weights[i] = G_malloc(ncb.nsize * sizeof(DCELL));
  15. if (!fp)
  16. G_fatal_error(_("Unable to open weights file %s"), filename);
  17. for (i = 0; i < ncb.nsize; i++)
  18. for (j = 0; j < ncb.nsize; j++)
  19. if (fscanf(fp, "%lf", &ncb.weights[i][j]) != 1)
  20. G_fatal_error(_("Error reading weights file %s"), filename);
  21. fclose(fp);
  22. }
  23. double gaussian(double factor, double squared_distance)
  24. {
  25. double sigma2 = factor * factor;
  26. return exp(-squared_distance / (2 * sigma2)) / (2 * M_PI * sigma2);
  27. }
  28. double exponential(double factor, double squared_distance)
  29. {
  30. return exp(factor * sqrt(squared_distance));
  31. }
  32. void compute_weights(const char *function_type, double factor)
  33. {
  34. int i, j;
  35. double (*weight) (double, double);
  36. if (!strcmp(function_type, "gaussian")) {
  37. weight = gaussian;
  38. }
  39. else if (!strcmp(function_type, "exponential")) {
  40. weight = exponential;
  41. }
  42. ncb.weights = G_malloc(ncb.nsize * sizeof(DCELL *));
  43. for (i = 0; i < ncb.nsize; i++)
  44. ncb.weights[i] = G_malloc(ncb.nsize * sizeof(DCELL));
  45. for (i = 0; i < ncb.nsize; i++) {
  46. double y = i - ncb.dist;
  47. for (j = 0; j < ncb.nsize; j++) {
  48. double x = j - ncb.dist;
  49. ncb.weights[i][j] = weight(factor, x * x + y * y);
  50. }
  51. }
  52. }