Exemplo n.º 1
0
def main():
    print "Starting main()\n"
    u.setup()
    u.calibrate()
    a.hold_cube_and_deliver_ambulance()
    a.hold_cube_and_get_prism()
    u.sd()
Exemplo n.º 2
0
def main():
    print "Starting main()\n"
    u.setup()
    u.calibrate(
    )  # You only need to include this command if you want the tophats to sense better at the cost of speed.
    a.get_gas_valve()
    print "Finished main\n"
    u.shutdown(86)
Exemplo n.º 3
0
def main():
    print "Starting main()\n"
    u.setup()
    u.calibrate()
    a.get_crates()
    a.put_crates_in_correct_zone()
    a.get_botguy()
    a.put_botguy_on_side()
    u.shutdown()
def main():
    """
    Generate image files for the documentation
    """
    utl.calibrate(False)
    undistort(False)
    edge_detect(False)
    transform(False)
    identify_line(False)
    lane_line(True)
def main():
    """
    Displays processed images on screen to verify they the image pipeline
    """
    utl.calibrate(False)
    undistort(False)
    edge_detect(False)
    transform(False)
    identify_line(False)
    lane_line(True)    
Exemplo n.º 6
0
def main():
    print "Starting main()\n"
    u.setup()
    u.calibrate()
    a.get_ambulance()
    a.get_blocks()
    a.deliver_ambulance_and_blocks()
    #a.get_firefighters()
    #a.deliver_firefighters()
    u.shutdown()
Exemplo n.º 7
0
def run_gyro():
    print "Starting run_gyro()"
    u.calibrate()
    msleep(3000)
    i = 0
    while i < 4:
        turn_gyro(-90)
        print str(c.ROBOT_ANGLE * c.WALLAGREES_TO_DEGREES_RATE)
        msleep(1000)
        i += 1
    print str(c.ROBOT_ANGLE * c.WALLAGREES_TO_DEGREES_RATE)
Exemplo n.º 8
0
def main():
    print "Starting main()\n"
    u.setup()
    u.calibrate(
    )  # You only need to include this command if you want the cliffs to sense better at the cost of speed.
    a.get_left_coupler()
    a.go_to_magnets()
    u.reset_roomba()
    a.do_magnets()
    a.deliver_left_coupler()
    print "Finished main\n"
    u.shutdown()
Exemplo n.º 9
0
def fit_sp(cfg, sp):

    bl_no = cfg.bls[sp['blid']]

    t0 = cfg.ap * sp['apid']
    t1 = t0 + sp['nap'] * cfg.ap + cfg.t_extra
    print('blid %d, %s ...' % (sp['blid'], cfg.bl_no2name[bl_no]))
    h, bufs, a2r = cfg.load_seg(bl_no, t0, t1)

    s0, s1 = cfg.bl_no2stns[bl_no]

    _, as0, _ = cfg.load_seg((s0 + 1) * 257, t0, t1)
    _, as1, _ = cfg.load_seg((s1 + 1) * 257, t0, t1)

    bufs = utils.make_norm(bufs, as0, as1)

    _nap = int((t1 - t0) / cfg.ap + 0.5)
    buf = np.zeros((_nap, cfg.nfreq, cfg.nchan), dtype=np.complex64)
    for pol in cfg.pols:
        buf += utils.calibrate(cfg, bufs[pol], bl_no, pol)

# load the first nap aps after dedispersion
    buf = utils.dedispersion(cfg, buf, sp['dm'])[:sp['nap'], :, :]

    buf = np.sum(buf, axis=0)
    fmin = cfg.freqs[0]
    assert fmin == np.min(cfg.freqs)
    fmax = cfg.freqs[-1] + cfg.bw
    bw_mc = fmax - fmin  # m stands for multi
    df_mc = cfg.bw / cfg.nchan
    nchan_mc = int(bw_mc / df_mc + 0.5)
    arr = np.zeros(nchan_mc, dtype=np.complex128)
    mids = []
    for fid in range(cfg.nfreq):
        for vid in range(1, cfg.nchan):
            f = cfg.freqs[fid] + vid * df_mc
            mid = int((f - fmin) / df_mc + 0.5)
            assert (not mid in mids)
            mids.append(mid)
            arr[mid] = buf[fid, vid]
    tau, amp = utils.fine_fit(arr, df_mc)

    def mk_comb(arr):
        nvsum = 128
        return np.sum(arr.reshape((-1, nvsum)), axis=1)

    nap = sp['nap']
    nfreq = cfg.nfreq
    nchan = cfg.nchan
    npol = len(cfg.pols)

    snr = amp * np.sqrt(2 * cfg.bw * cfg.ap /
                        (nap * nfreq * npol)) / (nchan - 1)
    #    snr     =   amp * np.sqrt(2 * bw_mc * cfg.ap / (nap)) / (nchan_mc - 1)
    tau_sig = 1. / (2. * np.pi * np.std(cfg.freqs) * snr)
    return arr, tau, snr, tau_sig
Exemplo n.º 10
0
def gen_fine_bl(cfg, bl_no, t0, t1):
    
    h, bufs, a2r    =   cfg.load_seg(bl_no, t0, t1)

    s0, s1  =   cfg.bl_no2stns[bl_no]

    _, as0, _    =   cfg.load_seg((s0+1)*257, t0, t1)
    _, as1, _    =   cfg.load_seg((s1+1)*257, t0, t1)

    bufs    =   utils.make_norm(bufs, as0, as1)

    nap =   int((t1 - t0) / cfg.ap + 0.5)
    buf =   np.zeros((nap, cfg.nfreq, cfg.nchan), dtype = np.complex64)
    for pol in cfg.pols:
        buf +=  utils.calibrate(cfg, bufs[pol], bl_no, pol)

    nap_e   =   calc_effective_ap(buf)
    
    buf     =   np.sum(buf, axis = 0)
    fmin    =   cfg.freqs[0]
    assert fmin == np.min(cfg.freqs)
    fmax    =   cfg.freqs[-1] + cfg.bw
    bw_mc   =   fmax - fmin # m stands for multi
    df_mc   =   cfg.bw / cfg.nchan
    nchan_mc=   int(bw_mc / df_mc + 0.5)
    arr =   np.zeros(nchan_mc, dtype=np.complex128)
    mids    =   []
    for fid in range(cfg.nfreq):
        for vid in range(1, cfg.nchan):
            f   =   cfg.freqs[fid] + vid * df_mc
            mid =   int((f - fmin) / df_mc + 0.5)
            assert (not mid in mids)
            mids.append(mid)
            arr[mid]    =   buf[fid, vid]
    tau, amp    =   utils.fine_fit(arr, df_mc) 

    snr =   amp * np.sqrt(2 * cfg.bw * cfg.ap / (nap_e * cfg.nfreq * len(cfg.pols))) / (cfg.nchan - 1)

    tau_sig =   1. / (2. * np.pi * np.std(cfg.freqs) * snr)

    bl_name =   cfg.bl_no2name[bl_no]
    xf  =   np.arange(nchan_mc) * df_mc
    dphs    =   2. * np.pi * xf * tau
    utils.plot_fine_fit(arr, df_mc, 'mc_raw_No%04d_%s' % \
            (cfg.scan_no, bl_name))
    arr1    =   arr * np.exp(-1j * dphs)
    utils.plot_fine_fit(arr1, df_mc, 'mc_fit_No%04d_%s' % \
            (cfg.scan_no, bl_name))

    d   =   {}
    d['snr']    =   snr
    d['tau']    =   tau
    d['tau_sig']    =   tau_sig
    
    return d
Exemplo n.º 11
0
def main():
    print "Starting main()\n"
    u.setup()
    u.calibrate()
    a.only_first_three()
    # m.backwards(1300)
    m.turn_right()
    m.backwards(4500)
    u.sd()


    a.get_low_poms_cheeky()
    a.get_frisbee()
    a.get_mid_poms()
    a.get_high_poms_cheeky()
    a.get_farther_high_poms() 
    a.get_farther_mid_poms()
    a.get_farther_low_poms()
    print "Finished main\n"
    u.shutdown(86)
Exemplo n.º 12
0
def fit_2d(cfg, t0, t1, bl_no):
    
    t11     =   t1 + cfg.t_extra
    if t11 > cfg.dur:
        t11 =   cfg.dur
        t11 =   int(t11 / cfg.tsum) * cfg.tsum
#    print('proc %d, load_seg ...' % (rank))
    heads, bufs, arr2recs   =   cfg.load_seg(bl_no, t0, t11)
#    print('proc %d, load_seg done!' % (rank))
    if bufs == {}:
        return {}

    nap1 =   int((t11 - t0) / cfg.ap + 0.5)
    buf =   np.zeros((nap1, cfg.nfreq, cfg.nchan), dtype = np.complex64)
    for pol in cfg.pols:
        buf +=  utils.calibrate(cfg, bufs[pol], bl_no, pol)
    buf =   utils.dedispersion(cfg, buf, cfg.dm)

    nsb =   cfg.nchan << 4
    nmb =   cfg.nmb
    
    s   =   np.zeros((nap1, nmb, nsb), dtype = np.complex64) 
    for fid in range(cfg.nfreq):
        id_mb   =   cfg.id_mbs[fid]
        if cfg.sbs[fid] == 'U':
            s[:, id_mb, 1:cfg.nchan]    =   buf[:, fid, 1:cfg.nchan]
        else:
            s[:, id_mb, -(cfg.nchan - 1): ] =   buf[:, fid, :-1]
    
    r   =   np.fft.fft2(s, axes = (-1, -2)) # defaults to the last 2 axes
    r   =   np.fft.fftshift(r, axes = (-1, -2)) # last 2 axes
    
# perform nsum:

    nap =   int((t1 - t0) / cfg.ap + 0.5)
    ds  =   {}
    for nsum in cfg.nsums:
        ds[nsum]    =   nsum_and_find_max(cfg, r[0:nap, :, :], nsum)
        hnsum   =   nsum // 2
        if t1 + cfg.ap * hnsum <= t11:
            ds[nsum+1]  =   nsum_and_find_max(cfg, r[hnsum:nap+hnsum, :, :], nsum)
        else:
            ds[nsum+1]  =   nsum_and_find_max(cfg, r[hnsum:nap-hnsum, :, :], nsum)
    return ds
Exemplo n.º 13
0
def test_2d():

    scan_no =   37
    cfg =   utils.gen_cfg_el060(scan_no)

    cfg.tsum    =   cfg.ap # set to 1 ap
    s1  =   cfg.stn2id['IR']
#    s2  =   cfg.stn2id['SR']
    s2  =   cfg.stn2id['MC']
    bl_no   =   (s1+1) * 256 + (s2+1) 
    t0, t1  =   25., 55.
    t0  =   int(t0 / cfg.tsum) * cfg.tsum
    t1  =   int(t1 / cfg.tsum) * cfg.tsum
    t11 =   t1

    heads, bufs, arr2recs   =   cfg.load_seg(bl_no, t0, t1)
    if bufs == {}:
        return {}

    nap1 =   int((t11 - t0) / cfg.ap + 0.5)

    buf =   np.zeros((nap1, cfg.nfreq, cfg.nchan), dtype = np.complex64)
    for pol in cfg.pols:
        buf +=  bufs[pol]
    utils.plot_if(cfg, np.sum(buf, axis = 0), 'raw')
 
    buf =   np.zeros((nap1, cfg.nfreq, cfg.nchan), dtype = np.complex64)
    for pol in cfg.pols:
        buf +=  utils.calibrate(cfg, bufs[pol], bl_no, pol)

    utils.plot_if(cfg, np.sum(buf, axis = 0), 'cal')

    nsb =   cfg.nchan << 4
    nmb =   cfg.nmb
    
    s   =   np.zeros((nap1, nmb, nsb), dtype = np.complex64) 
    for fid in range(cfg.nfreq):
        id_mb   =   cfg.id_mbs[fid]
        if cfg.sbs[fid] == 'U':
            s[:, id_mb, 1:cfg.nchan]    =   buf[:, fid, 1:cfg.nchan]
        else:
            s[:, id_mb, -(cfg.nchan - 1): ] =   buf[:, fid, :-1]
    
    r   =   np.fft.fft2(s, axes = (-1, -2)) # defaults to the last 2 axes
    r   =   np.fft.fftshift(r, axes = (-1, -2)) # last 2 axes
    
    nap =   int((t1 - t0) / cfg.ap + 0.5)

    r   =   np.sum(r, axis = 0)[np.newaxis, :, :]

    imbds, isbds, mags, mag0s =   test_find_max_2d(cfg, r)
    print(imbds)
    print(isbds)
    print(mags)
    print(mag0s)

    mb_res  =   1. / cfg.df_mb / nmb
    sb_res  =   1. / (cfg.bw / cfg.nchan) / nsb
    mb_range    =   mb_res * np.arange(-nmb // 2, nmb // 2, dtype = float)
    sb_range    =   sb_res * np.arange(-nsb // 2, nsb // 2, dtype = float)

    nap1    =   1
    
    for i in range(nap1):

        sbd =   sb_range[isbds[i]]
        mbd =   mb_range[imbds[i]]

        print('sbd, mbd: ', sbd, mbd)
 
        buf =   rot_if_sbd_mbd(cfg, np.sum(buf, axis = 0), sbd, mbd)
        utils.plot_if(cfg, buf, 'fit_ap%d' % (i))

    return
Exemplo n.º 14
0
def test():

#    scan_no =   37
#    cfg =   utils.gen_cfg_el060(scan_no)

    scan_no =   1
    cfg =   utils.gen_cfg_aov025(scan_no)

    cfg.tsum    =   cfg.ap # set to 1 ap
    s1  =   cfg.stn2id['SH']
    s2  =   cfg.stn2id['T6']
    bl_no   =   (s1+1) * 256 + (s2+1) 
    t0, t1  =   25., 55.
#    t0, t1  =   110, 150.
    t0  =   int(t0 / cfg.tsum) * cfg.tsum
    t1  =   int(t1 / cfg.tsum) * cfg.tsum
    t11 =   t1

    heads, bufs, arr2recs   =   cfg.load_seg(bl_no, t0, t1)
    if bufs == {}:
        return {}

    nap1 =   int((t11 - t0) / cfg.ap + 0.5)

    buf =   np.zeros((nap1, cfg.nfreq, cfg.nchan), dtype = np.complex64)
    for pol in cfg.pols:
        buf +=  bufs[pol]
    utils.plot_if(cfg, np.sum(buf, axis = 0), 'raw')
 
    buf =   np.zeros((nap1, cfg.nfreq, cfg.nchan), dtype = np.complex64)
    for pol in cfg.pols:
        buf +=  utils.calibrate(cfg, bufs[pol], bl_no, pol)
    utils.plot_if(cfg, np.sum(buf, axis = 0), 'cal')

    nap =   int((t1 - t0) / cfg.ap + 0.5)
    s   =   np.zeros((nap, cfg.nmc), dtype = np.complex64) 
    for fid in range(cfg.nfreq):
        id_mc   =   cfg.id_mcs[fid]
        s[:, id_mc+1:id_mc+cfg.nchan] =   buf[:nap, fid, 1:]
    
    r   =   np.fft.fft(s, n = cfg.nmc * cfg.npadding, axis = -1)
   
    r   =   np.sum(r, axis = 0)[np.newaxis, :]

    imbds, isbds, mags, mag0s =   test_find_max(cfg, r)
    print(imbds)
    print(isbds)
    print(mags)
    print(mag0s)

    nap1    =   1
    
    s   =   np.sum(s, axis = 0)
    for i in range(nap1):

        mcd =   cfg.tau_mc[imbds[i]]

        print('mcd: %.3f ns' % (mcd * 1E9))
 
        s1  =   s * np.exp(-1j * 2 * np.pi * mcd * np.arange(cfg.nmc) * cfg.bw / cfg.nchan)

        buf1    =   []
        for fid in range(cfg.nfreq):
            id_mc   =   cfg.id_mcs[fid]
            buf1.append(s1[id_mc:id_mc+cfg.nchan])
        buf1    =   np.array(buf1)
        
        utils.plot_if(cfg, buf1, 'fit_ap%d' % (i))

    return
Exemplo n.º 15
0
def fit(cfg, t0, t1, bl_no):
    
    t11     =   t1 + cfg.t_extra
    if t11 > cfg.dur:
        t11 =   cfg.dur
        t11 =   int(t11 / cfg.tsum) * cfg.tsum
#    print('proc %d, load_seg ...' % (rank))
    t_load  =   time.time()
    heads, bufs, arr2recs   =   cfg.load_seg(bl_no, t0, t11)
    t_load  =   time.time() - t_load 
        
#    print('proc %d, load_seg done!' % (rank))
    if bufs == {}:
        return {}

    t_cal   =   time.time()
    nap1 =   int((t11 - t0) / cfg.ap + 0.5)
    buf =   np.zeros((nap1, cfg.nfreq, cfg.nchan), dtype = np.complex64)
    for pol in cfg.pols:
        buf +=  utils.calibrate(cfg, bufs[pol], bl_no, pol)
    buf[:, :, 0]    =   0.0 # set DC to zero
    t_cal   =   time.time() - t_cal
    nap =   int((t1 - t0) / cfg.ap + 0.5)

    ds_dms  =   {}
    t_ded   =   0.0
    t_set   =   0.0
    t_fft   =   0.0
    t_nsum  =   0.0
    _buf    =   buf.copy()
    for dm in cfg.dms:
        
        t_bm    =   time.time()
        buf =   utils.dedispersion(cfg, _buf, dm)
        t_ded    +=  (time.time() - t_bm) 

        t_bm    =   time.time()
        s   =   np.zeros((nap1, cfg.nmc), dtype = np.complex64) 
        for fid in range(cfg.nfreq):
            id_mc   =   cfg.id_mcs[fid]
            s[:, id_mc:id_mc+cfg.nchan] =   buf[:, fid, :]
        t_set   +=  (time.time() - t_bm)
    
        t_bm    =   time.time()
        r   =   np.fft.fft(s, n = cfg.nmc * cfg.npadding, axis = -1)
        t_fft   +=  (time.time() - t_bm)
    
# perform nsum:
        
        t_bm    =   time.time()
        ds  =   {}
        for nsum in cfg.nsums:
            ds[nsum]    =   nsum_and_find_max(cfg, r[0:nap, :], nsum)
            hnsum   =   nsum // 2
            if t1 + cfg.ap * hnsum <= t11:
                ds[nsum+1]  =   nsum_and_find_max(cfg, r[hnsum:nap+hnsum, :], nsum)
            else:
                ds[nsum+1]  =   nsum_and_find_max(cfg, r[hnsum:nap-hnsum, :], nsum)
        ds_dms[dm]  =   ds
        t_nsum  +=  (time.time() - t_bm)
    
    if cfg.bm:
        print('t_load:  %f' % (t_load))
        print('t_cal:   %f' % (t_cal))
        print('t_ded:   %f' % (t_ded))
        print('t_set:   %f' % (t_set))
        print('t_fft:   %f' % (t_fft))
        print('t_nsum:  %f' % (t_nsum))

        return [t_load, t_cal, t_ded, t_set, t_fft, t_nsum]

    return ds_dms
Exemplo n.º 16
0
def fit_torch(cfg, t0, t1, bl_no):
    
    t11     =   t1 + cfg.t_extra
    if t11 > cfg.dur:
        t11 =   cfg.dur
        t11 =   int(t11 / cfg.tsum) * cfg.tsum
#    print('proc %d, load_seg ...' % (rank))
    t_load  =   time.time()
    heads, bufs, arr2recs   =   cfg.load_seg(bl_no, t0, t11)
    t_load  =   time.time() - t_load 
        
#    print('proc %d, load_seg done!' % (rank))
    if bufs == {}:
        return {}

    t_cal   =   time.time()
    nap1 =   int((t11 - t0) / cfg.ap + 0.5)
    buf =   np.zeros((nap1, cfg.nfreq, cfg.nchan), dtype = np.complex64)
    for pol in cfg.pols:
        buf +=  utils.calibrate(cfg, bufs[pol], bl_no, pol)
    buf[:, :, 0]    =   0.0 # set DC to zero
    t_cal   =   time.time() - t_cal
    nap =   int((t1 - t0) / cfg.ap + 0.5)

#    buf_1   =   torch.from_numpy(buf).cuda(device = cfg.dev).reshape((nap1, cfg.nfreq, cfg.nchan))

#    print('buf h2d, size %.1f MB...' % (buf.size * 8 / 1E6))
    buf_d   =   torch.from_numpy(buf).cuda(device = cfg.dev).reshape((nap1, cfg.nfreq, cfg.nchan))
#    print('allocate s_d...')

    ds_dms  =   {}
    t_ded   =   0.0
    t_set   =   0.0
    t_fft   =   0.0
    t_nsum  =   0.0
    for dm in cfg.dms:

        s_d     =   torch.zeros((nap1, cfg.nmc), dtype=torch.complex64, device=cfg.dev)

#        print('dm %.3f' % (dm))
        t_bm    =   time.time()
        s_d[:, :]   =   0.0
        for fid in range(cfg.nfreq):
            id_mc   =   cfg.id_mcs[fid]
# never uncomment
#            s_d[:, id_mc:id_mc+cfg.nchan]    =   \
#                    buf_d[:, fid, :]
            for vid in range(cfg.nchan):
                n_dm    =   cfg.tb[dm][fid, vid]

                s_d[0:nap1 - n_dm, id_mc+vid] =   \
                    buf_d[n_dm:nap1, fid, vid]

#                s_d[:, id_mc+vid]    =   \
#                    buf_d[:, fid, vid].roll(-n_dm, 0)
        torch.cuda.synchronize()
        t_ded   +=  time.time() - t_bm

#        print('fft ...')
        t_bm    =   time.time()
        r_d     =   torch.fft.fft(s_d, n = cfg.nmc * cfg.npadding, dim = 1)
        torch.cuda.synchronize()
        t_fft   +=  (time.time() - t_bm)

        s_d =   []
    
# perform nsum:
        
#        print('nsum ...')
        t_bm    =   time.time()
        ds  =   {}
        for nsum in cfg.nsums:
            ds[nsum]    =   nsum_and_find_max_torch(cfg, r_d[0:nap, :], nsum)
            hnsum   =   nsum // 2
            if t1 + cfg.ap * hnsum <= t11:
                ds[nsum+1]  =   nsum_and_find_max_torch(cfg, r_d[hnsum:nap+hnsum, :], nsum)
            else:
                ds[nsum+1]  =   nsum_and_find_max_torch(cfg, r_d[hnsum:nap-hnsum, :], nsum)
        ds_dms[dm]  =   ds
        torch.cuda.synchronize()
        t_nsum  +=  (time.time() - t_bm)

        r_d =   []

    buf_d   =   []

#    torch.cuda.empty_cache()
    
    if cfg.bm:
        print()
        print('t_load:  %f' % (t_load))
        print('t_cal:   %f' % (t_cal))
        print('t_ded:   %f' % (t_ded))
        print('t_set:   %f' % (t_set))
        print('t_fft:   %f' % (t_fft))
        print('t_nsum:  %f' % (t_nsum))

        return [t_load, t_cal, t_ded, t_set, t_fft, t_nsum]


    return ds_dms
Exemplo n.º 17
0
def predict(args, show, save, bland_altman):

    report = pd.DataFrame()
    now = datetime.now()
    test = []
    for arg in args:
        test.append(arg)

    calibrated, model, (X, Y) = calibrate(test)

    feature_data = pd.read_csv("saved_data/features.csv")
    feature_data.columns = [i for i in range(len(feature_data.columns))]
    p_column = len(feature_data.columns) - 1
    spo2_column = p_column - 1
    r_column = spo2_column - 1
    ref_r_column = r_column - 1

    test_df = feature_data[feature_data[p_column].isin(
        test)].iloc[:, [ref_r_column, spo2_column, p_column]]
    mae = []
    for i in range(len(test)):
        p = test[i]
        c = int(calibrated[i])
        predictions = []

        m, c = model[model[0] == c][1].values, model[model[0] == c][2].values

        max_x = 0
        for x in test_df[test_df[p_column] == p][ref_r_column]:
            if x > max_x:
                max_x = x
            predictions.append(m * x + c)

        predictions = np.asarray(predictions)
        predictions[np.where(predictions > 100)] = 100
        predictions = predictions.reshape((-1, ))
        truth = np.asarray(
            test_df[test_df[p_column] == p][spo2_column]).reshape((-1, ))
        running_mae = mean_absolute_error(truth, predictions)
        mae.append(running_mae)

        report = pd.concat([report, make_report(truth, predictions, p)],
                           axis=0)

        if not (bland_altman):
            fig, ax = plt.subplots(1, 1, figsize=[8, 8])
            plt.title("Patient {}".format(p))
            ax.plot(X, Y)
            ax.scatter(test_df[test_df[p_column] == p][ref_r_column],
                       test_df[test_df[p_column] == p][spo2_column])
            plt.text(max_x,
                     np.max(predictions) + 10,
                     "mae = {:.2f}".format(running_mae),
                     size=12,
                     bbox=dict(boxstyle="round",
                               ec=(0, 0, 0),
                               fc=(1., 0.8, 0.8)))

        elif bland_altman:
            fig, ax = plt.subplots(1, 2, figsize=[16, 8])
            fig.suptitle("Patient {}".format(p))
            ax[0].plot(X, Y)
            ax[0].scatter(test_df[test_df[p_column] == p][ref_r_column],
                          test_df[test_df[p_column] == p][spo2_column])
            ax[0].text(max_x,
                       np.max(predictions) + 10,
                       "mae = {:.2f}".format(running_mae),
                       size=12,
                       bbox=dict(boxstyle="round",
                                 ec=(0, 0, 0),
                                 fc=(1., 0.8, 0.8)))

            diff_bland = truth - np.asarray(predictions)
            mean = (np.asarray(test_df[test_df[p_column] == p][spo2_column]) +
                    predictions) / 2
            md = np.mean(diff_bland)
            std = np.std(diff_bland)
            plt.scatter(mean, diff_bland)
            ax[1].axhline(md, color='black', linestyle='--', linewidth=4)
            ax[1].axhline(md + 1.96 * std,
                          color='gray',
                          linestyle='--',
                          linewidth=4)
            ax[1].axhline(md - 1.96 * std,
                          color='gray',
                          linestyle='--',
                          linewidth=4)
            ax[1].axhline(md + 2, color='red', linestyle='--', linewidth=4)
            ax[1].axhline(md - 2, color='red', linestyle='--', linewidth=4)
            ax[1].set_xlabel("(y + y')/2", fontsize=12)
            ax[1].set_ylabel("y - y'", fontsize=12)

        if save:
            if not (os.path.exists("vizualize_results")):
                os.mkdir("vizualize_results")
            date_time = now.strftime("%m_%d_%Y_%H_%M_%S")
            path_now = "vizualize_results/" + date_time
            if not (os.path.exists(path_now)):
                os.mkdir(path_now)
            plt.savefig(path_now + "/Patient {}.png".format(p))

        if show:
            plt.show()
    if save:
        report.to_csv(path_now + "/report.csv".format(p), index=False)
Exemplo n.º 18
0
import pickle

from utils import show, save, calibrate, interpolate, adaptive_median

with open("potato.pickle", "rb") as f:
    image = pickle.load(f, encoding="latin1")

image = calibrate(image)  # Compensate for fixed-pattern noise
image = adaptive_median(image)  # Reduce gaussian noise and remove impulses
image = interpolate(image, 3,
                    mode="median")  # downsample to fit 'normal' y-scale

show(image, r=(0, 1.2))
Exemplo n.º 19
0
    cv2.putText(blend_on_road,
                'Curvature radius: {:.02f}m'.format(mean_curvature_meter),
                (60, 60), font, 1, (255, 255, 255), 2)
    cv2.putText(blend_on_road,
                'Offset from center: {:.02f}m'.format(offset_meter), (60, 90),
                font, 1, (255, 255, 255), 2)

    processed_frames += 1

    return blend_on_road


if __name__ == '__main__':

    # step 1: calibrate the camera
    mtx, dist = calibrate('camera_cal')
    mode = "video"
    processed_frames = 0
    line_lt, line_rt = Line(buffer_len=10), Line(buffer_len=10)

    if mode == "image":
        for test_img in glob.glob('test_images/*.jpg'):
            img = mpimg.imread(test_img)
            img_out = process_pipeline(img, True)
            plt.imshow(img_out)
            plt.show()

    elif mode == "video":
        selector = 'project'
        clip = VideoFileClip(
            '{}_video.mp4'.format(selector)).fl_image(process_pipeline)
Exemplo n.º 20
0
# -*- coding: utf-8 -*-

import os
import cv2
import utils
import matplotlib.pyplot as plt
import numpy as np

#script mainly use for drawing the demo picture

cal_imgs = utils.get_images_by_dir('camera_cal')
object_points,img_points = utils.calibrate(cal_imgs,grid=(9,6))

#test_imgs = utils.get_images_by_dir('test_images')
test_imgs = utils.get_images_by_dir('new_test')

undistorted = []
for img in test_imgs:
    img = utils.cal_undistort(img,object_points,img_points)
    undistorted.append(img)

trans_on_test=[]
for img in undistorted:
    src = np.float32([[(203, 720), (585, 460), (695, 460), (1127, 720)]])
    dst = np.float32([[(320, 720), (320, 0), (960, 0), (960, 720)]])
    M = cv2.getPerspectiveTransform(src, dst)
    trans = cv2.warpPerspective(img, M, img.shape[1::-1], flags=cv2.INTER_LINEAR)
    trans_on_test.append(trans)
    
thresh = []
binary_wrapeds = []
Exemplo n.º 21
0
            full_path = os.path.join(directory, calibration)

            if is_iterative:
                stereo_reproj_err, stereo_recon_err, tracked_reproj_err, \
                  tracked_recon_err, elapsed_time, mean_frame_grabbing_time, stereo_params = \
                    iterative_calibrate(left_point_detector,
                                        right_point_detector,
                                        full_path,
                                        iterative_image_file,
                                        iterative_iterations,
                                        pattern)
            else:
               stereo_reproj_err, stereo_recon_err, tracked_reproj_err, \
                  tracked_recon_err, elapsed_time, mean_frame_grabbing_time, stereo_params = \
                    calibrate(left_point_detector,
                              right_point_detector,
                              full_path)

            LOGGER.info(f"Stereo Reprojection Error: {stereo_reproj_err}")
            LOGGER.info(f"Stereo Reconstruction Error: {stereo_recon_err}")
            LOGGER.info(f"Tracked Reprojection Error: {tracked_reproj_err}")
            LOGGER.info(f"Tracked Reconstruction Error: {tracked_recon_err}")
            LOGGER.info(f"Calibration took: {elapsed_time} seconds")

            stereo_reproj_errors.append(stereo_reproj_err)
            stereo_recon_errors.append(stereo_recon_err)
            tracked_reproj_errors.append(tracked_reproj_err)
            tracked_recon_errors.append(tracked_recon_err)
            calib_times.append(elapsed_time)
            frame_grab_times.append(mean_frame_grabbing_time)
Exemplo n.º 22
0
def gen_cross_spec(cfg, scan_no, t0, t1, stn0, stn1):

    name_png = 'spec_No%04d_%s-%s_%.0f-%.0f.png' % (scan_no, stn0, stn1, t0,
                                                    t1)
    if os.path.exists(name_png):
        return

#    stn0    =   sys.argv[4].upper()
#    stn1    =   sys.argv[5].upper()
    stn_id0 = cfg.stn2id[stn0]
    stn_id1 = cfg.stn2id[stn1]
    if stn_id0 > stn_id1:
        stn_id0, stn_id1 = stn_id1, stn_id0

    bl_no = (stn_id0 + 1) * 256 + stn_id1 + 1

    cfg.tsum = cfg.ap  # set to 1 ap
    t0 = int(t0 / cfg.tsum) * cfg.tsum
    t1 = int(t1 / cfg.tsum) * cfg.tsum

    heads, bufs, arr2recs = cfg.load_seg(bl_no, t0, t1)
    if bufs == {}:
        return {}

    nap = int((t1 - t0) / cfg.ap + 0.5)

    buf = np.zeros((nap, cfg.nfreq, cfg.nchan), dtype=np.complex64)
    for pol in cfg.pols:
        buf += utils.calibrate(cfg, bufs[pol], bl_no, pol)


#    buf =   utils.dedispersion(cfg, buf, cfg.dm)

    nsum = 4

    nap = int(buf.shape[0] / nsum) * nsum
    buf = buf[:nap, :, :]

    fmin = cfg.freqs[0]
    fmax = cfg.freqs[-1] + cfg.bw

    df_mc = cfg.bw / cfg.nchan
    bw_mc = fmax - fmin
    nchan_mc = int(bw_mc / df_mc + 0.5)

    arr = np.zeros((nap, nchan_mc), dtype=np.complex128)
    for fid in range(cfg.nfreq):
        for vid in range(1, cfg.nchan):
            f = cfg.freqs[fid] + vid * df_mc
            mid = int((f - fmin) / df_mc + 0.5)
            arr[:, mid] = buf[:, fid, vid]

    arr = np.reshape(arr, (-1, nsum, nchan_mc))
    arr = np.sum(arr, axis=1)
    nap = int(nap / nsum)
    xf = np.arange(nchan_mc) * df_mc
    for i in range(nap):
        tau, _ = utils.fine_fit(arr[i, :], df_mc)
        arr[i, :] *= np.exp(-1j * 2 * np.pi * xf * tau)

    nvsum = 16
    arr = np.reshape(arr, (nap, -1, nvsum))
    arr = np.sum(arr, axis=-1)

    extent = (t0, t1, fmin, fmax)
    plot_spec(arr, extent, name_png)
Exemplo n.º 23
0
        calib_times = []
        frame_grab_times = []
        successful_dirs = []

        # Split into precalib set and the rest
        precalibration_data = calibrations[i]
        test_data = (c for j, c in enumerate(calibrations) if j != i)

        LOGGER.info(f"Using {precalibration_data} for precalibration")

        full_path = os.path.join(directory, precalibration_data)

        stereo_reproj_err, stereo_recon_err, tracked_reproj_err, \
            tracked_recon_err, elapsed_time, mean_frame_grabbing_time, \
                stereo_params = calibrate(left_point_detector,
                                            right_point_detector,
                                            full_path)

        LOGGER.info(f"Stereo Reprojection Error: {stereo_reproj_err}")
        LOGGER.info(f"Stereo Reconstruction Error: {stereo_recon_err}")
        LOGGER.info(f"Tracked Reprojection Error: {tracked_reproj_err}")
        LOGGER.info(f"Tracked Reconstruction Error: {tracked_recon_err}")
        LOGGER.info(f"Calibration took: {elapsed_time} seconds")

        for calibration in test_data:
            LOGGER.info(f"Calibrating {calibration}")

            try:
                full_path = os.path.join(directory, calibration)
                
                stereo_reproj_err, stereo_recon_err, tracked_reproj_err, \