def inspect_influence(actmat, measmat, apt_mask, infldat=None, what="all", fignum0=1000, store=False, interactive=True, outdir='./'): """ Given influence data, inspect it """ # Check matrix size, measmat should be (n_data, n_meas), actmat should # be (n_act, n_meas). We should have: # n_data > n_meas # n_meas > n_act n_data, n_meas1 = measmat.shape n_act, n_meas2 = actmat.shape assert (n_data > n_meas1), "Measurement matrix wrong, transposed?" assert (n_meas2 > n_act), "Actuation matrix wrong, transposed?" assert (n_meas2 == n_meas1), "Matrices incompatible, not the same number of measurements" if infldat == None: infldat = comp_influence(measmat, actmat) svd_U, svd_s, svd_Vh = infldat['svdcomps'] offsetmeas = infldat['offsetmeas'].ravel() dshape = apt_mask.shape apt_mask_c = im.mk_rad_mask(*dshape) < 0.9 plot_mask = np.ones(apt_mask.shape) plot_mask[apt_mask==False] = np.nan if (what in ["all", "singval"]): plt.figure(fignum0+100); plt.clf() plt.title("Singvals (n=%d, sum=%.4g, c=%.4g)" % (len(svd_s), svd_s.sum(), svd_s[0]/svd_s[-1])) plt.xlabel("Mode [#]") plt.ylabel("Singular value [AU]") plt.plot(svd_s) if (store): plt.savefig(pjoin(outdir, "cal_singvals.pdf")) plt.figure(fignum0+101); plt.clf() plt.title("Singvals [log] (n=%d, sum=%.4g, c=%.4g)" % (len(svd_s), svd_s.sum(), svd_s[0]/svd_s[-1])) plt.xlabel("Mode [#]") plt.ylabel("Singular value [AU]") plt.semilogy(svd_s) if (store): plt.savefig(pjoin(outdir, "cal_singvals_logy.pdf")) if (interactive): raw_input("Continue...") if (what in ["all", "offset"]): # Init new empty image thisvec = np.zeros(dshape) # Fill image with masked vector data thisvec[apt_mask] = offsetmeas imin, imax = offsetmeas.min(), offsetmeas.max() plt.figure(fignum0+200); plt.clf() plt.xlabel("X [pix]") plt.ylabel("Y [pix]") plt.title("Offset phase (system aberration)") plt.imshow(thisvec*plot_mask, vmin=imin, vmax=imax) plt.colorbar() if (store): plt.savefig(pjoin(outdir, "cal_offset_phase.pdf")) if (interactive): raw_input("Continue...") if (what in ["all", "actrec"]): plt.figure(fignum0+250); plt.clf() plt.title("Actuation matrix reconstruction") vmin, vmax = actmat.min(), actmat.max() plt.subplot(131) plt.xlabel("Actuator [id]") plt.ylabel("Measurement [#]") plt.imshow(actmat.T, vmin=vmin, vmax=vmax) plt.subplot(132) plt.xlabel("Actuator [id]") plt.imshow(infldat['actmat_rec'].T, vmin=vmin, vmax=vmax) plt.colorbar() plt.subplot(133) plt.xlabel("Actuator [id]") plt.imshow((actmat[:-1]-infldat['actmat_rec']).T) plt.colorbar() if (store): plt.savefig(pjoin(outdir, "cal_actmat_rec.pdf")) if (interactive): raw_input("Continue...") if (what in ["all", "actmat"]): # Init new empty image thisvec = np.zeros(dshape) for idx, inflvec in enumerate(infldat['inflmat'].T): thisvec[apt_mask] = inflvec.ravel() imin, imax = inflvec.min(), inflvec.max() plt.figure(fignum0+300); plt.clf() plt.xlabel("X [pix]") plt.ylabel("Y [pix]") plt.title("Actuator %d influence" % (idx)) plt.imshow(thisvec*plot_mask, vmin=imin, vmax=imax) plt.colorbar() if (store): plt.savefig(pjoin(outdir, "cal_infl_vec_%d.pdf" % (idx))) if (interactive): if (raw_input("Continue [b=break]...") == 'b'): break if (what in ["all", "sysmodes"]): # Init new empty image thisbase = np.zeros(dshape) for idx, base in enumerate(svd_U.T): thisbase[apt_mask] = base.ravel() imin, imax = base.min(), base.max() plt.figure(fignum0+400); plt.clf() plt.xlabel("X [pix]") plt.ylabel("Y [pix]") plt.title("DM base %d, s=%g (%g)" % (idx, svd_s[idx], svd_s[idx]/svd_s.sum())) plt.imshow(thisbase*plot_mask, vmin=imin, vmax=imax) plt.colorbar() if (store): plt.savefig(pjoin(outdir, "cal_dm_base_vec_%d.pdf" % (idx))) if (interactive): if (raw_input("Continue [b=break]...") == 'b'): break if (what in ["measrec"]): measmat_rec = np.dot(infldat['inflmat'], actmat[:-1]) thismeasrec = np.zeros(dshape) for idx, measvec_rec in enumerate(measmat_rec.T): thismeasrec[apt_mask] = measvec_rec.ravel() imin, imax = measvec_rec.min(), measvec_rec.max() plt.figure(fignum0+500); plt.clf() plt.xlabel("X [pix]") plt.ylabel("Y [pix]") plt.title("influence meas. %d rec" % (idx)) plt.imshow(thismeasrec*plot_mask, vmin=imin, vmax=imax) plt.colorbar() if (store): plt.savefig(pjoin(outdir, "cal_infl_vec_%d_rec.pdf" % (idx))) if (interactive): if (raw_input("Continue [b=break]...") == 'b'): break raw_input("Will now exit and close windows...") for fnum in [100, 101, 200, 250, 300, 400, 500]: plt.figure(fignum0 + fnum); plt.close()
def cam_setup(camidx=0, roi=None, flatf=None, darkf=None, maskshape='all', procd=32, usecam=True, outdir='./', verb=0): """ Setup IEEE1394 camera using Python's binding for OpenCV. Setup will be stored in global CAM_CFG dictionary for use by cam_getimage(). @param camidx Camera index @param roi Region of Interest to use, as (x, y, width, height) @param flatf Flatfield image to use [file] @param darkf Darkfield image to use [file] @param maskshape Shape for processing mask, 'circ' or 'all' @param procd Bitdepth to process images at (32 or 64) @param outdir Directory to store stuff to @param verb Verbosity """ global CAM_CFG if (verb&VERB_M > L_INFO): print "Setting up camera..." if (procd == 64): npdtype = np.float64 cvdtype = cv.IPL_DEPTH_64F else: npdtype = np.float32 cvdtype = cv.IPL_DEPTH_32F if (darkf and os.path.isfile(darkf)): if (verb&VERB_M > L_DEBG): print "Processing dark frames..." # Hard-link to used files for new cache newdarkf = pjoin(outdir, CAM_DARKFIELD) if (os.path.exists(newdarkf)): os.unlink(newdarkf) os.link(darkf, newdarkf) darkim = file.read_file(darkf).astype(npdtype) CAM_CFG['dark'] = cv.fromarray(darkim) if (flatf and os.path.isfile(flatf)): if (verb&VERB_M > L_DEBG): print "Processing flat frame(s)..." newflatf = pjoin(outdir, CAM_FLATFIELD) if (os.path.exists(newflatf)): os.unlink(newflatf) os.link(flatf, newflatf) flatim = file.read_file(flatf).astype(npdtype) CAM_CFG['flat'] = cv.fromarray(flatim) if (CAM_CFG.has_key('dark')): cv.Sub(CAM_CFG['flat'], CAM_CFG['dark'], CAM_CFG['flat']) if (verb&VERB_M > L_XNFO): print "Configuring camera..." if (not CAM_CFG.has_key('window')): CAM_CFG['window'] = 'cam_live' cv.NamedWindow(CAM_CFG['window'], cv.CV_WINDOW_AUTOSIZE) cv.NamedWindow("cam_histogram", cv.CV_WINDOW_AUTOSIZE) CAM_CFG['idx'] = camidx CAM_CFG['roi'] = roi if (usecam): CAM_CFG['handle'] = cv.CaptureFromCAM(camidx) #cv.GetCaptureProperty(CAM_CFG['handle'], cv.CV_CAP_PROP_FPS) cv.SetCaptureProperty(CAM_CFG['handle'], cv.CV_CAP_PROP_FPS, 60) else: CAM_CFG['handle'] = None if (roi): CAM_CFG['dshape'] = (roi[2], roi[3]) elif (usecam): # GetSize returns (width, h), NumPy arrays expect (height, w) rawframe = cv.QueryFrame(CAM_CFG['handle']) CAM_CFG['dshape'] = cv.GetSize(rawframe)[::-1] else: raise ValueError("Need ROI or camera to determine data shape.") CAM_CFG['frame'] = cv.CreateImage(CAM_CFG['dshape'][::-1], cvdtype, 1) if (maskshape == 'circ'): CAM_CFG['mask'] = im.mk_rad_mask(*CAM_CFG['dshape']) < 1 else: CAM_CFG['mask'] = np.ones(CAM_CFG['dshape']).astype(np.bool) CAM_CFG['imask'] = (CAM_CFG['mask'] == False) file.store_file(pjoin(outdir, CAM_APTMASK), CAM_CFG['mask'].astype(np.uint8), clobber=True) if (verb&VERB_M > L_INFO): print "Camera setup complete..." cam_getimage(show=True)
def cam_setup(camidx=0, roi=None, flatf=None, darkf=None, maskshape='all', procd=32, usecam=True, outdir='./', verb=0): """ Setup IEEE1394 camera using Python's binding for OpenCV. Setup will be stored in global CAM_CFG dictionary for use by cam_getimage(). @param camidx Camera index @param roi Region of Interest to use, as (x, y, width, height) @param flatf Flatfield image to use [file] @param darkf Darkfield image to use [file] @param maskshape Shape for processing mask, 'circ' or 'all' @param procd Bitdepth to process images at (32 or 64) @param outdir Directory to store stuff to @param verb Verbosity """ global CAM_CFG if (verb & VERB_M > L_INFO): print "Setting up camera..." if (procd == 64): npdtype = np.float64 cvdtype = cv.IPL_DEPTH_64F else: npdtype = np.float32 cvdtype = cv.IPL_DEPTH_32F if (darkf and os.path.isfile(darkf)): if (verb & VERB_M > L_DEBG): print "Processing dark frames..." # Hard-link to used files for new cache newdarkf = pjoin(outdir, CAM_DARKFIELD) if (os.path.exists(newdarkf)): os.unlink(newdarkf) os.link(darkf, newdarkf) darkim = file.read_file(darkf).astype(npdtype) CAM_CFG['dark'] = cv.fromarray(darkim) if (flatf and os.path.isfile(flatf)): if (verb & VERB_M > L_DEBG): print "Processing flat frame(s)..." newflatf = pjoin(outdir, CAM_FLATFIELD) if (os.path.exists(newflatf)): os.unlink(newflatf) os.link(flatf, newflatf) flatim = file.read_file(flatf).astype(npdtype) CAM_CFG['flat'] = cv.fromarray(flatim) if (CAM_CFG.has_key('dark')): cv.Sub(CAM_CFG['flat'], CAM_CFG['dark'], CAM_CFG['flat']) if (verb & VERB_M > L_XNFO): print "Configuring camera..." if (not CAM_CFG.has_key('window')): CAM_CFG['window'] = 'cam_live' cv.NamedWindow(CAM_CFG['window'], cv.CV_WINDOW_AUTOSIZE) cv.NamedWindow("cam_histogram", cv.CV_WINDOW_AUTOSIZE) CAM_CFG['idx'] = camidx CAM_CFG['roi'] = roi if (usecam): CAM_CFG['handle'] = cv.CaptureFromCAM(camidx) #cv.GetCaptureProperty(CAM_CFG['handle'], cv.CV_CAP_PROP_FPS) cv.SetCaptureProperty(CAM_CFG['handle'], cv.CV_CAP_PROP_FPS, 60) else: CAM_CFG['handle'] = None if (roi): CAM_CFG['dshape'] = (roi[2], roi[3]) elif (usecam): # GetSize returns (width, h), NumPy arrays expect (height, w) rawframe = cv.QueryFrame(CAM_CFG['handle']) CAM_CFG['dshape'] = cv.GetSize(rawframe)[::-1] else: raise ValueError("Need ROI or camera to determine data shape.") CAM_CFG['frame'] = cv.CreateImage(CAM_CFG['dshape'][::-1], cvdtype, 1) if (maskshape == 'circ'): CAM_CFG['mask'] = im.mk_rad_mask(*CAM_CFG['dshape']) < 1 else: CAM_CFG['mask'] = np.ones(CAM_CFG['dshape']).astype(np.bool) CAM_CFG['imask'] = (CAM_CFG['mask'] == False) file.store_file(pjoin(outdir, CAM_APTMASK), CAM_CFG['mask'].astype(np.uint8), clobber=True) if (verb & VERB_M > L_INFO): print "Camera setup complete..." cam_getimage(show=True)
def inspect_influence(actmat, measmat, apt_mask, infldat=None, what="all", fignum0=1000, store=False, interactive=True, outdir='./'): """ Given influence data, inspect it """ # Check matrix size, measmat should be (n_data, n_meas), actmat should # be (n_act, n_meas). We should have: # n_data > n_meas # n_meas > n_act n_data, n_meas1 = measmat.shape n_act, n_meas2 = actmat.shape assert (n_data > n_meas1), "Measurement matrix wrong, transposed?" assert (n_meas2 > n_act), "Actuation matrix wrong, transposed?" assert (n_meas2 == n_meas1 ), "Matrices incompatible, not the same number of measurements" if infldat == None: infldat = comp_influence(measmat, actmat) svd_U, svd_s, svd_Vh = infldat['svdcomps'] offsetmeas = infldat['offsetmeas'].ravel() dshape = apt_mask.shape apt_mask_c = im.mk_rad_mask(*dshape) < 0.9 plot_mask = np.ones(apt_mask.shape) plot_mask[apt_mask == False] = np.nan if (what in ["all", "singval"]): plt.figure(fignum0 + 100) plt.clf() plt.title("Singvals (n=%d, sum=%.4g, c=%.4g)" % (len(svd_s), svd_s.sum(), svd_s[0] / svd_s[-1])) plt.xlabel("Mode [#]") plt.ylabel("Singular value [AU]") plt.plot(svd_s) if (store): plt.savefig(pjoin(outdir, "cal_singvals.pdf")) plt.figure(fignum0 + 101) plt.clf() plt.title("Singvals [log] (n=%d, sum=%.4g, c=%.4g)" % (len(svd_s), svd_s.sum(), svd_s[0] / svd_s[-1])) plt.xlabel("Mode [#]") plt.ylabel("Singular value [AU]") plt.semilogy(svd_s) if (store): plt.savefig(pjoin(outdir, "cal_singvals_logy.pdf")) plt.figure(fignum0 + 102) plt.clf() plt.title("1-singvals cumsum (n=%d, sum=%.4g, c=%.4g)" % (len(svd_s), svd_s.sum(), svd_s[0] / svd_s[-1])) plt.xlabel("Mode [#]") plt.ylabel("Residual singval [AU]") plt.semilogy(1 - svd_s.cumsum() / svd_s.sum()) if (store): plt.savefig(pjoin(outdir, "cal_singvals_cumsum_logy.pdf")) if (interactive): raw_input("Continue...") if (what in ["all", "offset"]): # Init new empty image thisvec = np.zeros(dshape) # Fill image with masked vector data thisvec[apt_mask] = offsetmeas imin, imax = offsetmeas.min(), offsetmeas.max() plt.figure(fignum0 + 200) plt.clf() plt.xlabel("X [pix]") plt.ylabel("Y [pix]") plt.title("Offset phase (system aberration)") plt.imshow(thisvec * plot_mask, vmin=imin, vmax=imax) plt.colorbar() if (store): plt.savefig(pjoin(outdir, "cal_offset_phase.pdf")) if (interactive): raw_input("Continue...") if (what in ["all", "actrec"]): plt.figure(fignum0 + 250) plt.clf() plt.title("Actuation matrix reconstruction") vmin, vmax = actmat.min(), actmat.max() plt.subplot(131) plt.xlabel("Actuator [id]") plt.ylabel("Measurement [#]") plt.imshow(actmat.T, vmin=vmin, vmax=vmax) plt.subplot(132) plt.xlabel("Actuator [id]") plt.imshow(infldat['actmat_rec'].T, vmin=vmin, vmax=vmax) plt.colorbar() plt.subplot(133) plt.xlabel("Actuator [id]") plt.imshow((actmat[:-1] - infldat['actmat_rec']).T) plt.colorbar() if (store): plt.savefig(pjoin(outdir, "cal_actmat_rec.pdf")) if (interactive): raw_input("Continue...") if (what in ["all", "actmat"]): # Init new empty image thisvec = np.zeros(dshape) for idx, inflvec in enumerate(infldat['inflmat'].T): thisvec[apt_mask] = inflvec.ravel() imin, imax = inflvec.min(), inflvec.max() plt.figure(fignum0 + 300) plt.clf() plt.xlabel("X [pix]") plt.ylabel("Y [pix]") plt.title("Actuator %d influence" % (idx)) plt.imshow(thisvec * plot_mask, vmin=imin, vmax=imax) plt.colorbar() if (store): plt.savefig(pjoin(outdir, "cal_infl_vec_%d.pdf" % (idx))) if (interactive): if (raw_input("Continue [b=break]...") == 'b'): break if (what in ["all", "sysmodes"]): # Init new empty image thisbase = np.zeros(dshape) for idx, base in enumerate(svd_U.T): thisbase[apt_mask] = base.ravel() imin, imax = base.min(), base.max() plt.figure(fignum0 + 400) plt.clf() plt.xlabel("X [pix]") plt.ylabel("Y [pix]") plt.title("DM base %d, s=%g (%g)" % (idx, svd_s[idx], svd_s[idx] / svd_s.sum())) plt.imshow(thisbase * plot_mask, vmin=imin, vmax=imax) plt.colorbar() if (store): plt.savefig(pjoin(outdir, "cal_dm_base_vec_%d.pdf" % (idx))) if (interactive): if (raw_input("Continue [b=break]...") == 'b'): break if (what in ["measrec"]): measmat_rec = np.dot(infldat['inflmat'], actmat[:-1]) thismeasrec = np.zeros(dshape) for idx, measvec_rec in enumerate(measmat_rec.T): thismeasrec[apt_mask] = measvec_rec.ravel() imin, imax = measvec_rec.min(), measvec_rec.max() plt.figure(fignum0 + 500) plt.clf() plt.xlabel("X [pix]") plt.ylabel("Y [pix]") plt.title("influence meas. %d rec" % (idx)) plt.imshow(thismeasrec * plot_mask, vmin=imin, vmax=imax) plt.colorbar() if (store): plt.savefig(pjoin(outdir, "cal_infl_vec_%d_rec.pdf" % (idx))) if (interactive): if (raw_input("Continue [b=break]...") == 'b'): break raw_input("Will now exit and close windows...") for fnum in [100, 101, 102, 200, 250, 300, 400, 500]: plt.figure(fignum0 + fnum) plt.close()