main.c 25 KB

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