# 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
TXIDS = [0, 1, 2, 3, 4]


def print_detection_counts(toads, matched_toads):
    print('# Detection counts:')
    print(' - Total number of detections:    ', len(toads))
    print(' - Number of matched detections:  ', len(matched_toads))
    print(' - Number of unmatched detections:', len(toads)-len(matched_toads))
    print()


def print_count_table(matched_toads):
    data = toads_data.toads_array(matched_toads)
    rxids = np.sort(np.unique(data['rxid']))
    txids = np.sort(np.unique(data['txid']))

    rxnum = {rxids[i]: i for i in range(len(rxids))}
    txnum = {txids[i]: i for i in range(len(txids))}

    counts = [[0]*len(rxids) for _ in range(len(txids))]
    for row in data:
        rxid, txid = row['rxid'], row['txid']
        rxidx, txidx = rxnum[rxid], txnum[txid]
        counts[txidx][rxidx] += 1

    headers = ['v TX / RX >'] + list(rxids)
    table = [[txids[i]] + counts[i] for i in range(len(txids))]
    print('# Detection count table:')
    print(tabulate(table, headers=headers))
    # TODO: total row

# 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

TXIDS = [0, 1, 2, 3, 4]


def print_detection_counts(toads, matched_toads):
    print('# Detection counts:')
    print(' - Total number of detections:    ', len(toads))
    print(' - Number of matched detections:  ', len(matched_toads))
    print(' - Number of unmatched detections:', len(toads)-len(matched_toads))
    print()


def print_count_table(matched_toads):
    data = toads_data.toads_array(matched_toads)
    rxids = np.sort(np.unique(data['rxid']))
    txids = np.sort(np.unique(data['txid']))

    rxnum = {rxids[i]: i for i in range(len(rxids))}
    txnum = {txids[i]: i for i in range(len(txids))}

    counts = [[0]*len(rxids) for _ in range(len(txids))]
    for row in data:
        rxid, txid = row['rxid'], row['txid']
        rxidx, txidx = rxnum[rxid], txnum[txid]
        counts[txidx][rxidx] += 1

    headers = ['v TX / RX >'] + list(rxids)
    table = [[txids[i]] + counts[i] for i in range(len(txids))]
    print('# Detection count table:')
    print(tabulate(table, headers=headers))
    # TODO: total row

    print()