# Path: thrifty/toads_data.py
# class DetectionResult(object):
#     def __init__(self, timestamp, block, soa, carrier_info, corr_info,
#                  rxid=None, txid=None):
#     def serialize(self):
#     def deserialize(cls, string, with_rxid=False, with_txid=False):
# def _load_toads(stream, with_rxid=True, with_txid=True):
# def load_toad(stream):
# def load_toads(stream):
# def toads_array(detections, with_ids=True):
# 
# Path: thrifty/matchmaker.py
# def match_toads(toads, window, min_match=2):
# def load_matches(file_):
# def save_matches(matches, file_):
# def extract_match_matrix(detections, matches, rxids, txids=None):
# def _main():
# 
# Path: thrifty/tdoa_est.py
# SPEED_OF_LIGHT = 2.997e8
# MAX_TDOA = 30e3 / SPEED_OF_LIGHT
# TDOA_DTYPE = {'names': ('rx0', 'rx1', 'tdoa', 'snr', 'model_quality',
#                         'det0_idx', 'det1_idx'),
#               'formats': ('i4', 'i4', 'f8', 'f8', 'f8', 'i4', 'i4')}
# MATRIX_DTYPE = {'names': ('group_id', 'timestamp', 'tx') + TDOA_DTYPE['names'],
#                 'formats': ('i4', 'f8', 'i4') + TDOA_DTYPE['formats']}
# def make_detection_extractor(detections, matches):
#     def extract(rxid0, rxid1, timestamp_start, timestamp_stop):
# def estimate_model_quality(model, detection_pairs):
# def build_model_poly(detection_pairs, beacon_sdoa, nominal_sample_rate, deg=2):
#     def evaluate(det0, det1):
# def build_model_weighted_poly(detection_pairs, beacon_sdoa,
#                               nominal_sample_rate, deg=2):
#     def evaluate(det0, det1):
# def find_nearest_value(list_, value):
# def test_find_nearest_value():
# def build_model_nearest(detection_pairs, beacon_sdoa, nominal_sample_rate):
#     def evaluate(det0, det1):
# def build_model_linear(detection_pairs, beacon_sdoa, nominal_sample_rate):
#     def evaluate(det0, det1):
# def _dist(vector1, vector2):
# def estimate_tdoas(detections, matches, window_size,
#                    beacon_pos, rx_pos, sample_rate,
#                    model_builder=default_model, model_params=None):
#     def _beacon_tdoa(rxid0, rxid1, beaconid):
# def save_tdoa_groups(output, tdoa_groups):
# def load_tdoa_matrix(fname):
# def groups_to_matrix(groups):
# def load_tdoa_groups(fname):
# def load_pos_config(file_):
# def _main():
# 
# Path: thrifty/stat_tools.py
# def is_outlier(points, thresh=3.5):


import argparse
import itertools
import sys
import time
import numpy as np
import matplotlib.pyplot as plt
from tabulate import tabulate
from thrifty import toads_data
from thrifty import matchmaker
from thrifty import tdoa_est
from thrifty import stat_tools
    # print num failures / num outliers matrix
    # incorporate count in variance matrix?


def print_tdoa_variance_matrices(toads, matches):
    rxids = range(4)
    for rx1, rx2 in itertools.combinations(rxids, 2):
        print_tdoa_matrix(toads, matches, rx1, rx2)
    plt.show()


def _main():
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('input',
                        type=argparse.FileType('rb'), default='data.toads',
                        help=".toads data (\'-\' streams from stdin)")
    parser.add_argument('timeval', type=float, nargs='?', default=0,
                        help="time interval to calculate stats (minutes)."
                             "Use 0 to include everything earlier than 'now'.")
    parser.add_argument('--now', type=float,
                        help="fake the current time (timestamp)."
                             "Use a value less than zero to set the timestamp "
                             "relative to the last sample's timestamp.")
    parser.add_argument('--all', action='store_true')

    args = parser.parse_args()


# Path: thrifty/toads_data.py
# class DetectionResult(object):
#     def __init__(self, timestamp, block, soa, carrier_info, corr_info,
#                  rxid=None, txid=None):
#     def serialize(self):
#     def deserialize(cls, string, with_rxid=False, with_txid=False):
# def _load_toads(stream, with_rxid=True, with_txid=True):
# def load_toad(stream):
# def load_toads(stream):
# def toads_array(detections, with_ids=True):
# 
# Path: thrifty/matchmaker.py
# def match_toads(toads, window, min_match=2):
# def load_matches(file_):
# def save_matches(matches, file_):
# def extract_match_matrix(detections, matches, rxids, txids=None):
# def _main():
# 
# Path: thrifty/tdoa_est.py
# SPEED_OF_LIGHT = 2.997e8
# MAX_TDOA = 30e3 / SPEED_OF_LIGHT
# TDOA_DTYPE = {'names': ('rx0', 'rx1', 'tdoa', 'snr', 'model_quality',
#                         'det0_idx', 'det1_idx'),
#               'formats': ('i4', 'i4', 'f8', 'f8', 'f8', 'i4', 'i4')}
# MATRIX_DTYPE = {'names': ('group_id', 'timestamp', 'tx') + TDOA_DTYPE['names'],
#                 'formats': ('i4', 'f8', 'i4') + TDOA_DTYPE['formats']}
# def make_detection_extractor(detections, matches):
#     def extract(rxid0, rxid1, timestamp_start, timestamp_stop):
# def estimate_model_quality(model, detection_pairs):
# def build_model_poly(detection_pairs, beacon_sdoa, nominal_sample_rate, deg=2):
#     def evaluate(det0, det1):
# def build_model_weighted_poly(detection_pairs, beacon_sdoa,
#                               nominal_sample_rate, deg=2):
#     def evaluate(det0, det1):
# def find_nearest_value(list_, value):
# def test_find_nearest_value():
# def build_model_nearest(detection_pairs, beacon_sdoa, nominal_sample_rate):
#     def evaluate(det0, det1):
# def build_model_linear(detection_pairs, beacon_sdoa, nominal_sample_rate):
#     def evaluate(det0, det1):
# def _dist(vector1, vector2):
# def estimate_tdoas(detections, matches, window_size,
#                    beacon_pos, rx_pos, sample_rate,
#                    model_builder=default_model, model_params=None):
#     def _beacon_tdoa(rxid0, rxid1, beaconid):
# def save_tdoa_groups(output, tdoa_groups):
# def load_tdoa_matrix(fname):
# def groups_to_matrix(groups):
# def load_tdoa_groups(fname):
# def load_pos_config(file_):
# def _main():
# 
# Path: thrifty/stat_tools.py
# def is_outlier(points, thresh=3.5):


# Path: scripts/tdoa_matrix.py
import argparse
import itertools
import sys
import time
import numpy as np
import matplotlib.pyplot as plt
from tabulate import tabulate
from thrifty import toads_data
from thrifty import matchmaker
from thrifty import tdoa_est
from thrifty import stat_tools

    # print num failures / num outliers matrix
    # incorporate count in variance matrix?


def print_tdoa_variance_matrices(toads, matches):
    rxids = range(4)
    for rx1, rx2 in itertools.combinations(rxids, 2):
        print_tdoa_matrix(toads, matches, rx1, rx2)
    plt.show()


def _main():
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('input',
                        type=argparse.FileType('rb'), default='data.toads',
                        help=".toads data (\'-\' streams from stdin)")
    parser.add_argument('timeval', type=float, nargs='?', default=0,
                        help="time interval to calculate stats (minutes)."
                             "Use 0 to include everything earlier than 'now'.")
    parser.add_argument('--now', type=float,
                        help="fake the current time (timestamp)."
                             "Use a value less than zero to set the timestamp "
                             "relative to the last sample's timestamp.")
    parser.add_argument('--all', action='store_true')

    args = parser.parse_args()


    toads = toads_data.load_toads(args.input)