Exemple #1
0
    def test_prune(self):
        """Test the utils.get_uv_range function."""

        for filename, type in zip((idiFile, idiAltFile, uvFile),
                                  ('FITS-IDI', 'Alt. FITS-IDI', 'UVFITS')):
            with self.subTest(filetype=type):
                # Open the file
                idi = utils.CorrelatedData(filename)

                # Get some data to sort
                ds = idi.get_data_set(1)

                # Prune
                dsp1 = ds.get_uv_range(min_uv=10)
                for pol in ds.pols:
                    p0 = getattr(ds, pol)
                    p1 = getattr(dsp1, pol)
                    self.assertTrue(p1.nbaseline < p0.nbaseline)

                # Auto-prune
                dsp2 = idi.get_data_set(1, min_uv=10)
                for pol in ds.pols:
                    p0 = getattr(ds, pol)
                    p2 = getattr(dsp2, pol)
                    self.assertTrue(p2.nbaseline < p0.nbaseline)

                # Auto-prune that should result in no baselines
                dsp3 = idi.get_data_set(1, min_uv=100)
                for pol in ds.pols:
                    p0 = getattr(ds, pol)
                    p3 = getattr(dsp3, pol)
                    self.assertEqual(p3.nbaseline, 0)

                idi.close()
Exemple #2
0
    def test_gridding(self):
        """Test building a image from a visibility data set."""

        for filename, type in zip((idiFile, idiAltFile, uvFile),
                                  ('FITS-IDI', 'Alt. FITS-IDI', 'UVFITS')):
            with self.subTest(filetype=type):
                # Open the file
                idi = utils.CorrelatedData(filename)

                # Build the image
                ds = idi.get_data_set(1)
                junk = utils.build_gridded_image(ds, verbose=False)

                # Error checking
                self.assertRaises(RuntimeError,
                                  utils.build_gridded_image,
                                  ds,
                                  pol='XY')

                #
                # VisibilityData test
                #

                ds2 = VisibilityData()
                ds2.append(ds)
                junk = utils.build_gridded_image(ds, verbose=False)

                idi.close()
Exemple #3
0
    def test_CorrelatedDataIDI_MultiIF(self):
        """Test the utils.CorrelatedDataIDI class on a file with multiple IFs."""

        # Get some data
        data = self._init_data()

        # Filename and time
        testTime, testFile = time.time(), os.path.join('idi-test-MultiIF.fits')

        # Start the file
        fits = Idi(testFile, ref_time=testTime, overwrite=True)
        fits.set_stokes(['xx'])
        fits.set_frequency(data['freq'])
        fits.set_frequency(data['freq'] + 30e6)
        fits.set_geometry(data['site'], data['antennas'])
        fits.add_data_set(
            astro.utcjd_to_taimjd(astro.unix_to_utcjd(testTime)), 6.0,
            data['bl'],
            numpy.concatenate([data['vis'], 10 * data['vis']], axis=1))
        fits.write()
        fits.close()

        # Open the FITS IDI file
        idi = utils.CorrelatedData(testFile)
        self.assertEqual(idi.freq.size, 2 * data['freq'].size)
        ds = idi.get_data_set(1, include_auto=True)

        numpy.testing.assert_allclose(ds.XX.data[:, :data['freq'].size],
                                      data['vis'])
        numpy.testing.assert_allclose(ds.XX.data[:, data['freq'].size:],
                                      10 * data['vis'])

        idi.close()
Exemple #4
0
    def test_CorrelatedDataIDI_AltArrayGeometry(self):
        """Test the utils.CorrelatedDataIDI class on determing array geometry."""

        # Open the FITS IDI files
        idi1 = utils.CorrelatedData(idiFile)
        idi2 = utils.CorrelatedData(idiAltFile)

        # Dates
        self.assertEqual(idi1.date_obs.strftime("%Y-%m-%dT%H:%M:%S"),
                         idi2.date_obs.strftime("%Y-%m-%dT%H:%M:%S"))

        # Stand and baseline counts
        self.assertEqual(len(idi1.stands), len(idi2.stands))
        self.assertEqual(idi1.total_baseline_count, idi2.total_baseline_count)
        self.assertEqual(idi1.integration_count, idi2.integration_count)

        # Check stands
        for s1, s2 in zip(idi1.stands, idi2.stands):
            self.assertEqual(s1, s2)

        # Check stations
        station1 = parse_ssmif(idiSSMIFFile)
        station2 = idi2.station
        self.assertAlmostEqual(station1.lat, station2.lat, 3)
        self.assertAlmostEqual(station1.lon, station2.lon, 3)
        self.assertAlmostEqual(station1.elev, station2.elev, 1)

        # Check antennas
        ants1 = [a for a in station1.antennas if a.pol == 0]
        ants2 = station2.antennas
        for a1, a2 in zip(ants1, ants2):
            self.assertEqual(a1.id, a2.id)
            self.assertEqual(a1.stand.id, a2.stand.id)
            self.assertAlmostEqual(a1.stand.x, a2.stand.x, 2)
            self.assertAlmostEqual(a1.stand.y, a2.stand.y, 2)
            self.assertAlmostEqual(a1.stand.z, a2.stand.z, 2)

        idi1.close()
        idi2.close()
Exemple #5
0
    def test_image_coordinates(self):
        """Test getting per-pixel image coordinates."""

        for filename, type in zip((idiFile, idiAltFile, uvFile),
                                  ('FITS-IDI', 'Alt. FITS-IDI', 'UVFITS')):
            with self.subTest(filetype=type):
                uv = utils.CorrelatedData(filename)

                # Build the image
                ds = uv.get_data_set(1)
                junk = utils.build_gridded_image(ds, verbose=False)

                radec = utils.get_image_radec(junk, uv.get_antennaarray())
                azalt = utils.get_image_azalt(junk, uv.get_antennaarray())

                uv.close()
Exemple #6
0
    def test_subset(self):
        """Test the utils.get_antenna_subset function."""

        for filename, type in zip((idiFile, idiAltFile, uvFile),
                                  ('FITS-IDI', 'Alt. FITS-IDI', 'UVFITS')):
            with self.subTest(filetype=type):
                # Open the file
                idi = utils.CorrelatedData(filename)

                # Get some data to sort
                ds = idi.get_data_set(1)

                # Indicies
                ## Include
                dss1 = ds.get_antenna_subset(include=(0, 1, 2), indicies=True)
                self.assertEqual(len(dss1.baselines), 3)
                for a1, a2 in dss1.baselines:
                    self.assertTrue(a1 in (0, 1, 2))
                    self.assertTrue(a2 in (0, 1, 2))

                ## Exclude
                dss2 = ds.get_antenna_subset(exclude=(4, ), indicies=True)
                self.assertEqual(len(dss2.baselines), 6)
                for a1, a2 in dss2.baselines:
                    self.assertTrue(a1 != 4)
                    self.assertTrue(a2 != 4)

                # Stand numbers
                ## Include
                dss1 = ds.get_antenna_subset(include=(151, 222, 150),
                                             indicies=False)
                self.assertEqual(len(dss1.baselines), 3)
                for a1, a2 in dss1.baselines:
                    self.assertTrue(
                        a1 in [idi.stands.index(s) for s in (151, 222, 150)])
                    self.assertTrue(
                        a2 in [idi.stands.index(s) for s in (151, 222, 150)])

                ## Exclude
                dss2 = ds.get_antenna_subset(exclude=(173, ), indicies=False)
                self.assertEqual(len(dss2.baselines), 6)
                for a1, a2 in dss2.baselines:
                    self.assertTrue(a1 != idi.stands.index(173))
                    self.assertTrue(a2 != idi.stands.index(173))

                idi.close()
Exemple #7
0
    def test_sort(self):
        """Test the utils.sort function."""

        for filename, type in zip((idiFile, idiAltFile, uvFile),
                                  ('FITS-IDI', 'Alt. FITS-IDI', 'UVFITS')):
            with self.subTest(filetype=type):
                # Open the file
                idi = utils.CorrelatedData(filename)

                # Get some data to sort
                ds = idi.get_data_set(1, sort=False)

                # Sort
                dss = ds.copy()
                dss.sort()
                for pol in ds.pols:
                    p0 = getattr(ds, pol)
                    p1 = getattr(dss, pol)
                    self.assertEqual(p0.nbaseline, p1.nbaseline)
Exemple #8
0
    def test_rephase(self):
        """Test the utils.rephase_data function."""

        for filename, type in zip((idiFile, idiAltFile, uvFile),
                                  ('FITS-IDI', 'Alt. FITS-IDI', 'UVFITS')):
            with self.subTest(filetype=type):
                # Open the file
                idi = utils.CorrelatedData(filename)

                # Get the AntennaArray instance
                aa = idi.get_antennaarray()

                # Get some data to sort
                ds = idi.get_data_set(1)
                orig_bls = ds.baselines
                orig_dat = ds.XX.data.copy()
                orig_pc = ds.phase_center

                # Rephase #1
                ds.rephase(new_phase_center=vis.SOURCES['Sun'])
                for i in range(ds.nbaseline):
                    self.assertEqual(orig_bls[i][0], ds.baselines[i][0])
                    self.assertEqual(orig_bls[i][1], ds.baselines[i][1])

                # Rephase #2
                ds.rephase(new_phase_center=orig_pc)
                for i in range(ds.nbaseline):
                    self.assertEqual(orig_bls[i][0], ds.baselines[i][0])
                    self.assertEqual(orig_bls[i][1], ds.baselines[i][1])

                    for j in range(ds.nchan):
                        self.assertAlmostEqual(orig_dat[i][j],
                                               ds.XX.data[i][j], 2)

                # Bad rephase
                self.assertRaises(RuntimeError, ds.rephase, vis.SOURCES['vir'])

                idi.close()
Exemple #9
0
def main(args):
    # Grab the filename
    filename = args.filename

    idi = utils.CorrelatedData(filename)
    lo = idi.get_observer()
    lo.date = idi.date_obs.strftime("%Y/%m/%d %H:%M:%S")
    jd = lo.date + astro.DJD_OFFSET

    nStand = len(idi.stands)
    nchan = len(idi.freq)
    freq = idi.freq

    print("Raw Stand Count: %i" % nStand)
    print("Final Baseline Count: %i" % (nStand * (nStand - 1) / 2, ))
    print(
        "Spectra Coverage: %.3f to %.3f MHz in %i channels (%.2f kHz/channel)"
        % (freq[0] / 1e6, freq[-1] / 1e6, nchan, (freq[1] - freq[0]) / 1e3))
    print("Polarization Products: %i starting with %i" %
          (len(idi.pols), idi.pols[0]))
    print("JD: %.3f" % jd)

    print("Reading in FITS IDI data")
    nSets = idi.integration_count
    for set in range(1, nSets + 1):
        if args.dataset != -1 and args.dataset != set:
            continue

        print("Set #%i of %i" % (set, nSets))
        dataDict = idi.get_data_set(set, min_uv=args.uv_min)

        # Prune out what needs to go
        if args.include != 'all' or args.exclude != 'none':
            print("    Processing include/exclude lists")
            dataDict = dataDict.get_antenna_subset(include=args.include,
                                                   exclude=args.exclude,
                                                   indicies=False)

            ## Report
            for pol in dataDict.pols:
                print("        %s now has %i baselines" %
                      (pol, len(dataDict.baselines)))

        # Pull out the right channels
        toWork = numpy.where((freq >= args.freq_start)
                             & (freq <= args.freq_stop))[0]
        if len(toWork) == 0:
            raise RuntimeError("Cannot find data between %.2f and %.2f MHz" %
                               (args.freq_start / 1e6, args.freq_stop / 1e6))
        if args.frequency:
            xValues = freq[toWork] / 1e6
            xLabel = 'Frequency [MHz]'
        else:
            xValues = toWork
            xLabel = 'Channel'

        # Plot
        print("    Plotting the first 50 baselines")
        pols = dataDict['jd'].keys()
        nBL = len(dataDict['bls'][pols[0]])
        pb = ProgressBar(max=nBL)
        i = 0
        for k in range(2):
            fig = plt.figure()

            for j in range(25):
                try:
                    stnd1, stnd2 = dataDict['bls'][pols[0]][i]
                    stnd1 = idi.stands[stnd1]
                    stnd2 = idi.stands[stnd2]
                    vis = dataDict['vis'][pols[0]][i]
                    i += 1
                except IndexError:
                    plt.draw()
                    break

                amp = numpy.abs(vis)
                if args.log:
                    amp = numpy.log10(amp)
                phs = numpy.angle(vis) * 180 / numpy.pi

                ax = fig.add_subplot(10, 5, 2 * (j // 5) * 5 + j % 5 + 1)
                if ((phs + 360) % 360).std() < phs.std():
                    ax.plot(xValues, (phs[toWork] + 360) % 360,
                            linestyle=' ',
                            marker='x')
                    ax.set_ylim([0, 360])
                else:
                    ax.plot(xValues, phs[toWork], linestyle=' ', marker='x')
                    ax.set_ylim([-180, 180])
                ax.set_title('%i - %i' % (stnd1, stnd2))
                if j % 5 == 0:
                    ax.set_ylabel('Phs')

                ax = fig.add_subplot(10, 5, 2 * (j // 5) * 5 + j % 5 + 1 + 5)
                ax.plot(xValues,
                        amp[toWork],
                        linestyle=' ',
                        marker='x',
                        color='green')
                ax.set_title('%i - %i' % (stnd1, stnd2))
                if j % 5 == 0:
                    ax.set_xlabel(xLabel)
                    ax.set_ylabel('%sAmp' % '' 'Log ' if args.log else '')

                pb.inc(amount=1)
                if pb.amount != 0 and pb.amount % 10 == 0:
                    sys.stdout.write(pb.show() + '\r')
                    sys.stdout.flush()
            plt.draw()

        sys.stdout.write(pb.show() + '\r')
        sys.stdout.write('\n')
        sys.stdout.flush()
        plt.show()
Exemple #10
0
def main(args):
    filename = args.filename

    idi = utils.CorrelatedData(filename)
    aa = idi.get_antennaarray()
    lo = idi.get_observer()
    lo.date = idi.date_obs.strftime("%Y/%m/%d %H:%M:%S")
    jd = lo.date + astro.DJD_OFFSET
    lst = str(lo.sidereal_time())

    nStand = len(idi.stands)
    nchan = len(idi.freq)
    freq = idi.freq

    print("Raw Stand Count: %i" % nStand)
    print("Final Baseline Count: %i" % (nStand * (nStand - 1) // 2, ))
    print(
        "Spectra Coverage: %.3f to %.3f MHz in %i channels (%.2f kHz/channel)"
        % (freq[0] / 1e6, freq[-1] / 1e6, nchan,
           (freq[-1] - freq[0]) / 1e3 / nchan))
    print("Polarization Products: %i starting with %i" %
          (len(idi.pols), idi.pols[0]))
    print("JD: %.3f" % jd)

    # Pull out something reasonable
    toWork = numpy.where((freq >= args.lower) & (freq <= args.upper))[0]

    print("Reading in FITS IDI data")
    nSets = idi.total_baseline_count // (nStand * (nStand + 1) // 2)
    for set in range(1, nSets + 1):
        print("Set #%i of %i" % (set, nSets))
        fullDict = idi.get_data_set(set)
        dataDict = fullDict.get_uv_range(min_uv=14.0)
        dataDict.sort()

        # Gather up the polarizations and baselines
        pols = dataDict['jd'].keys()
        bls = dataDict['bls'][pols[0]]
        print("The reduced list has %i baselines and %i channels" %
              (len(bls), len(toWork)))

        # Build a list of unique JDs for the data
        jdList = []
        for jd in dataDict['jd'][pols[0]]:
            if jd not in jdList:
                jdList.append(jd)

        # Build the simulated visibilities
        print("Building Model")
        simDict = simVis.build_sim_data(aa,
                                        simVis.SOURCES,
                                        jd=[
                                            jdList[0],
                                        ],
                                        pols=pols,
                                        baselines=bls)

        print("Running self cal.")
        simDict = simDict.sort()
        dataDict = dataDict.sort()
        fixedDataXX, delaysXX = selfcal.delay_only(aa,
                                                   dataDict,
                                                   simDict,
                                                   toWork,
                                                   'xx',
                                                   ref_ant=args.reference,
                                                   max_iter=60)
        fixedDataYY, delaysYY = selfcal.delay_only(aa,
                                                   dataDict,
                                                   simDict,
                                                   toWork,
                                                   'yy',
                                                   ref_ant=args.reference,
                                                   max_iter=60)
        fixedFullXX = simVis.scale_data(fullDict, delaysXX * 0 + 1, delaysXX)
        fixedFullYY = simVis.scale_data(fullDict, delaysYY * 0 + 1, delaysYY)

        print("    Saving results")
        outname = os.path.split(filename)[1]
        outname = os.path.splitext(outname)[0]
        outname = "%s.sc" % outname
        fh = open(outname, 'w')
        fh.write("################################\n")
        fh.write("#                              #\n")
        fh.write("# Columns:                     #\n")
        fh.write("# 1) Stand number              #\n")
        fh.write("# 2) X pol. amplitude          #\n")
        fh.write("# 3) X pol. delay (ns)         #\n")
        fh.write("# 4) Y pol. amplitude          #\n")
        fh.write("# 5) Y pol. delay (ns)         #\n")
        fh.write("#                              #\n")
        fh.write("################################\n")
        for i in xrange(delaysXX.size):
            fh.write("%3i  %.6g  %.6g  %.6g  %.6g\n" %
                     (idi.stands[i], 1.0, delaysXX[i], 1.0, delaysYY[i]))
        fh.close()

        # Build up the images for each polarization
        if args.plot:
            print("    Gridding")
            toWork = numpy.where((freq >= 80e6) & (freq <= 82e6))[0]
            try:
                imgXX = utils.build_gridded_image(fullDict,
                                                  size=80,
                                                  res=0.5,
                                                  pol='xx',
                                                  chan=toWork)
            except:
                imgXX = None

            try:
                imgYY = utils.build_gridded_image(fullDict,
                                                  size=80,
                                                  res=0.5,
                                                  pol='yy',
                                                  chan=toWork)
            except:
                imgYY = None

            try:
                simgXX = utils.build_gridded_image(simDict,
                                                   size=80,
                                                   res=0.5,
                                                   pol='xx',
                                                   chan=toWork)
            except:
                simgXX = None
            try:
                simgYY = utils.build_gridded_image(simDict,
                                                   size=80,
                                                   res=0.5,
                                                   pol='yy',
                                                   chan=toWork)
            except:
                simgYY = None

            try:
                fimgXX = utils.build_gridded_image(fixedFullXX,
                                                   size=80,
                                                   res=0.5,
                                                   pol='xx',
                                                   chan=toWork)
            except:
                fimgXX = None
            try:
                fimgYY = utils.build_gridded_image(fixedFullYY,
                                                   size=80,
                                                   res=0.5,
                                                   pol='yy',
                                                   chan=toWork)
            except:
                fimgYY = None

            # Plots
            print("    Plotting")
            fig = plt.figure()
            ax1 = fig.add_subplot(3, 2, 1)
            ax2 = fig.add_subplot(3, 2, 2)
            ax3 = fig.add_subplot(3, 2, 3)
            ax4 = fig.add_subplot(3, 2, 4)
            ax5 = fig.add_subplot(3, 2, 5)
            ax6 = fig.add_subplot(3, 2, 6)
            for ax, img, pol in zip(
                [ax1, ax2, ax3, ax4, ax5, ax6],
                [imgXX, imgYY, simgXX, simgYY, fimgXX, fimgYY],
                ['XX', 'YY', 'simXX', 'simYY', 'scalXX', 'scalYY']):
                # Skip missing images
                if img is None:
                    ax.text(0.5,
                            0.5,
                            'Not found in file',
                            color='black',
                            size=12,
                            horizontalalignment='center')

                    ax.xaxis.set_major_formatter(NullFormatter())
                    ax.yaxis.set_major_formatter(NullFormatter())

                    ax.set_title("%s @ %s LST" % (pol, lst))
                    continue

                # Display the image and label with the polarization/LST
                out = img.image(center=(80, 80))
                print(pol, out.min(), out.max())
                #if pol == 'scalXX':
                #out = numpy.rot90(out)
                #out = numpy.rot90(out)
                cb = ax.imshow(out,
                               extent=(1, -1, -1, 1),
                               origin='lower',
                               vmin=img.image().min(),
                               vmax=img.image().max())
                fig.colorbar(cb, ax=ax)
                ax.set_title("%s @ %s LST" % (pol, lst))

                # Turn off tick marks
                ax.xaxis.set_major_formatter(NullFormatter())
                ax.yaxis.set_major_formatter(NullFormatter())

                # Compute the positions of major sources and label the images
                compSrc = {}
                ax.plot(0, 0, marker='+', markersize=10, markeredgecolor='w')
                for name, src in simVis.SOURCES.items():
                    src.compute(aa)
                    top = src.get_crds(crdsys='top', ncrd=3)
                    az, alt = aipy.coord.top2azalt(top)
                    compSrc[name] = [az, alt]
                    if alt <= 0:
                        continue
                    ax.plot(top[0],
                            top[1],
                            marker='x',
                            markerfacecolor='None',
                            markeredgecolor='w',
                            linewidth=10.0,
                            markersize=10)
                    ax.text(top[0], top[1], name, color='white', size=12)

                # Add lines of constant RA and dec.
                graticle(ax, lo.sidereal_time(), lo.lat)

            plt.show()

    print("...Done")
Exemple #11
0
def main(args):
    filename = args.filename
    
    idi = utils.CorrelatedData(filename)
    aa = idi.get_antennaarray()
    lo = idi.get_observer()
    
    nStand = len(idi.stands)
    nchan = len(idi.freq)
    freq = idi.freq
    
    print("Raw Stand Count: %i" % nStand)
    print("Final Baseline Count: %i" % (nStand*(nStand-1)/2,))
    print("Spectra Coverage: %.3f to %.3f MHz in %i channels (%.2f kHz/channel)" % (freq[0]/1e6, freq[-1]/1e6, nchan, (freq[1] - freq[0])/1e3))
    try:
        print("Polarization Products: %s" % ' '.join([NUMERIC_STOKES[p] for p in idi.pols]))
    except KeyError:
        # Catch for CASA MS that use a different numbering scheme
        NUMERIC_STOKESMS = {1:'I', 2:'Q', 3:'U', 4:'V', 
                        9:'XX', 10:'XY', 11:'YX', 12:'YY'}
        print("Polarization Products: %s" % ' '.join([NUMERIC_STOKESMS[p] for p in idi.pols]))
        
    print("Reading in FITS IDI data")
    nSets = idi.integration_count
    for set in range(1, nSets+1):
        if args.dataset != -1 and args.dataset != set:
            continue
            
        print("Set #%i of %i" % (set, nSets))
        dataDict = idi.get_data_set(set, min_uv=args.uv_min)
        
        # Build a list of unique JDs for the data
        pols = dataDict.pols
        jdList = [dataDict.mjd + astro.MJD_OFFSET,]
        
        # Find the LST
        lo.date = jdList[0] - astro.DJD_OFFSET
        utc = str(lo.date)
        lst = str(lo.sidereal_time())   # pylint:disable=no-member
        
        # Pull out the right channels
        toWork = numpy.where( (freq >= args.freq_start) & (freq <= args.freq_stop) )[0]
        if len(toWork) == 0:
            raise RuntimeError("Cannot find data between %.2f and %.2f MHz" % (args.freq_start/1e6, args.freq_stop/1e6))
            
        # Integration report
        print("    Date Observed: %s" % utc)
        print("    LST: %s" % lst)
        print("    Selected Frequencies: %.3f to %.3f MHz" % (freq[toWork[0]]/1e6, freq[toWork[-1]]/1e6))
        
        # Prune out what needs to go
        if args.include != 'all' or args.exclude != 'none':
            print("    Processing include/exclude lists")
            dataDict = dataDict.get_antenna_subset(include=args.include, 
                                                   exclude=args.exclude, 
                                                   indicies=False)
            
            ## Report
            for pol in dataDict.pols:
                print("        %s now has %i baselines" % (pol, len(dataDict.baselines)))
                
        # Build up the images for each polarization
        print("    Gridding")
        img1 = None
        lbl1 = 'XX'
        for p in ('XX', 'RR', 'I'):
            try:
                img1 = utils.build_gridded_image(dataDict, size=NPIX_SIDE//2, res=0.5, pol=p, chan=toWork)
                lbl1 = p.upper()
            except:
                pass
                
        img2 = None
        lbl2 = 'YY'
        for p in ('YY', 'LL', 'Q'):
            try:
                img2 = utils.build_gridded_image(dataDict, size=NPIX_SIDE//2, res=0.5, pol=p, chan=toWork)
                lbl2 = p.upper()
            except:
                pass
                
        img3 = None
        lbl3 = 'XY'
        for p in ('XY', 'RL', 'U'):
            try:
                img3 = utils.build_gridded_image(dataDict, size=NPIX_SIDE//2, res=0.5, pol=p, chan=toWork)
                lbl3 = p.upper()
            except:
                pass
                
        img4 = None
        lbl4 = 'YX'
        for p in ('YX', 'LR', 'V'):
            try:
                img4 = utils.build_gridded_image(dataDict, size=NPIX_SIDE//2, res=0.5, pol=p, chan=toWork)
                lbl4 = p.upper()
            except:
                pass
                
        # Plots
        print("    Plotting")
        fig = plt.figure()
        ax1 = fig.add_subplot(2, 2, 1)
        ax2 = fig.add_subplot(2, 2, 2)
        ax3 = fig.add_subplot(2, 2, 3)
        ax4 = fig.add_subplot(2, 2, 4)
        for ax, img, pol in zip([ax1, ax2, ax3, ax4], [img1, img2, img3, img4], [lbl1, lbl2, lbl3, lbl4]):
            # Skip missing images
            if img is None:
                ax.text(0.5, 0.5, 'Not found in file', color='black', size=12, horizontalalignment='center')
                
                ax.xaxis.set_major_formatter( NullFormatter() )
                ax.yaxis.set_major_formatter( NullFormatter() )
                
                if not args.utc:
                    ax.set_title("%s @ %s LST" % (pol, lst))
                else:
                    ax.set_title("%s @ %s UTC" % (pol, utc))
                continue
                
            # Display the image and label with the polarization/LST
            cb = utils.plot_gridded_image(ax, img)
            fig.colorbar(cb, ax=ax)
            if not args.utc:
                ax.set_title("%s @ %s LST" % (pol, lst))
            else:
                ax.set_title("%s @ %s UTC" % (pol, utc))
                
            junk = img.image(center=(NPIX_SIDE//2,NPIX_SIDE//2))
            print("%s: image is %.4f to %.4f with mean %.4f" % (pol, junk.min(), junk.max(), junk.mean()))
            
            # Turn off tick marks
            ax.xaxis.set_major_formatter( NullFormatter() )
            ax.yaxis.set_major_formatter( NullFormatter() )
            
            # Compute the positions of major sources and label the images
            overlay.sources(ax, aa, simVis.SOURCES, label=not args.no_labels)
            
            # Add in the horizon
            overlay.horizon(ax, aa)
            
            # Add lines of constant RA and dec.
            if not args.no_grid:
                if not args.topo:
                    overlay.graticule_radec(ax, aa)
                else:
                    overlay.graticule_azalt(ax, aa)
                    
        plt.show()
        
        if args.fits is not None:
            ## Loop over the images to build up the FITS file
            hdulist = [astrofits.PrimaryHDU(),]
            for img,pol in zip((img1,img2,img3,img4), (lbl1,lbl2,lbl3,lbl4)):
                if img is None:
                    continue
                    
                ### Create the HDU
                try:
                    hdu = astrofits.ImageHDU(data=img.image(center=(NPIX_SIDE//2,NPIX_SIDE//2)), name=pol)
                except AttributeError:
                    hdu = astrofits.ImageHDU(data=img, name=pol)
                    
                ### Add in the coordinate information
                hdu.header['EPOCH'] = 2000.0 + (jdList[0] - 2451545.0) / 365.25
                hdu.header['CTYPE1'] = 'RA---SIN'
                hdu.header['CRPIX1'] = NPIX_SIDE//2+1
                hdu.header['CDELT1'] = -360.0/NPIX_SIDE/numpy.pi
                hdu.header['CRVAL1'] = lo.sidereal_time()*180/numpy.pi	# pylint:disable=no-member
                hdu.header['CTYPE2'] = 'DEC--SIN'
                hdu.header['CRPIX2'] = NPIX_SIDE//2+1
                hdu.header['CDELT2'] = 360.0/NPIX_SIDE/numpy.pi
                hdu.header['CRVAL2'] = lo.lat*180/numpy.pi
                hdu.header['LONPOLE'] = 180.0
                hdu.header['LATPOLE'] = 90.0
                
                ### Add the HDU to the list
                hdulist.append(hdu)
                
            ## Save the FITS file to disk
            hdulist = astrofits.HDUList(hdulist)
            overwrite = False
            if os.path.exists(args.fits):
                yn = input("WARNING: '%s' exists, overwrite? [Y/n]" % args.fits)
                if yn not in ('n', 'N'):
                    overwrite = True
            try:
                hdulist.writeto(args.fits, overwrite=overwrite)
            except IOError as e:
                print("WARNING: FITS image file not saved")
                
    print("...Done")
Exemple #12
0
    def test_selfcal(self):
        """Test running a simple self calibration."""

        for filename, type in zip((idiFile, idiAltFile, uvFile),
                                  ('FITS-IDI', 'Alt. FITS-IDI', 'UVFITS')):
            with self.subTest(filetype=type):
                # Open the file
                idi = utils.CorrelatedData(idiFile)

                # Go for it!
                aa = idi.get_antennaarray()
                ds = idi.get_data_set(1)
                junk = selfcal.phase_only(aa,
                                          ds,
                                          ds,
                                          173,
                                          'XX',
                                          max_iter=1,
                                          verbose=False,
                                          amplitude=True)
                junk = selfcal.phase_only(aa,
                                          ds,
                                          ds,
                                          173,
                                          'XX',
                                          max_iter=1,
                                          verbose=False)
                junk = selfcal.delay_only(aa,
                                          ds,
                                          ds,
                                          173,
                                          'XX',
                                          max_iter=1,
                                          verbose=False,
                                          amplitude=True)
                junk = selfcal.delay_only(aa,
                                          ds,
                                          ds,
                                          173,
                                          'XX',
                                          max_iter=1,
                                          verbose=False)
                junk = selfcal.delay_and_phase(aa,
                                               ds,
                                               ds,
                                               173,
                                               'XX',
                                               max_iter=1,
                                               verbose=False,
                                               amplitude=True)
                junk = selfcal.delay_and_phase(aa,
                                               ds,
                                               ds,
                                               173,
                                               'XX',
                                               max_iter=1,
                                               verbose=False)

                # Error checking
                self.assertRaises(RuntimeError,
                                  selfcal.phase_only,
                                  aa,
                                  ds,
                                  ds,
                                  173,
                                  'YX',
                                  ref_ant=0)
                self.assertRaises(RuntimeError,
                                  selfcal.phase_only,
                                  aa,
                                  ds,
                                  ds,
                                  173,
                                  'YX',
                                  ref_ant=564)

                idi.close()