# Path: maxdiv/libmaxdiv_wrapper.py
# class detection_t(Structure):
# class pointwise_proposal_params_t(Structure):
# class erph_params_t(Structure):
# class embedding_params_t(Structure):
# class detrending_params_t(Structure):
# class projection_params_t(Structure):
# class preproc_params_t(Structure):
# class maxdiv_params_t(Structure):
# class _LibMaxDiv(object):
#     def __init__(self, library):
#     def _register_func(self, funcName, paramtypes, paramflags, errcheck = None):
#     def _errcheck_compile_pipeline(result, func, args):
# def _search_libmaxdiv():
# def maxdiv(X, method = 'gaussian_cov', num_intervals = 1, proposals = 'dense', **kwargs):
# def maxdiv_exec(X, params, num_intervals = 1):
# def maxdiv_score_intervals(X, params, intervals):
#         X = X.reshape((1, len(X)))
#                     X = preproc.local_linear_regression(X)
#                     X = preproc.deseasonalize_ft(X)
#         X = X.reshape((1, len(X)))
#         X = X.filled(np.nan)
#     X = np.require(X if isSpatioTemporal else X.T, np.float32 if maxdiv_scalar == c_float else np.float64, ['C_CONTIGUOUS'])
#         X = X.reshape((1, len(X)))
#         X = X.filled(np.nan)
#     X = np.require(X if isSpatioTemporal else X.T, np.float32 if maxdiv_scalar == c_float else np.float64, ['C_CONTIGUOUS'])
# 
# Path: maxdiv/maxdiv_util.py
# def IoU(start1, len1, start2, len2):
#     """ Computes the intersection over union of two intervals starting at start1 and start2 with lengths len1 and len2. """
#     intersection = max(0, min(start1 + len1, start2 + len2) - max(start1, start2))
#     return float(intersection) / (len1 + len2 - intersection)


import sys, os.path
import datetime, csv
from ctypes import *
from maxdiv.libmaxdiv_wrapper import maxdiv_params_t, maxdiv_params_p, detection_t, detection_p
from maxdiv.maxdiv_util import IoU
        start_year += YEAR_OFFS - 1
    return datetime.datetime(start_year, 1, 1, 1) + datetime.timedelta(seconds = t * 3600)

def time2ind(time, data_params = None):
    start_year = data_params.firstYear if data_params is not None else YEAR_OFFS
    if start_year < YEAR_OFFS:
        start_year += YEAR_OFFS - 1
    return round((time - datetime.datetime(start_year, 1, 1, 1)).total_seconds() / 3600)

def storm2str(storm):
    startDate, endDate = storm['START_DATE'].date(), storm['END_DATE'].date()
    if startDate == endDate:
        datestr = startDate.strftime('%b %d')
    elif startDate.month == endDate.month:
        datestr = '{}-{}'.format(startDate.strftime('%b %d'), endDate.strftime('%d'))
    else:
        datestr = '{} - {}'.format(startDate.strftime('%b %d'), endDate.strftime('%b %d'))
    return '{} ({})'.format(storm['NAME'], datestr)

def printCoastDatDetection(detection, data_params):
    print('TIMEFRAME: {} - {}'.format(ind2time(detection.range_start[0], data_params), ind2time(detection.range_end[0] - 1, data_params)))
    print('LOCATION:  {start[0]:.2f} N, {start[1]:.2f} E - {end[0]:.2f} N, {end[1]:.2f} E'.format(
        start = ind2latlon(detection.range_start[2], detection.range_start[1], data_params, 'topleft'),
        end   = ind2latlon(detection.range_end[2] - 1, detection.range_end[1] - 1, data_params, 'bottomright')
    ))
    print('SCORE:     {}'.format(detection.score))

def printCoastDatDetections(detections, data_params):
    matchedDetections, totalMatches, uniqueMatches = matchDetectionsWithStorms(detections, data_params)
    for i, (detection, storm) in enumerate(matchedDetections):

# Path: maxdiv/libmaxdiv_wrapper.py
# class detection_t(Structure):
# class pointwise_proposal_params_t(Structure):
# class erph_params_t(Structure):
# class embedding_params_t(Structure):
# class detrending_params_t(Structure):
# class projection_params_t(Structure):
# class preproc_params_t(Structure):
# class maxdiv_params_t(Structure):
# class _LibMaxDiv(object):
#     def __init__(self, library):
#     def _register_func(self, funcName, paramtypes, paramflags, errcheck = None):
#     def _errcheck_compile_pipeline(result, func, args):
# def _search_libmaxdiv():
# def maxdiv(X, method = 'gaussian_cov', num_intervals = 1, proposals = 'dense', **kwargs):
# def maxdiv_exec(X, params, num_intervals = 1):
# def maxdiv_score_intervals(X, params, intervals):
#         X = X.reshape((1, len(X)))
#                     X = preproc.local_linear_regression(X)
#                     X = preproc.deseasonalize_ft(X)
#         X = X.reshape((1, len(X)))
#         X = X.filled(np.nan)
#     X = np.require(X if isSpatioTemporal else X.T, np.float32 if maxdiv_scalar == c_float else np.float64, ['C_CONTIGUOUS'])
#         X = X.reshape((1, len(X)))
#         X = X.filled(np.nan)
#     X = np.require(X if isSpatioTemporal else X.T, np.float32 if maxdiv_scalar == c_float else np.float64, ['C_CONTIGUOUS'])
# 
# Path: maxdiv/maxdiv_util.py
# def IoU(start1, len1, start2, len2):
#     """ Computes the intersection over union of two intervals starting at start1 and start2 with lengths len1 and len2. """
#     intersection = max(0, min(start1 + len1, start2 + len2) - max(start1, start2))
#     return float(intersection) / (len1 + len2 - intersection)


# Path: experiments/coastdat/maxdiv_coastdat_utils.py
import sys, os.path
import datetime, csv
from ctypes import *
from maxdiv.libmaxdiv_wrapper import maxdiv_params_t, maxdiv_params_p, detection_t, detection_p
from maxdiv.maxdiv_util import IoU

        start_year += YEAR_OFFS - 1
    return datetime.datetime(start_year, 1, 1, 1) + datetime.timedelta(seconds = t * 3600)

def time2ind(time, data_params = None):
    start_year = data_params.firstYear if data_params is not None else YEAR_OFFS
    if start_year < YEAR_OFFS:
        start_year += YEAR_OFFS - 1
    return round((time - datetime.datetime(start_year, 1, 1, 1)).total_seconds() / 3600)

def storm2str(storm):
    startDate, endDate = storm['START_DATE'].date(), storm['END_DATE'].date()
    if startDate == endDate:
        datestr = startDate.strftime('%b %d')
    elif startDate.month == endDate.month:
        datestr = '{}-{}'.format(startDate.strftime('%b %d'), endDate.strftime('%d'))
    else:
        datestr = '{} - {}'.format(startDate.strftime('%b %d'), endDate.strftime('%b %d'))
    return '{} ({})'.format(storm['NAME'], datestr)

def printCoastDatDetection(detection, data_params):
    print('TIMEFRAME: {} - {}'.format(ind2time(detection.range_start[0], data_params), ind2time(detection.range_end[0] - 1, data_params)))
    print('LOCATION:  {start[0]:.2f} N, {start[1]:.2f} E - {end[0]:.2f} N, {end[1]:.2f} E'.format(
        start = ind2latlon(detection.range_start[2], detection.range_start[1], data_params, 'topleft'),
        end   = ind2latlon(detection.range_end[2] - 1, detection.range_end[1] - 1, data_params, 'bottomright')
    ))
    print('SCORE:     {}'.format(detection.score))

def printCoastDatDetections(detections, data_params):
    matchedDetections, totalMatches, uniqueMatches = matchDetectionsWithStorms(detections, data_params)
    for i, (detection, storm) in enumerate(matchedDetections):

        print('#{}'.format(i))