Skip to content

Instantly share code, notes, and snippets.

@n0531m
Last active August 24, 2018 08:25
Show Gist options
  • Save n0531m/cb99ca8fe1c4aeb28d9cad0b82b3fc84 to your computer and use it in GitHub Desktop.
Save n0531m/cb99ca8fe1c4aeb28d9cad0b82b3fc84 to your computer and use it in GitHub Desktop.
A query in BigQuery that leverages a Javascript library to compute a voronoi diagram.
#standardSQL
CREATE TEMP FUNCTION
testVolonoi (data ARRAY<STRUCT<x float64, y float64, id string, name string>>, margin_ratio float64)
RETURNS ARRAY<STRUCT<id string, name string, wkt String>>
LANGUAGE js AS """
let xl,xr=data[0].x;
let yt,yb=data[0].y;
for(i=1;i<data.length;i++){
if(data[i].x < xl) xl=data[i].x ;
if(data[i].x > xr) xr=data[i].x ;
if(data[i].y < yt) yt=data[i].y ;
if(data[i].y > yb) yb=data[i].y ;
}
box_width =xr-xl;
box_height=yb-yt;
bbox={
xl: xl - box_width * margin_ratio,
xr: xr + box_width * margin_ratio,
yt: yt - box_height * margin_ratio,
yb: yb + box_height * margin_ratio
};
voronoi=new Voronoi();
diagram = voronoi.compute(data, bbox);
cells=diagram.cells;
let results=new Array();
for (var i=0;i<cells.length;i++){
let halfedges=cells[i].halfedges;
let wkt_polygon="POLYGON((";
let vertex0=halfedges[0].getStartpoint();
wkt_polygon+= vertex0.x +" "+vertex0.y;
for (j=0;j<halfedges.length;j++){
let vertex=halfedges[j].getEndpoint();
wkt_polygon+=","+vertex.x+" "+vertex.y;
}
wkt_polygon+="))";
results.push({"wkt":wkt_polygon, "id":data[i].id, "name":data[i].name});
}
return results;
"""
OPTIONS
# loading hosted opensource library : https://github.com/gorhill/Javascript-Voronoi
( library="gs://moritani-bigdata-sgtaxi-us/udf/volonoi/rhill-voronoi-core.min.js" );
# ( library="gs://moritani-bigdata-sgtaxi-us/udf/volonoi/rhill-voronoi-core.js" );
SELECT
id, name, wkt
FROM
UNNEST(testVolonoi( ARRAY (
SELECT
STRUCT(
location.longitude AS x,
location.latitude AS y,
station_id AS id,
name) AS data
FROM
`moritani-bigdata.sg_taxi_prediction.rainfall_preproc`
GROUP BY
station_id, name, location.longitude, location.latitude ), 0.2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment