main.c 23 KB

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