Exemple #1
0
int main(){
    int N=4;
    dmat *A=dnew(N,N);
    dcell *B=cellnew(2,2);
    B->p[0]=dnew(N,N);
    B->p[2]=dnew(N,N);
    rand_t rstat;
    seed_rand(&rstat, 1);
    drandn(A, 1, &rstat);
    drandn(B->p[0], 1, &rstat);
    drandn(B->p[2], 1, &rstat);
    A->header=strdup("dx=1/64\ndy=1/64\nLong=kaflasdjfl ksflksjlfjasdflkj asldfj als fals fl asfjalsdf jalsf djasldf jal fsalfkjasdflkj asldfkj asldf \nadf\nwvf=1.e-4");
    writebin(A, "A.bin");
    writebin(A, "A.fits");
    writebin(A, "A.fits.gz");
    writebin(B, "B.bin");
    writebin(B, "B.fits");
    dmat *C=dread("A.fits");
    writebin(C, "C.fits");
    dcell *D=dcellread("B.fits");
    writebin(D, "D.fits");
    dcell *E=dcellread("A.fits");
    writebin(E, "E.fits");
    writebin(E, "E.fits.gz");
}
Exemple #2
0
static void test_cov(){/*not good */
    rand_t rstat;
    int seed=4;
    double r0=0.2;
    double dx=1./64;
    long N=1+1024;
    long nx=N;
    long ny=N;
    long nframe=1;
    seed_rand(&rstat, seed);
    map_t *atm=mapnew(nx, ny, dx,dx, NULL);
    cmat *atmhat=cnew((N+1)*3,(N+1)*3);
    dmat *atmhattot=dnew((N+1)*3,(N+1)*3);
    //cfft2plan(atmhat,-1);
    //cfft2plan(atmhat, 1);
    dset((dmat*)atm,1);
    cembedd(atmhat, (dmat*)atm, 0);
    cfft2(atmhat, -1);
    cabs22d(&atmhattot, 1, atmhat, 1);
    ccpd(&atmhat, atmhattot);
    cfft2i(atmhat, 1);
    cfftshift(atmhat);
    dmat *denom=dnew((N+1)*3,(N+1)*3);
    dmat *cov=dnew((N+1)*3,(N+1)*3);
    creal2d(&denom, 0, atmhat, 1);
    writebin(denom, "denom.bin");
    
    dzero(atmhattot);
    for(long i=0; i<nframe; i++){
	info("%ld of %ld\n", i, nframe);
	
	for(long j=0; j<nx*ny; j++){
	    atm->p[j]=randn(&rstat);
	}
	fractal_do((dmat*)atm, dx, r0,L0,ninit);
	/*mapwrite(atm, "atm_%ld.bin", i); */
	cembedd(atmhat, (dmat*)atm, 0);
	cfft2(atmhat, -1);
	cabs22d(&atmhattot, 1, atmhat, 1);

	if(i==0 || (i+1)%10==0){
	    dscale(atmhattot, 1./(i+1));
	    ccpd(&atmhat, atmhattot);
	    writebin(atmhattot, "atm_psf_%ld.bin",i+1);
	    cfft2i(atmhat, 1);
	    cfftshift(atmhat);
	    creal2d(&cov, 0, atmhat, 1);
	    for(long k=0; k<cov->nx*cov->ny; k++){
		cov->p[k]/=denom->p[k];
	    }
	    writebin(cov, "atm_cov_%ld.bin",i+1);
	}
    }
}
Exemple #3
0
static int test_fit(){
    info("Fit\n");
    dcell *opdr=dcellread("opdr.bin");
    MUV_T FR;
    FR.M=dspcellread("FRM.bin");
    FR.U=dcellread("FRU.bin");
    FR.V=dcellread("FRV.bin");
    MUV_T FL;
    FL.M=dspcellread("FLM.bin");
    FL.U=dcellread("FLU.bin");
    FL.V=dcellread("FLV.bin");
    dcell *rhs=NULL;
    tic;
    for(int i=0; i<10; i++)
	MUV(&rhs, &FR, opdr, 1);
    toc("");
    dcell *MUV_f=NULL;
    tic;
    for(int i=0; i<10; i++)
	MUV(&MUV_f, &FL, rhs, 1);
    toc("");
    writebin(rhs,"fit_rhs1.bin");
    writebin(MUV_f,"MUV_f.bin");
    RECON_T *recon=mycalloc(1,RECON_T);
    recon->HX=dspcellread("HX.bin");
    recon->HA=dspcellread("HA.bin");
    recon->W1=dread("W1.bin");
    recon->W0=dspread("W0.bin");
    recon->NW=dcellread("NW.bin");
    recon->fitwt=dread("fitwt.bin");
    dcell *rhs2=NULL;
    tic;
    for(int i=0; i<10; i++)
	FitR(&rhs2, recon, opdr, 1);
    toc("");
    writebin(rhs2,"fit_rhs2.bin");
    tic;
    dcell *FitL_f=NULL;
    for(int i=0; i<10; i++)
	FitL(&FitL_f, recon, rhs2, 1);
    toc("");
    writebin(FitL_f,"FitL_f.bin");
    info("Diff between rhs is %g\n", dcelldiff(rhs, rhs2));
    info("Diff between lhs is %g\n", dcelldiff(MUV_f, FitL_f));
    dcellfree(rhs);
    dcellfree(MUV_f);
    dcellfree(rhs2);
    dcellfree(FitL_f);
    return 0;
}
Exemple #4
0
static void test_part(){/**Compute the covariance of 4 points with various separation.*/
    rand_t rstat;
    int seed=4;
    double r0=0.2;
    double dx=1./64.;
    long N=1+2;
    long ofx=0;
    long ofy=0;
    long nx=N;
    long ny=N;
    long nframe=1000000;
    seed_rand(&rstat, seed);
    map_t *atm=mapnew(nx, ny, dx,dx, NULL);
    dmat *vec=dnew(4,1);
    dmat *cov=NULL;
    dmat* pp=(dmat*)atm;
    for(long i=0; i<nframe; i++){
	info("%ld of %ld\n", i, nframe);
	for(long j=0; j<nx*ny; j++){
	    atm->p[j]=randn(&rstat);
	}
	fractal_do((dmat*)atm, dx, r0,L0,ninit);
	vec->p[0]=IND(pp,ofx+0,ofy+0);
	vec->p[1]=IND(pp,ofx+1,ofy+0);
	vec->p[2]=IND(pp,ofx+0,ofy+1);
	vec->p[3]=IND(pp,ofx+1,ofy+1);
	dmm(&cov, 1, vec, vec, "nt", 1);
    }
    dscale(cov, 1./nframe);
    writebin(cov,"cov.bin");
}
Exemple #5
0
void Condition::write(FILE *out)
{
    compress();

	writebin(out, &type);
	writebin(out, &size);

    if (size >= 5)
        unit_cnst = pUnit ? pUnit->id() : -1;
    if (size >= 7)
	    tech_cnst = pTech ? pTech->id() : -1;

    if (size >= 0 && size <= MAXFIELDS) {
	    fwrite(&amount, sizeof(long) * size, 1, out);
    }
}
Exemple #6
0
/**
   Setup ray tracing operator HXF from xloc to aperture ploc along DM fiting directions*/
static void
setup_recon_HXF(RECON_T *recon, const PARMS_T *parms){
    if(parms->load.HXF && zfexist(parms->load.HXF)){
	warning("Loading saved HXF\n");
	recon->HXF=dspcellread("%s",parms->load.HXF);
    }else{
	info2("Generating HXF");TIC;tic;
	const int nfit=parms->fit.nfit;
	const int npsr=recon->npsr;
	recon->HXF=cellnew(nfit, npsr);
	PDSPCELL(recon->HXF,HXF);
	for(int ifit=0; ifit<nfit; ifit++){
	    double hs=parms->fit.hs->p[ifit];
	    for(int ips=0; ips<npsr; ips++){
		const double ht = recon->ht->p[ips];
		const double scale=1.-ht/hs;
		double displace[2];
		displace[0]=parms->fit.thetax->p[ifit]*ht;
		displace[1]=parms->fit.thetay->p[ifit]*ht;
		HXF[ips][ifit]=mkh(recon->xloc->p[ips], recon->floc, 
				   displace[0], displace[1], scale);
	    }
	}
	if(parms->save.setup){
	    writebin(recon->HXF,"HXF");
	}
	toc2(" ");
    }
}
Exemple #7
0
static int test_tomo(){
    info("Tomo\n");
    dcell *grad=dcellread("grad.bin");
    MUV_T RR;
    RR.M=dspcellread("RRM.bin"); 
    RR.U=dcellread("RRU.bin");
    RR.V=dcellread("RRV.bin");
    tic;
    dcell *rhs=NULL;
    MUV(&rhs, &RR, grad, 1);
    toc("");
    writebin(rhs,"rhs.bin");
    MUV_T RL;
    RL.M=dspcellread("RLM.bin");
    RL.U=dcellread("RLU.bin");
    RL.V=dcellread("RLV.bin");
    dcell *junk=NULL;
    tic; 
    for(int i=0; i<1; i++){
	MUV(&junk, &RL, rhs, 1);
    } 
    toc("");
    writebin(junk,"MUV1.bin");
    RECON_T *recon=mycalloc(1,RECON_T);
    recon->G0=dspcellread("G0.bin");
    recon->TT=dcellread("TT.bin");
    recon->PTT=dcellread("PTT.bin");
    recon->L2=dspcellread("L2.bin");
    recon->ZZT=dspcellread("ZZT.bin");
    recon->saneai=dspcellread("saneai.bin");
    tic;
    dcell *rhs2=NULL;
    TomoR(&rhs2, recon, grad, 1);
    toc("");
    writebin(rhs2,"rhs2.bin");
    dcell *junk2=NULL;
    tic;
    TomoL(&junk2, recon, rhs, 1);
    toc("");
    writebin(junk2,"TomoL1.bin");
    info("Diff between rhs is %g\n", dcelldiff(rhs, rhs2));
    info("Diff between lhs is %g\n", dcelldiff(junk,junk2));

    return 0;
}
Exemple #8
0
int main(int argc, char *argv[]) {
    if(argc<7) {
        info("Usage: %s loc.bin amp.bin cov.bin ncomp pttr wvl1 wvl2 ...\n", argv[0]);
        exit(0);
    }
    enum {
        P_EXE,
        P_LOC,
        P_AMP,
        P_COV,
        P_NCOMP,
        P_PTTR,
        P_WVL
    };
    loc_t *loc=locread("%s",argv[P_LOC]);
    dmat *amp=NULL;
    if(strcmp(argv[P_AMP],"NULL")) {
        amp=dread("%s",argv[P_AMP]);
    } else {
        amp=dnew(loc->nloc,1);
        dset(amp,1);
    }
    dmat *cov=dread("%s",argv[P_COV]);
    long ncomp=strtol(argv[P_NCOMP], NULL, 10);
    long pttr=strtol(argv[P_PTTR], NULL, 10);
    cmat *otf=otf=cnew(ncomp, ncomp);
    dmat *psf=NULL;
    for(int iwvl=0; iwvl<argc-P_WVL; iwvl++) {
        double wvl=strtod(argv[iwvl+P_WVL], NULL);
        double dtheta=wvl/(ncomp*loc->dx);
        genotf(&otf, loc, amp, NULL, NULL, 0, wvl, dtheta, cov, 0, 0, ncomp, ncomp, 1, pttr);
        writebin(otf, "%s_otf_%g.bin", argv[P_COV], wvl);
        cfftshift(otf);
        cfft2i(otf, 1);
        cfftshift(otf);
        creal2d(&psf, 0, otf, 1);
        writebin(psf, "%s_psf_%g.bin", argv[P_COV], wvl);
    }
    cfree(otf);
    dfree(psf);
    dfree(cov);
    dfree(amp);
    locfree(loc);
}
Exemple #9
0
int client(const char *hostname, int port, int nmin, int nmax, int nstep, int nrep){
    int sock=connect_port(hostname, port, 0, 1);
    if(sock<0 || stwriteint(sock, nstep) 
       || stwriteint(sock, nmin)
       || stwriteint(sock, nmax)
       || stwriteint(sock, nrep)) {
	warning("Unable to connecto to %s\n", hostname);
	close(sock); return 1;
    }
    buf1=(char*)malloc(nmax*nstep);
    for(int i=0;i<10;i++){//warm up
	stwrite(sock, buf1, nmax);
	stread(sock, buf1, 64);
	usleep(500);
    }
    double tim1, tim2, tim3;
    int nlen=(nmax-nmin+nstep)/nstep;
    dmat *timing=dnew(nrep, nlen);
    dmat *timing2=dnew(nrep, nlen);
    int ilen=-1;
    for(int len=nmin; len<=nmax; len+=nstep){
	ilen++;
	info("len=%d\n", len);
	for(int irep=0; irep<nrep; irep++){
	    if(irep%800==0){
		info("irep=%d of %d\n", irep, nrep);
	    }
	    usleep(500);
	    tim1=myclockd();
	    stwrite(sock, buf1, len);
	    tim2=myclockd();
	    stread(sock, buf1, 64);
	    tim3=myclockd();
	    timing->p[irep+ilen*nrep]=tim3-tim1;
	    timing2->p[irep+ilen*nrep]=tim2-tim1;
	}
    }
    close(sock);
    writebin(timing, "pix_timing_%s_%d_%d_%d", HOST, nmin, nmax, nstep);
    writebin(timing2, "pix_timing2_%s_%d_%d_%d", HOST, nmin, nmax, nstep);
    dbg("done\n");
    return 0;
}
Exemple #10
0
int main(int argc, char* argv[]){
    /*dsp *RLMc1=dspread("RLMc_old.bin"); */
    if(argc!=2){
	error("Need 1 argument\n");
    }
    dspcell *RLM=dspcellread("%s",argv[1]);
    dsp *RLMc=dspcell2sp(RLM);
    tic;info2("chol ...");
    spchol *R1=chol_factorize(RLMc);
    toc("done");
    rand_t rstat;
    seed_rand(&rstat,1);
    dmat *y=dnew(RLMc->m, 1);
    drandn(y, 1, &rstat);
    dmat *x=NULL, *x2=NULL, *x3=NULL;
    chol_convert(R1, 1);
    tic;
    chol_solve(&x, R1, y);
    toc("cholmod");tic;
    chol_solve(&x, R1, y);
    toc("cholmod");tic;
    chol_solve_upper(&x3, R1, y);
    toc("upper");tic;
    chol_solve_upper(&x3, R1, y);
    toc("upper");tic;
    chol_solve_lower(&x2, R1,y);
    toc("lower");tic;
    chol_solve_lower(&x2, R1,y);
    toc("lower");tic;
    chol_solve(&x, R1, y);
    toc("cholmod");tic;
    chol_solve(&x, R1, y);
    toc("cholmod");tic;
    writebin(y,"y");
    writebin(x,"x");
    writebin(x2,"x2");
    writebin(x3,"x3");
    chol_free(R1);
    dspfree(RLMc);
    dspcellfree(RLM);
}
Exemple #11
0
void save_gradstat(SIM_T *simu) {
    const PARMS_T *parms=simu->parms;
    const int isim=simu->isim;
    //Save pistat in the end of simulation
    for(int iwfs=0; iwfs<simu->parms->nwfs; iwfs++) {
        int ipowfs=parms->wfsr[iwfs].powfs;
        const int dtrat=parms->powfs[ipowfs].dtrat;
        double scale;
        if(parms->powfs[ipowfs].usephy) {
            scale=(simu->isim+1-simu->parms->powfs[ipowfs].phystep)/dtrat;
        } else {
            scale=(simu->isim+1)/dtrat;
        }
        if(scale<=0) continue;
        if(simu->pistatout && simu->pistatout->p[iwfs]) {
            int nstep=isim+1-parms->powfs[ipowfs].pistatstart;
            scale=1./(double)nstep;
            dcell *pp=simu->pistatout->p[iwfs];
            dcellscale(pp,scale);
            if(parms->sim.skysim) { /*need peak in corner */
                for(long ic=0; ic<pp->nx*pp->ny; ic++) {
                    dfftshift(pp->p[ic]);
                }
                writebin(pp,"%s/pistat/pistat_seed%d_sa%d_x%g_y%g.bin",
                         dirskysim,simu->seed,
                         parms->powfs[ipowfs].order,
                         parms->wfs[iwfs].thetax*206265,
                         parms->wfs[iwfs].thetay*206265);
                for(long ic=0; ic<pp->nx*pp->ny; ic++) {
                    dfftshift(pp->p[ic]);
                }
            } else { /*need peak in center */
                writebin(pp,"pistat_seed%d_wfs%d.bin", simu->seed,iwfs);
            }
            dcellscale(pp,1./scale);
        }
    }
}
Exemple #12
0
void setup_aster_lsr(ASTER_S *aster, STAR_S *star, const PARMS_S *parms){
    int ndtrat=parms->skyc.ndtrat;
    if(aster->pgm){
	dcellfree(aster->pgm);
	dcellfree(aster->sigman);
    }
    aster->pgm=cellnew(ndtrat,1);
    aster->sigman=cellnew(ndtrat,1);
    dmat *gm=ddup(aster->gm);
    if(aster->nwfs==1 && parms->maos.nmod==6 && gm->nx==8){
	info2("set 3rd column of gm to zero\n");
	memset(gm->p+gm->nx*2, 0, sizeof(double)*gm->nx);
    }

    for(int idtrat=0; idtrat<ndtrat; idtrat++){
	dcell *nea=cellnew(aster->nwfs, 1);
	for(int iwfs=0; iwfs<aster->nwfs; iwfs++){
	    nea->p[iwfs]=ddup(aster->wfs[iwfs].pistat->sanea->p[idtrat]);
	    dcwpow(nea->p[iwfs], 2);
	}
	dmat *neam=dcell2m(nea);//measurement error covariance
	dcellfree(nea); 
	dcwpow(neam, -1);//inverse
	/*Reconstructor */
	aster->pgm->p[idtrat]=dpinv(gm, neam);
	/*sigman is error due to noise. */
	dcwpow(neam, -1);//inverse again
	aster->sigman->p[idtrat]=calc_recon_error(aster->pgm->p[idtrat],neam,parms->maos.mcc);
	dfree(neam);
    }	
    if(parms->skyc.dbg){
	writebin(gm,"%s/aster%d_gm",dirsetup,aster->iaster);
	writebin(aster->pgm,    "%s/aster%d_pgm", dirsetup,aster->iaster);
	writebin(aster->sigman, "%s/aster%d_sigman", dirsetup,aster->iaster);
    }
    dfree(gm);
}
Exemple #13
0
/*
static int test_fft_speed_small(){
    int nis=128;
    int *is=mycalloc(nis,int);
    dmat *tim=dnew(nis,1);
    for(int ii=0; ii<nis; ii++){
	is[ii]=ii+1;
    }
    ccell *ac=cellnew(nis,1);
    rand_t stat;
    seed_rand(&stat,1);
    for(int ii=0; ii<nis; ii++){
	ac->p[ii]=cnew(is[ii],is[ii]);
	//cfft2plan(ac->p[ii],-1);
	crandn(ac->p[ii],20,&stat);
    }
    TIC;
    for(int ii=0; ii<nis; ii++){
	info2("size %4d: ",is[ii]);
	tic;
	for(int i=0; i<1000; i++){
	    cfft2(ac->p[ii],-1);
	}
	toc2("fft");
	tim->p[ii]=toc3;
    }
    writebin(tim,"fft_timing");
}

static void test_fft_speed(){
    int nis=2048;
    int *is=mycalloc(nis,int);
    dmat *tim=dnew(nis,1);
    for(int ii=0; ii<nis; ii++){
	is[ii]=(ii+1)*2;
    }
    ccell *ac=cellnew(nis,1);
    rand_t stat;
    seed_rand(&stat,1);
    TIC;
    for(int ii=0; ii<nis; ii++){
	info2("size %4d: ",is[ii]);
	tic;
	ac->p[ii]=cnew(is[ii],is[ii]);
	//cfft2plan(ac->p[ii],-1);
	crandn(ac->p[ii],20,&stat);
	toc("plan");
    }
    toc("plan");
    for(int ii=0; ii<nis; ii++){
	info2("size %4d: ",is[ii]);
	tic;
	int nrepeat;
	if(is[ii]<300)
	    nrepeat=100;
	else if(is[ii]<1000)
	    nrepeat=10;
	else
	    nrepeat=1;

	for(int i=0; i<nrepeat; i++){
	    cfft2(ac->p[ii],-1);
	}
	toc2("fft");
	tim->p[ii]=toc3/nrepeat;
    }
    writebin(tim,"fft_timing");
    }*/
static void test_fft_special(){
    int nis=2;
    int *is=mycalloc(nis,int);
    dmat *tim=dnew(nis,1);
    is[0]=3824;
    is[1]=4096;
    ccell *ac=ccellnew(nis,1);
    rand_t rstat;
    seed_rand(&rstat,1);
    TIC;
    for(int ii=0; ii<nis; ii++){
	info2("size %4d: ",is[ii]);
	tic;
	ac->p[ii]=cnew(is[ii],is[ii]);
	//cfft2plan(ac->p[ii],-1);
	//cfft2partialplan(ac->p[ii],512,-1);
	crandn(ac->p[ii],20,&rstat);
	toc("plan");
    }

    for(int ii=0; ii<nis; ii++){
	info2("size %4d: ",is[ii]);
	tic;
	int nrepeat;
	if(is[ii]<300)
	    nrepeat=100;
	else if(is[ii]<1000)
	    nrepeat=10;
	else
	    nrepeat=4;

	for(int i=0; i<nrepeat; i++){
	    cfft2(ac->p[ii],-1);
	}
	toc2("fft");
	for(int i=0; i<nrepeat; i++){
	    cfft2partial(ac->p[ii],512,-1);
	}
	toc2("fft2partial");
	tim->p[ii]=toc3/nrepeat;
    }
    writebin(tim,"fft_timing");

}
Exemple #14
0
/**
   Compute Modal to gradient operator using average gradients. Similar to Z tilt
   since the mode is low order
 */
static void setup_star_g(const PARMS_S *parms, POWFS_S *powfs, STAR_S *star, int nstar){
    const long npowfs=parms->maos.npowfs;
    const double hc=parms->maos.hc;
    const double hs=parms->maos.hs;
    const double scale=pow(1.-hc/hs, -2);
    const double scale1=1.-scale;
    const int nmod=parms->maos.nmod;
    assert(nmod>=5 && nmod<=6);
    for(int istar=0; istar<nstar; istar++){
	star[istar].g=dcellnew(npowfs, 1);
	for(int ipowfs=0; ipowfs<npowfs; ipowfs++){
	    const long nsa=parms->maos.nsa[ipowfs];
	    const double thetax=star[istar].thetax;
	    const double thetay=star[istar].thetay;
	    star[istar].g->p[ipowfs]=dnew(nsa*2, nmod);
	    dmat*  pg=star[istar].g->p[ipowfs];
	    for(long isa=0; isa<nsa; isa++){
		const double xm=powfs[ipowfs].locxamp[isa];/*dot of x with amp. */
		const double ym=powfs[ipowfs].locyamp[isa];

		IND(pg,isa,0)     = 1.;
		IND(pg,isa+nsa,1) = 1.;
		if(parms->maos.ahstfocus){/*This mode has no global focus*/
		    IND(pg,isa,2)     = ( - 2*thetax*hc*scale);
		    IND(pg,isa+nsa,2) = ( - 2*thetay*hc*scale);
		}else{
		    IND(pg,isa,2)     = (scale1*2*xm - 2*thetax*hc*scale);
		    IND(pg,isa+nsa,2) = (scale1*2*ym - 2*thetay*hc*scale);
		}
		IND(pg,isa,3)     = (scale1*2*xm - 2*thetax*hc*scale);
		IND(pg,isa+nsa,3) = (-scale1*2*ym+ 2*thetay*hc*scale);
		IND(pg,isa,4)     = (scale1*ym   - thetay*hc*scale);
		IND(pg,isa+nsa,4) = (scale1*xm   - thetax*hc*scale);
		if(nmod>5){/*include a defocus term*/
		    IND(pg,isa,5)     = xm*2;
		    IND(pg,isa+nsa,5) = ym*2;
		}
	    }
	}
	if(parms->skyc.dbg){
	    writebin(star[istar].g,"%s/star%d_g",dirsetup,istar);
	}
    }
}
Exemple #15
0
static void test_ints(){
    rand_t init;
    seed_rand(&init,1);
    const int nwfs=6;
    lrand(&init);/*atm */
    rand_t wfs_rand[nwfs];
    for(int iwfs=0; iwfs<nwfs; iwfs++){
	seed_rand(wfs_rand+iwfs,lrand(&init));
    }
    dcell *mtche=dcellread("powfs0_mtche.bin");
    int nsim=500;
    int nsa=2582;
    dmat *nea=dnew(nsim,nsa*2);
    double(*pnea)[nsim]=(void*)nea->p;
    double rne=3;
    double bkgrnd=0;
    double siglev=1000;
    for(int iwfs=0; iwfs<nwfs; iwfs++){
	for(int isim=0; isim<nsim; isim++){
	    dbg("iwfs %d isim=%d\n",iwfs,isim);
	    /*dcell *ints=dcellread("ints_%d_wfs%d.bin",isim,iwfs); */
	    dcell *ints=dcellread("ints_%d_wfs%d.bin",isim,iwfs);
	    /*dcell *i0=dcellread("powfs0_i0.bin"); */
	    dmat *im=NULL, *imy=NULL;
	    double gnf[2], gny[2];

	    for(int isa=0; isa<nsa; isa++){
		dcp(&im,ints->p[isa]);
		dscale(im,siglev);
		gnf[0]=0; gnf[1]=0;
		dmulvec(gnf, mtche->p[isa], im->p,1.);
		gny[0]=0; gny[1]=0;
		dcp(&imy, im);
		addnoise(imy, &wfs_rand[iwfs], bkgrnd, bkgrnd, 0,0,rne);
		dmulvec(gny, mtche->p[isa], imy->p,1.);
		P(pnea,isim,isa)=gny[0]-gnf[0];
		P(pnea,isim,isa+nsa)=gny[1]-gnf[1];
	    }
	}
	writebin(nea,"test_sanea_wfs%d.bin",iwfs);
    }
}
Exemple #16
0
static void test_corner(){/*Compute the covariance of 4 corner points*/
    rand_t rstat;
    int seed=4;
    double r0=0.2;
    double dx=32;
    long N=1+1;
    long nx=N;
    long ny=N;
    long nframe=1000000;
    seed_rand(&rstat, seed);
    map_t *atm=mapnew(nx, ny, dx, dx,NULL);
    dmat *vec=dref_reshape((dmat*)atm, N*N, 1);
    dmat *cov=NULL;
    for(long i=0; i<nframe; i++){
	info("%ld of %ld\n", i, nframe);
	for(long j=0; j<nx*ny; j++){
	    atm->p[j]=randn(&rstat);
	}
	fractal_do((dmat*)atm, dx, r0,L0,ninit);
	dmm(&cov, 1, vec, vec, "nt", 1);
    }
    dscale(cov, 1./nframe);
    writebin(cov,"cov.bin");
}
Exemple #17
0
static void test_psd(){
    rand_t rstat;
    int seed=4;
    double r0=0.2;
    double dx=1./64;
    long N=1024;
    long nx=N;
    long ny=N;
    long ratio=1;
    long xskip=nx*(ratio-1)/2;
    long yskip=ny*(ratio-1)/2;
    long nframe=512;
    seed_rand(&rstat, seed);
    if(1){
	map_t *atm=mapnew(nx+1, ny+1, dx,dx, NULL);
	cmat *hat=cnew(nx*ratio, ny*ratio);
	//cfft2plan(hat, -1);
	dmat *hattot=dnew(nx*ratio, ny*ratio);

	for(long i=0; i<nframe; i++){
	    info2("%ld of %ld\n", i, nframe);
	    for(long j=0; j<(nx+1)*(ny+1); j++){
		atm->p[j]=randn(&rstat);
	    }
	    fractal_do((dmat*)atm, dx, r0,L0,ninit);
	    czero(hat);
	    for(long iy=0; iy<ny; iy++){
		for(long ix=0; ix<nx; ix++){
		    IND(hat,ix+xskip,iy+yskip)=IND(atm,ix,iy);
		}
	    }
	    cfftshift(hat);
	    cfft2i(hat, -1);
	    cabs22d(&hattot, 1, hat, 1);
	}
	dscale(hattot, 1./nframe);
	dfftshift(hattot);
	writebin(hattot, "PSD_fractal");
    }
    {
	dmat *spect=turbpsd(nx, ny, dx, r0, 100, 0, 0.5);
	writebin(spect, "spect");
	cmat *hat=cnew(nx*ratio, ny*ratio);
	//cfft2plan(hat, -1);
	dmat *hattot=dnew(nx*ratio, ny*ratio);
	cmat *atm=cnew(nx, ny);
	//cfft2plan(atm, -1);
	dmat *atmr=dnew(atm->nx, atm->ny);
	dmat *atmi=dnew(atm->nx, atm->ny);
	cmat*  phat=hat;
	dmat*  patmr=atmr;
	dmat*  patmi=atmi;
	for(long ii=0; ii<nframe; ii+=2){
	    info2("%ld of %ld\n", ii, nframe);
	    for(long i=0; i<atm->nx*atm->ny; i++){
		atm->p[i]=COMPLEX(randn(&rstat), randn(&rstat))*spect->p[i];
	    }
	    cfft2(atm, -1);
	    for(long i=0; i<atm->nx*atm->ny; i++){
		atmr->p[i]=creal(atm->p[i]);
		atmi->p[i]=cimag(atm->p[i]);
	    }
	    czero(hat);
	    for(long iy=0; iy<ny; iy++){
		for(long ix=0; ix<nx; ix++){
		    IND(phat,ix+xskip,iy+yskip)=IND(patmr,ix,iy);
		}
	    }
	    cfftshift(hat);
	    cfft2i(hat, -1);
	    cabs22d(&hattot, 1, hat, 1);
	    czero(hat);
	    for(long iy=0; iy<ny; iy++){
		for(long ix=0; ix<nx; ix++){
		    IND(phat,ix+xskip,iy+yskip)=IND(patmi,ix,iy);
		}
	    }
	    cfftshift(hat);
	    cfft2i(hat, -1);
	    cabs22d(&hattot, 1, hat, 1);
	}
	dscale(hattot, 1./nframe);
	dfftshift(hattot);
	writebin(hattot, "PSD_fft");
    }
}
Exemple #18
0
void save_recon(SIM_T *simu) {
    const PARMS_T *parms=simu->parms;
    const RECON_T *recon=simu->recon;
    if(parms->plot.run) {
        if(parms->recon.alg==0) {
            for(int i=0; simu->opdr && i<simu->opdr->nx; i++) {
                if(simu->opdr->p[i]) {
                    drawopd("opdr", recon->xloc->p[i], simu->opdr->p[i]->p, NULL,
                            "Reconstructed Atmosphere","x (m)","y (m)","opdr %d",i);
                }
            }
            for(int i=0; simu->dmfit && i<simu->dmfit->nx; i++) {
                if(simu->dmfit->p[i]) {
                    drawopd("DM", recon->aloc->p[i], simu->dmfit->p[i]->p,NULL,
                            "DM Fitting Output","x (m)", "y (m)","Fit %d",i);
                }
            }
        }
        if(!parms->recon.modal) {
            for(int idm=0; simu->dmerr && idm<parms->ndm; idm++) {
                if(simu->dmerr->p[idm]) {
                    drawopd("DM",recon->aloc->p[idm], simu->dmerr->p[idm]->p,NULL,
                            "DM Error Signal (Hi)","x (m)","y (m)",
                            "Err Hi %d",idm);
                }
            }
        }
        for(int idm=0; simu->dmerr && idm<parms->ndm; idm++) {
            if(simu->dmint->mint->p[0]->p[idm]) {
                drawopd("DM",recon->aloc->p[idm], simu->dmint->mint->p[0]->p[idm]->p,NULL,
                        "DM Integrator (Hi)","x (m)","y (m)",
                        "Int Hi %d",idm);
            }
        }
        if(simu->dm_wfs) {
            for(int iwfs=0; iwfs<parms->nwfs; iwfs++) {
                int ipowfs=parms->wfs[iwfs].powfs;
                int imoao=parms->powfs[ipowfs].moao;
                if(imoao<0) continue;
                drawopd("moao", recon->moao[imoao].aloc->p[0], simu->dm_wfs->p[iwfs]->p, NULL,
                        "MOAO", "x(m)", "y(m)", "WFS %d", iwfs);
            }
        }
        if(simu->dm_evl) {
            int imoao=parms->evl.moao;
            for(int ievl=0; ievl<parms->evl.nevl && imoao>=0; ievl++) {
                drawopd("moao", recon->moao[imoao].aloc->p[0], simu->dm_evl->p[ievl]->p, NULL,
                        "MOAO", "x(m)", "y(m)", "Evl %d", ievl);
            }
        }
    }
    if(parms->plot.run && simu->Merr_lo) {
        dcell *dmlo=NULL;
        switch(simu->parms->recon.split) {
        case 1:
            ngsmod2dm(&dmlo, recon, simu->Merr_lo, 1);
            break;
        case 2:
            dcellmm(&dmlo, simu->recon->MVModes, simu->Merr_lo, "nn", 1);
            break;
        }
        for(int idm=0; dmlo && idm<parms->ndm; idm++) {
            drawopd("DM",recon->aloc->p[idm], dmlo->p[idm]->p,NULL,
                    "DM Error Signal (Lo)","x (m)","y (m)",
                    "Err Lo %d",idm);
        }
        dcellfree(dmlo);
    }
    if(parms->plot.run && simu->Mint_lo && simu->Mint_lo->mint->p[0]) {
        dcell *dmlo=NULL;
        switch(simu->parms->recon.split) {
        case 1:
            ngsmod2dm(&dmlo, recon, simu->Mint_lo->mint->p[0], 1);
            break;
        case 2:
            dcellmm(&dmlo, simu->recon->MVModes, simu->Mint_lo->mint->p[0], "nn", 1);
            break;
        }
        for(int idm=0; dmlo && idm<parms->ndm; idm++) {
            drawopd("DM",recon->aloc->p[idm], dmlo->p[idm]->p,NULL,
                    "DM Integrator (Lo)","x (m)","y (m)",
                    "Int Lo %d",idm);
        }
        dcellfree(dmlo);
    }
    if(parms->recon.alg==0) { /*minimum variance tomo/fit reconstructor */
        if(parms->save.opdr) {
            cellarr_dcell(simu->save->opdr, simu->reconisim, simu->opdr);
        }
        if(parms->save.opdx || parms->plot.opdx) {
            dcell *opdx=simu->opdx;
            if(!opdx) {
                atm2xloc(&opdx, simu);
            }
            if(parms->save.opdx) {
                cellarr_dcell(simu->save->opdx, simu->isim, opdx);
            }
            if(parms->plot.opdx) { /*draw opdx */
                for(int i=0; i<opdx->nx; i++) {
                    if(opdx->p[i]) {
                        drawopd("opdx", recon->xloc->p[i], opdx->p[i]->p, NULL,
                                "Atmosphere Projected to XLOC","x (m)","y (m)","opdx %d",i);
                    }
                }
            }
            if(!parms->sim.idealfit) {
                dcellfree(opdx);
            }
        }
    }
    if(parms->save.dm && (!parms->sim.closeloop || simu->isim>0)) {
        if(simu->dmfit) {
            cellarr_dcell(simu->save->dmfit, simu->reconisim, simu->dmfit);
        }
        if(simu->dmerr) {
            cellarr_dcell(simu->save->dmerr, simu->reconisim, simu->dmerr);
        }
        if(simu->dmint->mint->p[0]) {
            cellarr_dcell(simu->save->dmint, simu->reconisim, simu->dmint->mint->p[0]);
        }
        if(simu->Merr_lo) {
            cellarr_dcell(simu->save->Merr_lo, simu->reconisim, simu->Merr_lo);
            if(!parms->sim.fuseint && simu->Mint_lo->mint->p[0]) {
                cellarr_dcell(simu->save->Mint_lo, simu->reconisim, simu->Mint_lo->mint->p[0]);
            }
        }
    }
    const int seed=simu->seed;
    if(parms->save.ngcov>0 && CHECK_SAVE(parms->sim.start, parms->sim.end-(parms->sim.closeloop?1:0), simu->reconisim, parms->save.gcovp)) {
        double scale=1./(double)(simu->reconisim-parms->sim.start+1);
        dcellscale(simu->gcov, scale);
        for(int igcov=0; igcov<parms->save.ngcov; igcov++) {
            writebin(simu->gcov->p[igcov], "gcov_%d_wfs%ld_%ld_%d.bin", seed,
                     parms->save.gcov->p[igcov*2], parms->save.gcov->p[igcov*2+1],
                     simu->reconisim+1);
        }
        dcellscale(simu->gcov, 1./scale);
    }
    if(parms->sim.psfr && CHECK_SAVE(parms->evl.psfisim, parms->sim.end-(parms->sim.closeloop?1:0), simu->reconisim, parms->sim.psfr)) {
        info2("Output PSF Recon Telemetry\n");
        long nstep=simu->reconisim+1-parms->evl.psfisim;
        double scale=1./nstep;
        dcellscale(simu->ecov, scale);
        if(!parms->dbg.useopdr || parms->sim.idealfit) {
            writebin(simu->ecov, "ecov_%d_%ld", seed, nstep);
        } else { /*deprecated */
            char strht[24];
            for(int ievl=0; ievl<parms->evl.nevl; ievl++) {
                if(!simu->ecov->p[ievl]) continue;
                if(isfinite(parms->evl.hs->p[ievl])) {
                    snprintf(strht, 24, "_%g", parms->evl.hs->p[ievl]);
                } else {
                    strht[0]='\0';
                }
                writebin(simu->ecov->p[ievl], "ecov_%d_x%g_y%g%s_%ld.bin", seed,
                         parms->evl.thetax->p[ievl]*206265,
                         parms->evl.thetay->p[ievl]*206265, strht, nstep);
            }
        }
        dcellscale(simu->ecov, 1./scale);//scale back to continuous accumulation
    }
}
Exemple #19
0
/**
   Time domain physical simulation.
   
   noisy: 
   - 0: no noise at all; 
   - 1: poisson and read out noise. 
   - 2: only poisson noise.   
*/
dmat *skysim_sim(dmat **mresout, const dmat *mideal, const dmat *mideal_oa, double ngsol, 
		 ASTER_S *aster, const POWFS_S *powfs, 
		 const PARMS_S *parms, int idtratc, int noisy, int phystart){
    int dtratc=0;
    if(!parms->skyc.multirate){
	dtratc=parms->skyc.dtrats->p[idtratc];
    }
    int hasphy;
    if(phystart>-1 && phystart<aster->nstep){
	hasphy=1;
    }else{
	hasphy=0;
    }
    const int nmod=mideal->nx;
    dmat *res=dnew(6,1);/*Results. 1-2: NGS and TT modes., 
			  3-4:On axis NGS and TT modes,
			  4-6: On axis NGS and TT wihtout considering un-orthogonality.*/
    dmat *mreal=NULL;/*modal correction at this step. */
    dmat *merr=dnew(nmod,1);/*modal error */
    dcell *merrm=dcellnew(1,1);dcell *pmerrm=NULL;
    const int nstep=aster->nstep?aster->nstep:parms->maos.nstep;
    dmat *mres=dnew(nmod,nstep);
    dmat* rnefs=parms->skyc.rnefs;
    dcell *zgradc=dcellnew3(aster->nwfs, 1, aster->ngs, 0);
    dcell *gradout=dcellnew3(aster->nwfs, 1, aster->ngs, 0);
    dmat *gradsave=0;
    if(parms->skyc.dbg){
	gradsave=dnew(aster->tsa*2,nstep);
    }
   
    
    SERVO_T *st2t=0;
    kalman_t *kalman=0;
    dcell *mpsol=0;
    dmat *pgm=0;
    dmat *dtrats=0;
    int multirate=parms->skyc.multirate;
    if(multirate){
	kalman=aster->kalman[0];
	dtrats=aster->dtrats;
    }else{
	if(parms->skyc.servo>0){
	    const double dtngs=parms->maos.dt*dtratc;
	    st2t=servo_new(merrm, NULL, 0, dtngs, aster->gain->p[idtratc]);
	    pgm=aster->pgm->p[idtratc];
	}else{
	    kalman=aster->kalman[idtratc];
	}
    }
    if(kalman){
	kalman_init(kalman);
	mpsol=dcellnew(aster->nwfs, 1); //for psol grad.
    }
    const long nwvl=parms->maos.nwvl;
    dcell **psf=0, **mtche=0, **ints=0;
    ccell *wvf=0,*wvfc=0, *otf=0;
    if(hasphy){
	psf=mycalloc(aster->nwfs,dcell*);
	wvf=ccellnew(aster->nwfs,1);
	wvfc=ccellnew(aster->nwfs,1);
	mtche=mycalloc(aster->nwfs,dcell*);
	ints=mycalloc(aster->nwfs,dcell*);
	otf=ccellnew(aster->nwfs,1);
    
	for(long iwfs=0; iwfs<aster->nwfs; iwfs++){
	    const int ipowfs=aster->wfs[iwfs].ipowfs;
	    const long ncomp=parms->maos.ncomp[ipowfs];
	    const long nsa=parms->maos.nsa[ipowfs];
	    wvf->p[iwfs]=cnew(ncomp,ncomp);
	    wvfc->p[iwfs]=NULL;
	    psf[iwfs]=dcellnew(nsa,nwvl);
	    //cfft2plan(wvf->p[iwfs], -1);
	    if(parms->skyc.multirate){
		mtche[iwfs]=aster->wfs[iwfs].pistat->mtche[(int)aster->idtrats->p[iwfs]];
	    }else{
		mtche[iwfs]=aster->wfs[iwfs].pistat->mtche[idtratc];
	    }
	    otf->p[iwfs]=cnew(ncomp,ncomp);
	    //cfft2plan(otf->p[iwfs],-1);
	    //cfft2plan(otf->p[iwfs],1);
	    ints[iwfs]=dcellnew(nsa,1);
	    int pixpsa=parms->skyc.pixpsa[ipowfs];
	    for(long isa=0; isa<nsa; isa++){
		ints[iwfs]->p[isa]=dnew(pixpsa,pixpsa);
	    }
	}
    }
    for(int irep=0; irep<parms->skyc.navg; irep++){
	if(kalman){
	    kalman_init(kalman);
	}else{
	    servo_reset(st2t);
	}
	dcellzero(zgradc);
	dcellzero(gradout);
	if(ints){
	    for(int iwfs=0; iwfs<aster->nwfs; iwfs++){
		dcellzero(ints[iwfs]);
	    }
	}
	for(int istep=0; istep<nstep; istep++){
	    memcpy(merr->p, PCOL(mideal,istep), nmod*sizeof(double));
	    dadd(&merr, 1, mreal, -1);/*form NGS mode error; */
	    memcpy(PCOL(mres,istep),merr->p,sizeof(double)*nmod);
	    if(mpsol){//collect averaged modes for PSOL.
		for(long iwfs=0; iwfs<aster->nwfs; iwfs++){
		    dadd(&mpsol->p[iwfs], 1, mreal, 1);
		}
	    }
	    pmerrm=0;
	    if(istep>=parms->skyc.evlstart){/*performance evaluation*/
		double res_ngs=dwdot(merr->p,parms->maos.mcc,merr->p);
		if(res_ngs>ngsol*100){
		    dfree(res); res=NULL;
		    break;
		}
		{
		    res->p[0]+=res_ngs;
		    res->p[1]+=dwdot2(merr->p,parms->maos.mcc_tt,merr->p);
		    double dot_oa=dwdot(merr->p, parms->maos.mcc_oa, merr->p);
		    double dot_res_ideal=dwdot(merr->p, parms->maos.mcc_oa, PCOL(mideal,istep));
		    double dot_res_oa=0;
		    for(int imod=0; imod<nmod; imod++){
			dot_res_oa+=merr->p[imod]*IND(mideal_oa,imod,istep);
		    }
		    res->p[2]+=dot_oa-2*dot_res_ideal+2*dot_res_oa;
		    res->p[4]+=dot_oa;
		}
		{
		    double dot_oa_tt=dwdot2(merr->p, parms->maos.mcc_oa_tt, merr->p);
		    /*Notice that mcc_oa_tt2 is 2x5 marix. */
		    double dot_res_ideal_tt=dwdot(merr->p, parms->maos.mcc_oa_tt2, PCOL(mideal,istep));
		    double dot_res_oa_tt=0;
		    for(int imod=0; imod<2; imod++){
			dot_res_oa_tt+=merr->p[imod]*IND(mideal_oa,imod,istep);
		    }
		    res->p[3]+=dot_oa_tt-2*dot_res_ideal_tt+2*dot_res_oa_tt;
		    res->p[5]+=dot_oa_tt;
		}
	    }//if evl

	    if(istep<phystart || phystart<0){
		/*Ztilt, noise free simulation for acquisition. */
		dmm(&zgradc->m, 1, aster->gm, merr, "nn", 1);/*grad due to residual NGS mode. */
		for(int iwfs=0; iwfs<aster->nwfs; iwfs++){
		    const int ipowfs=aster->wfs[iwfs].ipowfs;
		    const long ng=parms->maos.nsa[ipowfs]*2;
		    for(long ig=0; ig<ng; ig++){
			zgradc->p[iwfs]->p[ig]+=aster->wfs[iwfs].ztiltout->p[istep*ng+ig];
		    }
		}
	
		for(int iwfs=0; iwfs<aster->nwfs; iwfs++){
		    int dtrati=(multirate?(int)dtrats->p[iwfs]:dtratc);
		    if((istep+1) % dtrati==0){
			dadd(&gradout->p[iwfs], 0, zgradc->p[iwfs], 1./dtrati);
			dzero(zgradc->p[iwfs]);
			if(noisy){
			    int idtrati=(multirate?(int)aster->idtrats->p[iwfs]:idtratc);
			    dmat *nea=aster->wfs[iwfs].pistat->sanea->p[idtrati];
			    for(int i=0; i<nea->nx; i++){
				gradout->p[iwfs]->p[i]+=nea->p[i]*randn(&aster->rand);
			    }
			}
			pmerrm=merrm;//record output.
		    }
		}
	    }else{
		/*Accumulate PSF intensities*/
		for(long iwfs=0; iwfs<aster->nwfs; iwfs++){
		    const double thetax=aster->wfs[iwfs].thetax;
		    const double thetay=aster->wfs[iwfs].thetay;
		    const int ipowfs=aster->wfs[iwfs].ipowfs;
		    const long nsa=parms->maos.nsa[ipowfs];
		    ccell* wvfout=aster->wfs[iwfs].wvfout[istep];
		    for(long iwvl=0; iwvl<nwvl; iwvl++){
			double wvl=parms->maos.wvl[iwvl];
			for(long isa=0; isa<nsa; isa++){
			    ccp(&wvfc->p[iwfs], IND(wvfout,isa,iwvl));
			    /*Apply NGS mode error to PSF. */
			    ngsmod2wvf(wvfc->p[iwfs], wvl, merr, powfs+ipowfs, isa,
				       thetax, thetay, parms);
			    cembedc(wvf->p[iwfs],wvfc->p[iwfs],0,C_FULL);
			    cfft2(wvf->p[iwfs],-1);
			    /*peak in corner. */
			    cabs22d(&psf[iwfs]->p[isa+nsa*iwvl], 1., wvf->p[iwfs], 1.);
			}/*isa */
		    }/*iwvl */
		}/*iwfs */
	
		/*Form detector image from accumulated PSFs*/
		double igrad[2];
		for(long iwfs=0; iwfs<aster->nwfs; iwfs++){
		    int dtrati=dtratc, idtrat=idtratc;
		    if(multirate){//multirate
			idtrat=aster->idtrats->p[iwfs];
			dtrati=dtrats->p[iwfs];
		    }
		    if((istep+1) % dtrati == 0){/*has output */
			dcellzero(ints[iwfs]);
			const int ipowfs=aster->wfs[iwfs].ipowfs;
			const long nsa=parms->maos.nsa[ipowfs];
			for(long isa=0; isa<nsa; isa++){
			    for(long iwvl=0; iwvl<nwvl; iwvl++){
				double siglev=aster->wfs[iwfs].siglev->p[iwvl];
				ccpd(&otf->p[iwfs],psf[iwfs]->p[isa+nsa*iwvl]);
				cfft2i(otf->p[iwfs], 1); /*turn to OTF, peak in corner */
				ccwm(otf->p[iwfs], powfs[ipowfs].dtf[iwvl].nominal);
				cfft2(otf->p[iwfs], -1);
				dspmulcreal(ints[iwfs]->p[isa]->p, powfs[ipowfs].dtf[iwvl].si, 
					   otf->p[iwfs]->p, siglev);
			    }
		
			    /*Add noise and apply matched filter. */
#if _OPENMP >= 200805 
#pragma omp critical 
#endif
			    switch(noisy){
			    case 0:/*no noise at all. */
				break;
			    case 1:/*both poisson and read out noise. */
				{
				    double bkgrnd=aster->wfs[iwfs].bkgrnd*dtrati;
				    addnoise(ints[iwfs]->p[isa], &aster->rand, bkgrnd, bkgrnd, 0,0,IND(rnefs,idtrat,ipowfs));
				}
				break;
			    case 2:/*there is still poisson noise. */
				addnoise(ints[iwfs]->p[isa], &aster->rand, 0, 0, 0,0,0);
				break;
			    default:
				error("Invalid noisy\n");
			    }
		
			    igrad[0]=0;
			    igrad[1]=0;
			    double pixtheta=parms->skyc.pixtheta[ipowfs];
			    if(parms->skyc.mtch){
				dmulvec(igrad, mtche[iwfs]->p[isa], ints[iwfs]->p[isa]->p, 1);
			    }
			    if(!parms->skyc.mtch || fabs(igrad[0])>pixtheta || fabs(igrad[1])>pixtheta){
				if(!parms->skyc.mtch){
				    warning2("fall back to cog\n");
				}else{
				    warning_once("mtch is out of range\n");
				}
				dcog(igrad, ints[iwfs]->p[isa], 0, 0, 0, 3*IND(rnefs,idtrat,ipowfs), 0); 
				igrad[0]*=pixtheta;
				igrad[1]*=pixtheta;
			    }
			    gradout->p[iwfs]->p[isa]=igrad[0];
			    gradout->p[iwfs]->p[isa+nsa]=igrad[1];
			}/*isa */
			pmerrm=merrm;
			dcellzero(psf[iwfs]);/*reset accumulation.*/
		    }/*if iwfs has output*/
		}/*for wfs*/
	    }/*if phystart */
	    //output to mreal after using it to ensure two cycle delay.
	    if(st2t){//Type I or II control.
		if(st2t->mint->p[0]){//has output.
		    dcp(&mreal, st2t->mint->p[0]->p[0]);
		}
	    }else{//LQG control
		kalman_output(kalman, &mreal, 0, 1);
	    }
	    if(kalman){//LQG control
		int indk=0;
		//Form PSOL grads and obtain index to LQG M
		for(int iwfs=0; iwfs<aster->nwfs; iwfs++){
		    int dtrati=(multirate?(int)dtrats->p[iwfs]:dtratc);
		    if((istep+1) % dtrati==0){
			indk|=1<<iwfs;
			dmm(&gradout->p[iwfs], 1, aster->g->p[iwfs], mpsol->p[iwfs], "nn", 1./dtrati);
			dzero(mpsol->p[iwfs]);
		    }
		}
		if(indk){
		    kalman_update(kalman, gradout->m, indk-1);
		}
	    }else if(st2t){
		if(pmerrm){
		    dmm(&merrm->p[0], 0, pgm, gradout->m, "nn", 1);	
		}
		servo_filter(st2t, pmerrm);//do even if merrm is zero. to simulate additional latency
	    }
	    if(parms->skyc.dbg){
		memcpy(PCOL(gradsave, istep), gradout->m->p, sizeof(double)*gradsave->nx);
	    }
	}/*istep; */
    }
    if(parms->skyc.dbg){
	int dtrati=(multirate?(int)dtrats->p[0]:dtratc);
	writebin(gradsave,"%s/skysim_grads_aster%d_dtrat%d",dirsetup, aster->iaster,dtrati);
	writebin(mres,"%s/skysim_sim_mres_aster%d_dtrat%d",dirsetup,aster->iaster,dtrati);
    }
  
    dfree(mreal);
    dcellfree(mpsol);
    dfree(merr);
    dcellfree(merrm);
    dcellfree(zgradc);
    dcellfree(gradout);
    dfree(gradsave);
    if(hasphy){
	dcellfreearr(psf, aster->nwfs);
	dcellfreearr(ints, aster->nwfs);
        ccellfree(wvf);
	ccellfree(wvfc);
	ccellfree(otf);
	free(mtche);
    }
    servo_free(st2t);
    /*dfree(mres); */
    if(mresout) {
	*mresout=mres;
    }else{
	dfree(mres);
    }
    dscale(res, 1./((nstep-parms->skyc.evlstart)*parms->skyc.navg));
    return res;
}
Exemple #20
0
/**
   Select a few asterisms that have decent performance (less than maxerror) */
int setup_aster_select(double *result, ASTER_S *aster, int naster, STAR_S *star, 
		       double maxerror, const PARMS_S *parms){
 
    int ndtrat=parms->skyc.ndtrat;
    dmat *res=dnew(ndtrat, naster);
    PDMAT(res,pres);
    dmat *imin=dnew(2,naster);
    PDMAT(imin, pimin);
    int master=-1;
    double mini;
    double minimum=INFINITY;
    //int dtrat_h=(parms->skyc.maxdtrat+1)/2;
    for(int iaster=0; iaster<naster; iaster++){
	mini=maxerror;
	aster[iaster].mdtrat=-1;
	for(int idtrat=0; idtrat<(parms->skyc.multirate?1:ndtrat); idtrat++){
	    /*should not add res_ws here since res_ngs already includes that.*/
	    double rms=aster[iaster].res_ngs->p[idtrat];
	    pres[iaster][idtrat]=rms;
	    if(rms<mini){
		mini=rms;
		aster[iaster].mdtrat=idtrat;
		aster[iaster].mresol=rms;
	    }
	}
	pimin[iaster][0]=mini;
	pimin[iaster][1]=iaster;
	if(mini<minimum){
	    master=iaster;
	    minimum=mini;
	}
	if(!parms->skyc.multirate){
	    if(aster[iaster].mdtrat!=-1){
		if(parms->skyc.maxdtrat>1){
		    /*This is variance. allow a threshold */
		    double thres=mini*3;
		    double thres2=mini*3;
		    if(thres>maxerror) thres=maxerror;
		    if(thres2>maxerror) thres2=maxerror;
		    /*Find upper and minimum good dtrats. */
		    //MIN(ndtrat, aster[iaster].mdtrat+dtrat_h+1)
		    for(int idtrat=aster[iaster].mdtrat; idtrat<ndtrat; idtrat++){
			if(pres[iaster][idtrat]<thres){
			    aster[iaster].idtratmax=idtrat+1;
			}else{
			    break;
			}
		    }
		    //MAX(aster[iaster].mdtrat-dtrat_h, 0)
		    for(int idtrat=aster[iaster].mdtrat; idtrat>=0; idtrat--){
			if(pres[iaster][idtrat]<thres2){
			    aster[iaster].idtratmin=idtrat;
			}else{
			    break;
			}
		    }
		    /*prefer low frame rate to have good S/N*/
		    if(aster[iaster].idtratmax>aster[iaster].idtratmin+parms->skyc.maxdtrat+1){
			aster[iaster].idtratmax=aster[iaster].idtratmin+parms->skyc.maxdtrat+1;
			/*int mid=0.5*(aster[iaster].idtratmax+aster[iaster].idtratmin);
			  int min2=ceil(mid-parms->skyc.maxdtrat*0.5);
			  int max2=floor(mid+parms->skyc.maxdtrat*0.5);
			  aster[iaster].idtratmin=min2;
			  aster[iaster].idtratmax=max2;*/
		    }
		}else{
		    aster[iaster].idtratmin=aster[iaster].mdtrat;
		    aster[iaster].idtratmax=aster[iaster].idtratmin+1;
		}
	    }
	}else{//multirate
	    aster[iaster].mdtrat=aster[iaster].idtrats->p[0];
	    aster[iaster].idtratmin=aster[iaster].idtrats->p[0];
	    aster[iaster].idtratmax=aster[iaster].idtratmin+1;
	}
	if(parms->skyc.verbose){
	    info2("aster%d, dtrats=[%d, %d], best:%d res=%.1f nm\n", 
		  iaster, (int)parms->skyc.dtrats->p[aster[iaster].idtratmin], 
		  (int)parms->skyc.dtrats->p[aster[iaster].idtratmax-1], 
		  (int)parms->skyc.dtrats->p[aster[iaster].mdtrat], sqrt(mini)*1e9);
	}
    }
    if(parms->skyc.dbgsky>-1){
	writebin(imin, "sky%d_imin", parms->skyc.dbgsky);
    }
    qsort(imin->p, naster, 2*sizeof(double),(int(*)(const void*,const void*))sortfun);
    result[0]=minimum;
    if(aster[master].mdtrat!=-1){
	result[1]=parms->skyc.fss[aster[master].mdtrat];
    }
    int count=0;
    if(minimum<maxerror){
	double thres=MIN(minimum*3, maxerror);
	int taster=naster;
	if(parms->skyc.maxaster>0 && naster>parms->skyc.maxaster){
	    taster=parms->skyc.maxaster;
	}
	for(int jaster=0; jaster<taster; jaster++){
	    if(aster[jaster].mdtrat!=-1 && pimin[jaster][0]<thres){
		count++;
		int iaster=(int)pimin[jaster][1];
		aster[iaster].use=1;/*mark as valid. */
		for(int iwfs=0; iwfs<aster[iaster].nwfs; iwfs++){
		    int istar=aster[iaster].wfs[iwfs].istar;
		    int ipowfs=aster[iaster].wfs[iwfs].ipowfs;
		    star[istar].use[ipowfs]=1;
		}
	    }
	}
    }
    if(parms->skyc.verbose){
	info2("Minimum is found at aster %d at %.1f Hz: %.2f nm. Will evaluate %d asterisms.\n", 
	      master,result[1],sqrt(minimum)*1e9, count);
    }
    if(parms->skyc.dbg){
	writebin(res, "%s/aster_resol",dirsetup);
    }
    dfree(res);
    dfree(imin);
    return count;
}
Exemple #21
0
static void setup_aster_kalman(SIM_S *simu, ASTER_S *aster, STAR_S *star, const PARMS_S *parms){
    int ndtrat=parms->skyc.ndtrat;
    if(parms->skyc.multirate){
	aster->res_ngs=dnew(1,1);
	//assemble neam
	if(aster->neam) error("neam is already set?\n");
	aster->neam=calloc(1, sizeof(dcell*));
	aster->neam[0]=cellnew(aster->nwfs, aster->nwfs);
	for(int iwfs=0; iwfs<aster->nwfs; iwfs++){
	    int ng=aster->g->p[iwfs]->nx;
	    aster->neam[0]->p[iwfs+aster->nwfs*iwfs]=dnew(ng, ng);
	}
	aster->dtrats=dnew(aster->nwfs, 1);
	aster->idtrats=dnew(aster->nwfs, 1);
	int wfs0_min=0, wfs0_max=0;
	PISTAT_S *pistat0=&star[aster->wfs[0].istar].pistat[aster->wfs[0].ipowfs];
	for(int idtrat=0; idtrat<parms->skyc.ndtrat; idtrat++){
	    if(wfs0_min==0 && pistat0->snr->p[idtrat]>3){
		wfs0_min=idtrat;
	    }
	    if(pistat0->snr->p[idtrat]>=parms->skyc.snrmin->p[idtrat]){
		wfs0_max=idtrat;
	    }
	}
	aster->kalman=calloc(1, sizeof(kalman_t*));
	double resmin=INFINITY;
	kalman_t *kalman_min=0;
	int idtrat_min=0;
	//Try progressively lower sampling frequencies until performance starts to degrades
	for(int idtrat_limit=wfs0_max; idtrat_limit>wfs0_min; idtrat_limit--){
	    setup_aster_kalman_dtrat(aster, star, parms, idtrat_limit);
	    aster->kalman[0]=sde_kalman(simu->sdecoeff, parms->maos.dt, aster->dtrats, aster->g, aster->neam[0], 0);
	    dmat *rests=0;
#if 1   //more accurate
	    dmat *res=skysim_sim(parms->skyc.dbg?&rests:0, simu->mideal, simu->mideal_oa, simu->rmsol,
				 aster, 0, parms, -1, 1, -1);
	    double res0=res?res->p[0]:simu->rmsol;
	    dfree(res);
#else
	    rests=kalman_test(aster->kalman[0], simu->mideal);
	    double res0=calc_rms(rests, parms->maos.mcc, parms->skyc.evlstart);
#endif
	    if(parms->skyc.dbg){
		writebin(rests, "isky%d_iaster%d_dtrat%d_rest", simu->isky, aster->iaster, idtrat_limit);
	    }
	    if(parms->skyc.verbose) info2("res0=%g, resmin=%g\n", sqrt(res0)*1e9, sqrt(resmin)*1e9);
	    dfree(rests);
	    if(res0<resmin-100e-18){//better by 10 nm
		resmin=res0;
		kalman_free(kalman_min);
		kalman_min=aster->kalman[0];
		aster->kalman[0]=0;
		idtrat_min=idtrat_limit;
	    }else{
		kalman_free(aster->kalman[0]);aster->kalman[0]=0;
		if(isfinite(resmin) && res0>resmin*2){//stop trying.
		    break;
		}
	    }
	}
	setup_aster_kalman_dtrat(aster, star, parms, idtrat_min);
	if(parms->skyc.verbose) info2("selected\n");
	aster->res_ngs->p[0]=resmin;
	aster->kalman[0]=kalman_min;
    }else{
	if(aster->neam) dcellfreearr(aster->neam, ndtrat);
	aster->neam=calloc(ndtrat, sizeof(dcell*));
	aster->res_ngs=dnew(ndtrat,3);
	PDMAT(aster->res_ngs, pres_ngs);
	aster->kalman=calloc(ndtrat, sizeof(kalman_t*));
	dmat *dtrats=dnew(aster->nwfs,1);
	for(int idtrat=0; idtrat<ndtrat; idtrat++){
	    //assemble neam
	    //TIC;tic;
	    aster->neam[idtrat]=cellnew(aster->nwfs, aster->nwfs);
	    for(int iwfs=0; iwfs<aster->nwfs; iwfs++){
		dmat *tmp=ddup(aster->wfs[iwfs].pistat->sanea->p[idtrat]);/*in rad */
		dcwpow(tmp, 2);
		dsp *tmp2=dspnewdiag(tmp->nx, tmp->p, 1);
		dspfull(&aster->neam[idtrat]->p[iwfs+aster->nwfs*iwfs], tmp2,'n',1);
		dfree(tmp); dspfree(tmp2);
	    }

	    int dtrat=parms->skyc.dtrats->p[idtrat];
	    for(int iwfs=0; iwfs<aster->nwfs; iwfs++){
		dtrats->p[iwfs]=dtrat;
	    }
	    aster->kalman[idtrat]=sde_kalman(simu->sdecoeff, parms->maos.dt, dtrats, aster->g, aster->neam[idtrat], 0);
	    //toc("kalman");
#if 1
	    dmat *res=skysim_sim(0, simu->mideal, simu->mideal_oa, simu->rmsol, aster, 0, parms, idtrat, 1, -1);
	    double rms=res?res->p[0]:simu->rmsol;
	    dfree(res);
#else
	    dmat *res=kalman_test(aster->kalman[idtrat], simu->mideal);
	    double rms=calc_rms(res, parms->maos.mcc, parms->skyc.evlstart);
	    dfree(res);
#endif
	    //toc("estimate");
	    pres_ngs[0][idtrat]=rms;
	}
	dfree(dtrats);
    }
}
Exemple #22
0
/**
   Optimize type II servo gains beased on measurement noise and signal PSD. We try to minimize
   \f[
   \sigma^2=\int \textrm{PSD}_{ngs,ws}H_{rej}\textrm{d}\nu + \int_0^{\nu_{nyquist}} \textrm{PSF}\textrm{d}\nu
   \f]
*/
static void setup_aster_servo(SIM_S *simu, ASTER_S *aster, const PARMS_S *parms){
    int ndtrat=parms->skyc.ndtrat;
    if(aster->gain){
	dcellfree(aster->gain);
	dfree(aster->res_ws);
	dfree(aster->res_ngs);
    }
    aster->gain=cellnew(ndtrat,1);
    aster->res_ws=dnew(ndtrat,1);
    aster->res_ngs=dnew(ndtrat,3);
    PDMAT(aster->res_ngs, pres_ngs);
    for(int idtrat=0; idtrat<ndtrat; idtrat++){
	int dtrat=parms->skyc.dtrats->p[idtrat];
	double sigma_ngs= aster->sigman->p[idtrat]->p[0];
	double sigma_tt = aster->sigman->p[idtrat]->p[1];
	double sigma_ps = sigma_ngs-sigma_tt;
	double sigma_focus = aster->sigman->p[idtrat]->p[2];
	long nmod=parms->maos.nmod;
	/*gsplit:
	  0: All modes use the same gain.
	  1: PS, TT, focus (if nmod>5) use different gains. 
	  2: PS, TT use different gains. focus mode (if nmod>5) use PS gains.
	 */

	double res_ngs;/*residual error due to signal after servo rejection. */
	double res_ngsn;/*residual error due to noise. */
	const int servotype=parms->skyc.servo;
	const int ng=parms->skyc.ngain;
	aster->gain->p[idtrat]=dnew(ng,nmod);
	PDMAT(aster->gain->p[idtrat], pgain);
	if(parms->skyc.gsplit){
	    double pg_tt[ng+2];
	    double pg_ps[ng+2];
	    double pg_focus[ng+2];
	    if(parms->skyc.interpg){
		interp_gain(pg_tt, simu->gain_tt[idtrat], simu->gain_x, sigma_tt);
		interp_gain(pg_ps, simu->gain_ps[idtrat], simu->gain_x, sigma_ps);
		interp_gain(pg_focus, simu->gain_focus[idtrat], simu->gain_x, sigma_focus);
	    }else{
		dmat *sigma2=dnew(1,1); 
		dcell *tmp;
		sigma2->p[0]=sigma_tt;
		tmp=servo_optim(simu->psd_tt, parms->maos.dt, dtrat, parms->skyc.pmargin, sigma2, servotype);
		memcpy(pg_tt, tmp->p[0]->p, (ng+2)*sizeof(double)); dcellfree(tmp);

		sigma2->p[0]=sigma_ps;
		tmp=servo_optim(simu->psd_ps,    parms->maos.dt, dtrat, parms->skyc.pmargin, sigma2, servotype);
		memcpy(pg_ps, tmp->p[0]->p, (ng+2)*sizeof(double)); dcellfree(tmp);

		if(nmod>5){
		    sigma2->p[0]=sigma_focus;
		    tmp=servo_optim(simu->psd_focus, parms->maos.dt, dtrat, parms->skyc.pmargin, sigma2, servotype);
		    memcpy(pg_focus, tmp->p[0]->p, (ng+2)*sizeof(double)); dcellfree(tmp);
		}
		dfree(sigma2);
	    }
	    res_ngs  = pg_tt[ng] + pg_ps[ng] + pg_focus[ng];//residual mode
	    res_ngsn = pg_tt[ng+1] + pg_ps[ng+1] + pg_focus[ng+1];//error due to noise
	    for(int imod=0; imod<MIN(nmod,5); imod++){
		memcpy(pgain[imod], imod<2?pg_tt:pg_ps, sizeof(double)*ng);
	    }
	    if(nmod>5){
		memcpy(pgain[5], pg_focus, sizeof(double)*ng);
	    }
	}else{
	    double pg_ngs[ng+2];
	    if(parms->skyc.interpg){
		interp_gain(pg_ngs, simu->gain_ngs[idtrat], simu->gain_x, sigma_ngs);
	    }else{
		dmat *sigma2=dnew(1,1); sigma2->p[0]=sigma_ngs;
		dcell *tmp;
		tmp=servo_optim(simu->psd_ngs, parms->maos.dt, dtrat, parms->skyc.pmargin, sigma2, servotype);
		memcpy(pg_ngs, tmp->p[0]->p, (ng+2)*sizeof(double)); dcellfree(tmp);
	    }
	    res_ngs=pg_ngs[ng];
	    res_ngsn=pg_ngs[ng+1];
	    for(int imod=0; imod<nmod; imod++){
		memcpy(pgain[imod], pg_ngs, sizeof(double)*ng);
	    }
	}
	pres_ngs[0][idtrat]=res_ngs+res_ngsn;/*error due to signal and noise */
	pres_ngs[1][idtrat]=res_ngs;/*error due to signal */
	pres_ngs[2][idtrat]=res_ngsn;/*error due to noise propagation. */
	/*if(parms->skyc.reest){//estiamte error in time domain
	    dmat *sigma2=dnew(nmod,nmod);PDMAT(sigma2, psigma2);
	    PDMAT(parms->maos.mcc, pmcc);
	    //convert noise into mode space from WFE space.
	    psigma2[0][0]=psigma2[1][1]=sigma_tt/(2*pmcc[0][0]);
	    psigma2[2][2]=psigma2[3][3]=psigma2[4][4]=sigma_ps/(3*pmcc[2][2]);
	    if(nmod>5){
		psigma2[5][5]=sigma_focus/pmcc[5][5];
	    }
	    dmat *res=servo_test(simu->mideal, parms->maos.dt, dtrat, sigma2, aster->gain->p[idtrat]);
	    double rms=calc_rms(res,parms->maos.mcc, parms->skyc.evlstart);
	    pres_ngs[0][idtrat]=rms;
	    dfree(sigma2);
	    dfree(res);
	    }*/
	dmat *g_tt=dnew_ref(ng,1,pgain[0]);
	double gain_n;
	aster->res_ws->p[idtrat]=servo_residual(&gain_n, parms->skyc.psd_ws, 
						parms->maos.dt, dtrat, g_tt, 2);
	dfree(g_tt);
    }//for dtrat
    if(parms->skyc.dbg){
	writebin(aster->gain,"%s/aster%d_gain",dirsetup,aster->iaster);
	writebin(aster->res_ws,"%s/aster%d_res_ws",dirsetup,aster->iaster);
	writebin(aster->res_ngs,"%s/aster%d_res_ngs",dirsetup,aster->iaster);
    }
}
Exemple #23
0
/**
   Save NGS WFS and other information for later use in MAOS simulations.*/
void skysim_save(const SIM_S *simu, const ASTER_S *aster, const double *ipres, int selaster, int seldtrat, int isky){
    const PARMS_S* parms=simu->parms;
    const int nwvl=parms->maos.nwvl;
    char path[PATH_MAX];
    snprintf(path,PATH_MAX,"Res%d_%d_maos/sky%d",simu->seed_maos,parms->skyc.seed,isky);
    mymkdir("%s",path);
    for(int iwfs=0; iwfs<aster[selaster].nwfs; iwfs++){
	dcell *sepsf=dcelldup(aster[selaster].wfs[iwfs].pistat->psf);
	for(int ic=0; ic<sepsf->nx*sepsf->ny; ic++){
	    dfftshift(sepsf->p[ic]);/*put peak in center. required by MAOS. */
	}
	writebin(sepsf, "%s/pistat_wfs%d",path,iwfs+6);
	dcellfree(sepsf);
	writebin(aster->wfs[iwfs].pistat->sanea->p[seldtrat], "%s/nea_tot_wfs%d",path,iwfs+6);
	writebin(aster[selaster].wfs[iwfs].pistat->sanea->p[seldtrat], 
	       "%s/nea_wfs%d",path,iwfs+6);
	writebin(aster[selaster].wfs[iwfs].pistat->sanea, 
		   "%s/neafull_wfs%d",path,iwfs+6);
    }
    writebin(aster[selaster].gain->p[seldtrat], "%s/gain",path);
    writebin(simu->mres->p[isky], "%s/mres",path);
    writebin(simu->psd_tt,"%s/psd_tt",path);
    writebin(simu->psd_ps,"%s/psd_ps",path);
    char fnconf[PATH_MAX];
    snprintf(fnconf,PATH_MAX,"%s/base.conf",path);
    FILE *fp=fopen(fnconf,"w");

    fprintf(fp,"sim.seeds=[%d]\n",simu->seed_maos);
    fprintf(fp,"sim.end=%d\n", parms->maos.nstep);
    fprintf(fp,"sim.dt=%g\n", parms->maos.dt);
    fprintf(fp,"sim.zadeg=%g\n", parms->maos.zadeg);
    fprintf(fp,"sim.mffocus=%d\n", parms->maos.mffocus);
    fprintf(fp,"sim.ahstfocus=%d\n", parms->maos.ahstfocus);
    fprintf(fp,"tomo.ahst_wt=3\n");
    fprintf(fp,"sim.servotype_lo=2\n");/*type II */
    fprintf(fp,"sim.eplo='gain.bin'\n");
    fprintf(fp,"powfs0_llt.fnrange='%s'\n", parms->maos.fnrange);
    fprintf(fp,"atm.r0z=%.4f\n", parms->maos.r0z);
    fprintf(fp,"atm.size=[128 128]\n");
    if(parms->maos.wddeg){
	fprintf(fp, "atm.wddeg=[");
	for(int ips=0; ips<parms->maos.nwddeg; ips++){
	    fprintf(fp, "%.2f ", parms->maos.wddeg[ips]);
	}
	fprintf(fp, "]\n");
    }
    fprintf(fp,"wfs.thetax=[0 0  -33.287 -20.5725  20.5725 33.287");
    for(int iwfs=0; iwfs<aster[selaster].nwfs; iwfs++){
	fprintf(fp," %.4f", aster[selaster].wfs[iwfs].thetax*206265);
    }
    fprintf(fp,"]\n");
    fprintf(fp,"wfs.thetay=[0 35 10.8156 -28.3156 -28.3156 10.8156");
    for(int iwfs=0; iwfs<aster[selaster].nwfs; iwfs++){
	fprintf(fp," %.4f", aster[selaster].wfs[iwfs].thetay*206265);
    }
    fprintf(fp,"]\n");

    fprintf(fp,"wfs.siglev=[900 900 900 900 900 900");
    for(int iwfs=0; iwfs<aster[selaster].nwfs; iwfs++){
	fprintf(fp, " %.2f", aster[selaster].wfs[iwfs].siglevtot);
    }
    fprintf(fp,"]\n");
    fprintf(fp,"wfs.wvlwts=[1 1 1 1 1 1");
    for(int iwfs=0; iwfs<aster[selaster].nwfs; iwfs++){
	for(int iwvl=0; iwvl<nwvl; iwvl++){
	    fprintf(fp," %.2f ", aster[selaster].wfs[iwfs].siglev->p[iwvl]
		    /aster[selaster].wfs[iwfs].siglevtot);
	}
    }
    fprintf(fp,"]\n");
    fprintf(fp,"wfs.powfs=[0 0 0 0 0 0");
    for(int iwfs=0; iwfs<aster[selaster].nwfs; iwfs++){
	fprintf(fp, " %d", aster[selaster].wfs[iwfs].ipowfs+1);
    }
    fprintf(fp,"]\n");

    dmat* rnefs=parms->skyc.rnefs;
    double rne=IND(rnefs,seldtrat,0);
    double bkgrnd=aster[selaster].wfs[0].bkgrnd;

    if(parms->maos.npowfs==1){
	fprintf(fp, "powfs.piinfile=[\"\" \"pistat\" ]\n");
	fprintf(fp, "powfs.neareconfile=[\"\" \"nea_tot\"]\n");
	fprintf(fp, "powfs.phyusenea=[0 1]\n");
	fprintf(fp, "powfs.dtrat=[1 %d]\n", (int)parms->skyc.dtrats->p[seldtrat]);
	fprintf(fp, "powfs.bkgrnd=[0 %.2f]\n", bkgrnd);
	fprintf(fp, "powfs.rne=[3 %.2f]\n", rne);
	fprintf(fp, "powfs.phystep=[0 %ld]\n", 50+(long)parms->skyc.dtrats->p[seldtrat]*20);
	fprintf(fp, "powfs.noisy=[1 1 ]\n");
	fprintf(fp, "powfs.pixtheta=[0.5/206265 %g/206265000]\n", parms->skyc.pixtheta[1]*206265000);
	fprintf(fp, "powfs.pixpsa=[6 %d]\n", parms->skyc.pixpsa[0]);
	fprintf(fp, "powfs.ncomp=[64 %d]\n", parms->maos.ncomp[0]);
	fprintf(fp, "powfs.nwvl=[1 %d]\n",nwvl);
	fprintf(fp, "powfs.wvl=[0.589e-6");
	for(int ip=0; ip<1; ip++){
	    for(int iwvl=0; iwvl<nwvl; iwvl++){
		fprintf(fp, " %.4g", parms->maos.wvl[iwvl]);
	    }
	}
	fprintf(fp,"]\n");
    }else if(parms->maos.npowfs==2){
	fprintf(fp, "powfs.piinfile=[\"\" \"pistat\" \"pistat\"]\n");
	fprintf(fp, "powfs.neareconfile=[\"\" \"nea_tot\" \"nea_tot\"]\n");
	fprintf(fp, "powfs.phyusenea=[0 1 1]\n");
	fprintf(fp, "powfs.dtrat=[1 %d %d]\n", (int)parms->skyc.dtrats->p[seldtrat],
		(int)parms->skyc.dtrats->p[seldtrat]);
	fprintf(fp, "powfs.bkgrnd=[0 %.2f %.2f]\n", bkgrnd, bkgrnd);
	fprintf(fp, "powfs.rne=[3 %.2f %.2f]\n", rne,rne);
	fprintf(fp, "powfs.phystep=[0 %ld %ld]\n", 
		50+(long)parms->skyc.dtrats->p[seldtrat]*20, 
		50+(long)parms->skyc.dtrats->p[seldtrat]*20);
	fprintf(fp, "powfs.noisy=[1 1 1]\n");
	fprintf(fp, "powfs.pixtheta=[0.5/206265 %g/206265000 %g/206265000]\n",
		parms->skyc.pixtheta[0]*206265000,
		parms->skyc.pixtheta[1]*206265000);
	fprintf(fp, "powfs.pixpsa=[6 %d %d]\n",
		parms->skyc.pixpsa[0], 
		parms->skyc.pixpsa[1]);
	fprintf(fp, "powfs.ncomp=[64 %d %d]\n", 
		parms->maos.ncomp[0], parms->maos.ncomp[1]);
	fprintf(fp, "powfs.nwvl=[1 %d %d]\n",nwvl,nwvl);
	fprintf(fp, "powfs.wvl=[0.589e-6");
	for(int ip=0; ip<2; ip++){
	    for(int iwvl=0; iwvl<nwvl; iwvl++){
		fprintf(fp, " %.4g", parms->maos.wvl[iwvl]);
	    }
	}
	fprintf(fp,"]\n");
	fprintf(fp, "powfs.wvlwts=[]\n");
    }else{
	error("Fill this out please\n");
    }
 
    fclose(fp);
    snprintf(fnconf,PATH_MAX,"%s/skyres.txt",path);
    fp=fopen(fnconf,"w");
    fprintf(fp, "TotAll\tNGS\tTT\n");
    fprintf(fp, "%g\t%g\t%g\n",
	    sqrt(ipres[0])*1e9, sqrt(ipres[1])*1e9, sqrt(ipres[2])*1e9);
    fclose(fp);
}
Exemple #24
0
static void test_accuracy(int argc, char **argv){
    double displacex=0.01;
    double displacey=0.05;
    double scale=1.01;/*.414065; */
    int wrap=0;  

    double D=30;
    double D2=32;
    int save=1;
    if(argc>1){
	scale=strtod(argv[1], 0);
    }
    if(argc>2){
	displacex=strtod(argv[2], 0);
    }
    if(argc>3){
	displacey=strtod(argv[3], 0);
    }
    if(argc>4){
	wrap=strtol(argv[4], 0, 10);
    }
    if(argc>5){
	D=strtod(argv[5], 0);
    }
    if(argc>6){
	D2=strtod(argv[6], 0);
    }
    if(argc>7){
	save=strtol(argv[7], 0, 10);
    }

    double dx=1/64.; 
    double dsa=0.5;
    map_t *screen=mapnew(D2/dx, D2/dx, dx, dx, 0);
    dset((dmat*)screen, 1);
    for(long iy=0; iy<screen->ny; iy++){
	for(long ix=0; ix<screen->nx; ix++){
	    screen->p[ix+iy*screen->nx]=sin((double)ix/screen->nx*2*M_PI)*sin((double)iy/screen->ny*2*M_PI);
	}
    }

    /*loc for the map */
    loc_t *locin=mksqloc(screen->nx,screen->ny,dx,dx,screen->ox,screen->oy);
    
    //pts_t *pts=realloc(mkannloc(D, 0, 1./2.,0), sizeof(pts_t));
    pts_t *pts=realloc(mksqloc_auto(D/dsa, D/dsa, dsa, dsa), sizeof(pts_t));
    pts->dx=dx;
    pts->dy=dx;
    pts->nx=dsa/dx;
    pts->ny=pts->nx;
    loc_t *loc=pts2loc(pts);

    loc_create_map(locin);
    loc_create_stat(loc);
    loc_create_map(loc);
    locstat_t *locstat=loc->stat;
  
    map_t *screen2=mapnew2(locin->map);
    dset((dmat*)screen2, NAN);
    loc_embed(screen2, locin, screen->p);


    double *phi_pts, *phi_loc, *phi_stat;
    double *phi_loc2loc, *phi_h, *phi_cub, *phi_cub2, *phi_cubh;

    double cubic=0.3;
    int ii;
	    
    info("displacex=%g, displacey=%g, scale=%g, wrap=%d\n",
	 displacex, displacey,scale,wrap);
	
    double diff1, diff2,diff3,diff14,diff15;
    diff1=0;
    diff2=0;
    diff3=0;
    diff14=0;
    diff15=0;
	
    phi_pts=calloc(loc->nloc, sizeof(double));
    phi_loc=calloc(loc->nloc, sizeof(double));
    phi_stat=calloc(loc->nloc, sizeof(double));
    phi_loc2loc=calloc(loc->nloc, sizeof(double));

    map_t *map1=mapnew2(loc->map);
    prop_grid_map(screen, map1, -2, displacex, displacey, scale, wrap, 0,0);
    tic;
    prop_grid_map(screen, map1, 1, displacex, displacey, scale, wrap, 0,0);
    toc("map\t\t");

    prop_grid_pts(screen, pts, phi_pts, -2, displacex, displacey, scale, wrap, 0,0);
    tic;
    prop_grid_pts(screen, pts, phi_pts,  1, displacex, displacey, scale, wrap, 0,0);
    toc("pts\t\t");

    prop_grid_stat(screen, locstat, phi_stat, -2,displacex, displacey, scale, wrap, 0,0);
    tic;
    prop_grid_stat(screen, locstat, phi_stat , 1, displacex, displacey, scale, wrap, 0,0);
    toc("stat\t");tic;

    prop_grid(screen, loc, phi_loc, -2,displacex, displacey, scale, wrap, 0,0);
    tic;
    prop_grid(screen, loc, phi_loc,  1,displacex, displacey, scale, wrap, 0,0);
    toc("loc\t\t");


    prop_nongrid(locin, screen->p,loc, phi_loc2loc, -2,displacex, displacey, scale,0,0);
    toc("nongrid\t"); tic;
    prop_nongrid(locin, screen->p,loc, phi_loc2loc, 1,displacex, displacey, scale,0,0);
    toc("nongrid\t");
	
    phi_h=calloc(loc->nloc,sizeof(double));
 
    tic;
    dsp *hfor=mkh(locin, loc, displacex, displacey, scale);
    toc("mkh\t\t\t");
    dspmulvec(phi_h,hfor, screen->p, 'n', -2);
    tic;
    dspmulvec(phi_h,hfor, screen->p, 'n', 1);
    toc("mul h\t\t");


    phi_cub=calloc(loc->nloc,sizeof(double));
    phi_cub2=calloc(loc->nloc,sizeof(double));
    double *phi_cub3=calloc(loc->nloc,sizeof(double));
    double *phi_cub4=calloc(loc->nloc,sizeof(double));
    phi_cubh=calloc(loc->nloc, sizeof(double));

    prop_nongrid_cubic(locin,screen->p,loc,phi_cub,-2, displacex, displacey, scale, cubic,0,0);
    tic;
    prop_nongrid_cubic(locin,screen->p,loc,phi_cub,1, displacex, displacey, scale, cubic,0,0);
    toc("nongrid, cubic\t");
    prop_grid_cubic(screen, loc, phi_cub2, -2,displacex, displacey, scale,  cubic, 0,0);
    tic;
    prop_grid_cubic(screen, loc, phi_cub2, 1,displacex, displacey, scale,  cubic, 0,0);
    toc("grid,  cubic\t");
    prop_grid_cubic(screen2, loc,phi_cub3, -2,displacex, displacey, scale,  cubic, 0,0);
    tic;
    prop_grid_cubic(screen2, loc,phi_cub3, 1,displacex, displacey, scale,  cubic, 0,0);
    toc("grid2, cubic\t");
    prop_grid_stat_cubic(screen, locstat,phi_cub4, -2,displacex, displacey, scale,  cubic, 0,0);
    tic;
    prop_grid_stat_cubic(screen, locstat,phi_cub4, 1,displacex, displacey, scale,  cubic, 0,0);
    toc("grid  2stat, cubic\t");
    dsp *hforcubic;
    tic;
    hforcubic=mkh_cubic(locin, loc, displacex, displacey, scale, cubic);
    toc("mkh cubic \t\t");
    dspmulvec(phi_cubh, hforcubic,screen->p,'n',-2);
    tic;
    dspmulvec(phi_cubh, hforcubic,screen->p,'n',1);
    toc("cubic mul h\t\t");
    double diffc12=0,diff45=0,diff46=0,diff47=0;
    for(ii=0; ii<loc->nloc; ii++){
	diff1+=fabs(phi_loc[ii]-phi_pts[ii]);
	diff2+=fabs(phi_stat[ii]-phi_loc[ii]);
	diff3+=fabs(phi_stat[ii]-phi_pts[ii]);
	diff14+=fabs(phi_loc2loc[ii]-phi_pts[ii]);
	diff15+=fabs(phi_h[ii]-phi_pts[ii]);
	diff45+=fabs(phi_loc2loc[ii]-phi_h[ii]);
	diffc12+=fabs(phi_cub[ii]-phi_cubh[ii]);
	diff46+=fabs(phi_cub[ii]-phi_cub2[ii]);
	diff47+=fabs(phi_cub[ii]-phi_cub3[ii]);
    }
    info2("(pts-loc)=\t%g\n(loc-stat)=\t%g\n(stat-pts)=\t%g\n"
	  "(loc2loc-pts)=\t%g\n(h-pts)=\t%g\n"
	  "(loc2loc-h)=\t%g\n"
	  "(cub:h-loc2loc)=\t%g\n"
	  "(cub:map2loc-loc2loc)=\t%g\n"
	  "(cub:locmap2loc-loc2loc=\t%g\n"
	  ,diff1, diff2,diff3,diff14,diff15,diff45,diffc12, 
	  diff46, diff47);

//    exit(0);
    if(!save) return;
    mapwrite(screen2,"accphi_screen2");
    mapwrite(screen,"accphi_screen");
    locwrite((loc_t*)pts,"accphi_pts");
    locwrite(loc,"accphi_loc");
    locwrite(locin, "accphi_locin");
    loc_create_map_npad(locin, 0, 0, 0);
    mapwrite(locin->map, "accphi_locin_map");
    mapwrite(loc->map, "accphi_loc_map");
    mapwrite(map1, "accphi_map2map.bin");
    writedbl(phi_pts,loc->nloc,1,"accphi_pts1.bin");
    writedbl(phi_loc,loc->nloc,1,"accphi_loc0.bin");
    writedbl(phi_stat,loc->nloc,1,"accphi_stat.bin");
    writedbl(phi_loc2loc,loc->nloc,1,"accphi_loc2loc.bin");
    writedbl(phi_h,loc->nloc,1,"accphi_loc2h.bin");
    writedbl(phi_cub,loc->nloc,1,"accphi_cub_loc2loc.bin");
    writedbl(phi_cub2,loc->nloc,1,"accphi_cub_map2loc.bin");
    writedbl(phi_cub3,loc->nloc,1,"accphi_cub_locmap2loc.bin");
    writedbl(phi_cub4,loc->nloc,1,"accphi_cub_locmap2stat.bin");
    writedbl(phi_cubh,loc->nloc,1,"accphi_cub_loc2h.bin");
    info("saved\n");

    writedbl(phi_pts,loc->nloc,1,"accphi_pts.bin");
    writedbl(phi_cub,loc->nloc,1,"accphi_cub.bin");

    writebin(hfor, "accphi_hfor");
    writebin(hforcubic, "accphi_cub_hfor");
    dspfree(hfor);
    dspfree(hforcubic);
    free(phi_loc); free(phi_stat);
    free(phi_loc2loc);

    free(phi_pts);
    free(phi_h); 
    free(phi_cub); 
    free(phi_cubh);
	
    cellfree(screen);
    locfree(locin);
}
Exemple #25
0
int main(int argc, char *argv[]){
    enum{
	P_EXE,
	P_FRAC,
	P_NSTEP,
	P_TOT,
    };
    if(argc!=P_TOT){
	info2("Usage: \n\tenv MVM_CLIENT=hostname MVM_PORT=port MVM_SASTEP=sastep ./mvm_cpu fraction nstep\n");
	_Exit(0);
    }
    int fraction=strtol(argv[P_FRAC], NULL, 10);
    int nstep=strtol(argv[P_NSTEP], NULL, 10);
    int nstep0=nstep>1?20:0;//warm up
    dmat *d_saind=dread("NFIRAOS_saind");
    const int nsa=(d_saind->nx-1)/fraction;
    int *saind=mymalloc((1+nsa),int);
    for(int i=0; i<nsa+1; i++){
	saind[i]=(int)d_saind->p[i];
    }
    dfree(d_saind);
    const int totpix=saind[nsa];
    const int nact=6981;//active subapertures.
    int ng=nsa*2;
    float FSMdelta=-0.2;
    smat *dm=snew(nact,1);
    smat *mvm=snew(nact, ng);
    smat *mtch=snew(totpix*2,1);
    smat *grad=snew(ng,1);
    smat *im0=snew(totpix,3);
    short *pix=mymalloc(totpix,short);
    short *pixbias=mymalloc(totpix,short);
    {
	rand_t rseed;
	seed_rand(&rseed, 1);
	srandu(mvm, 1e-7, &rseed);
	srandu(mtch, 1, &rseed);
	for(int i=0; i<totpix; i++){
	    pix[i]=(short)(randu(&rseed)*25565);
	    pixbias[i]=(short)(randu(&rseed)*1000);
	}
    }
    smat *mvmt=strans(mvm);
    int sastep=200;//how many subapertures each time
    int nrep=1;
    if(getenv("MVM_NREP")){
	nrep=strtol(getenv("MVM_NREP"), NULL, 10);
    }
    if(getenv("MVM_SECT")){
	sastep=nsa/strtol(getenv("MVM_SECT"), NULL, 10);
    }
    if(getenv("MVM_TRANS")){
	use_trans=strtol(getenv("MVM_TRANS"), NULL, 10);
    }
    if(getenv("MVM_SASTEP")){
	sastep=strtol(getenv("MVM_SASTEP"), NULL, 10);
    }
    info2("use_trans=%d, nrep=%d, sastep=%d\n", use_trans, nrep, sastep);
    int sock=-1;
    char* MVM_CLIENT=getenv("MVM_CLIENT");
    if(MVM_CLIENT){
	short port=(short)strtol(getenv("MVM_PORT"), NULL, 10);
	sock=connect_port(MVM_CLIENT, port, 0 ,1);
	if(sock!=-1) {
	    info2("Connected\n");
	    int cmd[7];
	    cmd[0]=nact;
	    cmd[1]=nsa;
	    cmd[2]=sastep;
	    cmd[3]=totpix;
	    cmd[4]=nstep;
	    cmd[5]=nstep0;
	    cmd[6]=2;
	    if(stwriteintarr(sock, cmd, 7) 
	       || stwriteintarr(sock, saind, nsa+1)
	       || stwrite(sock, pix, sizeof(short)*totpix)){
		close(sock); sock=-1;
		warning("Failed: %s\n", strerror(errno));
	    }
	}
    }
    int ready=0;
    if(sock!=-1 && stwriteint(sock, ready)){
	warning("error send ready signal: %s\n", strerror(errno));
	close(sock); sock=-1;
    }
    smat *timing=snew(nstep, 1);
    TIC;
    float timtot=0, timmax=0, timmin=INFINITY;
    set_realtime(-1, -20);
    for(int jstep=-nstep0; jstep<nstep; jstep++){
	int istep=jstep<0?0:jstep;
	tic;
	double theta=M_PI*0.5*istep+FSMdelta;
	float cd=cos(theta);
	float sd=cos(theta);
	szero(dm);
	for(int isa=0; isa<nsa; isa+=sastep){
	    int npixleft;
	    int nsaleft;
	    if(nsa<isa+sastep){//terminate
		npixleft=totpix-saind[isa];
		nsaleft=nsa-isa;
	    }else{
		npixleft=saind[isa+sastep]-saind[isa];
		nsaleft=sastep;
	    }

	    short *pcur=pix+saind[isa];
	    if(sock!=-1){
		if(stread(sock, pcur, sizeof(short)*npixleft)){
		    warning("failed: %s\n", strerror(errno));
		    close(sock); sock=-1;
		    _Exit(1);
		}
		if(isa==0) tic;
	    }
	    //Matched filter
	    mtch_do(mtch->p, pix, pixbias, 
		    grad->p+isa*2, im0->p, im0->p+totpix, im0->p+totpix*2,
		    saind+isa, nsaleft, cd, sd);
	    //MVM
	    for(int irep=0; irep<nrep; irep++){
		if(use_trans){
		    mvmt_do(mvmt->p+isa*2, grad->p+isa*2,dm->p, nact, nsaleft*2, ng);
		}else{
		    mvm_do(mvm->p+isa*2*nact, grad->p+isa*2, dm->p, nact, nsaleft*2);
		}
	    }
	}//for isa
	if(sock!=-1){
	    if(stwrite(sock, dm->p, sizeof(float)*nact)){
		warning("error write dmres: %s\n", strerror(errno));
		close(sock); sock=-1;
		_Exit(1);
	    }
	    if(streadint(sock, &ready)){//acknowledgement.
		warning("error read ack failed: %s\n", strerror(errno));
		close(sock), sock=-1;
		_Exit(1);
	    }
	    timing->p[istep]=ready*1.e-6;
	}else{
	    timing->p[istep]=toc3;//do not tic.
	}
	if(jstep==istep){
	    timtot+=timing->p[istep];
	    if(timmax<timing->p[istep]){
		timmax=timing->p[istep];
	    }
	    if(timmin>timing->p[istep]){
		timmin=timing->p[istep];
	    }
	}
    }//for istep
    float timmean=timtot/nstep;
    info2("Timing is mean %.3f, max %.3f min %.3f. BW is %.1f of 51.2GB/s\n",
	  timmean*1e3, timmax*1e3, timmin*1e3, nrep*(nact*ng+nact+ng)*sizeof(float)/timmean/(1024*1024*1024));
    writebin(timing, "cpu_timing_%s", HOST);
    if(nstep==1){
	writearr("cpu_pix", 1, sizeof(short), M_INT16, NULL, pix, totpix, 1);
	writearr("cpu_pixbias", 1, sizeof(short), M_INT16, NULL, pixbias, totpix, 1);
	writebin(dm, "cpu_dm");
	writebin(grad, "cpu_grad");
	writebin(mvm, "cpu_mvm");
	writebin(mtch, "cpu_mtch");
    }
   
}
Exemple #26
0
/**
   Setup the least square reconstruct by directly inverting GA matrix. 
   The reconstructor is simply the pseudo inverse of GA matrix:
   \f[\hat{x}=(G_a^TC_g^{-1}G_a)^{-1}G_a^TC_g^{-1}\f]

   This is very close to RR except replacing GX with GA.

   We use the tomograhy parameters for lsr, since lsr is simply "tomography" onto DM directly.
*/
void setup_recon_lsr(RECON_T *recon, const PARMS_T *parms){
    const int ndm=parms->ndm;
    const int nwfs=parms->nwfsr;
    cell *GAlsr;
    cell *GAM=parms->recon.modal?(cell*)recon->GM:(cell*)recon->GA;
    if(parms->recon.split){ //high order wfs only in split mode. 
	GAlsr=parms->recon.modal?(cell*)recon->GMhi:(cell*)recon->GAhi;
    }else{ //all wfs in integrated mode. 
	GAlsr=GAM;
    }
    int free_GAlsr=0;
    if(GAlsr->p[0]->id!=M_DBL){
	dsp *tmp=dsp_cast(GAlsr->p[0]);
	if(tmp->nzmax>tmp->nx*tmp->ny*0.2){//not very sparse
	    dcell *tmp2=0;
	    free_GAlsr=1;
	    dcelladd(&tmp2, 1, (dspcell*)GAlsr, 1);
	    GAlsr=(cell*)tmp2;
	}
    }
    info2("Building recon->LR\n");
    recon->LR.M=dcellmm2(GAlsr, recon->saneai, "tn");
    // Tip/tilt and diff focus removal low rand terms for LGS WFS.
    if(recon->TTF){
	dcellmm(&recon->LR.U, recon->LR.M, recon->TTF, "nn", 1);
	recon->LR.V=dcelltrans(recon->PTTF);
    }
    info2("Building recon->LL\n");
    recon->LL.M=dcellmm2(recon->LR.M, GAlsr, "nn");
    if(free_GAlsr){
	cellfree(GAlsr);
    }
    double maxeig=pow(recon->neamhi * recon->aloc->p[0]->dx, -2);
    if(parms->recon.modal){
	double strength=1;
	for(int idm=0; idm<ndm; idm++){
	    strength*=dnorm(recon->amod->p[idm]);
	}
	strength=pow(strength, 2./ndm);
	maxeig*=strength;
    }
    if(fabs(parms->lsr.tikcr)>EPS){
	info2("Adding tikhonov constraint of %g to LLM\n", parms->lsr.tikcr);
	info2("The maximum eigen value is estimated to be around %g\n", maxeig);
	dcelladdI(recon->LL.M, parms->lsr.tikcr*maxeig);
    }
    dcell *NW=NULL;
    if(!parms->recon.modal){
	if(parms->lsr.alg!=2){
	    /* Not SVD, need low rank terms for piston/waffle mode constraint. */
	    NW=dcellnew(ndm,1);
	    int nmod=2;/*two modes. */
	    for(int idm=0; idm<ndm; idm++){
		loc_create_map(recon->aloc->p[idm]);
		const long nloc=recon->aloc->p[idm]->nloc;
		NW->p[idm]=dnew(nloc, ndm*nmod);
		double *p=NW->p[idm]->p+nmod*idm*nloc;
		const double *cpl=recon->actcpl->p[idm]->p;
		for(long iloc=0; iloc<nloc; iloc++){
		    if(cpl[iloc]>0.1){
			p[iloc]=1;/*piston mode */
		    }
		}
		/*notice offset of 1 because map start count at 1 */
		p=NW->p[idm]->p+(1+nmod*idm)*nloc-1;
		map_t *map=recon->aloc->p[idm]->map;
		for(long iy=0; iy<map->ny; iy++){
		    for(long ix=0; ix<map->nx; ix++){
			if(IND(map,ix,iy)){
			    p[(long)IND(map,ix,iy)]=(double)2*((iy+ix)&1)-1;
			}
		    }
		}
	    }
	    /*scale it to match the magnitude of LL.M */
	    dcellscale(NW, sqrt(maxeig));
	    if(parms->save.setup){
		writebin(NW, "lsrNW");
	    }
	}
	if(parms->lsr.actslave){
	    /*actuator slaving. important. change from 0.5 to 0.1 on 2011-07-14. */
	    dspcell *actslave=slaving(recon->aloc, recon->actcpl, NW,
				      recon->actstuck, recon->actfloat, parms->lsr.actthres, maxeig);
	    if(parms->save.setup){
		if(NW){
		    writebin(NW, "lsrNW2");
		}
		writebin(actslave,"actslave");
	    }
	    dcelladd(&recon->LL.M, 1, actslave, 1);
	    cellfree(actslave);
	}
    }
    /*Low rank terms for low order wfs. Only in Integrated tomography. */
    dcell *ULo=dcellnew(ndm,nwfs);
    dcell *VLo=dcellnew(ndm,nwfs);
    dcell*  pULo=ULo/*PDELL*/;
    dcell*  pVLo=VLo/*PDELL*/;
    for(int iwfs=0; iwfs<nwfs; iwfs++){
	int ipowfs=parms->wfsr[iwfs].powfs;
	if(parms->powfs[ipowfs].skip || !parms->powfs[ipowfs].lo){
	    continue;
	}
	for(int idm=0; idm<ndm; idm++){
	    dspfull(PIND(pULo,idm,iwfs), (dsp*)IND(recon->LR.M, idm, iwfs),'n',-1);
	    dspfull(PIND(pVLo,idm,iwfs), (dsp*)IND(GAM, iwfs, idm),'t',1);
	}
    }
    recon->LL.U=dcellcat(recon->LR.U, ULo, 2);
    dcell *GPTTDF=NULL;
    dcellmm(&GPTTDF, GAM, recon->LR.V, "tn", 1);
    recon->LL.V=dcellcat(GPTTDF, VLo, 2);
    dcellfree(GPTTDF);
    dcellfree(ULo);
    dcellfree(VLo);
    if(!parms->recon.modal && NW){
	info2("Create piston and check board modes that are in NULL space of GA.\n");
	/*add to low rank terms. */
	dcell *tmp=recon->LL.U;
	recon->LL.U=dcellcat(tmp, NW, 2);
	dcellfree(tmp);
	dcellscale(NW, -1);
	tmp=recon->LL.V;
	recon->LL.V=dcellcat(tmp, NW, 2);
	dcellfree(tmp);
	dcellfree(NW);
    }
    if(parms->lsr.fnreg){
	warning("Loading LSR regularization from file %s.\n", parms->lsr.fnreg);
	dspcell *tmp=dspcellread("%s", parms->lsr.fnreg);
	dcelladd(&recon->LL.M, 1, tmp, 1);
	dspcellfree(tmp);
    }
    recon->LL.alg = parms->lsr.alg;
    recon->LL.bgs = parms->lsr.bgs;
    recon->LL.warm = parms->recon.warm_restart;
    recon->LL.maxit = parms->lsr.maxit;
    /*Remove empty cells. */
    dcelldropempty(&recon->LR.U,2);
    dcelldropempty(&recon->LR.V,2);
    dcelldropempty(&recon->LL.U,2);
    dcelldropempty(&recon->LL.V,2);
    if(parms->save.recon){
	writebin(recon->LR.M,"LRM");
	writebin(recon->LR.U,"LRU");
	writebin(recon->LR.V,"LRV");
	writebin(recon->LL.M,"LLM.bin");/*disable compression */
	writebin(recon->LL.U,"LLU");
	writebin(recon->LL.V,"LLV"); 
    }
    if(parms->lsr.alg==0 || parms->lsr.alg==2){
	if(!parms->lsr.bgs){
	    muv_direct_prep(&recon->LL, (parms->lsr.alg==2)*parms->lsr.svdthres);
	    if(parms->save.recon){
		if(recon->LL.C)
		    chol_save(recon->LL.C, "LLC.bin");
		else
		    writebin(recon->LL.MI, "LLMI.bin");
	    }
	    cellfree(recon->LL.M);
	    dcellfree(recon->LL.U);
	    dcellfree(recon->LL.V);	
	}else{
	    muv_direct_diag_prep(&(recon->LL), (parms->lsr.alg==2)*parms->lsr.svdthres);
	    if(parms->save.recon){
		for(int ib=0; ib<recon->LL.nb; ib++){
		    if(recon->LL.CB)
			chol_save(recon->LL.CB[ib],"LLCB_%d.bin", ib);
		    else
			writebin(recon->LL.MI,"LLMIB_%d.bin", ib);
		}
	    }
	    /*Don't free M, U, V */
	}
    }
}
Exemple #27
0
/**
   Setup the detector transfer functions. See maos/setup_powfs.c
 */
static void setup_powfs_dtf(POWFS_S *powfs, const PARMS_S* parms){
    const int npowfs=parms->maos.npowfs;
    for(int ipowfs=0; ipowfs<npowfs; ipowfs++){
	const int ncomp=parms->maos.ncomp[ipowfs];
	const int ncomp2=ncomp>>1;
	const int embfac=parms->maos.embfac[ipowfs];
	const int pixpsa=parms->skyc.pixpsa[ipowfs];
	const double pixtheta=parms->skyc.pixtheta[ipowfs];
	const double blur=parms->skyc.pixblur[ipowfs]*pixtheta;
	const double e0=exp(-2*M_PI*M_PI*blur*blur);
	const double dxsa=parms->maos.dxsa[ipowfs];
	const double pixoffx=parms->skyc.pixoffx[ipowfs];
	const double pixoffy=parms->skyc.pixoffy[ipowfs];
	const double pxo=-(pixpsa/2-0.5+pixoffx)*pixtheta;
	const double pyo=-(pixpsa/2-0.5+pixoffy)*pixtheta;
	loc_t *loc_ccd=mksqloc(pixpsa, pixpsa, pixtheta, pixtheta, pxo, pyo);
	powfs[ipowfs].dtf=mycalloc(parms->maos.nwvl,DTF_S);
	for(int iwvl=0; iwvl<parms->maos.nwvl; iwvl++){
	    const double wvl=parms->maos.wvl[iwvl];
	    const double dtheta=wvl/(dxsa*embfac);
	    const double pdtheta=pixtheta*pixtheta/(dtheta*dtheta);
	    const double du=1./(dtheta*ncomp);
	    const double du2=du*du;
	    const double dupth=du*pixtheta;
	    cmat *nominal=cnew(ncomp,ncomp);
	    //cfft2plan(nominal,-1);
	    //cfft2plan(nominal,1);
	    cmat* pn=nominal;
	    const double theta=0;
	    const double ct=cos(theta);
	    const double st=sin(theta);
	    for(int iy=0; iy<ncomp; iy++){
		int jy=iy-ncomp2;
		for(int ix=0; ix<ncomp; ix++){
		    int jx=ix-ncomp2;
		    double ir=ct*jx+st*jy;
		    double ia=-st*jx+ct*jy;
		    IND(pn,ix,iy)=sinc(ir*dupth)*sinc(ia*dupth)
			*pow(e0,ir*ir*du2)*pow(e0,ia*ia*du2)
			*pdtheta;
		}
	    }
	    if(parms->skyc.fnpsf1[ipowfs]){
		warning("powfs %d has additional otf to be multiplied\n", ipowfs);
		dcell *psf1c=dcellread("%s", parms->skyc.fnpsf1[ipowfs]);
		dmat *psf1=NULL;
		if(psf1c->nx == 1){
		    psf1=dref(psf1c->p[0]);
		}else if(psf1c->nx==parms->maos.nwvl){
		    psf1=dref(psf1c->p[iwvl]);
		}else{
		    error("skyc.fnpsf1 has wrong dimension\n");
		}
		dcellfree(psf1c);
		if(psf1->ny!=2){
		    error("skyc.fnpsf1 has wrong dimension\n");
		}
		dmat *psf1x=dnew_ref(psf1->nx, 1, psf1->p);
		dmat *psf1y=dnew_ref(psf1->nx, 1, psf1->p+psf1->nx);
		dmat *psf2x=dnew(ncomp*ncomp, 1);
		for(int iy=0; iy<ncomp; iy++){
		    int jy=iy-ncomp2;
		    for(int ix=0; ix<ncomp; ix++){
			int jx=ix-ncomp2;
			psf2x->p[ix+iy*ncomp]=sqrt(jx*jx+jy*jy)*dtheta;
		    }
		}
		info("powfs %d, iwvl=%d, dtheta=%g\n", ipowfs, iwvl, dtheta*206265000);
		writebin(psf2x, "powfs%d_psf2x_%d", ipowfs,iwvl);
		dmat *psf2=dinterp1(psf1x, psf1y, psf2x, 0);
		normalize_sum(psf2->p, psf2->nx*psf2->ny, 1);
		psf2->nx=ncomp; psf2->ny=ncomp;
		writebin(psf2, "powfs%d_psf2_%d", ipowfs,iwvl);
		cmat *otf2=cnew(ncomp, ncomp);
		//cfft2plan(otf2, -1);
		ccpd(&otf2, psf2);//peak in center
		cfftshift(otf2);//peak in corner
		cfft2(otf2, -1);
		cfftshift(otf2);//peak in center
		writebin(otf2, "powfs%d_otf2_%d", ipowfs, iwvl);
		writebin(nominal, "powfs%d_dtf%d_nominal_0",ipowfs,iwvl);
		for(int i=0; i<ncomp*ncomp; i++){
		    nominal->p[i]*=otf2->p[i];
		}
		writebin(nominal, "powfs%d_dtf%d_nominal_1",ipowfs,iwvl);
		dfree(psf1x);
		dfree(psf1y);
		dfree(psf2x);
		dfree(psf1);
		cfree(otf2);
		dfree(psf2);
	    }
	    cfftshift(nominal);//peak in corner
	    cfft2(nominal,-1);
	    cfftshift(nominal);//peak in center
	    cfft2i(nominal,1);
	    warning_once("double check nominal for off centered skyc.fnpsf1\n");
	    /*This nominal will multiply to OTF with peak in corner. But after
	      inverse fft, peak will be in center*/
	    ccp(&powfs[ipowfs].dtf[iwvl].nominal, nominal);
	    cfree(nominal);

	    loc_t *loc_psf=mksqloc(ncomp, ncomp, dtheta, dtheta, -ncomp2*dtheta, -ncomp2*dtheta);
	    powfs[ipowfs].dtf[iwvl].si=mkh(loc_psf,loc_ccd,0,0,1);
	    locfree(loc_psf);
	    if(parms->skyc.dbg){
		writebin(powfs[ipowfs].dtf[iwvl].nominal,
		       "%s/powfs%d_dtf%d_nominal",dirsetup,ipowfs,iwvl);
		writebin(powfs[ipowfs].dtf[iwvl].si,
			"%s/powfs%d_dtf%d_si",dirsetup,ipowfs,iwvl);
	    }
	    powfs[ipowfs].dtf[iwvl].U=cnew(ncomp,1);
	    dcomplex *U=powfs[ipowfs].dtf[iwvl].U->p;

	    for(int ix=0; ix<ncomp; ix++){
		int jx=ix<ncomp2?ix:(ix-ncomp);
		U[ix]=COMPLEX(0, -2.*M_PI*jx*du);
	    }
	}/*iwvl */
	locfree(loc_ccd);
    }/*ipowfs */
}
Exemple #28
0
/**
   Closed loop simulation main loop. It calls init_simu() to initialize the
   simulation struct. Then calls genatm() to generate atmospheric turbulence
   screens. Then for every time step, it calls perfevl() to evaluate
   performance, wfsgrad() to do wfs measurement, reconstruct() to do tomography
   and DM fit, filter() to do DM command filtering. In MOAO mode, it call calls
   moao_recon() for MOAO DM fitting.  \callgraph */
void maos_sim(){
    const PARMS_T *parms=global->parms;
    POWFS_T *powfs=global->powfs;
    RECON_T *recon=global->recon;
    APER_T *aper=global->aper;
    int simend=parms->sim.end;
    int simstart=parms->sim.start;
    if(parms->sim.skysim){
	save_skyc(powfs,recon,parms);
    }
    if(parms->evl.psfmean || parms->evl.psfhist){
	/*compute diffraction limited PSF. Save to output directory.*/
	dmat *iopdevl=dnew(aper->locs->nloc,1);
	ccell *psf2s=0;
	locfft_psf(&psf2s, aper->embed, iopdevl, parms->evl.psfsize, 0);
	const int nwvl=parms->evl.nwvl;
	dcell *evlpsfdl=dcellnew(nwvl,1);
	for(int iwvl=0; iwvl<nwvl; iwvl++){
	    cabs22d(&evlpsfdl->p[iwvl], 1, psf2s->p[iwvl], 1);
	    evlpsfdl->p[iwvl]->header=evl_header(parms, aper, -1, iwvl);
	}
	ccellfree(psf2s);
	writebin(evlpsfdl, "evlpsfdl.fits");
	dcellfree(evlpsfdl);
	dfree(iopdevl);
    }
    info2("PARALLEL=%d\n", PARALLEL);
    if(simstart>=simend) return;
    double restot=0; long rescount=0;
    for(int iseed=0; iseed<parms->sim.nseed; iseed++){
	SIM_T *simu=0;
	while(!(simu=maos_iseed(iseed))){
	    iseed++;
	}
#ifdef HAVE_NUMA_H
	numa_set_localalloc();
#endif
	for(int isim=simstart; isim<simend; isim++){
	    maos_isim(isim);
	    if(parms->sim.pause){
		mypause();
	    }
	}/*isim */
	{
	    /*Compute average performance*/
	    int isim0;
	    if(parms->sim.closeloop){
		if(parms->sim.end>100){
		    isim0=MAX(50,parms->sim.end/10);
		}else{
		    isim0=MIN(20, parms->sim.end/2);
		}
	    }else{
		isim0=0;
	    }
	    double sum=0;
	    for(int i=isim0; i<parms->sim.end; i++){
		sum+=simu->cle->p[i*parms->evl.nmod];
	    }
	    restot+=sum/(parms->sim.end-isim0);
	    rescount++;
	}
	free_simu(simu);
	global->simu=0;
    }/*seed */
    printf("%g\n", sqrt(restot/rescount)*1e9);
}
Exemple #29
0
/*
  Compute cxx on atm to compare against L2, invpsd, fractal.
*/
static void test_cxx(){
    rand_t rstat;
    int seed=4;
    double r0=0.2;
    double dx=1./4;
    long N=16;
    long nx=N;
    long ny=N;
    long nframe=40960;
    seed_rand(&rstat, seed);
    {
	dmat *cxx=dnew(N*N,N*N);
	map_t *atm=mapnew(nx+1, ny+1, dx, dx,NULL);
	for(long i=0; i<nframe; i++){
	    info("%ld of %ld\n", i, nframe);
	    for(long j=0; j<(nx+1)*(ny+1); j++){
		atm->p[j]=randn(&rstat);
	    }
	    fractal_do((dmat*)atm, dx, r0, L0, ninit);
	    dmat *sec=dsub((dmat*)atm, 0, nx, 0, ny);
	    dmat *atmvec=dref_reshape(sec, nx*ny, 1);
	    dmm(&cxx,1, atmvec,atmvec,"nt",1);
	    dfree(atmvec);
	    dfree(sec);
	}
	dscale(cxx, 1./nframe);
	writebin(cxx, "cxx_fractal");
	dfree(cxx);
	mapfree(atm);
    }
    {
	dmat *cxx=dnew(N*N,N*N);
	dmat *spect=turbpsd(nx, ny, dx, r0, 100, 0, 0.5);
	spect->p[0]=spect->p[1];
	cmat *atm=cnew(nx, ny);
	//cfft2plan(atm, -1);
	dmat *atmr=dnew(nx*ny,1);
	dmat *atmi=dnew(nx*ny,1);
	for(long ii=0; ii<nframe; ii+=2){
	    info("%ld of %ld\n", ii, nframe);
	    for(long i=0; i<atm->nx*atm->ny; i++){
		atm->p[i]=COMPLEX(randn(&rstat), randn(&rstat))*spect->p[i];
	    }
	    cfft2(atm, -1);
	    for(long i=0; i<atm->nx*atm->ny; i++){
		atmr->p[i]=creal(atm->p[i]);
		atmi->p[i]=cimag(atm->p[i]);
	    }
	    dmm(&cxx,1, atmr,atmr,"nt",1);
	    dmm(&cxx,1, atmi,atmi,"nt",1);
	}
	dscale(cxx, 1./nframe);
	writebin(cxx, "cxx_fft");
	dfree(cxx);
	dfree(atmr);
	dfree(atmi);
	cfree(atm);
    }
    loc_t *loc=mksqloc_auto(16,16,1./4,1./4);
    locwrite(loc,"loc");
    dmat *B=stfun_kolmogorov(loc, r0);
    writebin(B, "B_theory");
}
Exemple #30
0
static void test_stfun(){
    rand_t rstat;
    int seed=4;
    double r0=0.2;
    double dx=1./16;
    long N=32;
    long nx=N;
    long ny=N;
    long nframe=500;
    seed_rand(&rstat, seed);
    if(L0<9000){
	dmat *rr=dlinspace(0, N*dx, N);
	dmat *covvk=turbcov(rr, sqrt(2)*N*dx, r0, L0);
	writebin(covvk, "cov_vk");
	dfree(rr);
	dfree(covvk);
    }
    /*    return; */
    {
	map_t *atm=mapnew(nx+1, ny+1, dx, dx,NULL);
	stfun_t *data=stfun_init(nx, ny, NULL);
	zfarr *save=zfarr_init(nframe, 1, "fractal_atm.bin");
	for(long i=0; i<nframe; i++){
	    for(long j=0; j<(nx+1)*(ny+1); j++){
		atm->p[j]=randn(&rstat);
	    }
	    fractal_do((dmat*)atm, dx, r0,L0,ninit);
	    stfun_push(data, (dmat*)atm);
	    zfarr_dmat(save, i, (dmat*)atm);
	    if(i%100==0)
		info("%ld of %ld\n", i, nframe);
	}
	zfarr_close(save);
	dmat *st=stfun_finalize(data);
	writebin(st, "stfun_fractal.bin");
	ddraw("fractal", st, NULL,NULL, "Atmosphere","x","y","stfun");
    }
    /*exit(0); */
    {
	stfun_t *data=stfun_init(nx, ny, NULL);
	dmat *spect=turbpsd(nx, ny, dx, r0, 100, 0, 0.5);
	cmat *atm=cnew(nx, ny);
	//cfft2plan(atm, -1);
	dmat *atmr=dnew(atm->nx, atm->ny);
	dmat *atmi=dnew(atm->nx, atm->ny);
	spect->p[0]=0;
	for(long ii=0; ii<nframe; ii+=2){
	    for(long i=0; i<atm->nx*atm->ny; i++){
		atm->p[i]=COMPLEX(randn(&rstat), randn(&rstat))*spect->p[i];
	    }
	    cfft2(atm, -1);
	    for(long i=0; i<atm->nx*atm->ny; i++){
		atmr->p[i]=creal(atm->p[i]);
		atmi->p[i]=cimag(atm->p[i]);
	    }
	    stfun_push(data, atmr);
	    stfun_push(data, atmi);
	    if(ii%100==0)
		info("%ld of %ld\n", ii, nframe);
	}
	dmat *st=stfun_finalize(data);
	writebin(st, "stfun_fft.bin");
	ddraw("fft", st, NULL,NULL, "Atmosphere","x","y","stfun");
    }
	
}