| 1 | # PolyMap.pm | ||
| 2 | # | ||
| 3 | # Contains the KML backend functions for the Google Earth Census Visualization | ||
| 4 | # Project. These functions are responsible for taking data from the DB backend | ||
| 5 | # and turning it into a viewable KML file. | ||
| 6 | # | ||
| 7 | # Copyright 2007, Imran Haque (ihaque@cs.stanford.edu) | ||
| 8 | # | ||
| 9 | # This code is free software and is licensed under the same terms as Perl itself. | ||
| 10 | # | ||
| 11 | |||
| 12 | =pod | ||
| 13 | |||
| 14 | =head1 NAME | ||
| 15 | |||
| 16 | Geo::KML::PolyMap - Generate KML/KMZ-format choropleth (shaded polygonal) maps viewable in Google Earth | ||
| 17 | |||
| 18 | =head1 SYNOPSIS | ||
| 19 | |||
| 20 | use Geo::KML::PolyMap qw(generate_kml_file generate_kmz_file); | ||
| 21 | |||
| 22 | # Clusters "Total Population" data for "Foobar City" in $entities into 5 bins; | ||
| 23 | # renders using colors from $startcolor to $endcolor; | ||
| 24 | # generates a legend; renders output to file handle passed in $kmz_filehandle | ||
| 25 | generate_kmz_file(entities => $entities, | ||
| 26 | placename => "Foobar City", | ||
| 27 | data_desc => "Total Population", | ||
| 28 | nbins => 5, | ||
| 29 | kmzfh => $filehandle_for_kmz_output, | ||
| 30 | startcolor => "FFFF0000", | ||
| 31 | endcolor => "FF00FF00"); | ||
| 32 | |||
| 33 | # As above, but without a legend | ||
| 34 | generate_kml_file(entities => $entities, | ||
| 35 | placename => "Foobar City", | ||
| 36 | data_desc => "Total Population", | ||
| 37 | nbins => 5, | ||
| 38 | kmlfh => $filehandle_for_kml_output, | ||
| 39 | startcolor => "FFFF0000", | ||
| 40 | endcolor => "FF00FF00"); | ||
| 41 | |||
| 42 | =head1 REQUIRES | ||
| 43 | |||
| 44 | =over | ||
| 45 | |||
| 46 | =item * Carp | ||
| 47 | |||
| 48 | =item * Archive::Zip | ||
| 49 | |||
| 50 | =item * GD >=2.0 | ||
| 51 | |||
| 52 | =item * File::Temp | ||
| 53 | |||
| 54 | =item * Statistics::Descriptive | ||
| 55 | |||
| 56 | =back | ||
| 57 | |||
| 58 | =head1 DESCRIPTION | ||
| 59 | |||
| 60 | Geo::KML::PolyMap generates KML or KMZ-formatted maps for Google Earth. Given a set of polygonal regions and a number associated with each | ||
| 61 | region (for example, city blocks and population counts on each block), Geo::KML::PolyMap generates a choropleth map showing the data value | ||
| 62 | for each region as a shaded polygon. The polygons are divided into a number of bins, with the color of each bin unique. Optionally, | ||
| 63 | Geo::KML::PolyMap will generate a legend along with the map file to illustrate the data ranges represented by each color. | ||
| 64 | |||
| 65 | =head1 CONFIGURATION | ||
| 66 | |||
| 67 | Geo::KML::PolyMap includes two parameters which must be configured by direct code changes. | ||
| 68 | |||
| 69 | =head2 Font Selection | ||
| 70 | |||
| 71 | To generate legend files with generate_kmz_file(), you must specify the path to a TrueType (.ttf) font file in the variable $FONT_PATH. | ||
| 72 | This is clearly suboptimal and will change in a future revision. | ||
| 73 | |||
| 74 | =head2 Binning Method | ||
| 75 | |||
| 76 | The algorithm used to bin data points is also configurable. Please see the section on binning in generate_kml_file() for details. | ||
| 77 | |||
| 78 | =head1 DATA STRUCTURES | ||
| 79 | |||
| 80 | =head2 Points | ||
| 81 | |||
| 82 | A point is defined as a latitude,longitude pair. Since Google Earth uses the WGS-84 coordinate system, you probably should too. | ||
| 83 | |||
| 84 | Points are represented in Geo::KML::PolyMap as strings of the following form: | ||
| 85 | |||
| 86 | (latitude,longitude) | ||
| 87 | |||
| 88 | So, for example, the following are legal points: | ||
| 89 | |||
| 90 | my $pt = "(24,-12)"; | ||
| 91 | my $pt = "(123.456,-78.90)" | ||
| 92 | |||
| 93 | But the following are not: | ||
| 94 | |||
| 95 | my $pt = "(199,140)"; # latitude is out of range | ||
| 96 | my $pt = "24,-12"; # missing parentheses | ||
| 97 | |||
| 98 | =head2 Polygons | ||
| 99 | |||
| 100 | A polygon is defined as a series of at least 4 points in the plane. Consecutive points are joined to form the polygon edges, and the last | ||
| 101 | point must be the same as the first. The mapping results are undefined if edges in the polygon cross. | ||
| 102 | |||
| 103 | Polygons are represented in Geo::KML::PolyMap as strings containing comma-delimited lists of points, wrapped in a pair of parentheses: | ||
| 104 | |||
| 105 | "((lat1,long1),(lat2,long2),(lat3,long3),(lat1,long1))" | ||
| 106 | |||
| 107 | The following is an example of a legal polygon: | ||
| 108 | |||
| 109 | my $poly = "((1,2),(3,4),(5,6),(7,8),(1,2))"; | ||
| 110 | |||
| 111 | The following are examples of illegal polygons: | ||
| 112 | |||
| 113 | my $poly = "((1,2),(3,4),(5,6),(7,8))"; # last point must be the same as the first point | ||
| 114 | my $poly = "((1,2),(3,4),(1,2))"; # not enough points; need at least 4 | ||
| 115 | my $poly = "(1,2),(3,4),(5,6),(1,2)"; # missing parentheses | ||
| 116 | |||
| 117 | =head2 Entities | ||
| 118 | |||
| 119 | Entities are the structure used by Geo::KML::PolyMap to move data into the map generation process. An entity is a very simple polygon/data pair, | ||
| 120 | stored in a hashref. The polygon must be accessible from key "polygon", and the data point must be a number accessible from key "data": | ||
| 121 | |||
| 122 | my $polygon = "((1,2),(3,4),(5,6),(1,2))"; | ||
| 123 | my $data = "10"; | ||
| 124 | my $entity = { data => $data, | ||
| 125 | polygon => $polygon}; | ||
| 126 | |||
| 127 | Geo::KML::PolyMap functions take references to arrays of entities: | ||
| 128 | |||
| 129 | # Assume we have $entity1,$entity2,$entity3 defined already | ||
| 130 | my $mapdata = [$entity1,$entity2,\$entity3]; | ||
| 131 | |||
| 132 | =head1 METHODS | ||
| 133 | |||
| 134 | =cut | ||
| 135 | |||
| 136 | package Geo::KML::PolyMap; | ||
| 137 | |||
| 138 | use strict; | ||
| 139 | use warnings; | ||
| 140 | |||
| 141 | use Statistics::Descriptive; | ||
| 142 | use Carp; | ||
| 143 | use GD; | ||
| 144 | use Archive::Zip qw( :ERROR_CODES :CONSTANTS ); | ||
| 145 | use File::Temp qw( tempfile ); | ||
| 146 | |||
| 147 | my $FONT_PATH = "/usr/share/fonts/truetype/freefont/FreeSans.ttf"; | ||
| 148 | |||
| 149 | |||
| 150 | BEGIN { | ||
| 151 | use Exporter (); | ||
| 152 | our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,%EXPORT_TAGS); | ||
| 153 | # v1.0 ihaque 5/30/06 initial version | ||
| 154 | # v1.1 ihaque 5/31/06 added equipartition binning | ||
| 155 | # v1.2 ihaque ??? added k-means binning | ||
| 156 | # v1.3 ihaque ??? added rendering to disk | ||
| 157 | # v 1.31 ihaque 3/1/07 moved from EXPORT to EXPORT_OK | ||
| 158 | # v 1.32 ihaque 3/2/07 fixed documentation bug with SYNOPSIS | ||
| 159 | # v 1.33 ihaque 6/22/07 added rudimentary support for altitude-mapping data | ||
| 160 | # changed default font path to that for FreeSans | ||
| 161 | # v 1.34 ihaque 9/19/07 fixed bug relating to spaces in the polygon string passed to kml_polygon | ||
| 162 | # | ||
| 163 | $VERSION = 1.34; | ||
| 164 | @ISA = qw(Exporter); | ||
| 165 | @EXPORT = (); | ||
| 166 | %EXPORT_TAGS = (); | ||
| 167 | @EXPORT_OK = qw(&generate_kml_file &generate_kmz_file); | ||
| 168 | } | ||
| 169 | |||
| 170 | # generate_style(string color,OPT string id ) | ||
| 171 | # Returns reference to an array containing KML lines | ||
| 172 | # representating the polystyle | ||
| 173 | sub generate_kml_style($;$) { | ||
| 174 | my ($color,$id)=@_; | ||
| 175 | my @style; | ||
| 176 | if (defined $id) { | ||
| 177 | push (@style,"<Style id=\"$id\">"); | ||
| 178 | } else { | ||
| 179 | push (@style,"<Style>"); | ||
| 180 | } | ||
| 181 | #push (@style,"\t<PolyStyle>"); | ||
| 182 | #push (@style,"\t\t<color>$color</color>"); | ||
| 183 | #push (@style,"\t</PolyStyle>"); | ||
| 184 | push (@style,"<PolyStyle>"); | ||
| 185 | push (@style,"<color>$color</color>"); | ||
| 186 | push (@style,"</PolyStyle>"); | ||
| 187 | push (@style,"</Style>"); | ||
| 188 | |||
| 189 | return \@style; | ||
| 190 | #my $kml_style = join("\n",@style); | ||
| 191 | #return \$kml_style; | ||
| 192 | } | ||
| 193 | |||
| 194 | # generate_colors(int nbins,OPT string start,OPT string end) | ||
| 195 | # start: OBGR hex representation of a color, defaults to ff000000 | ||
| 196 | # end: OBGR hex representation of a color, defaults to ffffffff | ||
| 197 | # Returns reference to an array of nbins OBGR strings, equally spaced between | ||
| 198 | # start and end | ||
| 199 | sub generate_colors($;$$) { | ||
| 200 | my ($nbins,$start,$end) = @_; | ||
| 201 | $start = 'ff000000' if not defined $start; | ||
| 202 | $end = 'ffffffff' if not defined $end; | ||
| 203 | |||
| 204 | my @s; | ||
| 205 | my @e; | ||
| 206 | my @delta; | ||
| 207 | for (my $i=0;$i<4;$i++) { | ||
| 208 | $s[$i] = hex substr($start,$i*2,2); | ||
| 209 | $e[$i] = hex substr($end,$i*2,2); | ||
| 210 | $delta[$i]=$e[$i]-$s[$i]; | ||
| 211 | } | ||
| 212 | |||
| 213 | my @colors; | ||
| 214 | for (my $i=0;$i<$nbins;$i++) { | ||
| 215 | my @thiscolor; | ||
| 216 | for (my $j=0;$j<4;$j++) { | ||
| 217 | $thiscolor[$j] = int ($s[$j]+($i/$nbins)*$delta[$j]); | ||
| 218 | $thiscolor[$j] = 255 if ($thiscolor[$j] > 255); | ||
| 219 | } | ||
| 220 | push (@colors,sprintf("%02x%02x%02x%02x",@thiscolor)); | ||
| 221 | } | ||
| 222 | return \@colors; | ||
| 223 | } | ||
| 224 | |||
| 225 | # generate_kml_polygon(entity& entity) | ||
| 226 | # Returns reference to a array containing the lines of the | ||
| 227 | # KML version of entity->polygon | ||
| 228 | sub generate_kml_polygon($) { | ||
| 229 | my ($entity) = @_; | ||
| 230 | carp "Undefined entity" if not defined $entity; | ||
| 231 | # Preprocess altitude for concatenations | ||
| 232 | my $altitude = $entity->{altitude}; | ||
| 233 | if (not defined $altitude) { | ||
| 234 | $altitude=",0"; | ||
| 235 | } else { | ||
| 236 | $altitude=",".$altitude; | ||
| 237 | } | ||
| 238 | |||
| 239 | my $polystring = $entity->{polygon}; | ||
| 240 | #print "in gen_kml_polygon on entity number ".$entity->{number}."\n"; | ||
| 241 | if (not defined $polystring) { | ||
| 242 | warn "Undefined polygon"; | ||
| 243 | warn "entity->data = ".$entity->{data}."\n"; | ||
| 244 | warn "entity->number = ".$entity->{number}."\n"; | ||
| 245 | die; | ||
| 246 | } | ||
| 247 | # Clear spaces from the polystring | ||
| 248 | $polystring =~ s/ //g; | ||
| 249 | # Clear the double parens that postgres gives us | ||
| 250 | $polystring =~ s/\(\(/(/; | ||
| 251 | $polystring =~ s/\)\)$/)/; | ||
| 252 | # Nuke open parens | ||
| 253 | $polystring =~ tr/\(//d; | ||
| 254 | |||
| 255 | $polystring =~ s/\),/)/g; | ||
| 256 | #$polystring =~ s/\)/$altitude\n\t\t/g; | ||
| 257 | $polystring =~ s/\)/$altitude /g; | ||
| 258 | |||
| 259 | |||
| 260 | # Terribly inefficient - could replace with a here document | ||
| 261 | my @kml_poly; | ||
| 262 | push(@kml_poly,"<Polygon>"); | ||
| 263 | push(@kml_poly,"<extrude>1</extrude>"); | ||
| 264 | #push(@kml_poly,"<tessellate>1</tessellate>"); | ||
| 265 | push(@kml_poly,"<altitudeMode>relativeToGround</altitudeMode>"); | ||
| 266 | push(@kml_poly,"<outerBoundaryIs>"); | ||
| 267 | push(@kml_poly,"<LinearRing>"); | ||
| 268 | push(@kml_poly,"<coordinates>"); | ||
| 269 | #push(@kml_poly,split(/\n/,$polystring)); | ||
| 270 | push(@kml_poly,$polystring); | ||
| 271 | push(@kml_poly,"</coordinates>"); | ||
| 272 | push(@kml_poly,"</LinearRing>"); | ||
| 273 | push(@kml_poly,"</outerBoundaryIs>"); | ||
| 274 | push(@kml_poly,"</Polygon>"); | ||
| 275 | |||
| 276 | return \@kml_poly; | ||
| 277 | } | ||
| 278 | |||
| 279 | # bin_entities(entity[]& entities,int nbins) | ||
| 280 | # MODIFIES entities - adds/sets 'bin' attribute for each entity | ||
| 281 | # Returns reference to array of references to struct bin as hashes: | ||
| 282 | # struct bin { | ||
| 283 | # int[] entityidx | ||
| 284 | # double binbound | ||
| 285 | # } | ||
| 286 | |||
| 287 | sub bin_entities($$) { | ||
| 288 | return _bin_kmeans(@_); | ||
| 289 | } | ||
| 290 | |||
| 291 | sub _bin_percentile ($$) { | ||
| 292 | my ($entities,$nbins)=@_; | ||
| 293 | carp "Number of bins not passed to bin_entities" if not defined $nbins; | ||
| 294 | |||
| 295 | my $stat = Statistics::Descriptive::Full->new(); | ||
| 296 | foreach my $entity (@$entities) { | ||
| 297 | $stat->add_data($entity->{data}); | ||
| 298 | } | ||
| 299 | my %stat_bins = $stat->frequency_distribution($nbins); | ||
| 300 | my @binbounds = sort {$a <=> $b} keys %stat_bins; | ||
| 301 | my @bins; | ||
| 302 | for (my $i=0;$i<$nbins;$i++) { | ||
| 303 | $bins[$i]={entityidx => [], binbound => $binbounds[$i]}; | ||
| 304 | } | ||
| 305 | |||
| 306 | for (my $i=0;$i<(scalar @$entities);$i++) { | ||
| 307 | my $entity=$entities->[$i]; | ||
| 308 | my $data=$entity->{data}; | ||
| 309 | my $bin; | ||
| 310 | for (my $j=$#binbounds;$j>=0;$j--) { | ||
| 311 | $bin = $j if ($data <= $binbounds[$j]); | ||
| 312 | } | ||
| 313 | $entity->{bin}=$bin; | ||
| 314 | push(@{$bins[$bin]->{entityidx}},$i); | ||
| 315 | } | ||
| 316 | |||
| 317 | return \@bins; | ||
| 318 | |||
| 319 | } | ||
| 320 | sub _bin_equipartition ($$){ | ||
| 321 | my ($entities,$nbins)=@_; | ||
| 322 | carp "Number of bins not passed to bin_entities" if not defined $nbins; | ||
| 323 | |||
| 324 | my $stat = Statistics::Descriptive::Full->new(); | ||
| 325 | foreach my $entity (@$entities) { | ||
| 326 | $stat->add_data($entity->{data}); | ||
| 327 | } | ||
| 328 | my @binbounds; | ||
| 329 | for (my $i=1;$i<=$nbins;$i++) { | ||
| 330 | my $bound=$stat->percentile(($i/$nbins)*100.0); | ||
| 331 | # Only take unique bounds | ||
| 332 | push(@binbounds,$bound) if (($#binbounds < 0) or ($bound!=$binbounds[$#binbounds])); | ||
| 333 | } | ||
| 334 | croak "Fewer bins (".(scalar @binbounds).") than requested from equipartition ($nbins)!" if ($nbins != (scalar @binbounds)); | ||
| 335 | $nbins = (scalar @binbounds); | ||
| 336 | |||
| 337 | my %stat_bins = $stat->frequency_distribution(\@binbounds); | ||
| 338 | my @bins; | ||
| 339 | for (my $i=0;$i<$nbins;$i++) { | ||
| 340 | $bins[$i]={entityidx => [], binbound => $binbounds[$i]}; | ||
| 341 | } | ||
| 342 | |||
| 343 | for (my $i=0;$i<(scalar @$entities);$i++) { | ||
| 344 | my $entity=$entities->[$i]; | ||
| 345 | my $data=$entity->{data}; | ||
| 346 | my $bin; | ||
| 347 | for (my $j=$#binbounds;$j>=0;$j--) { | ||
| 348 | $bin = $j if ($data <= $binbounds[$j]); | ||
| 349 | } | ||
| 350 | $entity->{bin}=$bin; | ||
| 351 | push(@{$bins[$bin]->{entityidx}},$i); | ||
| 352 | } | ||
| 353 | |||
| 354 | return \@bins; | ||
| 355 | } | ||
| 356 | |||
| 357 | |||
| 358 | sub _bin_kmeans($$) { | ||
| 359 | my ($entities,$nbins)=@_; | ||
| 360 | |||
| 361 | my $rdata = []; | ||
| 362 | foreach my $ent (@$entities) { | ||
| 363 | push(@$rdata,$ent->{data}); | ||
| 364 | } | ||
| 365 | my $assn = _kmeans($rdata,$nbins,15); | ||
| 366 | # This needs to be a hash in kmeans because the bin numbers are not necessarily contiguous | ||
| 367 | my %bins = (); | ||
| 368 | for (my $i=0;$i<scalar(@$assn);$i++) { | ||
| 369 | my $bin = $assn->[$i]; | ||
| 370 | if (not defined $bins{$bin}) { | ||
| 371 | #warn "Assigning new element number $i: ".$rdata->[$i]." to bin $bin"; | ||
| 372 | $bins{$bin} = {entityidx => [], binbound => $rdata->[$i]} | ||
| 373 | } | ||
| 374 | $bins{$bin}->{binbound} = _max($bins{$bin}->{binbound},$rdata->[$i]); | ||
| 375 | push(@{$bins{$bin}->{entityidx}},$i); | ||
| 376 | } | ||
| 377 | |||
| 378 | my @sorted_bins = (); | ||
| 379 | #foreach my $key (keys %bins) { | ||
| 380 | # my $b = $bins{$key}; | ||
| 381 | # if (not defined $b->{binbound}) { | ||
| 382 | # die "Missing binbound in bin $key, with keys ".join(' ',(keys %$b))."."; | ||
| 383 | # } else { | ||
| 384 | # warn "Bin $key has keys ".join(' ',keys(%$b))."."; | ||
| 385 | # } | ||
| 386 | #} | ||
| 387 | @sorted_bins = sort {$a->{binbound} <=> $b->{binbound}} (values %bins); | ||
| 388 | |||
| 389 | |||
| 390 | return \@sorted_bins; | ||
| 391 | } | ||
| 392 | |||
| 393 | # generate_kml_placemark(entity[]& entities,string placename,string description | ||
| 394 | # string color,fh file) | ||
| 395 | # Renders KML lines of the placemark | ||
| 396 | # consisting of a MultiGeometry containing the given entities to the filehandle given | ||
| 397 | # | ||
| 398 | # Sets the default LookAt to the coordinates of the first point in the first | ||
| 399 | # entity's polygon. | ||
| 400 | sub generate_kml_placemark($$$$$) { | ||
| 401 | my ($entities,$placename,$description,$color,$fh)=@_; | ||
| 402 | |||
| 403 | #print "gen_kml_pm called with entities size ".(scalar @$entities)."\n"; | ||
| 404 | return if ((scalar @$entities)==0); | ||
| 405 | # Default LookAt values | ||
| 406 | my $range = 5000; | ||
| 407 | my $tilt = 0; | ||
| 408 | my $heading = 59; | ||
| 409 | |||
| 410 | my @placemark; | ||
| 411 | push(@placemark,'<Placemark>'); | ||
| 412 | push(@placemark,"<name>$placename</name>"); | ||
| 413 | push(@placemark,"<description><![CDATA[$description]]></description>"); | ||
| 414 | |||
| 415 | # Get the first polygon, and weed out XML tags | ||
| 416 | |||
| 417 | my $first_kml_poly = generate_kml_polygon($entities->[0]); | ||
| 418 | my @poly_cords = grep(!/^\t*</,@$first_kml_poly); | ||
| 419 | my @coords = split /,/,$poly_cords[0]; | ||
| 420 | $coords[0] =~ s/^\s*//; | ||
| 421 | |||
| 422 | push(@placemark,"<LookAt>"); | ||
| 423 | push(@placemark,"<longitude>$coords[0]</longitude>"); | ||
| 424 | push(@placemark,"<latitude>$coords[1]</latitude>"); | ||
| 425 | push(@placemark,"<range>$range</range>"); | ||
| 426 | push(@placemark,"<tilt>$tilt</tilt>"); | ||
| 427 | push(@placemark,"<heading>$heading</heading>"); | ||
| 428 | push(@placemark,"</LookAt>"); | ||
| 429 | |||
| 430 | my $style = generate_kml_style($color); | ||
| 431 | push(@placemark,@$style); | ||
| 432 | push(@placemark,""); | ||
| 433 | |||
| 434 | push(@placemark,"<MultiGeometry>"); | ||
| 435 | |||
| 436 | print $fh join('',@placemark); | ||
| 437 | @placemark=(); | ||
| 438 | |||
| 439 | #my $entity_idx=0; | ||
| 440 | #print "entities appears to have ".(scalar @$entities)." entries in g_placemark\n"; | ||
| 441 | foreach my $entity (@$entities) { | ||
| 442 | #print "Processing entity $entity_idx\n" if ($entity_idx>130); | ||
| 443 | my $poly = generate_kml_polygon($entity); | ||
| 444 | print $fh join('',@$poly); | ||
| 445 | #push(@placemark,@$poly); | ||
| 446 | #$entity_idx++; | ||
| 447 | } | ||
| 448 | push(@placemark,"</MultiGeometry>"); | ||
| 449 | push(@placemark,"</Placemark>"); | ||
| 450 | |||
| 451 | print $fh join('',@placemark); | ||
| 452 | return; | ||
| 453 | } | ||
| 454 | |||
| 455 | =pod | ||
| 456 | |||
| 457 | =head2 generate_kml_file() -- generate a KML file (map only) | ||
| 458 | |||
| 459 | Renders the data passed in in entities to a KML file, rendered to the filehandle passed in. | ||
| 460 | |||
| 461 | Parameters are passed in as named arguments in a hash. | ||
| 462 | |||
| 463 | =head3 Example: | ||
| 464 | |||
| 465 | generate_kml_file(entities => $entities, | ||
| 466 | placename => "Foobar City", | ||
| 467 | data_desc => "Total Population", | ||
| 468 | nbins => 5, | ||
| 469 | kmlfh => $filehandle_for_kml_output, | ||
| 470 | startcolor => "FFFF0000", | ||
| 471 | endcolor => "FF00FF00"); | ||
| 472 | |||
| 473 | =head3 Mandatory arguments | ||
| 474 | |||
| 475 | =over | ||
| 476 | |||
| 477 | =item * entities | ||
| 478 | |||
| 479 | Reference to an array of "entities", the data structure described above, used to store lists of (polygon,data) pairs. | ||
| 480 | |||
| 481 | =item * placename | ||
| 482 | |||
| 483 | A string containing a textual description (name) of the place represented by the given entities | ||
| 484 | |||
| 485 | =item * data_desc | ||
| 486 | |||
| 487 | A string describing the sort of data given in the entities | ||
| 488 | |||
| 489 | =item * nbins | ||
| 490 | |||
| 491 | The maximum number of bins into which to cluster the given data (see "Binning" below) | ||
| 492 | |||
| 493 | =item * kmlfh | ||
| 494 | |||
| 495 | Handle to an open-for-writing file into which to render the KML data. | ||
| 496 | |||
| 497 | =back | ||
| 498 | |||
| 499 | =head3 Optional arguments | ||
| 500 | |||
| 501 | =over | ||
| 502 | |||
| 503 | =item * startcolor | ||
| 504 | |||
| 505 | The OBGR color used for the bins with the lowest numerical value in the range provided. Defaults to FF000000. | ||
| 506 | See "Colors" below. | ||
| 507 | |||
| 508 | =item * endcolor | ||
| 509 | |||
| 510 | The OBGR color used for the bins with the highest numerical value in the range provided. Defaults to FFFFFFFF. | ||
| 511 | |||
| 512 | =back | ||
| 513 | |||
| 514 | =head3 Description | ||
| 515 | |||
| 516 | generate_kml_file renders the data provided in the given entities to a KML map suitable for display in Google Earth. To do this, | ||
| 517 | it first separates the data into a user-configurable number of bins (see "Binning"), then assigns each bin a color. The bin with | ||
| 518 | lowest numerical value is assigned color "startcolor" and the bin with largest value gets color "endcolor"; bins between these | ||
| 519 | have their colors calculated by linear interpolation between these two values. The final KML file will have one placemark for | ||
| 520 | each data bin, so that each bin can be viewed/hidden independently. | ||
| 521 | |||
| 522 | =head4 Placemark naming | ||
| 523 | |||
| 524 | Each placemark is named "[placename] Bin [n]", where placename is the parameter passed in, and n is the index of the bin which the | ||
| 525 | placemark represents. Each placemark has a description "[data_desc] less than or equal to [bound]", where data_desc is passed in, | ||
| 526 | and bound is the upper bound on the data values in that bin. | ||
| 527 | |||
| 528 | =head4 Binning | ||
| 529 | |||
| 530 | The code makes an attempt to separate the data into nbins separate bins. In some degenerate cases (such as nbins > #data points), | ||
| 531 | there will be fewer output bins than requested, but there will never be more than nbins bins in the output map. There are three | ||
| 532 | binning algorithms implemented in the code, as _bin_percentile, _bin_equipartition, and _bin_kmeans. The particular algorithm | ||
| 533 | used can be modified by changing the function bin_entities (there may be future support for a parameter to change the method). | ||
| 534 | The default method is _bin_kmeans. The algorithms are detailed below: | ||
| 535 | |||
| 536 | =over | ||
| 537 | |||
| 538 | =item * _bin_percentile | ||
| 539 | |||
| 540 | This method calculates a histogram of the data values, then divides the bins equally by percentile. For example, with nbins=5, | ||
| 541 | the bins will contain the [0,20), [20,40), [40,60), [60,80), [80,100] 'th percentiles of the data. This method is fast but has | ||
| 542 | several drawbacks. The most serious is that the raw percentile boundaries are often not helpful in the presence of outliers. | ||
| 543 | |||
| 544 | =item * _bin_equipartition | ||
| 545 | |||
| 546 | This method calculates a histogram of the data values, then divides the histogram into nbins sections such that each bin | ||
| 547 | has an (almost) equal number of data points within it. This also suffers the problem that outliers can induce highly artificial | ||
| 548 | bin boundaries. | ||
| 549 | |||
| 550 | =item * _bin_kmeans | ||
| 551 | |||
| 552 | This method performs a k-means clustering on the data, with k=nbins. In theory, this should separate the data points into | ||
| 553 | "natural" groupings; in practice it seems to work quite well. Its major disadvantage is that it is much more computationally | ||
| 554 | intensive than the other two methods, a problem which is exacerbated when the number of data points becomes large. | ||
| 555 | |||
| 556 | =back | ||
| 557 | |||
| 558 | =head4 Colors | ||
| 559 | |||
| 560 | Colors for this library are represented in the same OBGR format used by KML files. This format represents each color as a 32-bit | ||
| 561 | hexadecimal number, with 8 bits each for opacity (transparency), blue, green, and red. Note that the ordering of values is | ||
| 562 | different from usual web color specifications, which are RGB. Examples: | ||
| 563 | |||
| 564 | FFFF0000 = pure blue | ||
| 565 | 80FF0000 = blue, 50% transparency | ||
| 566 | 00FF0000 = blue, fully transparent | ||
| 567 | FF00FF00 = pure green | ||
| 568 | FF0000FF = pure red | ||
| 569 | |||
| 570 | Colors for each bin are constructed by linear interpolation between the optional parameters startcolor and endcolor. The | ||
| 571 | interpolation is not weighted by bin values; it is just a simple interpolation along the line between start and end in RGB space. | ||
| 572 | |||
| 573 | =cut | ||
| 574 | |||
| 575 | sub generate_kml_file { | ||
| 576 | my %args = @_; | ||
| 577 | return _generate_kml_file($args{entities},$args{placename},$args{data_desc}, | ||
| 578 | $args{nbins},$args{kmlfh},$args{startcolor},$args{endcolor}); | ||
| 579 | } | ||
| 580 | |||
| 581 | # _generate_kml_file(entity[]& entities,string placename,string data_desc, | ||
| 582 | # int nbins,fh filehandle,OPT string startcolor,OPT string endcolor); | ||
| 583 | # Fills filehandle with the lines of a KML file constituting a display | ||
| 584 | # for the given entities, split into nbins placemarks. | ||
| 585 | sub _generate_kml_file($$$$$;$$) { | ||
| 586 | my ($entities,$placename,$datadesc,$nbins,$fh,$startcolor,$endcolor) = @_; | ||
| 587 | |||
| 588 | # Refactored to expose bins and colors for legend generation in KMZ | ||
| 589 | my $bins_colors = _generate_bins_colors($entities,$nbins, | ||
| 590 | $startcolor,$endcolor); | ||
| 591 | |||
| 592 | # Map data parameter in entities to altitude | ||
| 593 | altitude_map($entities,"data"); | ||
| 594 | |||
| 595 | return _generate_kml($entities,$placename,$datadesc,$nbins, | ||
| 596 | $bins_colors->[0],$bins_colors->[1],$fh); | ||
| 597 | } | ||
| 598 | |||
| 599 | # _generate_kml(entity[]& entities,string placename,string data_desc, | ||
| 600 | # int nbins,bin[]& bins,string[]& colors,fh file | ||
| 601 | # OPT string legend_file_name) | ||
| 602 | # Internal function taking in entities, bins, and colors, and generating | ||
| 603 | # the associated KML file to the filehandle file | ||
| 604 | # Return as specified in (user-visible) generate_kml_file | ||
| 605 | sub _generate_kml($$$$$$$;$) { | ||
| 606 | my ($entities,$placename,$datadesc,$nbins,$bins,$colors,$fh,$legend_file_name) = @_; | ||
| 607 | |||
| 608 | my @kml_file; | ||
| 609 | |||
| 610 | push(@kml_file,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); | ||
| 611 | push(@kml_file,"<kml xmlns=\"http://earth.google.com/kml/2.0\">"); | ||
| 612 | push(@kml_file,"<Document>"); | ||
| 613 | |||
| 614 | if (defined $legend_file_name) { | ||
| 615 | push(@kml_file,"<ScreenOverlay>"); | ||
| 616 | push(@kml_file,"<description>$placename $datadesc</description>"); | ||
| 617 | push(@kml_file,"<name>Legend</name>"); | ||
| 618 | push(@kml_file,"<Icon>"); | ||
| 619 | push(@kml_file,"<href>$legend_file_name</href>"); | ||
| 620 | push(@kml_file,"</Icon>"); | ||
| 621 | push(@kml_file,"<overlayXY x=\"0\" y=\"1\" xunits=\"fraction\" yunits=\"fraction\"/>"); | ||
| 622 | push(@kml_file,"<screenXY x=\"0\" y=\"1\" xunits=\"fraction\" yunits=\"fraction\"/>"); | ||
| 623 | push(@kml_file,"<rotationXY x=\"0\" y=\"0\" xunits=\"fraction\" yunits=\"fraction\"/>"); | ||
| 624 | push(@kml_file,"<size x=\"0\" y=\"0\" xunits=\"pixels\" yunits=\"pixels\"/>"); | ||
| 625 | push(@kml_file,"<rotation>0</rotation>"); | ||
| 626 | push(@kml_file,"</ScreenOverlay>"); | ||
| 627 | } | ||
| 628 | print $fh join('',@kml_file); | ||
| 629 | @kml_file=(); | ||
| 630 | |||
| 631 | for (my $i=0;$i<(scalar @$bins);$i++) { | ||
| 632 | my $bin = $bins->[$i]; | ||
| 633 | my $entityidx = $bin->{entityidx}; | ||
| 634 | #carp $entityidx."\n"; | ||
| 635 | #carp @$entityidx."\n"; | ||
| 636 | # Fold singletons into a list | ||
| 637 | #print "Bin $i contains ".join(',',@$entityidx)."\n"; | ||
| 638 | my @selected_entities = ( @$entities[@$entityidx] ); | ||
| 639 | generate_kml_placemark( | ||
| 640 | \@selected_entities, | ||
| 641 | $placename." bin ".($i+1), | ||
| 642 | $datadesc." less than/equal to ".$bin->{binbound}, | ||
| 643 | $colors->[$i], | ||
| 644 | $fh); | ||
| 645 | #my $placemark=[""]; | ||
| 646 | #push(@kml_file,@$placemark); | ||
| 647 | } | ||
| 648 | |||
| 649 | push(@kml_file,"</Document>"); | ||
| 650 | push(@kml_file,"</kml>"); | ||
| 651 | print $fh join('',@kml_file); | ||
| 652 | return; | ||
| 653 | } | ||
| 654 | |||
| 655 | # altitude_map(entity[]& entities,string fieldname) | ||
| 656 | # MODIFIES entities - adds altitude attribute based on data value in fieldname for each entity | ||
| 657 | # returns none | ||
| 658 | |||
| 659 | sub altitude_map($$) { | ||
| 660 | my ($ents,$fname) = @_; | ||
| 661 | my $minval = $ents->[0]->{$fname}; | ||
| 662 | my $maxval = $ents->[0]->{$fname}; | ||
| 663 | foreach my $ent (@$ents) { | ||
| 664 | if ($ent->{$fname} < $minval) { | ||
| 665 | $minval = $ent->{$fname}; | ||
| 666 | } elsif ($ent->{$fname} > $maxval) { | ||
| 667 | $maxval = $ent->{$fname}; | ||
| 668 | } | ||
| 669 | } | ||
| 670 | # Use a 3km altitude scale | ||
| 671 | my $alt_scale = 3000; | ||
| 672 | # Place bottom of range 50m above ground to avoid artifacting | ||
| 673 | my $min_height = 50; | ||
| 674 | |||
| 675 | my $multiplier = $alt_scale/($maxval-$minval); | ||
| 676 | my $offset = $minval - $min_height; | ||
| 677 | |||
| 678 | foreach my $ent (@$ents) { | ||
| 679 | $ent->{altitude} = ($ent->{$fname}-$offset) * $multiplier; | ||
| 680 | } | ||
| 681 | |||
| 682 | return; | ||
| 683 | } | ||
| 684 | |||
| 685 | # _generate_bins_colors(entity[]& entities,int nbins,OPT string startcolor | ||
| 686 | # OPT string endcolor) | ||
| 687 | # Internal function which generates bins and bin colors for a KML file | ||
| 688 | # Returns arrayref [$bins $colors] | ||
| 689 | |||
| 690 | sub _generate_bins_colors($$;$$) { | ||
| 691 | |||
| 692 | my ($entities,$nbins,$startcolor,$endcolor) = @_; | ||
| 693 | |||
| 694 | my $bins = bin_entities($entities,$nbins); | ||
| 695 | $nbins = (scalar @$bins); | ||
| 696 | my $colors = generate_colors($nbins,$startcolor,$endcolor); | ||
| 697 | |||
| 698 | return [$bins,$colors]; | ||
| 699 | } | ||
| 700 | |||
| 701 | # generate_legend(bin[]& bins,color[]& colors,string font_path,OPT int font_size,OPT int patch_size) | ||
| 702 | # Returns a reference to a PNG file with a legend for the given bins | ||
| 703 | sub generate_legend($$$;$$) { | ||
| 704 | my ($bins,$colors,$font_path,$text_size,$patch_size) = @_; | ||
| 705 | $text_size = 12 if not defined $text_size; | ||
| 706 | $patch_size = 30 if not defined $patch_size; | ||
| 707 | my $hmargin = 5; | ||
| 708 | my $vmargin = $patch_size/6; | ||
| 709 | |||
| 710 | my $format = "%.3f - %.3f"; | ||
| 711 | |||
| 712 | my @bounds = ( 0 ); | ||
| 713 | for (my $i=0;$i < (scalar @$bins);$i++) { | ||
| 714 | my $bin = $bins->[$i]; | ||
| 715 | push @bounds,$bin->{binbound}; | ||
| 716 | } | ||
| 717 | # Find the max size required by the description text | ||
| 718 | my $maxtextwidth = 0; | ||
| 719 | my $maxtextheight = 0; | ||
| 720 | for (my $i = 0; $i < $#bounds; $i++) { | ||
| 721 | my @loopbound = | ||
| 722 | GD::Image->stringFT(0,$font_path,$text_size,0,0,0, | ||
| 723 | sprintf($format,$bounds[$i],$bounds[$i+1])); | ||
| 724 | $maxtextwidth = | ||
| 725 | _max($loopbound[2]-$loopbound[0], | ||
| 726 | $loopbound[4]-$loopbound[6], | ||
| 727 | $maxtextwidth); | ||
| 728 | # Coordinates increase as you go down and to the right... | ||
| 729 | $maxtextheight = | ||
| 730 | _max($loopbound[1]-$loopbound[7], | ||
| 731 | $loopbound[3]-$loopbound[5], | ||
| 732 | $maxtextheight); | ||
| 733 | } | ||
| 734 | my $rowheight = _max($patch_size,$maxtextheight); | ||
| 735 | my $imagewidth = $patch_size + $hmargin + $maxtextwidth; | ||
| 736 | my $imageheight = $rowheight * $#bounds; | ||
| 737 | |||
| 738 | my $im = new GD::Image($imagewidth,$imageheight,1); | ||
| 739 | |||
| 740 | my $white = $im->colorAllocate(255,255,255); | ||
| 741 | my $black = $im->colorAllocate(0,0,0); | ||
| 742 | my @bincolors; | ||
| 743 | for (my $i=0;$i < (scalar @$colors);$i++) { | ||
| 744 | my @vals = split //,$colors->[$i]; | ||
| 745 | #Colors are OBGR, GD expects RGBA with half range | ||
| 746 | my $color = | ||
| 747 | $im->colorAllocate(hex(join('',@vals[6..7])), | ||
| 748 | hex(join('',@vals[4..5])), | ||
| 749 | hex(join('',@vals[2..3]))); | ||
| 750 | push @bincolors,$color; | ||
| 751 | } | ||
| 752 | # BUG ALERT - this will break things maybe if the user picks black as a color.. | ||
| 753 | $im->transparent($black); | ||
| 754 | $im->filledRectangle(0,0,$imagewidth,$imageheight,$black); | ||
| 755 | |||
| 756 | for (my $i = 0; $i < $#bounds; $i++) { | ||
| 757 | $im->filledRectangle(0, | ||
| 758 | $i*$rowheight, | ||
| 759 | $patch_size, | ||
| 760 | $i*$rowheight+$patch_size - 1, | ||
| 761 | $bincolors[$i]); | ||
| 762 | |||
| 763 | $im->stringFT($white, | ||
| 764 | $font_path, | ||
| 765 | $text_size, | ||
| 766 | 0, | ||
| 767 | $patch_size+$hmargin, | ||
| 768 | $i*$rowheight + $patch_size - 1 - $vmargin, | ||
| 769 | sprintf($format,$bounds[$i],$bounds[$i+1])); | ||
| 770 | #"$bounds[$i] - $bounds[$i+1]"); | ||
| 771 | } | ||
| 772 | |||
| 773 | my $pngdata = $im->png; | ||
| 774 | return \$pngdata; | ||
| 775 | |||
| 776 | } | ||
| 777 | |||
| 778 | sub _max { | ||
| 779 | my $themax = shift; | ||
| 780 | my $elt; | ||
| 781 | while ($elt = shift) { | ||
| 782 | $themax = $elt if (defined($elt) and ($elt > $themax)); | ||
| 783 | } | ||
| 784 | return $themax; | ||
| 785 | } | ||
| 786 | |||
| 787 | =pod | ||
| 788 | |||
| 789 | =head2 generate_kmz_file() -- generate a KMZ file (KML map + PNG legend) | ||
| 790 | |||
| 791 | Renders the data passed in in entities to a KML file. Generates appropriate legend, and combines the legend and KML file into a KMZ file | ||
| 792 | stored into the filehandle passed as a parameter. | ||
| 793 | |||
| 794 | Parameters are passed in as named arguments in a hash. | ||
| 795 | |||
| 796 | =head3 Example: | ||
| 797 | |||
| 798 | generate_kmz_file(entities => $entities, | ||
| 799 | placename => "Foobar City", | ||
| 800 | data_desc => "Total Population", | ||
| 801 | nbins => 5, | ||
| 802 | kmzfh => $filehandle_for_kmz_output, | ||
| 803 | startcolor => "FFFF0000", | ||
| 804 | endcolor => "FF00FF00"); | ||
| 805 | |||
| 806 | =head3 Mandatory arguments | ||
| 807 | |||
| 808 | =over | ||
| 809 | |||
| 810 | =item * entities | ||
| 811 | |||
| 812 | Reference to an array of "entities", the data structure described above, used to store lists of (polygon,data) pairs. | ||
| 813 | |||
| 814 | =item * placename | ||
| 815 | |||
| 816 | A string containing a textual description (name) of the place represented by the given entities | ||
| 817 | |||
| 818 | =item * data_desc | ||
| 819 | |||
| 820 | A string describing the sort of data given in the entities | ||
| 821 | |||
| 822 | =item * nbins | ||
| 823 | |||
| 824 | The maximum number of bins into which to cluster the given data (see "Binning" below) | ||
| 825 | |||
| 826 | =item * kmzfh | ||
| 827 | |||
| 828 | Handle to an open-for-writing file into which to render the KML data. | ||
| 829 | |||
| 830 | =back | ||
| 831 | |||
| 832 | =head3 Optional arguments | ||
| 833 | |||
| 834 | =over | ||
| 835 | |||
| 836 | =item * startcolor | ||
| 837 | |||
| 838 | The OBGR color used for the bins with the lowest numerical value in the range provided. Defaults to FF000000. | ||
| 839 | See "Colors" under generate_kml_file(). | ||
| 840 | |||
| 841 | =item * endcolor | ||
| 842 | |||
| 843 | The OBGR color used for the bins with the highest numerical value in the range provided. Defaults to FFFFFFFF. | ||
| 844 | |||
| 845 | =back | ||
| 846 | |||
| 847 | =head3 Description | ||
| 848 | |||
| 849 | generate_kmz_file first generates a KML map for the given data, as described in generate_kml_file. It then generates a PNG legend | ||
| 850 | containing a color swatch for each data bin and the range of values represented in each bin. The KML map and PNG legend are | ||
| 851 | put together into a ZIP archive known as a KMZ file, ready for viewing in Google Earth. This KMZ file is written out to the | ||
| 852 | filehandle passed in as a parameter. | ||
| 853 | |||
| 854 | Please see generate_kml_file for additional details on the rendered KML map. | ||
| 855 | |||
| 856 | This version of generate_kmz_file renders temporary data (the KML map) to a tempfile to reduce memory footprint. | ||
| 857 | |||
| 858 | =cut | ||
| 859 | |||
| 860 | sub generate_kmz_file { | ||
| 861 | my %args = @_; | ||
| 862 | return _generate_kmz_file($args{entities},$args{placename},$args{data_desc}, | ||
| 863 | $args{nbins},$args{kmzfh},$args{startcolor},$args{endcolor}); | ||
| 864 | } | ||
| 865 | |||
| 866 | # _generate_kmz_file(entity[]& entities,string placename,string data_desc, | ||
| 867 | # int nbins,fh kmzfh, OPT string startcolor, | ||
| 868 | # OPT string endcolor); | ||
| 869 | # Returns void | ||
| 870 | # File 'kmzfh' will be a KMZ file containing the | ||
| 871 | # KML source and the legend diagram | ||
| 872 | |||
| 873 | sub _generate_kmz_file($$$$$;$$) { | ||
| 874 | my ($entities,$placename,$datadesc,$nbins,$kmzfh,$startcolor,$endcolor) = @_; | ||
| 875 | |||
| 876 | my $legend_name = "legend.png"; | ||
| 877 | |||
| 878 | |||
| 879 | my $bins_colors = _generate_bins_colors($entities,$nbins, | ||
| 880 | $startcolor,$endcolor); | ||
| 881 | |||
| 882 | # Map data parameter in entities to altitude | ||
| 883 | altitude_map($entities,"data"); | ||
| 884 | |||
| 885 | # OK to render the legend to RAM - it's small | ||
| 886 | my $legend = generate_legend($bins_colors->[0],$bins_colors->[1],$FONT_PATH); | ||
| 887 | |||
| 888 | # KML must be rendered to disk | ||
| 889 | my ($tmp_fh,$tmp_fn) = tempfile(); | ||
| 890 | _generate_kml($entities,$placename,$datadesc,$nbins, | ||
| 891 | $bins_colors->[0],$bins_colors->[1],$tmp_fh,$legend_name); | ||
| 892 | close($tmp_fh); | ||
| 893 | |||
| 894 | # Construct the KMZ/ZIP archive and add the kml and legend files | ||
| 895 | my $kmz = Archive::Zip->new(); | ||
| 896 | #my $kml_member = $kmz->addString(join("",@$kml),"generated_map.kml"); | ||
| 897 | my $kml_member = $kmz->addFile($tmp_fn,"generated_map.kml"); | ||
| 898 | $kml_member->desiredCompressionMethod( COMPRESSION_DEFLATED ); | ||
| 899 | my $leg_member = $kmz->addString($$legend,$legend_name); | ||
| 900 | $leg_member->desiredCompressionMethod( COMPRESSION_STORED ); | ||
| 901 | |||
| 902 | # Dump the zip data to the file | ||
| 903 | #my $kmz_fh; | ||
| 904 | #open($kmz_fh,">$kmzname") or die "Couldn't create output file in generate_kmz"; | ||
| 905 | if ($kmz->writeToFileHandle($kmzfh) != AZ_OK) { | ||
| 906 | die "Couldn't write to output file in generate_kmz"; | ||
| 907 | } | ||
| 908 | #close($kmzfh); | ||
| 909 | unlink($tmp_fn); | ||
| 910 | return; | ||
| 911 | } | ||
| 912 | sub _kmeans { | ||
| 913 | my ($data,$clusters,$npass) = @_; | ||
| 914 | if ($clusters > scalar(@$data)) { | ||
| 915 | warn "More clusters ($clusters) than data points (".scalar(@$data).")!"; | ||
| 916 | my @result; | ||
| 917 | for (my $i=0;$i < scalar(@$data); $i++) { | ||
| 918 | push (@result,$i); | ||
| 919 | } | ||
| 920 | return \@result; | ||
| 921 | } | ||
| 922 | |||
| 923 | my %cluster_centroids = (); | ||
| 924 | for (my $i=0; $i < $clusters; $i++) { | ||
| 925 | my $idx; | ||
| 926 | do { | ||
| 927 | $idx = int(rand(scalar(@$data))); | ||
| 928 | } while (defined($cluster_centroids{$idx})); | ||
| 929 | $cluster_centroids{$idx} = 1; | ||
| 930 | } | ||
| 931 | |||
| 932 | my $rcenters = []; | ||
| 933 | foreach my $cent (keys %cluster_centroids) { | ||
| 934 | push (@$rcenters,$data->[$cent]); | ||
| 935 | } | ||
| 936 | |||
| 937 | #Assign points to clusters | ||
| 938 | my $assn = assign_clusters($data,$rcenters); | ||
| 939 | |||
| 940 | for (;$npass>0;$npass--) { | ||
| 941 | #Recalculate centroids | ||
| 942 | $rcenters = recalculate_centroids($data,$rcenters,$assn); | ||
| 943 | #Assign points to clusters | ||
| 944 | my $newassn = assign_clusters($data,$rcenters); | ||
| 945 | |||
| 946 | # End the iterations if the assignments don't change | ||
| 947 | my $done = 1; | ||
| 948 | for (my $i = 0;$i<scalar(@$newassn) and $done; $i++) { | ||
| 949 | $done = ($assn->[$i] == $newassn->[$i]) | ||
| 950 | } | ||
| 951 | if ($done) { | ||
| 952 | $npass = 0; | ||
| 953 | } else { | ||
| 954 | $assn = $newassn; | ||
| 955 | } | ||
| 956 | } | ||
| 957 | return $assn; | ||
| 958 | } | ||
| 959 | |||
| 960 | sub assign_clusters { | ||
| 961 | my ($data,$centroids) = @_; | ||
| 962 | my @assn=(); | ||
| 963 | $#assn = scalar(@$data)-1; | ||
| 964 | for (my $di = 0; $di < scalar(@$data); $di++) { | ||
| 965 | my $pt = $data->[$di]; | ||
| 966 | my $dist = abs($pt-$centroids->[0]); | ||
| 967 | my $idx = 0; | ||
| 968 | for (my $i=1;$i<scalar(@$centroids);$i++) { | ||
| 969 | my $d2 = abs($pt-$centroids->[$i]); | ||
| 970 | if ($d2 < $dist) { | ||
| 971 | $dist = $d2; | ||
| 972 | $idx = $i; | ||
| 973 | } | ||
| 974 | } | ||
| 975 | $assn[$di] = $idx; | ||
| 976 | } | ||
| 977 | |||
| 978 | # This inverted loop loses on performance | ||
| 979 | #my @dists; | ||
| 980 | #for (my $c=0;$c<scalar(@$centroids);$c++) { | ||
| 981 | # for (my $i=0;$i<scalar(@$data);$i++) { | ||
| 982 | # my $dist = abs($data->[$i]-$centroids->[$c]); | ||
| 983 | # if (not defined($dists[$i]) or ($dists[$i] > $dist)) { | ||
| 984 | # $dists[$i] = $dist; | ||
| 985 | # $assn[$i] = $c; | ||
| 986 | # } | ||
| 987 | # } | ||
| 988 | #} | ||
| 989 | |||
| 990 | return \@assn; | ||
| 991 | } | ||
| 992 | |||
| 993 | sub recalculate_centroids { | ||
| 994 | my ($data,$centroids,$assignments) = @_; | ||
| 995 | |||
| 996 | my @means; | ||
| 997 | my @counts; | ||
| 998 | for (my $c=0;$c<scalar(@$centroids);$c++) { | ||
| 999 | push(@means,0); | ||
| 1000 | push(@counts,0); | ||
| 1001 | } | ||
| 1002 | for (my $i = 0;$i < scalar(@$data);$i++) { | ||
| 1003 | my $t = $assignments->[$i]; | ||
| 1004 | $means[$t] += $data->[$i]; | ||
| 1005 | $counts[$t]++; | ||
| 1006 | } | ||
| 1007 | for (my $i=0;$i<scalar(@means);$i++) { | ||
| 1008 | $means[$i] /= $counts[$i] if ($counts[$i]!=0); | ||
| 1009 | } | ||
| 1010 | return \@means; | ||
| 1011 | } | ||
| 1012 | |||
| 1013 | END {} | ||
| 1014 | 1; | ||
| 1015 | |||
| 1016 | |||
| 1017 | =pod | ||
| 1018 | |||
| 1019 | =head1 TIPS | ||
| 1020 | |||
| 1021 | =head2 Chunk size in Archive::Zip | ||
| 1022 | |||
| 1023 | I've found that changing the chunk size ($ChunkSize) in the Archive::Zip module from the default 32K (32768) to around 128K (131072) | ||
| 1024 | can really speed up KMZ generation, especially for really big maps. To do this, change the line | ||
| 1025 | |||
| 1026 | $ChunkSize=32768; | ||
| 1027 | |||
| 1028 | in Zip.pm to: | ||
| 1029 | |||
| 1030 | $ChunkSize=131072; | ||
| 1031 | |||
| 1032 | =head1 AUTHOR | ||
| 1033 | |||
| 1034 | Imran Haque, ihaque@cs.stanford.edu | ||
| 1035 | |||
| 1036 | =head1 COPYRIGHT AND LICENSE | ||
| 1037 | |||
| 1038 | This module is Copyright 2007, Imran Haque, ihaque@cs.stanford.edu. | ||
| 1039 | |||
| 1040 | You may modify and/or redistribute this module under the same terms as Perl itself. | ||
| 1041 | |||
| 1042 | =cut |