Skip to content

Commit

Permalink
Merge branch 'main' into allow-specify-products-to-notify
Browse files Browse the repository at this point in the history
  • Loading branch information
adybbroe authored Sep 8, 2023
2 parents 1835753 + 232d47d commit 621ee37
Show file tree
Hide file tree
Showing 14 changed files with 950 additions and 250 deletions.
87 changes: 82 additions & 5 deletions activefires_pp/geojson_utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) 2022 Adam Dybbroe
# Copyright (c) 2022 - 2023 Adam Dybbroe

# Author(s):

Expand All @@ -22,15 +22,20 @@

"""Geojson utilities."""

import os
import pyproj
import geojson
from geojson import Feature, Point, FeatureCollection, dump
import json
import logging
from trollsift import Parser, globify
import pytz
from datetime import datetime
import numpy as np

LOG = logging.getLogger(__name__)
from activefires_pp.utils import json_serial

logger = logging.getLogger(__name__)


def read_geojson_data(filename):
Expand All @@ -41,9 +46,9 @@ def read_geojson_data(filename):
with open(filename, "r") as fpt:
return geojson.load(fpt)
except json.decoder.JSONDecodeError:
LOG.exception("Geojson file invalid and cannot be read: %s", str(filename))
logger.exception("Geojson file invalid and cannot be read: %s", str(filename))
else:
LOG.error("No valid filename to read: %s", str(filename))
logger.error("No valid filename to read: %s", str(filename))


def get_geojson_files_in_observation_time_order(path, pattern, time_interval):
Expand Down Expand Up @@ -72,6 +77,67 @@ def get_geojson_files_in_observation_time_order(path, pattern, time_interval):
return files.tolist()


def geojson_feature_collection_from_detections(detections, platform_name=None):
"""Create the Geojson feature collection from fire detection data."""
if len(detections) == 0:
raise ValueError("No detections to save!")

# Convert points to GeoJSON
features = []
for idx in range(len(detections)):
starttime = detections.iloc[idx].starttime
endtime = detections.iloc[idx].endtime
mean_granule_time = starttime.to_pydatetime() + (endtime.to_pydatetime() -
starttime.to_pydatetime()) / 2.

prop = {'power': detections.iloc[idx].power,
'tb': detections.iloc[idx].tb,
'confidence': int(detections.iloc[idx].conf),
'observation_time': json_serial(mean_granule_time)
}

try:
prop['tb_celcius'] = detections.iloc[idx].tb_celcius
except AttributeError:
logger.debug("Failed adding the TB in celcius!")
pass
try:
prop['id'] = detections.iloc[idx].detection_id
except AttributeError:
logger.debug("Failed adding the unique detection id!")
pass

if platform_name:
prop['platform_name'] = platform_name
else:
logger.debug("No platform name specified for output")

feat = Feature(
geometry=Point(map(float, [detections.iloc[idx].longitude, detections.iloc[idx].latitude])),
properties=prop)
features.append(feat)

return FeatureCollection(features)


def map_coordinates_in_feature_collection(feature_collection, epsg_str):
"""Map the Point coordinates of all data in Feature Collection."""
outp = pyproj.Proj(init=epsg_str)

mapped_features = []
# Iterate through each feature of the feature collection
for feature in feature_collection['features']:
lon, lat = feature['geometry']['coordinates']
prop = feature['properties']
feature_out = Feature(geometry=Point(map(float, [lon, lat])), properties=prop)
# Project/transform coordinate pairs of each Point
result = outp(lon, lat)
feature_out['geometry']['coordinates'] = [result[0], result[1]]
mapped_features.append(feature_out)

return FeatureCollection(mapped_features)


def store_geojson_alarm(fires_alarms_dir, file_parser, idx, alarm):
"""Store the fire alarm to a geojson file."""
utc = pytz.timezone('utc')
Expand All @@ -82,6 +148,17 @@ def store_geojson_alarm(fires_alarms_dir, file_parser, idx, alarm):
'platform_name': platform_name})
output_filename = fires_alarms_dir / fname
with open(output_filename, 'w') as fpt:
geojson.dump(alarm, fpt)
dump(alarm, fpt)

return output_filename


def store_geojson(output_filename, feature_collection):
"""Store the Geojson feature collection of fire detections on disk."""
path = os.path.dirname(output_filename)
if not os.path.exists(path):
logger.info("Create directory: %s", path)
os.makedirs(path)

with open(output_filename, 'w') as fpt:
dump(feature_collection, fpt)
Loading

0 comments on commit 621ee37

Please sign in to comment.