def custom_demodulation(ts, myrecording, lenghtBits):
    # this custom ASK modulation (amplitude-shift modulation)
    # is to support CDMA, in this case: 0, -2, 2. Each number will have certain amplitude
    lenghtOneChunk = int(len(ts) / lenghtBits)
    bitsReceived = []
    currentChunk = 0

    for i in range(lenghtBits):
        allDataInCurrentChunk = []
        for j in range(lenghtOneChunk):
            currentData = myrecording[j + (currentChunk * lenghtOneChunk)]
            positiveValue = abs(currentData)
            allDataInCurrentChunk.append(positiveValue)
        median = pyl.median(allDataInCurrentChunk)
        print(median)
        currentBit = 0

        # WARNING: This values depends on device types
        #          and volume used.
        minForBit2 = 0.09
        minForBit_2 = 0.03
        if (median >= minForBit2):
            currentBit = 2
        elif (median >= minForBit_2 and median < minForBit2):
            currentBit = -2
        else:
            currentBit = 0
        bitsReceived.append(currentBit)
        currentChunk += 1
    return bitsReceived
Esempio n. 2
0
def self_resp_gate(navdata, tr, resp_dur):
    print("Generating respiratory gates from self-gated FIDs...")
    compi = N.array((0. + 1.j), N.complex)
    sizes = N.shape(navdata)
    ref_base = N.zeros(sizes, N.complex)
    diff_navdata = N.zeros(sizes, N.complex)
    ref_width = 512
    n_fids_perblock = 128
    num_blocks = int(N.ceil(sizes[0] / float(n_fids_perblock)))
    for j in range(num_blocks):
        fid_start = j * n_fids_perblock
        fid_end = (j + 1) * n_fids_perblock
        if (fid_end > sizes[0]):
            fid_end = sizes[0]
        start_pt = {
            0: 0,
            1: fid_start - (ref_width - n_fids_perblock) / 2
        }[fid_start - (ref_width - n_fids_perblock) / 2 > 0]
        end_pt = {
            0: sizes[0],
            1: fid_end + (ref_width - n_fids_perblock) / 2 + 1
        }[fid_end + (ref_width - n_fids_perblock) / 2 < sizes[0] - 1]
        if start_pt == 0:
            end_pt = ref_width
        if end_pt == sizes[0]:
            start_pt = sizes[0] - ref_width
        n_pts = end_pt - start_pt
        reference_fid = N.sort( navdata[start_pt:end_pt,:].real, axis=0)[n_pts/4:3*n_pts/4+1:n_pts/4,:] + \
                compi * N.sort( navdata[start_pt:end_pt,:].imag, axis=0)[n_pts/4:3*n_pts/4+1:n_pts/4,:]
        ref_base[fid_start:fid_end, :] = reference_fid[1, :]
        diff_navdata[fid_start:fid_end, :] = (
            navdata[fid_start:fid_end, :] -
            reference_fid[1, :]) / (reference_fid[2, :] - reference_fid[0, :])
    resp_sig = N.sum(abs(diff_navdata[:, 0:5]) / 4.0, axis=-1)
    testfig = N.ravel(resp_sig)
    ref_val = median(testfig)
    close_testfigs = N.compress(N.less(testfig, 20.0), testfig)
    numbins = 400
    [binfreq, binloc, patches] = hist(close_testfigs, numbins)
    max_freq = N.maximum.reduce(binfreq)
    testfig_mode = binloc[N.argmax(binfreq)]
    quiet_cutoff = binloc[N.maximum.reduce(
        N.nonzero(N.greater(binfreq, max_freq / 8))[0])]
    if (quiet_cutoff < 2 * testfig_mode):
        quiet_cutoff = 2 * testfig_mode
    print(quiet_cutoff)
    resp_gate_sig = N.less(resp_sig, quiet_cutoff)
    resp_gate_sig_orig = resp_gate_sig.copy()
    medfiltwindow = 2 * (int(resp_dur / tr)) + 1
    resp_gate_sig = medfilt(resp_gate_sig_orig, medfiltwindow)
    return resp_gate_sig, resp_sig
               color='black',
               label=label,
               zorder=10)
        if name in winners.values():
            i2 += 1
            label = None if i2 != 1 else "Tournament win (top 15 only)"
            yy = [y for y in years if winners[y] == name]
            P.scatter(yy,
                      P.array(C.get_y_hat(yy)),
                      marker="*",
                      color="green",
                      label=label,
                      zorder=15)
    else:
        P.plot(t, theta_hat, linewidth=1, color='grey', alpha=0.5, zorder=1)
years, med_theta = P.array([(year, P.median(abils[year]))
                            for year in range(1937, 2019)
                            if len(abils[year]) > 0]).T
P.plot(years,
       med_theta,
       linewidth=2,
       color='red',
       zorder=20,
       label="Median ability")
P.legend()
# P.title("Trajectories for abilities of Masters Tournament attendees")
P.xlabel("Year")
P.ylabel("Ability")
P.ylim([-3, 3])
# P.savefig('../writeup/figs/overall_golf_trajectories.pdf')
P.show()
Esempio n. 4
0
def phot1(r,
          imlist,
          plot=True,
          names=None,
          panel=None,
          debug=None,
          showmask="both"):
    """
    give me a region and an imlist and tell me whether to plot cutouts
    """
    nim = len(imlist)
    # TODO alg for how many subpanels.
    if panel == None: panel = [5, 4, 1]  # for vertical page
    f = []
    df = []
    raw = []
    for j in range(nim):
        im = imlist[j]
        # if plotting, need to make image cutouts; even if not, this tells
        # us if the source is off the edge
        xtents = r.imextents(imlist[j])
        minsize = 5
        if (xtents[3] - xtents[1]) < minsize or (xtents[2] -
                                                 xtents[0]) < minsize:
            raw0, f0, df0 = 0, 0, 0
            print "phot region too small - %f,%f less than %d pixels" % (
                (xtents[3] - xtents[1]), (xtents[2] - xtents[0]), minsize)
            print xtents, r.imcoords(im, reg="bg1")
        else:
            if plot:
                pl.subplot(panel[0], panel[1], panel[2])
                im = hextract(imlist[j], xtents)[0]
                ## ROTATE
                rotate = True
                if rotate:
                    from astropy import wcs
                    w = wcs.WCS(im.header)
                    from scipy.ndimage.interpolation import rotate
                    if w.wcs.has_crota():
                        t0 = w.wcs.crota[1]
                    else:
                        t0 = pl.arctan2(w.wcs.cd[0, 1],
                                        -w.wcs.cd[0, 0]) * 180 / pl.pi
                    theta = -1 * t0
                    im.data = rotate(im.data, theta, reshape=False)
                    ct = pl.cos(pl.pi * theta / 180)
                    st = pl.sin(pl.pi * theta / 180)
                    if w.wcs.has_crota():
                        w.wcs.crota[1] = w.wcs.crota[1] + theta
                        im.header['CROTA2'] = w.wcs.crota[1]
                        print "rotating crota by " + str(theta)
                    else:
                        w.wcs.cd = pl.matrix(w.wcs.cd) * pl.matrix([[ct, -st],
                                                                    [st, ct]])
                        im.header['CD1_1'] = w.wcs.cd[0, 0]
                        im.header['CD1_2'] = w.wcs.cd[0, 1]
                        im.header['CD2_1'] = w.wcs.cd[1, 0]
                        im.header['CD2_2'] = w.wcs.cd[1, 1]
                        print "rotating cd    by " + str(theta)

                    #pdb.set_trace()

                # ugh need minmax of aperture region...
                # estimate as inner 1/2 for now
                s = im.shape
                z = im.data[int(s[0] * 0.25):int(s[0] * 0.75),
                            int(s[1] * 0.25):int(s[1] * 0.75)]
                if len(z[0]) <= 0:
                    print z

                z = pl.where(pl.isnan(im.data))
                if len(z[0]) > 0:
                    z = pl.where(pl.isnan(im.data) == False)
                    std = im.data[z[0], z[1]].std()
                else:
                    std = im.data.std()
                rg = pl.median(im.data) + pl.array([-0.5, 5]) * std
                # marta wants them less saturated
                rg[1] = pl.nanmax(im.data)

                if rg[0] < 0: rg[0] = 0
                if rg[1] <= rg[0]:
                    rg = [pl.nanmin(z), pl.nanmax(z)]
                if showmask == False or showmask == "both":  # show the jet one
                    pl.imshow(im.data,
                              origin="bottom",
                              interpolation="nearest",
                              vmin=rg[0],
                              vmax=rg[1])
                elif showmask == True:  # only show the mask
                    pl.imshow(im.data,
                              origin="bottom",
                              interpolation="nearest",
                              vmin=rg[0],
                              vmax=rg[1],
                              cmap="YlGn")
                ax = pl.gca()
                ax.axes.get_xaxis().set_visible(False)
                ax.axes.get_yaxis().set_visible(False)
                if names:
                    pl.text(0.05,
                            0.99,
                            names[j],
                            horizontalalignment='left',
                            verticalalignment='top',
                            transform=ax.transAxes,
                            bbox=dict(facecolor='white', alpha=0.5))
                pl.xlim([-0.5, s[1] - 0.5])
                pl.ylim([-0.5, s[0] - 0.5])
                if showmask == False:
                    r.plotimx(im)  # overplot the apertures

                if showmask == "both":
                    panel[2] = panel[2] + 1
                    pl.subplot(panel[0], panel[1], panel[2])
                    rg = pl.median(im.data) + pl.array([-0.5, 5]) * std
                    if rg[0] < 0: rg[0] = 0
                    if rg[1] <= rg[0]:
                        rg = [pl.nanmin(z), pl.nanmax(z)]
                    pl.imshow(im.data,
                              origin="bottom",
                              interpolation="nearest",
                              vmin=rg[0],
                              vmax=rg[1],
                              cmap="YlGn")
                    ax = pl.gca()
                    ax.axes.get_xaxis().set_visible(False)
                    ax.axes.get_yaxis().set_visible(False)
                    if names:
                        pl.text(0.05,
                                0.99,
                                names[j],
                                horizontalalignment='left',
                                verticalalignment='top',
                                transform=ax.transAxes,
                                bbox=dict(facecolor='white', alpha=0.5))
                    pl.xlim([-0.5, s[1] - 0.5])
                    pl.ylim([-0.5, s[0] - 0.5])

            if debug:
                #                r.debug=True
                if names:
                    print names[j]

            raw0, bg, f0, df0 = r.phot(im)
        raw.append(raw0)
        f.append(f0)
        df.append(df0)
        panel[2] = panel[2] + 1
    if plot:
        pl.subplots_adjust(wspace=0.02,
                           hspace=0.02,
                           left=0.1,
                           right=0.97,
                           top=0.95,
                           bottom=0.05)
    return f, df, raw