Example #1
0
def extract_corrections(xds_path):
    """ Extract details for geometrical corrections and a mask of untrusted detector regions. 
    Save a .png file of the latter; assumes folder ./checks exists. """

    # generate boolean mask in shape of detector from INIT.LP, with False indicating untrusted pixel
    filename = xds_path + "INIT.LP"
    mask = np.ones(system['shape'], dtype = bool)

    with open(filename, "r") as f:
        
        content = f.readlines()
        
        # mask untrusted rows and columns of detector
        corners = np.asarray([s.strip('\n').split()[-6:-2] for s in content if "UNTRUSTED_RECTANGLE" in s], dtype=float).astype(int)
        for corner in corners:
            if corner[0] == 0:
                for i in range(corner[2], corner[3]):
                    mask[i] = False
            if corner[2] == 0:
                for i in range(corner[0], corner[1]):
                    mask[:,i] = False

        # mask shadow of beamstop arm if it's marked as an untrusted region by XDS
        if any("UNTRUSTED_QUADRILATERAL" in s for s in content):
            vertices = np.asarray([s.strip('\n').split()[-10:-2] for s in content if "UNTRUSTED_QUADRILATERAL" in s][0], dtype=int)
            bbPath = mplPath.Path(np.array([[vertices[0], vertices[1]],
                                            [vertices[2], vertices[3]],
                                            [vertices[4], vertices[5]],
                                            [vertices[6], vertices[7]],]))
            for x in range(mask.shape[1]):
                for y in range(mask.shape[0]):
                    if bbPath.contains_point((x, y)):
                        mask[y, x] = False
        
        # mask beamstop if marked as an untrusted region by XDS
        ebounds = [s.strip('\n').split()[1:5] for s in content if "UNTRUSTED_ELLIPSE" in s][0]
        ebounds = np.array([float(eb) for eb in ebounds])

        xwidth, ywidth = ebounds[1] - ebounds[0], ebounds[3] - ebounds[2]
        center = np.array([int(xwidth/2.0 + ebounds[0]), int(ywidth/2.0 + ebounds[2])])
        e = Ellipse(xy=center, width=xwidth, height=ywidth)
        for xpoint in np.arange(ebounds[0]-5, ebounds[1]+5):
            for ypoint in np.arange(ebounds[2]-5, ebounds[3]+5):
                if e.contains_point((xpoint, ypoint)):
                    mask[int(ypoint), int(xpoint)] = False

        system['mask'] = mask
        
    # extract parameters for parallax correction
    if 'parallax' in system['corrections']:
        
        filename = xds_path + "XYCORR.LP"
        with open(filename, "r") as f:
            
            content = f.readlines()
            
            # attentuation coefficient, mu, in units of m^{-1}; thickness, t0, in units of meters
            system['mu'] = 1000*float([s.strip('\n').split()[-1] for s in content if "SILICON" in s][0]) 
            system['t0'] = 0.001*float([s.strip('\n').split()[-1] for s in content if "SENSOR_THICKNESS" in s][0]) 

    # extract polarization fraction and check that plane normal is aligned along y
    if 'polarization' in system['corrections']:
        
        filename = xds_path + "CORRECT.LP"
        with open(filename, "r") as f:

            content = f.readlines()
            system['pf'] = float([s.strip('\n').split()[-1] for s in content if "FRACTION_OF_POLARIZATION" in s][0]) 
            pol_axis = np.asarray([s.strip('\n').split()[1:] for s in content if "POLARIZATION_PLANE_NORMAL" in s][0], dtype=float)

            try:
                assert pol_axis[0]==0 and pol_axis[1]==1 and pol_axis[2]==0
            except:
                "Polarization axis unexpected and flipped relative to Indexer.py"

    return
                ax.text(x - 15, y, len(pixels[0]) - i, c='k',
                        fontsize=15)  #shadow

            e = Ellipse((x, y),
                        l,
                        w,
                        angle=pa - 90,
                        linewidth=2,
                        edgecolor='k',
                        facecolor='none')
            es.append(e)
        matches = [[] for e in es]
        for i, e in enumerate(es):
            #print(e.contains_points(list(zip(*ca_pixels))))
            for j, (x, y) in enumerate(zip(*ca_pixels)):
                if e.contains_point([x, y]):
                    matches[i].append(j)
            if debug:
                ax.add_patch(e)
        matches = np.array(matches)

        ##### Remove duplicate matches
        len_matches = [len(l) for l in matches]
        len_matches_ranked = np.argsort(len_matches)
        c = Counter(list(pinklib.postprocessing.flatten(matches)))
        new_matches = [[] for e in es]

        dups = []
        for i, m in enumerate(matches[len_matches_ranked]):
            for mm in m:
                if c[mm] < 2:
Example #3
0
    logging.debug("Plotting footprint: %s"%opts.footprint)
    proj = safe_proj(m,perim['ra'],perim['dec'])
    m.plot(*proj,**ft_kwargs)

    if opts.footprint == 'des':
        # Plot the SN fields
        logging.debug("Plotting supernova fields.")
         
        # This does the projection correctly, but fails at boundary
        sn_kwargs = dict(facecolor='none',edgecolor=ft_kwargs['color'],zorder=exp_zorder-1)
        # Check that point inside boundary
        fact = 0.99
        boundary = Ellipse((m.rmajor,m.rminor),2*(fact*m.rmajor),2*(fact*m.rminor))
                           
        for v in SN.values():
            if not boundary.contains_point(m(*v)): continue
            m.tissot(v[0],v[1],1.0,100,**sn_kwargs)
         
        # The SN labels
        sntxt_kwargs = dict(zorder=exp_zorder-1,fontsize=12,
                            bbox=dict(boxstyle='round,pad=0',fc='w',ec='none',
                                      alpha=0.25))
        for k,v in SN_LABELS.items():
            ax.annotate(k,m(*v),**sntxt_kwargs)

    # Annotate with some information
    logging.debug("Adding info text.")
    bbox_props = dict(boxstyle='round', facecolor='white')
    textstr= "%s %s\n"%("UTC:",utc.strftime('%Y-%m-%d %H:%M:%S'))
    textstr+="%s %i (%s)\n"%("Exposure:",expnum[idx],band[idx])
    textstr+="%s %i\n"%("NExp:",opts.numexp)