Best Python code snippet using slash
imaging_observation.py
Source:imaging_observation.py
1#!/usr/bin/env python2##################################################3### MODULE IMPORT4##################################################5## STANDARD MODULES6import os7import sys8import subprocess9import string10import time11import signal12from threading import Thread13import datetime14import numpy as np15import random16import math17import errno18## ASTRO MODULES19from astropy.io import fits20## COMMAND-LINE ARG MODULES21import getopt22import argparse23import collections24#### GET SCRIPT ARGS ####25def str2bool(v):26 if v.lower() in ('yes', 'true', 't', 'y', '1'):27 return True28 elif v.lower() in ('no', 'false', 'f', 'n', '0'):29 return False30 else:31 raise argparse.ArgumentTypeError('Boolean value expected.')32def get_args():33 """This function parses and return arguments passed in"""34 parser = argparse.ArgumentParser(description="Parse args.")35 36 # - MANDATORY OPTIONS37 parser.add_argument('-vis', '--vis', dest='vis', required=True, type=str,action='store',help='Input visibility CASA table name produced by simobserve')38 parser.add_argument('-mapsize', '--mapsize', dest='mapsize', required=True, type=int,action='store',help='Map size in pixels')39 40 # OPTIONAL OPTIONS 41 parser.add_argument('-outimage', '--outimage', dest='outimage', required=False, type=str, default='mosaic',action='store',help='Output mosaic image')42 parser.add_argument('-mask', '--mask', dest='mask', required=False, type=str, default='',action='store',help='Mask file (default=none)')43 parser.add_argument('-outproject', '--outproject', dest='outproject', required=False, type=str, default='rec',action='store',help='Output project name (default=rec)')44 parser.add_argument('-pixsize', '--pixsize', dest='pixsize', required=False, type=str, default='1arcsec',action='store',help='Pixel size (default=1 arcsec)')45 parser.add_argument('-phasecenter', '--phasecenter', dest='phasecenter', required=False, type=str, default='J2000 254.85067091580214deg -41.47631111052697deg',action='store',help='Map phase center')46 parser.add_argument('-deconvolver', '--deconvolver', dest='deconvolver', required=False, type=str, default='clark',action='store',help='Deconvolver (default=clark)')47 parser.add_argument('-gridder', '--gridder', dest='gridder', required=False, type=str, default='standard',action='store',help='Gridder (default=standard)')48 parser.add_argument('-weighting', '--weighting', dest='weighting', required=False, type=str, default='briggs',action='store',help='weighting (default=briggs)')49 parser.add_argument('-projection', '--projection', dest='projection', required=False, type=str, default='SIN',action='store',help='projection (default=SIN)')50 51 parser.add_argument('-niter', '--niter', dest='niter', required=False, type=int, default=1000,action='store',help='Clean tot number of iterations (default=1000)')52 parser.add_argument('-cycleniter', '--cycleniter', dest='cycleniter', required=False, type=int, default=-1,action='store',help='Max cycle niter (default=-1)')53 parser.add_argument('-threshold', '--threshold', dest='threshold', required=False, type=float, default=0,action='store',help='Stopping threshold in Jy (default=0)')54 ##parser.add_argument('--mosaic', dest='enable_mosaic', action='store_true') 55 parser.add_argument('--no-mosaic', dest='enable_mosaic', action='store_false')56 parser.set_defaults(enable_mosaic=True)57 ##parser.add_argument('--fitsout', dest='enable_fitsout', action='store_true') 58 parser.add_argument('--no-fitsout', dest='enable_fitsout', action='store_false') 59 parser.set_defaults(enable_fitsout=True)60 parser.add_argument('-fitsout', '--fitsout', dest='fitsout', required=False, type=str, default='output.fits',action='store',help='Output FITS file (default=output.fits)')61 parser.add_argument('-scales', '--scales', dest='scales', required=False, type=str, default='0',action='store',help='List of scales (in pixels) for multiscale deconvolver (comma separated) (default=0)')62 parser.add_argument('-restoringbeam', '--restoringbeam', dest='restoringbeam', required=False, type=str, default='common',action='store',help='Restoring beam to be used (default=common)')63 64 parser.add_argument('--interactive', dest='enable_interactive', action='store_true') 65 parser.set_defaults(enable_interactive=False)66 67 parser.add_argument('-c', dest='scriptname', required=False, type=str, default='',action='store',help='Script name')68 args = parser.parse_args() 69 return args70def clean_observation(vis,image_size,niter=1000,cycleniter=-1,threshold=0,mask='',imagename='',field='',cell_size='1arcsec',phase_center='',weighting='briggs',projection='SIN',deconvolver='clark',gridder='standard',scales=[0],restoringbeam='common',savefits=True,fitsout='output.fits',interactive=False):71 """ Clean observation """72 73 ## Set image name if empty74 if not imagename:75 project_name= 'rec'76 recimg= 'recmap'77 imagename=project_name + '/' + recimg 78 ## Cleaning79 print ('INFO: Cleaning simulated data and produce final image...')80 tclean(81 imagename=imagename,82 vis=vis,83 field=field, 84 mask=mask,85 imsize=image_size,86 phasecenter=phase_center,87 projection=projection,88 cell=cell_size, 89 niter=niter,90 cycleniter=cycleniter,91 threshold=threshold,92 deconvolver=deconvolver,93 gridder=gridder,94 weighting=weighting,95 scales=scales,96 interactive=interactive97 )98 ## Exporting to FITS99 if savefits:100 exported_map= imagename + '.image' 101 print ('INFO: Exporting CASA map %s to FITS...' % exported_map)102 exportfits(imagename=exported_map, fitsimage=fitsout, history=False, overwrite=True)103##############104## MAIN ##105##############106def main():107 """Main function"""108 ## Get script args109 print 'INFO: #%d arguments found: %s' % (len(sys.argv),str(sys.argv))110 try:111 args= get_args()112 except Exception as ex:113 print("ERROR: Failed to get and parse options (err=%s)",str(ex))114 return 1115 vis= args.vis116 niter= args.niter117 mask= args.mask118 mapsize= args.mapsize 119 outproject= args.outproject120 pixsize= args.pixsize121 phasecenter= args.phasecenter122 deconvolver= args.deconvolver123 gridder= args.gridder124 weighting= args.weighting125 projection= args.projection126 outimage= args.outimage127 cycleniter= args.cycleniter128 threshold= args.threshold129 enable_mosaic= args.enable_mosaic130 ##mosaicimage= outproject + '_' + outimage131 mosaicimage= outproject + '/' + outimage132 133 enable_fitsout= args.enable_fitsout 134 fitsout= args.fitsout135 136 enable_interactive= args.enable_interactive137 scales_str = [str(item) for item in args.scales.split(',')]138 scales= []139 for item in scales_str:140 scale_int= int(item)141 scales.append(scale_int)142 restoringbeam= args.restoringbeam143 print("*** ARGS ***")144 print 'vis: ', vis145 print 'niter: ', niter146 print 'cycleniter: ', cycleniter147 print 'threshold: ', threshold148 print 'mask: ', mask149 print 'mapsize: ', mapsize150 print 'outproject: ', outproject151 print 'pixsize: ', pixsize152 print 'phasecenter: ', phasecenter153 print 'deconvolver: ', deconvolver154 print 'gridder: ', gridder155 print 'weighting: ', weighting156 print 'scales: ', scales157 print 'projection: ', projection158 print 'restoringbeam: ', restoringbeam159 print 'outimage: ', outimage160 print 'mosaicimage: ', mosaicimage161 print 'fitsout: ', fitsout162 print("************")163 164 # Retrieve number of pointings in simulation165 #tb= casac.table() 166 tb.open(vis + '/FIELD')167 npointings= tb.nrows()168 tb.close()169 print 'INFO: #' + str(npointings) + ' pointings present in input data...'170 171 ## Image each pointing172 print ("INFO: Starting imaging pointing-by-pointing...")173 t_start = time.time()174 weightmap_list= []175 cleanmap_list= []176 bmaj_list= []177 bmin_list= []178 bpa_list= []179 bunit_list= []180 for field in range(0,npointings):181 182 imgname= outproject + '_field' + str(field) + '/recmap'183 ##imgname= outproject + '/field' + str(field) + '/recmap'184 weightmap= imgname + '.pb'185 cleanmap= imgname + '.image'186 weightmap_list.append(weightmap) 187 cleanmap_list.append(cleanmap) 188 print 'INFO: Imaging field no. ', field189 clean_observation(190 vis=vis,191 niter=niter,192 cycleniter=cycleniter,193 threshold=threshold,194 mask=mask,195 imagename=imgname,196 field=str(field),197 image_size=mapsize,198 cell_size=pixsize,199 phase_center=phasecenter,200 weighting=weighting,201 projection=projection, 202 deconvolver=deconvolver,203 gridder=gridder,204 restoringbeam=restoringbeam,205 scales=scales,206 savefits=False,207 fitsout='tmpfield.fits',208 interactive=enable_interactive209 )210 211 ## Retrieve beam information per each cleaned map212 print 'INFO: Get CASA image header...'213 imghead= imhead(imagename=cleanmap,mode='list')214 bunit= imghead['bunit']215 bmaj= imghead['beammajor']['value']216 bmin= imghead['beamminor']['value']217 bpa= imghead['beampa']['value']218 bmaj_list.append(bmaj)219 bmin_list.append(bmin)220 bpa_list.append(bpa)221 bunit_list.append(bunit)222 223 print 'weightmap_list=',weightmap_list224 print 'cleanmap_list=',cleanmap_list225 print 'bmaj_list=',bmaj_list226 print 'bmin_list=',bmin_list227 print 'bpa_list=',bpa_list228 print 'bunit_list=',bunit_list229 230 ## Make linear mosaic with all fields231 if enable_mosaic:232 lm= casac.linearmosaic()233 lm.defineoutputimage(nx=mapsize,ny=mapsize,cellx=pixsize,celly=pixsize, imagecenter=phasecenter,outputimage=mosaicimage)234 lm.setlinmostype('optimal')235 ##lm.makemosaic(images=['rec_field0/recmap.image','rec_field1/recmap.image'],weightimages=['rec_field0/recmap.pb','rec_field1/recmap.pb'])236 lm.makemosaic(images=cleanmap_list,weightimages=weightmap_list)237 #lm.saultweightimage('test_sault.linmos') 238 ## Set missing field in mosaic image header239 ## NB: beam info are missing. Each field has its own restoring beam info. Which one to use? Using the largest bmaj. Alternatively one can set the restoring beam in tclean (FIX ME)240 largest_bmaj_index= bmaj_list.index(max(bmaj_list)) 241 cleanmap_head= imhead(imagename=cleanmap_list[largest_bmaj_index],mode='list')242 imhead(mosaicimage, mode="put", hdkey='beammajor', hdvalue=str(cleanmap_head['beammajor']['value']) + cleanmap_head['beammajor']['unit'])243 imhead(mosaicimage, mode="put", hdkey='beamminor', hdvalue=str(cleanmap_head['beamminor']['value']) + cleanmap_head['beamminor']['unit'])244 imhead(mosaicimage, mode="put", hdkey='beampa', hdvalue=str(cleanmap_head['beampa']['value']) + cleanmap_head['beampa']['unit'])245 imhead(mosaicimage, mode="put", hdkey='bunit', hdvalue=cleanmap_head['bunit'])246 ## Exporting to FITS247 if enable_fitsout:248 exported_map= mosaicimage 249 print ('INFO: Exporting mosaic map %s to FITS...' % exported_map)250 exportfits(imagename=exported_map, fitsimage=fitsout, history=False, overwrite=True)251 252 t_stop = time.time()253 t_elapsed = t_stop - t_start254 ## Print performance info255 print ('INFO: Imaging completed after dt(s)=%s' % str(t_elapsed))256 257###################258## MAIN EXEC ##259###################260if __name__ == "__main__":...
__init__.py
Source:__init__.py
...10 for extract source code, assembly, etc.11 """12 set_config("Executable_type", FullyInstrumentedExecutable) 13 set_config("ProgressBar", tqdm)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!