main.c 23 KB

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