def run(configfilename, configspecfile): hardwareconfigfile = 'speckle_instruments.ini' config = ConfigObj(configfilename, configspec=configspecfile) val = Validator() check = config.validate(val) centx = config['IM_PARAMS']['centerx'] centy = config['IM_PARAMS']['centery'] lambdaoverd = config['IM_PARAMS']['lambdaoverd'] regionfilename = config['CONTROLREGION']['filename'] # pharo = hardware.fake_pharo() #Real thing innerlam = config['CONTROLREGION']['innerannulus'] outerlam = config['CONTROLREGION']['outerannulus'] # pharo = hardware.PHARO_COM('PHARO', # configfile = hardwareconfigfile) #LOAD P3K HERE pharo = hardware.fake_pharo() print("Retrieving bgd, flat, badpix") # bgds = flh.setup_bgd_dict(config) fake_bgds = {'bkgd':np.zeros((1024, 1024)), 'masterflat':np.ones((1024, 1024)), 'badpix': np.zeros((1024, 1024))} print "WARNING: USING FAKE BGDS" bgds = fake_bgds.copy() firstim = pharo.take_src_return_imagedata(exptime = 4) image = pre.equalize_image(firstim, **bgds) image = firstim ann, verts = define_control_annulus(image, cx = centx, cy = centy, rad_in = lambdaoverd*innerlam, rad_out= lambdaoverd*outerlam) flh.writeout(ann*1.0, regionfilename) config['CONTROLREGION']['verticesx'] = [centx]+[x[0] for x in verts] config['CONTROLREGION']['verticesy'] = [centy]+[y[1] for y in verts] config.write() print "Configuration file written to "+config.filename
all_delta_i_y = np.zeros(Nstep) k0=98 for k in range(0,Nstep): print("k="+str(k)) print 'total offset', total_offset/lambdaoverd_arc, 'lbd/D' if lab: if k > 0 : p3k.sci_offset_left(pitch) while not(p3k.isReady()) : time.sleep(.1) img = pharo.take_src_return_imagedata() img = pre.equalize_image(img, bkgd = bgd) else : dir = '/home/ehuby/dev/repos/speckle_nulling/pharoimages/' img_file_name = dir + 'ph'+str(k+k0).zfill(4)+'.fits' img = pre.combine_quadrants(pf.open(img_file_name)) total_offset = k * pitch tip_tilt[k] = total_offset/lambdaoverd_arc # derive center # spotcenters = qacits.fit_satellite_centers(img, spotcenters, window=20) # centerx, centery = np.mean(spotcenters, axis = 0) # centerx, centery = 512, 512 delta_i_x, delta_i_y = qacits.get_delta_I(img, cx = centerx, cy=centery,
####MAIN LOOP STARTS HERE##### print "BEGINNING NULLING LOOP" for iteration in range(N_iterations): itcounter.append(iteration) if use_centoffs == False: current_flatmap = p3k.grab_current_flatmap() if use_centoffs == True: current_centoffs = p3k.grab_current_centoffs() print "Taking image of speckle field" raw_im = pharo.take_src_return_imagedata(exptime=exp) result_imagecube.update(raw_im) field_im = pre.equalize_image(raw_im, **bgds) clean_imagecube.update(field_im) field_ctrl = field_im * controlregion meanfluxes.append(np.mean(field_ctrl[field_ctrl > 0])) maxfluxes.append(np.max(field_ctrl[field_ctrl > 0])) totalfluxes.append(np.sum(field_ctrl)) rmsfluxes.append( np.std(field_ctrl[field_ctrl > 0]) / config['NULLING']['referenceval']) ax3.plot(itcounter, rmsfluxes) #w5 = plt.plot(itcounter, maxfluxes) #w5 = plt.plot(itcounter, totalfluxes) ax1.set_title('Iteration: ' + str(iteration) + ', Mean: ' + str(meanfluxes[iteration]) + ', Max: ' + str(maxfluxes[iteration]))
config = ConfigObj(configfilename, configspec=configspecfile) val = Validator() check = config.validate(val) regionfilename = config['CONTROLREGION']['filename'] #pharo = hardware.fake_pharo() #Real thing pharo = hardware.PHARO_COM('PHARO', configfile = hardwareconfigfile) #LOAD P3K HERE print("Retrieving bgd, flat, badpix") bgds = flh.setup_bgd_dict(config) firstim = pharo.take_src_return_imagedata(exptime = 4) image = pre.equalize_image(firstim, **bgds) image = firstim centx = config['IM_PARAMS']['centerx'] centy = config['IM_PARAMS']['centery'] #p , verts= define_control_region(image) ann, verts = define_control_annulus(image, cx = centx, cy = centy) flh.writeout(ann*1.0, regionfilename) config['CONTROLREGION']['verticesx'] = [centx]+[x[0] for x in verts] config['CONTROLREGION']['verticesy'] = [centy]+[y[1] for y in verts] config.write() print "Configuration file written to "+config.filename controlimage = ann*image plt.imshow(controlimage) plt.title("This is your control region"+ "\n saved as "+regionfilename)
Ki = config['PID']['Ki'] Kd = config['PID']['Kd'] #ipdb.set_trace() # PID loop p = pid.PID(P=np.array([Kp, Kp]), I=np.array([Ki, Ki]), D=np.array([Kd, Kd]), Deadband=.001) p.setPoint(np.array[0., 0.]) c = 1 while True: img = pharo.get_image() img = pre.equalize_image(img, masterflat=flat, bkgd=bgd, badpix=bpix) # Derive center of the image from the satellite spots # if c == 1 : # spotcenters = dm.get_satellite_centroids(img) # else : # spotcenters = fit_satellite_centers(img, spotcenters, window=20) spotcenters = fit_satellite_centers(img, spotcenters, window=20) centerx, centery = np.mean(spotcenters, axis=0) #centerx, centery = 512, 512 print centerx, centery if c == 3: ipdb.set_trace()
# defining the zone of interest for QACITS quad_width = config['QACITS_params']['quad_width'] # in lambda/D inner_rad = config['QACITS_params']['inner_rad'] # in lambda/D quad_width_pix = quad_width * lambdaoverd # in pixels inner_rad_pix = inner_rad * lambdaoverd # in pixels zone_type = config['QACITS_params']['type'] # 1) Take an image with the centered coronagraph as reference if onsky: img_ref = pharo.take_src_return_imagedata() img_ref = pre.equalize_image(img_ref, **bgds) else: img_ref = pre.combine_quadrants(pf.open(ref_filename)) img_ref = img_ref - bgd1 ix_ref , iy_ref = qacits.get_delta_I(img_ref, cx=centerx, cy=centery, quad_width_pix = quad_width_pix, inner_rad_pix = quad_width_pix, zone_type=zone_type) #ipdb.set_trace() # Apply sine waves if onsky : initial_flatmap = np.zeros((66, 66)) initial_flatmap = p3k.grab_current_flatmap() status = p3k.load_new_flatmap(FM.convert_hodm_telem(initial_flatmap))
#Real thing pharo = hardware.PHARO_COM('PHARO', configfile=hardwareconfigfile) #LOAD P3K HERE p3k = hardware.P3K_COM('P3K_COM', configfile=hardwareconfigfile) #LOAD CURRENT FLATMAP initial_flatmap = np.zeros((66, 66)) initial_flatmap = p3k.grab_current_flatmap() status = p3k.load_new_flatmap(fmap.convert_hodm_telem(initial_flatmap)) im = pharo.take_src_return_imagedata(exptime=4) #works, tested bck = pre.combine_quadrants( pf.open( '/data1/home/aousr/Desktop/speckle_nulling/pharoflatsdarks/medbackground.fits' )) im = pre.equalize_image(im, bkgd=bck) #im = pre.combine_quadrants(pf.open('/data1/home/aousr/Desktop/speckle_nulling/pharoimages/ph0186.fits')) #Replacing Mike's CV2 speckle detection with simple max search and gaussian fit #speckleslist = detect_speckles.detect_speckles(im, configfile = configfilename) #speckleobjects = [speckle(im, contour, im_params) for contour in speckleslist] speckle_positions, speckle_amplitude = detect_speckles.detect_speckles2( im, configfile=configfilename, configspecfile=configspecfile) #speckleobjects = [speckle2(im, pos, im_params) for pos in speckle_positions] speckleobjects = [] for k in range(speckle_positions.shape[1]): speckleobjects.append(speckle2(im, speckle_positions[:, k], im_params)) controlregion_tmp = pf.open('controlregion.fits')[0].data
def speck_killing_loop(wfo): #configfilename = 'speckle_null_config.ini' #config = ConfigObj(configfilename) configfilename = tp.FPWFSdir + 'speckle_null_config_Rupe.ini' hardwareconfigfile = tp.FPWFSdir + 'speckle_instruments.ini' configspecfile = tp.FPWFSdir + 'speckle_null_config.spec' print(configfilename) config = ConfigObj(configfilename, configspec=configspecfile) val = Validator() check = config.validate(val) #pharo = hardware.PHARO_COM('PHARO', # configfile = hardwareconfigfile) #p3k = hardware.P3K_COM('P3K_COM', configfile = hardwareconfigfile) camera = hardware.camera() ao = hardware.ao() apmask = False if not apmask: aperturemask = np.ones((66, 66)) if apmask: aperturemask = dm.annularmask(66, 12, 33) # nulled_field = None im_params = config['IM_PARAMS'] null_params = config['NULLING'] abc = config['INTENSITY_CAL']['abc'] use_centoffs = config['NULLING']['cent_off'] #bgds = flh.setup_bgd_dict(config) fake_bgds = { 'bkgd': np.zeros((tp.grid_size, tp.grid_size)), 'masterflat': np.ones((tp.grid_size, tp.grid_size)), 'badpix': np.zeros((tp.grid_size, tp.grid_size)) } print("WARNING: USING FAKE BGDS") bgds = fake_bgds.copy() # controlregion = pf.open(tp.FPWFSdir+config['CONTROLREGION']['filename'])[0].data # controlregion = controlregion[512-int(tp.grid_size/2):512+int(tp.grid_size/2), 512-int(tp.grid_size/2):512+int(tp.grid_size/2)] # controlregion = np.roll(controlregion, 15) # controlregion[:,0:70] = 0 # controlregion[:80] = 0 # controlregion[-80:] = 0 controlregion = np.zeros((tp.grid_size, tp.grid_size)) controlregion[50:80, 35:50] = 1 boarder = get_ctrlrgnBoarder(controlregion) quicklook_im(controlregion, logAmp=False) # plt.show(block=True) #Notes==>scale exptime in snr exp = config['INTENSITY_CAL']['exptime'] #Setup # initial_flatmap = ao.grab_current_flatmap() # initial_centoffs= ao.grab_current_centoffs() defaultim = np.ones((tp.grid_size, tp.grid_size)) vertsx = config['CONTROLREGION']['verticesx'] vertsy = config['CONTROLREGION']['verticesy'] # plt.ion() fig = plt.figure(figsize=(12, 12)) ax1 = plt.subplot2grid((4, 4), (0, 0), rowspan=2, colspan=2) ax2 = plt.subplot2grid((4, 4), (0, 2), rowspan=2, colspan=2) ax3 = plt.subplot2grid((4, 4), (3, 0)) ax4 = plt.subplot2grid((4, 4), (2, 2), rowspan=2, colspan=2) #ax5 = plt.subplot2grid((4,4),(3,2)) # ax1b =plt.subplot2grid((4,4),(0, 0), rowspan =2, colspan = 2) title = fig.suptitle('Speckle destruction') ax1.set_title('Image') ax2.set_title('Control region') ax3.set_title('RMS in region') ax4.set_title('Image') #ax5.set_title('Intensity') w1 = ax1.imshow(np.log10(np.abs(defaultim)) + boarder, origin='lower', interpolation='nearest') current_cmap = cm.get_cmap() current_cmap.set_bad(color='white') # w1b = ax1b.imshow(boarder*10, origin='lower', interpolation = 'none') # ax1.set_xlim(min(vertsx), max(vertsx)) # ax1.set_ylim(min(vertsy), max(vertsy)) #ax1.set_ylim(int(im_params['centery'])-25, int(im_params['centery']+50)) w2 = ax2.imshow(np.log(np.abs(controlregion * defaultim)), origin='lower', interpolation='nearest') # ax2.set_xlim(min(vertsx), max(vertsx)) # ax2.set_ylim(min(vertsy), max(vertsy)) w3 = ax3.plot([], []) ax3.set_xlim(0, 10) w4, = ax4.plot(np.abs(defaultim[64])) # w4 = ax4.imshow(np.log10(np.abs(defaultim))+boarder, origin='lower', interpolation = 'nearest') current_cmap = cm.get_cmap() current_cmap.set_bad(color='white') N_iterations = 10 itcounter = [] maxfluxes = [] meanfluxes = [] totalfluxes = [] rmsfluxes = [] #w5 = ax5.plot(np.arange(10)*0, np.arange(10)*0) # w4 = ax4.imshow(np.log(camera.take_src_return_imagedata(exptime =exp)[242:758, 242:758]), origin='lower', interpolation = 'nearest') plt.show() tstamp = time.strftime("%Y%m%d-%H%M%S").replace(' ', '_') cubeoutputdir = os.path.join(null_params['outputdir'], tstamp) if not os.path.exists(cubeoutputdir): os.makedirs(cubeoutputdir) print(configfilename) result_imagecube = output_imagecube(N_iterations, tp.grid_size, filepath=os.path.join( cubeoutputdir, 'test_' + tstamp + '.fits'), comment='fun', configfile=configfilename) clean_imagecube = output_imagecube(N_iterations, tp.grid_size, filepath=os.path.join( cubeoutputdir, 'test_clean_' + tstamp + '.fits'), comment='fun', configfile=configfilename) cal_imagecube = output_imagecube(4, tp.grid_size, filepath=os.path.join( cubeoutputdir, 'test_cals_' + tstamp + '.fits'), comment='fun', configfile=configfilename) cal_imagecube.update(controlregion) cal_imagecube.update(bgds['bkgd']) cal_imagecube.update(bgds['masterflat']) cal_imagecube.update(bgds['badpix']) ####MAIN LOOP STARTS HERE##### print("BEGINNING NULLING LOOP") for iteration in range(N_iterations): # quicklook_wf(wfo) itcounter.append(iteration) if use_centoffs == False: current_flatmap = ao.grab_current_flatmap() if use_centoffs == True: current_centoffs = ao.grab_current_centoffs() # quicklook_im(current_flatmap, logAmp=False, show=True) print("Taking image of speckle field") # if nulled_field != None: # raw_im = nulled_field # else: raw_im = camera.take_src_return_imagedata(wfo, exptime=exp) result_imagecube.update(raw_im) field_im = pre.equalize_image(raw_im, **bgds) clean_imagecube.update(field_im) field_ctrl = field_im * controlregion # print np.shape(field_im), np.shape(controlregion), np.shape(field_ctrl) # plt.figure() # plt.imshow(field_im) # plt.figure() # plt.imshow(controlregion) # plt.figure() # plt.imshow(field_ctrl) # plt.show(block=True) meanfluxes.append(np.mean(field_ctrl[field_ctrl > 0])) maxfluxes.append(np.max(field_ctrl[field_ctrl > 0])) totalfluxes.append(np.sum(field_ctrl)) rmsfluxes.append( np.std(field_ctrl[field_ctrl > 0]) / config['NULLING']['referenceval']) ax3.plot(itcounter, rmsfluxes) #w5 = plt.plot(itcounter, maxfluxes) #w5 = plt.plot(itcounter, totalfluxes) ax1.set_title('Iteration: ' + str(iteration) + ', Mean: ' + str(meanfluxes[iteration]) + ', Max: ' + str(maxfluxes[iteration])) w1.set_data(np.log(np.abs(field_ctrl)) + boarder) w1.autoscale() plt.draw() plt.pause(0.02) if iteration > 0: try: printstats(field_im, speckleslist) except: pass flh.writeout(current_flatmap, 'latestiteration.fits') # ans = raw_input('Do you want to run a speckle nulling iteration[Y/N]?') ans = 'Y' if ans == 'N': flatmapans = eval( input('Do you want to reload the' + 'flatmap/centoffs you started with[Y/N]?')) if flatmapans == 'Y': print("Reloading initial flatmap/centoffs") if use_centoffs == False: status = ao.load_new_flatmap((initial_flatmap)) if use_centoffs == True: status = ao.load_new_centoffs((initial_centoffs)) #ao.load_new_flatmap(initial_flatmap) break print(('Iteration ' + str(iteration) + ' total_intensity: ' + str(np.sum(field_ctrl)))) #return a list of points print("computing interesting bright spots") #note indices and coordinates are reversed ijofinterest = identify_bright_points(field_ctrl, controlregion) xyofinterest = [p[::-1] for p in ijofinterest] print(("computed ", str(len(xyofinterest)), " bright spots")) max_specks = config['DETECTION']['max_speckles'] #if len(xyofinterest)>50: # xyofinterest = xyofinterest[0:49] if len(xyofinterest) < max_specks: max_specks = len(xyofinterest) fps = filterpoints(xyofinterest, max=max_specks, rad=config['NULLING']['exclusionzone']) print(fps) print("creating speckle objects") speckleslist = [speckle(field_im, xy[0], xy[1], config) for xy in fps] speckleslist = [x for x in speckleslist if (x.intensity) > 0] #old way--filter the speckles #speckleslist =[speckle(field_im, xy[0], xy[1], config) for xy in xyofinterest] #speckleslist = filterspeckles(speckleslist, max = max_specks) phases = null_params['phases'] # phases = [-np.pi/2.,0,np.pi/2.,np.pi] for idx, phase in enumerate(phases): print(("Phase ", phase)) phaseflat = 0 allspeck_aps = 0 #put in sine waves at speckle locations for speck in speckleslist: #XXX # phaseflat= phaseflat+speck.generate_flatmap(phase) phaseflat = speck.generate_flatmap(phase) # quicklook_im(speck.generate_flatmap(phase), logAmp=False) allspeck_aps = allspeck_aps + speck.aperture print('here') ax2.set_title('Phase: ' + str(phase)) if idx == 0: # w1.set_data( (allspeck_aps*field_ctrl)-0.95*field_ctrl) w1.set_data( np.log(np.abs((allspeck_aps * field_im) - 0.95 * field_im)) + boarder) w1.autoscale() plt.draw() #w1.set_data(field_ctrl); w1.autoscale(); plt.draw() phaseflat = phaseflat * aperturemask # plt.figure() # plt.imshow(allspeck_aps) # plt.show() # ans = raw_input('press enter') wf_temp = copy.copy(wfo) if use_centoffs == False: status = ao.load_new_flatmap(current_flatmap + phaseflat, wf_temp) # if use_centoffs == True: # status = ao.load_new_centoffs(current_centoffs+ # fmf.convert_flatmap_centoffs(phaseflat)) tp.variable = proper.prop_get_phase(wf_temp)[20, 20] print(('speck phase', tp.variable, 'intensity', proper.prop_get_amplitude(wf_temp)[20, 20])) # plt.show(block=True) # quicklook_wf(wf_temp, show=True) phaseim = camera.take_src_return_imagedata(wf_temp, exptime=exp) # quicklook_im(phaseim, show=True) phaseim = pre.equalize_image(phaseim, **bgds) # quicklook_im(phaseim, show=True) w2.set_data(np.log(np.abs(phaseim * controlregion))) w2.autoscale() plt.draw() plt.pause(0.02) # w4.set_data(range(128), np.sum(np.eye(tp.grid_size)*proper.prop_get_amplitude(wf_temp),axis=1))#ax4.plot(range(128), proper.prop_get_amplitude(wf_temp)[20])#np.abs(field_im[20]))#+boarder) w4.set_data( list(range(128)), proper.prop_get_amplitude(wf_temp)[64] ) # ax4.plot(range(128), proper.prop_get_amplitude(wf_temp)[20])#np.abs(field_im[20]))#+boarder) ax4.set_xlim([0, 128]) ax4.set_ylim([0, 0.2]) print("recomputing intensities") for speck in speckleslist: phase_int = speck.recompute_intensity(phaseim) speck.phase_intensities[idx] = phase_int print((speck.phase_intensities)) time.sleep(3) # if use_centoffs == False: # ao.load_new_flatmap(current_flatmap, wf_temp) # # if use_centoffs == True: # # ao.load_new_centoffs(current_centoffs) if config['NULLING']['null_gain'] == False: defaultgain = config['NULLING']['default_flatmap_gain'] nullmap = generate_phase_nullmap(speckleslist, defaultgain, phases) nullmap = nullmap * aperturemask if use_centoffs == False: # ao.load_new_flatmap(current_flatmap + nullmap, wfo) ao.load_new_flatmap(nullmap, wfo) # FPWFS.quicklook_wf(wfo) # camera.take_src_return_imagedata(wfo, exptime=exp) # if use_centoffs == True: # ao.load_new_centoffs(current_centoffs+ fmf.convert_flatmap_centoffs(nullmap)) # ans = raw_input('press enter') if config['NULLING']['null_gain'] == True: ##NOW CALCULATE GAIN NULLS print("DETERMINING NULL GAINS") gains = config['NULLING']['amplitudegains'] for idx, gain in enumerate(gains): print("Checking optimal gains") nullmap = generate_phase_nullmap(speckleslist, gain, phases) nullmap = nullmap * aperturemask wf_temp = copy.copy(wfo) if use_centoffs == False: ao.load_new_flatmap(current_flatmap + nullmap, wf_temp) # if use_centoffs == True: # ao.load_new_centoffs(current_centoffs+ fmf.convert_flatmap_centoffs(nullmap)) ampim = camera.take_src_return_imagedata(wf_temp, exptime=exp) # quicklook_wf(wf_temp) ampim = pre.equalize_image(ampim, **bgds) w2.set_data(np.log(np.abs(ampim * controlregion))) ax2.set_title('Gain: ' + str(gain)) w2.autoscale() plt.draw() plt.pause(0.02) for speck in speckleslist: amp_int = speck.recompute_intensity(ampim) speck.gain_intensities[idx] = amp_int print((speck.gain_intensities)) w4.set_data( list(range(128)), proper.prop_get_amplitude(wf_temp)[64] ) #ax4.plot(range(128), proper.prop_get_amplitude(wf_temp)[20])#np.abs(field_im[20]))#+boarder) ax4.set_xlim([0, 128]) ax4.set_ylim([0, 0.2]) for speck in speckleslist: speck.compute_null_gain() supernullmap = generate_super_nullmap(speckleslist, phases) print( "Loading supernullmap now that optimal gains have been found!") supernullmap = supernullmap * aperturemask if use_centoffs == False: # ao.load_new_flatmap(current_flatmap + supernullmap, wfo) ao.load_new_flatmap(supernullmap, wfo) # FPWFS.quicklook_wf(wfo) # quicklook_im(supernullmap,logAmp=False, show=True) # camera.take_src_return_imagedata(wfo, exptime=exp) # if use_centoffs == True: # ao.load_new_centoffs(current_centoffs+ fmf.convert_flatmap_centoffs(supernullmap)) #ao.load_new_flatmap(supernullmap) # w3.set_data(nullmap) # plt.draw() # w4.set_data(np.log(np.abs(field_im))+boarder) # plt.draw() # w4.autoscale(); # quicklook_im(field_im, logAmp=False) quicklook_wf(wfo) plt.show(block=True) # ans = raw_input('press enter') # try: # check = raw_input("would you like to continue?: ") # except EOFError: # print ("Error: EOF or empty input!") # check = "" # print check plt.show(block=False)
# PID loop p = pid.PID(P=np.array([Kp,Kp]), I=np.array([Ki,Ki]), D=np.array([Kd,Kd]), Deadband=.01) p.setPoint(np.array([0.,0.])) """ ### reference image (acquire image or load image) if ref_file_name != '': img = pre.combine_quadrants(pf.open(ref_file_name)) k0 += 1 else: img = pharo.take_src_return_imagedata() img = pre.equalize_image(img, **bgds) delta_i_x_ref_in, delta_i_y_ref_in = get_delta_I( img, cx=centerx, cy=centery, quad_width_pix=quad_width_pix, inner_rad_pix=inner_rad_pix, zone_type='inner') delta_i_x_ref_out, delta_i_y_ref_out = get_delta_I( img, cx=centerx, cy=centery, quad_width_pix=quad_width_pix, inner_rad_pix=inner_rad_pix, zone_type='outer')