Beispiel #1
0
def super_plot(zoom_dynspec, pulse=0, zoom=1, info=None):
    '''Do some awesome ploting.
    '''
    #Create a frequency vector
    frequencies = zoom_dynspec.par.yvalues
    #Create a time vector
    times = zoom_dynspec.par.xvalues

    pdb.set_trace()
    cr.plt.clf()
    cr.plt.ion()
    zoom = 1
    if zoom:
        cr.plt.rcParams['font.size'] = 20
        cr.plt.rcParams['axes.titlesize'] = 30
        cr.plt.subplot(2, 2, 1)
        cr.plt.title("Pulse Profile from : " + zoom_dynspec.par.station)
        cr.plt.xlabel("+/- Time [s]")
        flat_dyn = bt.flatdyn(zoom_dynspec, axis='x')
        cr.plt.plot(flat_dyn.par.xvalues, flat_dyn)
        cr.plt.autoscale(axis='x', tight=True)

        cr.plt.subplot(2, 2, 4)
        cr.plt.xlabel("Frequency [MHz]")
        flat_dyn, flat_dyn2 = bt.flatdyn(
            zoom_dynspec,
            axis='y',
            pulse_range=info.par.pulse_range,
            background_range=[0, 50 / info.par.tbin])
        cr.plt.plot(flat_dyn.par.xvalues, flat_dyn)
        cr.plt.plot(flat_dyn.par.xvalues, flat_dyn2, 'r')
        cr.plt.autoscale(axis='x', tight=True)

        cr.plt.subplot(2, 2, 3)
    #Time integration.
    tbin = 1
    if tbin > 1:
        zoom_dynspec = cr.hArray_toNumpy(zoom_dynspec)
        zoom_dynspec = zoom_dynspec.reshape(
            (zoom_dynspec.shape[0] / tbin, tbin, zoom_dynspec.shape[1]))
        zoom_dynspec = np.sum(zoom_dynspec, axis=1)
        zoom_dynspec = cr.hArray(zoom_dynspec)
    zoom_dynspec = zoom_dynspec.Transpose()
    tbin = 4
    if tbin > 1:
        zoom_dynspec = cr.hArray_toNumpy(zoom_dynspec)
        zoom_dynspec = zoom_dynspec[:-3]
        zoom_dynspec = zoom_dynspec.reshape(
            (zoom_dynspec.shape[0] / tbin, tbin, zoom_dynspec.shape[1]))
        zoom_dynspec = np.sum(zoom_dynspec, axis=1)
        zoom_dynspec = cr.hArray(zoom_dynspec)
    zoom_dynspec = zoom_dynspec.Transpose()
    cr.plt.imshow(np.log10(cr.hArray_toNumpy(zoom_dynspec)),
                  aspect='auto',
                  origin='lower',
                  cmap=cr.plt.cm.hot,
                  extent=(times[0], times[-1], frequencies[0],
                          frequencies[-1]))
    cr.plt.xlabel("+/- Time [s]")
    cr.plt.ylabel("Frequency [MHz]")
Beispiel #2
0
def dynplot(dynspec, log=True):
    '''Plot dynamic spectrum.
    '''

    raise NotImplementedError

    #Create a frequency vector
    frequencies = dynspec.par.yvalues

    #Create a time vector
    times = dynspec.par.xvalues

    #Plotings....

    cr.plt.ion()
    cr.plt.clf()
    if not log:
        cr.plt.imshow(cr.hArray_toNumpy(dynspec),
                      aspect='auto',
                      origin='lower',
                      cmap=cr.plt.cm.hot,
                      vmin=1e-3,
                      vmax=0.03,
                      extent=(times[0], times[-1], frequencies[0],
                              frequencies[-1]))
    else:
        cr.plt.imshow(np.log10(cr.hArray_toNumpy(dynspec)),
                      aspect='auto',
                      origin='lower',
                      vmin=-3,
                      vmax=-1.5,
                      cmap=cr.plt.cm.hot,
                      extent=(times[0], times[-1], frequencies[0],
                              frequencies[-1]))
    cr.plt.xlabel("+/- Time [s]")
    cr.plt.ylabel("Frequency [MHz]")
Beispiel #3
0
    
cross_correlation = cross_correlation.Transpose()
final_cc = cross_correlation[...].sum()

print 'Need to check that the code is working, now with either doing the station mean on the complex or on the timeseries.'
stop

#------------------------
final_cc/=blocklen*nblocks
#final_cc.abs()

final_cc=cr.hArray(float,len(final_cc),fill=final_cc)

cr.plt.ion()
time = np.arange(-1*blocklen*5e-9/2,blocklen*5e-9/2,5e-9)
cr.plt.plot(time,cr.hArray_toNumpy(final_cc))
cr.plt.xlabel('Time [s] ')

final_cc=cr.hArray(float,[1,len(final_cc)],fill=final_cc)




#------------------------
#Fitting  cc.
range_cc = 20
cut_cc = cr.hArray(float,[1,len(final_cc[0,speclen-range_cc:speclen+range_cc].vec())],final_cc[0,speclen-range_cc:speclen+range_cc].vec())

mx=cr.trun("FitMaxima",cut_cc,doplot=True,peak_width=40)#,splineorder=2)

print '--------------------'
Beispiel #4
0
#------------------------
# Resample
resample = 32
delay_step = beams['TBB_SAMPLE_INTERVAL'][0] / resample

cc_smooth = cr.hArray(float, [1, blocklen * resample])
cr.hFFTWResample(cc_smooth, cross_correlation)

# Ploting resampled
cr.plt.ion()
cc_smooth = cr.hArray(float, len(cc_smooth), fill=cc_smooth)

time = np.arange(-1 * blocklen * 5e-9 / 2, blocklen * 5e-9 / 2,
                 5e-9 / resample)
cr.plt.plot(time, cr.hArray_toNumpy(cc_smooth))
cr.plt.xlabel('Time [s] ')

#cc_smooth.abs()
cr.plt.plot(time, cr.hArray_toNumpy(cc_smooth))

#------------------------
#Using a Hilbert envelope

if envelope:
    cr.plt.ion()
    cr.plt.figure()
    cr.plt.plot(cc_smooth)

    cc_nparray = cc_smooth.toNumpy()
    envelope_cc = abs(scipy.signal.hilbert(cc_nparray))
Beispiel #5
0
def calcIndividualStationDynspecs(beams,
                                  dm=0,
                                  save_file=False,
                                  fraction=None,
                                  tbin=1,
                                  clean=False,
                                  verbose=1,
                                  time_range=None):
    '''
    Calculates the dynamic spectrum of individual beams.

    ============ ===== ===================================================================
    *beams*            Input array.
    *dm*         0     Dedispersion Measure
    *save_file*  False Saves a file in hArray format with additional information besides the array values.
    *fraction*   None  If not None, then a list of the form [x,y] such that extracting the fraction x/y of the data. with x>-1, and y>=x.
    *tbin*       1     If >1 integrates over this number of blocks. Or time binning.
    *clean*      False If True it calculates the cleaned spectrum.
    *verbose*    1     If want to print status and performance.
    *time_range* None  List with the begin and end of time selection. [t1,t2] in s
    ============ ===== ===================================================================

    Example::

        import Beam_Tools as bt
        dynspecs = bt.calcIndividualStationDynspecs(beams)

    or::

        import Beam_Tools as bt
        dynspecs,cleandynspecs = bt.calcIndividualStationDynspecs(beams,tbin=16,clean=True,save_file=True,time_range=[0,.1])

    '''
    #-----------
    #Log of things to check:
    #1)tbin divisiion
    #-----------

    t0 = time.clock()

    #    filename_bin = os.path.join(filename,"data.bin")   #Maybe needed in the future if using "from_file" option.

    speclen = beams['BEAM_SPECLEN']
    block_duration = beams['BLOCKSIZE'] * beams['SAMPLE_INTERVAL'][0]
    nblocks = beams['NCHUNKS'] * beams['BEAM_NBLOCKS']

    if not beams['DM'] and dm:
        beams['DM'] = dm

    if time_range:
        #Time selection indexing.
        if type(time_range) != type([]) or len(time_range) != 2 or time_range[
                0] > time_range[1] or time_range[0] < 0 or time_range[1] < 0:
            raise ValueError(
                'Need a list of lenght 2, with first element "<" or "=" second element. Both elements positive.'
            )
        times = beams.getTimes()
        block_range = cr.hArray(int, 2)
        cr.hFindSequenceBetweenOrEqual(block_range, times, time_range[0],
                                       time_range[1], 0, 0)
        nblocks = block_range[1] - block_range[0]
        fraction = False
        block_range = range(block_range[0], block_range[1])

    if not fraction:
        fraction = [1, 1]
        if not time_range:
            block_range = range(0, nblocks)
    else:
        if type(fraction) != type([]) or len(fraction) != 2 or fraction[
                0] > fraction[1] or fraction[0] < 0 or fraction[1] < 0:
            raise ValueError(
                'Need a list of lenght 2, with first element "<" or "=" second element. Both elements positive.'
            )
        if fraction[0] == 0: fraction[0] = 1
        nblocks = int(nblocks / fraction[1])
        block_range = range((fraction[0] - 1) * nblocks,
                            (fraction[0]) * nblocks)

    beam = beams.empty('FFT_DATA')
    dynspec = cr.hArray(float, [beam.shape()[0], nblocks, beam.shape()[1]])

    #Dynamic spectrum calculation.
    for i, block in enumerate(block_range):
        if verbose:
            print 'Dynamic spectrum calculation at {0:.2%}  \r'.format(
                float(i) / nblocks),
        sys.stdout.flush()
        beams.getFFTData(beam, block)
        for b in range(beam.shape()[0]):
            dynspec[b, i].spectralpower2(beam[b])

    #Time integration.
    if tbin > 1:
        dynspec = cr.hArray_toNumpy(dynspec)
        dynspec = dynspec.reshape((dynspec.shape[0], dynspec.shape[1] / tbin,
                                   tbin, dynspec.shape[2]))
        dynspec = np.sum(dynspec, axis=2)
        dynspec = cr.hArray(dynspec)

    #Cleaning dynamic spectrum.
    if clean:
        cleandynspec = dynspec * 0
        for b in range(beam.shape()[0]):
            avspec = cr.hArray(float, speclen, fill=0.0)
            dynspec[b, ...].addto(avspec)
            cleandynspec[b] = (dynspec[b] * dynspec.shape()[1] / avspec)[0]

    #Transposing arrays.
    dynspec_T = dynspec.Transpose() * 0
    for b in range(beam.shape()[0]):
        dynspec_T[b] = dynspec[b].Transpose()
    dynspec = dynspec_T

    if clean:
        cleandynspec_T = cleandynspec.Transpose() * 0
        for b in range(beam.shape()[0]):
            cleandynspec_T[b] = cleandynspec[b].Transpose()
        cleandynspec = cleandynspec_T

    #Create a frequency vector
    frequencies = beams['BEAM_FREQUENCIES']

    #Create a time vector
    start_time = block_range[0] * block_duration
    end_time = block_range[-1] * block_duration
    times = cr.hArray(
        float,
        int(round((end_time - start_time) / (block_duration * tbin))),
        name="Time",
        units=("", "s"))
    times.fillrange(start_time, block_duration * tbin)

    #Adding parameters
    dynspec.par.yvalues = frequencies
    dynspec.par.xvalues = times
    dynspec.par.tbin = tbin
    if clean:
        cleandynspec.par.yvalues = frequencies
        cleandynspec.par.xvalues = times
        cleandynspec.par.tbin = tbin

    #Saving file(s).
    if save_file:
        dynspec.write(os.path.join(filename, "dynspec"),
                      nblocks=1,
                      block=0,
                      clearfile=True)
        print 'Saving binary in %s' % os.path.join(filename, "dynspec.pcr")
        if clean:
            cleandynspec.write(os.path.join(filename, "clean_dynspec"),
                               nblocks=1,
                               block=0,
                               clearfile=True)
            print 'Saving binary in %s' % os.path.join(filename,
                                                       "clean_dynspec.pcr")

    if verbose:
        print "Finished - dyncalc time used:", time.clock() - t0, "s."

    if clean:
        return dynspec, cleandynspec
    else:
        return dynspec
Beispiel #6
0
def rawdyncalc(TAB,
               fraction=None,
               tbin=1,
               clean=False,
               axis_val=False,
               verbose=1):
    '''
    Calculates the dynamic spectrum of a raw beam (no TBB info).

    =============== ===== ===================================================================
    *TAB*                 Input complex array.
    *fraction*      None  If not None, then a list of the form [x,y] such that extracting the fraction x/y of the data. with x>-1, and y>=x.
    *tbin*          1     If >1 integrates over this number of blocks. Or time binning.
    *clean*         False If True it calculates the cleaned spectrum.
    *verbose*       1     If want to print status and performance.
    =============== ===== ===================================================================

    Example::

        import Beam_Tools as bt
        dynspec = bt.rawdyncalc(filename)

    or::

        import Beam_Tools as bt
        dynspec,cleandynspec = bt.rawdyncalc(TAB,tbin=16,clean=True)

    '''

    t0 = time.clock()

    speclen = TAB.shape()[1]
    block_duration = (TAB.shape()[1] - 1) * 2 * 5e-09
    nblocks = TAB.shape()[0]

    #Create a frequency vector
    if axis_val:
        frequencies = TAB.par.yvalues
    else:
        frequencies = cr.hArray(
            float, speclen,
            list(np.arange(1e+08, 2e+08 + 12207.03125, 12207.03125)))

    if not fraction:
        fraction = [1, 1]
    else:
        if type(fraction) != type([]) or len(fraction) != 2 or fraction[
                0] > fraction[1] or fraction[0] < 0 or fraction[1] < 0:
            raise ValueError(
                'Need a list of lenght 2, with first element "<" or "=" second element. Both elements positive.'
            )
        if fraction[0] == 0: fraction[0] = 1
        nblocks = int(nblocks / fraction[1])

    start_time = (fraction[0] - 1) * (block_duration * nblocks) / fraction[1]
    end_time = fraction[0] * (block_duration * nblocks) / fraction[1]

    dynspec = cr.hArray(float, [nblocks, speclen])
    block_range = range((fraction[0] - 1) * nblocks, (fraction[0]) * nblocks)
    beam = cr.hArray(complex, speclen)

    #Reading TAB.
    for block in block_range:
        if verbose:
            print 'Dynspec calculation at {0:.2%}  \r'.format(
                float(block) / nblocks),
        sys.stdout.flush()
        beam = TAB[block]
        dynspec[block].spectralpower2(beam)

    #Time integration.
    if tbin > 1:
        dynspec = cr.hArray_toNumpy(dynspec)
        dynspec = dynspec.reshape(
            (dynspec.shape[0] / tbin, tbin, dynspec.shape[1]))
        dynspec = np.sum(dynspec, axis=1)
        dynspec = cr.hArray(dynspec)

    #Cleaning dynamic spectrum.
    if clean:
        avspec = cr.hArray(float, speclen, fill=0.0)
        dynspec[...].addto(avspec)
        cleandynspec = dynspec / avspec

    #Transposing arrays.
    dynspec = dynspec.Transpose()
    if clean:
        cleandynspec = cleandynspec.Transpose()

    #Create a time vector
    if axis_val:
        times = TAB.par.xvalues
    else:
        times = cr.hArray(
            float,
            int(round((end_time - start_time) / (block_duration * tbin))),
            name="Time",
            units=("", "s"))
        times.fillrange(start_time, block_duration * tbin)

    #Adding parameters
    dynspec.par.yvalues = frequencies
    dynspec.par.xvalues = times
    dynspec.par.tbin = tbin
    if clean:
        cleandynspec.par.yvalues = frequencies
        cleandynspec.par.xvalues = times
        cleandynspec.par.tbin = tbin

    if verbose:
        print "Finished - dyncalc time used:", time.clock() - t0, "s."

    if clean:
        return dynspec, cleandynspec
    else:
        return dynspec
Beispiel #7
0
def addBeams(beams,
             dyncalc=False,
             save_file=False,
             fraction=False,
             clean=False,
             tbin=1,
             dm=0,
             verbose=1,
             incoherent=False):
    '''Add complex beams toguether.
    If requested:
        - Calculates a dynamic spectrum.
        - Dedisperses the beam.
        - Bins the dynspec in integer time blocks (not for the TAB, which stays in complex).

    =============== ===== ===================================================================
    *beams*               Input beams, opened by the beam.py interphase.
    *dyncalc*       True  If True it calculates the dynamic spectrum
    *dm*            0     Dedispersion Measure
    *save_file*     False Saves a file in hArray format with additional information besides the array values.
    *fraction*      None  If not None, then a list of the form [x,y] such that extracting the fraction x/y of the data. with x>-1, and y>=x. This also makes tbin=1
    *tbin*          1     If >1 integrates over this number of blocks. Or time binning.
    *clean*         False If True it calculates the cleaned spectrum.
    *verbose*       1     If want to print status and performance.
    *incoherent*    False Adding beams coherently (default) or not.
    =============== ===== ===================================================================

    Example::

        import Beam_Tools as bt
        TAB,dynspec,cleandynspec = bt.addBeams(beams,dyncalc=True,tbin=16,dm=26.76,clean=True)

    '''
    if incoherent:
        print 'Incoherent addition of the following beams: '
    else:
        print 'Coherent addition of the following beams: '

    for file in beams['FILENAMES']:
        print file
    print '------_-------'

    if save_file:
        raise KeyError("Keyword is invalid for now: " + key)

    if fraction:
        if tbin > 1:
            print 'WARNING: tbin has been reset to 1, since using fraction.'
        tbin = 1

    t0 = time.clock()

    speclen = beams['BLOCKSIZE'] / 2 + 1
    block_duration = beams['BLOCKSIZE'] * beams['SAMPLE_INTERVAL'][0]
    nblocks = beams['NCHUNKS'] * beams['BEAM_NBLOCKS']
    beam = beams.empty('FFT_DATA')
    total_beam = cr.hArray(complex, (nblocks, beam.shape()[1]))
    fft_matrix = cr.hArray(complex, beam.shape()[1])
    if not beams['DM'] and dm:
        beams['DM'] = dm

    if not fraction:
        fraction = [1, 1]
    else:
        if type(fraction) != type([]) or len(fraction) != 2 or fraction[
                0] > fraction[1] or fraction[0] < 0 or fraction[1] < 0:
            raise ValueError(
                'Need a list of lenght 2, with first element "<" or "=" second element. Both elements positive.'
            )
        if fraction[0] == 0: fraction[0] = 1
        nblocks = int(nblocks / fraction[1])

    if dyncalc:
        dynspec = cr.hArray(float, (nblocks, beam.shape()[1]))

    if incoherent:
        for block in range(nblocks):
            bm = cr.hArray(complex, beam.shape()[1])
            if verbose:
                print 'Addition beams at {0:.2%}  \r'.format(
                    float(block) / nblocks),
            sys.stdout.flush()
            beams.getFFTData(beam, block)
            dynspec[block].spectralpower2(beam[...])
        total_beam = dynspec
    else:
        for block in range(nblocks):
            bm = cr.hArray(complex, beam.shape()[1])
            if verbose:
                print 'Addition beams at {0:.2%}  \r'.format(
                    float(block) / nblocks),
            sys.stdout.flush()
            beams.getFFTData(beam, block)
            for b in range(beam.shape()[0]):
                fft_matrix[:] = beam[b].vec() / float(b + 1.)
                if b > 0:
                    bm *= (b) / (b + 1.)
                bm += fft_matrix  #Around here I could possibly change the code to be saving each station at the time... just like beamformer does.. to help not eating too much memory.
            total_beam[block] = bm
            if dyncalc:
                dynspec[block].spectralpower2(bm)

    if verbose:
        print "Finished - addBeams in %f sec" % (time.clock() - t0)

    if dyncalc:
        start_time = (fraction[0] - 1) * (block_duration * nblocks)
        end_time = fraction[0] * (block_duration * nblocks)

        #Create a frequency vector
        frequencies = beams['BEAM_FREQUENCIES']

        #Create a time vector
        times = cr.hArray(
            float,
            int(round((end_time - start_time) / (block_duration * tbin))),
            name="Time",
            units=("", "s"))
        times.fillrange(start_time, block_duration * tbin)

        #Time integration.
        if tbin > 1:
            dynspec = cr.hArray_toNumpy(dynspec)
            dynspec = dynspec.reshape(
                (dynspec.shape[0] / tbin, tbin, dynspec.shape[1]))
            dynspec = np.sum(dynspec, axis=1)
            dynspec = cr.hArray(dynspec)

        #Cleaning dynamic spectrum.
        if clean:
            avspec = cr.hArray(float, speclen, fill=0.0)
            dynspec[...].addto(avspec)
            cleandynspec = dynspec / avspec

        #Transposing arrays.
        dynspec = dynspec.Transpose()
        if clean:
            cleandynspec = cleandynspec.Transpose()

        #Adding parameters
        dynspec.par.yvalues = frequencies
        dynspec.par.xvalues = times
        dynspec.par.tbin = tbin
        if clean:
            cleandynspec.par.yvalues = frequencies
            cleandynspec.par.xvalues = times
            cleandynspec.par.tbin = tbin

        if clean:
            return total_beam, dynspec, cleandynspec
        else:
            return total_beam, dynspec

    else:
        return total_beam
Beispiel #8
0
def dyncalc_multibeam(filename=None,
                      beams=None,
                      nbeam=0,
                      save_file=False,
                      from_file=False,
                      fraction=None,
                      tbin=1,
                      clean=False):
    '''
    Calculates the dynamic spectrum.

    =============== ===== ===================================================================
    *beams*         None  Input array.
    *nbeam*         0     Beam to work with, if ()beams has stored multiple ones.
    *save_file*     False Saves a file in hArray format with additional information besides the array values.
    *from_file*    False Read cleandynspec from file.
    *fraction*      None  If not None, then a list of the form [x,y] such that extracting the fraction x/y of the data. with x>-1, and y>=x.
    *tbin*          1     If >1 integrates over this number of blocks. Or time binning.
    *clean*         False If True it calculates the cleaned spectrum.
    =============== ===== ===================================================================

    Example::

        import Beam_Tools as bt
        dynspec = bt.dyncalc(filename)

    or::

        import Beam_Tools as bt
        dynspec,cleandynspec = bt.dyncalc(beams,tbin=16,clean=True,save_file=True)

    The regular and clean dynamic spectra (all blocks) are returned and stored in ``Task.dynspec`` and ``Task.cleandynspec`` respectively.
    '''

    raise NotImplementedError

    if beams == None and filename == None:
        raise ValueError(
            'Need to provide either the filename or the opened .beam file')

    if nbeam != 0 or from_file or save_file:
        raise KeyError("Keyword is invalid for now: " + key)

    t0 = time.clock()

    if beams == None:
        beams = cr.open(filename)
    elif filename == None:
        filename = beams['FILENAMES'][0]


#    filename_bin = os.path.join(filename,"data.bin")   #Maybe needed in the future if using "from_file" option.

    speclen = beams['BLOCKSIZE'] / 2 + 1
    block_duration = beams['BLOCKSIZE'] * beams['SAMPLE_INTERVAL'][0]
    nblocks = beams['NCHUNKS'] * beams['BEAM_NBLOCKS']

    if not fraction:
        fraction = [1, 1]
    else:
        if type(fraction) != type([]) or len(fraction) != 2 or fraction[
                0] > fraction[1] or fraction[0] < 0 or fraction[1] < 0:
            raise ValueError(
                'Need a list of lenght 2, with first element "<" or "=" second element. Both elements positive.'
            )
        if fraction[0] == 0: fraction[0] = 1
        nblocks = int(nblocks / fraction[1])

    start_time = (fraction[0] - 1) * (block_duration * nblocks) / fraction[1]
    end_time = fraction[0] * (block_duration * nblocks) / fraction[1]

    beam = beams.empty('FFT_DATA')
    tm = cr.hArray(float, beam)
    dynspec = cr.hArray(float, [nblocks, beam.shape()[0], speclen])
    block_range = range((fraction[0] - 1) * nblocks, (fraction[0]) * nblocks)
    pdb.set_trace()
    #Reading beams.
    for block in block_range:
        print ' Calculation at {0:.2%}  \r'.format(
            float(block) / len(block_range)),
        sys.stdout.flush()
        beams.getFFTData(beam, block)
        tm[...].spectralpower2(beam[...])
        dynspec[block] = tm

    #Time integration.
    if tbin > 1:
        dynspec = cr.hArray_toNumpy(dynspec)
        dynspec = dynspec.reshape((dynspec.shape[0] / tbin, tbin,
                                   dynspec.shape[1], dynspec.shape[2]))
        dynspec = np.sum(dynspec, axis=1)
        dynspec = cr.hArray(dynspec)

        #Rearranging dimensions.
        dynspec = cr.hArray_toNumpy(dynspec)
        #        dynspec = np.rollaxis(dynspec,0,3)
        dynspec = np.swapaxes(dynspec, 0, 1)
        dynspec = np.swapaxes(dynspec, 1, 2)
        dynspec = cr.hArray(
            dynspec.copy())  #The .copy() is quick&dirty way to avoid a bug.

    #Cleaning dynamic spectrum.
    if clean:
        avspec = cr.hArray(float, speclen, fill=0.0)
        cleandynspec = cr.hArray(float, dynspec, fill=0.0)
        for dim in range(dynspec.shape()[0]):
            single_dynspec = cr.hArray(float,
                                       dynspec.shape()[1:], dynspec[dim])
            single_dynspec[...].addto(avspec)
            cleandynspec[dim] = single_dynspec / avspec

    #Create a frequency vector
    frequencies = beams['BEAM_FREQUENCIES']

    #Create a time vector
    times = cr.hArray(
        float,
        int(round((end_time - start_time) / (block_duration * tbin))),
        name="Time",
        units=("", "s"))
    times.fillrange(start_time, block_duration * tbin)

    #Adding parameters
    dynspec.par.yvalues = frequencies
    dynspec.par.xvalues = times
    dynspec.par.tbin = tbin
    if clean:
        cleandynspec.par.yvalues = frequencies
        cleandynspec.par.xvalues = times
        cleandynspec.par.tbin = tbin

    #Saving file(s).
    if save_file:
        dynspec.write(os.path.join(filename, "dynspec"),
                      nblocks=1,
                      block=0,
                      clearfile=True)
        print 'Saving binary in %s' % os.path.join(filename, "dynspec.pcr")
        if clean:
            cleandynspec.write(os.path.join(filename, "clean_dynspec"),
                               nblocks=1,
                               block=0,
                               clearfile=True)
            print 'Saving binary in %s' % os.path.join(filename,
                                                       "clean_dynspec.pcr")

    print "Finished - total time used:", time.clock() - t0, "s."

    if clean:
        return dynspec, cleandynspec
    else:
        return dynspec
Beispiel #9
0
    #Calculate dynamic spectrum.
    dynspec, cleandynspec = bt.rawdyncalc(TAB, clean=True, tbin=tbin)

pulse_cut = 1
title = 'Superterp Stations (Coherent)-pol0'

if not pulse_cut:
    #Plot.
    #    frequencies = beams['BEAM_FREQUENCIES']/10**6
    #    times = cr.hArray(float,nblocks,list(np.arange(0,nblocks*block_tstep,block_tstep)))
    frequencies = cleandynspec.par.yvalues
    times = cleandynspec.par.xvalues

    cr.plt.clf()
    cr.plt.ion()
    cr.plt.imshow(np.log10(cr.hArray_toNumpy(cleandynspec)),
                  aspect='auto',
                  origin='lower',
                  cmap=cr.plt.cm.hot,
                  extent=(times[0], times[-1], frequencies[0],
                          frequencies[-1]))
    cr.plt.rcParams['font.size'] = 20
    cr.plt.ylabel("Frequency [MHz]")
    cr.plt.xlabel("Time [s]")
    #    cr.plt.title(beams_suffix)
    cr.plt.title(title)
else:

    pulse = 1

    # Get pulse information
def super_plot(zoom_dynspec,pulse=0,zoom=1):
    '''Do some awesome ploting.
    
    '''

    #Create a frequency vector
    frequencies = zoom_dynspec.par.yvalues

    #Create a time vector
    times = zoom_dynspec.par.xvalues

#    cr.plt.subplot(1,len(filenames),i)
    cr.plt.clf()
    
    zoom=0
    if zoom:
        cr.plt.rcParams['font.size']=20
        cr.plt.rcParams['axes.titlesize']=30
        flat_dyn=bt.flatdyn(zoom_dynspec,pulse=pulse)
        cr.plt.subplot(2,2,1)
        cr.plt.title("Pulse Profile from : " + zoom_dynspec.par.station)
        cr.plt.plot(flat_dyn.par.xvalues,flat_dyn)
        cr.plt.xlabel("+/- Time [s]")
        cr.plt.autoscale(axis='x',tight=True)
        pdb.set_trace()
    
        if pulse!=3:  # Need to fix flatdyn for any kind of pulse ... or need to actually remove all the hardcoded stuff.
            flat_dyn,flat_dyn2=bt.flatdyn(zoom_dynspec,axis='y',pulse=pulse)
            cr.plt.subplot(2,2,4)
            cr.plt.plot(flat_dyn.par.xvalues,flat_dyn)
            cr.plt.plot(flat_dyn.par.xvalues,flat_dyn2,'r')
            cr.plt.autoscale(axis='x',tight=True)
            cr.plt.xlabel("Frequency [MHz]")
    
        cr.plt.subplot(2,2,3)
    #Time integration.
#    tbin=9
    if pulse:
        tbin=4
    else:
        tbin=6
    if not zoom:
        tbin=1
    if tbin>1:
        zoom_dynspec = cr.hArray_toNumpy(zoom_dynspec)
        zoom_dynspec = zoom_dynspec.reshape((zoom_dynspec.shape[0]/tbin,tbin,zoom_dynspec.shape[1]))
        zoom_dynspec = np.sum(zoom_dynspec,axis=1)
        zoom_dynspec = cr.hArray(zoom_dynspec)
#    tbin=8
    tbin=1
    zoom_dynspec = zoom_dynspec.Transpose()
    if tbin>1:
        zoom_dynspec = cr.hArray_toNumpy(zoom_dynspec)
        zoom_dynspec = zoom_dynspec.reshape((zoom_dynspec.shape[0]/tbin,tbin,zoom_dynspec.shape[1]))
        zoom_dynspec = np.sum(zoom_dynspec,axis=1)
        zoom_dynspec = cr.hArray(zoom_dynspec)
    zoom_dynspec = zoom_dynspec.Transpose()
    cr.plt.imshow(np.log10(cr.hArray_toNumpy(zoom_dynspec)),aspect='auto',origin='lower',cmap=cr.plt.cm.hot,extent=(times[0],times[-1],frequencies[0],frequencies[-1]))
#    pdb.set_trace()
#    cr.plt.imshow(np.log10(cr.hArray_toNumpy(zoom_dynspec)),aspect='auto',origin='lower',cmap=cr.plt.cm.hot,vmin=-4,vmax=-3,extent=(times[0],times[-1],frequencies[0],frequencies[-1]))
    cr.plt.xlabel("+/- Time [s]")
    cr.plt.ylabel("Frequency [MHz]")
    if zoom:
        zoom_dynspec=bt.cutdynspec(full_dynspec,pulse=pulse)
        zoom_dynspec.par.station = beams['STATION_NAME'][0]
        incoherent_dynspec+=zoom_dynspec/6.
#        zoom_beam=bt.cutbeam(beam)
#        zoom_dynspec=bt.rawdyncalc(zoom_beam,axis_val=True)
        if verbose:
            super_plot(zoom_dynspec,pulse=pulse,zoom=zoom)
            pdb.set_trace()     # Used for now to pause and manually save the images.
    else:
        full_dynspec = full_dynspec.Transpose()
        dynspec=cr.hArray(float,[nblocks, 8193],full_dynspec[0:nblocks].vec())
        
        if tbin>1:
            dynspec = cr.hArray_toNumpy(dynspec)
            dynspec = dynspec.reshape((dynspec.shape[0]/tbin,tbin,dynspec.shape[1]))
            dynspec = np.sum(dynspec,axis=1)
            dynspec = cr.hArray(dynspec)

        dynspec = dynspec.Transpose()

        dynspec.par.station = beams['STATION_NAME'][0]
        dynspec.par.yvalues = beams['BEAM_FREQUENCIES']/10**6
        dynspec.par.xvalues = cr.hArray(float,nblocks,list(np.arange(0,nblocks*8192*2*5e-9,8192*2*5e-9)))

        if verbose:
            super_plot(dynspec,pulse=pulse,zoom=zoom)
            pdb.set_trace()     # Used for now to pause and manually save the images.

        incoherent_dynspec+=dynspec
Beispiel #12
0
        file['SELECTED_DIPOLES_INDEX'][i]
        for i in range(len(file['SELECTED_DIPOLES']))
    ],
                  rotation='vertical')
    p2 = outdir + '/RFI/FindRFI.' + str(
        Obs_ID2) + '.st_' + file['STATION_NAME'][0] + '.pol_' + str(
            polarization) + '.antennas_cleaned_power.png'
    cr.plt.savefig(p2)

    #Ploting a waterfall with freq vs antenna for both RFI regions.
    if 'msec' in obs_mode:
        cr.plt.figure()
    else:
        cr.plt.figure(figsize=(8, 12))
        cr.plt.subplot(211)
    cr.plt.imshow(cr.hArray_toNumpy(average_spectrum -
                                    median_average_spectrum),
                  aspect='auto',
                  origin='lower',
                  interpolation='nearest',
                  cmap=cr.plt.cm.jet,
                  vmin=-1,
                  vmax=1,
                  extent=(freqs[0], freqs[-1], 0, rfi.nantennas))
    cb = cr.plt.colorbar(pad=0.0, fraction=.1)
    cb.set_label('log( Power spectrum per antenna  / median)')
    cr.plt.xlabel('Frequency [MHz]')
    cr.plt.yticks(range(len(file['SELECTED_DIPOLES'])), [
        file['SELECTED_DIPOLES_INDEX'][i]
        for i in range(len(file['SELECTED_DIPOLES']))
    ],
                  fontsize=8)