Пример #1
0
def _main():
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('card_file',
                        type=argparse.FileType('rb'),
                        default='-',
                        help="card file with positioning signal to match "
                        "against.")
    parser.add_argument('block_id',
                        type=int,
                        help="Block within the card file that contains the"
                        "positioning signal to match against.")
    parser.add_argument('sample_rate',
                        type=metric_float,
                        help="Sample rate that was used to capture the data.")
    parser.add_argument('chip_rate',
                        type=metric_float,
                        help="Estimated chip rate.")
    parser.add_argument('bit_length',
                        type=int,
                        help="Register length of gold code to generate and "
                        "match.")
    parser.add_argument('code_index',
                        nargs='?',
                        type=int,
                        default=0,
                        help="Index of code within the set of Gold codes of "
                        "equal length.")
    parser.add_argument('-p',
                        '--plot',
                        action="store_true",
                        help="Plot best fit.")
    args = parser.parse_args()

    blocks = card_reader(args.card_file)
    block = _find_block(blocks, args.block_id)

    # Synchronize to carrier. It is assumed that a strong carrier is present.
    sps = args.sample_rate / args.chip_rate
    carrier_len = int((2**args.bit_length - 1) * sps)
    sync = DefaultSynchronizer(thresh_coeffs=(100, 0, 0),
                               window=None,
                               block_len=len(block),
                               carrier_len=carrier_len)
    shifted_fft, _ = sync(block)
    assert shifted_fft is not None

    best = search(fft=shifted_fft,
                  initial_chip_rate=args.chip_rate,
                  bit_length=args.bit_length,
                  code_index=args.code_index,
                  sample_rate=args.sample_rate)

    print("Best chip rate: {}".format(best))

    if args.plot:
        _plot(shifted_fft, best, args.bit_length, args.code_index,
              args.sample_rate)
Пример #2
0
def detect_all(cards, settings, detector=DEFAULT_DETECTOR):
    """Detect positioning signal and estimate SOA."""
    toad = []
    for rxid, card in cards.iteritems():
        logging.info(" * Detect: RX #%d (%s)", rxid, card)
        blocks = card_reader(open(card, 'r'))
        det = detector(settings, blocks, rxid=rxid)
        toad.extend([result for detected, result in det if detected])
    return toad
Пример #3
0
def _main():
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('input',
                        type=argparse.FileType('rb'),
                        default='-',
                        help="input data ('-' streams from stdin)")
    parser.add_argument('-o',
                        '--output',
                        type=argparse.FileType('wb'),
                        default='capture.npy',
                        help="Output file (.npy)")
    parser.add_argument('-p',
                        '--plot',
                        action='store_true',
                        help="Plot base template and extracted template.")

    setting_keys = [
        'sample_rate', 'block_size', 'block_history', 'carrier_window',
        'carrier_threshold', 'corr_threshold', 'template'
    ]
    config, args = settings.load_args(parser, setting_keys)

    bin_freq = config.sample_rate / config.block_size
    window = normalize_freq_range(config.carrier_window, bin_freq)

    blocks = card_reader(args.input)
    template = np.load(config.template)

    dsettings = detect.DetectorSettings(
        block_len=config.block_size,
        history_len=config.block_history,
        carrier_len=len(template),
        carrier_thresh=config.carrier_threshold,
        carrier_window=window,
        template=template,
        corr_thresh=config.corr_threshold,
    )
    detections = detect.Detector(dsettings, blocks, yield_data=True)

    full_signal, result = best_detection(detections, MAX_OFFSET)
    signal = extract_template(full_signal, result, len(template))

    np.save(args.output, signal)
    print("Captured template from block #{} (timestamp: {:.6f}): "
          "offset={:+.3f}; corr_ampl={}".format(result.block, result.timestamp,
                                                result.corr_info.offset,
                                                result.corr_info.energy))
    if args.plot:
        plot(signal, template, result.corr_info.offset)
Пример #4
0
def test_card_reader():
    """Basic test for card_reader"""
    stream = io.BytesIO("# Some comments\n"
                        "# more comments\n"
                        "1000.5425 10 r0+Om5==\n"
                        "1000.5442 20 aaaaaa==")
    blocks = list(block_data.card_reader(stream))
    timestamps, indices, data = zip(*blocks)
    chars = [tuple(block_data.complex_to_raw(x)) for x in data]

    assert timestamps == (1000.5425, 1000.5442)
    assert indices == (10, 20)
    assert chars == [(175, 79, 142, 155), (105, 166, 154, 105)]
Пример #5
0
def _main():
    # pylint: disable=too-many-locals

    plot_cmd_descriptions = [
        "  {:14s} {}".format(c,
                             f.__doc__.split('\n')[0])
        for c, f in sorted(_PLOT_COMMAND_STRINGS.items())
    ]

    fig_cmd_descriptions = [
        "  {:14s} {}".format(c,
                             f.__doc__.split('\n')[0])
        for c, f in sorted(_FIGURE_COMMAND_STRINGS.items())
    ]

    description = "{}\n\nplot commands:\n{}\n\nfigure commands:\n{}".format(
        __doc__, '\n'.join(plot_cmd_descriptions),
        '\n'.join(fig_cmd_descriptions))

    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('input',
                        type=argparse.FileType('rb'),
                        default='data.card',
                        help="input data ('-' streams from stdin)")
    parser.add_argument('--raw',
                        dest='raw',
                        action='store_true',
                        help="input data is raw binary data")
    parser.add_argument('-f',
                        '--force_cardet',
                        action='store_true',
                        help="force carrier detection")
    parser.add_argument('-F',
                        '--force_corrdet',
                        action='store_true',
                        help="force correlation peak detection")
    parser.add_argument('-i',
                        '--blocks',
                        type=parse_range_list,
                        help="indices of blocks to plot",
                        default='0-')
    parser.add_argument('-m',
                        '--max',
                        type=int,
                        help="maximum number of blocks",
                        default=20)
    parser.add_argument('-p',
                        '--plot',
                        type=str,
                        help="what to plot",
                        default="overview,time,overlays,spectra,corrs")
    parser.add_argument('--export',
                        type=str,
                        nargs='?',
                        const='plot',
                        help="export plots to .PDF files "
                        "with the given prefix")
    parser.add_argument('--save',
                        type=str,
                        nargs='?',
                        const='signals',
                        help="save detection signals to .npz"
                        "files with the given prefix")

    setting_keys = [
        'sample_rate', 'block_size', 'block_history', 'carrier_window',
        'carrier_threshold', 'corr_threshold', 'template'
    ]
    config, args = load_args(parser, setting_keys)

    window = normalize_freq_range(config.carrier_window,
                                  config.sample_rate / config.block_size)

    if args.raw:
        blocks = block_data.block_reader(args.input, config.block_size,
                                         config.block_history)
    else:
        blocks = block_data.card_reader(args.input)

    cmds = args.plot.split(',')
    template = np.load(config.template)
    settings = detect.DetectorSettings(block_len=config.block_size,
                                       history_len=config.block_history,
                                       carrier_len=len(template),
                                       carrier_thresh=config.carrier_threshold,
                                       carrier_window=window,
                                       template=template,
                                       corr_thresh=config.corr_threshold)
    detector = ForcibleDetector(settings,
                                force_carrier=args.force_cardet,
                                force_corr=args.force_corrdet)

    detections = []
    for timestamp, block_idx, block in blocks:
        if not block_in_range(block_idx, args.blocks):
            continue
        print("Checking block #{}".format(block_idx))
        detection = detector(timestamp, block_idx, block)
        if detection.detected:
            detections.append(detection)
            if len(detections) >= args.max:
                break
        else:
            print("Skipping block #{}".format(block_idx))

    if args.save:
        for detection in detections:
            npz = "{}_{}.npz".format(args.save, detection.result.block)
            carrier_info = dict(detection.result.carrier_info._asdict())
            corr_info = dict(detection.result.corr_info._asdict())
            np.savez(npz,
                     unsynced=detection.unsynced,
                     synced=detection.synced,
                     corr=detection.corr,
                     template=settings.template,
                     carrier_info=carrier_info,
                     corr_info=corr_info)

    if args.export:
        for detection in detections:
            plotter = Plotter(detection, settings, config.sample_rate)
            for cmd in cmds:
                filename = "{}_{}_{}.pdf".format(args.export,
                                                 detection.result.block, cmd)
                print("Exporting", filename)
                fig = Figure()
                FigureCanvas(fig)
                _plot(fig, plotter, cmd)
                fig.set_tight_layout(True)
                fig.savefig(filename)

    if not args.save and not args.export:
        app = qt.QApplication(sys.argv)
        ui = DetectionViewer(detections, cmds, settings, config.sample_rate)
        ui.show()
        app.exec_()