def match_pinholes(translationPass,holeSpacingPass,barrelCenterPass,barrelAmountPass,rotationAnglePass,writeoutString='test',plotTitleString='test',plot=True):

    # write the git hash
    write_hash('git_hash_match_pinholes.txt')

    # read in median image of pinholes
    hdul = fits.open(calibrated_pinholes_data_stem) 
    imagePinholes = hdul[0].data.copy()
    
    # make model pinhole locations: distorted and undistorted
    coordsModel_d, coordsModel_not_d = find_pinhole_centroids.put_down_grid_guesses(
        translationPass,
        holeSpacingPass,
        barrelCenterPass,
        barrelAmountPass,
        rotationAnglePass) 

    # find empirical pinhole locations
    coordsEmpirical = find_pinhole_centroids.find_psf_centers(
        imagePinholes,
        20.,
        30000.)

    # option for adding in some additional points manually
    ##xCoordsMissed = [71.774,697.353,1460.66]
    ##yCoordsMissed = [1267.57,1404.06,737.932]
    '''
    xCoordsFound = np.concatenate((xCoordsFoundAutomated,
                               xCoordsMissed),
                              axis=0)
    yCoordsFound = np.concatenate((yCoordsFoundAutomated,
                               yCoordsMissed),
                              axis=0)
    '''

    # match and sort the model coordinates (distorted and undistorted) with the empirical pinhole coordinates
    coordsModel_d_matched, coordsModel_not_d_matched, coordsEmpirical_matched = find_pinhole_centroids.match_model_empirical(
        coordsModel_d,
        coordsModel_not_d,
        coordsEmpirical,
        imagePinholes,
        plotTitleString,
        plot=plot)

    # pickle
    picklename='pinhole_coordinates_'+writeoutString+'.pkl'
    fo=open(picklename,'wb')
    pickle.dump({'coordsModel_d_matched':coordsModel_d_matched,
                 'coordsModel_not_d_matched':coordsModel_not_d_matched, 
                 'coordsEmpirical_matched':coordsEmpirical_matched},
                 fo)
    fo.close()

    print('------------------------------')
    print('Saved pinhole grid info to:')
    print(picklename)
    print('------------------------------')
def find_stars(dateString, number_of_dithers):

    star_coords_every_dither = {
    }  # initialize dictionary to hold the coords of found stars

    # initialize dictionary to contain x,y of stars in pixel space
    dictStars = {}

    for ditherPos in range(0, number_of_dithers):
        print("------------------------------")
        print("Finding star positions in dither position " + str(ditherPos) +
              " ...")

        # read in image and header
        imageMedian, header = fits.getdata(
            calibrated_trapezium_data_stem + 'step04_ditherMedians/lm_' +
            dateString + '_dither_' + '%02i' % ditherPos + '.fits',
            0,
            header=True)

        # find star locations; input parameters may need some fine-tuning to get good results
        coordsAsterism = find_pinhole_centroids.find_psf_centers(
            imageMedian, 20., 800.)
        coordsAsterismBright = find_pinhole_centroids.find_psf_centers(
            imageMedian, 20.,
            3000.)  # this is just for guiding the eye in identifying the stars

        if (len(coordsAsterism) >
                1):  # if there is >1 star, there are >=1 baselines
            '''
            import ipdb; ipdb.set_trace()
            star_coords_every_dither[keyName] = np.transpose([coordsAsterism[:,0], coordsAsterism[:,1]])
            '''
            indicesArray = np.arange(np.size(coordsAsterism[:, 0]))
            print("------------------------------")
            print(
                "Please check the plot and note the indices from among the printed star positions which are TRUE "
                "stars and are also IDENTIFIABLE (i.e., their RA and DEC is known. Then close the plot to continue."
            )
            print("------------------------------")
            print('Index, x, y:')
            dataFrame = pd.DataFrame(coordsAsterism, columns=['[x]', '[y]'])
            print(dataFrame)
            #print(np.transpose([indicesArray,coordsAsterism[:,0],coordsAsterism[:,1]]))

            # plots for cross-checking found centroids with true stars (save plots manually as desired)
            plt.imshow(imageMedian, origin="lower", cmap="gray")
            plt.scatter(coordsAsterism[:, 0], coordsAsterism[:, 1])
            #import ipdb; ipdb.set_trace()
            [
                plt.annotate(str(dataFrame.index.values[i]),
                             (coordsAsterism[i, 0], coordsAsterism[i, 1]),
                             fontsize=20,
                             color="white")
                for i in range(len(dataFrame.index.values))
            ]  # put index numbers next to star
            plt.scatter(coordsAsterismBright[:, 0],
                        coordsAsterismBright[:, 1],
                        s=60,
                        color="yellow")
            plt.title(
                "LMIRCam Trapezium observation, UT 2017 Nov 6\ndither position "
                + "%02i" % ditherPos)
            plt.show()

            # which coordinates should be pickled?
            print("------------------------------")
            print(
                'Type the indices, separated by spaces, of the elements that are good'
            )
            goodPts = [int(x) for x in input().split()]  # user inputs
            print("------------------------------")
            print(
                "Type the star names (in the above order, separated by spaces) as per the naming convention in star_coords.csv"
            )
            namesGoodPts = [str(x) for x in input().split()]  # user inputs
            print("------------------------------")

            # append the coordinate info
            keyName = "dither_pos_" + "%02i" % ditherPos  # name of dictionary key for this dither
            dictStars[keyName] = [goodPts, namesGoodPts, dataFrame]

        else:
            print('Did not find >=1 stellar pairs!'
                  )  # number of baselines is zero
            print("------------------------------")

    # pickle
    pickle.dump(dictStars, open("identified_stars_" + dateString + ".p", "wb"))
    print("Star dictionary pickled as " + "identified_stars_" + dateString +
          ".p")
    print("------------------------------")
Exemplo n.º 3
0
def find_stars(dateString,number_of_dithers):

    star_coords_every_dither = {} # initialize dictionary to hold the coords of found stars

    # initialize dictionary to contain x,y of stars in pixel space
    dictStars = {}

    # obtain the list of files which have been dewarped and de-rotated
    # according to the PA in the FITS headers
    asterism_frames_directory_retrieve = str(config["data_dirs"]["DIR_ASTERISM_DEROT"])
    asterism_frames_post_derot_names = list(glob.glob(os.path.join(asterism_frames_directory_retrieve, "*.fits")))

    for ditherPos in range(0,len(asterism_frames_post_derot_names)):
        print("------------------------------")
        print("Finding star positions in dither position "+str(ditherPos)+" ...")

        # read in image and header
        imageMedian, header = fits.getdata(asterism_frames_post_derot_names[ditherPos],
                                           0, header=True)
        
        # find star locations; input parameters may need some fine-tuning to get good results
        coordsAsterism = find_pinhole_centroids.find_psf_centers(imageMedian,20.,800.)
        coordsAsterismBright = find_pinhole_centroids.find_psf_centers(imageMedian,20.,3000.) # this is just for guiding the eye in identifying the stars
        
        if (len(coordsAsterism)>1): # if there is >1 star, there are >=1 baselines

            '''
            import ipdb; ipdb.set_trace()
            star_coords_every_dither[keyName] = np.transpose([coordsAsterism[:,0], coordsAsterism[:,1]])
            '''
            indicesArray = np.arange(np.size(coordsAsterism[:,0]))
            print("------------------------------")
            print("Please check the plot and note the indices from among the printed star positions which are TRUE "
                  "stars and are also IDENTIFIABLE (i.e., their RA and DEC is known. Then close the plot to continue.")
            print("------------------------------")
            print('Index, x, y:')
            dataFrame = pd.DataFrame(coordsAsterism, columns=['[x]','[y]'])
            print(dataFrame)
            #print(np.transpose([indicesArray,coordsAsterism[:,0],coordsAsterism[:,1]]))
        
            # plots for cross-checking found centroids with true stars (save plots manually as desired)
            plt.imshow(imageMedian, origin="lower", cmap="gray", vmin=0, vmax=1500)
            plt.scatter(coordsAsterism[:,0], coordsAsterism[:,1], color="yellow", label="Questionable detections")
            #import ipdb; ipdb.set_trace()
            # put index numbers next to star
            [plt.annotate(str(dataFrame.index.values[i]), (coordsAsterism[i,0], coordsAsterism[i,1]), fontsize=20, color="white") for i in range(len(dataFrame.index.values))] 
            plt.scatter(coordsAsterismBright[:,0], coordsAsterismBright[:,1], s=60, color="orange", label="Strong detections")
            plt.title("LMIRCam Trapezium observation, "+dateString+
                      "\n"+str(os.path.basename(asterism_frames_post_derot_names[ditherPos])))
            plt.legend()
            plt.show()

            # which coordinates should be pickled?
            print("------------------------------")
            print('Type the indices, separated by spaces, of the elements that are good')
            goodPts = [int(x) for x in input().split()] # user inputs
            print("------------------------------")
            print("Type the star names (in the above order, separated by spaces) as per the naming convention in star_coords.csv")
            namesGoodPts = [str(x) for x in input().split()] # user inputs
            print("------------------------------")

            # append the coordinate info
            keyName = "dither_pos_"+"%02i"%ditherPos # name of dictionary key for this dither
            dictStars[keyName] = [goodPts, namesGoodPts, dataFrame]

        else:
            print('Did not find >=1 stellar pairs!') # number of baselines is zero
            print("------------------------------")
            
    # pickle
    pickle.dump(dictStars, open("identified_stars_"+dateString+".p", "wb"))
    print("Star dictionary pickled as "+"identified_stars_"+dateString+".p")
    print("------------------------------")
Exemplo n.º 4
0
from astrom_lmircam_soln import dewarp
from astrom_lmircam_soln import make_barb_plot
from astropy.io import fits
import matplotlib.pyplot as plt
import pickle


#####################################################################
# RETRIEVE MEDIAN PINHOLE GRID IMAGE, FIND PINHOLE CENTERS

# (note this section will require multiple run-throughs until optimal parameters are specified: the ideal grid coords, the missed pinhole coords, etc.)

hdul = fits.open(calibrated_pinholes_data_stem+'pinhole_image_median_vignettingBlocked.fits') # median image of pinholes, with vignetted regions masked
imagePinholes = hdul[0].data.copy()
xCoordsIdealFullGrid, yCoordsIdealFullGrid = find_pinhole_centroids.put_down_grid_guesses(48.0,0.65) # sets down an 'ideal' set of pinholes made to match the real pinholes as closely as possible
xCoordsFoundAutomated, yCoordsFoundAutomated = find_pinhole_centroids.find_psf_centers(imagePinholes,20.,50000.) # finds the actual st of pinholes

# manually-found locations of pinholes that the above routine missed
xCoordsMissed = [71.774,697.353,1460.66]
yCoordsMissed = [1267.57,1404.06,737.932]

# remove subset of pinhole guesses that are in the vignetted region
xCoordsIdeal = xCoordsIdealFullGrid[np.where(np.logical_or(xCoordsIdealFullGrid>36,
                                                               yCoordsIdealFullGrid>760))]
yCoordsIdeal = yCoordsIdealFullGrid[np.where(np.logical_or(xCoordsIdealFullGrid>36,
                                                               yCoordsIdealFullGrid>760))]

# concatenate arrays
xCoordsFound = np.concatenate((xCoordsFoundAutomated,
                               xCoordsMissed),
                              axis=0)
Exemplo n.º 5
0
import matplotlib.pyplot as plt
import pickle

#####################################################################
# RETRIEVE MEDIAN PINHOLE GRID IMAGE, FIND PINHOLE CENTERS

# (note this section will require multiple run-throughs until optimal parameters are specified: the ideal grid coords, the missed pinhole coords, etc.)

hdul = fits.open(calibrated_pinholes_data_stem +
                 'pinhole_image_median_vignettingBlocked.fits'
                 )  # median image of pinholes, with vignetted regions masked
imagePinholes = hdul[0].data.copy()
xCoordsIdealFullGrid, yCoordsIdealFullGrid = find_pinhole_centroids.put_down_grid_guesses(
    48.0, 0.65
)  # sets down an 'ideal' set of pinholes made to match the real pinholes as closely as possible
xCoordsFoundAutomated, yCoordsFoundAutomated = find_pinhole_centroids.find_psf_centers(
    imagePinholes, 20., 50000.)  # finds the actual st of pinholes

# manually-found locations of pinholes that the above routine missed
xCoordsMissed = [71.774, 697.353, 1460.66]
yCoordsMissed = [1267.57, 1404.06, 737.932]

# remove subset of pinhole guesses that are in the vignetted region
xCoordsIdeal = xCoordsIdealFullGrid[np.where(
    np.logical_or(xCoordsIdealFullGrid > 36, yCoordsIdealFullGrid > 760))]
yCoordsIdeal = yCoordsIdealFullGrid[np.where(
    np.logical_or(xCoordsIdealFullGrid > 36, yCoordsIdealFullGrid > 760))]

# concatenate arrays
xCoordsFound = np.concatenate((xCoordsFoundAutomated, xCoordsMissed), axis=0)
yCoordsFound = np.concatenate((yCoordsFoundAutomated, yCoordsMissed), axis=0)
Exemplo n.º 6
0
import photutils
from photutils import DAOStarFinder

number_of_dithers = 18 # number of dither positions over the asterism
star_coords_every_dither = {} # initialize dictionary to hold the coords of found stars

for ditherPos in range(0,number_of_dithers):
    print("Finding star positions in dither position "+str(ditherPos)+" ...")

    # read in image and header
    imageMedian, header = fits.getdata(calibrated_trapezium_data_stem+
                                       'step04_ditherMedians/median_dither_'+'%02i'%ditherPos+'.fits',
                                       0, header=True)
    
    keyName = "dither_pos_"+str(ditherPos)

    # find star locations; input parameters may need some find-tuning to get good results
    xCoordsAsterism, yCoordsAsterism = find_pinhole_centroids.find_psf_centers(imageMedian,20.,15000.) 
    star_coords_every_dither[keyName] = np.transpose([xCoordsAsterism, yCoordsAsterism])
    print(np.transpose([xCoordsAsterism,yCoordsAsterism]))
    print("Please check the plot and note true positives among the printed star positions. Close the plot to continue.")
    
    # plots for cross-checking found centroids with true stars (save plots manually as desired)
    plt.imshow(imageMedian, origin="lower")
    plt.scatter(xCoordsAsterism, yCoordsAsterism)
    plt.title("LMIRCam Trapezium observation, UT 2016 Nov 12\ndither position "+"%02i"%ditherPos)
    plt.show()
    
# optional: save centroids as a FYI pickle binary file (remember: some coordinates are false positives! need to manually check)
#pickle.dump(star_coords_every_dither, open("centroid_coords_trapezium_ut_2016_nov_12.p", "wb"))