Skip to content

Instantly share code, notes, and snippets.

@danhammer
Last active December 25, 2015 22:29
Show Gist options
  • Save danhammer/7049642 to your computer and use it in GitHub Desktop.
Save danhammer/7049642 to your computer and use it in GitHub Desktop.
Draft workflow for loading FORMA hits to CartoDB from GEE
import pandas as pd
import forma
import ee
from bbox_tiler import bbox
from globalmaptiles import GlobalMercator
def coordsToTiles(lon, lat):
# Convert the supplied latitude and longitude coordinates to
# mercator tiles at zoom level 16, ready for upload to CartoDB.
mercator = GlobalMercator()
mx, my = mercator.LatLonToMeters(lat, lon)
tminx, tminy = mercator.MetersToTile(mx, my, 16)
return tminx, tminy
def grabPixels(img, coords):
# Accepts the FORMA alert image and the coordinates of a polygon
# and returns a list of lists, one for each pixel.
polygon = ee.Feature.Polygon(coords)
coll = ee.ImageCollection.fromImages([img])
return coll.getRegion(polygon, 250).getInfo()
def convertEntry(x):
# Convert the GEE output for each pixel into a dictionary entry
# that will eventually be converted to a Pandas data frame row;
# keys are the variable names.
x, y = coordsToTiles(x[1], x[2])
return {'x':x, 'y':y, 'z':16, 'p':'first-half 2007 alerts'}
def tileToPandas(img, tile):
# Accepts a FORMA alert image and the tile object and returns a
# Pandas data frame of the results
print tile
pixels = grabPixels(img, tile[2])
data = map(convertEntry, pixels[1::])
return pd.DataFrame(data)
def genResultCSV(filename = "/mnt/hgfs/Dropbox/forma_hits.csv"):
# Generate a CSV of the results for the entire ecoregion
img = forma.calcChange(40160, '01/17/2007', '12/31/2007')
UPPER_LEFT = [99.53064,3.25346]
LOWER_RIGHT = [106.23779,-4.31029]
tiles = bbox.mk_tile_bounding_points(UPPER_LEFT, LOWER_RIGHT, 20)
res = map(lambda t: tileToPandas(img, t), tiles)
coll = pd.concat(res, ignore_index=True)
coll.to_csv(filename)
return coll
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment