1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
|
/****************************************************************************
*
* MODULE: v.kernel
*
* AUTHOR(S): Stefano Menegon, ITC-irst, Trento, Italy
* PURPOSE: Generates a raster density map from vector points data using
* a moving 2D isotropic Gaussian kernel or
* optionally generates a vector density map on vector network
* with a 1D kernel
* COPYRIGHT: (C) 2004 by the GRASS Development Team
*
* This program is free software under the GNU General Public
* License (>=v2). Read the file COPYING that comes with GRASS
* for details.
*
*****************************************************************************/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include "gis.h"
#include "Vect.h"
#include "global.h"
static int ndists; /* number of distances in dists */
static double *dists; /* array of all distances < dmax */
static int npoints;
int net = 0;
static int verbose = 1 ;
static double dimension = 2.;
/* define score function L(window size) */
double L(double smooth)
{
int ii;
double resL,n,term;
n = npoints;
resL = 0.;
term=1./pow((2.*M_PI),dimension/2.);
for(ii=0; ii < ndists; ii++){
/* resL+= gaussianFunction(dists[ii]/smooth,2.,dimension) - 2. * gaussianKernel(dists[ii]/smooth,term); */
resL+= gaussianFunction(dists[ii]/smooth,2.,dimension) - 2. * gaussianFunction(dists[ii]/smooth,1.,dimension);
}
if ( !net ) resL *= 2.;
resL = (1./(pow(n,2.)*pow(smooth,dimension))) * (resL + n*( gaussianFunction(0.,2.,dimension) - 2. * gaussianFunction(0.,1.,dimension)) ) + (2./(n*pow(smooth,dimension)))*gaussianFunction(0.,1.,dimension);
/* 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); */
G_debug(3, "smooth = %e resL = %e", smooth, resL);
if(verbose){
fprintf (stderr, "\tScore Value=%f\tsmoothing parameter (standard deviation)=%f\n",resL, smooth);
}
return(resL);
}
int main(int argc, char **argv)
{
struct Option *in_opt, *net_opt, *out_opt;
struct Option *stddev_opt, *dsize_opt, *segmax_opt, *netmax_opt, *multip_opt;
struct Flag *flag_o, *flag_v, *flag_q;
char *mapset;
struct Map_info In, Net, Out;
int fdout, maskfd;
int row,col;
struct Cell_head window;
double gaussian;
double N,E;
CELL *mask;
DCELL *output_cell;
double sigma, dmax, segmax, netmax, multip;
double **coordinate;
double sigmaOptimal;
struct GModule *module;
double dsize;
double term;
double gausmax = 0;
/* Initialize the GIS calls */
G_gisinit(argv[0]);
module = G_define_module();
module->description =
"Generates a raster density map from vector points data using a moving 2D isotropic Gaussian kernel or "
"optionally generates a vector density map on vector network with a 1D kernel";
in_opt = G_define_standard_option(G_OPT_V_INPUT);
in_opt->description = "Input vector with training points";
net_opt = G_define_standard_option(G_OPT_V_INPUT);
net_opt->key = "net";
net_opt->description = "Input network vector";
net_opt->required = NO;
out_opt = G_define_option();
out_opt->key = "output";
out_opt->type = TYPE_STRING;
out_opt->required = YES;
out_opt->description = "output raster/vector map";
stddev_opt = G_define_option() ;
stddev_opt->key = "stddeviation";
stddev_opt->type = TYPE_DOUBLE;
stddev_opt->required = YES;
stddev_opt->description = "stddeviation in map units";
dsize_opt = G_define_option() ;
dsize_opt->key = "dsize";
dsize_opt->type = TYPE_DOUBLE;
dsize_opt->required = NO;
dsize_opt->description = "discretization error in map units" ;
dsize_opt->answer = "0.";
segmax_opt = G_define_option() ;
segmax_opt->key = "segmax";
segmax_opt->type = TYPE_DOUBLE;
segmax_opt->required = NO;
segmax_opt->description = "maximum length of segment on network" ;
segmax_opt->answer = "100.";
netmax_opt = G_define_option() ;
netmax_opt->key = "distmax";
netmax_opt->type = TYPE_DOUBLE;
netmax_opt->required = NO;
netmax_opt->description = "maximum distance from point to network" ;
netmax_opt->answer = "100.";
multip_opt = G_define_option() ;
multip_opt->key = "mult";
multip_opt->type = TYPE_DOUBLE;
multip_opt->required = NO;
multip_opt->description = "multiply the density result by this number" ;
multip_opt->answer = "1.";
flag_o = G_define_flag();
flag_o->key = 'o';
flag_o->description = "Try to calculate an optimal standard deviation with 'stddeviation' taken as maximum (experimental)";
flag_q = G_define_flag();
flag_q->key = 'q';
flag_q->description = "Only calculate optimal standard deviation and exit (no map is written)";
flag_v = G_define_flag();
flag_v->key = 'v';
flag_v->description = "Run verbosely";
if (G_parser(argc, argv))
exit(1);
/*read options*/
sigma = atof(stddev_opt->answer);
dsize = atof(dsize_opt->answer);
segmax = atof(segmax_opt->answer);
netmax = atof(netmax_opt->answer);
multip = atof(multip_opt->answer);
verbose = flag_v->answer;
if( flag_q->answer ) {
flag_o->answer=1;
}
Vect_check_input_output_name ( in_opt->answer, out_opt->answer, GV_FATAL_EXIT );
if ( net_opt->answer) {
Vect_check_input_output_name ( net_opt->answer, out_opt->answer, GV_FATAL_EXIT );
}
G_get_window(&window);
fprintf(stderr,"STDDEV: %f\nRES: %f\tROWS: %d\tCOLS: %d\n",
sigma, window.ew_res, window.rows, window.cols);
/* Open input vector */
if ((mapset = G_find_vector2 (in_opt->answer, "")) == NULL)
G_fatal_error ( "Could not find input map '%s'\n", in_opt->answer);
Vect_set_open_level (2);
Vect_open_old (&In, in_opt->answer, mapset);
if ( net_opt->answer) {
int nlines, line;
int notreachable=0;
struct line_pnts *Points;
Points = Vect_new_line_struct ();
net = 1;
dimension=1.;
/* Open input network */
if ((mapset = G_find_vector2 (net_opt->answer, "")) == NULL)
G_fatal_error ( "Could not find network input map '%s'\n", net_opt->answer);
Vect_set_open_level (2);
Vect_open_old (&Net, net_opt->answer, mapset);
Vect_net_build_graph ( &Net, GV_LINES, 0, 0, NULL, NULL, NULL, 0, 0 );
if( !flag_q->answer ) {
Vect_open_new (&Out, out_opt->answer, 0);
Vect_hist_command ( &Out );
}
/* verify not reachable points */
nlines = Vect_get_num_lines(&In);
for ( line = 1; line <= nlines; line++){
int ltype;
ltype = Vect_read_line (&In, Points, NULL, line);
if ( !(ltype & GV_POINTS ) ) continue;
if(Vect_find_line ( &Net, Points->x[0], Points->y[0] , 0.0, GV_LINES, netmax, 0, 0 ) ==0) notreachable++;
}
if(notreachable > 0) G_warning("%d points outside treshold",notreachable);
} else {
/* check and open the name of output map */
if( !flag_q->answer ) {
if(G_legal_filename( out_opt->answer ) < 0)
G_fatal_error("illegal file name [%s]", out_opt->answer);
G_set_fp_type (DCELL_TYPE);
if((fdout = G_open_raster_new(out_opt->answer,DCELL_TYPE)) < 0)
G_fatal_error("error opening raster map [%s]", out_opt->answer);
/* open mask file */
if ((maskfd = G_maskfd()) >= 0)
mask = G_allocate_cell_buf();
else
mask = NULL;
/* allocate output raster */
output_cell=G_allocate_raster_buf(DCELL_TYPE);
}
}
/* valutazione distanza ottimale */
if ( flag_o->answer ) {
/* Note: sigmaOptimal calculates using ALL points (also those outside the region) */
fprintf (stderr, "Automatic choose of smoothing parameter (standard deviation), maximum possible "
"value of standard deviation is was set to %f\n", sigma);
/* maximum distance 4*sigma (3.9*sigma ~ 1.0000), keep it small, otherwise it takes
* too much points and calculation on network becomes slow */
dmax = 4*sigma; /* used as maximum value */
fprintf (stderr, "Using maximum distance between points: %f\n", dmax);
if ( net_opt->answer ) {
npoints = Vect_get_num_primitives(&In,GV_POINTS);
/* Warning: each distance is registered twice (both directions) */
ndists = compute_all_net_distances(&In,&Net,netmax,&dists,dmax);
} else {
/* Read points */
npoints = read_points ( &In, &coordinate, dsize );
ndists = compute_all_distances(coordinate,&dists,npoints,dmax);
}
fprintf (stderr, "Number of input points: %d \n", npoints);
fprintf (stderr, "%d distances read from the map\n", ndists);
if(ndists ==0) G_fatal_error("distances between all points are beyond %e (4 * standard deviation) cannot calculate optimal value",dmax) ;
/* double iii;
for ( iii = 1.; iii <= 10000; iii++){
fprintf(stderr,"i=%f v=%.16f \n",iii,R(iii));
}*/
/* sigma is used in brent as maximum possible value for sigmaOptimal */
sigmaOptimal = brent_iterate( L, 0.0, sigma, 1000);
fprintf (stderr, "Optimal smoothing parameter (standard deviation): %f\n", sigmaOptimal);
/* Reset sigma to calculated optimal value */
sigma=sigmaOptimal;
if( flag_q->answer ) {
Vect_close (&In);
if ( net_opt->answer )
Vect_close (&Net);
exit (0);
}
}
term=1./(pow(sigma,dimension)*pow((2.*M_PI),dimension/2.));
dmax= sigma*4.;
if ( net ) {
int line, nlines;
struct line_pnts *Points, *SPoints;
struct line_cats *SCats;
fprintf (stderr, "\nWriting output vector file using smooth parameter=%f\n",sigma);
fprintf (stderr, "\nNormalising factor=%f\n",1./gaussianFunction(sigma/4.,sigma,dimension));
/* Divide lines to segments and calculate gaussian for center of each segment */
Points = Vect_new_line_struct ();
SPoints = Vect_new_line_struct ();
SCats = Vect_new_cats_struct ();
nlines = Vect_get_num_lines(&Net);
G_debug (3, "net nlines = %d", nlines);
for ( line = 1; line <= nlines; line++){
int seg, nseg, ltype;
double llength, length, x, y;
ltype = Vect_read_line (&Net, Points, NULL, line);
if ( !(ltype & GV_LINES ) ) continue;
llength = Vect_line_length (Points);
nseg = (int) (1 + llength / segmax);
length = llength / nseg;
G_debug (3, "net line = %d, nseg = %d, seg length = %f", line, nseg, length);
for ( seg = 0; seg < nseg; seg++ ) {
double offset1, offset2;
offset1 = (seg + 0.5) * length;
Vect_point_on_line ( Points, offset1, &x, &y, NULL, NULL, NULL);
G_debug (3, " segment = %d, offset = %f, xy = %f %f", seg, offset1, x, y);
compute_net_distance ( x, y, &In, &Net, netmax, sigma, term, &gaussian, dmax );
gaussian *= multip;
if ( gaussian > gausmax ) gausmax = gaussian;
G_debug (3, " gaussian = %f", gaussian);
/* Write segment */
if ( gaussian > 0 ) {
offset1 = seg * length;
offset2 = (seg + 1) * length;
if ( offset2 > llength ) offset2 = llength;
Vect_line_segment ( Points, offset1, offset2, SPoints );
/* TODO!!! remove later
if ( SPoints->n_points > 0 )
Vect_append_point( SPoints, SPoints->x[SPoints->n_points-1],
SPoints->y[SPoints->n_points-1], 0 );
*/
Vect_reset_cats ( SCats );
Vect_cat_set ( SCats, 1, (int) gaussian );
Vect_write_line ( &Out, GV_LINE, SPoints, SCats );
}
}
G_percent ( line, nlines, 1 );
}
Vect_close (&Net);
Vect_build (&Out, stderr);
Vect_close (&Out);
} else {
fprintf (stderr, "\nWriting output raster file using smooth parameter=%f\n",sigma);
fprintf (stderr, "\nNormalising factor=%f\n",1./gaussianFunction(sigma/4.,sigma,dimension));
for(row=0; row<window.rows; row++){
G_percent(row,window.rows,2);
if (mask)
{
if(G_get_map_row(maskfd, mask, row) < 0)
G_fatal_error("error reading MASK");
}
for(col=0; col<window.cols; col++) {
/* don't interpolate outside of the mask */
if (mask && mask[col] == 0)
{
G_set_d_null_value(&output_cell[col], 1);
continue;
}
N = G_row_to_northing(row+0.5,&window);
E = G_col_to_easting(col+0.5,&window);
compute_distance ( N, E, &In, sigma, term, &gaussian,dmax );
output_cell[col] = multip * gaussian;
if ( gaussian > gausmax ) gausmax = gaussian;
}
G_put_raster_row(fdout,output_cell,DCELL_TYPE);
}
G_close_cell(fdout);
}
fprintf (stderr, "Maximum value in output: %e\n", gausmax);
Vect_close (&In);
exit(0);
}
/* Read points to array return number of points */
int read_points( struct Map_info *In, double ***coordinate, double dsize)
{
int line, nlines, npoints, ltype, i = 0;
double **xySites;
static struct line_pnts *Points = NULL;
if (!Points)
Points = Vect_new_line_struct ();
/* Allocate array of pointers */
npoints = Vect_get_num_primitives(In,GV_POINT);
xySites = (double **) G_calloc ( npoints, sizeof(double*) );
nlines = Vect_get_num_lines(In);
for ( line = 1; line <= nlines; line++){
ltype = Vect_read_line (In, Points, NULL, line);
if ( !(ltype & GV_POINT ) ) continue;
xySites[i] = (double *) G_calloc (2,sizeof(double));
xySites[i][0] = Points->x[0];
xySites[i][1] = Points->y[0];
i++;
}
*coordinate = xySites;
return (npoints);
}
/* Calculate distances < dmax between all sites in coordinate
* Return: number of distances in dists */
double compute_all_distances(double **coordinate, double **dists, int n, double dmax)
{
int ii,jj,kk;
int nn;
nn = n*(n-1)/2;
*dists = (double *) G_calloc(nn,sizeof(double));
kk=0;
for(ii=0; ii < n-1; ii++){
for(jj=ii+1; jj<n; jj++){
double dist;
dist = euclidean_distance(coordinate[ii],coordinate[jj],2);
G_debug (3, "dist = %f", dist);
if ( dist <= dmax ) {
(*dists)[kk] = dist;
kk++;
}
}
}
return (kk);
}
/* Calculate distances < dmax between all sites in coordinate
* Return: number of distances in dists */
double compute_all_net_distances( struct Map_info *In, struct Map_info *Net,
double netmax, double **dists, double dmax)
{
int nn, kk, nalines, aline;
double dist;
struct line_pnts *APoints, *BPoints;
BOUND_BOX box;
struct ilist *List;
APoints = Vect_new_line_struct ();
BPoints = Vect_new_line_struct ();
List = Vect_new_list ();
nn = Vect_get_num_primitives(In,GV_POINTS);
nn = nn*(nn-1);
*dists = (double *) G_calloc(nn,sizeof(double));
kk=0;
nalines = Vect_get_num_lines(In);
for ( aline = 1; aline <= nalines; aline++){
int i, altype;
G_debug (3, " aline = %d", aline);
altype = Vect_read_line (In, APoints, NULL, aline);
if ( !(altype & GV_POINTS ) ) continue;
box.E = APoints->x[0] + dmax; box.W = APoints->x[0] - dmax;
box.N = APoints->y[0] + dmax; box.S = APoints->y[0] - dmax;
box.T = PORT_DOUBLE_MAX; box.B = -PORT_DOUBLE_MAX;
Vect_select_lines_by_box ( In, &box, GV_POINT, List);
G_debug (3, " %d points in box", List->n_values);
for ( i = 0; i < List->n_values; i++){
int bline, ret;
bline = List->value[i];
if ( bline == aline ) continue;
G_debug (3, " bline = %d", bline);
Vect_read_line (In, BPoints, NULL, bline);
ret = Vect_net_shortest_path_coor ( Net, APoints->x[0], APoints->y[0], 0.0,
BPoints->x[0], BPoints->y[0], 0.0,
netmax, netmax, &dist, NULL, NULL, NULL,
NULL, NULL, NULL );
G_debug (3, " SP: %f %f -> %f %f", APoints->x[0], APoints->y[0], BPoints->x[0], BPoints->y[0]);
if ( ret == 0 ) {
G_debug (3, "not reachable");
continue; /* Not reachable */
}
G_debug (3, " dist = %f", dist);
if ( dist <= dmax ) {
(*dists)[kk] = dist;
kk++;
}
G_debug (3, " kk = %d", kk);
}
}
return (kk);
}
/* Compute gausian for x, y along Net, using all points in In */
void compute_net_distance( double x, double y, struct Map_info *In, struct Map_info *Net, double netmax,
double sigma, double term, double *gaussian, double dmax)
{
int i;
double dist;
static struct line_pnts *Points = NULL;
BOUND_BOX box;
static struct ilist *List = NULL;
if (!Points)
Points = Vect_new_line_struct ();
if (!List)
List = Vect_new_list ();
*gaussian=.0;
/* The network is usually much bigger than dmax and to calculate shortest path is slow
* -> use spatial index to select points */
box.E = x + dmax; box.W = x - dmax;
box.N = y + dmax; box.S = y - dmax;
box.T = PORT_DOUBLE_MAX; box.B = -PORT_DOUBLE_MAX;
Vect_select_lines_by_box ( In, &box, GV_POINT, List);
G_debug (3, " %d points in box", List->n_values);
for ( i = 0; i < List->n_values; i++){
int line, ret;
line = List->value[i];
Vect_read_line (In, Points, NULL, line);
G_debug (3, " SP: %f %f -> %f %f", x, y, Points->x[0], Points->y[0]);
ret = Vect_net_shortest_path_coor ( Net, x, y, 0.0, Points->x[0], Points->y[0], 0.0,
netmax, netmax, &dist, NULL, NULL, NULL,
NULL, NULL, NULL );
if ( ret == 0 ) {
G_debug (3, "not reachable");
continue; /* Not reachable */
}
if(dist<=dmax)
*gaussian += gaussianKernel(dist/sigma,term);
G_debug (3, " dist = %f gaussian = %f", dist, *gaussian);
}
}
void compute_distance( double N, double E, struct Map_info *In,
double sigma, double term, double *gaussian, double dmax)
{
int line, nlines, ltype;
double a[2],b[2];
double dist;
static struct line_pnts *Points = NULL;
if (!Points)
Points = Vect_new_line_struct ();
a[0] = E;
a[1] = N;
*gaussian=.0;
nlines = Vect_get_num_lines(In);
/* TODO ? : use spatial index */
for ( line = 1; line <= nlines; line++){
ltype = Vect_read_line (In, Points, NULL, line);
if ( !(ltype & GV_POINT ) ) continue;
b[0] = Points->x[0];
b[1] = Points->y[0];
dist = euclidean_distance(a,b,2);
if(dist<=dmax)
*gaussian += gaussianKernel(dist/sigma,term);
}
}
|