def cal_image(filepath,plot = True,path=None,band='gp',source='BD710031',bias=None,dark=None,flat=None): if not path: path = set_path() if length(bias) == 1: bias = make_bias(path=path) if length(dark) == 1: dark = make_dark(path=path) if length(flat) == 1: flat = make_flat(path=path,band=band,bias=bias,dark=dark) image0, header0 = qi.readimage(filepath) refh = h.pyfits.getheader(filepath) im = h.pyfits.open(filepath) newim = h.hcongrid((im[0].data-dark-bias)/flat, im[0].header,refh) if plot: qi.display_image(newim) return newim,header0
def stack_ims(path=None,band='gp',source='NGC188',bias=None,dark=None,flat=None): if not path: path = set_path() if length(bias) == 1: bias = make_bias(path=path) if length(dark) == 1: dark = make_dark(path=path) if length(flat) == 1: flat = make_flat(path=path,band=band,bias=bias,dark=dark) files,sz = tp.get_files(dir=path, tag=source+'.'+band) # Designate reference file reffile = files[sz/2] image0, header0 = qi.readimage(reffile) ysz, xsz = np.shape(image0) refim = h.pyfits.open(reffile) refh = h.pyfits.getheader(reffile) stack = np.zeros((xsz,ysz,sz)) for i in range(sz): im = h.pyfits.open(files[i]) newim = h.hcongrid((im[0].data-dark-bias)/flat, im[0].header,refh) stack[:,:,i] = newim final = np.median(stack, axis=2) return final,refh
def headerplot(fluxdata,ykeyword='airmass',badimindices = [],band = 'gp',titleextra = '',path = None, source = 'BD710031', bias = None, dark=None, flat=None): if not path: path = set_path() if length(bias) == 1: bias = make_bias(path=path) if length(dark) == 1: dark = make_dark(path=path) if length(flat) == 1: flat = make_flat(path=path,band=band,bias=bias,dark=dark) files,osz = tp.get_files(dir=path, tag=source+'.'+band) #remove faulty images sz = osz if len(badimindices) != 0: for g in range(osz): if g in badimindices: del files[g] sz=sz-1 keyworddata = [] headers = [] #extract headers from each image for file in files: file,header = cal_image(file,plot=False,path=path,band=band,source=source,bias=bias,dark=dark,flat=flat) headers.append(header) #extract keyword data from each header for j in range(sz): header = headers[j] keyworddata.append(header[ykeyword]) #determine peak flux value, index, and its header for annotation peakflux = max(fluxdata) peakfluxindex = fluxdata.argmax() keyworddataofpeakflux = keyworddata[peakfluxindex] #normalize flux data nfluxdata = fluxdata for q in range(len(fluxdata)): nfluxdata[q] = nfluxdata[q]/peakflux #display plot; set y axis plt.scatter(keyworddata,nfluxdata) axes = plt.gca() axes.set_ylim([0,1]) #labels plt.title(ykeyword.capitalize()+' v. Flux (Band: ' + band + ')'+'\n'+'('+titleextra+')') plt.xlabel(ykeyword.capitalize()) plt.ylabel('Flux') xcoord = keyworddataofpeakflux ycoord = 1 plt.annotate('Peak Flux = '+str(peakflux), xy=(xcoord,ycoord), xytext=(xcoord ,ycoord - .05))
def validate(time_array, voltage_array): """This function validates the input data. This function also requires the length, neg and exceed functions from the length, negative and exceed files, respectively. The first line sets the variable final equal to an empty string. The next three lines create three different strings. The try and except functions each call in one of the imported functions (length, neg, exceed). If an exception is raised in either function, it adds a specific string to the variable final. The if statement checks to see if the final variable is not equal to an empty string, if so, a TypeError is raised and the final variable is printed. :param time_array: array of time values :param voltage_array: array of voltage values :type time_array: ndarray :type voltage_array: ndarray """ import logging from logging import config from length import length from negative import neg from exceed import exceed logging.config.fileConfig('logger_config.ini', disable_existing_loggers=False) final = "" s1 = "Time and Voltage arrays have different lengths." s2 = "Time has negative values." s3 = "Voltage exceeds 300mV." try: length(time_array, voltage_array) except: final += s1 try: neg(time_array) except: final += s2 try: exceed(voltage_array) except: final += s3 if final != "": logging.error(TypeError(final))
def vet_FWHM_series(time,raw): """ Description: ------------ Extract a numpy array of all FWHM measurements vetted against zeros and 0.08 values which seem to be a saturation effect Timestamp for data is also input so that vetted data contains corresponding timestamp. Also vets values over 50, which appear to come in as the sun is rising and setting """ new = [] newt = [] for r in raw: new = np.append(new,round(r,2)) for t in time: newt = np.append(newt,t) if length(newt) != length(new): print 'Time and data vectors not equal lengths!' return None,None inds, = np.where(new == '') if inds: new[inds] = '0.0' keep1, = np.where(new != 0.0) new = new[keep1] newt = newt[keep1] keep2, = np.where(new != 0.08) new = new[keep2] newt = newt[keep2] keep3, = np.where(new < 10) new = new[keep3] newt = newt[keep3] FWHM = new.astype('float') return newt, FWHM
def label_surface(obj_polygons, pdata_GetNumberOfCells, distance, number, labels, points): obj_polygons_temp = torch.tensor(obj_polygons.copy()) distance = length.length(pdata_GetNumberOfCells, obj_polygons_temp, points) for i in range(number): if distance[i] < 0.0001: labels[i, 0] = labels[i, 1] = 1
def test_length(): """This function unit tests the length function. This function requires the numpy and pytest packages, as well as the length function being testing. The with statement checks if an exception is raised if the input time and voltage arrays have unequal lengths. """ import numpy as np import pytest from length import length with pytest.raises(Exception): length(time_array=np.array([0, 1, 2]), voltage_array=np.array([-1, 3, 4, 9]) )
def make_flat(path=None,band='gp',bias=None,dark=None): """ Make master flat from raw data files in specified band """ if not path: path = set_path() if length(bias) == 1: bias = make_bias(path=path) if length(dark) == 1: dark = make_dark(path=path, bias=bias) flats,ct = tp.get_files(dir=path, tag='SkyFlat.'+band) masterflat = tp.master_flat(flats, bias=bias, dark=dark, outdir='./', suffix=band) return masterflat
def flux_all(path=None,band='gp',extraprecision=True,extraprecisionrange=100,source='BD710031',badimindices = [],bias=None,dark=None,flat=None): if not path: path = set_path() if length(bias) == 1: bias = make_bias(path=path) if length(dark) == 1: dark = make_dark(path=path) if length(flat) == 1: flat = make_flat(path=path,band=band,bias=bias,dark=dark) files,osz = tp.get_files(dir=path, tag=source+'.'+band) sz = osz #remove faulty images if len(badimindices) != 0: for g in range(osz): if g in badimindices: del files[g] sz=sz-1 flux = [] for file in files: image,header = cal_image(file,plot=False,path=path,band=band,source=source,bias=bias,dark=dark,flat=flat) w = wcs.WCS(header) x,y = w.all_world2pix(float(header['TARGRA']), float(header['TARGDEC']), 1) position = (float(x),float(y)) if extraprecision == True: for k in range(extraprecisionrange): if check_radii(image,header,position,rin=k+10,rout=k+15) == True: op_ap,xval,yval,fwhm,aspect,snrmax,totflux,totap,chisq = \ tp.optimal_aperture(float(x),float(y),image,[k+10,k+15],use_old=True) break else: op_ap,xval,yval,fwhm,aspect,snrmax,totflux,totap,chisq = \ tp.optimal_aperture(float(x),float(y),image,[10,15],use_old=True) #print "Final aperture: " + str(op_ap) phot = do_phot(image,position,radius=op_ap) flux = np.append(flux,phot['aperture_sum_bkgsub']) return flux
def make_dark(path=None, bias=None): """ Make master dark from raw data files """ if not path: path = set_path() if length(bias) == 1: bias = make_bias(path=path) darks,dct = tp.get_files(dir = path,tag='Dark') masterdark = tp.master_dark(darks,bias=bias,outdir='./') return masterdark
def photsky(xcen, ycen, skyrad, image, salg=None, srejalg=None, smaxiter=None, lorej=None, hirej=None, quick=None, exact=None): """Syntax - result = photsky( xcen, ycen, skyrad, image, [ salg=, srejalg=, smaxiter=, lorej=, hirej=, skyrms=, skyerr=, /quick, /exact ])""" #skyval, skyrms, and skyerr are the outputs outputs = {'skyval':None, 'skyrms':None, 'skyerr':None} if (salg is None): salg = 'mean' if (((salg != 'mean') & (salg !='median') & (salg != 'mode'))|(skyrad is None)): outputs['skyval']=None outputs['skyrms']=0.0 outputs['skyerr']=0.0 return outputs if ((srejalg is not None) == 0): srejalg = 'sigclip' if ((smaxiter is not None) == 0): smaxiter = 10 _expr = srejalg if _expr == 'sigclip': if ((lorej is not None) == 0): lorej = 3.0 if ((hirej is not None) == 0): hirej = 3.0 elif _expr == pclip: if ((lorej is not None) == 0): lorej = 0.05 if ((hirej is not None) == 0): hirej = 0.05 else: if ((lorej is not None) == 0): lorej = 0.0 if ((hirej is not None) == 0): hirej = 0.0 # Find sky pixels and contribution from each xdimen = length(image[0,:]) ydimen = length(image[:,0]) if (quick is not None): #THIS NEEDS TO BE FIXED quick_photfrac(xcen, ycen, skyrad, xdimen=xdimen, ydimen=ydimen, pixnum=pixnum, fracs=fracs, ragged=True) else: if (exact is not None): #THIS NEEDS TO BE FIXED exact_photfrac(xcen, ycen, skyrad, xdimen=xdimen, ydimen=ydimen, pixnum=pixnum, fracs=fracs) else: output_fracs=photfrac(xcen, ycen, skyrad, xdimen=xdimen, ydimen=ydimen) pixnum = output_fracs['pixnum'] xpixnum = output_fracs['xpixnum'] ypixnum = output_fracs['ypixnum'] fracs = output_fracs['fracs'] if (length(pixnum) !=0): # Trim to only those pixels more than half filled, unless that rejects # all pixels filled = np.nonzero(fracs > 0.5) count = np.size(filled) if (count != 0): pixnum = pixnum[filled] xpixnum = xpixnum[filled] ypixnum = ypixnum[filled] fracs = fracs[filled] # Iterate until one of the following conditions is met: # (1) the maximum number of iterations is reached # (2) no points are retained after the rejection algorithm # (3) the same sky value is returned after two iterations subimg = image[xpixnum,ypixnum] iiter = 0 dsky = 1.0 # Set NE 0 to prevent stopping at first iteration while ( (iiter <=smaxiter) & (np.size(subimg) != 0) & (dsky != 0.0)): if (iiter > 0): dsky = skyval skyval = photsky_compute(subimg, salg) skydiff = subimg - skyval skyrms = np.sqrt(np.sum((skydiff * skydiff)/np.size(skydiff))) skyerr = skyrms/np.sqrt( np.size(subimg)) #ipdb.set_trace() subimg = photsky_reject(skyval, image[xpixnum, ypixnum], srejalg, lorej, hirej) if (iiter > 0): dsky = dsky - skyval iiter = iiter + 1 else: skyval = 0.0 # No sky pixels exist in the given annulus skyrms = 0.0 skyerr = 0.0 outputs['skyval']=skyval outputs['skyrms']=skyrms outputs['skyerr']=skyerr return outputs
def phot(xcen, ycen, objrad, skyrad, image, invvar=None, calg=None, cbox=None, cmaxiter=None, cmaxshift=None, fwhm=None, fixfw=None, ceps=None, salg=None, srejalg=None, smaxiter=None, lorej=None, hirej=None, flerr=None, skyval=None, skyrms=None, skyerr=None, peakval=None, quick=None, exact=None): outputs = {'flux':None, 'fluxerr':None, 'xcen':None, 'ycen':None, 'skyval':None,'skyrms':None} #convert everything to numpy arrays xcen =np.array([xcen]).flatten() ycen =np.array([ycen]).flatten() objrad =np.array([objrad]).flatten() skyrad =np.array([skyrad]).flatten() nobj = length(xcen) if (length(ycen) != nobj): print('XCEN and YCEN must have same number of elements') if ((exact is not None)): # This still needs to be fixed ini = where(ravel(bitwise_or(array(xcen, copy=0).astype(Int32) != xcen, array(ycen, copy=0).astype(Int32) != ycen)))[0] if (nni > 0): print('xcen and ycen MUST be integers if /exact keyword is set') dims = np.shape(image) xdimen = dims[0] ydimen = dims[1] nrad = length(objrad) # Allocate memory for return values flux = np.zeros([nrad, nobj]) if (flerr is not None): flerr = np.zeros([nrad, nobj]) skyval = np.zeros([nobj]) skyrms = np.zeros([nobj]) skyerr = np.zeros([nobj]) if (peakval is not None): peakval = np.zeros([nrad, nobj]) #----- LOOP THROUGH EACH OBJECT ----- for iobj in range(0, (nobj - 1)+(1)): # Center the object xcen1 = xcen[iobj] ycen1 = ycen[iobj] if ((exact is None)): recenter=photcen(xcen1, ycen1, image, calg=calg, cbox=cbox, cmaxiter=cmaxiter, cmaxshift=cmaxshift) xcen1 = recenter['xcen'] ycen1 = recenter['ycen'] else: print('Not recentering -- /exact requires correct input center') xcen1 = xcen[iobj] ycen1 = ycen[iobj] # Find the sky value # Add 0.0 to the skyrad to convert to floating-point skyvals= photsky(xcen1, ycen1, skyrad + 0.0, image, salg=salg, srejalg=srejalg, smaxiter=smaxiter, lorej=lorej, hirej=hirej, quick=quick, exact=exact) skyval[iobj] = skyvals['skyval'] skyrms[iobj] = skyvals['skyrms'] skyerr[iobj] = skyvals['skyerr'] # Find total counts in object aperture(s) for irad in np.arange(0, (nrad - 1)+(1)): onerad = objrad[irad] + 0.0 # Convert to floating-point if (onerad > 0): if (quick is not None): quick_photfrac(xcen1, ycen1, onerad, xdimen=xdimen, ydimen=ydimen, pixnum=pixnum, fracs=fracs) else: if (exact is not None): exact_photfrac(xcen1, ycen1, onerad, xdimen=xdimen, ydimen=ydimen, pixnum=pixnum, fracs=fracs) else: output_object=photfrac(xcen1, ycen1, onerad, xdimen=xdimen, ydimen=ydimen) pixnum=output_object['pixnum'] fillfrac=output_object['fillfrac'] xpixnum=output_object['xpixnum'] ypixnum=output_object['ypixnum'] fracs=output_object['fracs'] else: pixnum = -1 if (pixnum[0] == -1): flux[irad,iobj] = 0.0 # No object pixels if (flerr is not None): flerr[irad,iobj] = 0.0 else: area = np.sum(fracs) flux[irad,iobj] = np.sum(image[xpixnum,ypixnum] * fracs) - \ (area * skyval[iobj]) if (flerr is not None): flerr[irad,iobj] = area * skyerr[iobj] if (peakval is not None): peakval[irad,iobj] = np.max(image[pixnum]) # If INVVAR was set, then measure those pixel errors and add # them in quadrature to the sky-subtraction errors. if ((invvar is not None) & (flerr is not None)): if (pixnum[0] == -1): sigma2 = 0 else: if (min(invvar[xpixnum, ypixnum])<=0 ): sigma2 = 0 else: sigma2 = np.sum(fracs / invvar[xpixnum, ypixnum]) if (sigma2 <= 0): flerr[irad,iobj] = -1 else: flerr[irad,iobj] = np.sqrt(flerr[irad,iobj] ** 2 + sigma2) # Overwrite the center positions with the newly computed ones xcen[iobj] = xcen1 ycen[iobj] = ycen1 outputs['flux']=flux outputs['fluxerr']=flerr outputs['xcen'] = xcen outputs['ycen'] = ycen outputs['skyval']=skyval outputs['skyrms']=skyrms return outputs
from length import length a = [5, 3, 4, 1, 2, 3] print(length(a)) a = [] print(length(a)) d = {} print(length(d)) d = {"one": True, "two": True} print(length(d)) s = "This is a string" print(length(s)) s = "" print(length(s))
# Create pyephem observatory object thob = ephem.Observer() thob.long = ephem.degrees(str(lon)) thob.lat = ephem.degrees(str(lat)) thob.elevation = 504.4 # in meters # Data directory dir = '/Users/jonswift/Dropbox (Thacher)/Observatory/AllSkyCam/Data/30Sept2016/' darks = glob.glob(dir+'dark*FIT') # Get dark frames d0 = getdata(darks[0],0,header=False) xsz,ysz = np.shape(d0) # Find a master dark dcube = np.empty((xsz,ysz,length(darks))) for i in range(length(darks)): dcube[:,:,i] = getdata(darks[i],0,header=False) dark = np.median(dcube,axis=2) # Measured sky brightness 9/30/2016 (hand held) mv = 20.8 # Mags per square arcsecond # Get sky images skys = glob.glob(dir+'sky*FIT') # Get image and header image, header = getdata(skys[2], 0, header=True) # Subtract dark current and bias (together) image -= dark
def get_distance(banks, params, latitude, longitude): distances = [] names = [] rates = [] spisok_rate = [] spisok_rate.clear() coordinates = [] coordinates.clear() spisok_text = [] spisok_text.clear() spisok_data = [] spisok_data.clear() spisok_buy = [] spisok_buy.clear() spisok_buy_sorted = [] spisok_buy_sorted.clear() spisok_sell = [] spisok_sell.clear() spisok_sell_sorted = [] spisok_sell_sorted.clear() maxsell = 0 lenmax = [] imax = -1 minbuy = 999999999 imin = -1 lenmin = [] maxsellnear = 0 minbuynear = 0 clon = 0 """Поиск максимального и минимального курса продажи покупки""" for i in range(len(banks)): if float(banks[i]["sell"]) > float(maxsell): maxsell = banks[i]["sell"] if float(banks[i]["buy"]) < float(minbuy): minbuy = banks[i]["buy"] """Сохранение всех максимальных и минимальных элементов""" for i in range(len(banks)): if banks[i]["sell"] == maxsell: spisok_buy.append([ banks[i]["latitude"], banks[i]["longitude"], length(latitude, longitude, banks[i]["latitude"], banks[i]["longitude"]), i, banks[i]["sell"], banks[i]["buy"], banks[i]["bank"] ]) if banks[i]["buy"] == minbuy: spisok_sell.append([ banks[i]["latitude"], banks[i]["longitude"], length(latitude, longitude, banks[i]["latitude"], banks[i]["longitude"]), i, banks[i]["sell"], banks[i]["buy"], banks[i]["bank"] ]) spisok_buy.sort(key=itemgetter(2)) spisok_sell.sort(key=itemgetter(2)) for i in range(0, 2): try: spisok_buy[i] except IndexError: break else: j = spisok_buy[i][3] lenmax.append( length_top5(latitude, longitude, banks[j]["latitude"], banks[j]["longitude"])) imax = min(lenmax) spisok_buy[0][2] = imax for i in range(0, 2): try: spisok_sell[i] except IndexError: break else: j = spisok_sell[i][3] lenmin.append( length_top5(latitude, longitude, banks[j]["latitude"], banks[j]["longitude"])) imin = min(lenmin) spisok_sell[0][2] = imin try: spisok_buy_sorted[i] except IndexError: spisok_buy_sorted.append(spisok_buy[0]) maxsell = spisok_buy_sorted[0] try: spisok_sell_sorted[i] except IndexError: spisok_sell_sorted.append(spisok_sell[0]) minbuy = spisok_sell_sorted[0] # "<i>%s</i>- <b>%s</b> / <b>%s</b> (<i>%s</i>км)" % (spisok_data[i][0], spisok_data[i][1], spisok_data[i][2], spisok_data[i][3] # maxsell = "🏦<b>%s</b> / <b>%s</b> <a href='%s'>%s</a> (<i>%s</i>км)" # покупка / продажа банк расстояние maxsell = "🏦<b>%s</b> / <b>%s</b> <a href='%s'>%s</a> (<i>%s</i>км)" % ( maxsell[4], maxsell[5], link(latitude, longitude, maxsell[0], maxsell[1]), maxsell[6], maxsell[2]) minbuy = "🏦<b>%s</b> / <b>%s</b> <a href='%s'>%s</a> (<i>%s</i>км)" % ( minbuy[4], minbuy[5], link(latitude, longitude, minbuy[0], minbuy[1]), minbuy[6], minbuy[2]) # print(maxsell) # print(minbuy) """Подсчет расстояния с помощью расстояния между точками, затем подсчет расстояния в топ5 через googlemapsapi""" distances.clear() for i in range(len(banks)): distances.append( length(latitude, longitude, banks[i]["latitude"], banks[i]["longitude"])) distances.sort(reverse=False) # print(distances[:7]) for i in range(0, 7): try: # Проверка на существование элемента distances[i] except IndexError: break else: """создание новых массивов потому что я бомж и не могу соритировать относительно расстояния из гугла""" """в этих массивах сохранены значения первых семи обменников по близости""" for j in range(len(banks)): # print(length(latitude,longitude,banks[j]["latitude"],banks[i]["longitude"])) if distances[i] == length(latitude, longitude, banks[j]["latitude"], banks[j]["longitude"]): names.append(banks[j]["bank"]) coordinates.append( [banks[j]["latitude"], banks[j]["longitude"]]) rates.append([banks[j]["sell"], banks[j]["buy"]]) spisok_rate.append( [banks[j]["bank"], banks[j]["sell"], banks[j]["buy"]]) """Создание списка уже из топ5 обменников но с Googlemaps""" """Удаление дубликатов чтобы получить списки с сохраненными данными без повторов""" names = delete_copy(names) # print(names) coordinates = delete_copy(coordinates) # print(coordinates) spisok_rate = delete_copy(spisok_rate) # print(spisok_rate) for i in range(0, 5): try: # Проверка на существование элемента names[i] except IndexError: break else: # список в котором сохранены все данные,для того чтобы делать сортировку относительно любогу параметра # затем можно отсортированный список использовать для создания списка из строчек с отсортированными данными spisok_data.append([ names[i], spisok_rate[i][1], spisok_rate[i][2], length_top5(latitude, longitude, coordinates[i][0], coordinates[i][1]), latitude, longitude, coordinates[i][0], coordinates[i][1] ]) """Ближайшие банки""" if params == "distance": spisok_data.sort(key=itemgetter(3)) for i in range(len(spisok_data)): spisok_text.append( "🏦<b>%s</b> / <b>%s</b> <a href='%s'>%s</a> (<i>%s</i>км)" % (spisok_data[i][1], spisok_data[i][2], link( spisok_data[i][4], spisok_data[i][5], spisok_data[i][6], spisok_data[i][7]), spisok_data[i][0], spisok_data[i][3])) text = "\n".join(spisok_text) # print(text) return text """Выгодная покупка(банк покупает по самому высоку курсу)""" if params == "distance_buy": spisok_data.sort(key=itemgetter(1)) for i in range(len(spisok_data)): spisok_text.append( "🏦<b>%s</b> / <b>%s</b> <a href='%s'>%s</a> (<i>%s</i>км)" % (spisok_data[i][1], spisok_data[i][2], link( spisok_data[i][4], spisok_data[i][5], spisok_data[i][6], spisok_data[i][7]), spisok_data[i][0], spisok_data[i][3])) # print("\n".join(spisok_text)) if maxsell not in spisok_text: spisok_text.insert(0, maxsell) text = "\n".join(spisok_text) return text """Выгодная продажа(банк продает по самому низкому курсу)""" if params == "distance_sell": spisok_data.sort(key=itemgetter(2)) for i in range(len(spisok_data)): spisok_text.append( "🏦<b>%s</b> / <b>%s</b> <a href='%s'>%s</a> (<i>%s</i>км)" % (spisok_data[i][1], spisok_data[i][2], link( spisok_data[i][4], spisok_data[i][5], spisok_data[i][6], spisok_data[i][7]), spisok_data[i][0], spisok_data[i][3])) if minbuy not in spisok_text: spisok_text.insert(0, minbuy) text = "\n".join(spisok_text) return text
def test_length(self): #test for length word5 = 'it is a beautiful night' self.assertEqual(length.length(word5), 0.0)
def photcen(xcen, ycen, image, calg=None, cbox=None, cmaxiter=None, cmaxshift=None, fwhm=None, fixfw=None, ceps=None, qmaxshift=None): """Syntax - result = photcen( xcen, ycen, image, $' [ calg=, cbox=, cmaxiter=, cmaxshift=, $' fwhm=, /fixfw, ceps= ] )""" outputs={'xcen':None, 'ycen':None, 'qmaxshift':None} # Need 3 parameters # _opt = (calg, cbox, cmaxiter, cmaxshift, fwhm, fixfw, ceps, qmaxshift) # def _ret(): # _optrv = zip(_opt, [calg, cbox, cmaxiter, cmaxshift, fwhm, fixfw, ceps, qmaxshift]) # _rv = [xcen, ycen, image] # _rv += [_o[1] for _o in _optrv if _o[0] is not None] # return tuple(_rv) # #---------- # If XCEN and YCEN are arrays, then call this routine recursively nx = length(xcen) ny = length(ycen) if (nx != ny): print('Dimensions of NX and NY do not agree') pass if (nx >1): #outputs['xcen']=np.zeros(length(xcen)) #outputs['ycen']=np.zeros(length(ycen)) #outputs['qmaxshift']=np.zeros(length(qmaxshift)) for i in np.arange(0, (nx - 1)+(1)): xtmp = xcen[i] ytmp = ycen[i] outs=photcen(xtmp, ytmp, image, calg=calg, cbox=cbox, cmaxiter=cmaxiter, cmaxshift=cmaxshift, fwhm=fwhm, fixfw=fixfw, ceps=ceps) for key in outputs.keys(): if outputs[key] is None: outputs[key] = outs[key] else: outputs[key] = np.append( np.array(outputs[key]), outs[key]) return outputs if ((calg is not None) == 0): calg = 'iweight' if ((cbox is not None) == 0): cbox = 7 if ((cmaxiter is not None) == 0): cmaxiter = 10 if ((cmaxshift is not None) == 0): cmaxshift = 3.0 if ((ceps is not None) == 0): ceps = 0.0 if ((fwhm is not None) == 0): fwhvec = np.array([1.0, 1.0]) else: if ((fwhm is not None) == 1): fwhvec = np.array([fwhm, fwhm]) else: fwhvec = np.array([fwhm(0), fwhm(1)]) if ((fixfw is not None) == 0): fixfw = 0 # Return if no centering is to be performed if (calg == 'none'): return outputs # Use the data array dimensions dims = np.shape(image) naxis1 = dims[0] naxis2 = dims[1] radius = 0.5 * cbox # Iterate until one of the following conditions is met: # (1) the maximum number of iterations is reached # (2) no pixels are within the centering box # (3) the maximum shift in both X and Y has been exceeded # (4) the same center position is returned after two iterations, # to within ceps of each other in both X and Y iiter = 0 dcen = 2 * ceps + 1.0 # Set > ceps to prevent stopping at first iteration qmaxshift = 0 while ( (iiter <= cmaxiter) & (qmaxshift == 0) & (np.max(abs(dcen)) > ceps)): if (iiter > 0): dcen = np.array([xcen, ycen]) # Limit computations to pixels in a square centered on (xCen, yCen) # which bounds the box with radius Radius. # Trim the X radius to be the largest symmetric box that falls within # the image boundaries. xrad = min( radius, np.maximum(xcen, 0), np.maximum((naxis1 - xcen),0)) istart = np.floor(xcen + 0.5 - xrad).astype('int') iend = np.ceil(xcen - 0.5 + xrad).astype('int') if ( (istart > naxis1) | (iend < 0)): #maybe throw a sys.exit in python? print('Error - No pixels in X range') return outputs ilen = iend - istart + 1 # Trim the Y radius to be the largest symmetric box that falls within # the image boundaries. yrad = min( radius, np.maximum(ycen, 0), np.maximum((naxis2 - ycen),0)) jstart = np.floor(ycen + 0.5 - yrad).astype('int') jend = np.ceil(ycen - 0.5 + yrad).astype('int') if ( (jstart > naxis2) | (jend < 0)): print('Error - No pixels in Y range') return outputs jlen = jend - jstart + 1 # Compute pixel corner locations relative to (xCen,yCen) xa = istart + np.arange(ilen) - 0.5 - xcen xb = xa + 1 ya = jstart + np.arange(jlen) - 0.5 - ycen yb = ya + 1 # Trim pixel sizes to only those coordinates falling within the # centering box xa = xa.clip(-xrad) xb = xb.clip(max=xrad) ya = ya.clip(-yrad) yb = yb.clip(max=yrad) # Determine the indices for the pixel npixelx = length(xa) npixely = length(ya) npixels = npixelx * npixely iindx = (np.arange(npixelx*npixely, dtype=np.uint32) .reshape(npixelx, npixely))%npixelx jindx = (np.arange(npixelx*npixely, dtype=np.uint32) .reshape(npixelx, npixely))/npixelx #iindx = lindgen(npixelx, npixely) % npixelx #jindx = array(lindgen(npixelx, npixely) / npixelx, copy=0).astype(Int32) + 0 xpixnum = (iindx + istart) ypixnum = (jindx + jstart) #pixnum = 0 + xpixnum + naxis1 * ypixnum #(this line is commented out and simplified in #the python version) # Compute contribution of each pixel fracs = (xb[iindx[:]] - xa[iindx[:]]) * (yb[jindx[:]] - ya[jindx[:]]) # Create a temporary data array with the box of pixels subimg = image[xpixnum, ypixnum] _expr = calg #This section needs to fix the gaussian fits if _expr == 'iweight': # Intensity-weighted centering norm = np.sum(subimg[:] * fracs) # Insist that the total flux is positive if (norm > 0): # Work with xPixNum-xcen and yPixNum-ycen for numerical stability newi = np.sum(subimg[:] * (xpixnum[:] - xcen) * fracs) / norm + xcen newj = np.sum(subimg[:] * (ypixnum[:] - ycen) * fracs) / norm + ycen xcen = newi ycen = newj elif _expr == 'gauss1': # THIS NEEDS TO BE IMPLEMENTED # One-dimensional gaussian fit, indepently fit in X and Y # Collapse the sub-image into two one-dimensional arrays # Fit X center ptemp = total(subimg, 2) fracx = xb - xa newi = photcen_gfit1(xpixnum[0,:], ptemp, fracx, fwhvec[0], xcen, fixfw) xcen = newi # Fit Y center ptemp = total(subimg, 1) fracy = yb - ya newj = photcen_gfit1(transpose(ypixnum[:,0]), ptemp, fracy, fwhvec[1], ycen, fixfw) ycen = newj elif _expr == 'gauss2': # THIS NEEDS TO BE IMPLEMENTED # Two-dimensional gaussian fit, simultaneously fitting in X and Y gres = gauss2dfit(subimg, gcoeff, tilt=True) xcen = gcoeff[4] + istart ycen = gcoeff[5] + jstart elif _expr == None: asdf = -1 else: print('Error - Invalid centering algorithm') return _ret() # Test to see if maximum shift was reached in either X or Y. # If so, then reset coordinates to original center and set the # qmaxshift flag. if ((cmaxshift is not None)): xold = xcen yold = ycen xcen = max(min(xcen, xcen+cmaxshift), xcen-cmaxshift) ycen = max(min(ycen, ycen+cmaxshift), ycen-cmaxshift) #xcen = maximum((minimum(xcen, xcen) + cmaxshift), xcen) - cmaxshift #ycen = maximum((minimum(ycen, ycen) + cmaxshift), ycen) - cmaxshift if ( (xold != xcen) | (yold != ycen)): outputs['qmaxshift'] = 1 if (iiter > 0): dcen = dcen - np.array([xcen, ycen]) iiter = iiter + 1 outputs['xcen']=xcen outputs['ycen']=ycen return outputs
def photfrac(xcen, ycen, rvec, xdimen=None, ydimen=None, xpixnum=None, ypixnum=None, pixnum=None, fracs=None, fillfrac=None): """Syntax - photfrac, xcen, ycen, Rvec, $ xdimen=, ydimen=, xPixNum=, yPixNum=, pixnum=, $ fracs=, fillfrac=""" outputs = {'pixnum':None, 'xpixnum':None, 'ypixnum':None, 'fracs':None, 'fillfrac':None} pixnum = -1 fracs = 0 # If Rvec contains one element, then use the annulus [0,Rvec], # otherwise use the annulus [Rvec[0],Rvec[1]]. if (length(rvec)==1): radius1 = 0.0 radius2 = abs(rvec) else: radius1 = abs(rvec[0]) radius2 = abs(rvec[1]) sqradius1 = radius1 * radius1 sqradius2 = radius2 * radius2 # Limit computations to pixels in a square centered on (xCen, yCen) # which completely bounds the outer circle described by Radius2. istart = np.maximum(0, np.floor(xcen + 0.5 - radius2).astype('int')) iend = np.minimum((xdimen - 1), np.ceil(xcen - 0.5 + radius2).astype('int')) ilen = iend - istart + 1 if ((istart > xdimen) | (iend < 0) | (ilen < 1) ): print('Error - No pixels in X range') pass jstart = np.maximum(0, np.floor(ycen + 0.5 - radius2).astype('int')) jend = np.minimum((ydimen - 1), np.ceil(ycen - 0.5 + radius2).astype('int')) jlen = jend - jstart + 1 if ((jstart > ydimen) | (jend < 0) | (jlen < 1)): print('Error - No pixels in Y range') pass # Compute pixel corner locations relative to (xCen,yCen) xa = (istart + np.arange(ilen) - 0.5) - xcen xb = xa + 1 ya = (jstart + np.arange(jlen) - 0.5) - ycen yb = ya + 1 # Split the pixel across the axis y=yCen by adding one more X pixel # e.g., by adding one more element to xA and xB. isplit = np.floor(xcen - istart + 0.5).astype('int')# Integer X pixel number to split q_splitx = (isplit >= 0) & (isplit < ilen) if (q_splitx): xa = np.append(xa,0.0) xb = np.append(xb,xb[isplit]) xb[isplit] = 0.0 # Split the pixel across the axis x=xCen by adding one more Y pixel # e.g., by adding one more element to yA and yB. # Integer Y pixel number to split jsplit = np.floor(ycen - jstart + 0.5).astype('int') q_splity = (jsplit >= 0) &( jsplit < jlen) if (q_splity): ya = np.append(ya,0.0) yb = np.append(yb, yb[jsplit]) yb[jsplit] = 0.0 # Force all relative coordinates to be non-negative and reorder # values such that xB>xA and yB>yA. xa = np.abs(xa) xb = np.abs(xb) ya = np.abs(ya) yb = np.abs(yb) xap = np.minimum(xa, xb) xbp = np.maximum(xa, xb) yap = np.minimum(ya, yb) ybp = np.maximum(ya, yb) # Compute distances to lower left corner of pixel, RadiusA, # and upper right corner, RadiusB. npixelx = length(xap) npixely = length(yap) npixels = npixelx * npixely #iindx = (np.arange(npixelx*npixely, dtype=np.uint32).reshape(npixelx, npixely))%npixelx #jindx = (np.arange(npixelx*npixely, dtype=np.uint32).reshape(npixelx, npixely))/npixelx iindx, jindx = np.meshgrid( np.arange(npixelx), np.arange(npixely)) sqradiusa = (xap[iindx.flatten()].reshape(np.shape(iindx))**2+ yap[jindx.flatten()].reshape(np.shape(jindx))**2) sqradiusb = (xbp[iindx.flatten()].reshape(np.shape(iindx))**2+ ybp[jindx.flatten()].reshape(np.shape(jindx))**2 ) # Integrate within the annulus defined by the circles [Radius1,Radius2] # within each pixel. integral = np.zeros((npixely, npixelx)) qpix0 = (sqradiusb > sqradius1) & (sqradiusa < sqradius2) pix1 = np.nonzero( (sqradiusb < sqradius2) & qpix0==True) count=np.size(pix1) if (count != 0): integral[pix1] = (xbp[iindx[pix1]] - xap[iindx[pix1]]) * ybp[jindx[pix1]] pix2 = np.nonzero((sqradiusb > sqradius2) & qpix0==True) count=np.size(pix2) if (count != 0): integral[pix2] = photfrac_intcirc(xap[iindx[pix2]], xbp[iindx[pix2]], yap[jindx[pix2]], ybp[jindx[pix2]], radius2) pix1 = np.nonzero((sqradiusa >= sqradius1) & qpix0==True) count= np.size(pix1) if (count != 0): integral[pix1] = integral[pix1] - (xbp[iindx[pix1]] - xap[iindx[pix1]]) * yap[jindx[pix1]] pix2 = np.nonzero((sqradiusa < sqradius1) & qpix0==True) count = np.size(pix2) if (count != 0): integral[pix2] = integral[pix2] - photfrac_intcirc(xap[iindx[pix2]], xbp[iindx[pix2]], yap[jindx[pix2]], ybp[jindx[pix2]], radius1) # Collapse the split pixels back into the original pixels if (q_splity): integral[jsplit,0:(npixelx - 1)+1] = integral[jsplit,0:(npixelx - 1)+1] + integral[npixely - 1,0:(npixelx - 1)+1] if (q_splitx): integral[0:(npixely - 1)+1,isplit] = integral[0:(npixely - 1)+1,isplit] + integral[0:(npixely - 1)+1,npixelx - 1] # Set the return values xpixnum = iindx[0:(npixely - 1 - q_splity)+1,0:(npixelx - 1 - q_splitx)+1] + istart ypixnum = jindx[0:(npixely - 1 - q_splity)+1,0:(npixelx - 1 - q_splitx)+1] + jstart fracs = integral[0:(npixely - 1 - q_splity)+1,0:(npixelx - 1 - q_splitx)+1] # Limit the return values to only those pixels with non-zero contributions pix1 = np.nonzero(fracs != 0.0) if (length(pix1)==0): return # ??? Should never happen! xpixnum = xpixnum[pix1] ypixnum = ypixnum[pix1] pixnum = 0 + xpixnum + xdimen * ypixnum fracs = fracs[pix1] # Test to see if aperature exceeds image boundary by computing the # ratio of the filled pixels to the area of the annulus. If all # pixels are within the image boundary, then fillfrac=1.0. fillfrac = np.sum(fracs) / (np.pi * (sqradius2 - sqradius1)) outputs = {'pixnum':pixnum, 'xpixnum':xpixnum, 'ypixnum':ypixnum, 'fracs':fracs, 'fillfrac':fillfrac} return outputs
def length(self, data): self.length = length.length(data)