Commit 883b7a77 authored by Fang Yuedong's avatar Fang Yuedong
Browse files

bug fixed

parent e82a5dcc
/* CAUTION: This is the ANSI C (only) version of the Numerical Recipes
utility file nrutil.h. Do not confuse this file with the same-named
file nrutil.h that may be supplied in a 'misc' subdirectory.
*That* file is the one from the book, and contains both ANSI and
traditional K&R versions, along with #ifdef macros to select the
correct version. *This* file contains only ANSI C. */
#ifndef _NR_UTILS_H_
#define _NR_UTILS_H_
static float sqrarg;
#define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 : sqrarg*sqrarg)
static double dsqrarg;
#define DSQR(a) ((dsqrarg=(a)) == 0.0 ? 0.0 : dsqrarg*dsqrarg)
static double dmaxarg1,dmaxarg2;
#define DMAX(a,b) (dmaxarg1=(a),dmaxarg2=(b),(dmaxarg1) > (dmaxarg2) ?\
(dmaxarg1) : (dmaxarg2))
static double dminarg1,dminarg2;
#define DMIN(a,b) (dminarg1=(a),dminarg2=(b),(dminarg1) < (dminarg2) ?\
(dminarg1) : (dminarg2))
static float maxarg1,maxarg2;
#define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1) > (maxarg2) ?\
(maxarg1) : (maxarg2))
static float minarg1,minarg2;
#define FMIN(a,b) (minarg1=(a),minarg2=(b),(minarg1) < (minarg2) ?\
(minarg1) : (minarg2))
static long lmaxarg1,lmaxarg2;
#define LMAX(a,b) (lmaxarg1=(a),lmaxarg2=(b),(lmaxarg1) > (lmaxarg2) ?\
(lmaxarg1) : (lmaxarg2))
static long lminarg1,lminarg2;
#define LMIN(a,b) (lminarg1=(a),lminarg2=(b),(lminarg1) < (lminarg2) ?\
(lminarg1) : (lminarg2))
static int imaxarg1,imaxarg2;
#define IMAX(a,b) (imaxarg1=(a),imaxarg2=(b),(imaxarg1) > (imaxarg2) ?\
(imaxarg1) : (imaxarg2))
static int iminarg1,iminarg2;
#define IMIN(a,b) (iminarg1=(a),iminarg2=(b),(iminarg1) < (iminarg2) ?\
(iminarg1) : (iminarg2))
#define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a))
void nrerror(char error_text[]);
float *vector(long nl, long nh);
int *ivector(long nl, long nh);
unsigned char *cvector(long nl, long nh);
unsigned long *lvector(long nl, long nh);
double *dvector(long nl, long nh);
float **matrix(long nrl, long nrh, long ncl, long nch);
double **dmatrix(long nrl, long nrh, long ncl, long nch);
int **imatrix(long nrl, long nrh, long ncl, long nch);
float **submatrix(float **a, long oldrl, long oldrh, long oldcl, long oldch,
long newrl, long newcl);
float **convert_matrix(float *a, long nrl, long nrh, long ncl, long nch);
float ***f3tensor(long nrl, long nrh, long ncl, long nch, long ndl, long ndh);
void free_vector(float *v, long nl, long nh);
void free_ivector(int *v, long nl, long nh);
void free_cvector(unsigned char *v, long nl, long nh);
void free_lvector(unsigned long *v, long nl, long nh);
void free_dvector(double *v, long nl, long nh);
void free_matrix(float **m, long nrl, long nrh, long ncl, long nch);
void free_dmatrix(double **m, long nrl, long nrh, long ncl, long nch);
void free_imatrix(int **m, long nrl, long nrh, long ncl, long nch);
void free_submatrix(float **b, long nrl, long nrh, long ncl, long nch);
void free_convert_matrix(float **b, long nrl, long nrh, long ncl, long nch);
void free_f3tensor(float ***t, long nrl, long nrh, long ncl, long nch,
long ndl, long ndh);
int ***i3tensor(long nrl, long nrh, long ncl, long nch, long ndl, long ndh);
void free_i3tensor(int ***t, long nrl, long nrh, long ncl, long nch,
long ndl, long ndh);
unsigned char ***b3tensor(long nrl, long nrh, long ncl, long nch, long ndl, long ndh);
void free_b3tensor(unsigned char ***t, long nrl, long nrh, long ncl, long nch,
long ndl, long ndh);
double ***d3tensor(long nrl, long nrh, long ncl, long nch, long ndl, long ndh);
void free_d3tensor(double ***t, long nrl, long nrh, long ncl, long nch,
long ndl, long ndh);
unsigned char **cmatrix(long nrl, long nrh, long ncl, long nch);
void free_cmatrix(unsigned char **m, long nrl, long nrh, long ncl, long nch);
#endif /* _NR_UTILS_H_ */
import numpy as np
import matplotlib.pyplot as plt
import ctypes
import galsim
libCentroid = ctypes.CDLL('../libCentroid.so') # CDLL加载库
print('load libCenroid')
libCentroid.centroidWgt.argtypes = [ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_double)]
IMAGE_WIDTH = 180
IMAGE_HEIGHT = 180
dx = 0.275
dy =-0.393
center_x = 90+dx
center_y = 90+dy
R = np.sqrt(center_x**2 + center_y**2)
Gauss_map = np.zeros((IMAGE_HEIGHT, IMAGE_WIDTH))
for i in range(IMAGE_HEIGHT):
for j in range(IMAGE_WIDTH):
dis = (i-center_y)**2+(j-center_x)**2
Gauss_map[i, j] = np.exp(-0.5*dis/R)
ymap = galsim.InterpolatedImage(galsim.ImageF(Gauss_map), scale=0.01)
zmap = ymap#.shear(g1 = 0.15, g2=0.27) #using shear
Gauss_map = zmap.drawImage(nx = 180, ny = 180, scale=0.01).array
fig=plt.figure(figsize=(5,5))
plt.imshow(Gauss_map, origin='lower')
imx = Gauss_map/np.sum(Gauss_map)
ny,nx = imx.shape
print(nx, ny, np.max(imx))
nn = nx*ny
arr = (ctypes.c_float*nn)()
arr[:] = imx.reshape(nn)
para = (ctypes.c_double*10)()
libCentroid.centroidWgt(arr, ny, nx, para)
print('haha')
print(para[0:5])
cx = para[3]
cy = para[4]
print('{:}'.format(cx), '{:}'.format(cy))
from scipy import ndimage
cx, cy = ndimage.center_of_mass(imx)
print('center_of_mass:', cx, cy)
plt.plot(para[4], para[3], 'bx', ms = 15)
plt.plot(cy, cx, 'r+', ms = 15)
plt.annotate('dx,dy:', [10, 170], color='w')
plt.annotate('{:8.5}, {:8.5}'.format(dx, dy), [10, 160], color='w')
plt.annotate('cx, cy:', [10, 150], color='w')
plt.annotate('{:0<8.5}, {:0<8.5}'.format(center_x, center_y), [10, 140], color='w')
plt.annotate('{:0<8.5}, {:0<8.5}'.format(para[4], para[3]), [10, 130], color='w')
plt.annotate('{:0<8.5}, {:0<8.5}'.format(cy, cx), [10, 120], color='w')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import ctypes
import galsim
libCentroid = ctypes.CDLL('../libCentroid.so') # CDLL加载库
print('load libCenroid')
libCentroid.centroidWgt.argtypes = [ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_double)]
libCentroid.imSplint.argtypes = [ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_double), ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_float)]
from scipy.io import loadmat
data = loadmat('/Users/chengliangwei/csstPSFdata/CSSOS_psf_ciomp/ccd20/wave_1/5_psf_array/psf_10.mat')
imx = data['psf']
imx = imx/np.sum(imx)
ny,nx = imx.shape
print(nx, ny)
#imx centroid
nn = nx*ny
arr = (ctypes.c_float*nn)()
arr[:] = imx.reshape(nn)
para = (ctypes.c_double*10)()
libCentroid.centroidWgt(arr, ny, nx, para)
imx_cx = para[3]
imx_cy = para[4]
#imx -> imy
nxt=nyt=160
nn=nxt*nyt
yat = (ctypes.c_float*nn)()
libCentroid.imSplint(arr, ny, nx, para, nxt, nyt, yat)
imy = np.array(yat[:]).reshape([nxt, nyt])
#imy centroid
libCentroid.centroidWgt(yat, nyt, nxt, para)
imy_cx = para[3]
imy_cy = para[4]
#plot check
fig = plt.figure(figsize=(12, 6))
##imx_plot
ax = plt.subplot(1,2,1)
cpix= int(nx/2)
dpix= 10
plt.imshow(imx[cpix-dpix:cpix+dpix, cpix-dpix:cpix+dpix], origin='lower')
plt.plot(imx_cy-cpix+dpix, imx_cx-cpix+dpix, 'bx', ms = 20)
from scipy import ndimage
cx, cy = ndimage.center_of_mass(imx)
plt.plot(cy-cpix+dpix, cx-cpix+dpix, 'r+', ms = 20)
maxIndx = np.argmax(imx)
maxIndx = np.unravel_index(maxIndx, np.array(imx).shape)
imgMaxPix_x = maxIndx[1]
imgMaxPix_y = maxIndx[0]
apSizeInPix = 23
imgT = np.zeros_like(imx)
imgT[imgMaxPix_y-apSizeInPix:imgMaxPix_y+apSizeInPix+1,
imgMaxPix_x-apSizeInPix:imgMaxPix_x+apSizeInPix+1] = \
imx[imgMaxPix_y-apSizeInPix:imgMaxPix_y+apSizeInPix+1,
imgMaxPix_x-apSizeInPix:imgMaxPix_x+apSizeInPix+1]
cx, cy = ndimage.center_of_mass(imgT)
plt.plot(cy - cpix+dpix, cx - cpix+dpix, 'b+', ms = 15)
##imy_plot
ax = plt.subplot(1,2,2)
cpix= int(nxt/2)
dpix= 10
plt.imshow(imy[cpix-dpix:cpix+dpix, cpix-dpix:cpix+dpix], origin='lower')
plt.plot(imy_cy-cpix+dpix, imy_cx-cpix+dpix, 'bx', ms = 20)
plt.plot([dpix, dpix],[0,dpix],'w:')
plt.plot([0, dpix],[dpix,dpix],'w:')
cx, cy = ndimage.center_of_mass(imy)
plt.plot(cy-cpix+dpix, cx-cpix+dpix, 'r+', ms = 20)
maxIndx = np.argmax(imy)
maxIndx = np.unravel_index(maxIndx, np.array(imy).shape)
imgMaxPix_x = maxIndx[1]
imgMaxPix_y = maxIndx[0]
apSizeInPix = 23
imgT = np.zeros_like(imy)
imgT[imgMaxPix_y-apSizeInPix:imgMaxPix_y+apSizeInPix+1,
imgMaxPix_x-apSizeInPix:imgMaxPix_x+apSizeInPix+1] = \
imy[imgMaxPix_y-apSizeInPix:imgMaxPix_y+apSizeInPix+1,
imgMaxPix_x-apSizeInPix:imgMaxPix_x+apSizeInPix+1]
cx, cy = ndimage.center_of_mass(imgT)
plt.plot(cy - cpix+dpix, cx - cpix+dpix, 'b+', ms = 15)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import ctypes
import galsim
libCentroid = ctypes.CDLL('../libCentroid.so') # CDLL加载库
print('load libCenroid')
libCentroid.centroidWgt.argtypes = [ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_double)]
'''
IMAGE_WIDTH = 180
IMAGE_HEIGHT = 180
dx = 0.#275
dy =-0.#393
center_x = 90 +dx #89.5 #IMAGE_WIDTH/2 -0.
center_y = 90 +dy #89.5 #IMAGE_HEIGHT/2+0.
R = np.sqrt(center_x**2 + center_y**2)
Gauss_map = np.zeros((IMAGE_HEIGHT, IMAGE_WIDTH))
for i in range(IMAGE_HEIGHT):
for j in range(IMAGE_WIDTH):
dis = (i-center_y)**2+(j-center_x)**2
Gauss_map[i, j] = np.exp(-0.5*dis/R)
ymap = galsim.InterpolatedImage(galsim.ImageF(Gauss_map), scale=0.01)
zmap = ymap.shear(g1 = 0.15, g2=0.27)
Gauss_map = zmap.drawImage(nx = 180, ny = 180, scale=0.01).array
fig=plt.figure(figsize=(5,5))
plt.imshow(Gauss_map, origin='lower')
imx = Gauss_map#/np.sum(Gauss_map)
ny,nx = imx.shape
print(nx, ny, np.max(imx))
nn = nx*ny
arr = (ctypes.c_float*nn)()
arr[:] = imx.reshape(nn)
para = (ctypes.c_double*10)()
libCentroid.centroidWgt(arr, ny, nx, para)
print('haha')
print(para[0:5])
cx = para[3]
cy = para[4]
print('{:}'.format(cx), '{:}'.format(cy))
from scipy import ndimage
cx, cy = ndimage.center_of_mass(imx)
print('center_of_mass:', cx, cy)
plt.plot(para[4], para[3], 'bx', ms = 15)
plt.plot(cy, cx, 'r+', ms = 15)
plt.annotate('dx,dy:', [10, 170], color='w')
plt.annotate('{:8.5}, {:8.5}'.format(dx, dy), [10, 160], color='w')
plt.annotate('cx, cy:', [10, 150], color='w')
plt.annotate('{:0<8.5}, {:0<8.5}'.format(center_x, center_y), [10, 140], color='w')
plt.annotate('{:0<8.5}, {:0<8.5}'.format(para[4], para[3]), [10, 130], color='w')
plt.annotate('{:0<8.5}, {:0<8.5}'.format(cy, cx), [10, 120], color='w')
'''
from scipy.io import loadmat
data = loadmat('/Users/chengliangwei/csstPSFdata/CSSOS_psf_ciomp/ccd13/wave_1/5_psf_array/psf_10.mat')
#plt.imshow(data['psf'])
#plt.show()
imx = data['psf']
imx = imx/np.sum(imx)
ny,nx = imx.shape
print(nx, ny)
nn = nx*ny
arr = (ctypes.c_float*nn)()
arr[:] = imx.reshape(nn)
para = (ctypes.c_double*10)()
print(arr[0:10])
#libCentroid.centroidWgt(arr, ny, nx, para)
nxt = nyt = 160
nn = nxt*nyt
yat = (ctypes.c_float*nn)()
libCentroid.centroidWgt(arr, ny, nx, para,nxt, nyt, yat)
mm = np.array(yat[:]).reshape([nxt, nyt])
imx = mm
print('haha')
print(para[0:5])
cx = para[3]
cy = para[4]
print(cx, cy)
fig = plt.figure(figsize=(12, 12))
cpix = 80
dpix = 10
#plt.imshow(np.log10(imx[cpix-dpix:cpix+dpix, cpix-dpix:cpix+dpix]), origin='lower')
plt.imshow(imx[cpix-dpix:cpix+dpix, cpix-dpix:cpix+dpix], origin='lower')
plt.plot(cy - cpix+dpix, cx - cpix+dpix, 'bx', ms = 20)
'''
from scipy import ndimage
cx, cy = ndimage.center_of_mass(imx)
print(cx, cy)
plt.plot(cy - cpix+dpix, cx - cpix+dpix, 'r+', ms = 20)
maxIndx = np.argmax(imx)
maxIndx = np.unravel_index(maxIndx, np.array(imx).shape)
imgMaxPix_x = maxIndx[1]
imgMaxPix_y = maxIndx[0]
apSizeInPix = 23
imgT = np.zeros_like(imx)
imgT[imgMaxPix_y-apSizeInPix:imgMaxPix_y+apSizeInPix+1,
imgMaxPix_x-apSizeInPix:imgMaxPix_x+apSizeInPix+1] = \
imx[imgMaxPix_y-apSizeInPix:imgMaxPix_y+apSizeInPix+1,
imgMaxPix_x-apSizeInPix:imgMaxPix_x+apSizeInPix+1]
cx, cy = ndimage.center_of_mass(imgT)
print(cx, cy)
plt.plot(cy - cpix+dpix, cx - cpix+dpix, 'b+', ms = 15)
maxIndx = np.argmax(imx)
maxIndx = np.unravel_index(maxIndx, np.array(imx).shape)
imgMaxPix_x = maxIndx[1]
imgMaxPix_y = maxIndx[0]
apSizeInPix =5
imgT = np.zeros_like(imx)
imgT[imgMaxPix_y-apSizeInPix:imgMaxPix_y+apSizeInPix+1,
imgMaxPix_x-apSizeInPix:imgMaxPix_x+apSizeInPix+1] = \
imx[imgMaxPix_y-apSizeInPix:imgMaxPix_y+apSizeInPix+1,
imgMaxPix_x-apSizeInPix:imgMaxPix_x+apSizeInPix+1]
cx, cy = ndimage.center_of_mass(imgT)
print(cx, cy)
plt.plot(cy - cpix+dpix, cx - cpix+dpix, 'm+', ms = 10)
print('maxPix:', imgMaxPix_x, imgMaxPix_y, imx[imgMaxPix_y, imgMaxPix_x])
'''
plt.show()
#OPTS += -D
CC = gcc
OPTIMIZE = -fPIC -g -O3 #-Wall -wd981 #-wd1419 -wd810
#GSLI = -I/home/alex/opt/gsl/include
#GSLL = -L/home/alex/opt/gsl/lib -lgsl -lgslcblas
#FFTWI = -I/home/alex/opt/fftw/include
#FFTWL = -L/home/alex/opt/fftw/lib -lfftw3 -lfftw3f
#HDF5I = -I/home/alex/opt/hdf5/include
#HDF5L = -L/home/alex/opt/hdf5/lib -lhdf5_hl -lhdf5
#FITSI = -I/home/alex/opt/cfitsio/include
#FITSL = -L/home/alex/opt/cfitsio/lib -lcfitsio
#EXTRACFLAGS =
#EXTRACLIB =
CLINK=$(CC)
CFLAGS=$(OPTIMIZE) #$(EXTRACFLAGS) $(OPTS)
CLIB= -lm #$(EXTRACLIB)
OBJS = centroidWgt.o nrutil.o
EXEC = centroid.X
all: $(EXEC)
$(EXEC): $(OBJS)
$(CLINK) $(CFLAGS) -o $@ $(OBJS) $(CLIB)
$(OBJS): nrutil.h Makefile
.PHONY : clean
clean:
rm -f *.o $(EXEC)
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "nrutil.h"
//y is the input image, nx and ny are the pixels along x and y axis;
//yt and residu are the required matrix for the function
//para contains the needed parameters: centx=para[3], centy=para[4]
void star_gaus(float **y,int nx,int ny,double *para);
void main()
{
int i, j;
int IMAGE_WIDTH, IMAGE_HEIGHT;
float center_x, center_y;
float R, dis;
float **Gauss_map;
double *para;
//double para[10];
IMAGE_WIDTH = 180;
IMAGE_HEIGHT = 180;
center_x = IMAGE_WIDTH/2 -0.;
center_y = IMAGE_HEIGHT/2+0.;
R = sqrt(center_x*center_x + center_y*center_y);
//Gauss_map = np.zeros((IMAGE_HEIGHT, IMAGE_WIDTH))
Gauss_map = matrix(0, IMAGE_HEIGHT-1, 0, IMAGE_WIDTH-1);
para = dvector(0,10);
for(i=0; i<IMAGE_HEIGHT; i++)
{
for(j=0; j<IMAGE_WIDTH; j++)
{
//#dis = np.sqrt((i-center_y)**2+(j-center_x)**2)
dis = (i-center_y)*(i-center_y) + (j-center_x)*(j-center_x);
//dis = sqrt(dis);
Gauss_map[i][j] = exp(-0.5*dis/R);
}
}
star_gaus(Gauss_map, IMAGE_HEIGHT, IMAGE_WIDTH, para);
printf("ok?\n");
printf("para:%f %f\n", para[3], para[4]);
//free_matrix(Gauss_map,0,IMAGE_HEIGHT-1,0,IMAGE_WIDTH-1);
//free_dvector(para,0,4);
}
void centroidWgt(float *y, int nx, int ny, double *para)
{
int i, j, k;
float **yy;
double **basef;
double **coff;
yy = matrix(0, nx-1, 0, ny-1);
for(i=0; i<nx; i++)
for(j=0; j<ny; j++)
{
k = j + i*nx;
yy[i][j] = y[k];
}
star_gaus(yy, nx, ny, para);
}
//void star_gaus(float **y,int nx,int ny,float **yt,float **residu,double *para)
void star_gaus(float **y,int nx,int ny,double *para)
{
void gasfit_2D(double **x, double *y,int np,double *para,double bg0, int fbg);
double **xs,*ys,ymax;
int i,j,np,npt,im,jm,**xi,k;
double kc,bgc,sigmac,xc,yc,sigma2v,det;
double bg0=0;
int fbg=0;
np=nx*ny;
xs=dmatrix(0,np-1,0,1);
ys=dvector(0,np-1);
xi=imatrix(0,np-1,0,1);
ymax=y[0][0];
for(i=0;i<nx;i++)for(j=0;j<ny;j++){
if(ymax<y[i][j]){ymax=y[i][j];im=i;jm=j;}
}printf("x=%d,y=%d,ymax=%e\n",im,jm,ymax);
int cutPix;
cutPix = 23;
npt=0;
for(i=-cutPix;i<=cutPix;i++){
for(j=-cutPix;j<=cutPix;j++){
xs[npt][0]=xi[npt][0]=i+im;
xs[npt][1]=xi[npt][1]=j+jm;
ys[npt]=y[im+i][jm+j];
npt++;
}
}
printf("check:: %f %f %f %d\n",ys[0], ys[10], ys[100], npt );
gasfit_2D(xs, ys,npt,para,bg0,fbg);
kc=para[0];sigmac=para[1];bgc=para[2];xc=para[3];yc=para[4];
printf("xc, yc: %f %f\n",yc, xc);
//printf("%e %e %e %e %e\n",kc,sigmac,bgc,xc,yc);
/*
sigma2v=-1./(2.*sigmac*sigmac);
for(i=0;i<nx;i++){
for(j=0;j<ny;j++){
det=DSQR(i-xc)+DSQR(j-yc);
yt[i][j]=kc*exp(det*sigma2v)+bgc;
residu[i][j]=y[i][j]-yt[i][j];
}
}
*/
free_dmatrix(xs,0,np-1,0,1);
free_imatrix(xi,0,np-1,0,1);
free_dvector(ys,0,np-1);
}
void gasfit_2D(double **x, double *y,int np,double *para,double bg0,int fbg)
{
void search_2D(double **x,double *y,int np,double kc,double kd,double sigmac,
double sigmad,double bgc,double bgd,double xc, double xd,
double yc, double yd,double *para,double bg0,int fbg);
int i,j,k,imax=0,isigma;
double ymax,ymin,kc,kd,sigmac,sigmad,bgc,bgd,ysigma,xc,yc,xd,yd;
double det,dett;
ymin=ymax=y[imax];
for(i=1;i<np;i++){
if(ymax<y[i]){imax=i;ymax=y[i];}
if(ymin>y[i])ymin=y[i];
}
//printf("ymax=%e,imax=%d\n",ymax,imax);
kc=ymax;kd=ymax/12.;
det=ysigma=kc*exp(-0.5);//printf("det=%e,kc=%e\n",det,kc);
for(i=0;i<np;i++){
dett=fabs(ysigma-y[i]);//printf("dett=%e,det=%e,i=%d\n",dett,det,i);
//if(dett<det && y[i]!=kc){det=dett;isigma=i;}
if(dett<det){det=dett;isigma=i;}
}
xc=x[imax][0];yc=x[imax][1];printf("isigma=%d,imax=%d\n",isigma,imax);
sigmac=sqrt(DSQR(xc-x[isigma][0])+DSQR(yc-x[isigma][1]))*1.;
xd=yd=sigmac*0.25;
sigmad=0.25*sigmac;
bgc=0.;bgd=fabs(ymin);
//printf("sigma=%e\n",sigmac);
for(i=0;i<4;i++){
printf("i = %d\n", i);
//printf("%e %e %e %e %e k2=%e\n",kc,sigmac,bgc,xc,yc,para[5]);
search_2D(x,y,np,kc,kd,sigmac,sigmad,bgc,bgd,xc,xd,yc,yd,para,bg0,fbg);
kd*=0.33;sigmad*=0.33;bgd*=0.33;xd*=0.33;yd*=0.33;
kc=para[0];sigmac=para[1];bgc=para[2];xc=para[3];yc=para[4];
}
if(fbg==0)para[2]=bg0;
}
void search_2D(double **x,double *y,int np,double kc,double kd,double sigmac,
double sigmad,double bgc,double bgd,double xc, double xd,
double yc, double yd,double *para,double bg0,int fbg)
{
double k,sigma,bg,k2,k20,sigma2v,det,xt,yt;
int i,j,l,m,p,q;
sigma2v=-1./(2.*sigmac*sigmac);
bg=bgc;
k20=0;
for(m=0;m<np;m++){
det=DSQR(x[m][0]-xc)+DSQR(x[m][1]-yc);
det=kc*exp(det*sigma2v)+bgc-y[m];
k20+=det*det;
}
for(i=-4;i<=4;i++){
k=kc+i*kd;
if(k>0){
for(j=-4;j<=4;j++){
sigma=sigmac+j*sigmad;
if(sigma>0){
sigma2v=-1./(2.*sigma*sigma);
for(p=-4;p<=4;p++){
xt=xc+p*xd;
for(q=-4;q<=4;q++){
yt=yc+q*yd;
k2=0;
if(fbg==0){
bg=bg0;
for(m=0;m<np;m++){
det=DSQR(x[m][0]-xt)+DSQR(x[m][1]-yt);
det=k*exp(det*sigma2v)+bg-y[m];
k2+=det*det;
}
}
else{
for(l=-4;l<=4;l++){
bg=bgc+l*bgd;
for(m=0;m<np;m++){
det=DSQR(x[m][0]-xt)+DSQR(x[m][1]-yt);
det=k*exp(det*sigma2v)+bg-y[m];
k2+=det*det;
}
}
}
//printf("k20=%e k2=%e\n",k20,k2);
if(k2<=k20){k20=k2;para[5]=k2;
para[0]=k;para[1]=sigma;para[2]=bg;para[3]=xt;para[4]=yt;}
}
}
}
}
}
}
}
/* CAUTION: This is the ANSI C (only) version of the Numerical Recipes
utility file nrutil.h. Do not confuse this file with the same-named
file nrutil.h that may be supplied in a 'misc' subdirectory.
*That* file is the one from the book, and contains both ANSI and
traditional K&R versions, along with #ifdef macros to select the
correct version. *This* file contains only ANSI C. */
#ifndef _NR_UTILS_H_
#define _NR_UTILS_H_
static float sqrarg;
#define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 : sqrarg*sqrarg)
static double dsqrarg;
#define DSQR(a) ((dsqrarg=(a)) == 0.0 ? 0.0 : dsqrarg*dsqrarg)
static double dmaxarg1,dmaxarg2;
#define DMAX(a,b) (dmaxarg1=(a),dmaxarg2=(b),(dmaxarg1) > (dmaxarg2) ?\
(dmaxarg1) : (dmaxarg2))
static double dminarg1,dminarg2;
#define DMIN(a,b) (dminarg1=(a),dminarg2=(b),(dminarg1) < (dminarg2) ?\
(dminarg1) : (dminarg2))
static float maxarg1,maxarg2;
#define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1) > (maxarg2) ?\
(maxarg1) : (maxarg2))
static float minarg1,minarg2;
#define FMIN(a,b) (minarg1=(a),minarg2=(b),(minarg1) < (minarg2) ?\
(minarg1) : (minarg2))
static long lmaxarg1,lmaxarg2;
#define LMAX(a,b) (lmaxarg1=(a),lmaxarg2=(b),(lmaxarg1) > (lmaxarg2) ?\
(lmaxarg1) : (lmaxarg2))
static long lminarg1,lminarg2;
#define LMIN(a,b) (lminarg1=(a),lminarg2=(b),(lminarg1) < (lminarg2) ?\
(lminarg1) : (lminarg2))
static int imaxarg1,imaxarg2;
#define IMAX(a,b) (imaxarg1=(a),imaxarg2=(b),(imaxarg1) > (imaxarg2) ?\
(imaxarg1) : (imaxarg2))
static int iminarg1,iminarg2;
#define IMIN(a,b) (iminarg1=(a),iminarg2=(b),(iminarg1) < (iminarg2) ?\
(iminarg1) : (iminarg2))
#define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a))
void nrerror(char error_text[]);
float *vector(long nl, long nh);
int *ivector(long nl, long nh);
unsigned char *cvector(long nl, long nh);
unsigned long *lvector(long nl, long nh);
double *dvector(long nl, long nh);
float **matrix(long nrl, long nrh, long ncl, long nch);
double **dmatrix(long nrl, long nrh, long ncl, long nch);
int **imatrix(long nrl, long nrh, long ncl, long nch);
float **submatrix(float **a, long oldrl, long oldrh, long oldcl, long oldch,
long newrl, long newcl);
float **convert_matrix(float *a, long nrl, long nrh, long ncl, long nch);
float ***f3tensor(long nrl, long nrh, long ncl, long nch, long ndl, long ndh);
void free_vector(float *v, long nl, long nh);
void free_ivector(int *v, long nl, long nh);
void free_cvector(unsigned char *v, long nl, long nh);
void free_lvector(unsigned long *v, long nl, long nh);
void free_dvector(double *v, long nl, long nh);
void free_matrix(float **m, long nrl, long nrh, long ncl, long nch);
void free_dmatrix(double **m, long nrl, long nrh, long ncl, long nch);
void free_imatrix(int **m, long nrl, long nrh, long ncl, long nch);
void free_submatrix(float **b, long nrl, long nrh, long ncl, long nch);
void free_convert_matrix(float **b, long nrl, long nrh, long ncl, long nch);
void free_f3tensor(float ***t, long nrl, long nrh, long ncl, long nch,
long ndl, long ndh);
int ***i3tensor(long nrl, long nrh, long ncl, long nch, long ndl, long ndh);
void free_i3tensor(int ***t, long nrl, long nrh, long ncl, long nch,
long ndl, long ndh);
unsigned char ***b3tensor(long nrl, long nrh, long ncl, long nch, long ndl, long ndh);
void free_b3tensor(unsigned char ***t, long nrl, long nrh, long ncl, long nch,
long ndl, long ndh);
double ***d3tensor(long nrl, long nrh, long ncl, long nch, long ndl, long ndh);
void free_d3tensor(double ***t, long nrl, long nrh, long ncl, long nch,
long ndl, long ndh);
unsigned char **cmatrix(long nrl, long nrh, long ncl, long nch);
void free_cmatrix(unsigned char **m, long nrl, long nrh, long ncl, long nch);
#endif /* _NR_UTILS_H_ */
PSFProcess.py: preProcess psfCentroidWgt
PSFInterp.py: PSF-object
"""
hoclist 查好最近的采样点
"""
import sys,os,math
import time
from IPython import display
import numpy as np
import matplotlib.pyplot as plt
sys.path.append("/public/home/weichengliang/lnData/CSST_new_framwork/csstPSF")
import PSFConfig as myConfig
import PSFUtil as myUtil
def findNeighbors_hoclist(px, py, tx=None,ty=None, dn=4, hoc=None, hoclist=None):
nhocy = nhocx = 20
pxMin = np.min(px)
pxMax = np.max(px)
pyMin = np.min(py)
pyMax = np.max(py)
dhocx = (pxMax - pxMin)/(nhocx-1)
dhocy = (pyMax - pyMin)/(nhocy-1)
partx = px - pxMin +dhocx/2
party = py - pyMin +dhocy/2
if hoc is None:
hoc, hoclist = myUtil.hocBuild(partx, party, nhocx, nhocy, dhocx, dhocy)
return hoc, hoclist
if hoc is not None:
tx = tx - pxMin +dhocx/2
ty = ty - pyMin +dhocy/2
itx = int(tx/dhocx)
ity = int(ty/dhocy)
ps = [-1, 0, 1]
neigh=[]
for ii in range(3):
for jj in range(3):
ix = itx + ps[ii]
iy = ity + ps[jj]
if ix < 0:
continue
if iy < 0:
continue
if ix > nhocx-1:
continue
if iy > nhocy-1:
continue
#neightt = myUtil.hocFind(ppx, ppy, dhocx, dhocy, hoc, hoclist)
it = hoc[iy, ix]
while it != -1:
neigh.append(it)
it = hoclist[it]
#neigh.append(neightt)
#ll = [i for k in neigh for i in k]
if dn != -1:
ptx = np.array(partx[neigh])
pty = np.array(party[neigh])
dd = np.hypot(ptx-tx, pty-ty)
idx = np.argsort(dd)
neigh= np.array(neigh)[idx[0:dn]]
return neigh
#####################################
iccd = 13 #[1, 30]
iwave= 1 #[1, 4]
ipsf = 1 #[1, 100]
psfPathA = '/data/simudata/CSSOSDataProductsSims/data/csstPSFdata/CSSOS_psf_ciomp'
psfPathB = '/data/simudata/CSSOSDataProductsSims/data/csstPSFdata/CSSOS_psf_ciomp_30X30'
for iccd in range(1,31):
if iccd != 1:
continue
npsfA = 100
npsfB = 900
imxA = np.zeros(npsfA)
imyA = np.zeros(npsfA)
imxB = np.zeros(npsfB)
imyB = np.zeros(npsfB)
for ipsf in range(npsfA):
print('ipsf-{:}'.format(ipsf), end='\r')
psfInfo = myConfig.LoadPSF(iccd, iwave, ipsf+1, psfPathA, InputMaxPixelPos=False, PSFCentroidWgt=True)
imxA[ipsf] = psfInfo['image_x']+psfInfo['centroid_x']
imyA[ipsf] = psfInfo['image_y']+psfInfo['centroid_y']
for ipsf in range(npsfB):
print('ipsf-{:}'.format(ipsf), end='\r')
psfInfo = myConfig.LoadPSF(iccd, iwave, ipsf+1, psfPathB, InputMaxPixelPos=True, PSFCentroidWgt=True)
imxB[ipsf] = psfInfo['image_x']+psfInfo['centroid_x']
imyB[ipsf] = psfInfo['image_y']+psfInfo['centroid_y']
#######
px = imxB
py = imyB
hoc,hoclist = findNeighbors_hoclist(px, py)
#if True:
for ipsfA in range(npsfA):
#plt.close()
plt.clf()
#fig = plt.figure(figsize=(12,12))
plt.plot(imxA, imyA, 'b.')
plt.plot(imxB, imyB, 'r.')
#ipsfA = 19
tx = imxA[ipsfA]
ty = imyA[ipsfA]
neigh = findNeighbors_hoclist(px, py, tx=tx,ty=ty, dn=4, hoc=hoc, hoclist=hoclist)
plt.plot(imxB[neigh],imyB[neigh],'x', ms=10)
plt.plot(tx, ty,'+', ms=10)
#plt.savefig('figs/psfCrossPos.pdf')
display.clear_output(wait=True)
plt.pause(0.05)
"""
plot PSF场的分布:iccd-1-30
"""
import sys,os,math
import time
from IPython import display
import numpy as np
import matplotlib.pyplot as plt
import mpi4py.MPI as MPI
sys.path.append("/public/home/weichengliang/lnData/CSST_new_framwork/csstPSF")
import PSFConfig as myConfig
import PSFUtil as myUtil
def assignTasks(npsf, NTasks, ThisTask):
npsfPerTasks = int(npsf/NTasks)
iStart= 0 + npsfPerTasks*ThisTask
iEnd = npsfPerTasks + npsfPerTasks*ThisTask
if ThisTask == NTasks:
iEnd = npsf
return iStart, iEnd
#######
comm = MPI.COMM_WORLD
ThisTask = comm.Get_rank()
NTasks = comm.Get_size()
#######
iccd = 1 #[1, 30]
iwave= 1 #[1, 4]
ipsf = 1 #[1, 100]
psfPathA = '/data/simudata/CSSOSDataProductsSims/data/csstPSFdata/CSSOS_psf_ciomp'
psfPathB = '/data/simudata/CSSOSDataProductsSims/data/csstPSFdata/CSSOS_psf_ciomp_30X30'
for iccd in range(1,31):
npsfA = 100
npsfB = 900
iStartA, iEndA = assignTasks(npsfA, NTasks, ThisTask)
iStartB, iEndB = assignTasks(npsfB, NTasks, ThisTask)
imxA = np.zeros(npsfA)
imyA = np.zeros(npsfA)
imxB = np.zeros(npsfB)
imyB = np.zeros(npsfB)
psfA_e1 = np.zeros(npsfA)
psfA_e2 = np.zeros(npsfA)
psfB_e1 = np.zeros(npsfB)
psfB_e2 = np.zeros(npsfB)
for ipsf in range(iStartA+1, iEndA+1):
print('ipsf-{:}'.format(ipsf), end='\r')
psfInfo = myConfig.LoadPSF(iccd, iwave, ipsf, psfPathA, InputMaxPixelPos=False, PSFCentroidWgt=True)
imxA[ipsf-1] = psfInfo['image_x']+psfInfo['centroid_x']
imyA[ipsf-1] = psfInfo['image_y']+psfInfo['centroid_y']
cenX, cenY, sz, e1, e2, REE80 = myUtil.psfSizeCalculator(psfInfo['psfMat'], CalcPSFcenter=True, SigRange=True, TailorScheme=2)
psfA_e1[ipsf-1] = e1
psfA_e2[ipsf-1] = e2
for ipsf in range(iStartB+1, iEndB+1):
print('ipsf-{:}'.format(ipsf), end='\r')
psfInfo = myConfig.LoadPSF(iccd, iwave, ipsf, psfPathB, InputMaxPixelPos=True, PSFCentroidWgt=True)
imxB[ipsf-1] = psfInfo['image_x']+psfInfo['centroid_x']
imyB[ipsf-1] = psfInfo['image_y']+psfInfo['centroid_y']
cenX, cenY, sz, e1, e2, REE80 = myUtil.psfSizeCalculator(psfInfo['psfMat'], CalcPSFcenter=True, SigRange=True, TailorScheme=2)
psfB_e1[ipsf-1] = e1
psfB_e2[ipsf-1] = e2
#######
comm.barrier()
imxA = comm.allreduce(imxA, op=MPI.SUM)
imyA = comm.allreduce(imyA, op=MPI.SUM)
imxB = comm.allreduce(imxB, op=MPI.SUM)
imyB = comm.allreduce(imyB, op=MPI.SUM)
psfA_e1 = comm.allreduce(psfA_e1, op=MPI.SUM)
psfA_e2 = comm.allreduce(psfA_e2, op=MPI.SUM)
psfB_e1 = comm.allreduce(psfB_e1, op=MPI.SUM)
psfB_e2 = comm.allreduce(psfB_e2, op=MPI.SUM)
#######
if ThisTask == 0:
plt.close()
fig = plt.figure(figsize=(12,12))
plt.plot(imxA, imyA, 'b.')
plt.plot(imxB, imyB, 'r.')
plt.savefig('figs/psfCrossPos.pdf')
#######
fig = plt.figure(figsize=(12, 12))
plt.subplots_adjust(wspace=0.1, hspace=0.1)
ax = plt.subplot(1, 1, 1)
for ipsf in range(npsfA):
plt.plot(imxA[ipsf], imyA[ipsf], 'b.')
ang = np.arctan2(psfA_e2[ipsf], psfA_e1[ipsf])/2
ell = np.sqrt(psfA_e1[ipsf]**2 + psfA_e2[ipsf]**2)
ell *= 50
lcos = ell*np.cos(ang)
lsin = ell*np.sin(ang)
plt.plot([imxA[ipsf]-lcos, imxA[ipsf]+lcos],[imyA[ipsf]-lsin, imyA[ipsf]+lsin],'b', lw=2)
###########
for ipsf in range(npsfB):
plt.plot(imxB[ipsf], imyB[ipsf], 'r.', alpha=0.75)
ang = np.arctan2(psfB_e2[ipsf], psfB_e1[ipsf])/2
ell = np.sqrt(psfB_e1[ipsf]**2 + psfB_e2[ipsf]**2)
ell *= 50
lcos = ell*np.cos(ang)
lsin = ell*np.sin(ang)
plt.plot([imxB[ipsf]-lcos, imxB[ipsf]+lcos],[imyB[ipsf]-lsin, imyB[ipsf]+lsin],'r', lw=2, alpha=0.75)
###########
plt.gca().set_aspect(1)
#plt.savefig('figs/psfCrossEll_iccd{:}.pdf'.format(iccd))
"""
画出指定PSF image
"""
import sys,os,math
import time
from IPython import display
import numpy as np
import matplotlib.pyplot as plt
import mpi4py.MPI as MPI
sys.path.append("/public/home/weichengliang/lnData/CSST_new_framwork/csstPSF")
import PSFConfig as myConfig
import PSFUtil as myUtil
def plotPSFMat(iccd, iwave, ipsf, psfPath):
print('ipsf:', ipsf)
psfInfo = myConfig.LoadPSF(iccd, iwave, ipsf, psfPath, InputMaxPixelPos=True, PSFCentroidWgt=True)
imx = psfInfo['psfMat']
plt.close()
fig = plt.figure(figsize=(8,8))
cpp = 128
dcpp= 10
plt.imshow(imx[cpp-dcpp:cpp+dcpp, cpp-dcpp:cpp+dcpp])
plt.annotate('iccd-{:} ipsf-{:}'.format(iccd, ipsf), (0.1, 0.9), xycoords='axes fraction',color='w')
plt.savefig('figs/psfMatPlot_iccd{:}_ipsf{:}.pdf'.format(iccd, ipsf))
iccd = 28 #[1, 30]
iwave= 1 #[1, 4]
ipsf = 1 #[1, 100]
#psfPath = '/data/simudata/CSSOSDataProductsSims/data/csstPSFdata/CSSOS_psf_ciomp'
psfPath = '/data/simudata/CSSOSDataProductsSims/data/csstPSFdata/CSSOS_psf_ciomp_30X30'
for ipsf in range(12, 21):
plotPSFMat(iccd, iwave, ipsf, psfPath)
for ipsf in range(12, 21):
plotPSFMat(iccd, iwave, ipsf+30, psfPath)
for ipsf in range(12, 21):
plotPSFMat(iccd, iwave, ipsf+60, psfPath)
'''
centroidWgt: 测试stack后质心与波长平均质心位置的相对偏差
'''
import sys
from itertools import islice
import mpi4py.MPI as MPI
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
#mpl.use('Agg')
import scipy.io
#import xlrd
from scipy import ndimage
sys.path.append("/public/home/weichengliang/lnData/CSST_new_framwork/csstPSF")
import PSFConfig as myConfig
import PSFUtil as myUtil
def test_psfCentroidWgt(iccd, iwave, ipsf, psfPath):
psfInfo = myConfig.LoadPSF(iccd, iwave, ipsf, psfPath, InputMaxPixelPos=False)
ipsfMat = psfInfo['psfMat']
print('centroid_x/y', psfInfo['centroid_x']/0.005, psfInfo['centroid_y']/0.005)
img, cx, cy = myUtil.centroidWgt(ipsfMat, nt=160)
return img, cx, cy
def test_wavePSFCentroidWgt(iccd, ipsf, psfPath):
'''
读取四个波长采样以及计算centroidWgt质心位置偏差
'''
psf4iwave = []
for iwave in range(1, 5):
psfInfo = myConfig.LoadPSF(iccd, iwave, ipsf, psfPath, InputMaxPixelPos=True)
psf4iwave.append(psfInfo['psfMat'])
tt = myUtil.psfStack(psf4iwave[0], psf4iwave[1], psf4iwave[2], psf4iwave[3])
imgt = []
cxt = []
cyt = []
for iwave in range(4):
ipsfMat = psf4iwave[iwave]
img, cx, cy = myUtil.centroidWgt(ipsfMat, nt=160)
#print('iwave-{:}:'.format(iwave), cx, cy, flush=True)
imgt.append(img)
cxt.append(cx)
cyt.append(cy)
cxm = np.mean(np.array(cxt))
cym = np.mean(np.array(cyt))
img, cx, cy = myUtil.centroidWgt(tt, nt=160)
imgt.append(img)
return psf4iwave, imgt, cx - cxm, cy - cym, cxt, cyt
def test_wavePSFCentroidWgt_mpi(iccd, psfPath, ThisTask, NTasks):
npsf = 900
npsfPerTasks = int(npsf/NTasks)
iStart= 0 + npsfPerTasks*ThisTask
iEnd = npsfPerTasks + npsfPerTasks*ThisTask
if ThisTask == NTasks:
iEnd = npsf
#print(ThisTask, ':', iStart, iEnd)
psf_dcx = np.zeros(npsf)
psf_dcy = np.zeros(npsf)
for ipsf in range(iStart, iEnd):
if ThisTask == 0:
print('ThisTask-ipsf:', ThisTask, ipsf, flush=True)
psf4iwave, imgt, dcx, dcy, cxt, cyt = test_wavePSFCentroidWgt(iccd, ipsf+1, psfPath)
psf_dcx[ipsf] = dcx
psf_dcy[ipsf] = dcy
'''
if dcx>=1.0 or dcy>=1.0:
fig = plt.figure(figsize=(12,18))
for iax in range(5):
ax = plt.subplot(3,2,iax+1)
plt.imshow(imgt[iax][80-10:80+10, 80-10:80+10], origin='lower')
plt.savefig('figs/psfCentroidWgt_imgt{:}.pdf'.format(ipsf))
fig = plt.figure(figsize=(12,18))
for iax in range(4):
ax = plt.subplot(3,2,iax+1)
plt.imshow(psf4iwave[iax][90-10:90+10, 90-10:90+10], origin='lower')
plt.plot(cxt[iax]-90+10, cyt[iax]-90+10, 'b+', ms=20)
ax = plt.subplot(3,2,5)
tt = myUtil.psfStack(psf4iwave[0], psf4iwave[1], psf4iwave[2], psf4iwave[3])
img, cx, cy = myUtil.centroidWgt(tt, nt=160)
plt.imshow(tt[90-10:90+10, 90-10:90+10], origin='lower')
plt.plot(cx-90+10, cy-90+10, 'b+', ms=20)
plt.savefig('figs/psfCentroidWgt_psfMat{:}.pdf'.format(ipsf))
print('ok?:', ipsf, dcx, dcy, cxt, cyt, cx, cy)
'''
comm.barrier()
psf_dcx = comm.allreduce(psf_dcx, op=MPI.SUM)
psf_dcy = comm.allreduce(psf_dcy, op=MPI.SUM)
if ThisTask == 0:
fig = plt.figure(figsize=(15,4))
ax = plt.subplot(1,3,1)
hist = plt.hist(psf_dcx)
plt.xlabel('dcx=cx-cxm')
plt.ylabel('PDF')
plt.annotate('psfCentroid_dcx', (0.65, 0.85), xycoords='axes fraction')
ax = plt.subplot(1,3,2)
hist = plt.hist(psf_dcy)
plt.xlabel('dcy=cy-cym')
plt.ylabel('PDF')
plt.annotate('psfCentroid_dcy', (0.65, 0.85), xycoords='axes fraction')
ax = plt.subplot(1,3,3)
hist = plt.hist(np.sqrt(psf_dcx*psf_dcx + psf_dcy*psf_dcy))
plt.xlabel('|dc|')
plt.ylabel('PDF')
plt.annotate('psfCentroid_|dc|', (0.65, 0.85), xycoords='axes fraction')
plt.savefig('figs/psfCentroidWgt_ccd{:}.pdf'.format(iccd))
plt.close()
if __name__=='__main__':
comm = MPI.COMM_WORLD
ThisTask = comm.Get_rank()
NTasks = comm.Get_size()
iccd = 13 #[1, 30]
iwave= 1 #[1, 4]
ipsf = 10 #[1, 100]
#psfPath = '/data/simudata/CSSOSDataProductsSims/data/csstPSFdata/CSSOS_psf_ciomp'
psfPath = '/data/simudata/CSSOSDataProductsSims/data/csstPSFdata/CSSOS_psf_ciomp_30X30'
'''
img, cx, cy = test_psfCentroidWgt(iccd, iwave, ipsf, psfPath)
print(cx, cy, flush=True)
plt.imshow(img[80-10:80+10, 80-10:80+10], origin='lower')
plt.show()
'''
'''
imgt = test_wavePSFCentroidWgt(iccd, ipsf, psfPath)
fig = plt.figure(figsize=(12,18))
for iax in range(5):
ax = plt.subplot(3,2,iax+1)
plt.imshow(imgt[iax][80-10:80+10, 80-10:80+10], origin='lower')
plt.savefig('figs/psfCentroidWgt.pdf')
'''
for iccd in range(1, 31):
if ThisTask ==0:
print('iccd:', iccd, flush=True)
test_wavePSFCentroidWgt_mpi(iccd, psfPath, ThisTask, NTasks)
'''
PSF-IDW插值的cross-check
'''
import sys
import numpy as np
import matplotlib.pyplot as plt
import mpi4py.MPI as MPI
sys.path.append("/public/home/weichengliang/lnData/CSST_new_framwork/csstPSF")
import PSFConfig as myConfig
import PSFUtil as myUtil
def assignTasks(npsf, NTasks, ThisTask):
npsfPerTasks = int(npsf/NTasks)
iStart= 0 + npsfPerTasks*ThisTask
iEnd = npsfPerTasks + npsfPerTasks*ThisTask
if ThisTask == NTasks:
iEnd = npsf
return iStart, iEnd
def test_Check(iccd, iwave, psfPathA, psfPathB, NTasks, ThisTask):
npsfA = 100
npsfB = 900
psfSetA, PSFMatA, cen_colA, cen_rowA = myConfig.LoadPSFset(iccd, iwave, npsfA, psfPathA, InputMaxPixelPos=False, PSFCentroidWgt=True)
psfSetB, PSFMatB, cen_colB, cen_rowB = myConfig.LoadPSFset(iccd, iwave, npsfB, psfPathB, InputMaxPixelPos=True, PSFCentroidWgt=True)
psf_sz = np.zeros(npsfA)
psf_e1 = np.zeros(npsfA)
psf_e2 = np.zeros(npsfA)
psfMaker_sz = np.zeros(npsfA)
psfMaker_e1 = np.zeros(npsfA)
psfMaker_e2 = np.zeros(npsfA)
iStart, iEnd= assignTasks(npsfA, NTasks, ThisTask)
for ipsf in range(iStart, iEnd):
#if ipsf != 83:
# continue
if ThisTask == 0:
print('ipsf:', ipsf, flush=True)
px = cen_colA[ipsf]
py = cen_rowA[ipsf]
img= myConfig.psfMaker_IDW(px, py, PSFMatB, cen_colB, cen_rowB, IDWindex=2, OnlyNeighbors=True, PSFCentroidWgt=False)
imgtt, cx, cy = myUtil.centroidWgt(img, nt=200)
imx = psfSetA[ipsf]['psfMat']
imy = imgtt
cenX, cenY, sz, e1, e2, REE80 = myUtil.psfSizeCalculator(imx, CalcPSFcenter=True, SigRange=True, TailorScheme=2)
psf_sz[ipsf] = sz
psf_e1[ipsf] = e1
psf_e2[ipsf] = e2
cenX, cenY, sz, e1, e2, REE80 = myUtil.psfSizeCalculator(imy, CalcPSFcenter=True, SigRange=True, TailorScheme=2)
psfMaker_sz[ipsf] = sz
psfMaker_e1[ipsf] = e1
psfMaker_e2[ipsf] = e2
#######
comm.barrier()
psf_sz = comm.allreduce(psf_sz, op=MPI.SUM)
psf_e1 = comm.allreduce(psf_e1, op=MPI.SUM)
psf_e2 = comm.allreduce(psf_e2, op=MPI.SUM)
psfMaker_sz = comm.allreduce(psfMaker_sz, op=MPI.SUM)
psfMaker_e1 = comm.allreduce(psfMaker_e1, op=MPI.SUM)
psfMaker_e2 = comm.allreduce(psfMaker_e2, op=MPI.SUM)
#######
if ThisTask == 0:
ell_iccd = np.zeros(npsfA)
ell_iccd_psfMaker = np.zeros(npsfA)
fig = plt.figure(figsize=(18, 5))
plt.subplots_adjust(wspace=0.1, hspace=0.1)
ax = plt.subplot(1, 3, 1)
for ipsf in range(npsfA):
imx = cen_colA[ipsf] #psfSet[ipsf-1]['image_x']
imy = cen_rowA[ipsf] #psfSet[ipsf-1]['image_y']
plt.plot(imx, imy, 'b.')
#ang = np.arctan2(psfSet[ipsf-1]['psf_e2'], psfSet[ipsf-1]['psf_e1'])/2
#ell = np.sqrt(psfSet[ipsf-1]['psf_e1']**2 + psfSet[ipsf-1]['psf_e2']**2)
ang = np.arctan2(psf_e2[ipsf], psf_e1[ipsf])/2
ell = np.sqrt(psf_e1[ipsf]**2 + psf_e2[ipsf]**2)
ell_iccd[ipsf] = ell
ell *= 50
lcos = ell*np.cos(ang)
lsin = ell*np.sin(ang)
plt.plot([imx-lcos, imx+lcos],[imy-lsin, imy+lsin],'b', lw=2)
###########
ang = np.arctan2(psfMaker_e2[ipsf], psfMaker_e1[ipsf])/2
ell = np.sqrt(psfMaker_e1[ipsf]**2 + psfMaker_e2[ipsf]**2)
ell_iccd_psfMaker[ipsf] = ell
ell *= 50
lcos = ell*np.cos(ang)
lsin = ell*np.sin(ang)
plt.plot([imx-lcos, imx+lcos],[imy-lsin, imy+lsin],'r', lw=1)
###########
plt.gca().set_aspect(1)
ax = plt.subplot(1, 3, 2)
tmp = plt.hist(ell_iccd, bins = 8, color='b', alpha=0.5)
tmp = plt.hist(ell_iccd_psfMaker, bins = 8, color='r', alpha=0.5)
plt.annotate('iccd-{:} iwave-{:}'.format(iccd, iwave), (0.55, 0.85), xycoords='axes fraction',fontsize=15)
plt.xlabel('ell')
plt.ylabel('PDF')
ax = plt.subplot(1, 3, 3)
dsz = (psfMaker_sz - psf_sz)/psf_sz
dsz_hist= plt.hist(dsz)
plt.xlabel('dsz')
plt.savefig('figs/psfCrossMakerIDW_30t10_iccd{:}_iwave{:}.pdf'.format(iccd, iwave))
if __name__ == '__main__':
#######
comm = MPI.COMM_WORLD
ThisTask = comm.Get_rank()
NTasks = comm.Get_size()
#######
iccd = 13 #[1, 30]
iwave= 1 #[1, 4]
ipsf = 10 #[1, 100]
psfPathA = '/data/simudata/CSSOSDataProductsSims/data/csstPSFdata/CSSOS_psf_ciomp'
psfPathB = '/data/simudata/CSSOSDataProductsSims/data/csstPSFdata/CSSOS_psf_ciomp_30X30'
for iccd in range(1, 31):
if iccd != 12:
continue
test_Check(iccd, iwave, psfPathA, psfPathB, NTasks, ThisTask)
#test_Check(28, iwave, psfPathA, psfPathB, NTasks, ThisTask)
#test_Check(29, iwave, psfPathA, psfPathB, NTasks, ThisTask)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment