main.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. /****************************************************************************
  2. *
  3. * MODULE: v.kernel
  4. *
  5. * AUTHOR(S): Stefano Menegon, ITC-irst, Trento, Italy
  6. * Radim Blazek (additional kernel functions, network part)
  7. * PURPOSE: Generates a raster density map from vector points data using
  8. * a moving kernel function or
  9. * optionally generates a vector density map on vector network
  10. * with a 1D kernel
  11. * COPYRIGHT: (C) 2004-2011 by the GRASS Development Team
  12. *
  13. * This program is free software under the GNU General Public
  14. * License (>=v2). Read the file COPYING that comes with GRASS
  15. * for details.
  16. *
  17. *****************************************************************************/
  18. #include <math.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <float.h>
  22. #include <string.h>
  23. #include <grass/gis.h>
  24. #include <grass/raster.h>
  25. #include <grass/glocale.h>
  26. #include <grass/gmath.h>
  27. #include <grass/vector.h>
  28. #include "global.h"
  29. static int ndists; /* number of distances in dists */
  30. static double *dists; /* array of all distances < dmax */
  31. static int npoints;
  32. int net = 0;
  33. static double dimension = 2.;
  34. /* define score function L(window size) */
  35. double L(double smooth)
  36. {
  37. int ii;
  38. double resL, n, term;
  39. n = npoints;
  40. resL = 0.;
  41. term = 1. / pow((2. * M_PI), dimension / 2.);
  42. for (ii = 0; ii < ndists; ii++) {
  43. /* resL+= gaussianFunction(dists[ii]/smooth,2.,dimension) - 2. * gaussianKernel(dists[ii]/smooth,term); */
  44. resL +=
  45. gaussianFunction(dists[ii] / smooth, 2.,
  46. dimension) -
  47. 2. * gaussianFunction(dists[ii] / smooth, 1., dimension);
  48. }
  49. if (!net)
  50. resL *= 2.;
  51. resL = (1. / (pow(n, 2.) * pow(smooth, dimension))) *
  52. (resL + n * (gaussianFunction(0., 2., dimension) -
  53. 2. * gaussianFunction(0., 1., dimension))) +
  54. (2. / (n * pow(smooth, dimension))) *
  55. gaussianFunction(0., 1., dimension);
  56. /* resL = (1./(pow(n,2.)*pow(smooth,dimension))) * (resL + n*( gaussianFunction(0.,2.,dimension) - 2. * gaussianKernel(0.,term)) ) + (2./(n*pow(smooth,dimension)))*gaussianKernel(0.,term); */
  57. G_debug(3, "smooth = %e resL = %e", smooth, resL);
  58. G_message(_("\tScore Value=%f\tsmoothing parameter (standard deviation)=%f"),
  59. resL, smooth);
  60. return (resL);
  61. }
  62. int main(int argc, char **argv)
  63. {
  64. struct Option *in_opt, *net_opt, *out_opt;
  65. struct Option *radius_opt, *dsize_opt, *segmax_opt, *netmax_opt,
  66. *multip_opt, *node_opt, *kernel_opt;
  67. struct Flag *flag_o, *flag_q, *flag_normalize, *flag_multiply;
  68. char *desc;
  69. struct Map_info In, Net, Out;
  70. int overwrite;
  71. int fdout = -1, maskfd = -1;
  72. int node_method, kernel_function;
  73. int row, col;
  74. struct Cell_head window;
  75. double gaussian;
  76. double N, E;
  77. CELL *mask = NULL;
  78. DCELL *output_cell = NULL;
  79. double sigma, dmax, segmax, netmax, multip;
  80. char *tmpstr1, *tmpstr2;
  81. double **coordinate;
  82. double sigmaOptimal;
  83. struct GModule *module;
  84. double dsize;
  85. double term = 0;
  86. double gausmax = 0;
  87. int notreachable = 0;
  88. /* Initialize the GIS calls */
  89. G_gisinit(argv[0]);
  90. module = G_define_module();
  91. G_add_keyword(_("vector"));
  92. G_add_keyword(_("kernel density"));
  93. module->label =
  94. _("Generates a raster density map from vector points map.");
  95. module->description = _("Density is computed using a moving kernel. "
  96. "Optionally generates a vector density map on a vector network.");
  97. in_opt = G_define_standard_option(G_OPT_V_INPUT);
  98. in_opt->label = _("Name of input vector map with training points");
  99. in_opt->description = NULL;
  100. net_opt = G_define_standard_option(G_OPT_V_INPUT);
  101. net_opt->key = "net";
  102. net_opt->label = _("Name of input network vector map");
  103. net_opt->description = NULL;
  104. net_opt->required = NO;
  105. net_opt->guisection = _("Network");
  106. out_opt = G_define_option();
  107. out_opt->key = "output";
  108. out_opt->type = TYPE_STRING;
  109. out_opt->key_desc = "name";
  110. out_opt->required = YES;
  111. out_opt->label = _("Name for output raster/vector map");
  112. out_opt->description = _("Outputs vector map if network map is given, otherwise raster map");
  113. radius_opt = G_define_option();
  114. radius_opt->key = "radius";
  115. radius_opt->type = TYPE_DOUBLE;
  116. radius_opt->required = YES;
  117. radius_opt->description = _("Kernel radius in map units");
  118. dsize_opt = G_define_option();
  119. dsize_opt->key = "dsize";
  120. dsize_opt->type = TYPE_DOUBLE;
  121. dsize_opt->required = NO;
  122. dsize_opt->description = _("Discretization error in map units");
  123. dsize_opt->answer = "0.";
  124. segmax_opt = G_define_option();
  125. segmax_opt->key = "segmax";
  126. segmax_opt->type = TYPE_DOUBLE;
  127. segmax_opt->required = NO;
  128. segmax_opt->description = _("Maximum length of segment on network");
  129. segmax_opt->answer = "100.";
  130. segmax_opt->guisection = _("Network");
  131. netmax_opt = G_define_option();
  132. netmax_opt->key = "distmax";
  133. netmax_opt->type = TYPE_DOUBLE;
  134. netmax_opt->required = NO;
  135. netmax_opt->description = _("Maximum distance from point to network");
  136. netmax_opt->answer = "100.";
  137. netmax_opt->guisection = _("Network");
  138. multip_opt = G_define_option();
  139. multip_opt->key = "mult";
  140. multip_opt->type = TYPE_DOUBLE;
  141. multip_opt->required = NO;
  142. multip_opt->description = _("Multiply the density result by this number");
  143. multip_opt->answer = "1.";
  144. node_opt = G_define_option();
  145. node_opt->key = "node";
  146. node_opt->type = TYPE_STRING;
  147. node_opt->required = NO;
  148. node_opt->description = _("Node method");
  149. node_opt->options = "none,split";
  150. node_opt->answer = "none";
  151. desc = NULL;
  152. G_asprintf(&desc,
  153. "none;%s;split;%s",
  154. _("No method applied at nodes with more than 2 arcs"),
  155. _("Equal split (Okabe 2009) applied at nodes"));
  156. node_opt->descriptions = desc;
  157. node_opt->guisection = _("Network");
  158. kernel_opt = G_define_option();
  159. kernel_opt->key = "kernel";
  160. kernel_opt->type = TYPE_STRING;
  161. kernel_opt->required = NO;
  162. kernel_opt->description = _("Kernel function");
  163. kernel_opt->options =
  164. "uniform,triangular,epanechnikov,quartic,triweight,gaussian,cosine";
  165. kernel_opt->answer = "gaussian";
  166. flag_o = G_define_flag();
  167. flag_o->key = 'o';
  168. flag_o->description =
  169. _("Try to calculate an optimal standard deviation with 'stddeviation' taken as maximum (experimental)");
  170. flag_q = G_define_flag();
  171. flag_q->key = 'q';
  172. flag_q->description =
  173. _("Only calculate optimal standard deviation and exit (no map is written)");
  174. flag_normalize = G_define_flag();
  175. flag_normalize->key = 'n';
  176. flag_normalize->description =
  177. _("In network mode, normalize values by sum of density multiplied by length of each segment. Integral over the output map then gives 1.0 * mult");
  178. flag_normalize->guisection = _("Network");
  179. flag_multiply = G_define_flag();
  180. flag_multiply->key = 'm';
  181. flag_multiply->description =
  182. _("In network mode, multiply the result by number of input points");
  183. flag_multiply->guisection = _("Network");
  184. overwrite = G_check_overwrite(argc, argv);
  185. if (G_parser(argc, argv))
  186. exit(EXIT_FAILURE);
  187. if (net_opt->answer) {
  188. if (G_find_vector2(out_opt->answer, G_mapset()))
  189. if (overwrite)
  190. G_warning(_("Vector map <%s> already exists and will be overwritten"),
  191. out_opt->answer);
  192. else
  193. G_fatal_error(_("Vector map <%s> already exists"),
  194. out_opt->answer);
  195. }
  196. else {
  197. if (G_find_raster(out_opt->answer, G_mapset()))
  198. if (overwrite)
  199. G_warning(_("Raster map <%s> already exists and will be overwritten"),
  200. out_opt->answer);
  201. else
  202. G_fatal_error(_("Raster map <%s> already exists"),
  203. out_opt->answer);
  204. }
  205. /*read options */
  206. dmax = atof(radius_opt->answer);
  207. sigma = dmax;
  208. dsize = atof(dsize_opt->answer);
  209. segmax = atof(segmax_opt->answer);
  210. netmax = atof(netmax_opt->answer);
  211. multip = atof(multip_opt->answer);
  212. if (strcmp(node_opt->answer, "none") == 0)
  213. node_method = NODE_NONE;
  214. else if (strcmp(node_opt->answer, "split") == 0)
  215. node_method = NODE_EQUAL_SPLIT;
  216. else
  217. G_fatal_error(_("Unknown node method"));
  218. kernel_function = KERNEL_GAUSSIAN;
  219. if (strcmp(kernel_opt->answer, "uniform") == 0)
  220. kernel_function = KERNEL_UNIFORM;
  221. else if (strcmp(kernel_opt->answer, "triangular") == 0)
  222. kernel_function = KERNEL_TRIANGULAR;
  223. else if (strcmp(kernel_opt->answer, "epanechnikov") == 0)
  224. kernel_function = KERNEL_EPANECHNIKOV;
  225. else if (strcmp(kernel_opt->answer, "quartic") == 0)
  226. kernel_function = KERNEL_QUARTIC;
  227. else if (strcmp(kernel_opt->answer, "triweight") == 0)
  228. kernel_function = KERNEL_TRIWEIGHT;
  229. else if (strcmp(kernel_opt->answer, "gaussian") == 0)
  230. kernel_function = KERNEL_GAUSSIAN;
  231. else if (strcmp(kernel_opt->answer, "cosine") == 0)
  232. kernel_function = KERNEL_COSINE;
  233. else
  234. G_fatal_error(_("Unknown kernel function"));
  235. if (flag_o->answer) {
  236. if (net_opt->answer) {
  237. if (node_method != NODE_NONE ||
  238. kernel_function != KERNEL_GAUSSIAN) {
  239. G_fatal_error(_("Optimal standard deviation calculation is supported only for node method 'none' and kernel function 'gaussian'."));
  240. }
  241. }
  242. else if (kernel_function != KERNEL_GAUSSIAN) {
  243. G_fatal_error(_("Optimal standard deviation calculation is supported only for kernel function 'gaussian'."));
  244. }
  245. }
  246. if (flag_q->answer) {
  247. flag_o->answer = 1;
  248. }
  249. if (net_opt->answer) {
  250. Vect_check_input_output_name(in_opt->answer, out_opt->answer,
  251. G_FATAL_EXIT);
  252. Vect_check_input_output_name(net_opt->answer, out_opt->answer,
  253. G_FATAL_EXIT);
  254. }
  255. G_get_window(&window);
  256. G_verbose_message(_("Standard deviation: %f"), sigma);
  257. G_asprintf(&tmpstr1, _n("%d row", "%d rows", window.rows), window.rows);
  258. G_asprintf(&tmpstr2, _n("%d column", "%d columns", window.cols), window.cols);
  259. /* GTC First argument is resolution, second - number of rows as a text, third - number of columns as a text. */
  260. G_verbose_message(_("Output raster map: resolution: %f\t%s\t%s"),
  261. window.ew_res, tmpstr1, tmpstr2);
  262. G_free(tmpstr1);
  263. G_free(tmpstr2);
  264. /* Open input vector */
  265. Vect_set_open_level(2);
  266. if (Vect_open_old(&In, in_opt->answer, "") < 0)
  267. G_fatal_error(_("Unable to open vector map <%s>"), in_opt->answer);
  268. if (net_opt->answer) {
  269. int nlines, line;
  270. struct line_pnts *Points;
  271. Points = Vect_new_line_struct();
  272. net = 1;
  273. dimension = 1.;
  274. /* Open input network */
  275. Vect_set_open_level(2);
  276. if (Vect_open_old(&Net, net_opt->answer, "") < 0)
  277. G_fatal_error(_("Unable to open vector map <%s>"), net_opt->answer);
  278. Vect_net_build_graph(&Net, GV_LINES, 0, 0, NULL, NULL, NULL, 0, 0);
  279. if (!flag_q->answer) {
  280. if (Vect_open_new(&Out, out_opt->answer, 0) < 0)
  281. G_fatal_error(_("Unable to create vector map <%s>"),
  282. out_opt->answer);
  283. Vect_hist_command(&Out);
  284. }
  285. /* verify not reachable points */
  286. nlines = Vect_get_num_lines(&In);
  287. for (line = 1; line <= nlines; line++) {
  288. int ltype;
  289. ltype = Vect_read_line(&In, Points, NULL, line);
  290. if (!(ltype & GV_POINTS))
  291. continue;
  292. if (Vect_find_line
  293. (&Net, Points->x[0], Points->y[0], 0.0, GV_LINES, netmax, 0,
  294. 0) == 0)
  295. notreachable++;
  296. }
  297. if (notreachable > 0)
  298. G_warning(_n("%d point outside threshold",
  299. "%d points outside threshold",
  300. notreachable), notreachable);
  301. }
  302. else {
  303. /* check and open the name of output map */
  304. if (!flag_q->answer) {
  305. fdout = Rast_open_new(out_opt->answer, DCELL_TYPE);
  306. /* open mask file */
  307. if ((maskfd = Rast_maskfd()) >= 0)
  308. mask = Rast_allocate_c_buf();
  309. else
  310. mask = NULL;
  311. /* allocate output raster */
  312. output_cell = Rast_allocate_buf(DCELL_TYPE);
  313. }
  314. }
  315. /* valutazione distanza ottimale */
  316. if (flag_o->answer) {
  317. /* Note: sigmaOptimal calculates using ALL points (also those outside the region) */
  318. G_message(_("Automatic choice of smoothing parameter (standard deviation), maximum possible "
  319. "value of standard deviation is set to %f"), sigma);
  320. /* maximum distance 4*sigma (3.9*sigma ~ 1.0000), keep it small, otherwise it takes
  321. * too much points and calculation on network becomes slow */
  322. dmax = 4 * sigma; /* used as maximum value */
  323. G_message(_("Using maximum distance between points: %f"), dmax);
  324. if (net_opt->answer) {
  325. npoints = Vect_get_num_primitives(&In, GV_POINTS);
  326. /* Warning: each distance is registered twice (both directions) */
  327. ndists =
  328. compute_all_net_distances(&In, &Net, netmax, &dists, dmax);
  329. }
  330. else {
  331. /* Read points */
  332. npoints = read_points(&In, &coordinate, dsize);
  333. ndists = compute_all_distances(coordinate, &dists, npoints, dmax);
  334. }
  335. G_message(_("Number of input points: %d."), npoints);
  336. G_message(_n("%d distance read from the map.",
  337. "%d distances read from the map.",
  338. ndists), ndists);
  339. if (ndists == 0)
  340. G_fatal_error(_("Distances between all points are beyond %e (4 * "
  341. "standard deviation), unable to calculate optimal value."),
  342. dmax);
  343. /* double iii;
  344. for ( iii = 1.; iii <= 10000; iii++){
  345. fprintf(stderr,"i=%f v=%.16f \n",iii,R(iii));
  346. } */
  347. /* sigma is used in brent as maximum possible value for sigmaOptimal */
  348. sigmaOptimal = brent_iterate(L, 0.0, sigma, 1000);
  349. G_message(_("Optimal smoothing parameter (standard deviation): %f."),
  350. sigmaOptimal);
  351. /* Reset sigma to calculated optimal value */
  352. sigma = sigmaOptimal;
  353. if (flag_q->answer) {
  354. Vect_close(&In);
  355. if (net_opt->answer)
  356. Vect_close(&Net);
  357. exit(EXIT_SUCCESS);
  358. }
  359. }
  360. if (kernel_function == KERNEL_GAUSSIAN)
  361. sigma /= 4.;
  362. if (net_opt->answer) {
  363. setKernelFunction(kernel_function, 1, sigma, &term);
  364. }
  365. else {
  366. setKernelFunction(kernel_function, 2, sigma, &term);
  367. }
  368. if (net) {
  369. int line, nlines;
  370. struct line_pnts *Points, *SPoints;
  371. struct line_cats *SCats;
  372. double total = 0.0;
  373. G_verbose_message(_("Writing output vector map using smooth parameter %f"),
  374. sigma);
  375. G_verbose_message(_("Normalising factor %f"),
  376. 1. / gaussianFunction(sigma / 4., sigma, dimension));
  377. /* Divide lines to segments and calculate gaussian for center of each segment */
  378. Points = Vect_new_line_struct();
  379. SPoints = Vect_new_line_struct();
  380. SCats = Vect_new_cats_struct();
  381. nlines = Vect_get_num_lines(&Net);
  382. G_debug(3, "net nlines = %d", nlines);
  383. for (line = 1; line <= nlines; line++) {
  384. int seg, nseg, ltype;
  385. double llength, length, x, y;
  386. G_percent(line, nlines, 5);
  387. ltype = Vect_read_line(&Net, Points, NULL, line);
  388. if (!(ltype & GV_LINES))
  389. continue;
  390. llength = Vect_line_length(Points);
  391. nseg = (int)(1 + llength / segmax);
  392. length = llength / nseg;
  393. G_debug(3, "net line = %d, nseg = %d, seg length = %f", line,
  394. nseg, length);
  395. for (seg = 0; seg < nseg; seg++) {
  396. double offset1, offset2;
  397. offset1 = (seg + 0.5) * length;
  398. Vect_point_on_line(Points, offset1, &x, &y, NULL, NULL, NULL);
  399. G_debug(3, " segment = %d, offset = %f, xy = %f %f", seg,
  400. offset1, x, y);
  401. compute_net_distance(x, y, &In, &Net, netmax, sigma, term,
  402. &gaussian, dmax, node_method);
  403. gaussian *= multip;
  404. if (gaussian > gausmax)
  405. gausmax = gaussian;
  406. G_debug(3, " gaussian = %f", gaussian);
  407. /* Write segment */
  408. if (gaussian > 0) {
  409. offset1 = seg * length;
  410. offset2 = (seg + 1) * length;
  411. if (offset2 > llength)
  412. offset2 = llength;
  413. Vect_line_segment(Points, offset1, offset2, SPoints);
  414. /* TODO!!! remove later
  415. if ( SPoints->n_points > 0 )
  416. Vect_append_point( SPoints, SPoints->x[SPoints->n_points-1],
  417. SPoints->y[SPoints->n_points-1], 0 );
  418. */
  419. Vect_reset_cats(SCats);
  420. Vect_cat_set(SCats, 1, (int)gaussian);
  421. Vect_write_line(&Out, GV_LINE, SPoints, SCats);
  422. total += length * gaussian;
  423. }
  424. }
  425. }
  426. if (flag_normalize->answer || flag_multiply->answer) {
  427. double m = multip;
  428. if (flag_normalize->answer) {
  429. m /= total;
  430. }
  431. if (flag_multiply->answer) {
  432. m *= (Vect_get_num_primitives(&In, GV_POINT) - notreachable);
  433. }
  434. Vect_build(&Out);
  435. gausmax = 0.0;
  436. nlines = Vect_get_num_lines(&Out);
  437. for (line = 1; line <= nlines; line++) {
  438. int cat;
  439. double gaussian;
  440. Vect_read_line(&Out, SPoints, SCats, line);
  441. Vect_cat_get(SCats, 1, &cat);
  442. gaussian = m * cat;
  443. Vect_reset_cats(SCats);
  444. Vect_cat_set(SCats, 1, (int)gaussian);
  445. Vect_rewrite_line(&Out, line, GV_LINE, SPoints, SCats);
  446. if (gaussian > gausmax)
  447. gausmax = gaussian;
  448. }
  449. Vect_build_partial(&Out, GV_BUILD_NONE); /* to force rebuild */
  450. }
  451. Vect_close(&Net);
  452. Vect_build(&Out);
  453. Vect_close(&Out);
  454. }
  455. else {
  456. /* spatial index handling, borrowed from lib/vector/Vlib/find.c */
  457. struct bound_box box;
  458. struct boxlist *NList = Vect_new_boxlist(1);
  459. G_verbose_message(_("Writing output raster map using smooth parameter %f"),
  460. sigma);
  461. G_verbose_message(_("Normalising factor %f"),
  462. 1. / gaussianFunction(sigma / 4., sigma, dimension));
  463. for (row = 0; row < window.rows; row++) {
  464. G_percent(row, window.rows, 2);
  465. if (mask)
  466. Rast_get_c_row(maskfd, mask, row);
  467. for (col = 0; col < window.cols; col++) {
  468. /* don't interpolate outside of the mask */
  469. if (mask && mask[col] == 0) {
  470. Rast_set_d_null_value(&output_cell[col], 1);
  471. continue;
  472. }
  473. N = Rast_row_to_northing(row + 0.5, &window);
  474. E = Rast_col_to_easting(col + 0.5, &window);
  475. if ((col & 31) == 0) {
  476. /* create bounding box 32x2*dmax size from the current cell center */
  477. box.N = N + dmax;
  478. box.S = N - dmax;
  479. box.E = E + dmax + 32 * window.ew_res;
  480. box.W = E - dmax;
  481. box.T = HUGE_VAL;
  482. box.B = -HUGE_VAL;
  483. Vect_select_lines_by_box(&In, &box, GV_POINT, NList);
  484. }
  485. box.N = N + dmax;
  486. box.S = N - dmax;
  487. box.E = E + dmax;
  488. box.W = E - dmax;
  489. box.T = HUGE_VAL;
  490. box.B = -HUGE_VAL;
  491. /* compute_distance(N, E, &In, sigma, term, &gaussian, dmax); */
  492. compute_distance(N, E, sigma, term, &gaussian, dmax, &box, NList);
  493. output_cell[col] = multip * gaussian;
  494. if (gaussian > gausmax)
  495. gausmax = gaussian;
  496. }
  497. Rast_put_row(fdout, output_cell, DCELL_TYPE);
  498. }
  499. G_percent(1, 1, 1);
  500. Rast_close(fdout);
  501. }
  502. G_done_msg(_("Maximum value in output: %e."), multip * gausmax);
  503. Vect_close(&In);
  504. exit(EXIT_SUCCESS);
  505. }
  506. /* Read points to array return number of points */
  507. int read_points(struct Map_info *In, double ***coordinate, double dsize)
  508. {
  509. int line, nlines, npoints, ltype, i = 0;
  510. double **xySites;
  511. static struct line_pnts *Points = NULL;
  512. if (!Points)
  513. Points = Vect_new_line_struct();
  514. /* Allocate array of pointers */
  515. npoints = Vect_get_num_primitives(In, GV_POINT);
  516. xySites = (double **)G_calloc(npoints, sizeof(double *));
  517. nlines = Vect_get_num_lines(In);
  518. for (line = 1; line <= nlines; line++) {
  519. ltype = Vect_read_line(In, Points, NULL, line);
  520. if (!(ltype & GV_POINT))
  521. continue;
  522. xySites[i] = (double *)G_calloc((size_t) 2, sizeof(double));
  523. xySites[i][0] = Points->x[0];
  524. xySites[i][1] = Points->y[0];
  525. i++;
  526. }
  527. *coordinate = xySites;
  528. return (npoints);
  529. }
  530. /* Calculate distances < dmax between all sites in coordinate
  531. * Return: number of distances in dists */
  532. double compute_all_distances(double **coordinate, double **dists, int n,
  533. double dmax)
  534. {
  535. int ii, jj, kk;
  536. size_t nn;
  537. nn = n * (n - 1) / 2;
  538. *dists = (double *)G_calloc(nn, sizeof(double));
  539. kk = 0;
  540. for (ii = 0; ii < n - 1; ii++) {
  541. for (jj = ii + 1; jj < n; jj++) {
  542. double dist;
  543. dist = euclidean_distance(coordinate[ii], coordinate[jj], 2);
  544. G_debug(3, "dist = %f", dist);
  545. if (dist <= dmax) {
  546. (*dists)[kk] = dist;
  547. kk++;
  548. }
  549. }
  550. }
  551. return (kk);
  552. }
  553. /* Calculate distances < dmax between all sites in coordinate
  554. * Return: number of distances in dists */
  555. double compute_all_net_distances(struct Map_info *In, struct Map_info *Net,
  556. double netmax, double **dists, double dmax)
  557. {
  558. int nn, kk, nalines, aline;
  559. double dist;
  560. struct line_pnts *APoints, *BPoints;
  561. struct bound_box box;
  562. struct boxlist *List;
  563. APoints = Vect_new_line_struct();
  564. BPoints = Vect_new_line_struct();
  565. List = Vect_new_boxlist(0);
  566. nn = Vect_get_num_primitives(In, GV_POINTS);
  567. nn = nn * (nn - 1);
  568. *dists = (double *)G_calloc(nn, sizeof(double));
  569. kk = 0;
  570. nalines = Vect_get_num_lines(In);
  571. for (aline = 1; aline <= nalines; aline++) {
  572. int i, altype;
  573. G_debug(3, " aline = %d", aline);
  574. altype = Vect_read_line(In, APoints, NULL, aline);
  575. if (!(altype & GV_POINTS))
  576. continue;
  577. box.E = APoints->x[0] + dmax;
  578. box.W = APoints->x[0] - dmax;
  579. box.N = APoints->y[0] + dmax;
  580. box.S = APoints->y[0] - dmax;
  581. box.T = PORT_DOUBLE_MAX;
  582. box.B = -PORT_DOUBLE_MAX;
  583. Vect_select_lines_by_box(In, &box, GV_POINT, List);
  584. G_debug(3, " %d points in box", List->n_values);
  585. for (i = 0; i < List->n_values; i++) {
  586. int bline, ret;
  587. bline = List->id[i];
  588. if (bline == aline)
  589. continue;
  590. G_debug(3, " bline = %d", bline);
  591. Vect_read_line(In, BPoints, NULL, bline);
  592. ret =
  593. Vect_net_shortest_path_coor(Net, APoints->x[0], APoints->y[0],
  594. 0.0, BPoints->x[0], BPoints->y[0],
  595. 0.0, netmax, netmax, &dist, NULL,
  596. NULL, NULL, NULL, NULL, NULL, NULL);
  597. G_debug(3, " SP: %f %f -> %f %f", APoints->x[0], APoints->y[0],
  598. BPoints->x[0], BPoints->y[0]);
  599. if (ret == 0) {
  600. G_debug(3, "not reachable");
  601. continue; /* Not reachable */
  602. }
  603. G_debug(3, " dist = %f", dist);
  604. if (dist <= dmax) {
  605. (*dists)[kk] = dist;
  606. kk++;
  607. }
  608. G_debug(3, " kk = %d", kk);
  609. }
  610. }
  611. return (kk);
  612. }
  613. /* get number of arcs for a node */
  614. int count_node_arcs(struct Map_info *Map, int node)
  615. {
  616. int i, n, line, type;
  617. int count = 0;
  618. n = Vect_get_node_n_lines(Map, node);
  619. for (i = 0; i < n; i++) {
  620. line = Vect_get_node_line(Map, node, i);
  621. type = Vect_get_line_type(Map, abs(line));
  622. if (type & GV_LINES)
  623. count++;
  624. }
  625. return count;
  626. }
  627. /* Compute gausian for x, y along Net, using all points in In */
  628. void compute_net_distance(double x, double y, struct Map_info *In,
  629. struct Map_info *Net, double netmax, double sigma,
  630. double term, double *gaussian, double dmax, int node_method)
  631. {
  632. int i;
  633. double dist, kernel;
  634. static struct line_pnts *FPoints = NULL;
  635. struct bound_box box;
  636. static struct boxlist *PointsList = NULL;
  637. static struct ilist *NodesList = NULL;
  638. if (!PointsList)
  639. PointsList = Vect_new_boxlist(1);
  640. if (node_method == NODE_EQUAL_SPLIT) {
  641. if (!NodesList)
  642. NodesList = Vect_new_list();
  643. if (!FPoints)
  644. FPoints = Vect_new_line_struct();
  645. }
  646. *gaussian = .0;
  647. /* The network is usually much bigger than dmax and to calculate shortest path is slow
  648. * -> use spatial index to select points
  649. * enlarge the box by netmax (max permitted distance between a point and net) */
  650. box.E = x + dmax + netmax;
  651. box.W = x - dmax - netmax;
  652. box.N = y + dmax + netmax;
  653. box.S = y - dmax - netmax;
  654. box.T = PORT_DOUBLE_MAX;
  655. box.B = -PORT_DOUBLE_MAX;
  656. Vect_select_lines_by_box(In, &box, GV_POINT, PointsList);
  657. G_debug(3, " %d points in box", PointsList->n_values);
  658. for (i = 0; i < PointsList->n_values; i++) {
  659. int line, ret;
  660. line = PointsList->id[i];
  661. G_debug(3, " SP: %f %f -> %f %f", x, y, PointsList->box[i].E, PointsList->box[i].N);
  662. /*ret = Vect_net_shortest_path_coor(Net, x, y, 0.0, Points->x[0], */
  663. /*Points->y[0], 0.0, netmax, netmax, */
  664. /*&dist, NULL, NULL, NULL, NULL, NULL, NULL, */
  665. /*NULL); */
  666. ret = Vect_net_shortest_path_coor(Net,
  667. PointsList->box[i].E,
  668. PointsList->box[i].N, 0.0,
  669. x, y, 0.0, netmax, 1.0,
  670. &dist, NULL,
  671. NULL, NodesList, FPoints, NULL,
  672. NULL, NULL);
  673. if (ret == 0) {
  674. G_debug(3, "not reachable");
  675. continue; /* Not reachable */
  676. }
  677. /* if (dist <= dmax)
  678. *gaussian += gaussianKernel(dist / sigma, term); */
  679. if (dist > dmax)
  680. continue;
  681. /* kernel = gaussianKernel(dist / sigma, term); */
  682. kernel = kernelFunction(term, sigma, dist);
  683. if (node_method == NODE_EQUAL_SPLIT) {
  684. int j, node;
  685. double ndiv = 1.;
  686. int start = 0;
  687. /* Count the nodes and arcs on path (n1-1)*(n2-1)* ... (ns-1) */
  688. for (j = start; j < NodesList->n_values; j++) {
  689. node = NodesList->value[j];
  690. /* Divide into 2/n if point falls on a node */
  691. if (j == 0 && FPoints->n_points < 3) {
  692. ndiv *= count_node_arcs(Net, node) / 2.;
  693. }
  694. else {
  695. ndiv *= count_node_arcs(Net, node) - 1;
  696. }
  697. }
  698. kernel /= ndiv;
  699. }
  700. *gaussian += kernel;
  701. G_debug(3, " dist = %f gaussian = %f", dist, *gaussian);
  702. }
  703. }
  704. void compute_distance(double N, double E, double sigma, double term,
  705. double *gaussian, double dmax, struct bound_box *box,
  706. struct boxlist *NList)
  707. {
  708. int line, nlines;
  709. double a[2], b[2];
  710. double dist;
  711. a[0] = E;
  712. a[1] = N;
  713. /* number of lines within dmax box */
  714. nlines = NList->n_values;
  715. *gaussian = .0;
  716. for (line = 0; line < nlines; line++) {
  717. b[0] = NList->box[line].E;
  718. b[1] = NList->box[line].N;
  719. if (b[0] <= box->E && b[0] >= box->W &&
  720. b[1] <= box->N && b[1] >= box->S) {
  721. dist = euclidean_distance(a, b, 2);
  722. if (dist <= dmax)
  723. /* *gaussian += gaussianKernel(dist / sigma, term); */
  724. *gaussian += kernelFunction(term, sigma, dist);
  725. }
  726. }
  727. }