Skip to content

Instantly share code, notes, and snippets.

@y-uti
Created January 17, 2018 14:54
Show Gist options
  • Save y-uti/922203eec5d2731215e625e1f2d9eb92 to your computer and use it in GitHub Desktop.
Save y-uti/922203eec5d2731215e625e1f2d9eb92 to your computer and use it in GitHub Desktop.
A sample code for DBSCAN with haversine as distance
<?php
/*
* A sample program for DBSCAN with haversine as distance
*
* Requirements
* - PHP-ML (https://github.com/php-ai/php-ml)
* - php-geospatial (https://github.com/php-geospatial/geospatial)
*/
require_once __DIR__ . '/vendor/autoload.php';
use Phpml\Clustering\DBSCAN;
use Phpml\Math\Distance;
class Haversine implements Distance
{
public function distance(array $a, array $b): float
{
return haversine(
['type' => 'Point', 'coordinates' => $a],
['type' => 'Point', 'coordinates' => $b]);
}
}
$samples = [
[0, 90 - 1e-6], [180, 90 - 1e-6], // two samples near the north pole
[-180 + 1e-6, 0], [180 - 1e-6, 0], // two samples on the equator
[0, -90 + 1e-6], [180, -90 + 1e-6], // two samples near the south pole
];
$dbscan = new DBSCAN($epsilon = 1, $min_samples = 2, new Haversine());
$clustered = $dbscan->cluster($samples);
foreach ($clustered as $i => $cluster) {
echo "cluster $i: ", json_encode($cluster), "\n";
}
/*
* cluster 0: [[0,89.999999],[180,89.999999]]
* cluster 1: [[-179.999999,0],[179.999999,0]]
* cluster 2: [[0,-89.999999],[180,-89.999999]]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment