예제 #1
0
///////// Interpolate the prior grid to the redshift grid
///////// defined in zphot.param.
void interpolate_prior(double **priorkz_first, double **priorkz_out, double *priorzval,
                       long nzp, long nkp)
{
    long mag,iz,istart;

    for (mag=0;mag<nkp;++mag) {
        
        
        istart=0;
        for (iz=0;iz<NZ;++iz) {
            //////// No extrapolation
            if (ztry[iz] > priorzval[nzp-1] || ztry[iz] < priorzval[0]) {
            
                priorkz_out[mag][iz] = 1.;
     //           printf("extrapolate: %lf %lf %lf\n",ztry[iz],priorzval[nzp-1],priorzval[0]);
            } else { 
                interpol(ztry[iz],&priorkz_out[mag][iz],
                               priorzval,priorkz_first[mag],nzp,&istart);  
      //          printf("prior %ld %lf %lf\n",mag,ztry[iz],priorkz_out[mag][iz]);
            }
            //// Enforce minimum prior
            //if (priorkz_out[mag][iz] < 1.e-20) priorkz_out[mag][iz] = 1.e-20;
        }  
    }
    
}
예제 #2
0
파일: subfield.c 프로젝트: BENGMN/soen490
static void
init_primedata(primedata *S)
{
  long i, j, l, lff = lg(S->ff), v = fetch_var(), N = degpol(S->pol);
  GEN T, p = S->p;

  if (S->lcm == degpol(S->ff[lff-1]))
  {
    T = shallowcopy((GEN)S->ff[lff-1]);
    setvarn(T, v);
  }
  else
    T = init_Fq(p, S->lcm, v);
  name_var(v,"y");
  S->T = T;
  S->firstroot = cgetg(lff, t_VECSMALL);
  S->interp = cgetg(lff, t_VEC);
  S->fk = cgetg(N+1, t_VEC);
  for (l=1,j=1; j<lff; j++)
  { /* compute roots and fix ordering (Frobenius cycles) */
    GEN F = FpX_factorff_irred(gel(S->ff,j), T, p);
    gel(S->interp,j) = interpol(F,T,p);
    S->firstroot[j] = l;
    for (i=1; i<lg(F); i++,l++) S->fk[l] = F[i];
  }
  S->Trk     = init_traces(S->ff, T,p);
  S->bezoutC = get_bezout(S->pol, S->ff, p);
}
예제 #3
0
double pgammaPairInj2(double E, Vector Nproton, Particle& particle, Particle& proton, Fun* tpf)  
{
	double veinteE = 20.0*E;
	double protonDist = interpol(veinteE,proton.energyPoints,Nproton,Nproton.size()-1);
	//double protonDist = 3;

	double t_1   = t_pair_PH(veinteE, proton, tpf);     //esto no es lossesPH porque son perdidas solo del canal de produccion de piones
	double omega = omega_pair_PH(veinteE, proton, tpf);
	
	double emissivity;

	if (omega > 0.0)	{  //t_1 > 0.0 && 
		double averageInel = t_1/omega;

		double k1 = 0.2;

		double k2 = 0.6;

		double p1 = (k2-averageInel)/(k2-k1);

//		double pseda = 0.5;

		emissivity = 20.0*(2.0-1.5*p1)*omega*protonDist;
	}
	else	{
		emissivity = 0.0;
	}
	
	return emissivity;
}
예제 #4
0
int tt_ima_series_rot(TT_IMA_SERIES *pseries)
{
   TT_IMA *p_in,*p_out;
   int index;

   double x0, y0, theta;
   int w, h;
   int x, y;

   double cos_theta,sin_theta;      /* cos theta,sin theta */
   double old_x,old_y;              /* old point */
   double value;                    /* value of the pixel */
   double a[6];

   /* --- intialisations ---*/
   p_in=pseries->p_in;
   p_out=pseries->p_out;
   index=pseries->index;

   x0=pseries->user3.x0;
   y0=pseries->user3.y0;
   theta=pseries->user3.angle;
   w=p_in->naxis1;
   h=p_in->naxis2;

   /* --- initialisation ---*/
   /*tt_imabuilder(p_out);*/
   tt_imacreater(p_out,p_in->naxis1,p_in->naxis2);

   /* --- calcul de l'image retournee --- */
   cos_theta = cos(theta);
   sin_theta = sin(theta);

   for(x = 0;x < w;x++)
   {
      for(y = 0;y < h;y++)
      {
         old_x = cos_theta * (x - x0) + sin_theta * (y - y0) + x0;
         old_y = - sin_theta * (x - x0) + cos_theta * (y - y0) + y0;
         value = interpol(pseries,old_x,old_y,1);
         p_out->p[x+y*w]=(TT_PTYPE)(value);
      } /* end of y-loop */
   } /* end of x_loop */

   /* --- calcule les nouveaux parametres de projection ---*/
   a[0]=cos_theta;
   a[1]=sin_theta;
   a[2]=-cos_theta*x0-sin_theta*y0+x0;
   a[3]=-sin_theta;
   a[4]=cos_theta;
   a[5]=sin_theta*x0-cos_theta*y0+y0;
   tt_util_update_wcs(p_in,p_out,a,2,NULL);

   /* --- calcul des temps (pour l'entete fits) ---*/
   pseries->jj_stack=pseries->jj[index-1];
   pseries->exptime_stack=pseries->exptime[index-1];

   return(OK_DLL);
}
예제 #5
0
int main()
{
	double /* **U, **Unew,err=0.0,*/ sta = 1.0/8.0, stb=1.0/128.0;
	int sa = 9, sb = 129, i/*,j*/;
	FILE *outs;
	init(&U,sa,sa);
	init(&Unew,sa,sa);
	init(&Ub,sb,sb);
	
	init_cond(&U, sa, sa, sta,sta);
	
	memcpy(&Unew,&U,sizeof(Unew));
	for(i = 0; i<1000 /*&& (err>0.001 || err == 0.0)*/; i++)
	{
		//err = 0.0;
		iteration(&U,&Unew, sa,sa, sta,sta);
		memcpy(&U,&Unew,sizeof(Unew));
	}
	
	outs = fopen("../output/out1.dat", "w");
	output_line(U, sa,sa, sta,sta, outs);
	fclose(outs);
	
	//init_cond(&Ub, sb, sb, stb,stb);
	interpol(&Ub, sb, sb, stb, stb, 	&U, sa-1, sa-1, sta, sta);
	init_cond(&Ub, sb, sb, stb, stb);
	
	outs = fopen("../output/out2.dat", "w");
	output_line(Ub, sb,sb, stb,stb, outs);
	fclose(outs);
	
	freeArr(&Unew, sa);
	//output_line(U, sa,sa, sta,sta);
	//output_line(Ub, sb,sb, stb,stb);
	//freeArr(&U, sa);
	init(&Unew,sb,sb);
	init_cond(&Unew, sb, sb, stb, stb);
	memcpy(&Unew,&Ub,sizeof(Ub));
	//err = 0.0;
	for(i = 0; i<1000 /*&& (err>0.0005 || err == 0.0)*/ ; i++)
	{
		iteration(&Ub,&Unew, sb,sb, stb,stb);
		memcpy(&Ub,&Unew,sizeof(Unew));
	}
	
	outs = fopen("../output/out3.dat", "w");
	output_line(Ub, sb,sb, stb,stb, outs);
	fclose(outs);
	
	
	outs = fopen("../output/out3_mstk.dat", "w");
	opt_mstk_line(Ub, sb,sb, stb,stb, outs);
	fclose(outs);
	//output_line(U, size,size, step,step);

	//printf("%f %f %f\n", step*5, step*5, err);
	return 0;
}
예제 #6
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    ui->setupUi(this);
    setWindowTitle(tr("My Progaramm"));
    QObject::connect(ui->openfile, SIGNAL(clicked()), this, SLOT(open()));
    QObject::connect(ui->table, SIGNAL(clicked()), this, SLOT(colum1()));
    QObject::connect(ui->grafbutton, SIGNAL(clicked()), this, SLOT(graf()));
    QObject::connect(ui->interbutton, SIGNAL(clicked()), this, SLOT(interpol());
}
예제 #7
0
/* The function returns the value nearest to the given time value.  If
   the otional parameter is true then additionally cubic spline
   interpolation is used. */
nr_double_t history::nearest (nr_double_t tval, bool interpolate) {
  if (t != NULL) {
    int l = leftidx ();
    int r = t->getSize () - 1;
    int i = -1;
    nr_double_t diff = NR_MAX;
    sign = true;
    i = seek (tval, l, r, diff, i);
    i = i - l;
    if (interpolate) return interpol (tval, i, sign);
    return values->get (i);
  }
  return 0.0;
}
void time_to_ra_dec(double time_jd, double *ra, double *dec) {
  int i=0;
  double raoffs=0;

  while ((i<swi.num_positions-2) && (swi.position_history[i+1].time<time_jd)) {
    i++;
  }

  if ((swi.position_history[i+1].ra-swi.position_history[i].ra)> 12.0) {
    raoffs=-24.0;
  }
  if ((swi.position_history[i].ra-swi.position_history[i+1].ra)> 12.0) {
    raoffs=24.0;
  }

  *ra=interpol(
        swi.position_history[i].time,
        swi.position_history[i].ra,
        swi.position_history[i+1].time,
        swi.position_history[i+1].ra+raoffs,
        time_jd
      );
  if (*ra<0) {
    *ra+=24;
  } else if (*ra>24) {
    *ra-=24;
  }

  *dec=interpol(
         swi.position_history[i].time,
         swi.position_history[i].dec,
         swi.position_history[i+1].time,
         swi.position_history[i+1].dec,
         time_jd
       );
}
예제 #9
0
int main(){
	puts("Polynomial interpolation ");
	double x[4] = {-3.0, -2.0, 2.0, 3.0};
	double fx[4] = {-5.0, -1.1, 1.9, 4.8};
	double z[4] = {-2.5, 0.0, 1.0, 2.5};
	double pz[4];
	interpol(x, fx, 4, z, pz, 4);
	show(pz, 4);

	puts("The least square method");
	double x1[9] = {-4.0, -3.0, -2.0, -1.5, -0.5, 1.0, 2.0, 3.5, 4.0};
	double y1[9] = {-3.0, -1.0, -2.0, -0.5, 1.0, 0.0, 1.5, 1.0, 2.5};
	double k = 0.0;
	double b = 0.0;
	lesq(x1, y1, 9, &k, &b);
	printf("%f, %f\n", k, b);

	return 0;
}
예제 #10
0
void FWI_PSV(){

/* global variables */
/* ---------------- */

/* forward modelling */
extern int MYID, FDORDER, NX, NY, NT, L, READMOD, QUELLART, RUN_MULTIPLE_SHOTS, TIME_FILT;
extern int LOG, SEISMO, N_STREAMER, FW, NXG, NYG, IENDX, IENDY, NTDTINV, IDXI, IDYI, NXNYI, INV_STF, DTINV;
extern float FC_SPIKE_1, FC_SPIKE_2, FC, FC_START, TIME, DT;
extern char LOG_FILE[STRING_SIZE], MFILE[STRING_SIZE];
extern FILE *FP;

/* gravity modelling/inversion */
extern int GRAVITY, NZGRAV, NGRAVB, GRAV_TYPE, BACK_DENSITY;
extern char GRAV_DATA_OUT[STRING_SIZE], GRAV_DATA_IN[STRING_SIZE], GRAV_STAT_POS[STRING_SIZE], DFILE[STRING_SIZE];
extern float LAM_GRAV, GAMMA_GRAV, LAM_GRAV_GRAD, L2_GRAV_IT1;

/* full waveform inversion */
extern int GRAD_METHOD, NLBFGS, ITERMAX, IDX, IDY, INVMAT1, EPRECOND;
extern int GRAD_FORM, POS[3], QUELLTYPB, MIN_ITER, MODEL_FILTER;
extern float FC_END, PRO, C_vp, C_vs, C_rho;
extern char MISFIT_LOG_FILE[STRING_SIZE], JACOBIAN[STRING_SIZE];
extern char *FILEINP1;

/* local variables */
int ns, nseismograms=0, nt, nd, fdo3, j, i, iter, h, hin, iter_true, SHOTINC, s=0;
int buffsize, ntr=0, ntr_loc=0, ntr_glob=0, nsrc=0, nsrc_loc=0, nsrc_glob=0, ishot, nshots=0, itestshot;

float sum, eps_scale, opteps_vp, opteps_vs, opteps_rho, Vp_avg, Vs_avg, rho_avg, Vs_sum, Vp_sum, rho_sum;
char *buff_addr, ext[10], *fileinp, jac[225], source_signal_file[STRING_SIZE];

double time1, time2, time7, time8, time_av_v_update=0.0, time_av_s_update=0.0, time_av_v_exchange=0.0, time_av_s_exchange=0.0, time_av_timestep=0.0;
	
float L2sum, *L2t;
	
float ** taper_coeff, * epst1, *hc=NULL;
int * DTINV_help;

MPI_Request *req_send, *req_rec;
MPI_Status  *send_statuses, *rec_statuses;

/* Variables for step length calculation */
int step1, step3=0;
float eps_true, tmp;

/* Variables for the L-BFGS method */
float * rho_LBFGS, * alpha_LBFGS, * beta_LBFGS; 
float * y_LBFGS, * s_LBFGS, * q_LBFGS, * r_LBFGS;
int NLBFGS_class, LBFGS_pointer, NLBFGS_vec;

/* Variables for energy weighted gradient */
float ** Ws, **Wr, **We;

/* parameters for FWI-workflow */
int stagemax=0, nstage;

/*vector for abort criterion*/
float * L2_hist=NULL;

/* help variable for MIN_ITER */
int min_iter_help=0;

/* parameters for gravity inversion */
float * gz_mod, * gz_res;
float ** gravpos=NULL, ** rho_grav=NULL, ** rho_grav_ext=NULL;
float ** grad_grav=NULL;
int ngrav=0, nxgrav, nygrav;
float L2_grav, FWImax, GRAVmax, FWImax_all, GRAVmax_all ;
char jac_grav[STRING_SIZE];

FILE *FPL2, *FP_stage, *FP_GRAV, *LAMBDA;

if (MYID == 0){
   time1=MPI_Wtime(); 
   clock();
}

/* open log-file (each PE is using different file) */
/*	fp=stdout; */
sprintf(ext,".%i",MYID);  
strcat(LOG_FILE,ext);

if ((MYID==0) && (LOG==1)) FP=stdout;
else FP=fopen(LOG_FILE,"w");
fprintf(FP," This is the log-file generated by PE %d \n\n",MYID);

/* ----------------------- */
/* define FD grid geometry */
/* ----------------------- */

/* domain decomposition */
initproc();

NT=iround(TIME/DT); /* number of timesteps */

/* output of parameters to log-file or stdout */
if (MYID==0) write_par(FP);

/* NXG, NYG denote size of the entire (global) grid */
NXG=NX;
NYG=NY;

/* In the following, NX and NY denote size of the local grid ! */
NX = IENDX;
NY = IENDY;

NTDTINV=ceil((float)NT/(float)DTINV);		/* round towards next higher integer value */

/* save every IDXI and IDYI spatial point during the forward modelling */
IDXI=1;
IDYI=1;

NXNYI=(NX/IDXI)*(NY/IDYI);
SHOTINC=1;

/* use only every DTINV time sample for the inversion */
DTINV_help=ivector(1,NT);

/* read parameters from workflow-file (stdin) */
FP_stage=fopen(FILEINP1,"r");
if(FP_stage==NULL) {
	if (MYID == 0){
		printf("\n==================================================================\n");
		printf(" Cannot open Denise workflow input file %s \n",FILEINP1);
		printf("\n==================================================================\n\n");
		err(" --- ");
	}
}

/* estimate number of lines in FWI-workflow */
i=0;
stagemax=0;
while ((i=fgetc(FP_stage)) != EOF)
if (i=='\n') ++stagemax;
rewind(FP_stage);
stagemax--;
fclose(FP_stage);

/* define data structures for PSV problem */
struct wavePSV;
struct wavePSV_PML;
struct matPSV;
struct fwiPSV;
struct mpiPSV;
struct seisPSV;
struct seisPSVfwi;
struct acq;

nd = FDORDER/2 + 1;
fdo3 = 2*nd;
buffsize=2.0*2.0*fdo3*(NX +NY)*sizeof(MPI_FLOAT);

/* allocate buffer for buffering messages */
buff_addr=malloc(buffsize);
if (!buff_addr) err("allocation failure for buffer for MPI_Bsend !");
MPI_Buffer_attach(buff_addr,buffsize);

/* allocation for request and status arrays */
req_send=(MPI_Request *)malloc(REQUEST_COUNT*sizeof(MPI_Request));
req_rec=(MPI_Request *)malloc(REQUEST_COUNT*sizeof(MPI_Request));
send_statuses=(MPI_Status *)malloc(REQUEST_COUNT*sizeof(MPI_Status));
rec_statuses=(MPI_Status *)malloc(REQUEST_COUNT*sizeof(MPI_Status));

/* --------- add different modules here ------------------------ */
ns=NT;	/* in a FWI one has to keep all samples of the forward modeled data
	at the receiver positions to calculate the adjoint sources and to do 
	the backpropagation; look at function saveseis_glob.c to see that every
	NDT sample for the forward modeled wavefield is written to su files*/

if (SEISMO){

   acq.recpos=receiver(FP, &ntr, ishot);
   acq.recswitch = ivector(1,ntr);
   acq.recpos_loc = splitrec(acq.recpos,&ntr_loc, ntr, acq.recswitch);
   ntr_glob=ntr;
   ntr=ntr_loc;
   
   if(N_STREAMER>0){
     free_imatrix(acq.recpos,1,3,1,ntr_glob);
     if(ntr>0) free_imatrix(acq.recpos_loc,1,3,1,ntr);
     free_ivector(acq.recswitch,1,ntr_glob);
   }
   
}

if(N_STREAMER==0){

   /* Memory for seismic data */
   alloc_seisPSV(ntr,ns,&seisPSV);

   /* Memory for FWI seismic data */ 
   alloc_seisPSVfwi(ntr,ntr_glob,ns,&seisPSVfwi);

}

/* Memory for full data seismograms */
alloc_seisPSVfull(&seisPSV,ntr_glob);

/* memory allocation for abort criterion*/
L2_hist = vector(1,1000);

/* estimate memory requirement of the variables in megabytes*/
	
switch (SEISMO){
case 1 : /* particle velocities only */
	nseismograms=2;	
	break;	
case 2 : /* pressure only */
	nseismograms=1;	
	break;	
case 3 : /* curl and div only */
	nseismograms=2;		
	break;	
case 4 : /* everything */
	nseismograms=5;		
	break;
}		

/* calculate memory requirements for PSV forward problem */
mem_fwiPSV(nseismograms,ntr,ns,fdo3,nd,buffsize,ntr_glob);

/* Define gradient formulation */
/* GRAD_FORM = 1 - stress-displacement gradients */
/* GRAD_FORM = 2 - stress-velocity gradients for decomposed impedance matrix */
GRAD_FORM = 1;

if(GRAVITY==1 || GRAVITY==2){
  
  if(GRAV_TYPE == 1){
  sprintf(GRAV_DATA_OUT, "./gravity/grav_mod.dat"); /* output file of gravity data */
  sprintf(GRAV_DATA_IN, "./gravity/grav_field.dat");  /* input file of gravity data */
  }
  if(GRAV_TYPE == 2){
  sprintf(GRAV_DATA_OUT, "./gravity/grav_grad_mod.dat"); /* output file of gravity gradient data */
  sprintf(GRAV_DATA_IN, "./gravity/grav_grad_field.dat");  /* input file of gravity gradientdata */
  }
  sprintf(GRAV_STAT_POS, "./gravity/grav_stat.dat"); /* file with station positions for gravity modelling */

  /* size of the extended gravity model */
  nxgrav = NXG + 2*NGRAVB;
  nygrav = NYG + NGRAVB;

}

/* allocate memory for PSV forward problem */
alloc_PSV(&wavePSV,&wavePSV_PML);

/* calculate damping coefficients for CPMLs (PSV problem)*/
if(FW>0){PML_pro(wavePSV_PML.d_x, wavePSV_PML.K_x, wavePSV_PML.alpha_prime_x, wavePSV_PML.a_x, wavePSV_PML.b_x, wavePSV_PML.d_x_half, wavePSV_PML.K_x_half, wavePSV_PML.alpha_prime_x_half, wavePSV_PML.a_x_half, 
                 wavePSV_PML.b_x_half, wavePSV_PML.d_y, wavePSV_PML.K_y, wavePSV_PML.alpha_prime_y, wavePSV_PML.a_y, wavePSV_PML.b_y, wavePSV_PML.d_y_half, wavePSV_PML.K_y_half, wavePSV_PML.alpha_prime_y_half, 
                 wavePSV_PML.a_y_half, wavePSV_PML.b_y_half);
}

/* allocate memory for PSV material parameters */
alloc_matPSV(&matPSV);

/* allocate memory for PSV FWI parameters */
alloc_fwiPSV(&fwiPSV);

/* allocate memory for PSV MPI variables */
alloc_mpiPSV(&mpiPSV);

/* Variables for the l-BFGS method */
if(GRAD_METHOD==2){

  NLBFGS_class = 3;                 /* number of parameter classes */ 
  NLBFGS_vec = NLBFGS_class*NX*NY;  /* length of one LBFGS-parameter class */
  LBFGS_pointer = 1;                /* initiate pointer in the cyclic LBFGS-vectors */
  
  y_LBFGS  =  vector(1,NLBFGS_vec*NLBFGS);
  s_LBFGS  =  vector(1,NLBFGS_vec*NLBFGS);

  q_LBFGS  =  vector(1,NLBFGS_vec);
  r_LBFGS  =  vector(1,NLBFGS_vec);

  rho_LBFGS = vector(1,NLBFGS);
  alpha_LBFGS = vector(1,NLBFGS);
  beta_LBFGS = vector(1,NLBFGS);
  
}

taper_coeff=  matrix(1,NY,1,NX);

/* memory for source position definition */
acq.srcpos1=fmatrix(1,8,1,1);

/* memory of L2 norm */
L2t = vector(1,4);
epst1 = vector(1,3);
	
fprintf(FP," ... memory allocation for PE %d was successfull.\n\n", MYID);

/* Holberg coefficients for FD operators*/
hc = holbergcoeff();

MPI_Barrier(MPI_COMM_WORLD);

/* Reading source positions from SOURCE_FILE */ 	
acq.srcpos=sources(&nsrc);
nsrc_glob=nsrc;


/* create model grids */
if(L){
	if (READMOD) readmod_visc_PSV(matPSV.prho,matPSV.ppi,matPSV.pu,matPSV.ptaus,matPSV.ptaup,matPSV.peta);
		else model(matPSV.prho,matPSV.ppi,matPSV.pu,matPSV.ptaus,matPSV.ptaup,matPSV.peta);
} else{
	if (READMOD) readmod_elastic_PSV(matPSV.prho,matPSV.ppi,matPSV.pu);
    		else model_elastic(matPSV.prho,matPSV.ppi,matPSV.pu);
}

/* check if the FD run will be stable and free of numerical dispersion */
if(L){
	checkfd_ssg_visc(FP,matPSV.prho,matPSV.ppi,matPSV.pu,matPSV.ptaus,matPSV.ptaup,matPSV.peta,hc);
} else{
	checkfd_ssg_elastic(FP,matPSV.prho,matPSV.ppi,matPSV.pu,hc);
}


if(GRAVITY==1 || GRAVITY==2){
 
  /* read station positions */
  MPI_Barrier(MPI_COMM_WORLD);
  gravpos=read_grav_pos(&ngrav);

  /* define model and residual data vector for gz (z-component of the gravity field) */
  gz_mod = vector(1,ngrav);
  gz_res = vector(1,ngrav);

  /* only forward modelling of gravity data */
  if(GRAVITY==1){

    /* global density model */
    rho_grav =  matrix(1,NYG,1,NXG);
    rho_grav_ext =  matrix(1,nygrav,1,nxgrav);

    read_density_glob(rho_grav,1);
    extend_mod(rho_grav,rho_grav_ext,nxgrav,nygrav);
    grav_mod(rho_grav_ext,ngrav,gravpos,gz_mod,nxgrav,nygrav,NZGRAV);

    free_matrix(rho_grav,1,NYG,1,NXG);
    free_matrix(rho_grav_ext,1,nygrav,1,nxgrav);

  }

  if(GRAVITY==2){
    grad_grav =  matrix(1,NY,1,NX);
  }

} 
      
SHOTINC=1;
    
iter_true=1;
/* Begin of FWI-workflow */
for(nstage=1;nstage<=stagemax;nstage++){

/* read workflow input file *.inp */
FP_stage=fopen(FILEINP1,"r");
read_par_inv(FP_stage,nstage,stagemax);
/*fclose(FP_stage);*/

if((EPRECOND==1)||(EPRECOND==3)){
  Ws = matrix(1,NY,1,NX); /* total energy of the source wavefield */
  Wr = matrix(1,NY,1,NX); /* total energy of the receiver wavefield */
  We = matrix(1,NY,1,NX); /* total energy of source and receiver wavefield */
}

FC=FC_END;

iter=1;
/* --------------------------------------
 * Begin of Full Waveform iteration loop
 * -------------------------------------- */
while(iter<=ITERMAX){

if(GRAD_METHOD==2){
  
  /* increase pointer to LBFGS-vector*/
  if(iter>2){
    LBFGS_pointer++;
  }
  
  /* if LBFGS-pointer > NLBFGS -> set LBFGS_pointer=1 */ 
  if(LBFGS_pointer>NLBFGS){LBFGS_pointer=1;}

}

if (MYID==0)
   {
   time2=MPI_Wtime();
   fprintf(FP,"\n\n\n ------------------------------------------------------------------\n");
   fprintf(FP,"\n\n\n                   TDFWI ITERATION %d \t of %d \n",iter,ITERMAX);
   fprintf(FP,"\n\n\n ------------------------------------------------------------------\n");
   }

/* For the calculation of the material parameters between gridpoints
   they have to be averaged. For this, values lying at 0 and NX+1,
   for example, are required on the local grid. These are now copied from the
   neighbouring grids */		
if (L){
	matcopy_PSV(matPSV.prho,matPSV.ppi,matPSV.pu,matPSV.ptaus,matPSV.ptaup);
} else{
	matcopy_elastic_PSV(matPSV.prho,matPSV.ppi,matPSV.pu);
}

MPI_Barrier(MPI_COMM_WORLD);

av_mue(matPSV.pu,matPSV.puipjp,matPSV.prho);
av_rho(matPSV.prho,matPSV.prip,matPSV.prjp);
if (L) av_tau(matPSV.ptaus,matPSV.ptausipjp);


/* Preparing memory variables for update_s (viscoelastic) */
if (L) prepare_update_s_visc_PSV(matPSV.etajm,matPSV.etaip,matPSV.peta,matPSV.fipjp,matPSV.pu,matPSV.puipjp,matPSV.ppi,matPSV.prho,matPSV.ptaus,matPSV.ptaup,matPSV.ptausipjp,matPSV.f,matPSV.g,
		matPSV.bip,matPSV.bjm,matPSV.cip,matPSV.cjm,matPSV.dip,matPSV.d,matPSV.e);


if(iter_true==1){

    for (i=1;i<=NX;i=i+IDX){ 
	for (j=1;j<=NY;j=j+IDY){
	
	if(INVMAT1==1){
	
	  fwiPSV.Vp0[j][i] = matPSV.ppi[j][i];
	  fwiPSV.Vs0[j][i] = matPSV.pu[j][i];
	  fwiPSV.Rho0[j][i] = matPSV.prho[j][i];

        }
	  
                 
		 
	if(INVMAT1==2){
        
	  fwiPSV.Vp0[j][i] = sqrt((matPSV.ppi[j][i]+2.0*matPSV.pu[j][i])*matPSV.prho[j][i]);
	  fwiPSV.Vs0[j][i] = sqrt(matPSV.pu[j][i]*matPSV.prho[j][i]);
	  fwiPSV.Rho0[j][i] = matPSV.prho[j][i];
	
	}
	 
	if(INVMAT1==3){
        
	  fwiPSV.Vp0[j][i] = matPSV.ppi[j][i];
	  fwiPSV.Vs0[j][i] = matPSV.pu[j][i];
	  fwiPSV.Rho0[j][i] = matPSV.prho[j][i];
	
	}  
	
    }
    }

/* ----------------------------- */
/* calculate Covariance matrices */
/* ----------------------------- */

	 Vp_avg = 0.0;
	 Vs_avg = 0.0;
	 rho_avg = 0.0;
	 
        for (i=1;i<=NX;i=i+IDX){
           for (j=1;j<=NY;j=j+IDY){
	  
		 /* calculate average Vp, Vs */
                 Vp_avg+=matPSV.ppi[j][i];
		 Vs_avg+=matPSV.pu[j][i];
		 
		 /* calculate average rho */
		 rho_avg+=matPSV.prho[j][i];
	
           }
        }
		
        /* calculate average Vp, Vs and rho of all CPUs*/
        Vp_sum = 0.0;
        MPI_Allreduce(&Vp_avg,&Vp_sum,1,MPI_FLOAT,MPI_SUM,MPI_COMM_WORLD);
        Vp_avg=Vp_sum;
	
	Vs_sum = 0.0;
        MPI_Allreduce(&Vs_avg,&Vs_sum,1,MPI_FLOAT,MPI_SUM,MPI_COMM_WORLD);
        Vs_avg=Vs_sum;
	
	rho_sum = 0.0;
        MPI_Allreduce(&rho_avg,&rho_sum,1,MPI_FLOAT,MPI_SUM,MPI_COMM_WORLD);
        rho_avg=rho_sum;
	
	Vp_avg /=NXG*NYG; 
	Vs_avg /=NXG*NYG; 
	rho_avg /=NXG*NYG;
	
	if(MYID==0){
           printf("Vp_avg = %.0f \t Vs_avg = %.0f \t rho_avg = %.0f \n ",Vp_avg,Vs_avg,rho_avg);	
	}
	
	C_vp = Vp_avg;
	C_vs = Vs_avg;
	C_rho = rho_avg;


}

/* Open Log File for L2 norm */
if(MYID==0){
  if(iter_true==1){
    FPL2=fopen(MISFIT_LOG_FILE,"w");
  }

  if(iter_true>1){
    FPL2=fopen(MISFIT_LOG_FILE,"a");
  }
}

/* ---------------------------------------------------------------------------------------------------- */
/* --------- Calculate gradient and objective function using the adjoint state method ----------------- */
/* ---------------------------------------------------------------------------------------------------- */

L2sum = grad_obj_psv(&wavePSV, &wavePSV_PML, &matPSV, &fwiPSV, &mpiPSV, &seisPSV, &seisPSVfwi, &acq, hc, iter, nsrc, ns, ntr, ntr_glob, 
nsrc_glob, nsrc_loc, ntr_loc, nstage, We, Ws, Wr, taper_coeff, hin, DTINV_help, req_send, req_rec);

L2t[1]=L2sum;
L2t[4]=L2sum;

if(GRAVITY==2){

  /* save seismic L2-norm of seismic data residuals */
  L2sum = L2t[1];

  /* global density model */
  rho_grav =  matrix(1,NYG,1,NXG);
  rho_grav_ext =  matrix(1,nygrav,1,nxgrav);

  /* model gravity data */
  /* save current density model */
  sprintf(jac_grav,"%s_tmp.rho.%i%i",JACOBIAN,POS[1],POS[2]);
  FP_GRAV=fopen(jac_grav,"wb");

  for (i=1;i<=NX;i=i+IDX){
      for (j=1;j<=NY;j=j+IDY){
          fwrite(&matPSV.prho[j][i],sizeof(float),1,FP_GRAV);
      }
  }
	
  fclose(FP_GRAV);

  MPI_Barrier(MPI_COMM_WORLD);
          
  /* merge model file */ 
  sprintf(jac_grav,"%s_tmp.rho",JACOBIAN);
  if (MYID==0) mergemod(jac_grav,3);
  
  MPI_Barrier(MPI_COMM_WORLD);
  
  /* gravity forward modelling */
  read_density_glob(rho_grav,2);
  extend_mod(rho_grav,rho_grav_ext,nxgrav,nygrav);
  grav_mod(rho_grav_ext,ngrav,gravpos,gz_mod,nxgrav,nygrav,NZGRAV);

  /* calculate gravity data residuals */
  L2_grav=calc_res_grav(ngrav,gz_mod,gz_res);

  /* calculate lambda 1 */
  if(iter==1){
  	LAM_GRAV = GAMMA_GRAV * (L2sum/L2_grav);
  }

  /* add gravity penalty term to the seismic objective function */
  L2t[1]+=LAM_GRAV * L2_grav;
  L2t[4]+=LAM_GRAV * L2_grav;

  /* calculate gravity gradient */
  for (i=1;i<=NX;i=i+IDX){
       for (j=1;j<=NY;j=j+IDY){
           grad_grav[j][i]=0.0;
       }
  }
  grav_grad(ngrav,gravpos,grad_grav,gz_res);
  
  MPI_Barrier(MPI_COMM_WORLD);        

  /* merge model file */
  sprintf(jac,"%s_grav",JACOBIAN);          
  if (MYID==0) mergemod(jac,3); 

  /* free memory */
  free_matrix(rho_grav,1,NYG,1,NXG);
  free_matrix(rho_grav_ext,1,nygrav,1,nxgrav);
  

}

/* Interpolate missing spatial gradient values in case IDXI > 1 || IDXY > 1 */
/* ------------------------------------------------------------------------ */

if((IDXI>1)||(IDYI>1)){

   interpol(IDXI,IDYI,fwiPSV.waveconv,1);
   interpol(IDXI,IDYI,fwiPSV.waveconv_u,1);
   interpol(IDXI,IDYI,fwiPSV.waveconv_rho,1);

}

/* Preconditioning of gradients after shot summation */
precond_PSV(&fwiPSV,&acq,nsrc,ntr_glob,taper_coeff,FP_GRAV);

/* Add gravity gradient to FWI density gradient */
/* -------------------------------------------- */
	
   if(GRAVITY==2){
		 		 
     /* calculate maximum values of waveconv_rho and grad_grav */
     FWImax = 0.0;
     GRAVmax = 0.0;
	
     for (i=1;i<=NX;i++){
        for (j=1;j<=NY;j++){
		
	    if(fabs(fwiPSV.waveconv_rho[j][i])>FWImax){FWImax=fabs(fwiPSV.waveconv_rho[j][i]);}
	    if(fabs(grad_grav[j][i])>GRAVmax){GRAVmax=fabs(grad_grav[j][i]);}
		
        }
     }
	
     MPI_Allreduce(&FWImax,&FWImax_all,  1,MPI_FLOAT,MPI_MAX,MPI_COMM_WORLD);
     MPI_Allreduce(&GRAVmax,&GRAVmax_all,1,MPI_FLOAT,MPI_MAX,MPI_COMM_WORLD);
		
    /* calculate lambda 2, normalized with respect to the maximum gradients */
	if(iter==1){
		LAM_GRAV_GRAD = GAMMA_GRAV * (FWImax_all/GRAVmax_all);
	} 
		 
     /* add gravity gradient to seismic gradient with respect to the density */
     for (i=1;i<=NX;i++){
        for (j=1;j<=NY;j++){
			
            fwiPSV.waveconv_rho[j][i] += LAM_GRAV_GRAD * grad_grav[j][i];
				
        }
     }
		
   }

/* Use preconditioned conjugate gradient optimization method */
if(GRAD_METHOD==1){
  PCG(fwiPSV.waveconv, taper_coeff, nsrc, acq.srcpos, acq.recpos, ntr_glob, iter, fwiPSV.gradp, fwiPSV.waveconv_u, fwiPSV.gradp_u, fwiPSV.waveconv_rho, fwiPSV.gradp_rho);
}

/* Use l-BFGS optimization */
if(GRAD_METHOD==2){ 

    /* store models and gradients in l-BFGS vectors */
    store_LBFGS_PSV(taper_coeff, nsrc, acq.srcpos, acq.recpos, ntr_glob, iter, fwiPSV.waveconv, fwiPSV.gradp, fwiPSV.waveconv_u, fwiPSV.gradp_u, fwiPSV.waveconv_rho, 
		    fwiPSV.gradp_rho, y_LBFGS, s_LBFGS, q_LBFGS, matPSV.ppi, matPSV.pu, matPSV.prho, NXNYI, LBFGS_pointer, NLBFGS, NLBFGS_vec);

    /* apply l-BFGS optimization */
    LBFGS(iter, y_LBFGS, s_LBFGS, rho_LBFGS, alpha_LBFGS, q_LBFGS, r_LBFGS, beta_LBFGS, LBFGS_pointer, NLBFGS, NLBFGS_vec);

    /* extract gradients and save old models/gradients for next l-BFGS iteration */
    extract_LBFGS_PSV(iter, fwiPSV.waveconv, fwiPSV.gradp, fwiPSV.waveconv_u, fwiPSV.gradp_u, fwiPSV.waveconv_rho, fwiPSV.gradp_rho, matPSV.ppi, matPSV.pu, matPSV.prho, r_LBFGS);

}

opteps_vp=0.0;
opteps_vs=0.0;
opteps_rho=0.0;

/* ============================================================================================================================*/
/* =============================================== test loop L2 ===============================================================*/
/* ============================================================================================================================*/

/* set min_iter_help to initial global value of MIN_ITER */
if(iter==1){min_iter_help=MIN_ITER;}

/* Estimate optimum step length ... */

/* ... by line search (parabolic fitting) */
eps_scale = step_length_est_psv(&wavePSV,&wavePSV_PML,&matPSV,&fwiPSV,&mpiPSV,&seisPSV,&seisPSVfwi,&acq,hc,iter,nsrc,ns,ntr,ntr_glob,epst1,L2t,nsrc_glob,nsrc_loc,&step1,&step3,nxgrav,nygrav,ngrav,gravpos,gz_mod,NZGRAV,
                                ntr_loc,Ws,Wr,hin,DTINV_help,req_send,req_rec);

/* no model update due to steplength estimation failed or update with the smallest steplength if the number of iteration is smaller than the minimum number of iteration per
frequency MIN_ITER */
if((iter>min_iter_help)&&(step1==0)){ 
	eps_scale=0.0;
	opteps_vp=0.0;
}
else{
	opteps_vp=eps_scale;
}

/* write log-parameter files */
if(MYID==0){
printf("MYID = %d \t opteps_vp = %e \t opteps_vs = %e \t opteps_rho = %e \n",MYID,opteps_vp,opteps_vs,opteps_rho);
printf("MYID = %d \t L2t[1] = %e \t L2t[2] = %e \t L2t[3] = %e \t L2t[4] = %e \n",MYID,L2t[1],L2t[2],L2t[3],L2t[4]);
printf("MYID = %d \t epst1[1] = %e \t epst1[2] = %e \t epst1[3] = %e \n",MYID,epst1[1],epst1[2],epst1[3]);

/*output of log file for combined inversion*/
if(iter_true==1){
    LAMBDA = fopen("gravity/lambda.dat","w");
}
if(iter_true>1){
    LAMBDA = fopen("gravity/lambda.dat","a");
}
fprintf(LAMBDA,"%d \t %d \t %e \t %e \t %e \t %e \t %e \t %e \t %e \n",nstage,iter,LAM_GRAV,L2sum,L2_grav,L2t[4],LAM_GRAV_GRAD,FWImax_all,GRAVmax_all);
fclose(LAMBDA);

}

if(MYID==0){
if (TIME_FILT==0){
	fprintf(FPL2,"%e \t %e \t %e \t %e \t %e \t %e \t %e \t %e \t %d \n",opteps_vp,epst1[1],epst1[2],epst1[3],L2t[1],L2t[2],L2t[3],L2t[4],nstage);}
else{
	fprintf(FPL2,"%e \t %e \t %e \t %e \t %e \t %e \t %e \t %e \t %f \t %f \t %d \n",opteps_vp,epst1[1],epst1[2],epst1[3],L2t[1],L2t[2],L2t[3],L2t[4],FC_START,FC,nstage);}}


/* saving history of final L2*/
L2_hist[iter]=L2t[4];
s=0;


/* calculate optimal change in the material parameters */
eps_true=calc_mat_change_test_PSV(fwiPSV.waveconv,fwiPSV.waveconv_rho,fwiPSV.waveconv_u,fwiPSV.prho_old,matPSV.prho,fwiPSV.ppi_old,matPSV.ppi,fwiPSV.pu_old,matPSV.pu,iter,1,eps_scale,0);

if (MODEL_FILTER){
/* smoothing the velocity models vp and vs */
smooth_model(matPSV.ppi,matPSV.pu,matPSV.prho,iter);
}

if(MYID==0){	
/*	fprintf(FPL2,"=============================================================\n");
	fprintf(FPL2,"=============================================================\n");
	fprintf(FPL2,"STATISTICS FOR ITERATION STEP %d \n",iter);
	fprintf(FPL2,"=============================================================\n");
	fprintf(FPL2,"=============================================================\n");*/
/*	fprintf(FPL2,"Low-pass filter at %e Hz\n",freq);
	fprintf(FPL2,"----------------------------------------------\n");
*/	/*fprintf(FPL2,"L2 at iteration step n = %e \n",L2);*/
/*        fprintf(FPL2,"%e \t %e \t %e \t %e \t %e \t %e \t %e \t %e \n",EPSILON,EPSILON_u,EPSILON_rho,L2t[4],betaVp,betaVs,betarho,sqrt(C_vp));*/

	/*fprintf(FPL2,"----------------------------------------------\n");*/
/*	fprintf(FPL2,"=============================================================\n");
	fprintf(FPL2,"=============================================================\n\n\n");*/
}

if(MYID==0){
  fclose(FPL2);
}

if (iter>min_iter_help){

float diff=0.0, pro=PRO;

/* calculating differnce of the actual L2 and before two iterations, dividing with L2_hist[iter-2] provide changing in procent*/
diff=fabs((L2_hist[iter-2]-L2_hist[iter])/L2_hist[iter-2]);
	
	if((diff<=pro)||(step3==1)){
        
        	/* output of the model at the end of given corner frequency */
        	model_freq_out_PSV(matPSV.ppi,matPSV.prho,matPSV.pu,nstage,FC);
		s=1;
		min_iter_help=0;
		min_iter_help=iter+MIN_ITER;
		iter=0;

        	if(GRAD_METHOD==2){
	  		zero_LBFGS(NLBFGS, NLBFGS_vec, y_LBFGS, s_LBFGS, q_LBFGS, r_LBFGS, alpha_LBFGS, beta_LBFGS, rho_LBFGS);
          		LBFGS_pointer = 1;  
		}

        	if(MYID==0){
			if(step3==1){
			        printf("\n Steplength estimation failed step3=%d \n Changing to next FWI stage \n",step3);
			}
			else{
  				printf("\n Reached the abort criterion of pro=%e and diff=%e \n Changing to next FWI stage \n",pro,diff);
			}
	
		}
		break;
	}
}

iter++;
iter_true++;

/* ====================================== */
} /* end of fullwaveform iteration loop*/
/* ====================================== */

} /* End of FWI-workflow loop */

/* deallocate memory for PSV forward problem */
dealloc_PSV(&wavePSV,&wavePSV_PML);

/* deallocation of memory */
free_matrix(fwiPSV.Vp0,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.Vs0,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.Rho0,-nd+1,NY+nd,-nd+1,NX+nd);

free_matrix(matPSV.prho,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.prho_old,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(matPSV.prip,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(matPSV.prjp,-nd+1,NY+nd,-nd+1,NX+nd);

free_matrix(matPSV.ppi,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.ppi_old,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(matPSV.pu,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.pu_old,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(matPSV.puipjp,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_lam,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_shot,-nd+1,NY+nd,-nd+1,NX+nd);

free_matrix(mpiPSV.bufferlef_to_rig,1,NY,1,fdo3);
free_matrix(mpiPSV.bufferrig_to_lef,1,NY,1,fdo3);
free_matrix(mpiPSV.buffertop_to_bot,1,NX,1,fdo3);
free_matrix(mpiPSV.bufferbot_to_top,1,NX,1,fdo3);

free_vector(hc,0,6);

free_matrix(fwiPSV.gradg,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.gradp,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.gradg_rho,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.gradp_rho,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_rho,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_rho_s,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_rho_shot,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.gradg_u,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.gradp_u,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_u,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_mu,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_u_shot,-nd+1,NY+nd,-nd+1,NX+nd);

free_vector(fwiPSV.forward_prop_x,1,NY*NX*NT);
free_vector(fwiPSV.forward_prop_y,1,NY*NX*NT);
free_vector(fwiPSV.forward_prop_rho_x,1,NY*NX*NT);
free_vector(fwiPSV.forward_prop_rho_y,1,NY*NX*NT);
free_vector(fwiPSV.forward_prop_u,1,NY*NX*NT);

if (nsrc_loc>0){	
	free_matrix(acq.signals,1,nsrc_loc,1,NT);
	free_matrix(acq.srcpos_loc,1,8,1,nsrc_loc);
	free_matrix(acq.srcpos_loc_back,1,6,1,nsrc_loc);
}		   

 /* free memory for global source positions */
 free_matrix(acq.srcpos,1,8,1,nsrc);

 /* free memory for source position definition */
 free_matrix(acq.srcpos1,1,8,1,1);
 
 /* free memory for abort criterion */
 free_vector(L2_hist,1,1000);
 		
 free_vector(L2t,1,4);
 free_vector(epst1,1,3);

 if(N_STREAMER==0){

    if (SEISMO) free_imatrix(acq.recpos,1,3,1,ntr_glob);

    if ((ntr>0) && (SEISMO)){

            free_imatrix(acq.recpos_loc,1,3,1,ntr);
            acq.recpos_loc = NULL;
 
            switch (SEISMO){
            case 1 : /* particle velocities only */
                    free_matrix(seisPSV.sectionvx,1,ntr,1,ns);
                    free_matrix(seisPSV.sectionvy,1,ntr,1,ns);
                    seisPSV.sectionvx=NULL;
                    seisPSV.sectionvy=NULL;
                    break;
             case 2 : /* pressure only */
                    free_matrix(seisPSV.sectionp,1,ntr,1,ns);
                    break;
             case 3 : /* curl and div only */
                    free_matrix(seisPSV.sectioncurl,1,ntr,1,ns);
                    free_matrix(seisPSV.sectiondiv,1,ntr,1,ns);
                    break;
             case 4 : /* everything */
                    free_matrix(seisPSV.sectionvx,1,ntr,1,ns);
                    free_matrix(seisPSV.sectionvy,1,ntr,1,ns);
                    free_matrix(seisPSV.sectionp,1,ntr,1,ns);
                    free_matrix(seisPSV.sectioncurl,1,ntr,1,ns);
                    free_matrix(seisPSV.sectiondiv,1,ntr,1,ns);
                    break;

             }

    }

    free_matrix(seisPSVfwi.sectionread,1,ntr_glob,1,ns);
    free_ivector(acq.recswitch,1,ntr);
    
    if((QUELLTYPB==1)||(QUELLTYPB==3)||(QUELLTYPB==5)||(QUELLTYPB==7)){
       free_matrix(seisPSVfwi.sectionvxdata,1,ntr,1,ns);
       free_matrix(seisPSVfwi.sectionvxdiff,1,ntr,1,ns);
       free_matrix(seisPSVfwi.sectionvxdiffold,1,ntr,1,ns);
    }

    if((QUELLTYPB==1)||(QUELLTYPB==2)||(QUELLTYPB==6)||(QUELLTYPB==7)){    
       free_matrix(seisPSVfwi.sectionvydata,1,ntr,1,ns);
       free_matrix(seisPSVfwi.sectionvydiff,1,ntr,1,ns);
       free_matrix(seisPSVfwi.sectionvydiffold,1,ntr,1,ns);
    }
    
    if(QUELLTYPB>=4){    
       free_matrix(seisPSVfwi.sectionpdata,1,ntr,1,ns);
       free_matrix(seisPSVfwi.sectionpdiff,1,ntr,1,ns);
       free_matrix(seisPSVfwi.sectionpdiffold,1,ntr,1,ns);
    }
    
 }

 if(SEISMO){
  free_matrix(seisPSV.fulldata,1,ntr_glob,1,NT); 
 }

 if(SEISMO==1){
  free_matrix(seisPSV.fulldata_vx,1,ntr_glob,1,NT);
  free_matrix(seisPSV.fulldata_vy,1,ntr_glob,1,NT);
 }

 if(SEISMO==2){
  free_matrix(seisPSV.fulldata_p,1,ntr_glob,1,NT);
 } 
 
 if(SEISMO==3){
  free_matrix(seisPSV.fulldata_curl,1,ntr_glob,1,NT);
  free_matrix(seisPSV.fulldata_div,1,ntr_glob,1,NT);
 }

 if(SEISMO==4){
  free_matrix(seisPSV.fulldata_vx,1,ntr_glob,1,NT);
  free_matrix(seisPSV.fulldata_vy,1,ntr_glob,1,NT);
  free_matrix(seisPSV.fulldata_p,1,ntr_glob,1,NT); 
  free_matrix(seisPSV.fulldata_curl,1,ntr_glob,1,NT);
  free_matrix(seisPSV.fulldata_div,1,ntr_glob,1,NT);
 }

 free_ivector(DTINV_help,1,NT);
 
 /* free memory for viscoelastic modeling variables */
 if (L) {
		free_matrix(matPSV.ptaus,-nd+1,NY+nd,-nd+1,NX+nd);
		free_matrix(matPSV.ptausipjp,-nd+1,NY+nd,-nd+1,NX+nd);
		free_matrix(matPSV.ptaup,-nd+1,NY+nd,-nd+1,NX+nd);
		free_vector(matPSV.peta,1,L);
		free_vector(matPSV.etaip,1,L);
		free_vector(matPSV.etajm,1,L);
		free_vector(matPSV.bip,1,L);
		free_vector(matPSV.bjm,1,L);
		free_vector(matPSV.cip,1,L);
		free_vector(matPSV.cjm,1,L);
		free_matrix(matPSV.f,-nd+1,NY+nd,-nd+1,NX+nd);
		free_matrix(matPSV.g,-nd+1,NY+nd,-nd+1,NX+nd);
		free_matrix(matPSV.fipjp,-nd+1,NY+nd,-nd+1,NX+nd);
		free_f3tensor(matPSV.dip,-nd+1,NY+nd,-nd+1,NX+nd,1,L);
		free_f3tensor(matPSV.d,-nd+1,NY+nd,-nd+1,NX+nd,1,L);
		free_f3tensor(matPSV.e,-nd+1,NY+nd,-nd+1,NX+nd,1,L);
}

if(GRAVITY){

  free_matrix(gravpos,1,2,1,ngrav);
  free_vector(gz_mod,1,ngrav);
  free_vector(gz_res,1,ngrav);

  if(GRAVITY==2){
    free_matrix(grad_grav,1,NY,1,NX);
  }

}
 
/* de-allocate buffer for messages */
MPI_Buffer_detach(buff_addr,&buffsize);

MPI_Barrier(MPI_COMM_WORLD);

if (MYID==0){
	fprintf(FP,"\n **Info from main (written by PE %d): \n",MYID);
	fprintf(FP," CPU time of program per PE: %li seconds.\n",clock()/CLOCKS_PER_SEC);
	time8=MPI_Wtime();
	fprintf(FP," Total real time of program: %4.2f seconds.\n",time8-time1);
	time_av_v_update=time_av_v_update/(double)NT;
	time_av_s_update=time_av_s_update/(double)NT;
	time_av_v_exchange=time_av_v_exchange/(double)NT;
	time_av_s_exchange=time_av_s_exchange/(double)NT;
	time_av_timestep=time_av_timestep/(double)NT;
	/* fprintf(FP," Average times for \n");
	fprintf(FP," velocity update:  \t %5.3f seconds  \n",time_av_v_update);
	fprintf(FP," stress update:  \t %5.3f seconds  \n",time_av_s_update);
	fprintf(FP," velocity exchange:  \t %5.3f seconds  \n",time_av_v_exchange);
	fprintf(FP," stress exchange:  \t %5.3f seconds  \n",time_av_s_exchange);
	fprintf(FP," timestep:  \t %5.3f seconds  \n",time_av_timestep);*/
		
}

fclose(FP);


}
예제 #11
0
파일: aprstat.c 프로젝트: SQ6NTI/dxlAPRS
extern void aprstat_althist(maptool_pIMAGE * img, aprsdecode_pOPHIST op,
                char * test, float * way, unsigned long * beacons,
                unsigned long * msgs, unsigned long * acks,
                unsigned long * rejs)
{
   char h[256];
   char s[256];
   float maxalt;
   float minalt;
   float alt[5760];
   float hdiv;
   float wdiv;
   unsigned long markx1;
   unsigned long markx;
   unsigned long xc;
   unsigned long sc;
   unsigned long x;
   unsigned long Maxx;
   struct aprsdecode_DAT dat;
   float waysum;
   long markalt;
   size_t tmp[2];
   unsigned long tmp0;
   *way = 0.0f;
   *beacons = 0UL;
   *msgs = 0UL;
   *acks = 0UL;
   *rejs = 0UL;
   if (op==0 || op->frames==0) {
      *test = 0;
      return;
   }
   Maxx = dynmaxx(8UL, 400UL, 720UL);
   decodealt(way, beacons, wdiv, rejs, acks, msgs, &dat, alt, &waysum, op,
                &markalt, &markx1, &markx, 0);
   if (waysum<0.05f) {
      *test = 0; /* no altitudes or km */
      return;
   }
   if (*test) return;
   X2C_DYNALLOCATE((char **)img,sizeof(struct maptool_PIX),
                (tmp[0] = Maxx+16UL,tmp[1] = 136U,tmp),2u);
   useri_debugmem.screens += (*img)->Len1*(*img)->Size1;
   if (*img==0) {
      osi_WrStrLn("error image alloc", 18ul);
      return;
   }
   maptool_clr(*img);
   wdiv = X2C_DIVR((float)(Maxx*8UL-1UL),waysum);
   decodealt(way, beacons, wdiv, rejs, acks, msgs, &dat, alt, &waysum, op,
                &markalt, &markx1, &markx, 1);
   interpol(alt);
   norm(&hdiv, alt, &maxalt, &minalt);
   /*
   FOR x:=0 TO HIGH(alt) DO
    IF alt[x]>=0.0 THEN WrFixed(alt[x], 3,11) ELSE WrStr(".") END;
   END;
    WrStrLn("");
   */
   /*sc:=VAL(CARDINAL, maxalt-minalt) DIV sfact(FLOAT(maxalt-minalt)); */
   sc = sfact(maxalt-minalt);
   strncpy(s,"  ",256u);
   aprsstr_Append(s, 256ul, op->call, 9ul);
   aprsstr_Append(s, 256ul, " dist=", 7ul);
   aprsstr_FixToStr(waysum, 2UL, h, 256ul);
   aprsstr_Append(s, 256ul, h, 256ul);
   aprsstr_Append(s, 256ul, "km min=", 8ul);
   aprsstr_IntToStr((long)X2C_TRUNCI(minalt,X2C_min_longint,X2C_max_longint),
                 1UL, h, 256ul);
   aprsstr_Append(s, 256ul, h, 256ul);
   aprsstr_Append(s, 256ul, "m max=", 7ul);
   aprsstr_IntToStr((long)X2C_TRUNCI(maxalt,X2C_min_longint,X2C_max_longint),
                 1UL, h, 256ul);
   aprsstr_Append(s, 256ul, h, 256ul);
   if (markalt>X2C_min_longint) {
      aprsstr_Append(s, 256ul, "m curs=", 8ul);
      aprsstr_IntToStr(markalt, 1UL, h, 256ul);
      aprsstr_Append(s, 256ul, h, 256ul);
   }
   aprsstr_Append(s, 256ul, "m (NN)", 7ul);
   paper(img, minalt, maxalt, sc, 8UL, Maxx, 120UL, s, 256ul);
   tmp0 = Maxx+8UL;
   x = 5UL;
   if (x<=tmp0) for (;; x++) {
      setpix(*img, (long)x, 8L, 200L, 1000L, 200L);
      if (x==tmp0) break;
   } /* end for */
   strncpy(h,"km",256u);
   if (waysum<5.0f) {
      waysum = waysum*1000.0f;
      strncpy(h,"m",256u);
   }
   sc = sfact(waysum);
   hdiv = X2C_DIVR((float)sc*(float)Maxx,waysum);
   wdiv = 0.0f;
   xc = 0UL;
   do {
      for (x = 5UL; x<=7UL; x++) {
         setpix(*img, (long)(aprsdecode_trunc(wdiv)+8UL), (long)x, 200L,
                1000L, 200L);
      } /* end for */
      if (xc>0UL && aprsdecode_trunc(wdiv)<Maxx-10UL) {
         num(*img, (long)((aprsdecode_trunc(wdiv)+8UL)-6UL), 8L, (long)xc, h,
                 256ul);
         h[0U] = 0;
      }
      xc += sc;
      wdiv = wdiv+hdiv;
   } while (aprsdecode_trunc(wdiv)<=Maxx);
   if (markx>0UL) {
      for (x = 8UL; x<=128UL; x++) {
         setpix(*img, (long)(markx+8UL), (long)x, 50L, 400L, 500L);
      } /* end for */
   }
   tmp0 = Maxx*8UL-1UL;
   x = 0UL;
   if (x<=tmp0) for (;; x++) {
      /* draw graph */
      addpix(*img, (float)x*0.125f+8.0f, alt[x]+8.0f, 62UL, 62UL, 87UL);
      if (x==tmp0) break;
   } /* end for */
} /* end althist() */
예제 #12
0
void RTM_PSV(){

/* global variables */
/* ---------------- */

/* forward modelling */
extern int MYID, FDORDER, NX, NY, NT, L, READMOD, QUELLART, RUN_MULTIPLE_SHOTS, TIME_FILT;
extern int LOG, SEISMO, N_STREAMER, FW, NXG, NYG, IENDX, IENDY, NTDTINV, IDXI, IDYI, NXNYI, INV_STF, DTINV;
extern float FC_SPIKE_1, FC_SPIKE_2, FC, FC_START, TIME, DT;
extern char LOG_FILE[STRING_SIZE], MFILE[STRING_SIZE];
extern FILE *FP;

/* gravity modelling/inversion */
extern int GRAVITY, NZGRAV, NGRAVB, GRAV_TYPE, BACK_DENSITY;
extern char GRAV_DATA_OUT[STRING_SIZE], GRAV_DATA_IN[STRING_SIZE], GRAV_STAT_POS[STRING_SIZE], DFILE[STRING_SIZE];
extern float LAM_GRAV, GAMMA_GRAV, LAM_GRAV_GRAD, L2_GRAV_IT1;

/* full waveform inversion */
extern int GRAD_METHOD, NLBFGS, ITERMAX, IDX, IDY, INVMAT1, EPRECOND;
extern int GRAD_FORM, POS[3], QUELLTYPB, MIN_ITER, MODEL_FILTER;
extern float FC_END, PRO, C_vp, C_vs, C_rho;
extern char MISFIT_LOG_FILE[STRING_SIZE], JACOBIAN[STRING_SIZE];
extern char *FILEINP1;

/* local variables */
int ns, nseismograms=0, nt, nd, fdo3, j, i, iter, h, hin, iter_true, SHOTINC, s=0;
int buffsize, ntr=0, ntr_loc=0, ntr_glob=0, nsrc=0, nsrc_loc=0, nsrc_glob=0, ishot, nshots=0, itestshot;

float sum, eps_scale, opteps_vp, opteps_vs, opteps_rho, Vp_avg, Vs_avg, rho_avg, Vs_sum, Vp_sum, rho_sum;
char *buff_addr, ext[10], *fileinp, jac[225], source_signal_file[STRING_SIZE];

double time1, time2, time7, time8, time_av_v_update=0.0, time_av_s_update=0.0, time_av_v_exchange=0.0, time_av_s_exchange=0.0, time_av_timestep=0.0;
	
float L2sum, *L2t;
	
float ** taper_coeff, * epst1, *hc=NULL;
int * DTINV_help;

MPI_Request *req_send, *req_rec;
MPI_Status  *send_statuses, *rec_statuses;

/* Variables for step length calculation */
int step1, step3=0;
float eps_true, tmp;

/* Variables for the L-BFGS method */
float * rho_LBFGS, * alpha_LBFGS, * beta_LBFGS; 
float * y_LBFGS, * s_LBFGS, * q_LBFGS, * r_LBFGS;
int NLBFGS_class, LBFGS_pointer, NLBFGS_vec;

/* Variables for energy weighted gradient */
float ** Ws, **Wr, **We;

/* parameters for FWI-workflow */
int stagemax=0, nstage;

/* help variable for MIN_ITER */
int min_iter_help=0;

/* parameters for gravity inversion */
char jac_grav[STRING_SIZE];

FILE *FP_stage, *FP_GRAV;

if (MYID == 0){
   time1=MPI_Wtime(); 
   clock();
}

/* open log-file (each PE is using different file) */
/*	fp=stdout; */
sprintf(ext,".%i",MYID);  
strcat(LOG_FILE,ext);

if ((MYID==0) && (LOG==1)) FP=stdout;
else FP=fopen(LOG_FILE,"w");
fprintf(FP," This is the log-file generated by PE %d \n\n",MYID);

/* ----------------------- */
/* define FD grid geometry */
/* ----------------------- */

/* domain decomposition */
initproc();

NT=iround(TIME/DT); /* number of timesteps */

/* output of parameters to log-file or stdout */
if (MYID==0) write_par(FP);

/* NXG, NYG denote size of the entire (global) grid */
NXG=NX;
NYG=NY;

/* In the following, NX and NY denote size of the local grid ! */
NX = IENDX;
NY = IENDY;

NTDTINV=ceil((float)NT/(float)DTINV);		/* round towards next higher integer value */

/* save every IDXI and IDYI spatial point during the forward modelling */
IDXI=1;
IDYI=1;

NXNYI=(NX/IDXI)*(NY/IDYI);
SHOTINC=1;

/* use only every DTINV time sample for the inversion */
DTINV_help=ivector(1,NT);

/* Check if RTM workflow-file is defined (stdin) */
FP_stage=fopen(FILEINP1,"r");
if(FP_stage==NULL) {
	if (MYID == 0){
		printf("\n==================================================================\n");
		printf(" Cannot open Denise workflow input file %s \n",FILEINP1);
		printf("\n==================================================================\n\n");
		err(" --- ");
	}
}

fclose(FP_stage);

/* define data structures for PSV problem */
struct wavePSV;
struct wavePSV_PML;
struct matPSV;
struct fwiPSV;
struct mpiPSV;
struct seisPSV;
struct seisPSVfwi;
struct acq;

nd = FDORDER/2 + 1;
fdo3 = 2*nd;
buffsize=2.0*2.0*fdo3*(NX +NY)*sizeof(MPI_FLOAT);

/* allocate buffer for buffering messages */
buff_addr=malloc(buffsize);
if (!buff_addr) err("allocation failure for buffer for MPI_Bsend !");
MPI_Buffer_attach(buff_addr,buffsize);

/* allocation for request and status arrays */
req_send=(MPI_Request *)malloc(REQUEST_COUNT*sizeof(MPI_Request));
req_rec=(MPI_Request *)malloc(REQUEST_COUNT*sizeof(MPI_Request));
send_statuses=(MPI_Status *)malloc(REQUEST_COUNT*sizeof(MPI_Status));
rec_statuses=(MPI_Status *)malloc(REQUEST_COUNT*sizeof(MPI_Status));

/* --------- add different modules here ------------------------ */
ns=NT;	/* in a FWI one has to keep all samples of the forward modeled data
	at the receiver positions to calculate the adjoint sources and to do 
	the backpropagation; look at function saveseis_glob.c to see that every
	NDT sample for the forward modeled wavefield is written to su files*/

if (SEISMO){

   acq.recpos=receiver(FP, &ntr, ishot);
   acq.recswitch = ivector(1,ntr);
   acq.recpos_loc = splitrec(acq.recpos,&ntr_loc, ntr, acq.recswitch);
   ntr_glob=ntr;
   ntr=ntr_loc;
   
   if(N_STREAMER>0){
     free_imatrix(acq.recpos,1,3,1,ntr_glob);
     if(ntr>0) free_imatrix(acq.recpos_loc,1,3,1,ntr);
     free_ivector(acq.recswitch,1,ntr_glob);
   }
   
}

if(N_STREAMER==0){

   /* Memory for seismic data */
   alloc_seisPSV(ntr,ns,&seisPSV);

   /* Memory for FWI seismic data */ 
   alloc_seisPSVfwi(ntr,ntr_glob,ns,&seisPSVfwi);

}

/* Memory for full data seismograms */
alloc_seisPSVfull(&seisPSV,ntr_glob);

/* estimate memory requirement of the variables in megabytes*/
	
switch (SEISMO){
case 1 : /* particle velocities only */
	nseismograms=2;	
	break;	
case 2 : /* pressure only */
	nseismograms=1;	
	break;	
case 3 : /* curl and div only */
	nseismograms=2;		
	break;	
case 4 : /* everything */
	nseismograms=5;		
	break;
}		

/* calculate memory requirements for PSV forward problem */
mem_fwiPSV(nseismograms,ntr,ns,fdo3,nd,buffsize,ntr_glob);

/* Define gradient formulation */
/* GRAD_FORM = 1 - stress-displacement gradients */
/* GRAD_FORM = 2 - stress-velocity gradients for decomposed impedance matrix */
GRAD_FORM = 1;

/* allocate memory for PSV forward problem */
alloc_PSV(&wavePSV,&wavePSV_PML);

/* calculate damping coefficients for CPMLs (PSV problem)*/
if(FW>0){PML_pro(wavePSV_PML.d_x, wavePSV_PML.K_x, wavePSV_PML.alpha_prime_x, wavePSV_PML.a_x, wavePSV_PML.b_x, wavePSV_PML.d_x_half, wavePSV_PML.K_x_half, wavePSV_PML.alpha_prime_x_half, wavePSV_PML.a_x_half, 
                 wavePSV_PML.b_x_half, wavePSV_PML.d_y, wavePSV_PML.K_y, wavePSV_PML.alpha_prime_y, wavePSV_PML.a_y, wavePSV_PML.b_y, wavePSV_PML.d_y_half, wavePSV_PML.K_y_half, wavePSV_PML.alpha_prime_y_half, 
                 wavePSV_PML.a_y_half, wavePSV_PML.b_y_half);
}

/* allocate memory for PSV material parameters */
alloc_matPSV(&matPSV);

/* allocate memory for PSV FWI parameters */
alloc_fwiPSV(&fwiPSV);

/* allocate memory for PSV MPI variables */
alloc_mpiPSV(&mpiPSV);

taper_coeff=  matrix(1,NY,1,NX);

/* memory for source position definition */
acq.srcpos1=fmatrix(1,8,1,1);

/* memory of L2 norm */
L2t = vector(1,4);
epst1 = vector(1,3);
	
fprintf(FP," ... memory allocation for PE %d was successfull.\n\n", MYID);

/* Holberg coefficients for FD operators*/
hc = holbergcoeff();

MPI_Barrier(MPI_COMM_WORLD);

/* Reading source positions from SOURCE_FILE */ 	
acq.srcpos=sources(&nsrc);
nsrc_glob=nsrc;


/* create model grids */
if(L){
	if (READMOD) readmod_visc_PSV(matPSV.prho,matPSV.ppi,matPSV.pu,matPSV.ptaus,matPSV.ptaup,matPSV.peta);
		else model(matPSV.prho,matPSV.ppi,matPSV.pu,matPSV.ptaus,matPSV.ptaup,matPSV.peta);
} else{
	if (READMOD) readmod_elastic_PSV(matPSV.prho,matPSV.ppi,matPSV.pu);
    		else model_elastic(matPSV.prho,matPSV.ppi,matPSV.pu);
}

/* check if the FD run will be stable and free of numerical dispersion */
if(L){
	checkfd_ssg_visc(FP,matPSV.prho,matPSV.ppi,matPSV.pu,matPSV.ptaus,matPSV.ptaup,matPSV.peta,hc);
} else{
	checkfd_ssg_elastic(FP,matPSV.prho,matPSV.ppi,matPSV.pu,hc);
}
      
SHOTINC=1;

/* For RTM read only first line from FWI workflow file and set iter = 1 */
stagemax = 1;   
iter_true = 1;
iter = 1;

/* Begin of FWI-workflow */
for(nstage=1;nstage<=stagemax;nstage++){

/* read workflow input file *.inp */
FP_stage=fopen(FILEINP1,"r");
read_par_inv(FP_stage,nstage,stagemax);
/*fclose(FP_stage);*/

if((EPRECOND==1)||(EPRECOND==3)){
  Ws = matrix(1,NY,1,NX); /* total energy of the source wavefield */
  Wr = matrix(1,NY,1,NX); /* total energy of the receiver wavefield */
  We = matrix(1,NY,1,NX); /* total energy of source and receiver wavefield */
}

FC=FC_END;

if (MYID==0)
   {
   time2=MPI_Wtime();
   fprintf(FP,"\n\n\n ------------------------------------------------------------------\n");
   fprintf(FP,"\n\n\n                   Elastic Reverse Time Migration RTM \n");
   fprintf(FP,"\n\n\n ------------------------------------------------------------------\n");
   }

/* For the calculation of the material parameters between gridpoints
   they have to be averaged. For this, values lying at 0 and NX+1,
   for example, are required on the local grid. These are now copied from the
   neighbouring grids */		
if (L){
	matcopy_PSV(matPSV.prho,matPSV.ppi,matPSV.pu,matPSV.ptaus,matPSV.ptaup);
} else{
	matcopy_elastic_PSV(matPSV.prho,matPSV.ppi,matPSV.pu);
}

MPI_Barrier(MPI_COMM_WORLD);

av_mue(matPSV.pu,matPSV.puipjp,matPSV.prho);
av_rho(matPSV.prho,matPSV.prip,matPSV.prjp);
if (L) av_tau(matPSV.ptaus,matPSV.ptausipjp);


/* Preparing memory variables for update_s (viscoelastic) */
if (L) prepare_update_s_visc_PSV(matPSV.etajm,matPSV.etaip,matPSV.peta,matPSV.fipjp,matPSV.pu,matPSV.puipjp,matPSV.ppi,matPSV.prho,matPSV.ptaus,matPSV.ptaup,matPSV.ptausipjp,matPSV.f,matPSV.g,
		matPSV.bip,matPSV.bjm,matPSV.cip,matPSV.cjm,matPSV.dip,matPSV.d,matPSV.e);

/* ------------------------------------- */
/* calculate average material parameters */
/* ------------------------------------- */
Vp_avg = 0.0;
Vs_avg = 0.0;
rho_avg = 0.0;
 
for (i=1;i<=NX;i=i+IDX){
   for (j=1;j<=NY;j=j+IDY){
  
	 /* calculate average Vp, Vs */
         Vp_avg+=matPSV.ppi[j][i];
	 Vs_avg+=matPSV.pu[j][i];
	 
	 /* calculate average rho */
	 rho_avg+=matPSV.prho[j][i];

   }
}
	
/* calculate average Vp, Vs and rho of all CPUs */
Vp_sum = 0.0;
MPI_Allreduce(&Vp_avg,&Vp_sum,1,MPI_FLOAT,MPI_SUM,MPI_COMM_WORLD);
Vp_avg=Vp_sum;

Vs_sum = 0.0;
MPI_Allreduce(&Vs_avg,&Vs_sum,1,MPI_FLOAT,MPI_SUM,MPI_COMM_WORLD);
Vs_avg=Vs_sum;

rho_sum = 0.0;
MPI_Allreduce(&rho_avg,&rho_sum,1,MPI_FLOAT,MPI_SUM,MPI_COMM_WORLD);
rho_avg=rho_sum;

Vp_avg /=NXG*NYG; 
Vs_avg /=NXG*NYG; 
rho_avg /=NXG*NYG;

if(MYID==0){
   printf("Vp_avg = %.0f \t Vs_avg = %.0f \t rho_avg = %.0f \n ",Vp_avg,Vs_avg,rho_avg);	
}

C_vp = Vp_avg;
C_vs = Vs_avg;
C_rho = rho_avg;

/* ---------------------------------------------------------------------------------------------------- */
/* --------- Calculate RTM P- and S- wave image using the adjoint state method ------------------------ */
/* ---------------------------------------------------------------------------------------------------- */

L2sum = grad_obj_psv(&wavePSV, &wavePSV_PML, &matPSV, &fwiPSV, &mpiPSV, &seisPSV, &seisPSVfwi, &acq, hc, iter, nsrc, ns, ntr, ntr_glob, 
nsrc_glob, nsrc_loc, ntr_loc, nstage, We, Ws, Wr, taper_coeff, hin, DTINV_help, req_send, req_rec);

/* Interpolate missing spatial gradient values in case IDXI > 1 || IDXY > 1 */
/* ------------------------------------------------------------------------ */

if((IDXI>1)||(IDYI>1)){

   interpol(IDXI,IDYI,fwiPSV.waveconv,1);
   interpol(IDXI,IDYI,fwiPSV.waveconv_u,1);
   interpol(IDXI,IDYI,fwiPSV.waveconv_rho,1);

}

/* Preconditioning of gradients after shot summation */
precond_PSV(&fwiPSV,&acq,nsrc,ntr_glob,taper_coeff,FP_GRAV);

/* Output of RTM results */
RTM_PSV_out(&fwiPSV);

} /* End of RTM-workflow loop */

/* deallocate memory for PSV forward problem */
dealloc_PSV(&wavePSV,&wavePSV_PML);

/* deallocation of memory */
free_matrix(fwiPSV.Vp0,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.Vs0,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.Rho0,-nd+1,NY+nd,-nd+1,NX+nd);

free_matrix(matPSV.prho,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.prho_old,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(matPSV.prip,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(matPSV.prjp,-nd+1,NY+nd,-nd+1,NX+nd);

free_matrix(matPSV.ppi,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.ppi_old,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(matPSV.pu,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.pu_old,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(matPSV.puipjp,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_lam,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_shot,-nd+1,NY+nd,-nd+1,NX+nd);

free_matrix(mpiPSV.bufferlef_to_rig,1,NY,1,fdo3);
free_matrix(mpiPSV.bufferrig_to_lef,1,NY,1,fdo3);
free_matrix(mpiPSV.buffertop_to_bot,1,NX,1,fdo3);
free_matrix(mpiPSV.bufferbot_to_top,1,NX,1,fdo3);

free_vector(hc,0,6);

free_matrix(fwiPSV.gradg,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.gradp,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.gradg_rho,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.gradp_rho,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_rho,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_rho_s,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_rho_shot,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.gradg_u,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.gradp_u,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_u,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_mu,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(fwiPSV.waveconv_u_shot,-nd+1,NY+nd,-nd+1,NX+nd);

free_vector(fwiPSV.forward_prop_x,1,NY*NX*NT);
free_vector(fwiPSV.forward_prop_y,1,NY*NX*NT);
free_vector(fwiPSV.forward_prop_rho_x,1,NY*NX*NT);
free_vector(fwiPSV.forward_prop_rho_y,1,NY*NX*NT);
free_vector(fwiPSV.forward_prop_u,1,NY*NX*NT);

if (nsrc_loc>0){	
	free_matrix(acq.signals,1,nsrc_loc,1,NT);
	free_matrix(acq.srcpos_loc,1,8,1,nsrc_loc);
	free_matrix(acq.srcpos_loc_back,1,6,1,nsrc_loc);
}		   

 /* free memory for global source positions */
 free_matrix(acq.srcpos,1,8,1,nsrc);

 /* free memory for source position definition */
 free_matrix(acq.srcpos1,1,8,1,1);
 
 /* free memory for abort criterion */
 		
 free_vector(L2t,1,4);
 free_vector(epst1,1,3);

 if(N_STREAMER==0){

    if (SEISMO) free_imatrix(acq.recpos,1,3,1,ntr_glob);

    if ((ntr>0) && (SEISMO)){

            free_imatrix(acq.recpos_loc,1,3,1,ntr);
            acq.recpos_loc = NULL;
 
            switch (SEISMO){
            case 1 : /* particle velocities only */
                    free_matrix(seisPSV.sectionvx,1,ntr,1,ns);
                    free_matrix(seisPSV.sectionvy,1,ntr,1,ns);
                    seisPSV.sectionvx=NULL;
                    seisPSV.sectionvy=NULL;
                    break;
             case 2 : /* pressure only */
                    free_matrix(seisPSV.sectionp,1,ntr,1,ns);
                    break;
             case 3 : /* curl and div only */
                    free_matrix(seisPSV.sectioncurl,1,ntr,1,ns);
                    free_matrix(seisPSV.sectiondiv,1,ntr,1,ns);
                    break;
             case 4 : /* everything */
                    free_matrix(seisPSV.sectionvx,1,ntr,1,ns);
                    free_matrix(seisPSV.sectionvy,1,ntr,1,ns);
                    free_matrix(seisPSV.sectionp,1,ntr,1,ns);
                    free_matrix(seisPSV.sectioncurl,1,ntr,1,ns);
                    free_matrix(seisPSV.sectiondiv,1,ntr,1,ns);
                    break;

             }

    }

    free_matrix(seisPSVfwi.sectionread,1,ntr_glob,1,ns);
    free_ivector(acq.recswitch,1,ntr);
    
    if((QUELLTYPB==1)||(QUELLTYPB==3)||(QUELLTYPB==5)||(QUELLTYPB==7)){
       free_matrix(seisPSVfwi.sectionvxdata,1,ntr,1,ns);
       free_matrix(seisPSVfwi.sectionvxdiff,1,ntr,1,ns);
       free_matrix(seisPSVfwi.sectionvxdiffold,1,ntr,1,ns);
    }

    if((QUELLTYPB==1)||(QUELLTYPB==2)||(QUELLTYPB==6)||(QUELLTYPB==7)){    
       free_matrix(seisPSVfwi.sectionvydata,1,ntr,1,ns);
       free_matrix(seisPSVfwi.sectionvydiff,1,ntr,1,ns);
       free_matrix(seisPSVfwi.sectionvydiffold,1,ntr,1,ns);
    }
    
    if(QUELLTYPB>=4){    
       free_matrix(seisPSVfwi.sectionpdata,1,ntr,1,ns);
       free_matrix(seisPSVfwi.sectionpdiff,1,ntr,1,ns);
       free_matrix(seisPSVfwi.sectionpdiffold,1,ntr,1,ns);
    }
    
 }

 if(SEISMO){
  free_matrix(seisPSV.fulldata,1,ntr_glob,1,NT); 
 }

 if(SEISMO==1){
  free_matrix(seisPSV.fulldata_vx,1,ntr_glob,1,NT);
  free_matrix(seisPSV.fulldata_vy,1,ntr_glob,1,NT);
 }

 if(SEISMO==2){
  free_matrix(seisPSV.fulldata_p,1,ntr_glob,1,NT);
 } 
 
 if(SEISMO==3){
  free_matrix(seisPSV.fulldata_curl,1,ntr_glob,1,NT);
  free_matrix(seisPSV.fulldata_div,1,ntr_glob,1,NT);
 }

 if(SEISMO==4){
  free_matrix(seisPSV.fulldata_vx,1,ntr_glob,1,NT);
  free_matrix(seisPSV.fulldata_vy,1,ntr_glob,1,NT);
  free_matrix(seisPSV.fulldata_p,1,ntr_glob,1,NT); 
  free_matrix(seisPSV.fulldata_curl,1,ntr_glob,1,NT);
  free_matrix(seisPSV.fulldata_div,1,ntr_glob,1,NT);
 }

 free_ivector(DTINV_help,1,NT);
 
 /* free memory for viscoelastic modeling variables */
 if (L) {
		free_matrix(matPSV.ptaus,-nd+1,NY+nd,-nd+1,NX+nd);
		free_matrix(matPSV.ptausipjp,-nd+1,NY+nd,-nd+1,NX+nd);
		free_matrix(matPSV.ptaup,-nd+1,NY+nd,-nd+1,NX+nd);
		free_vector(matPSV.peta,1,L);
		free_vector(matPSV.etaip,1,L);
		free_vector(matPSV.etajm,1,L);
		free_vector(matPSV.bip,1,L);
		free_vector(matPSV.bjm,1,L);
		free_vector(matPSV.cip,1,L);
		free_vector(matPSV.cjm,1,L);
		free_matrix(matPSV.f,-nd+1,NY+nd,-nd+1,NX+nd);
		free_matrix(matPSV.g,-nd+1,NY+nd,-nd+1,NX+nd);
		free_matrix(matPSV.fipjp,-nd+1,NY+nd,-nd+1,NX+nd);
		free_f3tensor(matPSV.dip,-nd+1,NY+nd,-nd+1,NX+nd,1,L);
		free_f3tensor(matPSV.d,-nd+1,NY+nd,-nd+1,NX+nd,1,L);
		free_f3tensor(matPSV.e,-nd+1,NY+nd,-nd+1,NX+nd,1,L);
}
 
/* de-allocate buffer for messages */
MPI_Buffer_detach(buff_addr,&buffsize);

MPI_Barrier(MPI_COMM_WORLD);

if (MYID==0){
	fprintf(FP,"\n **Info from main (written by PE %d): \n",MYID);
	fprintf(FP," CPU time of program per PE: %li seconds.\n",clock()/CLOCKS_PER_SEC);
	time8=MPI_Wtime();
	fprintf(FP," Total real time of program: %4.2f seconds.\n",time8-time1);
	time_av_v_update=time_av_v_update/(double)NT;
	time_av_s_update=time_av_s_update/(double)NT;
	time_av_v_exchange=time_av_v_exchange/(double)NT;
	time_av_s_exchange=time_av_s_exchange/(double)NT;
	time_av_timestep=time_av_timestep/(double)NT;
	/* fprintf(FP," Average times for \n");
	fprintf(FP," velocity update:  \t %5.3f seconds  \n",time_av_v_update);
	fprintf(FP," stress update:  \t %5.3f seconds  \n",time_av_s_update);
	fprintf(FP," velocity exchange:  \t %5.3f seconds  \n",time_av_v_exchange);
	fprintf(FP," stress exchange:  \t %5.3f seconds  \n",time_av_s_exchange);
	fprintf(FP," timestep:  \t %5.3f seconds  \n",time_av_timestep);*/
		
}

fclose(FP);


}
예제 #13
0
파일: ex-1.c 프로젝트: boosheng/masterca
int main(int argc, char **argv) {

double             x[SIZE],
                   fx[SIZE],
                   z[SIZE],
                   pz[SIZE],
                   y[SIZE],
                   b1,
                   b0;

int                retval,
                   i,
                   n;

/*****************************************************************************
*                                                                            *
*  Interpolate a function.                                                   *
*                                                                            *
*****************************************************************************/

fprintf(stdout, "Perform polynomial interpolation\n");

x[0] = -3.0; fx[0] = -5.0;
x[1] = -2.0; fx[1] = -1.1;
x[2] =  2.0; fx[2] =  1.9;
x[3] =  3.0; fx[3] =  4.8;

z[0] = -2.5;
z[1] = -1.0;
z[2] =  0.0;
z[3] =  1.0;
z[4] =  1.5;
z[5] =  2.5;

if (interpol(x, fx, 4, z, pz, 6) != 0)
   return 1;

fprintf(stdout, "Interpolating f(z) with p(z)\n");

for (i = 0; i < 4; i++)
   fprintf(stdout, "x[%d]=%+1.6e, f(x[%d])=%+1.6e\n", i, x[i], i, fx[i]);

for (i = 0; i < 6; i++)
   fprintf(stdout, "z[%d]=%+1.6e, p(z[%d])=%+1.6e\n", i, z[i], i, pz[i]);

x[0] = -4.0; fx[0] = -3.0;
x[1] = -3.5; fx[1] =  1.5;
x[2] = -2.5; fx[2] =  2.5;
x[3] = -1.5; fx[3] =  1.5;
x[4] =  0.0; fx[4] =  0.5;
x[5] =  1.5; fx[5] =  1.5;
x[6] =  2.5; fx[6] =  2.5;
x[7] =  3.5; fx[7] =  1.5;
x[8] =  4.0; fx[8] = -3.0;

z[0] = -0.50;
z[1] = -1.00;
z[2] = -2.00;
z[3] = -3.00;
z[4] = -3.25;
z[5] = -3.50;
z[6] = -3.75;

if (interpol(x, fx, 9, z, pz, 7) != 0)
   return 1;

fprintf(stdout, "Interpolating f(z) with p(z)\n");

for (i = 0; i < 9; i++)
   fprintf(stdout, "x[%d]=%+1.6e, f(x[%d])=%+1.6e\n", i, x[i], i, fx[i]);

for (i = 0; i < 7; i++)
   fprintf(stdout, "z[%d]=%+1.6e, p(z[%d])=%+1.6e\n", i, z[i], i, pz[i]);

/*****************************************************************************
*                                                                            *
*  Compute least-squares estimators.                                         *
*                                                                            *
*****************************************************************************/

fprintf(stdout, "Perform least-squares estimation\n");

x[0] =  4.0; y[0] =  197.0;
x[1] =  6.0; y[1] =  272.0;
x[2] =  2.0; y[2] =  100.0;
x[3] =  5.0; y[3] =  228.0;
x[4] =  7.0; y[4] =  327.0;
x[5] =  6.0; y[5] =  279.0;
x[6] =  3.0; y[6] =  148.0;
x[7] =  8.0; y[7] =  377.0;
x[8] =  5.0; y[8] =  238.0;
x[9] =  3.0; y[9] =  142.0;
x[10] = 1.0; y[10] =  66.0;
x[11] = 5.0; y[11] = 239.0;

for (i = 0; i < 12; i++)
   fprintf(stdout, "x[%02d]=%+1.6e, y[%02d]=%+1.6e\n", i, x[i], i, y[i]);

lsqe(x, y, 12, &b1, &b0);

fprintf(stdout, "b1=%+1.6e, b0=%+1.6e\n", b1, b0);

/*****************************************************************************
*                                                                            *
*  Find the roots of an equation.                                            *
*                                                                            *
*****************************************************************************/

fprintf(stdout, "Finding the roots of an equation\n");

n = 10;
x[0] = -2.0;
retval = root(f, g, x, &n, 0.0001);

for (i = 0; i < n; i++)
   fprintf(stdout, "x[%d]=%+1.6e\n", i, x[i]);

if (retval != 0)
   fprintf(stdout, "Did not find a root\n");
else
   fprintf(stdout, "Found a root at %+1.6e\n", x[n - 1]);

n = 10;
x[0] = 0.5;
retval = root(f, g, x, &n, 0.0001);

for (i = 0; i < n; i++)
   fprintf(stdout, "x[%d]=%+1.6e\n", i, x[i]);

if (retval != 0)
   fprintf(stdout, "Did not find a root\n");
else
   fprintf(stdout, "Found a root at %+1.6e\n", x[n - 1]);

n = 10;
x[0] = 2.0;
retval = root(f, g, x, &n, 0.0001);

for (i = 0; i < n; i++)
   fprintf(stdout, "x[%d]=%+1.6e\n", i, x[i]);

if (retval != 0)
   fprintf(stdout, "Did not find a root\n");
else
   fprintf(stdout, "Found a root at %+1.6e\n", x[n - 1]);

return 0;

}
void
EBLevelTransport::
doRegularUpdate(LevelData<EBCellFAB>&         a_divF,
                LevelData<EBCellFAB>&         a_cons,
                const LevelData<EBCellFAB>&   a_normalVel,
                const LevelData<EBFluxFAB>&   a_advVel,
                const LayoutData< Vector <BaseIVFAB<Real> * > >& a_coveredAdvVelMinu,
                const LayoutData< Vector <BaseIVFAB<Real> * > >& a_coveredAdvVelPlus,
                EBFluxRegister&               a_fineFluxRegister,
                EBFluxRegister&               a_coarFluxRegister,
                const LevelData<EBCellFAB>&   a_source,
                Real a_time, Real a_dt)
{
  bool verbose = false;
  int ibox = 0;
  Interval consInterv(0, m_nCons-1);
  Interval fluxInterv(0, m_nFlux-1);

    for (DataIterator dit = m_thisGrids.dataIterator(); dit.ok(); ++dit, ibox++)
    {
      const Box& cellBox = m_thisGrids.get(dit());
      const EBISBox& ebisBox = m_thisEBISL[dit()];
      if(!ebisBox.isAllCovered())
        {
          const IntVectSet& cfivs = m_cfIVS[dit()];

          EBCellFAB& consState = a_cons[dit()];
          m_ebPatchGodunov->setValidBox(cellBox, ebisBox, cfivs, a_time, a_dt); 
          //begin debug
          //int here = 0;
          //if(cellBox.contains(EBPatchGodunov::s_debugIV) && (EBPatchGodunov::s_whichLev==1))
          //  {
          //    here = 1;
          //  }
          //end debug

          const EBCellFAB& source = a_source[dit()];
          const EBCellFAB& normalVel = a_normalVel[dit()];
          const EBFluxFAB& advVel = a_advVel[dit()];
          const Vector<BaseIVFAB <Real>* >& coveredAdvVelMinu = a_coveredAdvVelMinu[dit()];
          const Vector<BaseIVFAB <Real>* >& coveredAdvVelPlus = a_coveredAdvVelPlus[dit()];

          m_ebPatchGodunov->setVelocities(normalVel, advVel, coveredAdvVelMinu, coveredAdvVelPlus);

          EBFluxFAB flux(ebisBox, cellBox, m_nFlux);
          BaseIVFAB<Real>& nonConsDiv    = m_nonConsDivergence[dit()];
          BaseIVFAB<Real>& ebIrregFlux   = m_ebIrregFaceFlux[dit()];
          flux.setVal(7.89);
          ebIrregFlux.setVal(7.89);
          const IntVectSet& ivsIrreg     = m_irregSetsSmall[dit()];
          const EBCellFAB& flatteningFAB = m_flattening[dit()];

          BaseIVFAB<Real>  coveredPrimMinu[SpaceDim];
          BaseIVFAB<Real>  coveredPrimPlus[SpaceDim];
          Vector<VolIndex> coveredFaceMinu[SpaceDim];
          Vector<VolIndex> coveredFacePlus[SpaceDim];
          EBFluxFAB facePrim;

          EBCellFAB& divFFAB = a_divF[dit()];
//          EBPatchTransport& patchTrans = (EBPatchTransport&) (*m_ebPatchGodunov);

          EBPatchGodunov::setCurComp(0);
          EBPatchGodunov::setDoingVel(0);
          EBPatchGodunov::setDoingAdvVel(0);


          m_ebPatchGodunov->primitivesAndDivergences(divFFAB, consState,
                                             facePrim,
                                             coveredPrimMinu,
                                             coveredPrimPlus,
                                             coveredFaceMinu,
                                             coveredFacePlus,
                                             flux, ebIrregFlux,
                                             nonConsDiv,flatteningFAB,
                                             source, cellBox, ivsIrreg,
                                             dit(),verbose);

          //do fluxregister cha-cha
          /*
            Coarse flux register is flux register with the coarse level.
            Fine flux register is the flux register with the fine level.
            To the finer level FR, this level is the coarse level.
            To the coarser level FR, this level is the fine level.
          */
          for(int idir = 0; idir < SpaceDim; idir++)
            {
              Real scale = a_dt;

              EBFaceFAB fluxRegFlux;
              if(m_hasFiner)
                {
                  a_fineFluxRegister.incrementCoarseRegular(flux[idir], scale,dit(),
                                                            consInterv, idir);
                }

              if(m_hasCoarser)
                {
                  for(SideIterator sit; sit.ok(); ++sit)
                    {
                      a_coarFluxRegister.incrementFineRegular(flux[idir],scale, dit(),
                                                              consInterv, idir,sit());
                    }
                }
            }

          //copy fluxes into sparse interpolant
          for(int faceDir = 0; faceDir < SpaceDim; faceDir++)
            {
              IntVectSet ivsIrregGrown = m_irregSetsGrown[faceDir][dit()];
              ivsIrregGrown &= cellBox;
              FaceStop::WhichFaces stopCrit = FaceStop::SurroundingWithBoundary;

              BaseIFFAB<Real>& interpol = m_fluxInterpolants[faceDir][dit()];
              interpol.setVal(7.7777e7);
              EBFaceFAB& fluxDir = flux[faceDir];
              for(FaceIterator faceit(ivsIrregGrown, ebisBox.getEBGraph(),
                                      faceDir, stopCrit);
                  faceit.ok(); ++faceit)
                {
                  for(int ivar = 0; ivar < m_nFlux; ivar++)
                    {
                      interpol(faceit(), ivar) = fluxDir(faceit(), ivar);
                    }
                }

            }
        }
    }

  for(int faceDir = 0; faceDir < SpaceDim; faceDir++)
    {
      m_fluxInterpolants[faceDir].exchange(fluxInterv);
    } 
}
예제 #15
0
main()
{
	FILE *mock; //Input catalog
	FILE *cat; //Output catalog
	FILE *filt; //Filter response
	FILE *nom_filt; //Filter names
	FILE *nom_sed; //Sed names
	FILE *sed1; //Spectral template. It must cover all filters range
	FILE *sed2; //Spectral template. It must cover all filters range  
	
	char nom_fich_filt_a[1000];
	char nom_fich_filt_b[1000];
	char nom_fich_sed1[1000];
	char nom_fich_sed2[1000];
	char line[1000];

	int i, N_gal = 0, *error, filt_index, sed_index1, sed_index2, num_gal = 0, num_filt = 0; //index filtr, sed & obj
	double type; //Real spectral index
	double *in_r, *in_sed; //in: integral r:filter sed:template
	double x, *y, *y_sed, *xn, *xn1, *yn, *yn1; 
	double id, ebv, Mr, z, mi, mag_ab;
	double *coef;
	double intro[5], sdss[2], des[6], pau[40], F814, mass[3];

	xn = (double*) calloc(3, sizeof(double)); //0:filter 1:sed1 2:sed2
	xn1 = (double*) calloc(3, sizeof(double)); //0:filter 1:sed1 2:sed2
	yn = (double*) calloc(3, sizeof(double)); //0:filter 1:sed1 2:sed2
	yn1 = (double*) calloc(3, sizeof(double)); //0:filter 1:sed1 2:sed2
	y = (double*) calloc(2, sizeof(double)); //0:filter 1:sed
	y_sed = (double*) calloc(2, sizeof(double)); //0:sed1 1:sed2
	coef = (double*) calloc(2, sizeof(double)); //0:sed1 1:sed2
	error = (int*) calloc(1, sizeof(int));

	printf("\n***********************************************\n");
	printf("*                                             *\n");
	printf("*   NOISELESS CATALOG GENERATOR by P. Marti   *\n");
	printf("*                 Version 1                   *\n");
	printf("*                                             *");
	printf("\n***********************************************\n");

	//Computing number of filters....................................................................
	nom_filt = fopen(nom_filt_file, "r"); //apertura arxiu amb noms dels filtres
	while(*error = fscanf(nom_filt, "%s\n", nom_fich_filt_a) != -1) if(*error !=-1) num_filt++;
	fclose(nom_filt);
	printf("\n\tTotal Number of filters = %d\n",num_filt);
		
	//Openinf output catalog.........................................................................
	cat = fopen(cat_out_file , "w"); 
	fprintf(cat,"#1:ID\n#2:z_true\n#3:t_true\n#4:E(B-V)\n#5:Mr\n");
	
	//FILTERS MODULE.................................................................................
	nom_filt = fopen(nom_filt_file, "r"); //apertura arxiu amb noms dels filtres

	//Loop over filters..............................................................................
	in_r = (double*) calloc(num_filt + 1, sizeof(double));
	i = 0;
	do{ 
		if(i == 0) filt_path(nom_fich_filt_b, nom_filt_seed);
		else filt_path(nom_fich_filt_b, nom_fich_filt_a);
		
		if(i != 0) fprintf(cat,"#%d:%s\n",i + 5, nom_fich_filt_a);
		
		filt = file_init(nom_fich_filt_b); //obrim l'arxiu del filtre corresponent

		fscanf(filt, "%lf %lf\n", &xn[0] , &yn[0]); //lectura 2 punts
		*error = fscanf(filt, "%lf %lf\n", &xn1[0] , &yn1[0]);
		x = xn[0]; //x inicial
		y[0] = yn[0]; //y[0] inicial
		
		in_r[i] = 0;
		while(*error != -1){ //Bucle per integrar sobre tot el filtre
			in_r[i] += y[0]*(delta/x); //integral filtre
			x+=delta; //nou punt x
			
			*error = inter_filt_point(filt, error, 0, xn1, xn, yn1, yn, x);
			if(*error != -1) y[0] = interpol(xn1[0], xn[0], yn1[0], yn[0], x);
		}
		fclose(filt); //tancament arxiu filtre
		i++;
	}while(fscanf(nom_filt, "%s\n", nom_fich_filt_a) != -1);

	fclose(nom_filt);
	
	//CATALOG MODULE.................................................................................
	//Count number of objects in the file
	mock = file_init(cat_in_file);
	while(fgets(line, 1000, mock) != NULL) N_gal++;
	fclose(mock);
	printf("\tTotal number of objects = %d\n", N_gal);

	mock = file_init(cat_in_file);
	
	//Loop over objects of mock catalog..............................................................
	in_sed = (double*) calloc(num_filt + 1, sizeof(double));
	//while(fscanf(mock, "%lf %lf %lf %lf %lf %lf\n", &id, &mi, &z, &type, &ebv, &Mr) != -1){
	while(fscanf(mock,"%lf ", &intro[0]) != -1){
		num_gal++;
		
		for(i=1; i<5; i++) fscanf(mock,"%lf ",&intro[i]);
		fscanf(mock,"%lf ", &sdss[0]);
		for(i=0; i<6; i++) fscanf(mock,"%lf ",&des[i]);
		for(i=0; i<40; i++) fscanf(mock,"%lf ",&pau[i]);
		fscanf(mock,"%lf ", &F814);
		fscanf(mock,"%lf ", &sdss[1]);
		for(i=0; i<2; i++) fscanf(mock,"%lf ",&mass[i]);
		fscanf(mock,"%lf\n",&mass[2]);
		
		id = intro[0];
		z = intro[1];
		type = intro[2];
		ebv = intro[3];
		Mr = intro[4];
		mi = sdss[1];
		
		//Calcular la integral convolució filtres-SED i filtres sols.................................
		nom_filt = fopen(nom_filt_file, "r"); //apertura arxiu amb noms dels filtres
			
		set_type(type, coef, nom_fich_sed1 , nom_fich_sed2);
		//Loop over filters..........................................................................
		i = 0;
		do{ 
			if(i == 0) filt_path(nom_fich_filt_b, nom_filt_seed);
			else filt_path(nom_fich_filt_b, nom_fich_filt_a);
			
			sed1 = fopen(nom_fich_sed1 , "r");
			sed2 = fopen(nom_fich_sed2 , "r");
			xn1[1] = 0, xn1[2] = 0; //Forcing SEDs to start at wavelenght 0 
			
			filt = file_init(nom_fich_filt_b); //obrim l'arxiu del filtre corresponent
			fscanf(filt, "%lf %lf\n", &xn[0] , &yn[0]); //lectura 2 punts
			*error = fscanf(filt, "%lf %lf\n", &xn1[0] , &yn1[0]);
			x = xn[0]; //x inicial
			y[0] = yn[0]; //y[0] inicial
			
			//Loop over all the filter range.........................................................
			in_sed[i] = 0;
			while(*error != -1){ 
				//SED1
				inter_sed_point(sed1, 1, xn1, xn, yn1, yn, x, z);
				y_sed[0] = interpol(xn1[1], xn[1], yn1[1], yn[1], x);
				
				//SED2
				inter_sed_point(sed2, 2, xn1, xn, yn1, yn, x, z); 
				y_sed[1] = interpol(xn1[2], xn[2], yn1[2], yn[2], x);
		
				y[1] = coef[0]*y_sed[0] + coef[1]*y_sed[1]; //Combinació lineal seds
				in_sed[i] += y[0]*y[1]*(x*delta); //integral filtre i sed
				x += delta; //nou punt x
				
				//FILTER
				*error = inter_filt_point(filt, error, 0, xn1, xn, yn1, yn, x);
				if(*error != -1) y[0] = interpol(xn1[0], xn[0], yn1[0], yn[0], x);
				
			}
			fclose(filt), fclose(sed1), fclose(sed2);
			i++;
		}while(fscanf(nom_filt, "%s\n", nom_fich_filt_a) != -1);
		
		fclose(nom_filt);

		//Printing catalog with all magnitudes in different filters....................................
		fprintf(cat, "%d ", (int)id);
		printf("\tProcess completed:\t%2.2f%%\r", 100*((double)num_gal/(double)N_gal));
		fflush(stdout);

		for(i=1; i <= num_filt; i++){
			mag_ab = mi+2.5*(log10(in_sed[0])+log10(in_r[i])-log10(in_r[0])-log10(in_sed[i]));
			fprintf(cat, "%4.4f ", mag_ab);
		}
		fprintf(cat, "%4.4f %2.2f\n", z, type);
	}
	fclose(cat);
	fclose(mock);
	
	printf("\n");

	return 0;
}
예제 #16
0
int tt_ima_series_pol2rec(TT_IMA_SERIES *pseries)
{
   TT_IMA *p_out;
   int index;

   int width, height;
   double scale_theta,scale_rho;
   int x,y;               /* loop variable */
   double value;           /* temporary variable */
   int x0,y0;
   double old_rho,old_theta=0.;
   char message[TT_MAXLIGNE];

   /* --- intialisations ---*/
   p_out=pseries->p_out;
   index=pseries->index;

   width=pseries->user3.width;
   height=pseries->user3.height;
   x0=(int)(pseries->user3.x0-1);
   y0=(int)(pseries->user3.y0-1);
   scale_theta=pseries->user3.scale_theta;
   scale_rho=pseries->user3.scale_rho;


   /* verification des donnees */
   if ((scale_theta < 0) || (scale_rho < 0))
   {
         sprintf(message,"scale must be positive");
         tt_errlog(TT_ERR_WRONG_VALUE,message);
         return(TT_ERR_WRONG_VALUE);
   } /* end of if-statement */

   if ((width < 0) || (height < 0))
   {
         sprintf(message,"height and width must be positive");
         tt_errlog(TT_ERR_WRONG_VALUE,message);
         return(TT_ERR_WRONG_VALUE);
   } /* end of if-statement */

   /* --- initialisation ---*/
   /*tt_imabuilder(p_out);*/
   tt_imacreater(p_out,width,height);

   for(x = 0; x < width;x++)
   {
   	for(y = 0; y < height;y++)
      {
          if((x == x0) && (y == y0))
          {
          	old_rho = 0.;
            old_theta = 0.;
          }
          else
          {
          	old_rho = sqrt((x - x0) * (x - x0) + (y - y0) * (y - y0));
            if(y > y0)
          	old_theta = acos((x - x0) / old_rho) * 180. / TT_PI;
            else if (y < y0)
            old_theta = (360. - acos((x - x0) / old_rho) * 180. / TT_PI);
            else if ((y == y0) && (x < x0))
            old_theta = 180.;
            else if ((y == y0) && (x >= x0))
            old_theta = 0.;
          }
          value = interpol(pseries,old_theta * scale_theta,old_rho * scale_rho,1);
      	 p_out->p[x + y * width] = (TT_PTYPE)value;
      } /* end of y-loop */
   } /* end of x-loop */


   /* --- calcul des temps (pour l'entete fits) ---*/
   pseries->jj_stack=pseries->jj[index-1];
   pseries->exptime_stack=pseries->exptime[index-1];

   return(OK_DLL);
}
예제 #17
0
int tt_ima_series_rec2pol(TT_IMA_SERIES *pseries)
{
   TT_IMA *p_in,*p_out;
   int index;

   int w, h;
   double scale_theta,scale_rho;
   int rho,theta;         /* loop variable */
   double value;           /* temporary variable */
   int x0,y0;
   double rho_max;
   int axis_theta,axis_rho;
   double old_x,old_y,temp;
   char message[TT_MAXLIGNE];

   /* --- intialisations ---*/
   p_in=pseries->p_in;
   p_out=pseries->p_out;
   index=pseries->index;

   w=p_in->naxis1;
   h=p_in->naxis2;
   x0=(int)pseries->user3.x0-1;
   y0=(int)pseries->user3.y0-1;
   scale_theta=pseries->user3.scale_theta;
   scale_rho=pseries->user3.scale_rho;

   rho_max = sqrt(w * w + h * h);
   axis_theta = (int)(361. * scale_theta);
   axis_rho = (int)(rho_max * scale_rho + 1.);

   /* verification des donnees */
   if ((scale_theta < 0) || (scale_rho < 0))
   {
         sprintf(message,"scale must be positive");
         tt_errlog(TT_ERR_WRONG_VALUE,message);
         return(TT_ERR_WRONG_VALUE);
   } /* end of if-statement */

   /* --- initialisation ---*/
   /*tt_imabuilder(p_out);*/
   tt_imacreater(p_out,axis_theta,axis_rho);

   for(theta = 0;theta < axis_theta;theta++)
   {
   	for(rho = 0;rho < axis_rho;rho++)
      {
         temp = theta / scale_theta * (TT_PI/180.);
      	old_x = x0 + rho * cos(temp) / scale_rho;
         old_y = y0 + rho * sin(temp) / scale_rho;
         value = interpol(pseries,old_x,old_y,1);
         p_out->p[theta + rho * axis_theta] = (TT_PTYPE)value;
      } /* end of rho-loop */
   } /* end of theta_loop */

   /* --- calcul des temps (pour l'entete fits) ---*/
   pseries->jj_stack=pseries->jj[index-1];
   pseries->exptime_stack=pseries->exptime[index-1];

   return(OK_DLL);
}
예제 #18
0
파일: main.c 프로젝트: robzidek/DCOC
int value_iteration(){
    
    //init stuff
    float stopping_criterion = 0.01;
    float *x1_space, *x2_space, ***V, ***V_old, *temp_w, *temp_u;
    int i,j,k;
    int x1_len = (x_max[0]-x_min[0])/step_size[0] + 1;
    int x2_len = (x_max[1]-x_min[1])/step_size[1] + 1;
    int w_len = sizeof(w_space)/sizeof(float);
    int u_len = sizeof(u_space)/sizeof(float);
    float x_new[] = {0,0};
    float g = 1;
    
    x1_space = (float *)(malloc(x1_len*sizeof(float)));
    for(i=0;i<x1_len;i++){
        x1_space[i] = x_min[0] + step_size[0]*i;
        //printf("%f ",x1_space[i]);
    }
    printf("\n");
    
    x2_space = (float *)(malloc(x2_len*sizeof(float)));
    for(i=0;i<x2_len;i++){
        x2_space[i] = x_min[1] + step_size[1]*i;
        //printf("%f ",x2_space[i]);
    }
    
    temp_w = (float *)(malloc(w_len*sizeof(float)));
    temp_u = (float *)(malloc(u_len*sizeof(float)));
    
    V = (float ***)(malloc(x1_len*sizeof(float *)));
    V_old = (float ***)(malloc(x1_len*sizeof(float *)));
    for(i=0;i<x1_len;i++){
        V[i] = (float **)(malloc(x2_len*sizeof(float *)));
        V_old[i] = (float **)(malloc(x2_len*sizeof(float *)));
        for(j=0;j<x2_len;j++){
            V[i][j]=(float *)(malloc(w_len*sizeof(float)));
            V_old[i][j]=(float *)(malloc(w_len*sizeof(float)));
            for(k=0;k<w_len;k++){
                V[i][j][k] = 0;
                V_old[i][j][k] = 1;
                
            }
        }
    }
    
    
    float a[] = {0,0};
    float x1=0.1,x2=0.1,w=0.1;
    pendulum_nonlinearmodel_ss(&a[0], 1, 0, del_t, &x_new[0]);
    printf("array gotten %f,%f\n",x_new[0],x_new[1]);
    
    float temp;
    temp= interpol(x1_space, x2_space, w_space, V, x1, x2, w,  x1_len, x2_len, w_len);
    printf("d %f",temp);
    //V_old = memcpy(&V[0][0][0], &V_old[0][0][0], x1_len*x2_len*w_len*sizeof(float));
    
    i = 0, j=0, k=0;
    int c = 0, d=0;
    float x_old[] = {0,0};
    float max_temp_u = 0;
    int iteration = 0;
    while(max_of_V(V, V_old, x1_len, x2_len, w_len) > stopping_criterion){
        deepcopy(V, V_old, x1_len, x2_len, w_len);
        //printf("cpy %f %f \n",V[1][1][1],V_old[1][1][1]);
        for(i=0;i<x1_len;i++){
            for(j=0;j<x2_len;j++){
                for(k=0;k<w_len;k++){
                    for(c=0;c<u_len;c++){
                        x_old[0] = x1_space[i];
                        x_old[1] = x2_space[j];
                        pendulum_nonlinearmodel_ss(&x_old[0], u_space[c], w_space[k], del_t, &x_new[0]);
                        //printf("non linear %f %f \n",x_new[0],x_new[1]);
                        temp_u[c] = g;
                        for(d=0;d<w_len;d++){
                            temp_w[d] = interpol(x1_space, x2_space, w_space, V, x_new[0], x_new[1], w_space[d],  x1_len, x2_len, w_len);
                            
                            temp_u[c] = temp_u[c] + temp_w[d]*prob_matrix[k][d];
                            //printf("temp w[d] %f\n",temp_w[d]);
                        }
                        
                        if(temp_u[c]>max_temp_u){
                            max_temp_u = temp_u[c];
                        }
                        
                    }
                    V[i][j][k] = max_temp_u;
                }
            }
        }
        printf("iteration %d value %f \n",iteration, max_of_V(V, V_old, x1_len, x2_len, w_len));
        
        iteration += 1;

    }
    
    
    


    
    
    printf("Value iteration Done\n");
    FILE *outfile;
    char *outfilename = "/Users/Rounak/Desktop/Summer project/DCOC/DCOC_in_C/DCOC_in_C/abc.csv";
    printf("%s",outfilename);
    if ((outfile = fopen(outfilename,"w")) == NULL)
    {
        printf("Error opening output file.\n");
        return -1;
    }
    else{
        printf("file opened\n");
    }
    for(i=0;i<x1_len;i++)
    {
        for(j=0;j<x2_len;j++)
        {
            for(k=0;k<w_len;k++){
                fprintf(outfile,"%f,",V[i][j][k]);
            }
            fprintf(outfile,"::::::");
        }
        fprintf(outfile,"\n");
    }
    fclose(outfile);
    
    return 0;
}
예제 #19
0
QImage *ImageResizer::resizeImageSingleDim(QImage *src,int renewedDimVal,int otherDimVal,bool widthChanged)
{
    int previousDimValue = (widthChanged) ? src->width() : src->height();
    int wsel_dim_multiple = renewedDimVal / previousDimValue;
    int wsel_dim_added = renewedDimVal % previousDimValue;
    int wsel_dim_added_tmp = wsel_dim_added;
    int wsel_dim_added_mult2 = 0;
    int wsel_dim_added_Non_mult2 = wsel_dim_added;
    int wsel_dim_added_tmp_Non_mult2 = 0;
    int w_Non_mult2_count=0;
    bool every_2=false;
    int mult_2 = 2;
    bool b_Add=true;
    int tmp_add,tmp_nb_points_del,tmp_del=0;
    int wsel_dim_step_Non_mult2 = previousDimValue+8; // cas où les positions mult2 couvrent le besoin
    while ((wsel_dim_added_tmp < (previousDimValue/mult_2)) && (mult_2 <= 32)) {
        mult_2 *= 2;
    }
    if (wsel_dim_added_tmp >= (previousDimValue/mult_2))
    {
        every_2 = true;
        wsel_dim_added_mult2 = previousDimValue/mult_2;
        wsel_dim_added_Non_mult2 -= wsel_dim_added_mult2;
    }
    if (wsel_dim_added_Non_mult2 > 0)
    {
        tmp_add = (previousDimValue-wsel_dim_added_mult2) / wsel_dim_added_Non_mult2;
        tmp_nb_points_del = previousDimValue-wsel_dim_added_mult2-wsel_dim_added_Non_mult2;
        if (tmp_nb_points_del > 0)
            tmp_del = (previousDimValue-wsel_dim_added_mult2) / tmp_nb_points_del;
        if (tmp_del > tmp_add)
        {
            b_Add=false;
            wsel_dim_step_Non_mult2 = tmp_del;
        } else
        {
            b_Add=true;
            wsel_dim_step_Non_mult2 = tmp_add;
        }
    }
    int wsel_dim_index = 0;
    QRgb color1,color2;
    int nb_interpolation=0;
    QImage *ret = (widthChanged) ? new QImage(renewedDimVal,otherDimVal,src->format()) :
                                   new QImage(otherDimVal,renewedDimVal,src->format());
    int otherDimLimit = (widthChanged) ? src->height() : src->width();
    int thisDimLimit = (widthChanged) ? src->width() : src->height();
    for (int otherDimParam=0; otherDimParam < otherDimLimit  ; otherDimParam++) {
        wsel_dim_index = 0;
        w_Non_mult2_count = 0;
        wsel_dim_added_tmp = wsel_dim_added;
        wsel_dim_added_tmp_Non_mult2 = wsel_dim_added - wsel_dim_added_mult2;
        if (!b_Add)
            wsel_dim_added_tmp_Non_mult2 = tmp_nb_points_del;
        for (int thisDimParam = 0; thisDimParam < thisDimLimit; thisDimParam++) {
            nb_interpolation=wsel_dim_multiple;
            if (widthChanged)
            {
                color1 = src->pixel(thisDimParam,otherDimParam);
                if (thisDimParam < (thisDimLimit-1))
                    color2 = src->pixel(thisDimParam+1,otherDimParam);
                else
                    color2 = src->pixel(thisDimParam,otherDimParam);
            } else
            {
                color1 = src->pixel(otherDimParam,thisDimParam);
                if (thisDimParam < (thisDimLimit-1))
                    color2 = src->pixel(otherDimParam,thisDimParam+1);
                else
                    color2 = src->pixel(otherDimParam,thisDimParam);
            }
            if (every_2)
            {
                if ((thisDimParam % mult_2) == 0)
                {
                    if (wsel_dim_added_tmp > 0)
                    {
                        nb_interpolation++;
                        wsel_dim_added_tmp--;
                    }
                }
                else
                {
                    if (((b_Add)&&((w_Non_mult2_count % wsel_dim_step_Non_mult2) == 0)&&(wsel_dim_added_tmp_Non_mult2 > 0))
                            ||((!b_Add)&&(((w_Non_mult2_count % wsel_dim_step_Non_mult2) != 0)||(wsel_dim_added_tmp_Non_mult2<=0))))
                        if (wsel_dim_added_tmp > 0)
                        {
                            nb_interpolation++;
                            wsel_dim_added_tmp_Non_mult2--;
                            wsel_dim_added_tmp--;
                        }
                    w_Non_mult2_count++;
                }
            }
            else
            {
                if ((thisDimParam % wsel_dim_step_Non_mult2) == 0)
                    if (wsel_dim_added_tmp > 0)
                    {
                        nb_interpolation++;
                        wsel_dim_added_tmp--;
                    }
            }
            if (widthChanged)
                interpol(ret,wsel_dim_index,otherDimParam,nb_interpolation,color1,color2,widthChanged);
            else
                interpol(ret,otherDimParam,wsel_dim_index,nb_interpolation,color1,color2,widthChanged);
            wsel_dim_index += nb_interpolation;
        }
    }
    return ret;
}