Ejemplo n.º 1
0
def generic_gradient_magnitude(
    input, derivative, output=None, mode="reflect", cval=0.0, extra_arguments=(), extra_keywords={}
):
    """Calculate a gradient magnitude using the provdide function for
    the gradient.

    The derivative parameter must be a callable with the following 
    signature:
                    
    derivative(input, axis, output, mode, cval,
               *extra_arguments, **extra_keywords)

    The extra_arguments and extra_keywords arguments can be used to pass 
    extra arguments and keywords that are passed to derivative2 at each 
    call.
    """
    input = numarray.asarray(input)
    output, return_value = _ni_support._get_output(output, input)
    axes = range(input.rank)
    if len(axes) > 0:
        derivative(input, axes[0], output, mode, cval, *extra_arguments, **extra_keywords)
        numarray.multiply(output, output, output)
        for ii in range(1, len(axes)):
            tmp = derivative(input, axes[ii], output.type(), mode, cval, *extra_arguments, **extra_keywords)
            numarray.multiply(tmp, tmp, tmp)
            output += tmp
        numarray.sqrt(output, output)
    else:
        output[...] = input[...]
    return return_value
Ejemplo n.º 2
0
def getpositions(ximage, yimage, xmax, ymax):
    dmin = 5.  #minimum distance to object + sqrt(isoarea)
    xpos = []
    ypos = []
    d = N.zeros(len(ximage), 'f')
    #print len(d)
    i = 0
    while i < npoints:
        xtemp = int(round(random.uniform(
            5., 125.)))  #random.uniform(5.,125.)#*xmax
        ytemp = int(round(random.uniform(
            5., 140.)))  #random.uniform(5.,140.)#*ymax
        if (xtemp > 10.) & (ytemp < (ymax - 10)):
            d = N.sqrt((ximage - xtemp)**2 + (yimage - ytemp)**2)
            if (min(d) > dmin):
                if i > 2:
                    xap = N.array(xpos, 'f')
                    yap = N.array(ypos, 'f')
                    d2 = N.sqrt((xtemp - xap)**2 + (ytemp - yap)**2)
                    if (min(d2) > dmin):
                        xpos.append(xtemp)
                        ypos.append(ytemp)
                        i = i + 1

            else:
                xpos.append(xtemp)
                ypos.append(ytemp)
                i = i + 1
    xpos = N.array(xpos, 'f')
    ypos = N.array(ypos, 'f')
    return xpos, ypos
Ejemplo n.º 3
0
 def plot_source_info(self,event):
 
     ra = event.xdata
     dec = event.ydata
     #print (event.key,ra,dec)
     if event.key == 's':
         #print self.constructed_pos[:,0]
         #print self.constructed_pos[:,1]
         dist = numarray.sqrt( (self.constructed_pos[:,0] - ra)**2 + (self.constructed_pos[:,1] - dec)**2)
         
         #print dist
         #print "min distance = %f " % min(dist)
         the_source_ind = numarray.compress(dist == min(dist), numarray.fromlist(range(len(self.constructed_source_list))))
         #print the_source_ind
         #the_source_ind = numarray.compress(dist == min(dist),numarray.arange(len(self.constructed_source_list)))
         the_source = self.constructed_source_list[the_source_ind[0]]
         print the_source
         dist = numarray.sqrt( (the_source.current_pos[0] - self.real_pos[:,0])**2 + (the_source.current_pos[1] - self.real_pos[:,1])**2)
         print "min distances to nearest real source = %f arcsec" % min(dist)
         the_source_ind = numarray.compress(dist == min(dist), numarray.fromlist(range(len(self.real_list))))
         the_source = self.real_list[the_source_ind[0]]
         print "That real source is at ra=%f dec=%f" % (the_source.start_pos[0],the_source.start_pos[1])
     if event.key == 'r':
         dist = numarray.sqrt( (self.real_pos[:,0] - ra)**2 + (self.real_pos[:,1] - dec)**2)
         
         #print dist
         #print "min distance = %f " % min(dist)
         the_source_ind = numarray.compress(dist == min(dist), numarray.fromlist(range(len(self.real_list))))
         #print the_source_ind
         #the_source_ind = numarray.compress(dist == min(dist),numarray.arange(len(self.constructed_source_list)))
         the_source = self.real_list[the_source_ind[0]]
         print the_source
Ejemplo n.º 4
0
 def getnearest(self,j):
     self.sig5=N.zeros(len(self.ra),'f')
     self.sig10=N.zeros(len(self.ra),'f')
     self.sig5phot=N.zeros(len(self.ra),'f')
     self.sig10phot=N.zeros(len(self.ra),'f')
     self.nearest=N.zeros(len(self.ra),'f')#distance to nearest neighbor
     self.dmagnearest=N.zeros(len(self.ra),'f')#mag diff b/w spec obj and nearest
     for i in range(len(self.ra)):
         angdist=my.DA(c.z[j],h100)#kpc/arcsec
         if self.memb[i] > 0:
             dspec=N.sqrt((self.ra[i]-self.ra)**2+(self.dec[i]-self.dec)**2)#sorted array of distances in degrees
             dphot=N.sqrt((self.ra[i]-self.photra)**2+(self.dec[i]-self.photdec)**2)#sorted array of distances in degrees
             Mvsort=N.take(self.V,N.argsort(dspec))
             phMvsort=N.take(self.phMv,N.argsort(dphot))
             dspecsort=N.take(dspec,N.argsort(dspec))
             self.sig5[i]=5./(N.pi)/(dspecsort[5]*3600.*angdist/1000.)**2#convert from deg to arcsec, multiply by DA (kpc/arcsec), divide by 1000 to convert to Mpc, index 5 element b/c 0 is itself
             if (len(dspecsort) > 10):
                 self.sig10[i]=10./(N.pi)/(dspecsort[10]*3600.*angdist/1000.)**2
             else:
                 self.sig10[i]=0.
             dphotsort=N.take(dphot,N.argsort(dphot))
             self.nearest[i]=dphotsort[0]
             self.dmagnearest[i]=phMvsort[0]-Mvsort[0]
             self.sig5phot[i]=5./(N.pi)/(dphotsort[5]*3600.*angdist/1000.)**2
             self.sig10phot[i]=10./(N.pi)/(dphotsort[10]*3600.*angdist/1000.)**2
Ejemplo n.º 5
0
def plotFitRms(root, polyroot, gcfitdir):
    s = starset.StarSet(root)
    s.loadPolyfit(polyroot, arcsec=1, accel=0)

    years = s.stars[0].years
    fitPx = s.getArray('fitXv.p')
    fitVx = s.getArray('fitXv.v')
    fitPy = s.getArray('fitYv.p')
    fitVy = s.getArray('fitYv.v')
    t0x = s.getArray('fitXv.t0')
    t0y = s.getArray('fitYv.t0')

    rmsX = na.zeros(len(s.stars), type=na.Float)
    rmsY = na.zeros(len(s.stars), type=na.Float)
    rms = na.zeros(len(s.stars), type=na.Float)
    cnt = na.zeros(len(s.stars), type=na.Int)

    for ee in range(len(years)):
        dtX = years[ee] - t0x
        dtY = years[ee] - t0y

        xfit = fitPx + (dtX * fitVx)
        yfit = fitPy + (dtY * fitVy)

        x = s.getArrayFromEpoch(ee, 'x')
        y = s.getArrayFromEpoch(ee, 'y')
        xpix = s.getArrayFromEpoch(ee, 'xpix')
        ypix = s.getArrayFromEpoch(ee, 'ypix')

        diffx = xfit - x
        diffy = yfit - y
        diff = na.sqrt(diffx**2 + diffy**2)

        idx = (na.where(xpix > -999))[0]

        rmsX[idx] += diffx**2
        rmsY[idx] += diffy**2
        rms[idx] += diff**2
        cnt[idx] += 1

    rmsX = na.sqrt(rmsX / cnt) * 1000.0
    rmsY = na.sqrt(rmsY / cnt) * 1000.0
    rms = na.sqrt(rms / cnt) * 1000.0

    mag = s.getArray('mag')
    x = s.getArray('x')
    y = s.getArray('y')
    r = na.sqrt(x**2 + y**2)

    idx = (na.where(mag < 15))[0]

    p.clf()
    p.semilogy(r[idx], rms[idx], 'k.')
Ejemplo n.º 6
0
def plotFitRms(root, polyroot, gcfitdir):
    s = starset.StarSet(root)
    s.loadPolyfit(polyroot, arcsec=1, accel=0)

    years = s.stars[0].years
    fitPx = s.getArray('fitXv.p')
    fitVx = s.getArray('fitXv.v')
    fitPy = s.getArray('fitYv.p')
    fitVy = s.getArray('fitYv.v')
    t0x = s.getArray('fitXv.t0')
    t0y = s.getArray('fitYv.t0')

    rmsX = na.zeros(len(s.stars), type=na.Float)
    rmsY = na.zeros(len(s.stars), type=na.Float)
    rms = na.zeros(len(s.stars), type=na.Float)
    cnt = na.zeros(len(s.stars), type=na.Int)

    for ee in range(len(years)):
        dtX = years[ee] - t0x
        dtY = years[ee] - t0y

        xfit = fitPx + (dtX * fitVx)
        yfit = fitPy + (dtY * fitVy)

        x = s.getArrayFromEpoch(ee, 'x')
        y = s.getArrayFromEpoch(ee, 'y')
        xpix = s.getArrayFromEpoch(ee, 'xpix')
        ypix = s.getArrayFromEpoch(ee, 'ypix')

        diffx = xfit - x
        diffy = yfit - y
        diff = na.sqrt(diffx**2 + diffy**2)

        idx = (na.where(xpix > -999))[0]

        rmsX[idx] += diffx**2
        rmsY[idx] += diffy**2
        rms[idx] += diff**2
        cnt[idx] += 1

    rmsX = na.sqrt(rmsX / cnt) * 1000.0
    rmsY = na.sqrt(rmsY / cnt) * 1000.0
    rms = na.sqrt(rms / cnt) * 1000.0

    mag = s.getArray('mag')
    x = s.getArray('x')
    y = s.getArray('y')
    r = na.sqrt(x**2 + y**2)

    idx = (na.where(mag < 15))[0]

    p.clf()
    p.semilogy(r[idx], rms[idx], 'k.')
Ejemplo n.º 7
0
def phaselag(spectrum, coherence, numinbin):

    """Compute phase lags from a cross spectrum.

    lag, error = phaselag(spectrum, coherence, numinbin)

    Inputs:

    spectrum: The cross spectrum.  A complex array.

    coherence: The uncorrected coherence.

    numinbin: The number of raw estimates that went into each frequency bin.

    Outputs:

    lag: The phase of the input spectrum.  In radians.

    error: The standard deviation of the lag.  Also in radians.
    Calculated from eq. (9.52) in Bendat & Piersol 2000."""

    lag = num.arctan2(spectrum.imag, spectrum.real)

    # eq. (9.52) in Bendat & Piersol 2000
    error = num.sqrt((1 - coherence) / (2 * numinbin * coherence))

    return lag, error
Ejemplo n.º 8
0
def binitbins(xmin, xmax, nbin, x, y):  #use equally spaced bins
    dx = float((xmax - xmin) / (nbin))
    xbin = N.arange(xmin, (xmax), dx) + dx / 2.
    #print "within binitbins"
    #print "xbin = ",xbin
    #print "dx = ",dx
    #print "xmax = ",xmax
    #print "xmin = ",xmin
    ybin = N.zeros(len(xbin), 'd')
    ybinerr = N.zeros(len(xbin), 'd')
    xbinnumb = N.array(len(x), 'd')
    x1 = N.compress((x >= xmin) & (x <= xmax), x)
    y1 = N.compress((x >= xmin) & (x <= xmax), y)
    x = x1
    y = y1
    xbinnumb = ((x - xmin) * nbin / (xmax - xmin)
                )  #calculate x  bin number for each point
    j = -1
    for i in range(len(xbin)):
        ydata = N.compress(abs(xbinnumb - float(i)) < .5, y)
        try:
            ybin[i] = N.average(ydata)
            #ybin[i]=pylab.median(ydata)
            ybinerr[i] = pylab.std(ydata) / N.sqrt(float(len(ydata)))
        except ZeroDivisionError:
            ybin[i] = 0.
            ybinerr[i] = 0.
    return xbin, ybin, ybinerr
Ejemplo n.º 9
0
def binitbinsfix(binsleft, binsright, x, y):  #give bins for binning
    nbin = len(binsleft)
    xbin = N.zeros(len(binsleft), 'f')
    ybin = N.zeros(len(binsleft), 'f')
    ybinerr = N.zeros(len(binsleft), 'f')
    y = N.take(y, N.argsort(x))  #sort y according to x rankings
    x = N.take(x, N.argsort(x))

    j = -1
    for i in range(len(xbin)):
        xmin = binsleft[i]
        xmax = binsright[i]
        yb = []
        for j in range(len(x)):
            if x[j] > xmin:
                yb.append(y[j])
            if x[j] > xmax:
                yb = N.array(yb, 'f')
                xbin[i] = 0.5 * (xmin + xmax)
                try:
                    ybin[i] = pylab.median(yb)
                    ybinerr[i] = pylab.std(yb) / N.sqrt(1. * len(yb))
                except ZeroDivisionError:
                    print "warning: ZeroDivision error in binitbinsfix"
                    ybin[i] = 0.
                    ybinerr[i] = 0.

                break

    return xbin, ybin, ybinerr
Ejemplo n.º 10
0
def horizontalhist(x, xmin, xmax, nbin):  #give bins for binning
    #nbin=len(bins)
    xbin = N.zeros(nbin, 'f')
    ybin = N.zeros(nbin, 'f')
    ybinerr = N.zeros(nbin, 'f')
    dbin = (xmax - xmin) / (1. * nbin)
    bins = N.arange(xmin, (xmax + dbin), dbin)
    x = N.take(x, N.argsort(x))
    xmin = min(bins)
    xmax = max(bins)
    xbinnumb = ((x - xmin) * nbin / (xmax - xmin)
                )  #calculate x  bin number for each point
    #print "from within horizontal hist"
    #print "bins = ",bins
    for i in range(len(xbin) - 1):
        xmin = bins[i]
        xmax = bins[i + 1]
        xbin[i] = xmin
        yb = 0.
        for j in range(len(x)):
            if (x[j] > xmin) & (x[j] <= xmax):
                yb = yb + 1.
        ybin[i] = yb
        ybinerr[i] = N.sqrt(yb)
        #print i,len(xbin),xbin[i],xmin,xmax,ybin[i],bins[i]
    xbin[(len(xbin) - 1)] = xbin[(len(xbin) - 2)] + dbin
    #xbin=bins
    #print "from w/in horizontal hist, ybin = ",ybin
    return xbin, ybin, ybinerr
Ejemplo n.º 11
0
    def points(self,npoints):
        """
        compute arrays of npoints equally spaced
        intermediate points along the great circle.

        input parameter npoints is the number of points
        to compute.

        Returns lons, lats (lists with longitudes and latitudes
        of intermediate points in degrees).

        For example npoints=10 will return arrays lons,lats of 10
        equally spaced points along the great circle.
        """
        # can't do it if endpoints of great circle are antipodal, since
        # route is undefined.
        if self.antipodal:
            raise ValueError,'cannot compute intermediate points on a great circle whose endpoints are antipodal'
        d = self.distance
        delta = 1.0/(npoints-1)
        f = delta*N.arange(npoints)
        lat1 = self.lat1
        lat2 = self.lat2
        lon1 = self.lon1
        lon2 = self.lon2
        A = N.sin((1-f)*d)/math.sin(d)
        B = N.sin(f*d)/math.sin(d)
        x = A*math.cos(lat1)*math.cos(lon1)+B*math.cos(lat2)*math.cos(lon2)
        y = A*math.cos(lat1)*math.sin(lon1)+B*math.cos(lat2)*math.sin(lon2)
        z = A*math.sin(lat1)               +B*math.sin(lat2)
        lats=N.arctan2(z,N.sqrt(x**2+y**2))
        lons=N.arctan2(y,x)
        lons = map(math.degrees,lons.tolist())
        lats = map(math.degrees,lats.tolist())
        return lons,lats
Ejemplo n.º 12
0
    def abs_fft(self, points=None, zoom=None,write = 'off'):
	"""
	Fourier transforms the timesignal;
	points is the number of points to transform, if more points given than data points
	the rest is zero padded

	absfft(points=4096)
	"""
	realdata = numarray.array(self.the_result.y[0])
	imdata = numarray.array(self.the_result.y[1])
	data = realdata + 1j*imdata
	fftdata = self.rearrange(numarray.fft.fft(data, points))
	absfft = numarray.sqrt(fftdata.real**2 + fftdata.imag**2)
	# create our x axis
	n = fftdata.size()
	self.the_result.x = numarray.arange(n)*(self.sampling_rate/n)-(self.sampling_rate/2.0)
	self.the_result.y[0] = absfft
	self.the_result.y[1] = numarray.zeros(n)
	if write == 'on':
	    return self
	else:
	    if zoom is None: return self.the_result
	    else:
		center, width = zoom
		return self.zoom(self.the_result, center, width)
Ejemplo n.º 13
0
def phaselag(spectrum, coherence, numinbin):
    """Compute phase lags from a cross spectrum.

    lag, error = phaselag(spectrum, coherence, numinbin)

    Inputs:

    spectrum: The cross spectrum.  A complex array.

    coherence: The uncorrected coherence.

    numinbin: The number of raw estimates that went into each frequency bin.

    Outputs:

    lag: The phase of the input spectrum.  In radians.

    error: The standard deviation of the lag.  Also in radians.
    Calculated from eq. (9.52) in Bendat & Piersol 2000."""

    lag = num.arctan2(spectrum.imag, spectrum.real)

    # eq. (9.52) in Bendat & Piersol 2000
    error = num.sqrt((1 - coherence) / (2 * numinbin * coherence))

    return lag, error
Ejemplo n.º 14
0
def scipyhist2(bins, y):  #give bins for binning
    nbin = len(bins)
    xbin = N.zeros(len(bins), 'f')
    ybin = N.zeros(len(bins), 'f')
    ybinerr = N.zeros(len(bins), 'f')
    y = N.take(y, N.argsort(y))
    xmin = min(bins)
    xmax = max(bins)
    xbinnumb = ((y - xmin) * nbin / (xmax - xmin)
                )  #calculate x  bin number for each point
    for i in range(len(xbin) - 1):
        xmin = bins[i]
        xmax = bins[i + 1]
        yb = 0.
        for j in range(len(y)):
            if y[j] > xmin:
                yb = yb + 1.
            if y[j] > xmax:
                ybin[i] = yb
                ybinerr[i] = N.sqrt(yb)
                xbin[i] = 0.5 * (xmin + xmax)

                break

    return xbin, ybin, ybinerr
Ejemplo n.º 15
0
    def readpsoutput(self,file,z):
	input=open(file,'r')
	mass=[]
	frac=[]

	for line in input:
	    t=line.split()
	    mass.append(float(t[2]))
	    frac.append(float(t[3]))

	    #try:
		#frac.append(float(t[3]))
	    #except:
	#	frac.append(1.e-10)
	input.close()

	mass=N.array(mass,'d')
	sigma=((mass/(1.2e15/h)*N.sqrt(.7+.3*(1+z)**3))**(1./3.))*1000.
	frac=N.array(frac,'d')
	sigma=N.log10(sigma)


	#maccret=(frac*mass)
	maccret=N.zeros(len(mass),'d')
	for i in range(len(mass)):
	    maccret[i]=mass[i]*frac[i]
	    print i,mass[i],frac[i],maccret[i]
	frac=N.log10(frac)
	self.sigma=sigma
	self.mass=mass
	self.frac=frac
	self.maccret=maccret
Ejemplo n.º 16
0
def verticalhist(y, ymin, ymax, nbin):  #give bins for binning
    #nbin=len(bins)
    xbin = N.zeros(nbin, 'f')
    ybin = N.zeros(nbin, 'f')
    ybinerr = N.zeros(nbin, 'f')
    dbin = (ymax - ymin) / (1. * nbin)
    bins = N.arange(ymin, (ymax + dbin), dbin)
    y = N.take(y, N.argsort(y))
    xmin = min(bins)
    xmax = max(bins)
    xbinnumb = ((y - xmin) * nbin / (xmax - xmin)
                )  #calculate x  bin number for each point
    for i in range(len(xbin) - 1):
        xmin = bins[i]
        xmax = bins[i + 1]
        yb = 0.
        for j in range(len(y)):
            if y[j] > xmin:
                yb = yb + 1.
            if y[j] > xmax:
                ybin[i] = yb
                ybinerr[i] = N.sqrt(yb)
                #xbin[i]=0.5*(xmin+xmax)
                xbin[i] = xmax
                break
    drawhist(ybin, xbin)
Ejemplo n.º 17
0
    def points(self,npoints):
        """
        compute arrays of npoints equally spaced
        intermediate points along the great circle.

        input parameter npoints is the number of points
        to compute.

        Returns lons, lats (lists with longitudes and latitudes
        of intermediate points in degrees).

        For example npoints=10 will return arrays lons,lats of 10
        equally spaced points along the great circle.
        """
        # must ask for at least 2 points.
        if npoints <= 1:
            raise ValueError,'npoints must be greater than 1'
        elif npoints == 2:
            return [math.degrees(self.lon1),math.degrees(self.lon2)],[math.degrees(self.lat1),math.degrees(self.lat2)]
        # can't do it if endpoints are antipodal, since
        # route is undefined.
        if self.antipodal:
            raise ValueError,'cannot compute intermediate points on a great circle whose endpoints are antipodal'
        d = self.gcarclen
        delta = 1.0/(npoints-1)
        f = delta*N.arange(npoints) # f=0 is point 1, f=1 is point 2.
        incdist = self.distance/(npoints-1)
        lat1 = self.lat1
        lat2 = self.lat2
        lon1 = self.lon1
        lon2 = self.lon2
        # perfect sphere, use great circle formula
        if self.f == 0.:
            A = N.sin((1-f)*d)/math.sin(d)
            B = N.sin(f*d)/math.sin(d)
            x = A*math.cos(lat1)*math.cos(lon1)+B*math.cos(lat2)*math.cos(lon2)
            y = A*math.cos(lat1)*math.sin(lon1)+B*math.cos(lat2)*math.sin(lon2)
            z = A*math.sin(lat1)               +B*math.sin(lat2)
            lats=N.arctan2(z,N.sqrt(x**2+y**2))
            lons=N.arctan2(y,x)
            lons = map(math.degrees,lons.tolist())
            lats = map(math.degrees,lats.tolist())
        # use ellipsoid formulas
        else:
            latpt = self.lat1
            lonpt = self.lon1
            azimuth = self.azimuth12
            lons = [math.degrees(lonpt)]
            lats = [math.degrees(latpt)]
            for n in range(npoints-2):
                latptnew,lonptnew,alpha21=vinc_pt(self.f,self.a,latpt,lonpt,azimuth,incdist) 
                d,azimuth,a21=vinc_dist(self.f,self.a,latptnew,lonptnew,lat2,lon2) 
                lats.append(math.degrees(latptnew))
                lons.append(math.degrees(lonptnew))
                latpt = latptnew; lonpt = lonptnew
            lons.append(math.degrees(self.lon2))
            lats.append(math.degrees(self.lat2))
        return lons,lats
Ejemplo n.º 18
0
def mask(clus_id, line_s):
    imagefile = c.imagefile
    sex_cata = c.sex_cata
    threshold = c.threshold
    thresh_area = c.thresh_area
    size = c.size
    mask_reg = c.mask_reg
    x = n.reshape(n.arange(size*size),(size,size)) % size
    x = x.astype(n.Float32)
    y = n.reshape(n.arange(size*size),(size,size)) / size
    y = y.astype(n.Float32)
    values = line_s.split()
    mask_file = 'mask_' + str(imagefile)[:6] + '_'  + str(clus_id) + '.fits'
    xcntr_o  = float(values[1]) #x center of the object
    ycntr_o  = float(values[2]) #y center of the object
    xcntr = size / 2.0 + 1.0 + xcntr_o - int(xcntr_o)
    ycntr = size / 2.0 + 1.0 + ycntr_o - int(ycntr_o)
    mag    = float(values[7]) #Magnitude
    radius = float(values[9]) #Half light radius
    mag_zero = c.mag_zero #magnitude zero point
    sky	 = float(values[10]) #sky 
    pos_ang = float(values[11]) - 90.0 #position angle
    axis_rat = 1.0 / float(values[12]) #axis ration b/a
    major_axis = float(values[14])	#major axis of the object
    z = n.zeros((size,size))
    for line_j in open(sex_cata,'r'):
        try:
            values = line_j.split()
            xcntr_n  = float(values[1]) #x center of the neighbour
            ycntr_n  = float(values[2]) #y center of the neighbour
            mag    = float(values[7]) #Magnitude
            radius = float(values[9]) #Half light radius
            sky      = float(values[10]) #sky
            pos_ang = float(values[11]) - 90.0 #position angle
            axis_rat = 1.0/float(values[12]) #axis ration b/a
            area = float(values[13])
            maj_axis = float(values[14])#major axis of neighbour
            if(abs(xcntr_n - xcntr_o) < size/2.0 and abs(ycntr_n - ycntr_o) \
               < size/2.0 and area < thresh_area):
                if(abs(xcntr_n - xcntr_o) >= major_axis * threshold or \
                   abs(ycntr_n - ycntr_o) >= major_axis * threshold):
                    if((xcntr_o - xcntr_n) < 0):
                        xn = xcntr + abs(xcntr_n - xcntr_o)
                    if((ycntr_o - ycntr_n) < 0):
                        yn = ycntr + abs(ycntr_n - ycntr_o)
                    if((xcntr_o - xcntr_n) > 0):
                        xn = xcntr - (xcntr_o - xcntr_n)
                    if((ycntr_o - ycntr_n) > 0):
                        yn = ycntr - (ycntr_o - ycntr_n)
                    tx = x - xn + 0.5 
                    ty = y - yn + 0.5
                    R = n.sqrt(tx**2.0 + ty**2.0)
                    z[n.where(R<=mask_reg*maj_axis)] = 1
        except:
            pass	
    hdu = pyfits.PrimaryHDU(z.astype(n.Float32))
    hdu.writeto(mask_file)
Ejemplo n.º 19
0
    def drawmeridians(self,ax,meridians,color='k',linewidth=1., \
                      linestyle='--',dashes=[1,1]):
        """
 draw meridians (longitude lines).

 ax - current axis instance.
 meridians - list containing longitude values to draw (in degrees).
 color - color to draw meridians (default black).
 linewidth - line width for meridians (default 1.)
 linestyle - line style for meridians (default '--', i.e. dashed).
 dashes - dash pattern for meridians (default [1,1], i.e. 1 pixel on,
  1 pixel off).
        """
        if self.projection not in ['merc','cyl']:
            lats = N.arange(-80,81).astype('f')
        else:
            lats = N.arange(-90,91).astype('f')
        xdelta = 0.1*(self.xmax-self.xmin)
        ydelta = 0.1*(self.ymax-self.ymin)
        for merid in meridians:
            lons = merid*N.ones(len(lats),'f')
            x,y = self(lons,lats)
            # remove points outside domain.
            testx = N.logical_and(x>=self.xmin-xdelta,x<=self.xmax+xdelta)
            x = N.compress(testx, x)
            y = N.compress(testx, y)
            testy = N.logical_and(y>=self.ymin-ydelta,y<=self.ymax+ydelta)
            x = N.compress(testy, x)
            y = N.compress(testy, y)
            if len(x) > 1 and len(y) > 1:
                # split into separate line segments if necessary.
                # (not necessary for mercator or cylindrical).
                xd = (x[1:]-x[0:-1])**2
                yd = (y[1:]-y[0:-1])**2
                dist = N.sqrt(xd+yd)
                split = dist > 500000.
                if N.sum(split) and self.projection not in ['merc','cyl']:
                   ind = (N.compress(split,MLab.squeeze(split*N.indices(xd.shape)))+1).tolist()
                   xl = []
                   yl = []
                   iprev = 0
                   ind.append(len(xd))
                   for i in ind:
                       xl.append(x[iprev:i])
                       yl.append(y[iprev:i])
                       iprev = i
                else:
                    xl = [x]
                    yl = [y]
                # draw each line segment.
                for x,y in zip(xl,yl):
                    # skip if only a point.
                    if len(x) > 1 and len(y) > 1:
                        l = Line2D(x,y,linewidth=linewidth,linestyle=linestyle)
                        l.set_color(color)
                        l.set_dashes(dashes)
                        ax.add_line(l)
Ejemplo n.º 20
0
    def plot_source_info(self, event):

        ra = event.xdata
        dec = event.ydata
        #print (event.key,ra,dec)
        if event.key == 's':
            #print self.constructed_pos[:,0]
            #print self.constructed_pos[:,1]
            dist = numarray.sqrt((self.constructed_pos[:, 0] - ra)**2 +
                                 (self.constructed_pos[:, 1] - dec)**2)

            #print dist
            #print "min distance = %f " % min(dist)
            the_source_ind = numarray.compress(
                dist == min(dist),
                numarray.fromlist(range(len(self.constructed_source_list))))
            #print the_source_ind
            #the_source_ind = numarray.compress(dist == min(dist),numarray.arange(len(self.constructed_source_list)))
            the_source = self.constructed_source_list[the_source_ind[0]]
            print the_source
            dist = numarray.sqrt(
                (the_source.current_pos[0] - self.real_pos[:, 0])**2 +
                (the_source.current_pos[1] - self.real_pos[:, 1])**2)
            print "min distances to nearest real source = %f arcsec" % min(
                dist)
            the_source_ind = numarray.compress(
                dist == min(dist),
                numarray.fromlist(range(len(self.real_list))))
            the_source = self.real_list[the_source_ind[0]]
            print "That real source is at ra=%f dec=%f" % (
                the_source.start_pos[0], the_source.start_pos[1])
        if event.key == 'r':
            dist = numarray.sqrt((self.real_pos[:, 0] - ra)**2 +
                                 (self.real_pos[:, 1] - dec)**2)

            #print dist
            #print "min distance = %f " % min(dist)
            the_source_ind = numarray.compress(
                dist == min(dist),
                numarray.fromlist(range(len(self.real_list))))
            #print the_source_ind
            #the_source_ind = numarray.compress(dist == min(dist),numarray.arange(len(self.constructed_source_list)))
            the_source = self.real_list[the_source_ind[0]]
            print the_source
Ejemplo n.º 21
0
 def getnearestgen(self,ra1,dec1,ra2,dec2,j):#measure distances from ra1, dec1 to members in catalog ra2, dec2
     sig5=N.zeros(len(ra1),'f')
     sig10=N.zeros(len(ra1),'f')
     for i in range(len(ra1)):
         angdist=my.DA(c.z[j],h100)#kpc/arcsec
         dspec=N.sqrt((ra1[i]-ra2)**2+(dec1[i]-dec2)**2)#sorted array of distances in degrees
         dspecsort=N.take(dspec,N.argsort(dspec))
         sig5[i]=5./(N.pi)/(dspecsort[5]*3600.*angdist/1000.)**2#convert from deg to arcsec, multiply by DA (kpc/arcsec), divide by 1000 to convert to Mpc, index 5 element b/c 0 is itself
         sig10[i]=10./(N.pi)/(dspecsort[10]*3600.*angdist/1000.)**2#convert from deg to arcsec, multiply by DA (kpc/arcsec), divide by 1000 to convert to Mpc, index 5 element b/c 0 is itself
     return sig5, sig10
Ejemplo n.º 22
0
def line_search_BFGS(f, xk, pk, gfk, args=(), c1=1e-4, alpha0=1):
    """alpha, fc, gc = line_search(f, xk, pk, gfk,
                                   args=(), c1=1e-4, alpha0=1)

    minimize over alpha, the function f(xk+alpha pk) using the interpolation
    algorithm (Armiijo backtracking) as suggested by
    Wright and Nocedal in 'Numerical Optimization', 1999, pg. 56-57
    """

    fc = 0
    phi0 = apply(f, (xk, ) + args)  # compute f(xk)
    phi_a0 = apply(f, (xk + alpha0 * pk, ) + args)  # compute f
    fc = fc + 2
    derphi0 = Num.dot(gfk, pk)

    if (phi_a0 <= phi0 + c1 * alpha0 * derphi0):
        return alpha0, fc, 0

    # Otherwise compute the minimizer of a quadratic interpolant:

    alpha1 = -(derphi0) * alpha0**2 / 2.0 / (phi_a0 - phi0 - derphi0 * alpha0)
    phi_a1 = apply(f, (xk + alpha1 * pk, ) + args)
    fc = fc + 1

    if (phi_a1 <= phi0 + c1 * alpha1 * derphi0):
        return alpha1, fc, 0

    # Otherwise loop with cubic interpolation until we find an alpha which satifies
    #  the first Wolfe condition (since we are backtracking, we will assume that
    #  the value of alpha is not too small and satisfies the second condition.

    while 1:  # we are assuming pk is a descent direction
        factor = alpha0**2 * alpha1**2 * (alpha1 - alpha0)
        a = alpha0**2 * (phi_a1 - phi0 - derphi0*alpha1) - \
            alpha1**2 * (phi_a0 - phi0 - derphi0*alpha0)
        a = a / factor
        b = -alpha0**3 * (phi_a1 - phi0 - derphi0*alpha1) + \
            alpha1**3 * (phi_a0 - phi0 - derphi0*alpha0)
        b = b / factor

        alpha2 = (-b + Num.sqrt(abs(b**2 - 3 * a * derphi0))) / (3.0 * a)
        phi_a2 = apply(f, (xk + alpha2 * pk, ) + args)
        fc = fc + 1

        if (phi_a2 <= phi0 + c1 * alpha2 * derphi0):
            return alpha2, fc, 0

        if (alpha1 - alpha2) > alpha1 / 2.0 or (1 - alpha2 / alpha1) < 0.96:
            alpha2 = alpha1 / 2.0

        alpha0 = alpha1
        alpha1 = alpha2
        phi_a0 = phi_a1
        phi_a1 = phi_a2
Ejemplo n.º 23
0
 def __call__(self, x):
     if (type(x) == type(1) or type(x) == type(1.)):
         return self.value(x)
     elif (type(x) == type([])):
         my_list = []
         for xx in x:
             my_list.append(self.value(xx))
         return my_list
     elif (type(x) == numarray.NumArray):
         return (numarray.exp(-numarray.power((x-self.mean)/self.sigma, 2)/2.)
                 /numarray.sqrt(2.*numarray.pi)/self.sigma)
Ejemplo n.º 24
0
def fit_i(x, y, sig, int_scat=0.0):
    #Given a set of data points x, y,
    #with individual measurement error standard deviations sig,
    #fit them to a straight line relation y = a + bx
    #with intrinsic scatter int_scat by minimizing chi-sq.
    #Returned are a, b and their respective probable uncertainties siga and sigb,
    #the chi-square chi2, and the scatter sigdat.
    #If mwt=0 on input, then the standard deviations are assumed to be unavailable:
    #the normalization of chi2 is to unit standard deviation on all points.
    sigtot = N.sqrt(sig**2 + int_scat**2)
    return fit(x, y, sigtot)
Ejemplo n.º 25
0
def fit_intercept_i(x, y, sig, int_scat, b=0.0, sigb=0.0):
    #Given a set of data points x, y,
    #with individual standard deviations sig,
    #fit them to a straight line y = a + bx by minimizing chi-sq,
    #where the intercept of the line is fixed.
    #Returned are a and its probable uncertainty siga,
    #the chi-square chi2, and the scatter sigdat.
    #If mwt=0 on input, then the standard deviations are assumed to be unavailable:
    #the normalization of chi2 is to unit standard deviation on all points.
    sigtot = N.sqrt(sig**2 + int_scat**2)
    return fit_intercept(x, y, sigtot, 1, b, sigb)
Ejemplo n.º 26
0
 def __call__(self, x):
     if (type(x) == type(1) or type(x) == type(1.)):
         return self.value(x)
     elif (type(x) == type([])):
         my_list = []
         for xx in x:
             my_list.append(self.value(xx))
         return my_list
     elif (type(x) == numarray.NumArray):
         return (numarray.exp(-numarray.power(
             (x - self.mean) / self.sigma, 2) / 2.) /
                 numarray.sqrt(2. * numarray.pi) / self.sigma)
Ejemplo n.º 27
0
def gauss(x,m,sigma):
    """ Return a Gaussian with mean, sigma for a numarray x """
    sigma2 = sigma*sigma
    exponent = -(x-m)**2/(2.*sigma2)
    exponent = numarray.choose(exponent<-700.,(exponent,-700.))
    try:
       result = numarray.exp(exponent)/numarray.sqrt(2.*numarray.pi*sigma2)
    except OverflowError:
       print "gauss: overflow error"
       print "sigma = ", sigma
       print "m = ", m
       print "x = ", x
       sys.exit()
    return result
Ejemplo n.º 28
0
def generic_gradient_magnitude(input,
                               derivative,
                               output=None,
                               mode="reflect",
                               cval=0.0,
                               extra_arguments=(),
                               extra_keywords={}):
    """Calculate a gradient magnitude using the provdide function for
    the gradient.

    The derivative parameter must be a callable with the following 
    signature:
                    
    derivative(input, axis, output, mode, cval,
               *extra_arguments, **extra_keywords)

    The extra_arguments and extra_keywords arguments can be used to pass 
    extra arguments and keywords that are passed to derivative2 at each 
    call.
    """
    input = numarray.asarray(input)
    output, return_value = _ni_support._get_output(output, input)
    axes = range(input.rank)
    if len(axes) > 0:
        derivative(input, axes[0], output, mode, cval, *extra_arguments,
                   **extra_keywords)
        numarray.multiply(output, output, output)
        for ii in range(1, len(axes)):
            tmp = derivative(input, axes[ii], output.type(), mode, cval,
                             *extra_arguments, **extra_keywords)
            numarray.multiply(tmp, tmp, tmp)
            output += tmp
        numarray.sqrt(output, output)
    else:
        output[...] = input[...]
    return return_value
Ejemplo n.º 29
0
 def _SampleDist(self, sep, ntrials=20, nsamp=100):
     srcDir = SkyDir(180., sep)
     nobs = []
     for j in range(ntrials):
         naccept = 0
         for i in range(nsamp):
             appDir = self.psf.appDir(self.energy, srcDir, self.scZAxis,
                                      self.scXAxis)
             if self.cones[0].inside(appDir):
                 naccept += 1
         nobs.append(naccept)
     nobs = num.array(nobs)
     navg = sum(nobs)/float(ntrials)
     return (navg/float(nsamp),
             num.sqrt(sum(nobs**2)/float(ntrials) - navg**2)/float(nsamp))
Ejemplo n.º 30
0
def solveforab(aveaperr, avearea):  #(a,b)=solveforab(aveap,avearea)
    amin = .0
    amax = 1
    bmin = .0
    bmax = 1
    step = .005
    a = N.arange(amin, amax, step, 'f')
    b = N.arange(bmin, bmax, step, 'f')
    y = N.zeros(len(aveaperr), 'f')
    diff = N.zeros(len(aveaperr), 'f')
    mini = 1000000000.
    for ai in a:
        for bi in b:
            y = N.zeros(len(avearea), 'f')
            y = N.sqrt(avearea) * ai * (1. + bi * N.sqrt(avearea))
            #diff = N.sqrt((y - aveap)**2)
            diff = (y - aveaperr)
            sumdiff = N.sum(abs(diff))
            #print "%5.3f %5.3f %8.2f %8.2f" %(ai,bi,sumdiff,mini)
            if sumdiff < mini:
                afinal = ai
                bfinal = bi
                mini = sumdiff
    return afinal, bfinal
Ejemplo n.º 31
0
def gauss(x, m, sigma):
    """ Return a Gaussian with mean, sigma for a numarray x """
    sigma2 = sigma * sigma
    exponent = -(x - m)**2 / (2. * sigma2)
    exponent = numarray.choose(exponent < -700., (exponent, -700.))
    try:
        result = numarray.exp(exponent) / numarray.sqrt(
            2. * numarray.pi * sigma2)
    except OverflowError:
        print "gauss: overflow error"
        print "sigma = ", sigma
        print "m = ", m
        print "x = ", x
        sys.exit()
    return result
Ejemplo n.º 32
0
def ratioerrorold(a, b):
    a = 1. * a  #make sure it's a real number, not integer
    b = 1. * b
    try:
        len(a)  #continue of a in an array
        ratio = []
        err = []
        for i in range(len(a)):
            try:
                ratio.append(a[i] / b[i])
                if a[i] > 0.:
                    err.append(a[i] / b[i] * N.sqrt(1. / a[i] + 1. / b[i]))
                else:
                    err.append(0.)
            except ZeroDivisionError:
                ratio.append(-1)
                err.append(0.)
    except TypeError:  #a is a number rather than an array
        ratio = a / b
        try:
            err = a / b * N.sqrt(1. / a + 1. / b)
        except:
            err = 0.
    return ratio, err
Ejemplo n.º 33
0
def findnearest(x1, y1, x2, y2, delta):
    dmin = 100000000000000000000000000000000000.
    matchflag = 1
    nmatch = 0
    for i in range(len(x2)):
        d = N.sqrt((x1 - x2[i])**2 + (y1 - y2[i])**2)
        if d < delta:
            nmatch = nmatch + 1
        if d < dmin:
            dmin = d
            imatch = i

    if dmin > delta:
        imatch = 0
        matchflag = 0
    return imatch, matchflag, nmatch
Ejemplo n.º 34
0
def makeplot():
    psplotinit("noise.ps")

    DATAMIN = 0.
    DATAMAX = 15.

    ppgplot.pgbox("", 0.0, 0, "L", 0.0, 0)
    #print "making graph, ncl = ",ncl
    path = os.getcwd()
    f = path.split('/')
    #print path
    #print f
    prefix = f[4]
    title = prefix
    ymin = -.05
    ymax = max(aveaperr) + .1
    #ymax=10.
    ppgplot.pgenv(DATAMIN, DATAMAX, ymin, ymax, 0)
    ppgplot.pglab("linear size N of aperture (pixel)", "rms in Sky (ADU/s)",
                  title)
    ppgplot.pgsci(2)  #red
    ppgplot.pgslw(4)  #line width
    x = N.sqrt(avearea)
    y = aveaperr
    ppgplot.pgpt(x, y, 7)
    #errory(x,y,erry)
    ppgplot.pgsci(1)  #black
    #ppgplot.pgpt(isoarea,fluxerriso,3)
    #x1=N.sqrt(contsubisoarea)
    #y1=contsuberr

    #x1=N.sqrt(isoarea)
    #y1=fluxerriso
    #y=n*y1

    #ppgplot.pgpt(x1,y1,1)
    #ppgplot.pgsci(4)#blue
    #ppgplot.pgpt(x1,y,1)
    #ppgplot.pgsci(1)#black
    x = N.arange(0, 50, 1)
    y = x * (a + b * a * x)
    #y=N.sqrt(x)*.02
    ppgplot.pgline(x, y)
    #errory(x,y,erry)

    ppgplot.pgend()
Ejemplo n.º 35
0
def findnearestalt(x1, y1, x2, y2, delta):  #use where command
    dmin = 100000000000000000000000000000000000.
    matchflag = 1
    nmatch = 0
    d = N.sqrt((x1 - x2)**2 + (y1 - y2)**2)  #x2 and y2 are arrays
    t = pylab.where(d < delta)
    matches = t[0]
    if len(matches) > 0:
        nmatch = len(matches)
        z = d[matches]
        imatch = matches[pylab.where(z == z.min())]

    else:
        imatch = 0
        matchflag = 0

    return imatch, matchflag, nmatch
Ejemplo n.º 36
0
def _stdev(data):
    n = len(data[:,0,0])
    s = num.zeros(data[0,:,:].shape, num.Float32)
    # First pass to get the mean.
    for j in range(n): s += data[j,:,:]
    ave = s/n
    var = num.zeros(s.shape, num.Float32)
    ep  = num.zeros(s.shape, num.Float32)
    for j in range(n):
        s = data[j,:,:]-ave
        num.add(ep, s, ep)
        p = s**2
        num.add(var, p, var)
    # Corrected two-pass formula.
    num.subtract(var, ep*ep/n, var)
    num.divide(var, (n-1), var)
    return num.sqrt(var)
Ejemplo n.º 37
0
    def xy2rd(self, pos):
        """
        This method would apply the WCS keywords to a position to
        generate a new sky position.

        The algorithm comes directly from 'imgtools.xy2rd'

        translate (x,y) to (ra, dec)
        """
        if self.ctype1.find('TAN') < 0 or self.ctype2.find('TAN') < 0:
            print 'XY2RD only supported for TAN projections.'
            raise TypeError

        if isinstance(pos, N.NumArray):
            # If we are working with an array of positions,
            # point to just X and Y values
            posx = pos[:, 0]
            posy = pos[:, 1]
        else:
            # Otherwise, we are working with a single X,Y tuple
            posx = pos[0]
            posy = pos[1]

        xi = self.cd11 * (posx - self.crpix1) + self.cd12 * (posy -
                                                             self.crpix2)
        eta = self.cd21 * (posx - self.crpix1) + self.cd22 * (posy -
                                                              self.crpix2)

        xi = DEGTORAD(xi)
        eta = DEGTORAD(eta)
        ra0 = DEGTORAD(self.crval1)
        dec0 = DEGTORAD(self.crval2)

        ra = N.arctan((xi / (N.cos(dec0) - eta * N.sin(dec0)))) + ra0
        dec = N.arctan(
            ((eta * N.cos(dec0) + N.sin(dec0)) /
             (N.sqrt((N.cos(dec0) - eta * N.sin(dec0))**2 + xi**2))))

        ra = RADTODEG(ra)
        dec = RADTODEG(dec)
        ra = DIVMOD(ra, 360.)

        # Otherwise, just return the RA,Dec tuple.
        return ra, dec
Ejemplo n.º 38
0
def xy2rd(filename, x,y,hdu = -1, hms = 0,  verbose = 0):
    from numarray import sin,cos,arctan2,sqrt
    def degtorad(num):
	return num/180.0*numarray.pi
    def radtodeg(num):
	return num/numarray.pi * 180.0
    def degtoHMS(num):
	mmm = int((num-int(num))*60.0)
	sss = ((num-int(num))*60.0-mmm)*60.0
	num = `int(num)`+":"+ `mmm`+":"+`sss`
	return num
	
    keys = ["CRPIX1","CRPIX2","CRVAL1","CRVAL2","CD1_1","CD1_2","CD2_1","CD2_2"]
    CD =  read_keys(filename,keys,hdu)
    crpix = numarray.zeros((2),numarray.Float)
    cd = numarray.zeros((2,2),numarray.Float)

    crpix[0] = CD['CRPIX1'][0]
    crpix[1] = CD['CRPIX2'][0]
    ra0 = CD['CRVAL1'][0]
    dec0 = CD['CRVAL2'][0]
    cd[0,0] = CD['CD1_1'][0]
    cd[0,1] = CD['CD1_2'][0]
    cd[1,0] = CD['CD2_1'][0]
    cd[1,1] = CD['CD2_2'][0]
    xi = cd[0, 0] * (x - crpix[0]) + cd[0, 1] * (y - crpix[1])
    eta = cd[1, 0] * (x - crpix[0]) + cd[1, 1] * (y - crpix[1])
    xi = degtorad(xi)
    eta = degtorad(eta)
    ra0 = degtorad(ra0)
    dec0 = degtorad(dec0)

    ra = arctan2(xi,cos(dec0)-eta*sin(dec0)) + ra0
    dec = arctan2(eta*cos(dec0)+sin(dec0),sqrt((cos(dec0)-eta*sin(dec0))**2 + xi**2))

    ra = radtodeg(ra)# % 360.0
  #  if ra < 0: ra = ra + 360.0
    dec = radtodeg(dec)

    if (hms):
	return degtoHMS(ra/15.0),degtoHMS(dec)
    else:
	return ra,dec
Ejemplo n.º 39
0
def plotPosError(starlist, outsuffix, imgtype='png'):
    """
    Load up a starlist output by align_rms.
    """

    tab = asciidata.open(starlist)

    mag = tab[1].tonumarray()
    x = tab[3].tonumarray()
    y = tab[4].tonumarray()
    xerr = tab[5].tonumarray()
    yerr = tab[6].tonumarray()

    xdiff = x - 512.0
    ydiff = y - 512.0
    r = na.sqrt(xdiff**2 + ydiff**2)

    err = (xerr + yerr) / 2.0

    # Plot magnitude dependance
    p.clf()
    p.semilogy(mag, err*9.94, 'k.')

    idx = (na.where(mag < 14))[0]

    medianPix = na.linear_algebra.mlab.median(err[idx])
    medianArc = medianPix * 9.94
    p.text(9, 60, 'For (8 < K < 14)')
    p.text(9, 40, 'Median Error = %5.3f pix (%5.3f mas)' %
           (medianPix, medianArc))
    p.xlabel('Magnitude')
    p.ylabel('Positional Uncertainty (mas)''Positional Uncertainty (mas)')

    p.savefig('pos_error_mag_%s.%s' % (outsuffix, imgtype))


    # Plot radial dependance
    p.clf()
    p.semilogy(r[idx] * 0.00994, err[idx] * 9.94, 'k.')
    p.xlabel('Radius from Field Center (arcsec)')
    p.ylabel('Positional Uncertainty (mas)')
    p.savefig('pos_error_r_%s.%s' % (outsuffix, imgtype))
Ejemplo n.º 40
0
Archivo: wcsutil.py Proyecto: OSSOS/MOP
    def xy2rd(self,pos):
        """
        This method would apply the WCS keywords to a position to
        generate a new sky position.

        The algorithm comes directly from 'imgtools.xy2rd'

        translate (x,y) to (ra, dec)
        """
        if self.ctype1.find('TAN') < 0 or self.ctype2.find('TAN') < 0:
            print 'XY2RD only supported for TAN projections.'
            raise TypeError

        if isinstance(pos,N.NumArray):
            # If we are working with an array of positions,
            # point to just X and Y values
            posx = pos[:,0]
            posy = pos[:,1]
        else:
            # Otherwise, we are working with a single X,Y tuple
            posx = pos[0]
            posy = pos[1]

        xi = self.cd11 * (posx - self.crpix1) + self.cd12 * (posy - self.crpix2)
        eta = self.cd21 * (posx - self.crpix1) + self.cd22 * (posy - self.crpix2)

        xi = DEGTORAD(xi)
        eta = DEGTORAD(eta)
        ra0 = DEGTORAD(self.crval1)
        dec0 = DEGTORAD(self.crval2)

        ra = N.arctan((xi / (N.cos(dec0)-eta*N.sin(dec0)))) + ra0
        dec = N.arctan( ((eta*N.cos(dec0)+N.sin(dec0)) /
                (N.sqrt((N.cos(dec0)-eta*N.sin(dec0))**2 + xi**2))) )

        ra = RADTODEG(ra)
        dec = RADTODEG(dec)
        ra = DIVMOD(ra, 360.)

        # Otherwise, just return the RA,Dec tuple.
        return ra,dec
Ejemplo n.º 41
0
def plotPosError(starlist, outsuffix, imgtype='png'):
    """
    Load up a starlist output by align_rms.
    """

    tab = asciidata.open(starlist)

    mag = tab[1].tonumarray()
    x = tab[3].tonumarray()
    y = tab[4].tonumarray()
    xerr = tab[5].tonumarray()
    yerr = tab[6].tonumarray()

    xdiff = x - 512.0
    ydiff = y - 512.0
    r = na.sqrt(xdiff**2 + ydiff**2)

    err = (xerr + yerr) / 2.0

    # Plot magnitude dependance
    p.clf()
    p.semilogy(mag, err * 9.94, 'k.')

    idx = (na.where(mag < 14))[0]

    medianPix = na.linear_algebra.mlab.median(err[idx])
    medianArc = medianPix * 9.94
    p.text(9, 60, 'For (8 < K < 14)')
    p.text(9, 40,
           'Median Error = %5.3f pix (%5.3f mas)' % (medianPix, medianArc))
    p.xlabel('Magnitude')
    p.ylabel('Positional Uncertainty (mas)' 'Positional Uncertainty (mas)')

    p.savefig('pos_error_mag_%s.%s' % (outsuffix, imgtype))

    # Plot radial dependance
    p.clf()
    p.semilogy(r[idx] * 0.00994, err[idx] * 9.94, 'k.')
    p.xlabel('Radius from Field Center (arcsec)')
    p.ylabel('Positional Uncertainty (mas)')
    p.savefig('pos_error_r_%s.%s' % (outsuffix, imgtype))
Ejemplo n.º 42
0
def biniterr(
        x, y, n
):  #bin arrays x, y into n equally-populated bins, returning xbin,ybin
    nx = len(x)
    #x=N.array(x,'f')
    #y=N.array(y,'f')
    y = N.take(y, N.argsort(x))
    x = N.take(x, N.argsort(x))
    xbin = N.zeros(n, 'f')
    xbin = N.zeros(n, 'f')
    ybin = N.zeros(n, 'f')
    ybinerr = N.zeros(n, 'f')
    for i in range(n):
        nmin = i * int(float(nx) / float(n))
        nmax = (i + 1) * int(float(nx) / float(n))
        #xbin[i]=scipy.stats.stats.median(x[nmin:nmax])
        #ybin[i]=scipy.stats.stats.median(y[nmin:nmax])
        xbin[i] = N.average(x[nmin:nmax])
        ybin[i] = N.average(y[nmin:nmax])
        ybinerr[i] = pylab.std(y[nmin:nmax]) / N.sqrt(1. * (nmax - nmin))
    return xbin, ybin, ybinerr
Ejemplo n.º 43
0
    def points(self, npoints):
        """
        compute arrays of npoints equally spaced
        intermediate points along the great circle.

        input parameter npoints is the number of points
        to compute.

        Returns lons, lats (lists with longitudes and latitudes
        of intermediate points in degrees).

        For example npoints=10 will return arrays lons,lats of 10
        equally spaced points along the great circle.
        """
        # can't do it if endpoints of great circle are antipodal, since
        # route is undefined.
        if self.antipodal:
            raise ValueError, 'cannot compute intermediate points on a great circle whose endpoints are antipodal'
        d = self.distance
        delta = 1.0 / (npoints - 1)
        f = delta * N.arange(npoints)
        lat1 = self.lat1
        lat2 = self.lat2
        lon1 = self.lon1
        lon2 = self.lon2
        A = N.sin((1 - f) * d) / math.sin(d)
        B = N.sin(f * d) / math.sin(d)
        x = A * math.cos(lat1) * math.cos(lon1) + B * math.cos(
            lat2) * math.cos(lon2)
        y = A * math.cos(lat1) * math.sin(lon1) + B * math.cos(
            lat2) * math.sin(lon2)
        z = A * math.sin(lat1) + B * math.sin(lat2)
        lats = N.arctan2(z, N.sqrt(x**2 + y**2))
        lons = N.arctan2(y, x)
        lons = map(math.degrees, lons.tolist())
        lats = map(math.degrees, lats.tolist())
        return lons, lats
Ejemplo n.º 44
0
	def kaiser_window(self, beta=4, show=0, use_scipy=None):
		if use_scipy == None:
		# modified Bessel function of zero kind order
			def I_0(x):
				i0=0
				fac = lambda n:reduce(lambda a,b:a*(b+1),range(n),1)
				for n in range(20):
					i0 += ((x/2.0)**n/(fac(n)))**2
				return i0
	
			t = numarray.arange(self.data_points, type=numarray.Float) - self.data_points/2.0
			T = self.data_points
			# this is the window function array
			apod = I_0(beta*numarray.sqrt(1-(2*t/T)**2))/I_0(beta)
		else:
			# alternative method using scipy
			import scipy 
			apod=scipy.kaiser(self.data_points, beta)
	
		for i in range(2):
			self.the_result.y[i] = self.the_result.y[i]*apod
		if show == 1:
			return self.the_result
		return self
Ejemplo n.º 45
0
def calcCorrelationHelper(s1p, s2p):
    # if the traits share less than six strains, then we don't
    # bother with the correlations
    if len(s1p) < 6:
        return 0.0
    
    # subtract by x-bar and y-bar elementwise
    #oldS1P = s1p.copy()
    #oldS2P = s2p.copy()
    
    s1p = (s1p - numarray.average(s1p)).astype(numarray.Float64)
    s2p = (s2p - numarray.average(s2p)).astype(numarray.Float64)

    # square for the variances 
    s1p_2 = numarray.sum(s1p**2)
    s2p_2 = numarray.sum(s2p**2)

    try: 
        corr = (numarray.sum(s1p*s2p)/
                numarray.sqrt(s1p_2 * s2p_2))
    except ZeroDivisionError:
        corr = 0.0

    return corr
Ejemplo n.º 46
0
def coherence(cross_spectrum, power_spectra, noise=None, numinbin=1,
              subbed=1):

    """Compute coherence from cross and power spectra.

    uncoh, uncoh_err, corcoh = coherence(cross_spectrum, power_spectra,
                                         noise=None, numinbin=1, subbed=1)

    Inputs:

    cross_spectrum, power_spectra: Complex and real arrays, respectively.
    power_spectra has one row for each signal band.
    cross_spectrum has one fewer, and it is assumed that the cross spectra
    of all bands but the first have been taken with respect to the first.

    Will correct[1] for noise if it is supplied.

    numinbin: The number of independent estimates that have gone into
    each frequency bin.

    If subbed is true, noise has already been subtracted from
    the power spectra, and will not be during the calculations.

    Outputs:

    uncoh: The raw coherence.  Eq. (6.51) in Bendat & Piersol 2000.

    uncoh_err:  Standard deviation in the raw coherence.
    Eq. (9.81) in Bendat & Piersol 2000.

    corcoh: The corrected coherence.  Eq. (8) in Vaughan & Nowak 1997.

    [1] Vaughan & Nowak 1997, ApJ 474:L43"""

    cross_spectrum = num.asarray(cross_spectrum)
    power_spectra = num.asarray(power_spectra)
    if noise is not None:
        correct = 1
        noise = num.asarray(noise)

    if subbed:
        unsubtracted = power_spectra + noise
        if correct:
            subtracted = power_spectra
    else:
        unsubtracted = power_spectra
        if correct:
            subtracted = power_spectra - noise

    s_one = unsubtracted[..., :1, :]
    s_two = unsubtracted[..., 1:, :]
    numerator = num.absolute(cross_spectrum) ** 2
    uncorrected = numerator / (s_one * s_two)
    # Sometimes floating-point issues cause these limits to be violated.
    uncorrected = num.minimum(uncorrected, 1.0)
    uncorrected = num.maximum(uncorrected, 0.0)

    # error in uncorrected coherence
    # eq. (9.81) in Bendat & Piersol 2000
    varcoh = 2 * uncorrected * (1 - uncorrected) ** 2 / numinbin 
    uncoh_error = num.sqrt(varcoh)

    if correct:
        s_one = subtracted[..., :1, :]
        s_two = subtracted[..., 1:, :]
        n_one = noise[..., :1, :]
        n_two = noise[..., 1:, :]
        n_square = (s_one * n_two + n_one * s_two + n_one * n_two) / numinbin
        numerator -= n_square
        corrected = numerator / (s_one * s_two)

    if correct:
        return uncorrected, uncoh_error, corrected
    else:
        return uncorrected, uncoh_error
Ejemplo n.º 47
0
def mad_combine(infileglob, outfilebase):
    # get list of files to operate on
    files = glob.glob(infileglob)
    # check more than one image exists
    if files < 2:
        print 'Less than two input files found!'
        return
    print 'Operating on images',infileglob
    # get images
    images = _get_images(files)
    lenimages = len(images)
    print 'Found', lenimages, 'images'
    # get header of first image
    hdr = images[0][0].header
    # get ascard of first image
    hdrascard = hdr.ascard
    # get data from images into num (untidy tuple concatenation)
    data = num.zeros((lenimages,) + images[0][0].data.shape, num.Float32)
    for i in range(lenimages):
        data[i,:,:] = images[i][0].data
    # delete array
    del images
    # sort data
    print 'Sorting... (this may take a while, i.e an hour or so!)'
    #data_sorted = num.sort(data, axis=0)
    data_sorted = data  # for debugging
    # find standard deviation of lowest n - n_discard pixels
    print 'Calculating mad_low...'
    mad_low = _mad3(data_sorted[:-n_discard,:,:])
    # correct for bias to stddev
    num.multiply(mad_low, corr[`lenimages - n_discard` + ',' + `lenimages`], mad_low)
    # make median image
    print 'Calculating median...'
    if lenimages%2 != 0:  # then odd number of images
        m = (lenimages - 1) / 2
        median = data_sorted[m,:,:]
    else:                   # even number of images
        m = lenimages / 2
        median = (data_sorted[m,:,:] + data_sorted[m-1,:,:]) / 2
    # delete array
    del data_sorted
    # get ccd properties from header
    # these keywords are for FORS2
    # - they may need altering for other instruments

    gain = hdr['OUT1GAIN'] # N_{ADU} = gain * N_{e-}
    invgain = 1.0 / gain   # N_{e-} = invgain * N_{ADU}
    ron  = hdr['OUT1RON']  # read out noise in e- 
    # take only +ve values in median
    median_pos = num.choose(median < 0.0, (median, 0.0))
    # calculate sigma due to ccd noise for each pixel
    print 'Calculating noise_med...'
    noise_med = num.sqrt(median_pos * invgain + ron*ron) * gain
    # delete array
    del median_pos
    # find maximum of noise and mad_low
    # -> sigma to test pixels against to identify cosmics
    print 'Calculating sigma_test...'
    sigma_test = num.choose(noise_med < mad_low, (noise_med, mad_low))
    # delete arrays
    del mad_low, noise_med
    # calculate 'relative residual' for each pixel
    print 'Calculating rel_res...'
    rel_res = num.zeros(data.shape, num.Float32)
    res = num.zeros(data[0].shape, num.Float32)
    for i in range(lenimages):
        num.subtract(data[i,:,:], median, res)
        num.divide(res, sigma_test, rel_res[i,:,:])
    # delete arrays
    del sigma_test, res
    # now average over all pixels for which rel_res < sigma_limit
    # first count number included for each pixel
    # by testing to produce a boolean array, then summing over.
    print 'Calculating included...'
    included = num.zeros(rel_res[0].shape, num.Int16)
    included[:,:] = num.sum(rel_res <= sigma_limit)
    # put all discarded pixels to zero
    print 'Calculating combined...'
    pre_combine = num.choose(rel_res <= sigma_limit, (0.0,data))
    # delete array
    del rel_res
    # sum all pixels and divide by included to give mean
    combined = num.sum(pre_combine)
    # delete array
    del pre_combine
    num.divide(combined, included, combined)
    # Work out errors on this combined image
    # take only +ve values in combined
    mean_pos = num.choose(combined < 0.0, (combined, 0.0))
    # calculate sigma due to ccd noise for each pixel
    print 'Calculating noise_mean...'
    noise_mean = num.sqrt(mean_pos * invgain + ron*ron) * gain
    # delete array
    del mean_pos
    # create standard error image
    print 'Calculating error...'
    error = noise_mean / num.sqrt(included)
    # delete array
    del noise_mean
    # write all images to disk
    print 'Writing images to disk...'
    _write_images(combined, error, included,
                  hdrascard, outfilebase)
Ejemplo n.º 48
0
def vc_v200_nfw(x, c):
    top = N.log(1.0 + c*x) - c*x / (1.0 + c*x)
    bottom = N.log(1.0 + c) - c / (1.0 + c)
    vc2 = top / (x * bottom)
    vc = N.sqrt(vc2)
    return vc
Ejemplo n.º 49
0
    def points(self, npoints):
        """
        compute arrays of npoints equally spaced
        intermediate points along the great circle.

        input parameter npoints is the number of points
        to compute.

        Returns lons, lats (lists with longitudes and latitudes
        of intermediate points in degrees).

        For example npoints=10 will return arrays lons,lats of 10
        equally spaced points along the great circle.
        """
        # must ask for at least 2 points.
        if npoints <= 1:
            raise ValueError, 'npoints must be greater than 1'
        elif npoints == 2:
            return [math.degrees(self.lon1),
                    math.degrees(self.lon2)
                    ], [math.degrees(self.lat1),
                        math.degrees(self.lat2)]
        # can't do it if endpoints are antipodal, since
        # route is undefined.
        if self.antipodal:
            raise ValueError, 'cannot compute intermediate points on a great circle whose endpoints are antipodal'
        d = self.gcarclen
        delta = 1.0 / (npoints - 1)
        f = delta * N.arange(npoints)  # f=0 is point 1, f=1 is point 2.
        incdist = self.distance / (npoints - 1)
        lat1 = self.lat1
        lat2 = self.lat2
        lon1 = self.lon1
        lon2 = self.lon2
        # perfect sphere, use great circle formula
        if self.f == 0.:
            A = N.sin((1 - f) * d) / math.sin(d)
            B = N.sin(f * d) / math.sin(d)
            x = A * math.cos(lat1) * math.cos(lon1) + B * math.cos(
                lat2) * math.cos(lon2)
            y = A * math.cos(lat1) * math.sin(lon1) + B * math.cos(
                lat2) * math.sin(lon2)
            z = A * math.sin(lat1) + B * math.sin(lat2)
            lats = N.arctan2(z, N.sqrt(x**2 + y**2))
            lons = N.arctan2(y, x)
            lons = map(math.degrees, lons.tolist())
            lats = map(math.degrees, lats.tolist())
        # use ellipsoid formulas
        else:
            latpt = self.lat1
            lonpt = self.lon1
            azimuth = self.azimuth12
            lons = [math.degrees(lonpt)]
            lats = [math.degrees(latpt)]
            for n in range(npoints - 2):
                latptnew, lonptnew, alpha21 = vinc_pt(self.f, self.a, latpt,
                                                      lonpt, azimuth, incdist)
                d, azimuth, a21 = vinc_dist(self.f, self.a, latptnew, lonptnew,
                                            lat2, lon2)
                lats.append(math.degrees(latptnew))
                lons.append(math.degrees(lonptnew))
                latpt = latptnew
                lonpt = lonptnew
            lons.append(math.degrees(self.lon2))
            lats.append(math.degrees(self.lat2))
        return lons, lats
     NA.array([0, 0, 0]),
     NA.array([[1, r12, r13], [r12, 1, r23], [r13, r23, 1]]), nsamps)
 print 'correlations (r12,r13,r23) = ', r12, r13, r23
 print 'number of realizations = ', nsamps
 # training data.
 obs = x[:, 0]
 climprob = NA.sum((obs > 0).astype('f')) / nsamps
 fcst = NA.transpose(x[:, 1:])  # 2 predictors.
 obs_binary = obs > 0.
 # independent data for verification.
 obs2 = x2[:, 0]
 fcst2 = NA.transpose(x2[:, 1:])
 # compute logistic regression.
 beta, Jbar, llik = logistic_regression(fcst, obs_binary, verbose=True)
 covmat = LA.inverse(Jbar)
 stderr = NA.sqrt(mlab.diag(covmat))
 print 'beta =', beta
 print 'standard error =', stderr
 # forecasts from independent data.
 prob = calcprob(beta, fcst2)
 # compute Brier Skill Score
 verif = (obs2 > 0.).astype('f')
 bs = mlab.mean((0.01 * prob - verif)**2)
 bsclim = mlab.mean((climprob - verif)**2)
 bss = 1. - (bs / bsclim)
 print 'Brier Skill Score (should be within +/- 0.1 of 0.18) = ', bss
 # calculate reliability.
 # see http://www.bom.gov.au/bmrc/wefor/staff/eee/verif/verif_web_page.html
 # for information on the Brier Skill Score and reliability diagrams.
 totfreq = NA.zeros(10, 'f')
 obfreq = NA.zeros(10, 'f')
Ejemplo n.º 51
0
    def drawmeridians(self,ax,meridians,color='k',linewidth=1., \
                      linestyle='--',dashes=[1,1],labels=[0,0,0,0],\
                      font='rm',fontsize=12):
        """
 draw meridians (longitude lines).

 ax - current axis instance.
 meridians - list containing longitude values to draw (in degrees).
 color - color to draw meridians (default black).
 linewidth - line width for meridians (default 1.)
 linestyle - line style for meridians (default '--', i.e. dashed).
 dashes - dash pattern for meridians (default [1,1], i.e. 1 pixel on,
  1 pixel off).
 labels - list of 4 values (default [0,0,0,0]) that control whether
  meridians are labelled where they intersect the left, right, top or 
  bottom of the plot. For example labels=[1,0,0,1] will cause meridians
  to be labelled where they intersect the left and bottom of the plot,
  but not the right and top. Labels are located with a precision of 0.1
  degrees and are drawn using mathtext.
 font - mathtext font used for labels ('rm','tt','it' or 'cal', default 'rm'.
 fontsize - font size in points for labels (default 12).
        """
        # don't draw meridians past latmax, always draw parallel at latmax.
        latmax = 80. # not used for cyl, merc projections.
        # offset for labels.
	yoffset = (self.urcrnry-self.llcrnry)/100./self.aspect
	xoffset = (self.urcrnrx-self.llcrnrx)/100.

        if self.projection not in ['merc','cyl']:
            lats = N.arange(-latmax,latmax+1).astype('f')
        else:
            lats = N.arange(-90,91).astype('f')
        xdelta = 0.1*(self.xmax-self.xmin)
        ydelta = 0.1*(self.ymax-self.ymin)
        for merid in meridians:
            lons = merid*N.ones(len(lats),'f')
            x,y = self(lons,lats)
            # remove points outside domain.
            testx = N.logical_and(x>=self.xmin-xdelta,x<=self.xmax+xdelta)
            x = N.compress(testx, x)
            y = N.compress(testx, y)
            testy = N.logical_and(y>=self.ymin-ydelta,y<=self.ymax+ydelta)
            x = N.compress(testy, x)
            y = N.compress(testy, y)
            if len(x) > 1 and len(y) > 1:
                # split into separate line segments if necessary.
                # (not necessary for mercator or cylindrical).
                xd = (x[1:]-x[0:-1])**2
                yd = (y[1:]-y[0:-1])**2
                dist = N.sqrt(xd+yd)
                split = dist > 500000.
                if N.sum(split) and self.projection not in ['merc','cyl']:
                   ind = (N.compress(split,pylab.squeeze(split*N.indices(xd.shape)))+1).tolist()
                   xl = []
                   yl = []
                   iprev = 0
                   ind.append(len(xd))
                   for i in ind:
                       xl.append(x[iprev:i])
                       yl.append(y[iprev:i])
                       iprev = i
                else:
                    xl = [x]
                    yl = [y]
                # draw each line segment.
                for x,y in zip(xl,yl):
                    # skip if only a point.
                    if len(x) > 1 and len(y) > 1:
                        l = Line2D(x,y,linewidth=linewidth,linestyle=linestyle)
                        l.set_color(color)
                        l.set_dashes(dashes)
                        ax.add_line(l)
        # draw labels for meridians.
        # search along edges of map to see if parallels intersect.
        # if so, find x,y location of intersection and draw a label there.
        if self.projection == 'cyl':
            dx = 0.01; dy = 0.01
        elif self.projection == 'merc':
            dx = 0.01; dy = 1000
        else:
            dx = 1000; dy = 1000
        for dolab,side in zip(labels,['l','r','t','b']):
            if not dolab: continue
            # for cyl or merc, don't draw meridians on left or right.
            if self.projection in ['cyl','merc'] and side in ['l','r']: continue
            if side in ['l','r']:
	        nmax = int((self.ymax-self.ymin)/dy+1)
                if self.urcrnry < self.llcrnry:
	            yy = self.llcrnry-dy*N.arange(nmax)
                else:
	            yy = self.llcrnry+dy*N.arange(nmax)
                if side == 'l':
	            lons,lats = self(self.llcrnrx*N.ones(yy.shape,'f'),yy,inverse=True)
                else:
	            lons,lats = self(self.urcrnrx*N.ones(yy.shape,'f'),yy,inverse=True)
                lons = N.where(lons < 0, lons+360, lons)
                lons = [int(lon*10) for lon in lons.tolist()]
                lats = [int(lat*10) for lat in lats.tolist()]
            else:
	        nmax = int((self.xmax-self.xmin)/dx+1)
                if self.urcrnrx < self.llcrnrx:
	            xx = self.llcrnrx-dx*N.arange(nmax)
                else:
	            xx = self.llcrnrx+dx*N.arange(nmax)
                if side == 'b':
	            lons,lats = self(xx,self.llcrnry*N.ones(xx.shape,'f'),inverse=True)
                else:
	            lons,lats = self(xx,self.urcrnry*N.ones(xx.shape,'f'),inverse=True)
                lons = N.where(lons < 0, lons+360, lons)
                lons = [int(lon*10) for lon in lons.tolist()]
                lats = [int(lat*10) for lat in lats.tolist()]
            for lon in meridians:
                if lon<0: lon=lon+360.
                # find index of meridian (there may be two, so
                # search from left and right).
                try:
                    nl = lons.index(int(lon*10))
                except:
                    nl = -1
                try:
                    nr = len(lons)-lons[::-1].index(int(lon*10))-1
                except:
                    nr = -1
        	if lon>180:
        	    lonlab = r'$\%s{%g\/^{\circ}\/W}$'%(font,N.fabs(lon-360))
        	elif lon<180 and lon != 0:
        	    lonlab = r'$\%s{%g\/^{\circ}\/E}$'%(font,lon)
        	else:
        	    lonlab = r'$\%s{%g\/^{\circ}}$'%(font,lon)
                # meridians can intersect each map edge twice.
                for i,n in enumerate([nl,nr]):
                    lat = lats[n]/10.
                    # no meridians > latmax for projections other than merc,cyl.
                    if self.projection not in ['merc','cyl'] and lat > latmax: continue
                    # don't bother if close to the first label.
                    if i and abs(nr-nl) < 100: continue
                    if n > 0:
                        if side == 'l':
        	            pylab.text(self.llcrnrx-xoffset,yy[n],lonlab,horizontalalignment='right',verticalalignment='center',fontsize=fontsize)
                        elif side == 'r':
        	            pylab.text(self.urcrnrx+xoffset,yy[n],lonlab,horizontalalignment='left',verticalalignment='center',fontsize=fontsize)
                        elif side == 'b':
        	            pylab.text(xx[n],self.llcrnry-yoffset,lonlab,horizontalalignment='center',verticalalignment='top',fontsize=fontsize)
                        else:
        	            pylab.text(xx[n],self.urcrnry+yoffset,lonlab,horizontalalignment='center',verticalalignment='bottom',fontsize=fontsize)

        # make sure axis ticks are turned off
        ax.set_xticks([]) 
        ax.set_yticks([])
Ejemplo n.º 52
0
def distance_transform_edt(input, sampling = None, 
                        return_distances = True, return_indices = False,
                        distances = None, indices = None):
    """Exact euclidean distance transform.

    In addition to the distance transform, the feature transform can
    be calculated. In this case the index of the closest background
    element is returned along the first axis of the result.

    The return_distances, and return_indices flags can be used to
    indicate if the distance transform, the feature transform, or both
    must be returned.

    Optionally the sampling along each axis can be given by the
    sampling parameter which should be a sequence of length equal to
    the input rank, or a single number in which the sampling is assumed
    to be equal along all axes.

    the distances and indices arguments can be used to give optional
    output arrays that must be of the correct size and type (Float64
    and Int32).
    """
    if (not return_distances) and (not return_indices):
        msg = 'at least one of distances/indices must be specified'
        raise RuntimeError, msg
    ft_inplace = isinstance(indices, numarray.NumArray)
    dt_inplace = isinstance(distances, numarray.NumArray)
    # calculate the feature transform
    input = numarray.where(input, 1, 0).astype(numarray.Int8)
    if sampling is not None:
        sampling = _ni_support._normalize_sequence(sampling, input.rank)
        sampling = numarray.asarray(sampling, type = numarray.Float64)
        if not sampling.iscontiguous():
            sampling = sampling.copy()
    if ft_inplace:
        ft = indices
        if ft.shape != (input.rank,) + input.shape:
            raise RuntimeError, 'indices has wrong shape'
        if ft.type() != numarray.Int32:
            raise RuntimeError, 'indices must be of Int32 type'
    else:
        ft = numarray.zeros((input.rank,) + input.shape,
                            type = numarray.Int32) 
    _nd_image.euclidean_feature_transform(input, sampling, ft)
    # if requested, calculate the distance transform
    if return_distances:
        dt = ft - numarray.indices(input.shape, type = ft.type())
        dt = dt.astype(numarray.Float64)
        if sampling is not None:
            for ii in range(len(sampling)):
                dt[ii, ...] *= sampling[ii]
        numarray.multiply(dt, dt, dt)
        if dt_inplace:
            dt = numarray.add.reduce(dt, axis = 0)
            if distances.shape != dt.shape:
                raise RuntimeError, 'indices has wrong shape'
            if distances.type() != numarray.Float64:
                raise RuntimeError, 'indices must be of Float64 type'
            numarray.sqrt(dt, distances)
            del dt
        else:
            dt = numarray.add.reduce(dt, axis = 0)
            dt = numarray.sqrt(dt)
    # construct and return the result
    result = []
    if return_distances and not dt_inplace:
        result.append(dt)
    if return_indices and not ft_inplace:
        result.append(ft)
    if len(result) == 2:
        return tuple(result)
    elif len(result) == 1:
        return result[0]
    else:
        return None
Ejemplo n.º 53
0
	def abs_fft(self, points=None, zoom=None,write = 'off'):
		"""
		Fourier transforms the timesignal;
		points is the number of points to transform, 
		if more points given than data points
		the rest is zero padded
	
		absfft(points=4096)
		"""
		realdata = numarray.array(self.the_result.y[0])
		imdata = numarray.array(self.the_result.y[1])
		data = realdata + 1j*imdata
		fftdata = self.rearrange(numarray.fft.fft(data, points))
		absfft = numarray.sqrt(fftdata.real**2 + fftdata.imag**2)
		# create our x axis
		n = fftdata.size()
		self.the_result.x = (numarray.arange(n)*(self.sampling_rate/n)-
												(self.sampling_rate/2.0))
		self.the_result.y[0] = absfft
		self.the_result.y[1] = numarray.zeros(n)
		if write == 'on':
			return self
		else:
			if zoom is None: return self.the_result
			else:
			center, width = zoom
			return self.zoom(self.the_result, center, width)

	def fft(self, points=None, zoom=None, write='off'):
		realdata = numarray.array(self.the_result.y[0])
		imdata = numarray.array(self.the_result.y[1])
		data = realdata + 1j*imdata
		fftdata = self.rearrange(numarray.fft.fft(data, points))
		#phase = numarray.arctan(fftdata.real.sum() / fftdata.imag.sum())
		#print "PHASE:", phase*180/numarray.pi
		# create our x axis
		n = fftdata.size()
		self.the_result.x = numarray.arange(n)*(self.sampling_rate/n)-(self.sampling_rate/2.0)
		# create new result
		self.the_result.y[0] = fftdata.real
		self.the_result.y[1] = fftdata.imag
		if write == 'on':
			return self
		else:
			if zoom is None: return self.the_result
			else:
				center, width = zoom
				return self.zoom(self.the_result, center, width)

	def realfft(self, points=None, zoom=None, write = 'off'):
		realdata = numarray.array(self.the_result.y[0])
		imdata = numarray.array(self.the_result.y[1])
		data = realdata + 1j*imdata
		fftdata = self.rearrange(numarray.fft.fft(data, points))
		realfft = fftdata.real
		# create our x axis
		n = fftdata.size()
		self.the_result.x =	 numarray.arange(n)*(self.sampling_rate/n)-(self.sampling_rate/2.0)
		self.the_result.y[0] = realfft
		self.the_result.y[1] = numarray.zeros(n)
		if write == 'on':
			return self
		else:
			if zoom is None: return self.the_result
			else:
			center, width = zoom
			return self.zoom(self.the_result, center, width)

	def zoom(self,some_result, center="auto", width=1000):
		if center == "auto":
			i_center = int(self.the_result.y[0].argmax())
			maximum = self.the_result.y[0][i_center]
			print "Maximum at Frequency:", self.the_result.x[i_center]
		else:
			i_center = int(self.data_points/2.0+self.data_points*center/self.sampling_rate)
		#print "TODO: set width automagically"
		#if width == "auto":
		#	 i_width = int(self.data_points*width)
		i_width = int(self.data_points*width/self.sampling_rate)
		some_result.x=some_result.x[i_center-i_width/2:i_center+i_width/2]
		some_result.y[0]=some_result.y[0][i_center-i_width/2:i_center+i_width/2]
		some_result.y[1]=some_result.y[1][i_center-i_width/2:i_center+i_width/2]
		return some_result

	""" 
	Apodization functions:
	* exp_window and gauss_window are S/N enhancing,
	* dexp_window and traf_window are resolution enhancing
	* standard windows [hamming, hanning, bartlett, blackman, kaiser-bessel] are also available 
	self.timepoints		=	time points
	self.aquisition_time	=	aquisition time (no. samples / sampling_rate)
	line_broadening		=	line broadening factor (standard = 10 Hz)
	gaussian_multiplicator = Gaussian Multiplication Factor for 
				the double exponential apodization 
				function (standard = 0.3)
	"""
	def exp_window(self, line_broadening=10, show=0):
		apod = numarray.exp(-self.timepoints*line_broadening)
		for i in range(2):
			self.the_result.y[i] = self.the_result.y[i]*apod
		if show == 1 :
			return self.the_result
		return self

	def gauss_window(self, line_broadening=10, show=0):
		apod = numarray.exp(-(self.timepoints*line_broadening)**2)
		for i in range(2):
			self.the_result.y[i] = self.the_result.y[i]*apod
		if show == 1 :
			return self.the_result
		return self

	def dexp_window(self, line_broadening=10, gaussian_multiplicator=0.3, show=0):
		apod = numarray.exp(-(self.timepoints*line_broadening - 
					gaussian_multiplicator*self.aquisition_time)**2)
		for i in range(2):
			self.the_result.y[i] = self.the_result.y[i]*apod 
		if show == 1:
			return self.the_result
		return self

	def traf_window(self, line_broadening=10, show=0):
		apod = (numarray.exp(-self.timepoints*line_broadening))**2 / ( 
					(numarray.exp(-self.timepoints*line_broadening))**3 
		+ (numarray.exp(-self.aquisition_time*line_broadening))**3	)
		for i in range(2):
			self.the_result.y[i] = self.the_result.y[i]*apod
		if show == 1:
			return self.the_result
		return self

	def hanning_window(self, show=0):
		apod = numarray.mlab.hanning(self.data_points)
		for i in range(2):
			self.the_result.y[i] = self.the_result.y[i]*apod
		if show == 1:
			return self.the_result
		return self

	def hamming_window(self, show=0):
		apod = numarray.mlab.hamming(self.data_points)
		for i in range(2):
			self.the_result.y[i] = self.the_result.y[i]*apod
		if show == 1:
			return self.the_result
		return self

	def blackman_window(self, show=0):
		apod = numarray.mlab.blackman(self.data_points)
		for i in range(2):
			self.the_result.y[i] = self.the_result.y[i]*apod
		if show == 1:
			return self.the_result
		return self

	def bartlett_window(self, show=0):
		apod = numarray.mlab.bartlett(self.data_points)
		for i in range(2):
			self.the_result.y[i] = self.the_result.y[i]*apod
		if show == 1:
			return self.the_result
		return self

	def kaiser_window(self, beta=4, show=0, use_scipy=None):
		if use_scipy == None:
		# modified Bessel function of zero kind order
			def I_0(x):
				i0=0
				fac = lambda n:reduce(lambda a,b:a*(b+1),range(n),1)
				for n in range(20):
					i0 += ((x/2.0)**n/(fac(n)))**2
				return i0
	
			t = numarray.arange(self.data_points, type=numarray.Float) - self.data_points/2.0
			T = self.data_points
			# this is the window function array
			apod = I_0(beta*numarray.sqrt(1-(2*t/T)**2))/I_0(beta)
		else:
			# alternative method using scipy
			import scipy 
			apod=scipy.kaiser(self.data_points, beta)
	
		for i in range(2):
			self.the_result.y[i] = self.the_result.y[i]*apod
		if show == 1:
			return self.the_result
		return self
Ejemplo n.º 54
0
 def getNorm(self):
     return sqrt(dot(self.array, self.array))
Ejemplo n.º 55
0
def plotRadial():
    # Constants take from Bender et al. (2005)
    cc = objects.Constants()
    m31mass = 1.4e8
    m31dist = 760000.0

    # Construct an array of radii out to 5 arcsec in steps of 0.05''
    r = (na.arange(12 * 5) * 0.05) + 0.05
    r_au = r * m31dist
    r_pc = r_au / cc.au_in_pc
    r_cm = r_au * cc.cm_in_au

    # Determine the theoretical amount for a vs. r
    a_cm_s2 = cc.G * m31mass * cc.msun / r_cm**2
    a_km_s_yr = a_cm_s2 * cc.sec_in_yr / 1.0e5
    a_mas_yr2 = a_cm_s2 * pow(cc.sec_in_yr, 2) * 1000.0 
    a_mas_yr2 /= (cc.cm_in_au * m31dist)

    # Plot circular velocity in both mas/yr and km/s
    v_cm_s = na.sqrt(cc.G * m31mass * cc.msun / r_cm)
    v_km_s = v_cm_s / 1.0e5
    v_mas_yr = v_cm_s * cc.sec_in_yr * 1000.0/ (cc.cm_in_au * m31dist)
    
    masyr_kms = (1.0/1000.0) * m31dist * cc.cm_in_au / (1.0e5 * cc.sec_in_yr)
    masyr2_kmsyr = (1.0/1000.0) * m31dist * cc.cm_in_au 
    masyr2_kmsyr /= 1.0e5 * pow(cc.sec_in_yr, 2)

    ##########
    #
    # Calculate some useful quantities for Keck/TMT
    #
    ##########
    dKeck = 10.0
    dTMT = 10.0

    resKeckK = 1.0e3 * 0.25 * 2.2 / dKeck   # K (GC) on Keck has similar Strehl
    resTMTZ = 1.0e3 * 0.25 * 1.035 / dTMT   # to obs with Z on TMT (mas).

    posErrKeck = 0.15   # mas
    ratioKeck = resKeckK / posErrKeck

    posErrTMT = resTMTZ / ratioKeck
    print('Estimated positional error for TMT at Z-band: %5.3f' % (posErrTMT))

    # 1 years, 3 sigma
    velLo1 = 3.0 * posErrTMT
    velLoKms1 = velLo1 * masyr_kms

    # 3 years, 3 sigma
    velLo3 = posErrTMT
    velLoKms3 = velLo3 * masyr_kms

    print('Lowest detectable velocities in:')
    print('\t 1 year, 3 sigma -- low vel = %4.2f mas/yr = %4d km/s' % \
          (velLo1, velLoKms1))
    print('\t 3 year, 3 sigma -- low vel = %4.2f mas/yr = %4d km/s' % \
          (velLo3, velLoKms3))

    ##########
    #
    # Velocity vs. Radius
    #
    ##########
    pylab.figure(2, figsize=(7, 7))
    pylab.clf()

#     pylab.plot(r, v_mas_yr, linewidth=2)
#     pylab.xlabel('Distance from Mbh (arcsec)')
#     pylab.ylabel('Circular Velocity (mas/yr)')
    pylab.plot(r, v_km_s, linewidth=2)
    pylab.xlabel('Distance from Mbh (arcsec)')
    pylab.ylabel('Circular Velocity (km/s)')

    # Detection limit
#     pylab.plot([0, 10], [velLo1, velLo1], 'k--')
#     pylab.plot([0, 10], [velLo3, velLo3], 'k--')
#     pylab.text(2.5, velLo1, '1 year')
#     pylab.text(2.5, velLo3, '3 years')
    pylab.plot([0, 10], [velLoKms1, velLoKms1], 'k--')
    pylab.plot([0, 10], [velLoKms3, velLoKms3], 'k--')
    pylab.plot([0, 10], [30.0, 30.0], 'k--')
    pylab.text(2.5, velLoKms1, '1 year')
    pylab.text(2.5, velLoKms3, '3 years')
    pylab.text(0.3, 35.0, 'Radial Vel.')

    arr1 = pylab.Arrow(2.4, velLoKms1, 0, 0.04*masyr_kms, width=0.09)
    arr3 = pylab.Arrow(2.4, velLoKms3, 0, 0.04*masyr_kms, width=0.09)
    arrRv = pylab.Arrow(0.2, 30.0, 0, 0.04*masyr_kms, width=0.09)
    fig = pylab.gca()
    fig.add_patch(arr1)
    fig.add_patch(arr3)
    fig.add_patch(arrRv)

    str = '0.1 mas/yr = %4d km/s' % (0.1 * masyr_kms)
    pylab.axis([0.0, 3, 0.0, 0.5*masyr_kms])
    pylab.text(1.3, 0.45*masyr_kms, str)
    pylab.savefig('m31theory_vel.png')
    pylab.savefig('m31theory_vel.eps')

    pylab.clf()
    pylab.plot(r, a_mas_yr2)
    pylab.xlabel('Distance from Mbh (arcsec)')
    pylab.ylabel('Acceleration (mas/yr^2)')
    str = '1 mas/yr^2 = %5.2f km/s/yr' % (1.0 * masyr2_kmsyr)
    pylab.text(1.0e-3, 1.5, str)
    pylab.savefig('m31theory_acc.eps')
    pylab.savefig('m31theory_acc.png')
Ejemplo n.º 56
0
def plotRadial():
    # Constants take from Bender et al. (2005)
    cc = objects.Constants()
    m31mass = 1.4e8
    m31dist = 760000.0

    # Construct an array of radii out to 5 arcsec in steps of 0.05''
    r = (na.arange(12 * 5) * 0.05) + 0.05
    r_au = r * m31dist
    r_pc = r_au / cc.au_in_pc
    r_cm = r_au * cc.cm_in_au

    # Determine the theoretical amount for a vs. r
    a_cm_s2 = cc.G * m31mass * cc.msun / r_cm**2
    a_km_s_yr = a_cm_s2 * cc.sec_in_yr / 1.0e5
    a_mas_yr2 = a_cm_s2 * pow(cc.sec_in_yr, 2) * 1000.0
    a_mas_yr2 /= (cc.cm_in_au * m31dist)

    # Plot circular velocity in both mas/yr and km/s
    v_cm_s = na.sqrt(cc.G * m31mass * cc.msun / r_cm)
    v_km_s = v_cm_s / 1.0e5
    v_mas_yr = v_cm_s * cc.sec_in_yr * 1000.0 / (cc.cm_in_au * m31dist)

    masyr_kms = (1.0 / 1000.0) * m31dist * cc.cm_in_au / (1.0e5 * cc.sec_in_yr)
    masyr2_kmsyr = (1.0 / 1000.0) * m31dist * cc.cm_in_au
    masyr2_kmsyr /= 1.0e5 * pow(cc.sec_in_yr, 2)

    ##########
    #
    # Calculate some useful quantities for Keck/TMT
    #
    ##########
    dKeck = 10.0
    dTMT = 10.0

    resKeckK = 1.0e3 * 0.25 * 2.2 / dKeck  # K (GC) on Keck has similar Strehl
    resTMTZ = 1.0e3 * 0.25 * 1.035 / dTMT  # to obs with Z on TMT (mas).

    posErrKeck = 0.15  # mas
    ratioKeck = resKeckK / posErrKeck

    posErrTMT = resTMTZ / ratioKeck
    print('Estimated positional error for TMT at Z-band: %5.3f' % (posErrTMT))

    # 1 years, 3 sigma
    velLo1 = 3.0 * posErrTMT
    velLoKms1 = velLo1 * masyr_kms

    # 3 years, 3 sigma
    velLo3 = posErrTMT
    velLoKms3 = velLo3 * masyr_kms

    print('Lowest detectable velocities in:')
    print('\t 1 year, 3 sigma -- low vel = %4.2f mas/yr = %4d km/s' % \
          (velLo1, velLoKms1))
    print('\t 3 year, 3 sigma -- low vel = %4.2f mas/yr = %4d km/s' % \
          (velLo3, velLoKms3))

    ##########
    #
    # Velocity vs. Radius
    #
    ##########
    pylab.figure(2, figsize=(7, 7))
    pylab.clf()

    #     pylab.plot(r, v_mas_yr, linewidth=2)
    #     pylab.xlabel('Distance from Mbh (arcsec)')
    #     pylab.ylabel('Circular Velocity (mas/yr)')
    pylab.plot(r, v_km_s, linewidth=2)
    pylab.xlabel('Distance from Mbh (arcsec)')
    pylab.ylabel('Circular Velocity (km/s)')

    # Detection limit
    #     pylab.plot([0, 10], [velLo1, velLo1], 'k--')
    #     pylab.plot([0, 10], [velLo3, velLo3], 'k--')
    #     pylab.text(2.5, velLo1, '1 year')
    #     pylab.text(2.5, velLo3, '3 years')
    pylab.plot([0, 10], [velLoKms1, velLoKms1], 'k--')
    pylab.plot([0, 10], [velLoKms3, velLoKms3], 'k--')
    pylab.plot([0, 10], [30.0, 30.0], 'k--')
    pylab.text(2.5, velLoKms1, '1 year')
    pylab.text(2.5, velLoKms3, '3 years')
    pylab.text(0.3, 35.0, 'Radial Vel.')

    arr1 = pylab.Arrow(2.4, velLoKms1, 0, 0.04 * masyr_kms, width=0.09)
    arr3 = pylab.Arrow(2.4, velLoKms3, 0, 0.04 * masyr_kms, width=0.09)
    arrRv = pylab.Arrow(0.2, 30.0, 0, 0.04 * masyr_kms, width=0.09)
    fig = pylab.gca()
    fig.add_patch(arr1)
    fig.add_patch(arr3)
    fig.add_patch(arrRv)

    str = '0.1 mas/yr = %4d km/s' % (0.1 * masyr_kms)
    pylab.axis([0.0, 3, 0.0, 0.5 * masyr_kms])
    pylab.text(1.3, 0.45 * masyr_kms, str)
    pylab.savefig('m31theory_vel.png')
    pylab.savefig('m31theory_vel.eps')

    pylab.clf()
    pylab.plot(r, a_mas_yr2)
    pylab.xlabel('Distance from Mbh (arcsec)')
    pylab.ylabel('Acceleration (mas/yr^2)')
    str = '1 mas/yr^2 = %5.2f km/s/yr' % (1.0 * masyr2_kmsyr)
    pylab.text(1.0e-3, 1.5, str)
    pylab.savefig('m31theory_acc.eps')
    pylab.savefig('m31theory_acc.png')
Ejemplo n.º 57
0
Archivo: wcsutil.py Proyecto: OSSOS/MOP
    def recenter(self):
        """
        Reset the reference position values to correspond to the center
        of the reference frame.
        Algorithm used here developed by Colin Cox - 27-Jan-2004.
        """
        if self.ctype1.find('TAN') < 0 or self.ctype2.find('TAN') < 0:
            print 'WCS.recenter() only supported for TAN projections.'
            raise TypeError

        # Check to see if WCS is already centered...
        if self.crpix1 == self.naxis1/2. and self.crpix2 == self.naxis2/2.:
            # No recentering necessary... return without changing WCS.
            return

        # This offset aligns the WCS to the center of the pixel, in accordance
        # with the 'align=center' option used by 'drizzle'.
        #_drz_off = -0.5
        _drz_off = 0.
        _cen = (self.naxis1/2.+ _drz_off,self.naxis2/2. + _drz_off)

        # Compute the RA and Dec for center pixel
        _cenrd = self.xy2rd(_cen)
        _cd = N.array([[self.cd11,self.cd12],[self.cd21,self.cd22]],type=N.Float64)
        _ra0 = DEGTORAD(self.crval1)
        _dec0 = DEGTORAD(self.crval2)
        _ra = DEGTORAD(_cenrd[0])
        _dec = DEGTORAD(_cenrd[1])

        # Set up some terms for use in the final result
        _dx = self.naxis1/2. - self.crpix1
        _dy = self.naxis2/2. - self.crpix2

        _dE,_dN = DEGTORAD(N.dot(_cd,(_dx,_dy)))
        _dE_dN = 1 + N.power(_dE,2) + N.power(_dN,2)
        _cosdec = N.cos(_dec)
        _sindec = N.sin(_dec)
        _cosdec0 = N.cos(_dec0)
        _sindec0 = N.sin(_dec0)

        _n1 = N.power(_cosdec,2) + _dE*_dE + _dN*_dN*N.power(_sindec,2)
        _dra_dE = (_cosdec0 - _dN*_sindec0)/_n1
        _dra_dN = _dE*_sindec0 /_n1

        _ddec_dE = -_dE*N.tan(_dec) / _dE_dN
        _ddec_dN = (1/_cosdec) * ((_cosdec0 / N.sqrt(_dE_dN)) - (_dN*N.sin(_dec) / _dE_dN))

        # Compute new CD matrix values now...
        _cd11n = _cosdec * (self.cd11*_dra_dE + self.cd21 * _dra_dN)
        _cd12n = _cosdec * (self.cd12*_dra_dE + self.cd22 * _dra_dN)
        _cd21n = self.cd11 * _ddec_dE + self.cd21 * _ddec_dN
        _cd22n = self.cd12 * _ddec_dE + self.cd22 * _ddec_dN

        _new_orient = RADTODEG(N.arctan2(_cd12n,_cd22n))

        # Update the values now...
        self.crpix1 = _cen[0]
        self.crpix2 = _cen[1]
        self.crval1 = RADTODEG(_ra)
        self.crval2 = RADTODEG(_dec)

        # Keep the same plate scale, only change the orientation
        self.rotateCD(_new_orient)

        # These would update the CD matrix with the new rotation
        # ALONG with the new plate scale which we do not want.
        self.cd11 = _cd11n
        self.cd12 = _cd12n
        self.cd21 = _cd21n
        self.cd22 = _cd22n
Ejemplo n.º 58
0
def mask(clus_id, line_s):
    imagefile = c.imagefile
    sex_cata = c.sex_cata
    clus_cata = c.out_cata
    threshold = c.threshold
    thresh_area = c.thresh_area
    size = c.size
    mask_reg = c.mask_reg
    x = n.reshape(n.arange(size*size),(size,size)) % size
    x = x.astype(n.Float32)
    y = n.reshape(n.arange(size*size),(size,size)) / size
    y = y.astype(n.Float32)
    values = line_s.split()
    mask_file = 'ell_mask_' + str(imagefile)[:6] + '_'  + str(clus_id) + '.fits'
    xcntr_o  = float(values[1]) #x center of the object
    ycntr_o  = float(values[2]) #y center of the object
    xcntr = size / 2.0 + 1.0 + xcntr_o - int(xcntr_o)
    ycntr = size / 2.0 + 1.0 + ycntr_o - int(ycntr_o)
    mag    = float(values[7]) #Magnitude
    radius = float(values[9]) #Half light radius
    mag_zero = c.mag_zero #magnitude zero point
    sky	 = float(values[10]) #sky 
    pos_ang = float(values[11]) - 90.0 #position angle
    axis_rat = 1.0 / float(values[12]) #axis ration b/a
    major_axis = float(values[14])	#major axis of the object
    z = n.zeros((size,size))		
    for line_j in open(sex_cata,'r'):
        try:
            values = line_j.split()
            xcntr_n  = float(values[1]) #x center of the neighbour
            ycntr_n  = float(values[2]) #y center of the neighbour
            mag    = float(values[7]) #Magnitude
            radius = float(values[9]) #Half light radius
            sky      = float(values[10]) #sky
            pos_ang = float(values[11]) #position angle
            axis_rat = 1.0/float(values[12]) #axis ration b/a
            si = n.sin(pos_ang * n.pi / 180.0)
            co = n.cos(pos_ang * n.pi / 180.0)
            area = float(values[13])
            maj_axis = float(values[14])#major axis of neighbour
            eg = 1.0 - axis_rat
            one_minus_eg_sq    = (1.0-eg)**2.0
            if(abs(xcntr_n - xcntr_o) < size/2.0 and \
               abs(ycntr_n - ycntr_o) < size/2.0 and \
               xcntr_n != xcntr_o and ycntr_n != ycntr_o):
                if((xcntr_o - xcntr_n) < 0):
                    xn = xcntr + abs(xcntr_n - xcntr_o)
                if((ycntr_o - ycntr_n) < 0):
                    yn = ycntr + abs(ycntr_n - ycntr_o)
                if((xcntr_o - xcntr_n) > 0):
                    xn = xcntr - (xcntr_o -xcntr_n)
                if((ycntr_o - ycntr_n) > 0):
                    yn = ycntr - (ycntr_o -ycntr_n)
                tx = (x - xn + 0.5) * co + (y - yn + 0.5) * si
                ty = (xn - 0.5 -x) * si + (y - yn + 0.5) * co
                R = n.sqrt(tx**2.0 + ty**2.0 / one_minus_eg_sq)
                z[n.where(R<=mask_reg*maj_axis)] = 1
        except:
            i=1	
    hdu = pyfits.PrimaryHDU(z.astype(n.Float32))
    hdu.writeto(mask_file)
Ejemplo n.º 59
0
def run():
    # Assume circular orbits with isotropic normal vectors on circular
    # orbits with circular orbital velocity of 500 km/s.
    ntrials = 10000
    nstars = int((1.0 / 3.0) * 100)
    gens = aorb.create_generators(7, ntrials*10)

    velTot = 500.0  # km/s -- velocity amplitude
    radTot = 2.04   # arcsec

    def fitfunc(p, fjac=None, vx=None, vy=None, vz=None, 
		vxerr=None, vyerr=None, vzerr=None):
        irad = math.radians(p[0])
        orad = math.radians(p[1])
	nx = math.sin(irad) * math.cos(orad)
	ny = -math.sin(irad) * math.sin(orad)
	nz = -math.cos(irad)

	top = (nx*vx + ny*vy + nz*vz)**2
	bot = (nx*vxerr + ny*vyerr + nz*vzerr)**2

	devs = (1.0 / (len(vx) - 1.0)) * top / bot
	status = 0

        return [status, devs.flat]

    # Keep track from every trial the incl, omeg, chi2, number of stars
    incl = na.zeros(ntrials, type=na.Float)
    omeg = na.zeros(ntrials, type=na.Float)
    chi2 = na.zeros(ntrials, type=na.Float)
    niter = na.zeros(ntrials)
    stars = na.zeros(ntrials)

    # Keep track of same stuff for spatial test
    inclPos = na.zeros(ntrials, type=na.Float)
    omegPos = na.zeros(ntrials, type=na.Float)
    chi2Pos = na.zeros(ntrials, type=na.Float)
    niterPos = na.zeros(ntrials)

    angleAvg = na.zeros(ntrials, type=na.Float)
    angleStd = na.zeros(ntrials, type=na.Float)

    for trial in range(ntrials):
	if ((trial % 100) == 0):
	    print 'Trial %d' % trial

	x = na.zeros(nstars, type=na.Float)
	y = na.zeros(nstars, type=na.Float)
	z = na.zeros(nstars, type=na.Float)

	vx = na.zeros(nstars, type=na.Float)
	vy = na.zeros(nstars, type=na.Float)
	vz = na.zeros(nstars, type=na.Float)

	rmag = na.zeros(nstars, type=na.Float)
	vmag = na.zeros(nstars, type=na.Float)
	nx = na.zeros(nstars, type=na.Float)
	ny = na.zeros(nstars, type=na.Float)
	nz = na.zeros(nstars, type=na.Float)
	

	for ss in range(nstars):
	    vx[ss] = gens[0].uniform(-velTot, velTot)
	
	    vyTot = math.sqrt(velTot**2 - vx[ss]**2)
	    vy[ss] = gens[1].uniform(-vyTot, vyTot)
	    
	    vz[ss] = math.sqrt(velTot**2 - vx[ss]**2 - vy[ss]**2)
	    vz[ss] *= gens[2].choice([-1.0, 1.0])
	    
	    x[ss] = gens[3].uniform(-radTot, radTot)

	    yTot = math.sqrt(radTot**2 - x[ss]**2)
	    y[ss] = gens[4].uniform(-yTot, yTot)

	    z[ss] = math.sqrt(radTot**2 - x[ss]**2 - y[ss]**2)
	    z[ss] *= gens[5].choice([-1.0, 1.0])

	    rmag[ss] = math.sqrt(x[ss]**2 + y[ss]**2 + z[ss]**2)
	    vmag[ss] = math.sqrt(vx[ss]**2 + vy[ss]**2 + vz[ss]**2)

	    rvec = [x[ss], y[ss], z[ss]]
	    vvec = [vx[ss], vy[ss], vz[ss]]
	    tmp = util.cross_product(rvec, vvec)
	    tmp /= rmag[ss] * vmag[ss]
	    nx[ss] = tmp[0]
	    ny[ss] = tmp[1]
	    nz[ss] = tmp[2]
	    
	r2d = na.hypot(x, y)
	v2d = na.hypot(vx, vy)
	top = (x * vy - y * vx)
	jz = (x * vy - y * vx) / (r2d * v2d)

	djzdx = (vy * r2d * v2d - (top * v2d * x / r2d)) / (r2d * v2d)**2
	djzdy = (-vx * r2d * v2d - (top * v2d * y / r2d)) / (r2d * v2d)**2
	djzdvx = (-y * r2d * v2d - (top * r2d * vx / v2d)) / (r2d * v2d)**2
	djzdvy = (x * r2d * v2d - (top * r2d * vy / v2d)) / (r2d * v2d)**2
	
	xerr = na.zeros(nstars, type=na.Float) + 0.001 # arcsec
	yerr = na.zeros(nstars, type=na.Float) + 0.001
	vxerr = na.zeros(nstars, type=na.Float) + 10.0  # km/s
	vyerr = na.zeros(nstars, type=na.Float) + 10.0
	vzerr = na.zeros(nstars, type=na.Float) + 30.0 # km/s
	
	jzerr = na.sqrt((djzdx*xerr)**2 + (djzdy*yerr)**2 + 
			(djzdvx*vxerr)**2 + (djzdvy*vyerr)**2)

	# Eliminate all stars with jz > 0 and jz/jzerr < 2
	# I think these are they cuts they are doing
	idx = (na.where((jz < 0) & (na.abs(jz/jzerr) > 2)))[0]
	#idx = (na.where(jz < 0))[0]
	#idx = range(len(jz))

	cotTheta = vz / na.sqrt(vx**2 + vy**2)
	phi = na.arctan2(vy, vx)

	# Initial guess:
	p0 = na.zeros(2, type=na.Float)
	p0[0] = gens[5].uniform(0.1, 90)     # deg -- inclination
	p0[1] = gens[6].uniform(0.1, 360)     # deg -- omega

	# Setup properties of each free parameter.
	parinfo = {'relStep':10.0, 'step':10.0, 'fixed':0, 
		   'limits':[0.0,360.0],
		   'limited':[1,1], 'mpside':1}
	pinfo = [parinfo.copy() for i in range(len(p0))]

	pinfo[0]['limits'] = [0.0, 180.0]
	pinfo[1]['limits'] = [0.0, 360.0]

	# Stuff to pass into the fit function
	functargs = {'vx': vx[idx], 'vy': vy[idx], 'vz': vz[idx],
		     'vxerr':vxerr[idx], 'vyerr':vyerr[idx], 'vzerr':vzerr[idx]}

	m = mpfit.mpfit(fitfunc, p0, functkw=functargs, parinfo=pinfo,
			quiet=1)
	if (m.status <= 0): 
	    print 'error message = ', m.errmsg

	p = m.params

	incl[trial] = p[0]
	omeg[trial] = p[1]
	stars[trial] = len(idx)
	chi2[trial] = m.fnorm / (stars[trial] - len(p0))
	niter[trial] = m.niter
	
	n = [math.sin(p[0]) * math.cos(p[1]),
	     -math.sin(p[0]) * math.sin(p[1]),
	     -math.cos(p[0])]

	# Now look at the angle between the best fit normal vector
	# from the velocity data and the true r cross v normal vector.
	# Take the dot product between n and nreal.
	angle = na.arccos(n[0]*nx + n[1]*ny + n[2]*nz)
	angle *= (180.0 / math.pi)

	# What is the average angle and std angle
	angleAvg[trial] = angle.mean()
	angleStd[trial] = angle.stddev()

# 	print chi2[trial], chi2Pos[trial], incl[trial], inclPos[trial], \
# 	    omeg[trial], omegPos[trial], niter[trial], niterPos[trial]
# 	print angleAvg[trial], angleStd[trial]
	

    # Plot up chi2 for v-fit vs. chi2 for x-fit
    pylab.clf()
    pylab.semilogx(chi2, angleAvg, 'k.')
    pylab.errorbar(chi2, angleAvg, fmt='k.', yerr=angleStd)
    pylab.xlabel('Chi^2')
    pylab.ylabel('Angle w.r.t. Best Fit')
    foo = raw_input('Contine?')

    # Probability of encountering solution with chi^2 < 2
    idx = (na.where(chi2 < 2.0))[0]
    print 'Prob(chi^2 < 2) = %5.3f ' % (len(idx) / float(ntrials))

    # Probability of encountering solution with chi^2 < 2 AND 
    # inclination = 20 - 30 and Omega = 160 - 170
    foo = (na.where((chi2 < 2.0) & (incl > 20) & (incl < 40)))[0]
    print 'Prob of chi2 and incl = %5.3f' % (len(foo) / float(ntrials))

    pylab.clf()
    pylab.subplot(2, 2, 1)
    pylab.hist(chi2, bins=na.arange(0, 10, 0.5))
    pylab.xlabel('Log Chi^2')

    pylab.subplot(2, 2, 2)
    pylab.hist(incl[idx])
    pylab.xlabel('Inclination for Chi^2 < 2')
    rng = pylab.axis()
    pylab.axis([0, 180, rng[2], rng[3]])

    pylab.subplot(2, 2, 3)
    pylab.hist(omeg[idx])
    pylab.xlabel('Omega for Chi^2 < 2')
    rng = pylab.axis()
    pylab.axis([0, 360, rng[2], rng[3]])

    pylab.subplot(2, 2, 4)
    pylab.hist(stars[idx])
    pylab.xlabel('Nstars for Chi^2 < 2')
    rng = pylab.axis()
    pylab.axis([0, 33, rng[2], rng[3]])

    pylab.savefig('diskTest.png')
    
    # Pickle everything
    foo = {'incl': incl, 'omeg': omeg, 'star': stars, 
	   'chi2': chi2, 'niter': niter}

    pickle.dump(foo, open('diskTestSave.pick', 'w'))