Example #1
0
bool get_tah(float* trace, float* header, 
	     int n1_traces, int n1_headers, sf_file file)
/*< get tah.  return 1 if eof encountered, 0 otherwise >*/
{
  int input_record_length;
  char type_input_record[5];

  /* sergey suggests
     if (!sf_try_charread("tah",file)) return 1;
     but I cannot find function and I donot think it will do all that I need
     For now I am changing back to my stub kls */
  
  if(4!=sf_try_charread2(type_input_record,4,file)){
    /* must have encounterred eof. */
    return true;
  }
  type_input_record[4]='\0';
  sf_intread(&input_record_length,1,file);
  /* fprintf(stderr,"sf_get_tah type_input_record=\"%s\"\n",
     type_input_record); */
  if(strcmp(type_input_record,"tah ")!=0){
    /* not my kind of record.  Just write it back out */
    /* Right now tah programs only have tah records.  Other type records 
       used to be be helpful to me.  They allowed me to share the pipe.  
       Program looked for the type records and they wanted and ignored the 
       ones it was not interested in an may did not even know.  If I 
       add other record types this is where I need to add the 
       sf_get_tah_buffer allocations kls */
    sf_error("non tah record found. Better write this code segment\n");
  }     
  
  if(sizeof(float)*(n1_traces+n1_headers)!=input_record_length){
      sf_warning("%s: n1_traces, and n1_headers are",__FILE__);
      sf_warning("inconsistent with input record length");
      sf_warning("n1_traces=%d, n1_headers=%d, sizeof(float)=%d",
		  n1_traces   , n1_headers  ,(int)sizeof(float) );
      sf_warning("input_record_length=%d",input_record_length);
      sf_error("sizeof(float)*(n1_traces+n1_headers)!=input_record_length");
  }
  
  /*fprintf(stderr,"read n1_traces=%d floats from input file\n",n1_traces); */

  sf_floatread(trace,n1_traces,file);

  /*fprintf(stderr,"read n1_headers=%d floats from input file\n",n1_headers);*/

  sf_floatread(header,n1_headers,file);

  return false;
}
Example #2
0
File: Mss.c Project: krushev36/src
int main(int argc, char*argv[])
{
    sf_file in, out ;
    int i1, i2, n1, n2, *v;
    float o1, d1, **u;
    char *l1, *u1;
    sf_axis ax;

    sf_init(argc, argv);

    in  = sf_input("in");  /* delay file (int) */
    out = sf_output("out");

    if(!sf_histint(in, "n1", &n2)) sf_error("n1 needed");
    sf_shiftdim(in, out, 1);


    if(!sf_getint("n1", &n1)) n1=1000; /* samples */
    if(!sf_getfloat("o1", &o1)) o1=0.0; /* sampling interval */
    if(!sf_getfloat("d1", &d1)) d1=0.004; /* original  */
    if((l1=sf_getstring("l1")) == NULL) l1="Time"; /* label "Time" */
    if((u1=sf_getstring("u1")) == NULL) u1="s"; /* unit "s" */

    ax = sf_maxa(n1, o1, d1);
    sf_setlabel(ax, l1);
    sf_setunit(ax, u1);
    sf_oaxa(out, ax, 1);
    sf_putint(out, "n2", n2);
    sf_settype(out, SF_FLOAT);

    v = sf_intalloc(n2);
    u = sf_floatalloc2(n1, n2);
    sf_intread(v, n2, in);

    for(i2=0; i2<n2; i2++)
        for(i1=0; i1<n1; i1++)
            if(i1==v[i2])	u[i2][i1] = 1;
            else u[i2][i1] = 0;

    sf_floatwrite(u[0], n1*n2, out);

    free(v);
    free(u[0]);
    free(u);

    return 0;

}
Example #3
0
int main(int argc, char* argv[])
{
    bool adj, verb;
    int nd, nm, nx, im, min, max, id, i, ix, sx;
    int **indx, *size;
    float *model, *data;
    sf_file inp, index, out;

    sf_init(argc,argv);
  
    if (!sf_getbool("adj",&adj)) adj=true;
    /* adjoint flag */
    if (!sf_getbool("verb",&verb)) verb=false;
    /* verbosity flag */

    inp = sf_input("in");
    if (SF_FLOAT != sf_gettype(inp)) 
	sf_error("Need float input");

    out = sf_output("out");

    index = sf_input("index");
    if (SF_INT != sf_gettype(index)) 
	sf_error("Need int index");

    if (!sf_histint(index,"n1",&nd)) 
	sf_error("No n1= in index");
    nm = sf_leftsize(index,1);

    if (adj) {
	if (nd != sf_filesize(inp)) 
	    sf_error("Wrong data size");
    } else {
	sf_putint(out,"n1",nd);
    }

    data = sf_floatalloc(nd);
    indx = sf_intalloc2(nd,nm);
    size = sf_intalloc(nm);

    sf_intread(indx[0],nd*nm,index);

    nx = 0;
    for (im=0; im < nm; im++) {
	min = max = indx[im][0];
	for (id=1; id < nd; id++) {
	    i = indx[im][id];
	    if (i < min) min=i;
	    if (i > max) max=i;
	}
	if (min) {
	    for (id=0; id < nd; id++) {
		indx[im][id] -= min;
	    }
	}
	size[im]=max-min+1;
	nx += size[im];
	if (verb) sf_warning("size%d=%d",im+1,size[im]);
    }

    if (adj) {
	sf_putint(out,"n1",nx);
    } else {
	if (nx != sf_filesize(inp)) 
	    sf_error("Wrong model size");
    }

    model = sf_floatalloc(nx);
    
    if (adj) {
	sf_floatread(data,nd,inp);
	for (ix=0; ix < nx; ix++) {
	    model[ix] = 0.0f;
	}
    } else {
	sf_floatread(model,nx,inp);
	for (id=0; id < nd; id++) {
	    data[id] = 0.0f;
	}
    }

    sx=0;
    for (im=0; im < nm; im++) {
	for (id=0; id < nd; id++) {
	    ix = indx[im][id]+sx;
	    
	    if (adj) {
		model[ix] += data[id];
	    } else {
		data[id] += model[ix];
	    }
	}
	sx += size[im];
    }

    if (adj) {
	sf_floatwrite(model,nx,out);
    } else {	
	sf_floatwrite(data,nd,out);
    } 
    
    exit(0);
}
Example #4
0
int main (int argc, char* argv[])
{
    int n1,n2,i3,i2,n4,j,n12,fold,ndim, mdim;
    int n[SF_MAX_DIM], m[SF_MAX_DIM], *mk;
    float *d, *sht, *x, mean, std, sum, amp=0.0;
    bool verb;
    sf_file in, out, msk, scl;

    sf_init (argc,argv);
    in  = sf_input("in");
    out = sf_output("out");
    
    if (SF_FLOAT != sf_gettype(in)) sf_error("Need float");
    
    if (!sf_histint(in,"n1",&n1)) sf_error("Need n1=");
    if (!sf_histint(in,"n2",&n2)) sf_error("Need n2=");
    n4 = sf_leftsize(in,2);
    n12=n1*n2;

    if (!sf_getbool("verb",&verb)) verb=false;
    /* verbosity flag */

    /* input file*/
    if (! (sf_getstring("mask") || 
               sf_histstring(in,"mask")))
         sf_error("Need mask=");

    msk = sf_input("mask");
    if (SF_INT != sf_gettype(msk)) sf_error("Need integer mask");

    sf_getfloat("amp",&amp);
    /*Exclude amplitudes greater than amp && less than -amp for statistics computations*/

    ndim = sf_filedims(in,n);
    mdim = sf_filedims(msk,m);

    if (mdim != ndim) 
	sf_error("Wrong dimensions: %d != %d",mdim,ndim);
    
    for (j=0; j < ndim; j++) {
	if (m[j] != n[j])
            sf_error("Size mismatch [n%d]: %d != %d",
		     j+1,m[j],n[j]);
    }

    /* output file*/
    if (NULL != sf_getstring("scaler")){
        scl = sf_output("scaler");
        sf_unshiftdim(in, scl, 2);
        sf_putint(scl,"n1",2);
    } else {
	scl = NULL;
    }
    
    d   = sf_floatalloc(n12*n4);
    x   = sf_floatalloc(2*n4);
    sht = sf_floatalloc(n12);
    mk  = sf_intalloc(n12);
    
    /* loop through time samples */
    for (i3=0; i3 < n4; i3++) {
        mean=0.0;
        fold=0;
        std =0.0;
        sum=0.0;
	sf_floatread(sht,n12,in);
        sf_intread(mk,n12,msk);
        /* compute mean */
	for (i2=0; i2 < n12; i2++) {
           if (sht[i2]!=0.0 && mk[i2]!=0 ) {
                if ( amp==0.0 || fabsf(sht[i2]) < fabsf(amp) ){        
                    sum  +=sht[i2];
                    fold +=1;
                }
           }     
        }
        if (fold > 0) mean=sum/fold;
        
        /* compute standard deviation */
        for (i2=0; i2 < n12; i2++) {
           if (sht[i2]!=0.0 && mk[i2]!=0 ) {
               //if (!(amp && fabsf(sht[i2]) < fabsf(amp)))
               //     continue;
               if ( amp==0.0 || fabsf(sht[i2]) < fabsf(amp) )
                  std += (sht[i2]-mean)*(sht[i2]-mean);
           }     
        }
        if (fold > 0) std =sqrtf(std/(fold-1));
        
        /* scale time samples*/
        for (i2=0; i2 < n12; i2++) 
            if (sht[i2]!=0.0 && mean!=0.0 && std!=0.0)
                d[i2+i3*n12]=(sht[i2]-mean)/std;
            else
                d[i2+i3*n12]=sht[i2];
        x[0+i3*2]=mean;
        x[1+i3*2]=std;

        if (verb) sf_warning("shot %8d-> mean:%8g std:%8g, fold:%8d\n;",i3+1,mean,std,fold);
    }
    sf_floatwrite (d,n4*n12,out);
    if (scl)
       sf_floatwrite (x,n4*2,scl);
    exit(0);
}
Example #5
0
int main(int argc, char* argv[])
{
    /*------------------------------------------------------------*/
    /* Execution control, I/O files and geometry                  */
    /*------------------------------------------------------------*/
    bool verb,fsrf,snap,back,esou; /* execution flags */
    int  jsnap,ntsnap,jdata; /* jump along axes */
    int  shft; /* time shift for wavefield matching in RTM */

    /* I/O files */
    sf_file Fwav=NULL; /* wavelet   */
    sf_file Fdat=NULL; /* data      */
    sf_file Fsou=NULL; /* sources   */
    sf_file Frec=NULL; /* receivers */
    sf_file Fccc=NULL; /* velocity  */
    sf_file Frkp=NULL; /* app. rank */
    sf_file Fltp=NULL; /* left mat  */
    sf_file Frtp=NULL; /* right mat */
    sf_file Fwfp=NULL; /* wavefield */
    sf_file Frks=NULL; /* app. rank */
    sf_file Flts=NULL; /* left mat  */
    sf_file Frts=NULL; /* right mat */
    sf_file Fwfs=NULL; /* wavefield */

    /* cube axes */
    sf_axis at,ax,ay,az; /* time, x, y, z */ 
    sf_axis asx,asy,arx,ary,ac;    /* sou, rec-x, rec-y, component */ 

    /* dimension, index and interval */
    int     nt,nz,nx,ny,ns,nr,nc,nb;
    int     it,iz,ix,iy;
    float   dt,dz,dx,dy;
    int     nxyz, nk;

    /* FDM and KSP structure */ //!!!JS
    fdm3d    fdm=NULL;
    dft3d    dft=NULL;
    clr3d    clr_p=NULL, clr_s=NULL;

    /* I/O arrays for sou & rec */
    sf_complex***ww=NULL;    /* wavelet   */
    pt3d        *ss=NULL;    /* sources   */
    pt3d        *rr=NULL;    /* receivers */
    sf_complex **dd=NULL;    /* data      */

    /*------------------------------------------------------------*/
    /* displacement: uo = U @ t; up = U @ t+1                     */
    /*------------------------------------------------------------*/
    sf_complex ***uox, ***uoy, ***uoz, **uo;
    sf_complex ***uox_p, ***uoy_p, ***uoz_p, **uo_p;
    sf_complex ***uox_s, ***uoy_s, ***uoz_s, **uo_s;
    /*sf_complex ***upx, ***upy, ***upz, **up;*/

    /*------------------------------------------------------------*/
    /* lowrank decomposition arrays                               */
    /*------------------------------------------------------------*/
    int ntmp, *n2s_p, *n2s_s;
    sf_complex **lt_p, **rt_p, **lt_s, **rt_s;

    /*------------------------------------------------------------*/
    /* linear interpolation weights/indices                       */
    /*------------------------------------------------------------*/
    lint3d cs,cr; /* for injecting source and extracting data */

    /* Gaussian bell */
    int nbell;
    
    /*------------------------------------------------------------*/
    /* wavefield cut params                                       */
    /*------------------------------------------------------------*/
    sf_axis   acz=NULL,acx=NULL,acy=NULL;
    int       nqz,nqx,nqy;
    float     oqz,oqx,oqy;
    float     dqz,dqx,dqy;
    sf_complex***uc=NULL; /* tmp array for output wavefield snaps */

    /*------------------------------------------------------------*/
    /* init RSF                                                   */
    /*------------------------------------------------------------*/
    sf_init(argc,argv);

    /*------------------------------------------------------------*/
    /* OMP parameters                                             */
    /*------------------------------------------------------------*/
#ifdef _OPENMP
    omp_init();
#endif

    /*------------------------------------------------------------*/
    /* read execution flags                                       */
    /*------------------------------------------------------------*/
    if(! sf_getbool("verb",&verb)) verb=false; /* verbosity flag */
    if(! sf_getbool("snap",&snap)) snap=false; /* wavefield snapshots flag */
    if(! sf_getbool("free",&fsrf)) fsrf=false; /* free surface flag */
    if(! sf_getbool("back",&back)) back=false; /* backward extrapolation flag (for rtm) */
    if(! sf_getbool("esou",&esou)) esou=false; /* explosive force source */

    /*------------------------------------------------------------*/
    /* I/O files                                                  */
    /*------------------------------------------------------------*/
    Fwav = sf_input ("in" ); /* wavelet   */
    Fdat = sf_output("out"); /* data      */
    Fsou = sf_input ("sou"); /* sources   */
    Frec = sf_input ("rec"); /* receivers */
    Fccc = sf_input ("ccc"); /* stiffness */
    Frkp = sf_input ("rkp"); /* app. rank */
    Fltp = sf_input ("ltp"); /* left mat  */
    Frtp = sf_input ("rtp"); /* right mat */
    Fwfp = sf_output("wfp"); /* wavefield */
    Frks = sf_input ("rks"); /* app. rank */
    Flts = sf_input ("lts"); /* left mat  */
    Frts = sf_input ("rts"); /* right mat */
    Fwfs = sf_output("wfs"); /* wavefield */

    /*------------------------------------------------------------*/
    /* axes                                                       */
    /*------------------------------------------------------------*/
    at = sf_iaxa(Fwav,4); sf_setlabel(at,"t"); if(verb) sf_raxa(at); /* time */
    az = sf_iaxa(Fccc,1); sf_setlabel(az,"z"); if(verb) sf_raxa(az); /* depth */
    ax = sf_iaxa(Fccc,2); sf_setlabel(ax,"x"); if(verb) sf_raxa(ax); /* space x */
    ay = sf_iaxa(Fccc,3); sf_setlabel(ay,"y"); if(verb) sf_raxa(ay); /* space y */

    asx = sf_iaxa(Fsou,2); sf_setlabel(asx,"sx"); if(verb) sf_raxa(asx); /* sources x */
    asy = sf_iaxa(Fsou,3); sf_setlabel(asy,"sy"); if(verb) sf_raxa(asy); /* sources y */
    arx = sf_iaxa(Frec,2); sf_setlabel(arx,"rx"); if(verb) sf_raxa(arx); /* receivers x */
    ary = sf_iaxa(Frec,3); sf_setlabel(ary,"ry"); if(verb) sf_raxa(ary); /* receivers y */

    nt = sf_n(at); dt = sf_d(at);
    nz = sf_n(az); dz = sf_d(az);
    nx = sf_n(ax); dx = sf_d(ax);
    ny = sf_n(ay); dy = sf_d(ay);

    ns = sf_n(asx)*sf_n(asy);
    nr = sf_n(arx)*sf_n(ary);

    /*------------------------------------------------------------*/
    /* other execution parameters                                 */
    /*------------------------------------------------------------*/
    if(! sf_getint("nbell",&nbell)) nbell=NOP;  /* bell size */
    if(verb) sf_warning("nbell=%d",nbell);
    if(! sf_getint("jdata",&jdata)) jdata=1;
    if(snap) {  /* save wavefield every *jsnap* time steps */
	if(! sf_getint("jsnap",&jsnap)) jsnap=nt;
    }
    if(back) {
        shft = (nt-1)%jsnap;
        sf_warning("For backward extrapolation, make sure nbell(%d)=0",nbell);
    } else shft = 0;

    /*------------------------------------------------------------*/
    /* expand domain for FD operators and ABC                     */
    /*------------------------------------------------------------*/
    if( !sf_getint("nb",&nb)) nb=NOP;

    fdm=fdutil3d_init(verb,fsrf,az,ax,ay,nb,1);
    if(nbell) fdbell3d_init(nbell);

    sf_setn(az,fdm->nzpad); sf_seto(az,fdm->ozpad); if(verb) sf_raxa(az);
    sf_setn(ax,fdm->nxpad); sf_seto(ax,fdm->oxpad); if(verb) sf_raxa(ax);
    sf_setn(ay,fdm->nypad); sf_seto(ay,fdm->oypad); if(verb) sf_raxa(ay);

    /*------------------------------------------------------------*/
    /* 3D vector components                                       */
    /*------------------------------------------------------------*/
    nc=3;
    ac=sf_maxa(nc,0,1); /* output 3 cartesian components */

    /*------------------------------------------------------------*/
    /* setup output data header                                   */
    /*------------------------------------------------------------*/
    sf_settype(Fdat,SF_COMPLEX);
    sf_oaxa(Fdat,arx,1);
    sf_oaxa(Fdat,ary,2);
    sf_oaxa(Fdat,ac,3);

    sf_setn(at,nt/jdata);
    sf_setd(at,dt*jdata);
    sf_oaxa(Fdat,at,4);

    /* setup output wavefield header */
    if(snap) {
	if(!sf_getint  ("nqz",&nqz)) nqz=sf_n(az);
	if(!sf_getint  ("nqx",&nqx)) nqx=sf_n(ax);
	if(!sf_getint  ("nqy",&nqy)) nqy=sf_n(ay);

	if(!sf_getfloat("oqz",&oqz)) oqz=sf_o(az);
	if(!sf_getfloat("oqx",&oqx)) oqx=sf_o(ax);
	if(!sf_getfloat("oqy",&oqy)) oqy=sf_o(ay);

	dqz=sf_d(az);
	dqx=sf_d(ax);
	dqy=sf_d(ay);

	acz = sf_maxa(nqz,oqz,dqz); sf_raxa(acz);
	acx = sf_maxa(nqx,oqx,dqx); sf_raxa(acx);
	acy = sf_maxa(nqy,oqy,dqy); sf_raxa(acy);

	uc=sf_complexalloc3(sf_n(acz),sf_n(acx),sf_n(acy));

	ntsnap=0; /* ntsnap = it/jsnap+1; */
	for(it=0; it<nt; it++) {
	    if(it%jsnap==0) ntsnap++;
	}
	sf_setn(at,  ntsnap);
	sf_setd(at,dt*jsnap);
	if(verb) sf_raxa(at);

        sf_settype(Fwfp,SF_COMPLEX);
	sf_oaxa(Fwfp,acz,1);
	sf_oaxa(Fwfp,acx,2);
	sf_oaxa(Fwfp,acy,3);
	sf_oaxa(Fwfp,ac, 4);
	sf_oaxa(Fwfp,at, 5);

        sf_settype(Fwfs,SF_COMPLEX);
	sf_oaxa(Fwfs,acz,1);
	sf_oaxa(Fwfs,acx,2);
	sf_oaxa(Fwfs,acy,3);
	sf_oaxa(Fwfs,ac, 4);
	sf_oaxa(Fwfs,at, 5);
    }

    /*------------------------------------------------------------*/
    /* source and data array                                      */
    /*------------------------------------------------------------*/
    ww=sf_complexalloc3(ns,nc,nt); /* Fast axis: n_sou > n_comp > n_time */
    sf_complexread(ww[0][0],nt*nc*ns,Fwav);

    dd=sf_complexalloc2(nr,nc);

    /*------------------------------------------------------------*/
    /* setup source/receiver coordinates                          */
    /*------------------------------------------------------------*/
    ss = (pt3d*) sf_alloc(ns,sizeof(*ss)); 
    rr = (pt3d*) sf_alloc(nr,sizeof(*rr)); 

    pt3dread1(Fsou,ss,ns,3); /* read (x,y,z) coordinates */
    pt3dread1(Frec,rr,nr,3); /* read (x,y,z) coordinates */

    /* calculate 3d linear interpolation coef for sou & rec */
    cs = lint3d_make(ns,ss,fdm);
    cr = lint3d_make(nr,rr,fdm);

    /*------------------------------------------------------------*/
    /* allocate and initialize wavefield arrays                   */
    /*------------------------------------------------------------*/
    /* z-component */
    uoz=sf_complexalloc3(fdm->nzpad,fdm->nxpad,fdm->nypad);
    uoz_p=sf_complexalloc3(fdm->nzpad,fdm->nxpad,fdm->nypad);
    uoz_s=sf_complexalloc3(fdm->nzpad,fdm->nxpad,fdm->nypad);
    /*upz=sf_complexalloc3(fdm->nzpad,fdm->nxpad,fdm->nypad);*/

    /* x-component */
    uox=sf_complexalloc3(fdm->nzpad,fdm->nxpad,fdm->nypad);
    uox_p=sf_complexalloc3(fdm->nzpad,fdm->nxpad,fdm->nypad);
    uox_s=sf_complexalloc3(fdm->nzpad,fdm->nxpad,fdm->nypad);
    /*upx=sf_complexalloc3(fdm->nzpad,fdm->nxpad,fdm->nypad);*/

    /* y-component */
    uoy=sf_complexalloc3(fdm->nzpad,fdm->nxpad,fdm->nypad);
    uoy_p=sf_complexalloc3(fdm->nzpad,fdm->nxpad,fdm->nypad);
    uoy_s=sf_complexalloc3(fdm->nzpad,fdm->nxpad,fdm->nypad);
    /*upy=sf_complexalloc3(fdm->nzpad,fdm->nxpad,fdm->nypad);*/

    /* wavefield vector */
    uo = (sf_complex**) sf_alloc(3,sizeof(sf_complex*));
    uo[0] = uox[0][0]; uo[1] = uoy[0][0]; uo[2] = uoz[0][0];
    uo_p = (sf_complex**) sf_alloc(3,sizeof(sf_complex*));
    uo_p[0] = uox_p[0][0]; uo_p[1] = uoy_p[0][0]; uo_p[2] = uoz_p[0][0];
    uo_s = (sf_complex**) sf_alloc(3,sizeof(sf_complex*));
    uo_s[0] = uox_s[0][0]; uo_s[1] = uoy_s[0][0]; uo_s[2] = uoz_s[0][0];
    /*up = (sf_complex**) sf_alloc(3,sizeof(sf_complex*));*/
    /*up[0] = upx[0][0]; up[1] = upy[0][0]; up[2] = upz[0][0];*/

    /* initialize fft and lrk */
    dft = dft3d_init(1,false,false,fdm);
    nxyz= fdm->nypad*fdm->nxpad*fdm->nzpad;
    nk  = dft->nky  *dft->nkx  *dft->nkz;

    /*------------------------------------------------------------*/ 
    /* allocation I/O arrays                                      */
    /*------------------------------------------------------------*/ 
    n2s_p = sf_intalloc(9);
    sf_intread(n2s_p,9,Frkp);
    clr_p = clr3d_make2(n2s_p,fdm);

    n2s_s = sf_intalloc(9);
    sf_intread(n2s_s,9,Frks);
    clr_s = clr3d_make2(n2s_s,fdm);

    if (clr_p->n2_max > clr_s->n2_max) clr3d_init(fdm,dft,clr_p);
    else clr3d_init(fdm,dft,clr_s);

    /* check the dimension */
    if (!sf_histint(Fltp,"n1",&ntmp) || ntmp != nxyz)          sf_error("Need n1=%d in left",nxyz);
    if (!sf_histint(Fltp,"n2",&ntmp) || ntmp != clr_p->n2_sum) sf_error("Need n2=%d in left",clr_p->n2_sum);
    if (!sf_histint(Frtp,"n1",&ntmp) || ntmp != nk)            sf_error("Need n1=%d in right",nk);
    if (!sf_histint(Frtp,"n2",&ntmp) || ntmp != clr_p->n2_sum) sf_error("Need n2=%d in right",clr_p->n2_sum);
  
    lt_p = sf_complexalloc2(nxyz,clr_p->n2_sum); 
    rt_p = sf_complexalloc2(nk  ,clr_p->n2_sum); 
    sf_complexread(lt_p[0],nxyz*clr_p->n2_sum,Fltp);
    sf_complexread(rt_p[0],nk  *clr_p->n2_sum,Frtp);

    if (!sf_histint(Flts,"n1",&ntmp) || ntmp != nxyz)          sf_error("Need n1=%d in left",nxyz);
    if (!sf_histint(Flts,"n2",&ntmp) || ntmp != clr_s->n2_sum) sf_error("Need n2=%d in left",clr_s->n2_sum);
    if (!sf_histint(Frts,"n1",&ntmp) || ntmp != nk)            sf_error("Need n1=%d in right",nk);
    if (!sf_histint(Frts,"n2",&ntmp) || ntmp != clr_s->n2_sum) sf_error("Need n2=%d in right",clr_s->n2_sum);

    lt_s = sf_complexalloc2(nxyz,clr_s->n2_sum); 
    rt_s = sf_complexalloc2(nk  ,clr_s->n2_sum); 
    sf_complexread(lt_s[0],nxyz*clr_s->n2_sum,Flts);
    sf_complexread(rt_s[0],nk  *clr_s->n2_sum,Frts);

    /* initialize to zero */
#ifdef _OPENMP
#pragma omp parallel for              \
    schedule(dynamic,1)               \
    private(iy,ix,iz)                 \
    shared(fdm,uoz,uox,uoy,uoz_p,uox_p,uoy_p,uoz_s,uox_s,uoy_s)
#endif
    for        (iy=0; iy<fdm->nypad; iy++) {
	for    (ix=0; ix<fdm->nxpad; ix++) {
	    for(iz=0; iz<fdm->nzpad; iz++) {
		uoz  [iy][ix][iz]=sf_cmplx(0.,0.); uox  [iy][ix][iz]=sf_cmplx(0.,0.); uoy  [iy][ix][iz]=sf_cmplx(0.,0.);
		uoz_p[iy][ix][iz]=sf_cmplx(0.,0.); uox_p[iy][ix][iz]=sf_cmplx(0.,0.); uoy_p[iy][ix][iz]=sf_cmplx(0.,0.);
		uoz_s[iy][ix][iz]=sf_cmplx(0.,0.); uox_s[iy][ix][iz]=sf_cmplx(0.,0.); uoy_s[iy][ix][iz]=sf_cmplx(0.,0.);
		/*upz[iy][ix][iz]=sf_cmplx(0.,0.); upx[iy][ix][iz]=sf_cmplx(0.,0.); upy[iy][ix][iz]=sf_cmplx(0.,0.);*/
	    }
	}
    }

    /*------------------------------------------------------------*/ 
    /*------------------------ MAIN LOOP -------------------------*/ 
    /*------------------------------------------------------------*/
    if(verb) fprintf(stderr,"\n");
    for (it=0; it<nt; it++) {
        if(verb) sf_warning("it=%d/%d;",it,nt); /*fprintf(stderr,"\b\b\b\b\b%d",it);*/

	/*------------------------------------------------------------*/
	/* apply lowrank matrix to wavefield vector                   */
        /*------------------------------------------------------------*/
        clr3d_apply(uo_p, uo, lt_p, rt_p, fdm, dft, clr_p);
        clr3d_apply(uo_s, uo, lt_s, rt_s, fdm, dft, clr_s);

	/*------------------------------------------------------------*/
        /* combine P and S wave modes                                 */
        /*------------------------------------------------------------*/
#ifdef _OPENMP
#pragma omp parallel for              \
        schedule(dynamic,1)               \
        private(iy,ix,iz)                 \
        shared(fdm,uoz,uox,uoy,uoz_p,uox_p,uoy_p,uoz_s,uox_s,uoy_s)
#endif
        for        (iy=0; iy<fdm->nypad; iy++) {
            for    (ix=0; ix<fdm->nxpad; ix++) {
                for(iz=0; iz<fdm->nzpad; iz++) {
                    uoz[iy][ix][iz] = uoz_p[iy][ix][iz] + uoz_s[iy][ix][iz];
                    uox[iy][ix][iz] = uox_p[iy][ix][iz] + uox_s[iy][ix][iz];
                    uoy[iy][ix][iz] = uoy_p[iy][ix][iz] + uoy_s[iy][ix][iz];
                    /*upz[iy][ix][iz]=sf_cmplx(0.,0.); upx[iy][ix][iz]=sf_cmplx(0.,0.); upy[iy][ix][iz]=sf_cmplx(0.,0.);*/
                }
            }
        }

	/*------------------------------------------------------------*/
	/* free surface */
	/*------------------------------------------------------------*/
	if(fsrf) { /* need to do something here */ }

        /*------------------------------------------------------------*/
	/* inject displacement source                                 */
	/*------------------------------------------------------------*/
        if(esou) {
            /* exploding force source */
            lint3d_expl_complex(uoz,uox,uoy,ww[it],cs);
        } else {
            if(nbell) {
                lint3d_bell_complex(uoz,ww[it][0],cs);
                lint3d_bell_complex(uox,ww[it][1],cs);
                lint3d_bell_complex(uoy,ww[it][2],cs);
            } else {
                lint3d_inject_complex(uoz,ww[it][0],cs);
                lint3d_inject_complex(uox,ww[it][1],cs);
                lint3d_inject_complex(uoy,ww[it][2],cs);
            }
        }

	/*------------------------------------------------------------*/
	/* cut wavefield and save */
	/*------------------------------------------------------------*/
        if(snap && (it-shft)%jsnap==0) {
            /* P wave */
            cut3d_complex(uoz_p,uc,fdm,acz,acx,acy);
            sf_complexwrite(uc[0][0],sf_n(acx)*sf_n(acy)*sf_n(acz),Fwfp);

            cut3d_complex(uox_p,uc,fdm,acz,acx,acy);
            sf_complexwrite(uc[0][0],sf_n(acx)*sf_n(acy)*sf_n(acz),Fwfp);

            cut3d_complex(uoy_p,uc,fdm,acz,acx,acy);
            sf_complexwrite(uc[0][0],sf_n(acx)*sf_n(acy)*sf_n(acz),Fwfp);

            /* S wave */
            cut3d_complex(uoz_s,uc,fdm,acz,acx,acy);
            sf_complexwrite(uc[0][0],sf_n(acx)*sf_n(acy)*sf_n(acz),Fwfs);

            cut3d_complex(uox_s,uc,fdm,acz,acx,acy);
            sf_complexwrite(uc[0][0],sf_n(acx)*sf_n(acy)*sf_n(acz),Fwfs);

            cut3d_complex(uoy_s,uc,fdm,acz,acx,acy);
            sf_complexwrite(uc[0][0],sf_n(acx)*sf_n(acy)*sf_n(acz),Fwfs);
        }

        lint3d_extract_complex(uoz,dd[0],cr);
        lint3d_extract_complex(uox,dd[1],cr);
        lint3d_extract_complex(uoy,dd[2],cr);
        if(it%jdata==0) sf_complexwrite(dd[0],nr*nc,Fdat);

    }
    if(verb) sf_warning(".");
    if(verb) fprintf(stderr,"\n");    
    
    /*------------------------------------------------------------*/
    /* deallocate arrays */
    
    free(dft);
    dft3d_finalize();
    free(clr_p); free(clr_s);
    clr3d_finalize();

    free(**ww); free(*ww); free(ww);
    free(ss);
    free(rr);
    free(*dd);  free(dd);

    free(n2s_p); free(n2s_s);
    free(*lt_p); free(lt_p); free(*rt_p); free(rt_p);
    free(*lt_s); free(lt_s); free(*rt_s); free(rt_s);

    free(**uoz  ); free(*uoz  ); free(uoz)  ;
    free(**uoz_p); free(*uoz_p); free(uoz_p);
    free(**uoz_s); free(*uoz_s); free(uoz_s);
    /*free(**upz); free(*upz); free(upz);*/
    free(uo); free(uo_p); free(uo_s);
    /*free(up);*/

    if (snap) {
       free(**uc);  free(*uc);  free(uc);    
    }

    /*------------------------------------------------------------*/


    exit (0);
}
Example #6
0
int main(int argc, char* argv[])
{
    bool verb;
    int n[SF_MAX_DIM], m[SF_MAX_DIM], rect[SF_MAX_DIM];
    int ndim, mdim, nd, ns, n12, i, j, niter, na, ia, i4, n4=1;
    float *d, *f, *g, mean, a0;
    char key[6], *peffile, *lagfile;
    sf_filter aa;
    sf_file dat, flt, mat, pre, pef, lag;

    sf_init(argc,argv);

    dat = sf_input("in");
    mat = sf_input("match");
    flt = sf_output("out");

    if (NULL != sf_getstring("pred")) {
	pre = sf_output("pred");
    } else {
	pre = NULL;
    }

    ndim = 3;
    mdim = 2;


    if (!sf_histint(dat,"n1",&n[0])) sf_error("No n1= in input");
    if (!sf_histint(dat,"n2",&n[1])) sf_error("No n2= in input");
    if (!sf_histint(dat,"n3",&n[2])) sf_error("No n3= in input");
    n[3] = sf_leftsize(dat,3);

    if (!sf_histint(mat,"n1",&m[0])) sf_error("No n1= in match");
    if (!sf_histint(mat,"n2",&m[1])) sf_error("No n2= in match");
    m[2] = sf_leftsize(mat,2);

    if (mdim > ndim) 
	sf_error("Wrong dimensions: %d > %d",mdim,ndim);
 
    if (m[2] != n[3]) {
	sf_error("Size mismatch [n%d] : %d != %d",3,m[2],n[3]);
    } else {
	n4 = n[3];
    }

    nd = 1;
    for (j=0; j < mdim; j++) {
	if (m[j] != n[j]) 
	    sf_error("Size mismatch [n%d]: %d != %d",
		     j+1,m[j],n[j]);
	nd *= m[j];
	snprintf(key,6,"rect%d",j+1);
	if (!sf_getint(key,rect+j)) rect[j]=1;
    }
    for (ns = 1; j < ndim; j++) {
	ns *= n[j];
	if (pre) {
	    snprintf(key,6,"n%d",j+1);
	    sf_putint(pre,key,n4);
	    snprintf(key,6,"n%d",j+2);
	    sf_putint(pre,key,1);
	}
    }
    n12 = nd*ns;

    if (!sf_getint("niter",&niter)) niter=100;
    /* number of iterations */

    if (!sf_getbool("verb",&verb)) verb=true;
    /* verbosity flag */

    if (NULL == (peffile = sf_getstring("pef"))) { 
        /* signal PEF file (optional) */
	aa = NULL;
    } else {
	pef = sf_input(peffile);
	if (!sf_histint(pef,"n1",&na)) 
	    sf_error("No n1= in pef");
	aa = sf_allocatehelix (na);
	
	if (!sf_histfloat(pef,"a0",&a0)) a0=1.;
	sf_floatread (aa->flt,na,pef);
	for( ia=0; ia < na; ia++) {
	    aa->flt[ia] /= a0;
	}
	if (NULL != (lagfile = sf_getstring("lag")) 
	    || 
	    NULL != (lagfile = sf_histstring(pef,"lag"))) {
            /* file with PEF lags (optional) */
	    lag = sf_input(lagfile);
	    sf_intread(aa->lag,na,lag);
	    sf_fileclose(lag);
	} else {
	    for( ia=0; ia < na; ia++) {
		aa->lag[ia] = ia+1;
	    }
	}
    }

    d = sf_floatalloc(n12);
    f = sf_floatalloc(n12);
    g = sf_floatalloc(nd);

    for(i4=0; i4 < n4; i4++) {
	fprintf(stderr,"slice %d of %d\n",i4+1,n4);	
	for (i=0; i < n12; i++) {
	    d[i] = 0.;
	}
	sf_multidivn_init(ns, mdim, nd, m, rect, d, aa, verb); 
    
	sf_floatread(d,n12,dat);
	sf_floatread(g,nd,mat);

	mean = 0.;
	for(i=0; i < n12; i++) {
	    mean += d[i]*d[i];
	}
	if (mean == 0.) {
	    sf_floatwrite(d,n12,flt);
	    continue;
	}
	
	mean = sqrtf (mean/n12);
	
	for(i=0; i < n12; i++) {
	    d[i] /= mean;
	}
	for(i=0; i < nd; i++) {
	    g[i] /= mean;
	}
	
	sf_multidivn (g,f,niter);
	sf_floatwrite(f,n12,flt);
	
	if (pre) {
	    for(i=0; i < n12; i++) {
		d[i] *= mean;
	    }
	    
	    sf_weight2_lop(false,false,n12,nd,f,g);
	    sf_floatwrite(g,nd,pre);
	}
    }
    
    exit(0);
}
Example #7
0
int main(int argc, char* argv[])
{
    bool velocity, verb, shape;
    int dim, i, j, n[3], rect[3], it, nt, order, nt0, nx0;
    int iter, niter, iline, nline, cgiter, *f0, *m0=NULL;
    float d[3], o[3], dt0, dx0, ot0, ox0, eps, tol, *p=NULL, *p0=NULL, thres;
    float *vd, *vdt, *vdx, *s, *t0, *x0, *ds, *rhs, *rhs0, *rhs1=NULL, error0, error1, error, scale;
    char key[6];
    sf_file in, out, dix, t_0=NULL, x_0=NULL, f_0=NULL, grad=NULL, cost=NULL, mini=NULL, prec=NULL;

    sf_init(argc,argv);
    in = sf_input("in");
    out = sf_output("out");

    /* read input dimension */
    dim = sf_filedims(in,n);

    nt = 1;
    for (i=0; i < dim; i++) {
	sprintf(key,"d%d",i+1);
	if (!sf_histfloat(in,key,d+i)) sf_error("No %s= in input",key);
	sprintf(key,"o%d",i+1);
	if (!sf_histfloat(in,key,o+i)) o[i]=0.;
	nt *= n[i];
    }
    if (dim < 3) {
	n[2] = 1; d[2] = d[1]; o[2] = o[1];
    }

    /* read initial guess */
    s = sf_floatalloc(nt);
    sf_floatread(s,nt,in);

    if (!sf_getbool("velocity",&velocity)) velocity=true;
    /* y, input is velocity / n, slowness-squared */

    if (velocity) {
	for (it=0; it < nt; it++) {
	    s[it] = 1./s[it]*1./s[it];
	}
    }

    /* read Dix velocity */
    if (NULL == sf_getstring("dix")) sf_error("No Dix input dix=");
    dix = sf_input("dix");

    if(!sf_histint(dix,"n1",&nt0)) sf_error("No n1= in dix");
    if(!sf_histint(dix,"n2",&nx0)) sf_error("No n2= in dix");
    if(!sf_histfloat(dix,"d1",&dt0)) sf_error("No d1= in dix");
    if(!sf_histfloat(dix,"d2",&dx0)) sf_error("No d2= in dix");
    if(!sf_histfloat(dix,"o1",&ot0)) sf_error("No o1= in dix");
    if(!sf_histfloat(dix,"o2",&ox0)) sf_error("No o2= in dix");

    vd = sf_floatalloc(nt0*nx0);
    sf_floatread(vd,nt0*nx0,dix);
    sf_fileclose(dix);

    /* Dix velocity derivative in t0 (2nd order FD) */
    vdt = sf_floatalloc(nt0*nx0);
    for (i=0; i < nt0; i++) {
	for (j=0; j < nx0; j++) {
	    if (i == 0)
		vdt[j*nt0+i] = (-vd[j*nt0+i+2]+4.*vd[j*nt0+i+1]-3.*vd[j*nt0+i])/(2.*dt0);
	    else if (i == nt0-1)
		vdt[j*nt0+i] = (3.*vd[j*nt0+i]-4.*vd[j*nt0+i-1]+vd[j*nt0+i-2])/(2.*dt0);
	    else
		vdt[j*nt0+i] = (vd[j*nt0+i+1]-vd[j*nt0+i-1])/(2.*dt0);
	}
    }

    /* Dix velocity derivative in x0 (2nd order FD) */
    vdx = sf_floatalloc(nt0*nx0);
    for (j=0; j < nx0; j++) {
	for (i=0; i < nt0; i++) {
	    if (j == 0)
		vdx[j*nt0+i] = (-vd[(j+2)*nt0+i]+4.*vd[(j+1)*nt0+i]-3.*vd[j*nt0+i])/(2.*dx0);
	    else if (j == nx0-1)
		vdx[j*nt0+i] = (3.*vd[j*nt0+i]-4.*vd[(j-1)*nt0+i]+vd[(j-2)*nt0+i])/(2.*dx0);
	    else
		vdx[j*nt0+i] = (vd[(j+1)*nt0+i]-vd[(j-1)*nt0+i])/(2.*dx0);
	}
    }

    if (!sf_getint("order",&order)) order=1;
    /* fastmarch accuracy order */

    if (!sf_getfloat("thres",&thres)) thres=10.;
    /* thresholding for caustics */

    if (!sf_getint("niter",&niter)) niter=1;
    /* number of nonlinear updates */

    if (!sf_getint("cgiter",&cgiter)) cgiter=200;
    /* number of CG iterations */

    if (!sf_getbool("shape",&shape)) shape=false;
    /* regularization (default Tikhnov) */

    if (!sf_getfloat("eps",&eps)) eps=0.1;
    /* regularization parameter */

    if (!sf_getint("nline",&nline)) nline=0;
    /* maximum number of line search (default turned-off) */

    if (!sf_getbool("verb",&verb)) verb=false;
    /* verbosity flag */

    if (shape) {
	if (!sf_getfloat("tol",&tol)) tol=1.e-6;
	/* tolerance for shaping regularization */

	for (i=0; i < dim; i++) {
	    sprintf(key,"rect%d",i+1);
	    if (!sf_getint(key,rect+i)) rect[i]=1;
	    /*( rect#=(1,1,...) smoothing radius on #-th axis )*/
	}
	
	/* triangle smoothing operator */
	sf_trianglen_init(dim,rect,n);
	sf_repeat_init(nt,1,sf_trianglen_lop);
	
	sf_conjgrad_init(nt,nt,nt,nt,eps,tol,verb,false);
	p = sf_floatalloc(nt);
    } else {
	/* initialize 2D gradient operator */
	sf_igrad2_init(n[0],n[1]);
    }
    
    /* allocate memory for fastmarch */
    t0 = sf_floatalloc(nt);
    x0 = sf_floatalloc(nt);
    f0 = sf_intalloc(nt);

    /* allocate memory for update */
    ds  = sf_floatalloc(nt);
    rhs = sf_floatalloc(nt);

    /* output transformation matrix */
    if (NULL != sf_getstring("t0")) {
	t_0 = sf_output("t0");
	sf_putint(t_0,"n3",niter+1);
    }
    if (NULL != sf_getstring("x0")) {
	x_0 = sf_output("x0");
	sf_putint(x_0,"n3",niter+1);
    }

    /* output auxiliary label */
    if (NULL != sf_getstring("f0")) {
	f_0 = sf_output("f0");
	sf_settype(f_0,SF_INT);
	sf_putint(f_0,"n3",niter+1);
    }

    /* output gradient */
    if (NULL != sf_getstring("grad")) {
	grad = sf_output("grad");
	sf_putint(grad,"n3",niter);
    }

    /* output cost */
    if (NULL != sf_getstring("cost")) {
	cost = sf_output("cost");
	sf_putint(cost,"n3",niter+1);
    }

    /* read mask (desired minimum) */
    m0 = sf_intalloc(nt);

    if (NULL != sf_getstring("mask")) {
	mini = sf_input("mask");
	sf_intread(m0,nt,mini);
	sf_fileclose(mini);
    } else {
	for (it=0; it < nt; it++) m0[it] = -1;
    }

    /* read cost (desired minimum) */
    rhs0 = sf_floatalloc(nt);

    if (NULL != sf_getstring("mval")) {
	mini = sf_input("mval");
	sf_floatread(rhs0,nt,mini);
	sf_fileclose(mini);
    } else {
	for (it=0; it < nt; it++) rhs0[it] = 0.;
    }

    /* read preconditioner */
    if (NULL != sf_getstring("prec")) {
	prec = sf_input("prec");
	p0 = sf_floatalloc(nt);
	sf_floatread(p0,nt,prec);
	sf_fileclose(prec);

	rhs1 = sf_floatalloc(nt);
    }

    /* fastmarch initialization */
    fastmarch_init(n,o,d,order);

    /* update initialization */
    t2d_init(dim,n,d,nt0,dt0,ot0,nx0,dx0,ox0);

    /* fastmarch */
    fastmarch(t0,x0,f0,s);

    /* caustic region (2D) */
    t2d_caustic(x0,f0,n,d,thres);

    /* set up operator */
    t2d_set(t0,x0,f0,s,vd,vdt,vdx,m0,p0);

    /* evaluate cost */
    t2d_cost(rhs);

    for (it=0; it < nt; it++) {
	if (f0[it] >= 0 || m0[it] >= 0)
	    rhs[it] = 0.;
	else
	    rhs[it] -= rhs0[it];
    }

    if (p0 == NULL) {
	error0 = error1 = cblas_snrm2(nt,rhs,1);
    } else {
	for (it=0; it < nt; it++) rhs1[it] = p0[it]*rhs[it];
	error0 = error1 = cblas_snrm2(nt,rhs1,1);
    }

    /* write optional outputs */    
    if (NULL!=t_0)  sf_floatwrite(t0,nt,t_0);
    if (NULL!=x_0)  sf_floatwrite(x0,nt,x_0);
    if (NULL!=f_0)  sf_intwrite(f0,nt,f_0);
    if (NULL!=cost) sf_floatwrite(rhs,nt,cost);

    sf_warning("Start conversion, cost %g",1.);

    /* nonlinear loop */
    for (iter=0; iter < niter; iter++) {
	
	/* solve ds */
	if (shape) {
	    if (p0 == NULL)
		sf_conjgrad(NULL,t2d_oper,sf_repeat_lop,p,ds,rhs,cgiter);
	    else
		sf_conjgrad(t2d_prec,t2d_oper,sf_repeat_lop,p,ds,rhs,cgiter);
	} else {
	    sf_solver_reg(t2d_oper,sf_cgstep,sf_igrad2_lop,2*nt,nt,nt,ds,rhs,cgiter,eps,"verb",verb,"end");
	    sf_cgstep_close();
	}

	/* add ds */
	for (it=0; it < nt; it++) {
	    s[it] = s[it]+ds[it]+0.25*ds[it]*ds[it]/s[it];
	}

	/* fastmarch */
	fastmarch(t0,x0,f0,s);

	/* caustic region (2D) */
	t2d_caustic(x0,f0,n,d,thres);

	/* set up operator */
	t2d_set(t0,x0,f0,s,vd,vdt,vdx,m0,p0);

	/* evaluate cost */
	t2d_cost(rhs);

	for (it=0; it < nt; it++) {
	    if (f0[it] >= 0 || m0[it] >= 0)
		rhs[it] = 0.;
	    else
		rhs[it] -= rhs0[it];
	}
	
	if (p0 == NULL) {
	    error = cblas_snrm2(nt,rhs,1);
	} else {
	    for (it=0; it < nt; it++) rhs1[it] = p0[it]*rhs[it];
	    error = cblas_snrm2(nt,rhs1,1);
	}

	error = cblas_snrm2(nt,rhs,1);

	/* line search */
	if (nline > 0 && error >= error1) {

	    scale = 0.5;
	    for (iline=0; iline < nline; iline++) {

		for (it=0; it < nt; it++) {
		    s[it] = s[it]+(scale*ds[it])+0.25*(scale*ds[it])*(scale*ds[it])/s[it];
		}
		
		fastmarch(t0,x0,f0,s);
		t2d_caustic(x0,f0,n,d,thres);

		t2d_set(t0,x0,f0,s,vd,vdt,vdx,m0,p0);
		t2d_cost(rhs);

		for (it=0; it < nt; it++) {
		    if (f0[it] >= 0 || m0[it] >= 0)
			rhs[it] = 0.;
		    else
			rhs[it] -= rhs0[it];
		}
		
		if (p0 == NULL) {
		    error = cblas_snrm2(nt,rhs,1);
		} else {
		    for (it=0; it < nt; it++) rhs1[it] = p0[it]*rhs[it];
		    error = cblas_snrm2(nt,rhs1,1);
		}
		
		error = cblas_snrm2(nt,rhs,1);
		if (error < error1) {
		    sf_warning("Exist line search %d of %d",iline+1,nline);
		} else {
		    scale *= 0.5;
		}
	    }
	}

	error1 = error;

	/* write optional outputs */
	if (NULL!=t_0)  sf_floatwrite(t0,nt,t_0);
	if (NULL!=x_0)  sf_floatwrite(x0,nt,x_0);
	if (NULL!=f_0)  sf_intwrite(f0,nt,f_0);
	if (NULL!=cost) sf_floatwrite(rhs,nt,cost);
	if (NULL!=grad) sf_floatwrite(ds,nt,grad);

	sf_warning("Cost after iteration %d: %g",iter+1,error/error0);
    }

    /* write output */
    if (velocity) {
	for (it=0; it < nt; it++) {
	    s[it] = 1./sqrtf(s[it]);
	}
    }

    sf_floatwrite(s,nt,out);

    exit(0);
}
Example #8
0
int main(int argc, char* argv[]) 
{
    int i, n, nbuf;
    int glob_i = 0;   /* Global counter in file */
    int   *ibuf=NULL; /* Input reading buffer */
    float *fbuf=NULL; /* Input reading buffer */
    sf_file in=NULL;
    bool float_inp=false, int_inp=false; /* Input flags */
    sf_datatype inp_type; /* Input data type */
    int i_fac;     /* Integer division factor */
    float f_fac; /* Non-integer division factor */ 
    bool istat; /* Return value of CLI read function */

    sf_init(argc,argv);
    in = sf_input("in");
    inp_type = sf_gettype(in);
    n = sf_filesize(in);

    istat = sf_getint ("i_fac",&i_fac);
    
    if (inp_type == SF_FLOAT) {
        float_inp = true;
        nbuf = BUFSIZ/sizeof(float);
        fbuf = sf_floatalloc(nbuf);
        if (!istat) {
            if (!sf_getfloat("f_fac",&f_fac)) \
                sf_error("Need either i_fac= or f_fac=");
        }
        else f_fac = i_fac;
    }
    else if (inp_type == SF_INT) {
        int_inp = true;
        nbuf = BUFSIZ/sizeof(int);
        ibuf = sf_intalloc(nbuf);
        if (!istat) sf_error("Need i_fac=");
    }
    else sf_error("Need float or int input");

    /* Duplicating boilerplate code to avoid conditionals inside loops */

    if (float_inp) {

        for (; n > 0; n -= nbuf) {

            if (nbuf > n) nbuf = n;

            sf_floatread(fbuf, nbuf, in);

            for (i=0; i < nbuf; i++) {
                glob_i++;
                if (0 != fmod(fbuf[i],f_fac)) \
                    sf_error("Mismatch at element %d", glob_i);
            }
        }
    }

    else if (int_inp) {

        for (; n > 0; n -= nbuf) {

            if (nbuf > n) nbuf = n;

            sf_intread(ibuf, nbuf, in);

            for (i=0; i < nbuf; i++) {
                glob_i++;
                if (0 != (ibuf[i] % i_fac )) \
                    sf_error("Mismatch at element %d", glob_i);
            }
        }
    }


    exit(0);
}
Example #9
0
int main(int argc, char* argv[])
{
    bool inv, adj, linear, kn;
    int n1, n2, na, i1, i2, ia, *mask;
    float dd, da, dn, rn, eps;
    float *d, *a, *r, *d2, *r2;
    sf_file inp, pef, out, pat, known;

    sf_init(argc,argv);
    inp = sf_input("in");
    out = sf_output("out");

    if (!sf_getbool("inv",&inv)) inv=false;
    /* inversion flag */

    if (!sf_getbool("adj",&adj)) adj=false;
    /* adjoint flag (for linear operator) */

    if (SF_FLOAT != sf_gettype(inp)) sf_error("Need float input");
    if (!sf_histint(inp,"n1",&n1)) sf_error("No n1= in input");
    n2 = sf_leftsize(inp,1);

    if (!sf_getint("na",&na)) sf_error("Need na=");
    /* PEF filter size (not including leading one) */
    if (na > n1) sf_error("Cannot handle na > n1");

    if (!sf_getfloat("eps",&eps)) sf_error("Need eps=");
    /* regularization */
    eps *= eps;

    d = sf_floatalloc(n1);
    r = sf_floatalloc(n1);
    a = sf_floatalloc(na);

    linear = (NULL != sf_getstring("pattern"));
    /* pattern data (for linear operator) */

    if (linear) {
	pat = sf_input("pattern");
	d2  = sf_floatalloc(n1);
	r2  = sf_floatalloc(n1);
    } else {
	pat = inp;
	d2 = NULL;
	r2 = NULL;
    }

    if (NULL != sf_getstring("pef")) {
	/* output PEF (optional) */
	pef = sf_output("pef");
	sf_putint(pef,"n1",na);
	sf_putint(pef,"n2",n1);
	sf_putint(pef,"n3",n2);
    } else {
	pef = NULL;
    }

    if (NULL != sf_getstring("known")) {
	/* known data locations (optional) */
	known = sf_input("known");
	if (SF_INT != sf_gettype(known)) sf_error("Need int type in known");
	mask = sf_intalloc(n1);
    } else {
	known = NULL;
    }

    for (i2=0; i2 < n2; i2++) {
	sf_floatread(inv? r: d,n1,pat);
	if (NULL != known) sf_intread(mask,n1,known);

	if (linear)  {
	    if (adj) {
		sf_floatread(r2,n1,inp);
		for (i1=0; i1 < n1; i1++) {
		    d2[i1] = 0.0f;
		}
	    } else {
		sf_floatread(d2,n1,inp);
	    }
	}

	dd = 0.0f;
	da = 0.0f;
	for (ia=0; ia < na; ia++) {
	    a[ia]=0.0f;
	    if (inv) {
		d[ia] = r[ia];
	    } else {
		r[ia] = d[ia];
	    }
	    dd += d[ia]*d[ia];
	}

	if (linear) {
	    for (ia=0; ia < na; ia++) {
		if (adj) {
		    d2[ia] = r2[ia];
		} else {
		    r2[ia] = d2[ia];
		}
	    }
	}

	if (NULL != pef) {
	    for (ia=0; ia < na; ia++) {
		sf_floatwrite(a,na,pef);
	    }
	}
	
	for (i1=na; i1 < n1; i1++) {
	    kn = (NULL == known) || (1==mask[i1]);

	    if (inv) {
		rn = kn? r[i1]/eps: 0.0f;
		dn = rn*(eps+dd)-da;
		d[i1] = dn;
	    } else {
		dn = kn? d[i1]: -da;
		rn = (dn+da)/(eps+dd);
		r[i1] = eps*rn;
	    }

	    for (ia=0; ia < na; ia++) {
		a[ia] -= rn*d[i1-1-ia];
	    }

	    if (NULL != pef) sf_floatwrite(a,na,pef);

	    dd += dn*dn - d[i1-na]*d[i1-na];	    
	    da = dn*a[0];
	    for (ia=1; ia < na; ia++) {
		da += a[ia]*d[i1-ia];
	    }

	    if (linear) {
		if (adj) {
		    d2[i1] += r2[i1];
		    for (ia=0; ia < na; ia++) {
			d2[i1-1-ia] += a[ia]*r2[i1];
		    }
		} else {
		    r2[i1] = d2[i1];
		    for (ia=0; ia < na; ia++) {
			r2[i1] += a[ia]*d2[i1-1-ia];
		    }
		}
	    }
	}

	if (linear) {
	    sf_floatwrite(adj? d2: r2,n1,out);
	} else {	
	    sf_floatwrite(inv? d: r,n1,out);
	}
    }

    exit(0);
}
Example #10
0
/* main function */
int main(int argc, char* argv[])
{
    clock_t tstart,tend;
    double duration;

    /*flags*/
    bool verb, adj; /* migration(adjoint) flag */
    bool wantwf; /* outputs wavefield snapshots */
    bool wantrecord; /* actually means "need record" */
    bool illum; /* source illumination flag */
    bool roll; /* survey strategy */
    bool fm; /* forward modeling */

    /*I/O*/
    sf_file Fvel;
    sf_file left, right, leftb, rightb;
    sf_file Fsrc, Frcd/*source and record*/;
    sf_file Ftmpwf;
    sf_file Fimg;
    sf_file mask;

    /*axis*/
    sf_axis at, ax, az, as;

    /*grid index variables*/
    int nx, nz, nt, wfnt;
    int nzx, nx2, nz2, n2, m2, pad1, nk;
    int ix, iz, it, is;
    int nxb, nzb;
    int snpint, wfint;
    float dt, dx, dz, wfdt;
    float ox, oz;

    /*source/geophone location*/
    int   spx, spz;
    int   gpz,gpx,gpl; /*geophone depth/x-crd/length*/

    /*Model*/
    sf_complex **lt, **rt;
    sf_complex **ltb, **rtb;

    /*Data*/
    sf_complex ***wavefld;
    sf_complex ***record, **tmprec, **img, **imgsum;
    float **sill;

    /*source*/
    sf_complex *ww;
    float **rr;
    int **kill=NULL;
    int rectz,rectx,repeat; /*smoothing parameters*/
    float trunc;
    int sht0,shtbgn,shtend,shtnum,shtint;

    /*abc boundary*/
    int top,bot,lft,rht;

    /*tmp*/
    int tmpint;

    /*parameter structs*/
    geopar geop;
    mpipar mpip;

    /*MPI*/
    int rank, nodes;
    sf_complex *sendbuf, *recvbuf;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &nodes);

    sf_init(argc, argv);

    if(rank==0) sf_warning("nodes=%d",nodes);

    if (!sf_getbool("verb", &verb)) verb=false; /*verbosity*/
    if (!sf_getbool("adj", &adj)) adj=true; /*migration*/
    if (!sf_getbool("wantwf", &wantwf)) wantwf=false; /*output forward and backward wavefield*/
    if (!sf_getbool("wantrecord", &wantrecord)) wantrecord=true; /*if n, using record data generated by this program */
    if (!sf_getbool("illum", &illum)) illum=false; /*if n, no source illumination applied */
    if (!sf_getbool("roll", &roll)) roll=true; /*if n, receiver is independent of source location and gpl=nx*/
    if (!sf_getbool("fm", &fm)) fm=false; /* if n, Born modelling  */
    if (!sf_getbool("incom", &incom)) incom=false; /* if n, use complete data */
    /* source/receiver info */
    if (!sf_getint("shtbgn", &shtbgn)) sf_error("Need shot starting location on grid!");
    if (!sf_getint("sht0", &sht0)) sht0=shtbgn; /*actual shot origin on grid*/
    if (!sf_getint("shtend", &shtend)) sf_error("Need shot ending location on grid!");
    if (!sf_getint("shtint", &shtint)) sf_error("Need shot interval on grid!");
    shtnum = (int)((shtend-shtbgn)/shtint) + 1;
    if (!sf_getint("spz", &spz)) sf_error("Need source depth!");
    if (!sf_getint("gpz", &gpz)) sf_error("Need receiver depth!");
    if (roll) if (!sf_getint("gpl", &gpl)) sf_error("Need receiver length");
    if (!sf_getint("snapinter", &snpint)) snpint=1;     /* snap interval */
    if (!sf_getint("wfint", &wfint)) wfint=50;     /* snap interval */
    /*--- parameters of source ---*/
    if (!sf_getfloat("srctrunc", &trunc)) trunc=0.4;
    if (!sf_getint("rectz", &rectz)) rectz=2;
    if (!sf_getint("rectx", &rectx)) rectx=2;
    if (!sf_getint("repeat", &repeat)) repeat=2;
    /* abc parameters */
    if (!sf_getint("top", &top)) top=40;
    if (!sf_getint("bot", &bot)) bot=40;
    if (!sf_getint("lft", &lft)) lft=40;
    if (!sf_getint("rht", &rht)) rht=40;
    /* simultaneous sources parameter */
    if (!sf_getint("nsource", &nsource)) nsource=1;
    if (!sf_getint("dsource", &dsource)) dsource=0;
    if (!sf_getfloat("tdelay", &tdelay)) tdelay=0;
    if (!sf_getint("choose", &choose)) choose=nsource;

    /*Set I/O file*/
    if (adj) { /* migration */
        if (wantrecord) {
            Frcd = sf_input("input"); /*record from elsewhere*/
            Fsrc  = sf_input("src");   /*source wavelet*/
        } else {
            Frcd = sf_output("rec"); /*record produced by forward modeling*/
            Fsrc = sf_input("input");   /*source wavelet*/
        }

        Fimg  = sf_output("output");
    } else { /* modeling */
        Fimg = sf_input("input");
        Frcd = sf_output("output");
        Fsrc  = sf_input("src");   /*source wavelet*/
    }

    left  = sf_input("left");
    right = sf_input("right");
    leftb  = sf_input("leftb");
    rightb = sf_input("rightb");
    Fvel  = sf_input("vel");  /*velocity - just for model dimension*/
    if (wantwf) {
        Ftmpwf  = sf_output("tmpwf");/*wavefield snap*/
    }
    if (incom) {
        mask=sf_input("mask"); /*mask operator*/
    }

    /*--- Axes parameters ---*/
    at = sf_iaxa(Fsrc, 1);
    nt = sf_n(at);
    dt = sf_d(at);
    az = sf_iaxa(Fvel, 1);
    nzb = sf_n(az);
    dz = sf_d(az);
    oz = sf_o(az);
    ax = sf_iaxa(Fvel, 2);
    nxb = sf_n(ax);
    dx = sf_d(ax);
    ox = sf_o(ax);
    nzx = nzb*nxb;
    nz = nzb - top - bot;
    nx = nxb - lft - rht;
    if (!roll) gpl = nx; /* global survey setting */
    /* wavefield axis */
    wfnt = (int)(nt-1)/snpint+1;
    wfdt = dt*snpint;
    ndelay=tdelay/dt;

    /* propagator matrices */
    if (!sf_getint("pad1",&pad1)) pad1=1; /* padding factor on the first axis */
    nz2 = kiss_fft_next_fast_size(nzb*pad1);
    nx2 = kiss_fft_next_fast_size(nxb);
    nk = nz2*nx2; /*wavenumber*/
    if (!sf_histint(left,"n1",&n2) || n2 != nzx) sf_error("Need n1=%d in left",nzx);
    if (!sf_histint(left,"n2",&m2))  sf_error("Need n2= in left");
    if (!sf_histint(right,"n1",&n2) || n2 != m2) sf_error("Need n1=%d in right",m2);
    if (!sf_histint(right,"n2",&n2) || n2 != nk) sf_error("Need n2=%d in right",nk);

    /*check record data*/
    if (adj && wantrecord) {
        sf_histint(Frcd,"n1", &tmpint);
        if (tmpint != nt ) sf_error("Error parameter n1 in record!");
        sf_histint(Frcd,"n2", &tmpint);
        if (tmpint != gpl ) sf_error("Error parameter n2 in record!");
        sf_histint(Frcd,"n3", &tmpint);
        if (tmpint != shtnum ) sf_error("Error parameter n3 in record!");
    }

    /*allocate memory*/
    ww=sf_complexalloc(nt);
    rr=sf_floatalloc2(nzx,nsource);
    lt = sf_complexalloc2(nzx,m2);
    rt = sf_complexalloc2(m2,nk);
    ltb = sf_complexalloc2(nzx,m2);
    rtb = sf_complexalloc2(m2,nk);
    geop = (geopar) sf_alloc(1, sizeof(*geop));
    mpip = (mpipar) sf_alloc(1, sizeof(*mpip));
    tmprec = sf_complexalloc2(nt, gpl);
    record = sf_complexalloc3(nt, gpl, shtnum);
    if (incom) {
        kill = sf_intalloc2(gpl, shtnum);
        sf_intread(kill[0],gpl*shtnum,mask);
    }
    wavefld = sf_complexalloc3(nz, nx, wfnt);
    if (illum ) sill = sf_floatalloc2(nz, nx);
    else sill = NULL;
    img = sf_complexalloc2(nz, nx);

    if (adj) {
        imgsum = sf_complexalloc2(nz, nx);
#ifdef _OPENMP
        #pragma omp parallel for private(ix,iz)
#endif
        for (ix=0; ix<nx; ix++)
            for (iz=0; iz<nz; iz++) {
                imgsum[ix][iz] = sf_cmplx(0.,0.);
            }

    }

    /*read from files*/
    sf_complexread(ww,nt,Fsrc);
    sf_complexread(lt[0],nzx*m2,left);
    sf_complexread(rt[0],m2*nk,right);
    sf_complexread(ltb[0],nzx*m2,leftb);
    sf_complexread(rtb[0],m2*nk,rightb);
    if(!adj) sf_complexread(img[0],nx*nz,Fimg);

    if(adj && wantrecord) {
        sf_complexread(record[0][0], shtnum*gpl*nt, Frcd);
        if(incom) {
            for (is=0; is<shtnum; is++)
                for (ix=0; ix<gpl; ix++)
                    if(kill[is][ix]==0)
                        for (it=0; it<nt; it++)
                            record[is][ix][it]=sf_cmplx(0.,0.);
        }
    } else {
#ifdef _OPENMP
        #pragma omp parallel for private(is,ix,it)
#endif
        for (is=0; is<shtnum; is++)
            for (ix=0; ix<gpl; ix++)
                for (it=0; it<nt; it++)
                    record[is][ix][it] = sf_cmplx(0.,0.);
    }

    /*close RSF files*/
    sf_fileclose(Fsrc);
    sf_fileclose(left);
    sf_fileclose(right);
    sf_fileclose(leftb);
    sf_fileclose(rightb);

    /*load constant geopar elements*/
    mpip->cpuid=rank;
    mpip->numprocs=nodes;
    /*load constant geopar elements*/
    geop->nx  = nx;
    geop->nz  = nz;
    geop->nxb = nxb;
    geop->nzb = nzb;
    geop->dx  = dx;
    geop->dz  = dz;
    geop->ox  = ox;
    geop->oz  = oz;
    geop->snpint = snpint;
    geop->spz = spz;
    geop->gpz = gpz;
    geop->gpl = gpl;
    geop->top = top;
    geop->bot = bot;
    geop->lft = lft;
    geop->rht = rht;
    geop->nt = nt;
    geop->dt = dt;
    geop->trunc = trunc;
    geop->shtnum = shtnum;

    /* output RSF files */

    if (rank==0) {
        sf_setn(ax, gpl);
        sf_setn(az, nz);
        as = sf_iaxa(Fvel, 2);
        sf_setn(as,shtnum);
        sf_setd(as,shtint*dx);
        sf_seto(as,shtbgn*dx+ox);

        if (adj) { /* migration */
            if(!wantrecord) {
                sf_oaxa(Frcd, at, 1);
                sf_oaxa(Frcd, ax, 2);
                sf_oaxa(Frcd, as, 3);
                sf_settype(Frcd,SF_COMPLEX);
            }
            sf_setn(ax, nx);
            /*write image*/
            sf_oaxa(Fimg, az, 1);
            sf_oaxa(Fimg, ax, 2);
            sf_settype(Fimg,SF_COMPLEX);

        } else { /* modeling */
            sf_oaxa(Frcd, at, 1);
            sf_oaxa(Frcd, ax, 2);
            sf_oaxa(Frcd, as ,3);
            sf_settype(Frcd,SF_COMPLEX);
        }

        if (wantwf) {
            sf_setn(ax, nx);
            /*write temp wavefield */
            sf_setn(at, (wfnt-1)/wfint+1);
            sf_setd(at, wfdt*wfint);

            sf_oaxa(Ftmpwf, az, 1);
            sf_oaxa(Ftmpwf, ax, 2);
            sf_oaxa(Ftmpwf, at, 3);
            sf_settype(Ftmpwf,SF_COMPLEX);
        }
    }

    tstart = clock();

    for (is=rank; is<shtnum; is+=nodes) {
        spx = shtbgn + shtint*is;
        if (roll)
            gpx = spx - (int)(gpl/2);
        else
            gpx = 0;
        geop->spx = spx;
        geop->gpx = gpx;

        if (verb) {
            sf_warning("============================");
            sf_warning("processing shot #%d", is);
            sf_warning("nx=%d nz=%d nt=%d", geop->nx, geop->nz, geop->nt);
            sf_warning("nxb=%d nzb=%d ", geop->nxb, geop->nzb);
            sf_warning("dx=%f dz=%f dt=%f", geop->dx, geop->dz, geop->dt);
            sf_warning("top=%d bot=%d lft=%d rht=%d", geop->top, geop->bot, geop->lft, geop->rht);
            sf_warning("rectz=%d rectx=%d repeat=%d srctrunc=%f",rectz,rectx,repeat,geop->trunc);
            sf_warning("spz=%d spx=%d gpz=%d gpx=%d gpl=%d", spz, spx, gpz, gpx, gpl);
            sf_warning("snpint=%d wfdt=%f wfnt=%d ", snpint, wfdt, wfnt);
            sf_warning("sht0=%d shtbgn=%d shtend=%d shtnum=%d", sht0, shtbgn, shtend, shtnum);
            if (roll) sf_warning("Rolling survey!");
            else sf_warning("Global survey (gpl=nx)!");
            if (illum) sf_warning("Using source illumination!");
            else sf_warning("No source illumination!");
            sf_warning("============================");
        }

        /*generate reflectivity map*/
        reflgen(nzb, nxb, spz+top, spx+lft, rectz, rectx, repeat, rr);

        lrosfor2(wavefld, sill, tmprec, verb, lt, rt, m2, geop, ww, rr, pad1, illum);

        if(adj && wantrecord)
#ifdef _OPENMP
            #pragma omp parallel for private(ix,it)
#endif
            for (ix=0; ix<gpl; ix++)
                for (it=0; it<nt; it++)
                    tmprec[ix][it] = record[is][ix][it];

        if(!fm) {
            lrosback2(img, wavefld, sill, tmprec, adj, verb, wantwf, ltb, rtb, m2, geop, pad1, illum);
        }

        if (adj) {
#ifdef _OPENMP
            #pragma omp parallel for private(ix,iz)
#endif
            for (ix=0; ix<nx; ix++)
                for (iz=0; iz<nz; iz++)
                    imgsum[ix][iz] += img[ix][iz];
        }

        if (!adj || !wantrecord)
#ifdef _OPENMP
            #pragma omp parallel for private(ix,it)
#endif
            for (ix=0; ix<gpl; ix++)
                for (it=0; it<nt; it++)
                    record[is][ix][it] = tmprec[ix][it];

        if (wantwf && is==0)
            for (it=0; it<wfnt; it++) {
                if (it%wfint == 0) {
                    sf_complexwrite(wavefld[it][0], nx*nz, Ftmpwf);
                }
            }
    } /*shot iteration*/

    MPI_Barrier(MPI_COMM_WORLD);
    /*write record/image*/
    if (adj) {
        if (rank==0) {
            sendbuf = (sf_complex *) MPI_IN_PLACE;
            recvbuf = imgsum[0];
        } else {
            sendbuf = imgsum[0];
            recvbuf = NULL;
        }
        MPI_Reduce(sendbuf, recvbuf, nx*nz, MPI_COMPLEX, MPI_SUM, 0, MPI_COMM_WORLD);
        if (rank==0)
            sf_complexwrite(imgsum[0], nx*nz, Fimg);
    }

    if (!adj || !wantrecord) {
        if (rank==0) {
            sendbuf = (sf_complex *) MPI_IN_PLACE;
            recvbuf = record[0][0];
        } else {
            sendbuf = record[0][0];
            recvbuf = NULL;
        }
        MPI_Reduce(sendbuf, recvbuf, shtnum*gpl*nt, MPI_COMPLEX, MPI_SUM, 0, MPI_COMM_WORLD);
        if (rank==0) {
            if(incom) {
                for (is=0; is<shtnum; is++)
                    for (ix=0; ix<gpl; ix++)
                        if(kill[is][ix]==0)
                            for (it=0; it<nt; it++)
                                record[is][ix][it]=sf_cmplx(0.,0.);
            }
            sf_complexwrite(record[0][0], shtnum*gpl*nt, Frcd);
        }
    }

    /*free memory*/
    free(ww);
    free(rr);
    free(*lt);
    free(lt);
    free(*rt);
    free(rt);
    free(*ltb);
    free(ltb);
    free(*rtb);
    free(rtb);
    free(geop);
    free(mpip);
    free(*tmprec);
    free(tmprec);
    free(**record);
    free(*record);
    free(record);
    free(**wavefld);
    free(*wavefld);
    free(wavefld);
    if (illum) {
        free(*sill);
        free(sill);
    }
    free(*img);
    free(img);
    if (adj) {
        free(*imgsum);
        free(imgsum);
    }
    if (incom) {
        free(* kill);
        free(kill);
    }

    tend = clock();
    duration=(double)(tend-tstart)/CLOCKS_PER_SEC;
    sf_warning(">> The CPU time of single shot migration is: %f seconds << ", duration);

    MPI_Finalize();
    exit(0);
}
Example #11
0
int main(int argc, char* argv[])
{
    bool spitz, verb;
    int niter, sa, na, j, dim, nx, n[SF_MAX_DIM], m[SF_MAX_DIM];
    float *dd, *ss, eps, na0, sa0;
    char varname[6], *lagfile;
    sf_filter naa, saa;
    sf_file spef, npef, dat, signoi, slag, nlag;

    sf_init(argc,argv);
    dat = sf_input("in");
    signoi = sf_output("out");

    spef = sf_input("sfilt");
    npef = sf_input("nfilt");

    dim = sf_filedims(dat,n);
    
    if (!sf_histint(spef,"n1",&sa)) sf_error("No n1= in sfilt");
    if (!sf_histint(npef,"n1",&na)) sf_error("No n1= in nfilt");

    naa = sf_allocatehelix(na);
    saa = sf_allocatehelix(sa);

    if (NULL == (lagfile = sf_histstring(spef,"lag")) &&
	NULL == (lagfile = sf_getstring("slag"))) 
	sf_error("Need slag=");
    slag = sf_input(lagfile);
    if (!sf_histints(slag,"n",m,dim)) sf_error("No n= in %s",lagfile);
    sf_intread(saa->lag,sa,slag);
    regrid(dim,m,n,saa);
    sf_fileclose(slag);

    if (NULL == (lagfile = sf_histstring(npef,"lag")) &&
	NULL == (lagfile = sf_getstring("nlag"))) 
	sf_error("Need nlag=");
    nlag = sf_input(lagfile);
    if (!sf_histints(nlag,"n",m,dim)) sf_error("No n= in %s",lagfile);
    sf_intread(naa->lag,na,nlag);
    regrid(dim,m,n,naa);
    sf_fileclose(nlag);

    if (!sf_histfloat(spef,"a0",&sa0)) sa0=1.;
    if (!sf_histfloat(npef,"a0",&na0)) na0=1.;

    if (!sf_getfloat("epsilon",&eps)) sf_error("Need eps=");
    /* regularization parameter */

    if (!sf_getint("niter",&niter)) niter=20;
    /* number of iterations */

    sprintf(varname,"n%d",dim+1);
    sf_putint(signoi,varname,2);

    nx=1;
    for(j=0; j < dim; j++) {
	nx *= n[j];
    }

    dd = sf_floatalloc(nx);
    ss = sf_floatalloc(nx);

    sf_floatread(dd,nx,dat);
    sf_floatread(saa->flt,sa,spef);
    for (j=0; j < sa; j++) {
	saa->flt[j] /= sa0;
    }

    sf_floatread(naa->flt,na,npef);
    for (j=0; j < na; j++) {
	naa->flt[j] /= na0;
    }

    if (!sf_getbool("spitz",&spitz)) spitz=false;
    /* if use Spitz method */

    if (!sf_getbool("verb",&verb)) verb=false;
    /* verbosity flag */

    signoi_init (naa, saa, niter, nx, eps, verb);

    if (spitz) {
	signoi2_lop  (false,false,nx,nx,dd,ss);
    } else {
	signoi_lop  (false,false,nx,nx,dd,ss);
    }

    sf_floatwrite(ss,nx,signoi);

    for (j=0; j < nx; j++) {
	dd[j] -= ss[j];
    }

    sf_floatwrite(dd,nx,signoi);


    exit (0);
}
Example #12
0
int main(int argc, char* argv[])
{
    int i, ia, na, nx, ns, dim, niter;
    int n[SF_MAX_DIM], m[SF_MAX_DIM], a[SF_MAX_DIM];
    float a0, eps, *mm, *pp;
    bool verb, *known;
    sf_filter aa;
    char* lagfile;
    sf_file in, out, filt, lag, mask;

    sf_init (argc,argv);
    in = sf_input("in");
    filt = sf_input("filt");
    out = sf_output("out");

    dim = sf_filedims (in,n);

    if (!sf_histint(filt,"n1",&na)) sf_error("No n1= in filt");
    aa = sf_allocatehelix (na);

    if (!sf_histfloat(filt,"a0",&a0)) a0=1.;
    if (!sf_histints(filt,"a",a,dim)) {
	for (i=0; i < dim; i++) {
	    a[i]=1;
	}
    }

    if (NULL != (lagfile = sf_getstring("lag")) /* file with filter lags */
	|| 
	NULL != (lagfile = sf_histstring(filt,"lag"))) {
	lag = sf_input(lagfile);

	sf_intread(aa->lag,na,lag);
    } else {
	lag = NULL;
	for( ia=0; ia < na; ia++) {
	    aa->lag[ia] = ia+1;
	}
    }

    
    if (!sf_getints ("n",m,dim) && (NULL == lag ||
				    !sf_histints (lag,"n",m,dim))) {
	for (i=0; i < dim; i++) {
	    m[i] = n[i];
	}
    }
 
    if (NULL != lag) sf_fileclose(lag);

    bound (dim, m, n, a, aa);

    sf_floatread (aa->flt,na,filt);
    sf_fileclose(filt);
    
    for( ia=0; ia < na; ia++) {
	aa->flt[ia] /= a0;
    }

    if (!sf_getint ("ns",&ns)) sf_error("Need ns=");
    /* scaling */
    if (!sf_getint("niter",&niter)) niter=100;
    /* Number of iterations */
    if (!sf_getfloat("eps",&eps)) eps=1.;
    /* regularization parameter */
    if (!sf_getbool("verb",&verb)) verb=true;
    /* verbosity flag */

    nx = 1;
    for( i=0; i < dim; i++) {
	nx *= n[i];
    }
  
    mm = sf_floatalloc (nx);
    pp = sf_floatalloc (nx);
    known = sf_boolalloc (nx);

    sf_mask_init(known);
    hshape_init (nx,ns,aa);
    sf_conjgrad_init(nx, nx, nx, nx, eps, 1.e-8, verb, false);

    if (NULL != sf_getstring("mask")) {
	/* optional input mask file for known data */
	mask = sf_input("mask");
	sf_floatread(mm,nx,mask);
	sf_fileclose(mask);
	
	for (i=0; i < nx; i++) {
	    known[i] = (bool) (mm[i] != 0.);
	}
	sf_floatread(mm,nx,in);
    } else {
	sf_floatread(mm,nx,in);
	   
	for (i=0; i < nx; i++) {
	    known[i] = (bool) (mm[i] != 0.);
	}
    }

    sf_conjgrad(NULL, sf_mask_lop, hshape_lop, pp, mm, mm, niter);
    
    sf_floatwrite (mm,nx,out);


    exit (0);
}
Example #13
0
int main(int argc, char* argv[])
{
    bool velocity, causal, limit, verb, shape;
    int dimw, dimt, i, n[SF_MAX_DIM], rect[SF_MAX_DIM], iw, nw, ir, nr;
    long nt, *order;
    int iter, niter, cgiter, count;
    int *ff, *dp, *mp, nloop;
    float o[SF_MAX_DIM], d[SF_MAX_DIM], *dt, *dw, *dv, *t, *w, *t0, *w1, *p=NULL;
    float eps, tol, thres, rhsnorm, rhsnorm0, rhsnorm1, rate, gama;
    char key[6];
    sf_file in, out, reco, grad, mask, prec;

    sf_init(argc,argv);
    in  = sf_input("in");
    out = sf_output("out");
   
    /* read dimension */
    dimw = sf_filedims(in,n);
	    
    nw = 1;
    for (i=0; i < dimw; i++) {
	sprintf(key,"d%d",i+1);
	if (!sf_histfloat(in,key,d+i)) sf_error("No %s= in input.",key);
	sprintf(key,"o%d",i+1);
	if (!sf_histfloat(in,key,o+i)) o[i]=0.;
	nw *= n[i];
    }
	    
    if (dimw > 2) sf_error("Only works for 2D now.");
	    
    n[2] = n[1]; d[2] = d[1]; o[2] = o[1];
    dimt = 3; nr = n[1]*n[2]; nt = nw*n[2];

    /* read initial velocity */
    w = sf_floatalloc(nw);
    sf_floatread(w,nw,in);
	    
    if (!sf_getbool("velocity",&velocity)) velocity=true;
    /* if y, the input is velocity; n, slowness-squared */
	    	    
    /* convert to slowness-squared */
    if (velocity) {
	for (iw=0; iw < nw; iw++)
	    w[iw] = 1./w[iw]*1./w[iw];
	
	dv = sf_floatalloc(nw);
    } else {
	dv = NULL;
    }
	    
    if (!sf_getbool("limit",&limit)) limit=false;
    /* if y, limit computation within receiver coverage */

    if (!sf_getbool("shape",&shape)) shape=false;
    /* shaping regularization (default no) */
	    
    /* read record */
    if (NULL == sf_getstring("reco"))
	sf_error("Need record reco=");
    reco = sf_input("reco");
    
    t0 = sf_floatalloc(nr);
    sf_floatread(t0,nr,reco);
    sf_fileclose(reco);
	    
    /* read receiver mask */	    
    if (NULL == sf_getstring("mask")) {
	mask = NULL;
	dp = NULL;
    } else {
	mask = sf_input("mask");
	dp = sf_intalloc(nr);
	sf_intread(dp,nr,mask);
	sf_fileclose(mask);
    }
	    
    /* read model mask */
    if (NULL == sf_getstring("prec")) {
	prec = NULL;
	mp = NULL;
    } else {
	prec = sf_input("prec");
	mp = sf_intalloc(nw);
	sf_intread(mp,nw,prec);
	sf_fileclose(prec);
    }

    if (!sf_getbool("verb",&verb)) verb=false;
    /* verbosity flag */
	    
    if (!sf_getint("niter",&niter)) niter=5;
    /* number of inversion iterations */
	    
    if (!sf_getint("cgiter",&cgiter)) cgiter=10;
    /* number of conjugate-gradient iterations */
	    
    if (!sf_getfloat("thres",&thres)) thres=5.e-5;
    /* threshold (percentage) */
	    
    if (!sf_getfloat("tol",&tol)) tol=1.e-3;
    /* tolerance for bisection root-search */

    if (!sf_getint("nloop",&nloop)) nloop=10;
    /* number of bisection root-search */

    /* output gradient at each iteration */
    if (NULL != sf_getstring("grad")) {
	grad = sf_output("grad");
	sf_putint(grad,"n3",niter);
    } else {
	grad = NULL;
    }
	    
    if (!sf_getfloat("eps",&eps)) eps=0.;
    /* regularization parameter */

    if (shape) {
	for (i=0; i < dimw; i++) {
	    sprintf(key,"rect%d",i+1);
	    if (!sf_getint(key,rect+i)) rect[i]=1;
	    /*( rect#=(1,1,...) smoothing radius on #-th axis )*/
	}
	
	/* triangle smoothing operator */
	sf_trianglen_init(dimw,rect,n);
	sf_repeat_init(nw,1,sf_trianglen_lop);
	
	sf_conjgrad_init(nw,nw,nr,nr,eps,1.e-6,verb,false);
	p = sf_floatalloc(nw);
    } else {
	/* initialize 2D gradient operator */
	sf_igrad2_init(n[0],n[1]);
    }

    /* allocate temporary array */
    t  = sf_floatalloc(nt);
    dw = sf_floatalloc(nw);
    dt = sf_floatalloc(nr);
    w1 = sf_floatalloc(nw);
    ff = sf_intalloc(nt);

    if (!sf_getbool("causal",&causal)) causal=true;
    /* if y, neglect non-causal branches of DSR */

    /* initialize eikonal */
    dsreiko_init(n,o,d,
		 thres,tol,nloop,
		 causal,limit,dp);
	    
    /* initialize operator */
    dsrtomo_init(dimt,n,d);

    /* upwind order */
    order = dsrtomo_order();

    /* initial misfit */
    dsreiko_fastmarch(t,w,ff,order);
    dsreiko_mirror(t);

    /* calculate L2 data-misfit */
    for (ir=0; ir < nr; ir++) {
	if (dp == NULL || dp[ir] == 1) {
	    dt[ir] = t0[ir]-t[(long) ir*n[0]];
	} else {
	    dt[ir] = 0.;
	}
    }

    rhsnorm0 = cblas_snrm2(nr,dt,1);
    rhsnorm = rhsnorm0;
    rhsnorm1 = rhsnorm;
    rate = rhsnorm1/rhsnorm0;
	    
    sf_warning("L2 misfit after iteration 0 of %d: %g",niter,rate);
    
    /* iterations over inversion */
    for (iter=0; iter < niter; iter++) {
	
	/* clean-up */
	for (iw=0; iw < nw; iw++) dw[iw] = 0.;
	
	/* set operator */
	dsrtomo_set(t,w,ff,dp,mp);
	
	/* solve dw */
	if (shape) {
	    sf_conjgrad(NULL,dsrtomo_oper,sf_repeat_lop,p,dw,dt,cgiter);
	} else {
	    sf_solver_reg(dsrtomo_oper,sf_cgstep,sf_igrad2_lop,2*nw,nw,nr,dw,dt,cgiter,eps,"verb",verb,"end");
	    sf_cgstep_close();
	}
	
	/* output gradient */
	if (grad != NULL) {
	    if (velocity) {
		for (iw=0; iw < nw; iw++) {
		    dv[iw] = -dw[iw]/(2.*sqrtf(w[iw])*(w[iw]+dw[iw]/2.));
		}
		sf_floatwrite(dv,nw,grad);
	    } else {
		sf_floatwrite(dw,nw,grad);
	    }
	}
	
	/* line search */
	gama = 0.5;
	for (count=0; count < 5; count++) {
	    
	    /* update slowness */
	    for (iw=0; iw < nw; iw++) 
		w1[iw] = (w[iw]+gama*dw[iw])*(w[iw]+gama*dw[iw])/w[iw];
	    
	    /* compute new misfit */
	    dsreiko_fastmarch(t,w1,ff,order);
	    dsreiko_mirror(t);
	    
	    for (ir=0; ir < nr; ir++) {
		if (dp == NULL || dp[ir] == 1) {
		    dt[ir] = t0[ir]-t[(long) ir*n[0]];
		} else {
		    dt[ir] = 0.;
		}
	    }

	    rhsnorm = cblas_snrm2(nr,dt,1);
	    rate = rhsnorm/rhsnorm1;
	    
	    if (rate < 1.) {
		for (iw=0; iw < nw; iw++) w[iw] = w1[iw];
		
		rhsnorm1 = rhsnorm;
		rate = rhsnorm1/rhsnorm0;
		break;
	    }
	    
	    gama *= 0.5;
	}
	
	if (count == 5) {
	    sf_warning("Line-search failure at iteration %d of %d.",iter+1,niter);
	    break;
	}
	
	sf_warning("L2 misfit after iteration %d of %d: %g (line-search %d)",iter+1,niter,rate,count);
    }
    
    /* convert to velocity */
    if (velocity) {
	for (iw=0; iw < nw; iw++) {
	    w[iw] = 1./sqrtf(w[iw]);
	}
    }
    
    sf_floatwrite(w,nw,out);
       
    exit(0);
}
Example #14
0
int main(int argc, char* argv[])
{
    fint1 nmo;
    bool sembl, half, slow, dsembl, asembl, weight, squared, trend, ratio;
    int it,ih,ix,iv, nt,nh,nx,nv, ib,ie,nb,i, nw, is, ns, CDPtype, mute, *mask;
    float amp, amp2, dt, dh, t0, h0, v0, dv, ds, smax, num, den, dy, str, sh=0., sh2=0.;
    float *trace, ***stack, ***stack2, ***stack2h, ***stackh, *hh, **bb;
    char *time, *space, *unit;
    const char *type;
    size_t len;
    sf_file cmp, scan, offset, msk, grd;
    mapfunc nmofunc;

    sf_init (argc,argv);
    cmp = sf_input("in");
    scan = sf_output("out");

    if (!sf_histint(cmp,"n1",&nt)) sf_error("No n1= in input");
    if (!sf_histint(cmp,"n2",&nh)) sf_error("No n2= in input");
    nx = sf_leftsize(cmp,2);

    if (!sf_getbool("semblance",&sembl)) sembl=false;
    /* if y, compute semblance; if n, stack */
    if (sembl || !sf_getbool("diffsemblance",&dsembl)) dsembl=false;
    /* if y, compute differential semblance */
    if (sembl || dsembl || !sf_getbool("avosemblance",&asembl)) asembl=false;
    /* if y, compute AVO-friendly semblance */

    if (NULL == (type = sf_getstring("type"))) {
	/* type of semblance (avo,diff,sembl,power,weighted) */
	if (asembl) {
	    type="avo";
	} else if (dsembl) {
	    type="diff";
	} else if (sembl) {
	    type="sembl";
	} else {
	    type="power";
	}
    }

    trend = (bool) ('a' == type[0] || 'w' == type[0]);
    ratio = (bool) ('p' != type[0] && 'd' != type[0]);

    if (!sf_getint("nb",&nb)) nb=2;
    /* semblance averaging */
    if (!sf_getbool("weight",&weight)) weight=true;
    /* if y, apply pseudo-unitary weighting */

    if (!sf_histfloat(cmp,"o1",&t0)) sf_error("No o1= in input");
    if (!sf_histfloat(cmp,"d1",&dt)) sf_error("No d1= in input");

    if (!sf_getbool("half",&half)) half=true;
    /* if y, the second axis is half-offset instead of full offset */

    CDPtype=1;
    if (NULL != sf_getstring("offset")) {
	offset = sf_input("offset");
	hh = sf_floatalloc(nh);

	h0 = dh = 0.;
    } else {
	if (!sf_histfloat(cmp,"o2",&h0)) sf_error("No o2= in input");
	if (!sf_histfloat(cmp,"d2",&dh)) sf_error("No d2= in input");
	
	sf_putfloat(scan,"h0",h0);
	sf_putfloat(scan,"dh",dh);
	sf_putint(scan,"nh",nh);

	if (sf_histfloat(cmp,"d3",&dy)) {
	    CDPtype=half? 0.5+dh/dy: 0.5+0.5*dh/dy;
	    if (0 == CDPtype) CDPtype=1;
	    if (1 != CDPtype) {
		sf_histint(cmp,"CDPtype",&CDPtype);
		sf_warning("CDPtype=%d",CDPtype);
	    }
	}

	offset = NULL;
	hh = NULL;
    }

    if (NULL != sf_getstring("mask")) {
	/* optional mask file */ 
	msk = sf_input("mask");
	mask = sf_intalloc(nh);
    } else {
	msk = NULL;
	mask = NULL;
    }

    if (!sf_getfloat("v0",&v0) && !sf_histfloat(cmp,"v0",&v0)) 
	sf_error("Need v0=");
    /*(v0 first scanned velocity )*/
    if (!sf_getfloat("dv",&dv) && !sf_histfloat(cmp,"dv",&dv)) 
	sf_error("Need dv=");
    /*(dv step in velocity )*/
    if (!sf_getint("nv",&nv) && !sf_histint(cmp,"nv",&nv)) 
	sf_error("Need nv=");
    /*(nv number of scanned velocities )*/

    sf_putfloat(scan,"o2",v0);
    sf_putfloat(scan,"d2",dv);
    sf_putint(scan,"n2",nv);

    if (!sf_getfloat("smax",&smax)) smax=2.0;
    /* maximum heterogeneity */
    if (!sf_getint("ns",&ns)) ns=1;
    /* number of heterogeneity scans */ 
    ds = ns>1? (smax-1.0)/(ns-1): 0.;

    if (ns > 1) {
	sf_putfloat(scan,"o3",1.0);
	sf_putfloat(scan,"d3",ds);
	sf_putint(scan,"n3",ns);

	sf_shiftdim(cmp, scan, 3);
    }

    if (!sf_getbool("slowness",&slow)) slow=false;
    /* if y, use slowness instead of velocity */
    sf_putstring(scan,"label2",slow? "Slowness": "Velocity");

    if (!sf_getbool("squared",&squared)) squared=false;
    /* if y, the slowness or velocity is squared */

    if (!sf_getfloat("v1",&v1)) {
	/*( v1 reference velocity )*/
	if (ns > 1) {
	    nmofunc = squared? noncurved: nonhyperb;
	} else {
	    nmofunc = squared? curved: hyperb;
	}
    } else {
	if (ns > 1) {
	    nmofunc = squared? noncurved1: nonhyperb1;
	} else {
	    nmofunc = squared? curved1: hyperb1;
	}
	if (!slow) v1 = 1./v1;
    }

    if (NULL != (time = sf_histstring(cmp,"unit1")) &&
	NULL != (space = sf_histstring(cmp,"unit2"))) {
	len = strlen(time)+strlen(space)+2;
	unit = sf_charalloc(len);
	if (slow) {
	    snprintf(unit,len,"%s/%s",time,space);
	} else {
	    snprintf(unit,len,"%s/%s",space,time);
	}
	sf_putstring(scan,"unit2",unit);
    }

    if (NULL != sf_getstring("grad")) {
	grd = sf_input("grad");

	bb = sf_floatalloc2(nt,nv);
	sf_floatread(bb[0],nt*nv,grd);

	sf_fileclose(grd);
    } else {
	bb = NULL;
    }

    stack =  sf_floatalloc3(nt,nv,ns);
    stack2 = ('p' != type[0])? sf_floatalloc3(nt,nv,ns): NULL;
    stackh = trend? sf_floatalloc3(nt,nv,ns): NULL;
    stack2h = ('w' == type[0])? sf_floatalloc3(nt,nv,ns): NULL;

    if (!sf_getint("extend",&nw)) nw=4;
    /* trace extension */

    if (!sf_getint("mute",&mute)) mute=12;
    /* mute zone */

    if (!sf_getfloat("str",&str)) str=0.5;
    /* maximum stretch allowed */

    trace = sf_floatalloc(nt);
    nmo = fint1_init(nw,nt,mute);

    for (ix=0; ix < nx; ix++) {
	sf_warning("cmp %d of %d;",ix+1,nx);

	for (it=0; it < nt*nv*ns; it++) {
	    stack[0][0][it] = 0.;
	    if (ratio) stack2[0][0][it] = 0.;
	    if (trend) stackh[0][0][it] = 0.;
	}

	if (NULL != offset) sf_floatread(hh,nh,offset);
	if (NULL != msk) sf_intread(mask,nh,msk);

	if (trend) sh = sh2 = 0.;

	for (ih=0; ih < nh; ih++) {
	    sf_floatread(trace,nt,cmp); 
	    if (NULL != msk && 0==mask[ih]) continue;

	    h = (NULL != offset)? hh[ih]: 
		h0 + ih * dh + (dh/CDPtype)*(ix%CDPtype);
	    if (half) h *= 2.;

	    if (trend) {
		sh  += h;    /* sf  */
		sh2 += h*h;  /* sf2 */
	    }

	    for (it=0; it < nt; it++) {
		trace[it] /= nt*nh;
	    }
	    fint1_set(nmo,trace);

	    for (is=0; is < ns; is++) {
		s = 1.0 + is*ds;

		for (iv=0; iv < nv; iv++) {
		    v = v0 + iv * dv;
		    v = slow? h*v: h/v;

		    stretch(nmo,nmofunc,nt,dt,t0,nt,dt,t0,trace,str);

		    for (it=0; it < nt; it++) {
			amp = weight? fabsf(v)*trace[it]: trace[it];
			if (NULL != bb) amp *= (1.0-bb[iv][it]*h);
			
			switch(type[0]) {
			    case 'd':
				if (ih > 0) {
				    amp2 = amp - stack2[is][iv][it];
				    stack[is][iv][it] += amp2*amp2;
				}
				stack2[is][iv][it] = amp;
				break;
			    case 's':
				stack2[is][iv][it] += amp*amp;
				stack[is][iv][it] += amp;
				break;
			    case 'a': 
				stackh[is][iv][it] += amp*h;    /* saf */
				stack2[is][iv][it] += amp*amp;  /* sa2 */
				stack[is][iv][it] += amp;       /* sa1 */
				break;
			    case 'w':
				stackh[is][iv][it] += amp*h;       /* saf */
				stack2h[is][iv][it] += amp*amp*h;  /* sfa2 */
				stack2[is][iv][it] += amp*amp;     /* sa2 */
				stack[is][iv][it] += amp;          /* sa1 */
				break;
			    case 'p':
			    default:
				stack[is][iv][it] += amp;
				break;				
			} 
		    } /* t */
		} /* v */
	    } /* s */
	} /* h */
	
	if (ratio) {
	    for (is=0; is < ns; is++) {
		for (iv=0; iv < nv; iv++) {
		    for (it=0; it < nt; it++) {
			ib = it-nb;
			ie = it+nb+1;
			if (ib < 0) ib=0;
			if (ie > nt) ie=nt;
			num = 0.;
			den = 0.;
			for (i=ib; i < ie; i++) {
			    switch(type[0]) {
				case 'a':
				    /* (N*saf^2 + sa1^2*sf2 - 2*sa1*saf*sf)/((N*sf2 - sf^2)*sa2) */

				    num += nh*stackh[is][iv][i]*stackh[is][iv][i] + 
					sh2*stack[is][iv][i]*stack[is][iv][i] - 
					2.*sh*stack[is][iv][i]*stackh[is][iv][i];
				    den += stack2[is][iv][i];
				    break;
				case 'w':
				    /* 4*(sa1*sfa2 - sa2*saf)*(N*saf - sa1*sf)/(N*sfa2 - sa2*sf)^2 */

				    num += 
					(stack[is][iv][i]*stack2h[is][iv][i]-
					 stack2[is][iv][i]*stackh[is][iv][i])*
					(nh*stackh[is][iv][i]-stack[is][iv][i]*sh);
				    den += 
					(nh*stack2h[is][iv][i]-stack2[is][iv][i]*sh)*
					(nh*stack2h[is][iv][i]-stack2[is][iv][i]*sh);
				    break;
				case 's':
				default:
				    num += stack[is][iv][i]*stack[is][iv][i];
				den += stack2[is][iv][i];
				break;
			    }
			}
			    
			switch(type[0]) {
			    case 'a':
				den *= (nh*sh2-sh*sh);
				break;
			    case 'w':
				num *= 4.0f;
				break;
			    case 's':
				den *= nh;
				break;
			}

			trace[it] = (den > 0.)? num/den: 0.;
		    }
		    sf_floatwrite(trace,nt,scan);
		} /* v */
	    } /* s */
	} else {
	    sf_floatwrite (stack[0][0],nt*nv*ns,scan);
	}
    } /* x */
    sf_warning(".");
    
    exit(0);
}
Example #15
0
int main(int argc, char* argv[])
{
    int n[SF_MAX_DIM], m[SF_MAX_DIM];
    int ndim, dim, n123, n123s, i, ia, ns, i1, na, i4, n4;
    float *f, *dd;
    char *lagfile;
    sf_filter aa;
    sf_file in, filt, lag, out;
 
    sf_init(argc,argv);

    in = sf_input("in");
    filt = sf_output("filt");
    out = sf_output("out");

    if (!sf_histint(filt,"n1",&na)) sf_error("No n1= in filt");

    aa = sf_allocatehelix (na);

    if (NULL != (lagfile = sf_getstring("lag")) 
	/*( lag file with filter lags )*/
	|| 
	NULL != (lagfile = sf_histstring(filt,"lag"))) {
	lag = sf_input(lagfile);

	sf_intread(aa->lag,na,lag);
    } else {
	lag = NULL;
	for( ia=0; ia < na; ia++) {
	    aa->lag[ia] = ia+1;
	}
    }


    ndim = sf_filedims(in,n);

    if (!sf_getint("dim",&dim)) dim=ndim; /* number of dimensions */
    
    if (!sf_getints ("n",m,dim) && (NULL == lag ||
				    !sf_histints (lag,"n",m,dim))) {
	for (i=0; i < dim; i++) {
	    m[i] = n[i];
	}
    }

    regrid (dim, m, n, aa);

    n4 = sf_leftsize(in,dim);
    
    n123 = 1;
    for (i=0; i < dim; i++) {
	n123 *= n[i];
    }

    dd = sf_floatalloc(n123);

    n123s = n123*na;    
    f = sf_floatalloc(n123s);

    for (i4=0; i4 < n4; i4++) {

	sf_floatread(dd,n123,in);
	sf_floatread(f,n123s,in);
	
	/* apply shifts: dd -> d */
	for (i=ia=0; ia < na; ia++) {
	    ns = aa->lag[ia];
	    for (i1=0; i1 < n123; i1++,i++) {
		dd[i1] -= f[i]*dd[i1-ns];
	    }
	}

	sf_floatwrite(dd,n123,out);
    }
    
    exit(0);
}
Example #16
0
int main(int argc, char* argv[])
{
    bool adj, velocity, l1norm, plane[3], verb;
    int dim, i, count, n[SF_MAX_DIM], it, nt, **m, nrhs, is, nshot=1, *flag, order, iter, niter, stiter, *k, nfreq, nmem;
    float o[SF_MAX_DIM], d[SF_MAX_DIM], **t, *t0, *s, *temps, **source, *rhs, *ds;
    float rhsnorm, rhsnorm0, rhsnorm1, rate, eps, gama;
    char key[4], *what;
    sf_file sinp, sout, shot, time, reco, rece, topo, grad, norm;
    sf_weight weight=NULL;

    sf_init(argc,argv);
    sinp = sf_input("in");
    sout = sf_output("out");

    if (NULL == (what = sf_getstring("what"))) what="tomo";
    /* what to compute (default tomography) */

    switch (what[0]) {
	case 'l': /* linear operator */

	    if (NULL == sf_getstring("time"))
		sf_error("Need time=");
	    time = sf_input("time");

	    /* read operator dimension from time table */
	    dim = sf_filedims(time,n);
	    
	    nt = 1;
	    for (i=0; i < 3; i++) {
		sprintf(key,"d%d",i+1);
		if (!sf_histfloat(time,key,d+i)) sf_error("No %s= in input",key);
		sprintf(key,"o%d",i+1);
		if (!sf_histfloat(time,key,o+i)) o[i]=0.;
		nt *= n[i]; plane[i] = false;
	    }
	    if (dim < 3) {
		n[2] = 1; o[2] = o[1]; d[2] = d[1]; plane[2] = false;
	    }

	    dim = 2;

	    /* read in shot file */
	    if (NULL == sf_getstring("shot"))
		sf_error("Need source shot=");
	    shot = sf_input("shot");
	    
	    if (!sf_histint(shot,"n2",&nshot)) nshot=1;
	    sf_fileclose(shot);

	    /* read in receiver file */
	    m = sf_intalloc2(nt,nshot);
	    if (NULL == sf_getstring("receiver")) {
		for (is=0; is < nshot; is++) {
		    for (it=0; it < nt; it++) {
			m[is][it] = 1;
		    }
		}
	    } else {
		rece = sf_input("receiver");
		sf_intread(m[0],nt*nshot,rece);
		sf_fileclose(rece);
	    }

	    /* number of right-hand side */
	    nrhs = 0;
	    for (is=0; is < nshot; is++) {
		for (it=0; it < nt; it++) {
		    if (m[is][it] == 1) nrhs++;
		}
	    }
	    rhs = sf_floatalloc(nrhs);

	    t = sf_floatalloc2(nt,nshot);
	    sf_floatread(t[0],nt*nshot,time);

	    if (!sf_getbool("adj",&adj)) adj=false;
	    /* adjoint flag (for what=linear) */

	    /* initialize fatomo */
	    fatomo_init(dim,n,d,nshot);

	    /* set operators */
	    fatomo_set(t,m);

	    t0 = sf_floatalloc(nt);

	    if (adj) {
		sf_floatread(rhs,nrhs,sinp);

		fatomo_lop(true,false,nt,nrhs,t0,rhs);

		sf_putint(sout,"n1",nt);
		sf_putint(sout,"n2",1);
		sf_putint(sout,"n3",1);
		sf_floatwrite(t0,nt,sout);
	    } else {
		sf_floatread(t0,nt,sinp);

		fatomo_lop(false,false,nt,nrhs,t0,rhs);
		
		sf_putint(sout,"n1",nrhs);
		sf_putint(sout,"n2",1);
		sf_putint(sout,"n3",1);
		sf_floatwrite(rhs,nrhs,sout);
	    }

	    break;
	    
	case 't': /* tomography */

	    /* read input dimension */
	    dim = sf_filedims(sinp,n);
	    
	    nt = 1;
	    for (i=0; i < dim; i++) {
		sprintf(key,"d%d",i+1);
		if (!sf_histfloat(sinp,key,d+i)) sf_error("No %s= in input",key);
		sprintf(key,"o%d",i+1);
		if (!sf_histfloat(sinp,key,o+i)) o[i]=0.;
		nt *= n[i]; plane[i] = false;
	    }
	    if (dim < 3) {
		n[2] = 1; o[2] = o[1]; d[2] = d[1]; plane[2] = false;
	    }
	    
	    /* read initial guess */
	    s = sf_floatalloc(nt);
	    sf_floatread(s,nt,sinp);
	    
	    if (!sf_getbool("velocity",&velocity)) velocity=true;
	    /* if y, the input is velocity; n, slowness squared */

	    if (velocity) {
		for (it=0; it < nt; it++) {
		    s[it] = 1./s[it]*1./s[it];
		}
	    }

	    /* allocate memory for temporary data */
	    ds    = sf_floatalloc(nt);
	    flag  = sf_intalloc(nt);
	    
	    temps = sf_floatalloc(nt);
	    for (it=0; it < nt; it++) {
		temps[it] = s[it];
	    }
	    
	    if (!sf_getbool("l1norm",&l1norm)) l1norm=false;
	    /* norm for minimization (default L2 norm) */

	    if (!sf_getbool("verb",&verb)) verb=false;
	    /* verbosity flag */

	    /* read in shot file */
	    if (NULL == sf_getstring("shot"))
		sf_error("Need source shot=");
	    shot = sf_input("shot");

	    if (!sf_histint(shot,"n2",&nshot)) nshot=1;

	    source = sf_floatalloc2(3,nshot);
	    sf_floatread(source[0],3*nshot,shot);
	    sf_fileclose(shot);

	    /* allocate memory for time table */
	    t = sf_floatalloc2(nt,nshot);

	    /* read in receiver file */
	    m = sf_intalloc2(nt,nshot);
	    if (NULL == sf_getstring("receiver")) {
		for (is=0; is < nshot; is++) {
		    for (it=0; it < nt; it++) {
			m[is][it] = 1;
		    }
		}
	    } else {
		rece = sf_input("receiver");
		sf_intread(m[0],nt*nshot,rece);
		sf_fileclose(rece);
	    }
	    
	    /* number of right-hand side */
	    nrhs = 0;
	    for (is=0; is < nshot; is++) {
		for (it=0; it < nt; it++) {
		    if (m[is][it] == 1) nrhs++;
		}
	    }
	    rhs = sf_floatalloc(nrhs);
	    
	    /* read in record file */
	    if (NULL == sf_getstring("record"))
		sf_error("Need data record=");
	    reco = sf_input("record");

	    t0 = sf_floatalloc(nrhs);
	    sf_floatread(t0,nrhs,reco);
	    sf_fileclose(reco);

	    /* read in topography file */
	    if (NULL != sf_getstring("topo")) {
		topo = sf_input("topo");
		k = sf_intalloc(nt);
		sf_intread(k,nt,topo);
		sf_fileclose(topo);
	    } else {
		k = NULL;
	    }
	    
	    if (!sf_getint("order",&order)) order=2;
	    /* fast marching accuracy order */

	    if (!sf_getint("niter",&niter)) niter=10;
	    /* number of slowness inversion iterations */

	    if (!sf_getint("stiter",&stiter)) stiter=200;
	    /* number of step iterations */

	    if (!sf_getfloat("eps",&eps)) eps=0.;
	    /* regularization parameter */

	    /* output gradient at each iteration */
	    if (NULL != sf_getstring("gradient")) {
		grad = sf_output("gradient");
		sf_putint(grad,"n3",n[2]);
		sf_putfloat(grad,"d3",d[2]);
		sf_putfloat(grad,"o3",o[2]);
		sf_putint(grad,"n4",niter);
	    } else {
		grad = NULL;
	    }

	    /* output misfit L2 norm at each iteration */
	    if (NULL != sf_getstring("misnorm")) {
		norm = sf_output("misnorm");
		sf_putint(norm,"n1",niter+1);
		sf_putfloat(norm,"d1",1.);
		sf_putfloat(norm,"o1",0.);
		sf_putint(norm,"n2",1);
		sf_putint(norm,"n3",1);
	    } else {
		norm = NULL;
	    }

	    /* initialize fatomo */
	    fatomo_init(dim,n,d,nshot);

	    /* initialize 2D gradient operator */
	    sf_igrad2_init(n[0],n[1]);

	    if (l1norm) {
		/*
		if (!sf_getfloat("perc",&perc)) perc=90.;

		l1_init(nt,stiter,perc,false);
		*/
		if (!sf_getint("nfreq",&nfreq)) nfreq=1;
		/* l1-norm weighting nfreq */

		if (!sf_getint("nmem",&nmem)) nmem=1;
		/* l1-norm weighting nmem */

		weight = sf_l1;
		sf_irls_init(nt);
	    }

	    /* initial misfit */
	    fastmarch_init(n[2],n[1],n[0]);
	    
	    i = 0;
	    for (is=0; is < nshot; is++) {
		fastmarch(t[is],s,flag,plane,
			  n[2],n[1],n[0],o[2],o[1],o[0],d[2],d[1],d[0],
			  source[is][2],source[is][1],source[is][0],1,1,1,order);

		for (it=0; it < nt; it++) {
		    if (m[is][it] == 1) {
			rhs[i] = t0[i]-t[is][it];
			i++;
		    }
		}
	    }
	    
	    fastmarch_close();
	    
	    /* calculate L2 data-misfit */
	    rhsnorm0 = cblas_snrm2(nrhs,rhs,1);
	    rhsnorm = rhsnorm0;
	    rhsnorm1 = rhsnorm;
	    rate = rhsnorm1/rhsnorm0;

	    if (l1norm)
		sf_warning("L1 misfit after iteration 0 of %d: %g",niter,rate);
	    else
		sf_warning("L2 misfit after iteration 0 of %d: %g",niter,rate);

	    if (norm != NULL) sf_floatwrite(&rate,1,norm);

	    /* iterations over inversion */
	    for (iter=0; iter < niter; iter++) {
		
		/* clean-up */
		for (it=0; it < nt; it++) {
		    ds[it] = 0.;
		}

		/* prepare for CG */
		fatomo_set(t,m);

		/* solve ds */
		if (l1norm) {
		    /*
		      sf_solver_reg(fatomo_lop,l1step,sf_igrad2_lop,2*nt, nt,nrhs,ds,rhs,stiter,eps,"verb",verb,"end");
		    */
		    sf_solver_reg(fatomo_lop,sf_cgstep,sf_igrad2_lop,2*nt,nt,nrhs,ds,rhs,stiter,eps,"wght",weight,"nfreq",nfreq,"nmem",nmem,"verb",verb,"end");
		    
		    /*
		      l1step_close();
		    */
		    
		    sf_cgstep_close();
		} else {
		    sf_solver_reg(fatomo_lop,sf_cgstep,sf_igrad2_lop,2*nt,nt,nrhs,ds,rhs,stiter,eps,"verb",verb,"end");
			
		    sf_cgstep_close();
		}
		
		/* line search */
		gama = 1.;
		for (count=0; count < 10; count++) {
		    
		    /* update slowness */
		    for (it=0; it < nt; it++) {
			if (k == NULL || k[it] != 1)
			    temps[it] = (s[it]+gama*ds[it])*(s[it]+gama*ds[it])/s[it];
		    }

		    /* forward fast-marching for stencil time */
		    fastmarch_init(n[2],n[1],n[0]);
		    
		    i = 0;
		    for (is=0; is < nshot; is++) {
			fastmarch(t[is],temps,flag,plane,
				  n[2],n[1],n[0],o[2],o[1],o[0],d[2],d[1],d[0],
				  source[is][2],source[is][1],source[is][0],1,1,1,order);
			
			for (it=0; it < nt; it++) {
			    if (m[is][it] == 1) {
				rhs[i] = t0[i]-t[is][it];
				i++;
			    }
			}
		    }
		    
		    fastmarch_close();
		    
		    rhsnorm = cblas_snrm2(nrhs,rhs,1);
		    rate = rhsnorm/rhsnorm1;
		    
		    if (rate < 1.) {
			for (it=0; it < nt; it++) {
			    s[it] = temps[it];
			}
			rhsnorm1 = rhsnorm;
			rate = rhsnorm1/rhsnorm0;
			break;
		    }
		    
		    gama *= 0.5;
		}
		
		if (count == 10) {
		    sf_warning("Line-search Failure. Iteration terminated at %d of %d.",iter+1,niter);
		    sf_warning("Dimensions for GRAD and NORM need to be fixed before read.");
		    break;
		}

		if (l1norm)
		    sf_warning("L1 misfit after iteration %d of %d: %g (line-search %d)",iter+1,niter,rate,count);
		else
		    sf_warning("L2 misfit after iteration %d of %d: %g (line-search %d)",iter+1,niter,rate,count);
		
		if (grad != NULL) sf_floatwrite(ds,nt,grad);
		if (norm != NULL) sf_floatwrite(&rate,1,norm);
	    }
	    
	    /* convert to velocity */
	    if (velocity) {
		for (it=0; it < nt; it++) {
		    s[it] = 1./sqrtf(s[it]);
		}
	    }
	    
	    sf_floatwrite(s,nt,sout);

       	    break;
    }
    
    exit(0);
}
Example #17
0
int main(int argc, char *argv[])
{
    off_t n[SF_MAX_DIM],n_r[SF_MAX_DIM], nsiz,nsiz_r=0,nleft;
    int qq[BUFSIZ];
    char buf[BUFSIZ],buf_r[BUFSIZ],*right=0,*sign;
    float eps,fl=0,fr;
    size_t bufsiz=BUFSIZ,dim,dim_r,i,nbuf;
    sf_complex c;
    sf_file in,in_r=0,out;
    sf_datatype type;
    bool cmp_num=false;

    sf_init(argc,argv);

    cmp_num = sf_getfloat("right_f",&fr);
    /* compare input (left) to a single float value (right) */

    if (!cmp_num && NULL == (right=sf_getstring("right"))) sf_error("No right or right_f parameter set.");
    /* the rsf file you will be comparing to */

    if (NULL == (sign=sf_getstring("sign"))) sign="eq";
    /* 'eq'(default),'gt','ge','lq','lt','ne'
        sign=   'eq' equal-to ( == )
        sign=   'gt' greater-than ( > )
        sign=   'ge' greater-than or equal-to ( >= )
        sign=   'lq' less-than or equal-to ( <= )
        sign=   'lt' less-than ( < )
        sign=   'ne' not-equal ( != )
    sign=   'and' the values are both non-zero ( && )
    sign=   'or' one value is non-zero ( !! )
    */

    if (!sf_getfloat("eps",&eps)) eps=0;
    /* comparing within this range epsilon */

    in = sf_input("in");
    out = sf_output("out");
    sf_settype(out,SF_INT);

    dim = sf_largefiledims(in,n);
    for (nsiz=1, i=0; i < dim; i++) nsiz *= n[i];

    if (!cmp_num) {
        in_r = sf_input(right);
        dim_r = (size_t) sf_largefiledims(in_r,n_r);
        for (nsiz_r=1, i=0; i < dim_r; i++) nsiz_r *= n_r[i];
    }

    bufsiz /= sf_esize(in);
    type = sf_gettype(in);

    if (!cmp_num && type != sf_gettype(in_r)) sf_error("Type of input and right files do not match.");
    if (!cmp_num && nsiz != nsiz_r) sf_error("Size of input and right files do not match.");


    for (nleft=nsiz; nleft>0; nleft -= nbuf) {
        nbuf = (bufsiz < nleft)? bufsiz: nleft;
        switch (type) {
        case SF_FLOAT:
            sf_floatread((float*) buf,nbuf,in);
            if (!cmp_num) sf_floatread((float*) buf_r,nbuf,in_r);
            break;
        case SF_INT:
            sf_intread((int*) buf,nbuf,in);
            if (!cmp_num) sf_intread((int*) buf_r,nbuf,in_r);
            break;
        case SF_COMPLEX:
            sf_complexread((sf_complex*) buf,nbuf,in);
            if (!cmp_num) sf_complexread((sf_complex*) buf_r,nbuf,in_r);
            break;
        default:
            sf_error("Type not understood.");
            break;
        }
        for (i=0; i<nbuf; i++) {
            switch (type) {
            case SF_FLOAT:
                fl = ((float*)buf)[i];
                if (!cmp_num) fr = ((float*)buf_r)[i];
                break;
            case SF_INT:
                fl = (float) ((int*)buf)[i];
                if (!cmp_num) fr = (float) ((int*)buf_r)[i];
                break;
            case SF_COMPLEX:
                c=((sf_complex*)buf)[i];
                fl=cabsf(c);
                if (!cmp_num) {
                    c=((sf_complex*)buf_r)[i];
                    fr=cabsf(c);
                }
                break;
            default:
                sf_error("Type not understood.");
                break;
            }

            if      (0==strcmp(sign,"ge")) qq[i] = ((fl-fr) >= -eps);
            else if (0==strcmp(sign,"gt")) qq[i] = ((fl-fr) > -eps);
            else if (0==strcmp(sign,"eq")) qq[i] = (fabs(fl-fr) <= eps);
            else if (0==strcmp(sign,"lt")) qq[i] = ((fl-fr) < eps);
            else if (0==strcmp(sign,"lq")) qq[i] = ((fl-fr) <= eps);
            else if (0==strcmp(sign,"ne")) qq[i] = (fabs(fl-fr) > eps);
            else if (0==strcmp(sign,"and")) qq[i] = ((fabs(fl) > eps) && (fabs(fr) > eps));
            else if (0==strcmp(sign,"or")) qq[i] = ((fabs(fl) > eps) || (fabs(fr) > eps));
            else sf_error("Sign not recognized. Please specify: gt,ge,eq,lq,lt,ne,and,or");
        }
        sf_intwrite(qq,nbuf,out);
    }

    exit(0);
}
Example #18
0
int main (int argc, char* argv[])
{
    off_t n1, n2, n[SF_MAX_DIM];
    int axis, ndim, i, i2, *ibuf;
    size_t nsize, nbuf, ntest;
    sf_file in=NULL;
    sf_file out=NULL;
    float *fbuf, *abuf, dscale, pclip;
    sf_complex* cbuf;
    sf_datatype type;

    sf_init (argc, argv);
    in = sf_input ("in");
    out = sf_output ("out");

    type = sf_gettype(in);
    nbuf = sf_bufsiz(in);
    if (SF_INT == type) sf_settype(out,SF_FLOAT);

    sf_fileflush(out,in);

    if (!sf_getint("axis",&axis)) axis = 0;
    /* Scale by maximum in the dimensions up to this axis. */
    if (!sf_getfloat("rscale",&dscale)) dscale=0.;
    /* Scale by this factor. */
    if (!sf_getfloat("pclip",&pclip)) pclip=100.;
    /* data clip percentile */

    ndim = sf_largefiledims (in, n);

    n1=1;
    n2=1;

    for (i=0; i < ndim; i++) {
	if (i < axis) n1 *= n[i];
	else          n2 *= n[i];
    }

    abuf = sf_floatalloc(n1);

    ntest = SF_MAX(n1*pclip/100. + .5,0);
    if (ntest > n1) ntest = n1;

    if (1 < n1 && 0. == dscale) {
	switch (type) {
	    case SF_FLOAT:
		fbuf = sf_floatalloc(n1);

		for (i2=0; i2 < n2; i2++) {
		    sf_floatread (fbuf,n1,in);
		    for (i=0; i < n1; i++) {
			abuf[i] = fabsf(fbuf[i]);
		    }
		    dscale = getscale(ntest,n1,abuf);		    
		    for (i=0; i < n1; i++) {
			fbuf[i] *= dscale;
		    }
		    sf_floatwrite (fbuf,n1,out);
		}
		break;
	    case SF_COMPLEX:
		cbuf = sf_complexalloc(n1);

		for (i2=0; i2 < n2; i2++) {
		    sf_complexread (cbuf,n1,in);
		    for (i=0; i < n1; i++) {
			abuf[i] = cabsf(cbuf[i]);
		    }
		    dscale = getscale(ntest,n1,abuf);
		    for (i=0; i < n1; i++) {
#ifdef SF_HAS_COMPLEX_H
			cbuf[i] *= dscale;
#else
			cbuf[i] = sf_crmul(cbuf[i],dscale);
#endif
		    }
		    sf_complexwrite (cbuf,n1,out);
		}
		break;
	    default:
		sf_error("Unsupported type %d",type);	
		break;
	}
    } else {
	if (0.==dscale && !sf_getfloat("dscale",&dscale)) dscale=1.;
	/* Scale by this factor (works if rscale=0) */

	nsize = n1*n2;

	switch (type) {
	    case SF_COMPLEX:
		nsize *= 2;
		sf_settype(in,SF_FLOAT);
		sf_settype(out,SF_FLOAT);
	    case SF_FLOAT:
		nbuf /= sizeof(float);
		fbuf = sf_floatalloc(nbuf);
	
		while (nsize > 0) {
		    if (nsize < nbuf) nbuf = nsize;
		    sf_floatread (fbuf,nbuf,in);
		    for (i=0; i < nbuf; i++) {
			fbuf[i] *= dscale;
		    }
		    sf_floatwrite (fbuf,nbuf,out);
		    nsize -= nbuf;
		}	
		break;
	    case SF_INT:
		nbuf /= sizeof(int);
		ibuf = sf_intalloc(nbuf);
		fbuf = sf_floatalloc(nbuf);
		
		while (nsize > 0) {
		    if (nsize < nbuf) nbuf = nsize;
		    sf_intread (ibuf,nbuf,in);
		    for (i=0; i < nbuf; i++) {
			fbuf[i] = (double) ibuf[i]*dscale;
		    }
		    sf_floatwrite (fbuf,nbuf,out);
		    nsize -= nbuf;
		}	
		break;
	    default:
		sf_error("Unsupported type %d",type);

	} 
    }


    exit (0);
}
Example #19
0
int main(int argc, char* argv[])
{
    bool verb;
    int i, nz, iz, nh, ih, ncdp, icdp, np, ip, jtau, *itau, *mute, *npicks;
    float dz, dh, dcdp, cut, s, z, h;
    float *tau, **ztau, *semb;
    sf_file in, pick, npick, semblance;
    FILE *fp;

    sf_init(argc, argv);
    in = sf_input("in");
    pick = sf_input("pick");
    npick = sf_input("npick");
    semblance = sf_input("semblance");
    fp=fopen("sogpicks.txt","w");

    if (!sf_histint(in,"n1",&nz)) sf_error("No n1= in input");
    if (!sf_histfloat(in,"d1",&dz)) sf_error("No d1= in input");
    if (!sf_histint(in,"n2",&nh)) sf_error("No n2= in input");
    if (!sf_histfloat(in,"d2",&dh)) sf_error("No d2= in input");
    ncdp = sf_leftsize(in,2);
    if (!sf_histfloat(in,"d3",&dcdp)) sf_error("No d3= in input");
    if (!sf_histint(pick,"n1",&np)) sf_error("No n1= in pick");

    if (!sf_getbool("verb",&verb)) verb=true;
    /* if y, print icdp/ncdp during operation */
    if (!sf_getfloat("cut",&cut)) cut=0.;
    /* muting value in boundary */

	itau = sf_intalloc(np);
	tau = sf_floatalloc(np);
	mute = sf_intalloc(nz);
	ztau = sf_floatalloc2(nz, nh);
	semb = sf_floatalloc(nz);

	npicks = sf_intalloc(ncdp);
	sf_intread(npicks, ncdp, npick);

    for (icdp=0; icdp < ncdp; icdp++) {

		if(verb) sf_warning("icdp/ncdp=%d/%d;",icdp+1, ncdp);

		/* read data */
		sf_floatread(ztau[0], nz*nh, in);
		sf_floatread(tau, np, pick);
		sf_floatread(semb, nz, semblance);

		for (ip=0; ip<np; ip++){
			itau[ip] = tau[ip]/dz+0.5;
		}

		/* muting boundary */
		for (iz=0; iz<nz; iz++){
			if(ztau[0][iz]>=cut) break;
		}
		for (i=0; i<iz; i++) mute[i]=dz*(nh-1)*(iz-i)/cut+0.5;
		for (i=iz; i<nz; i++) mute[i]=0;

		fprintf(fp, "%4d %11.5f %2d\n", icdp+1, icdp*dcdp, npicks[icdp]);

		for (ip=0; ip<npicks[icdp]; ip++){
			jtau=itau[npicks[icdp]-1-ip];
			fprintf(fp, "%2d %11.5f %3d\n", ip+1, jtau*dz, nh-mute[jtau]);

			s=semb[jtau];
			for (ih=nh-1; ih>=mute[jtau]; ih--){
				h=dh*(nh-1-ih);
				z=ztau[ih][jtau];
				fprintf(fp, "%11.5f %11.5f %6.5f\n", h, z, s);
			} // end of ih
		} // end of ip
	} // end of icdp

	fclose(fp);

    exit(0);
}
Example #20
0
int main(int argc, char* argv[])
{
    bool segy;
    int i, i1, i2, n1, n2, n3, n, nt, len, nkey, row;
    sf_file in, out;
    int mem; /* for avoiding int to off_t typecast warning */
    off_t memsize;
    char *eq, *output, *key, *arg;
    float **ftra=NULL, **fbuf=NULL, **fst=NULL, d2, o2;
    int **itra=NULL, **ibuf=NULL, **ist=NULL;
    sf_datatype type;

    sf_init (argc,argv);
    in = sf_input ("in");
    out = sf_output ("out");

    sf_putint(out,"N",0);
    sf_putint(out,"T",1);
    sf_putint(out,"input",2);

    type = sf_gettype(in);

    if (SF_FLOAT != type && SF_INT != type) sf_error("Need float or int input");

    if (!sf_getbool("segy",&segy)) segy=true;
    /* if SEGY headers */

    if (!sf_histint(in,"n1",&n1)) n1=1;
    if (!sf_histint(in,"n2",&n2)) n2=1;
    n3 = sf_leftsize(in,2); /* left dimensions after the first two */

    if (segy) {
	segy_init(n1,in);
    } else {
	other_init(n1,in);
    }

    if (NULL != (key = sf_getstring("key"))) { 
	/* key to replace */
	row = segykey(key);
	free(key);
    } else {
	if (!sf_getint("nkey",&row)) row=-1;
	/* number of key to replace */
    }	
    if (row > n1) sf_error("nkey=%d is too large, need nkey <= %d",row,n1);
    
    if (n1 > 1) {
	if (n2 > 1) { /* input: many keys */
	    if (row < 0) sf_putint(out,"n1",1);
	} else { /* input: one key, arranged in n1 */
	    n2 = n1;
	    n1 = 1;
	}
    }


    for (i=0; i < n1; i++) {
	sf_putint(out,segykeyword(i),i+3);
    }

    for (i=1; i< argc; i++) { /* collect inputs */
	arg = argv[i];
	eq =  strchr(arg,'=');
	if (NULL == eq) continue; /* not a parameter */
	if (0 == strncmp(arg,"output",6) ||
	    0 == strncmp(arg,    "--",2)) continue; /* not a key */

	len = (size_t) (eq-arg);
	key = sf_charalloc(len+1);
	memcpy(key,arg,len);
	key[len]='\0';

	if (sf_getint(key,&nkey))
	    sf_putint(out,key,nkey+3);
	free(key);
    }
  
    if (!sf_histfloat(in,n1>1? "d2":"d1",&d2)) d2=1.;
    if (!sf_histfloat(in,n1>1? "o2":"o1",&o2)) o2=0.;

    if (NULL == (output = sf_getstring("output"))) sf_error("Need output=");
    /* Describes the output in a mathematical notation. */

    if (!sf_getint("memsize",&mem))
        mem=sf_memsize();
    /* Max amount of RAM (in Mb) to be used */
    memsize = mem * (1<<20); /* convert Mb to bytes */

    len = sf_math_parse (output,out,type);

    /* number of traces for optimal I/O */
    nt = SF_MAX(1,memsize/((2*n1+len+6)*sizeof(float)));

    if (SF_FLOAT == type) { /* float type */
	ftra = sf_floatalloc2(n1,nt);
	fbuf = sf_floatalloc2(nt,n1+3);
	fst  = sf_floatalloc2(nt,len+3);
    } else {               /* int type */
	itra = sf_intalloc2(n1,nt);
	ibuf = sf_intalloc2(nt,n1+3);
	ist  = sf_intalloc2(nt,len+3);
    }

    for (n=n2*n3; n > 0; n -= nt) {
	if (n < nt) nt=n;

	if (SF_FLOAT == type) { 
	    sf_floatread(ftra[0],n1*nt,in);
	} else {
	    sf_intread(itra[0],n1*nt,in);
	}

	for (i2=0; i2 < nt; i2++) {
	    if (SF_FLOAT == type) { 
		fbuf[0][i2]=(float) i2;  /* N */
		fbuf[1][i2]=o2+i2*d2;    /* T */
		fbuf[2][i2]=ftra[0][i2]; /* input */
	    } else {
		ibuf[0][i2]=i2;          /* N */
		ibuf[1][i2]=o2+i2*d2;    /* T */
		ibuf[2][i2]=itra[0][i2]; /* input */
	    }
	}
	for (i1=0; i1 < n1; i1++) {
	    for (i2=0; i2 < nt; i2++) {
		if (SF_FLOAT == type) { 
		    fbuf[i1+3][i2]=ftra[i2][i1];
		} else {
		    ibuf[i1+3][i2]=itra[i2][i1];
		}
	    }
	}
	
	if (SF_FLOAT == type) { 
	    sf_math_evaluate (len, nt, fbuf, fst);
	    if (row < 0) {
		sf_floatwrite(fst[1],nt,out);
	    } else {
		for (i2=0; i2 < nt; i2++) {
		    ftra[i2][row] = fst[1][i2];
		}
		sf_floatwrite(ftra[0],n1*nt,out);
	    }
	} else {
	    sf_int_math_evaluate (len, nt, ibuf, ist);
	    if (row < 0) {
		sf_intwrite(ist[1],nt,out);
	    } else {
		for (i2=0; i2 < nt; i2++) {
		    itra[i2][row] = ist[1][i2];
		}
		sf_intwrite(itra[0],n1*nt,out);
	    }
	}
    }

    exit(0);
}
Example #21
0
int main(int argc, char* argv[])
{
    int n1, n2, ns, nw;
    int is, iw, **pp, i, ip;
    double omega;
    float dw, ow;
    float *ahess, **ahesss, **ahessr;
    sf_complex **f, ***swave, ***rwave;
    sf_complex **stemp, **rtemp;
    sf_file in, out, list, us, ur, wvlt;
    int uts, mts;

    sf_init(argc,argv);
    in  = sf_input("in");
    out = sf_output("out");

    if (!sf_getint("uts",&uts)) uts=0;
    /* number of OMP threads */

#ifdef _OPENMP
    mts = omp_get_max_threads();
#else
    mts = 1;
#endif

    uts = (uts < 1)? mts: uts;

    /* read model dimensions */
    if (!sf_histint(in,"n1",&n1)) sf_error("No n1= in input.");
    if (!sf_histint(in,"n2",&n2)) sf_error("No n2= in input.");

    /* read source wavefield */
    if (NULL == sf_getstring("us"))
	sf_error("Need source wavefield us=");
    us = sf_input("us");

    if (!sf_histint(us,"n3",&ns)) sf_error("No ns=.");
    if (!sf_histint(us,"n4",&nw)) sf_error("No nw=.");
    if (!sf_histfloat(us,"d4",&dw)) sf_error("No dw=.");
    if (!sf_histfloat(us,"o4",&ow)) sf_error("No ow=.");

    /* read receiver wavefield */	
    if (NULL == sf_getstring("ur"))
	sf_error("Need receiver wavefield ur=");
    ur = sf_input("ur");    
    
    /* read wavelet */
    if (NULL == sf_getstring("wvlt"))
	sf_error("Need wvlt=");
    wvlt = sf_input("wvlt");
    
    f = sf_complexalloc2(nw,ns);
    sf_complexread(f[0],nw*ns,wvlt);
    sf_fileclose(wvlt);

    /* read list */
    if (NULL == sf_getstring("list"))
	sf_error("Need list=");
    list = sf_input("list");

    pp = sf_intalloc2(2,ns);
    sf_intread(pp[0],2*ns,list);
    sf_fileclose(list);

    /* allocate memory */
    swave = sf_complexalloc3(n1,n2,ns);
    rwave = sf_complexalloc3(n1,n2,ns);
    stemp = sf_complexalloc2(ns,ns);
    rtemp = sf_complexalloc2(ns,ns);

    ahesss = sf_floatalloc2(n1*n2,ns);
    ahessr = sf_floatalloc2(n1*n2,ns);

    ahess = sf_floatalloc(n1*n2);

    /* loop over frequency */
    for (iw=0; iw < nw; iw++) {
	omega = (double) 2.*SF_PI*(ow+iw*dw);	

	/* read wavefields */
	sf_complexread(swave[0][0],n1*n2*ns,us);
	sf_complexread(rwave[0][0],n1*n2*ns,ur);

#ifdef _OPENMP
#pragma omp parallel num_threads(uts) private(is,ip,i)
#endif
	{
#ifdef _OPENMP
#pragma omp for
#endif
	    for (is=0; is < ns; is++) {
		for (ip=0; ip < ns; ip++) {
		    /* temps */
		    stemp[is][ip] = -omega*omega/conjf(f[ip][iw])
			*rwave[is][pp[ip][1]][pp[ip][0]];
		    
		    /* tempr */
		    rtemp[is][ip] = -omega*omega/conjf(f[ip][iw])
			*conjf(swave[is][pp[ip][1]][pp[ip][0]]);
		}
	    }

	    /* loop over model */
#ifdef _OPENMP
#pragma omp for
#endif
	    for (i=0; i < n1*n2; i++) {
		for (is=0; is < ns; is++) {
		    for (ip=0; ip < ns; ip++) {
			ahesss[ip][i] += crealf(
			    conjf(swave[ip][0][i]*swave[is][0][i])*stemp[is][ip]);
			ahessr[ip][i] += crealf(
			    conjf(swave[ip][0][i])*rwave[is][0][i]*rtemp[is][ip]);
		    }
		}
	    }
	}	
    }

    /* assemble */
#ifdef _OPENMP
#pragma omp parallel for num_threads(uts) private(i,ip)
#endif
    for (i=0; i < n1*n2; i++) {
	for (ip=0; ip < ns; ip++) {
	    ahess[i] += powf(ahesss[ip][i]+ahessr[ip][i],2.);
	}
    }

    /* output hessian */
    sf_floatwrite(ahess,n1*n2,out);

    exit(0);
}
Example #22
0
int main (int argc, char* argv[])
{
    fint1 nmo;
    bool half;
    int ix,ih, nt,nx,nw, nh, noff, nmask, CDPtype, mute, *mask;
    float dt, t0, h0, dh, dy, str;
    float *trace, *off;
    mapfunc nmofunc;
    sf_file cmp, nmod, velocity, offset, msk, het;

    sf_init (argc,argv);
    cmp      = sf_input("in");
    velocity = sf_input("velocity");
    nmod     = sf_output("out");

    if (NULL != sf_getstring("s")) {
      	het = sf_input("s");
	nmofunc = shifted_nmo_map;	
    } else if (NULL != sf_getstring("a")) {
        het = sf_input("a");
        nmofunc = taner_nmo_map;
    } else {
	het = NULL;
	nmofunc =  nmo_map;
    } 

    if (SF_FLOAT != sf_gettype(cmp)) sf_error("Need float input");
    if (!sf_histint  (cmp,"n1",&nt)) sf_error("No n1= in input");
    if (!sf_histfloat(cmp,"d1",&dt)) sf_error("No d1= in input");
    if (!sf_histfloat(cmp,"o1",&t0)) sf_error("No o1= in input");
    if (!sf_histint  (cmp,"n2",&nh)) sf_error("No n2= in input");
    nx = sf_leftsize(cmp,2);

    if (!sf_getbool("half",&half)) half=true;
    /* if y, the second axis is half-offset instead of full offset */
    if (!sf_getfloat("str",&str)) str=0.5;
    /* maximum stretch allowed */

    if (!sf_getint("mute",&mute)) mute=12;
    /* mute zone */

    CDPtype=1;
    off = sf_floatalloc(nh);

    if (NULL != sf_getstring("offset")) {
	offset = sf_input("offset");
	if (SF_FLOAT != sf_gettype(offset)) sf_error("Need float offset");
	noff = sf_filesize(offset);
	if (noff == nh) {
	    sf_floatread (off,nh,offset);
	} else if (noff != nh*nx) {
	    sf_error("Wrong dimensions in offset");
	}
    } else {
	if (!sf_histfloat(cmp,"d2",&dh)) sf_error("No d2= in input");
	if (!sf_histfloat(cmp,"o2",&h0)) sf_error("No o2= in input");

	if (sf_histfloat(cmp,"d3",&dy) && !sf_getint("CDPtype",&CDPtype)) {
	    CDPtype=half? 0.5+dh/dy : 0.5+0.5*dh/dy;
	    if (CDPtype < 1) {
		CDPtype=1;
	    } else if (1 != CDPtype) {
		sf_histint(cmp,"CDPtype",&CDPtype);
	    	sf_warning("CDPtype=%d",CDPtype);
	    }
	} 	    

	for (ih = 0; ih < nh; ih++) {
	    off[ih] = h0 + ih*dh; 
	}

	noff = nh;
	offset = NULL;
    }
    
    if (NULL != sf_getstring("mask")) {
	msk = sf_input("mask");

	if (SF_INT != sf_gettype(msk)) sf_error("Need integer mask");
	nmask = sf_filesize(msk);
	mask = sf_intalloc(nh);

	if (nmask == nh) {
	    sf_intread (mask,nh,msk);
	} else if (nmask != nh*nx) {
	    sf_error("Wrong dimensions in mask");
	}
    } else {
	nmask = nh;

	msk = NULL;
	mask = NULL;
    }

    if (!sf_getbool("slowness",&slow)) slow=false;
    /* if y, use slowness instead of velocity */

    if (!sf_getbool("squared",&squared)) squared=false;
    /* if y, the slowness or velocity is squared */

    if (!sf_getfloat ("h0",&h0)) h0=0.;
    /* reference offset */
    if (half) h0 *= 2.;
    if (!sf_getint("extend",&nw)) nw=4;
    /* trace extension */

    trace = sf_floatalloc(nt);
    vel   = sf_floatalloc(nt);
    if (NULL != het) {
	par = sf_floatalloc(nt);
    } else {
	par = NULL;
    }

    nmo = fint1_init (nw, nt, mute);
    
    for (ix = 0; ix < nx; ix++) {
	sf_warning("CMP %d of %d;",ix+1,nx);

	sf_floatread (vel,nt,velocity);	
	if (NULL != het) sf_floatread(par,nt,het);
	if (NULL != offset && noff != nh) sf_floatread (off,nh,offset);
	if (NULL != msk && nmask != nh) sf_intread (mask,nh,msk);

	for (ih = 0; ih < nh; ih++) {
	    sf_floatread (trace,nt,cmp);
	    
	    /* skip dead traces */
	    if (NULL != msk && 0==mask[ih]) {
		sf_floatwrite (trace,nt,nmod);
		continue;
	    }
	    
	    fint1_set(nmo,trace);

	    h = off[ih];
	    if (NULL == offset) h += (dh/CDPtype)*(ix%CDPtype); 
	    if (half) h *= 2;
	    h = h*h - h0*h0;
	    
	    stretch(nmo,nmofunc,nt,dt,t0,nt,dt,t0,trace,str);
	    sf_floatwrite (trace,nt,nmod);
	}
    }
    sf_warning(".");

    exit (0);
}
Example #23
0
void mexFunction(int nlhs, mxArray *plhs[], 
		 int nrhs, const mxArray *prhs[])
{
    int taglen, status, argc=2, dim, n[SF_MAX_DIM], i, esize, len;
    size_t nbuf = BUFSIZ, nd, j;
    char *tag, *argv[] = {"matlab","-"}, *par;
    double *pr, *pi=NULL;
    char buf[BUFSIZ];
    off_t pos;
    static off_t shift=0;
    bool same;
    sf_datatype type;
    sf_file file;

    /* Check for proper number of arguments. */
    if (nrhs < 2 || nrhs > 3) mexErrMsgTxt("Two or three inputs required.");

    /* Second input must be a string. */
    if (!mxIsChar(prhs[1]))
	mexErrMsgTxt("Second input must be a string.");

    /* Second input must be a row vector. */
    if (mxGetM(prhs[1]) != 1)
	mexErrMsgTxt("Second input must be a row vector.");

    /* Get the length of the input string. */
    taglen = mxGetN(prhs[1]) + 1;

    /* Allocate memory for input string. */
    tag = mxCalloc(taglen, sizeof(char));

    /* Copy the input filename into a C string. */
    status = mxGetString(prhs[1], tag, taglen);
    if (status != 0) 
	mexWarnMsgTxt("Not enough space. String is truncated.");

    if (3 == nrhs) {
        /* Input 3 must be a string. */
	if (!mxIsChar(prhs[2]))
	    mexErrMsgTxt("Input 3 must be a string.");

	/* Input 3 must be a row vector. */
	if (mxGetM(prhs[2]) != 1)
	    mexErrMsgTxt("Input 3 must be a row vector.");

	/* Get the length of the input string. */
	len = mxGetN(prhs[2]) + 1;

	/* Allocate memory for input string. */
	par = mxCalloc(len, sizeof(char));

	/* Copy the string data from prhs[2] into a C string. */
	status = mxGetString(prhs[2], par, len);
	if (status != 0) 
	    mexWarnMsgTxt("Not enough space. String is truncated.");

	same = (0 == (strncmp(par,"same",4)));
    } else {
	same = false;
    }

    sf_init(argc,argv);
    file = sf_input(tag);

    dim = sf_filedims(file,n);
    type = sf_gettype (file);
    esize = sf_esize(file);

    /* data pointers */
    pr = mxGetPr(prhs[0]);

    /* get data size */
    nd = mxGetNumberOfElements(prhs[0]);

    pos = sf_tell(file);
    if (same) sf_seek(file,shift,SEEK_CUR);

    for (j=0, nbuf /= esize; nd > 0; nd -= nbuf) {
	if (nbuf > nd) nbuf=nd;

	switch(type) {
	    case SF_FLOAT:
		if (!mxIsDouble(prhs[0])) mexErrMsgTxt("First input must be double.");

		sf_floatread((float*) buf,nbuf,file);
		for (i=0; i < nbuf; i++, j++) {
		    pr[j] = (double) ((float*) buf)[i];
		}
		break;
	    case SF_INT:
		if (!mxIsDouble(prhs[0])) mexErrMsgTxt("First input must be double.");

		sf_intread((int*) buf,nbuf,file);
		for (i=0; i < nbuf; i++, j++) {
		    pr[j] = (double) ((int*) buf)[i];
		}
		break;
	    case SF_COMPLEX:
		if(!mxIsComplex(prhs[0])) mexErrMsgTxt("First input must be complex.");

		pi = mxGetPi(prhs[0]);

		sf_complexread((sf_complex*) buf,nbuf,file);
		for (i=0; i < nbuf; i++, j++) {
		    pr[j] = (double) crealf(((sf_complex*) buf)[i]);
		    pi[j] = (double) cimagf(((sf_complex*) buf)[i]);
		}
		break;
	    default:
		mexErrMsgTxt("Unsupported file type.");
		break;
	}
    }

    shift = sf_tell(file) - pos;
    sf_close();
}
Example #24
0
int main(int argc, char* argv[])
{
  bool adj; 
  float *input1, *output1, *filter;
  float **input2, **output2;
  float ***input3, ***output3;
  int *lag1,*lag2,*lag3,nd;
  int n1,n2,n3,nl,ndim,  n[SF_MAX_DIM];
  sf_axis axlag; 

  sf_file Fin=NULL; /* velocity  */
  sf_file Fout=NULL; /* density */
  sf_file Flag1=NULL; /* filter lags */
  sf_file Flag2=NULL; /* filter lags */
  sf_file Flag3=NULL; /* filter lags */
  sf_file Ffilter=NULL; /* filter lags */

  /*------------------------------------------------------------*/
  /*------------------------------------------------------------*/
  /* init RSF */
  sf_init(argc,argv);

  if(! sf_getbool("adj",&adj)) adj=false;
  if(! sf_getint("n",&nd)) nd=1;
  
  /*------------------------------------------------------------*/

  /*------------------------------------------------------------*/
  /* I/O files */
  
  Fin = sf_input ("in" ); /* wavelet   */
  Ffilter = sf_input ("filter"); /* filter lags */
  Fout = sf_output ("out"); /* velocity  */
  
  ndim =sf_filedims (Fin,n);

  if(ndim==1 || nd==1){
    sf_warning("1d conv,%d",ndim);
    n1 = n[0];
    input1 = sf_floatalloc(n1);
    output1 = sf_floatalloc(n1);
    Flag1 = sf_input ("lag"); /* filter lags */

    axlag = sf_iaxa(Flag1,1); 
    nl = sf_n(axlag);
    filter = sf_floatalloc(nl);
    lag1 = sf_intalloc(nl);
    sf_floatread(filter,nl,Ffilter);
    sf_intread(lag1,nl,Flag1);

    int ntraces = sf_leftsize(Fin,1);

    sf_warning("read n1=%d tr=%d",n1,ntraces);
    convkernel1_init(n1,nl,lag1,filter);
    for (int itr=0; itr<ntraces; ++itr){
      sf_floatread(input1,n1,Fin);
      if (adj){
        convkernel1_apply(output1,input1,adj);
      }else{
        convkernel1_apply(input1,output1,adj);
      }
      sf_floatwrite(output1,n1,Fout);
    }


    free(input1);
    free(output1);
    free(lag1);
    free(filter);

  }else if(ndim==2){ 
    sf_warning("2d conv");
    n1 = n[0];
    n2 = n[1];
    input2 = sf_floatalloc2(n1,n2);
    output2 = sf_floatalloc2(n1,n2);
    sf_floatread(input2[0],n1*n2,Fin);
    Flag1 = sf_input ("lag1"); /* filter lags */
    Flag2 = sf_input ("lag2"); /* filter lags */

    axlag = sf_iaxa(Flag1,1); 
    nl = sf_n(axlag);
    filter = sf_floatalloc(nl);
    lag1 = sf_intalloc(nl);
    lag2 = sf_intalloc(nl);
    sf_floatread(filter,nl,Ffilter);
    sf_intread(lag1,nl,Flag1);
    sf_intread(lag2,nl,Flag2);
    convkernel2_init(n1,n2,nl,lag1,lag2,filter);
    if (adj){
      convkernel2_apply(output2,input2,adj);
    }else{
      convkernel2_apply(input2,output2,adj);
    }
    sf_floatwrite(output2[0],n1*n2,Fout);
    free(*input2); free(input2);
    free(*output2); free(output2);
    free(lag1);
    free(lag2);
    free(filter);

  }else if(ndim==3){
    sf_warning("3d conv");
    n1 = n[0];
    n2 = n[1];
    n3 = n[2];

    input3 = sf_floatalloc3(n1,n2,n3);
    output3 = sf_floatalloc3(n1,n2,n3);
    sf_floatread(input3[0][0],n1*n2*n3,Fin);
    Flag1 = sf_input ("lag1"); /* filter lags */
    Flag2 = sf_input ("lag2"); /* filter lags */
    Flag3 = sf_input ("lag3"); /* filter lags */


    axlag = sf_iaxa(Flag1,1); 
    nl = sf_n(axlag);
    filter = sf_floatalloc(nl);
    lag1 = sf_intalloc(nl);
    lag2 = sf_intalloc(nl);
    lag3 = sf_intalloc(nl);
    sf_floatread(filter,nl,Ffilter);
    sf_intread(lag1,nl,Flag1);
    sf_intread(lag2,nl,Flag2);
    sf_intread(lag3,nl,Flag3);
    convkernel3_init(n1,n2,n3,nl,lag1,lag2,lag3,filter);
    if (adj){
      convkernel3_apply(output3,input3,adj);
    }else{
      convkernel3_apply(input3,output3,adj);
    }
    sf_floatwrite(output3[0][0],n1*n2*n3,Fout);
    free(**input3); free(*input3); free(input3);
    free(**input3); free(*output3); free(output3);
    free(lag1);
    free(lag2);
    free(lag3);
    free(filter);  
  }else{
      sf_warning("X conv");
      exit(1);
  }


  exit (0);
}
Example #25
0
int main(int argc, char* argv[])
{
    int i, ia, na, nx, ns, dim, n[SF_MAX_DIM], m[SF_MAX_DIM];
    float a0, *pp, *qq;
    bool adj;
    sf_filter aa;
    char* lagfile;
    sf_file in, out, filt, lag;

    sf_init (argc,argv);
    in = sf_input("in");
    filt = sf_input("filt");
    out = sf_output("out");

    dim = sf_filedims (in,n);

    if (!sf_histint(filt,"n1",&na)) sf_error("No n1= in filt");
    aa = sf_allocatehelix (na);

    if (!sf_histfloat(filt,"a0",&a0)) a0=1.;
    sf_floatread (aa->flt,na,filt);
    for( ia=0; ia < na; ia++) {
	aa->flt[ia] /= a0;
    }

    if (NULL != (lagfile = sf_getstring("lag")) /* file with filter lags */
	|| 
	NULL != (lagfile = sf_histstring(filt,"lag"))) {
	lag = sf_input(lagfile);

	sf_intread(aa->lag,na,lag);
    } else {
	lag = NULL;
	for( ia=0; ia < na; ia++) {
	    aa->lag[ia] = ia+1;
	}
    }

    sf_fileclose(filt);
    
    if (!sf_getints ("n",m,dim) && (NULL == lag ||
				    !sf_histints (lag,"n",m,dim))) {
	for (i=0; i < dim; i++) {
	    m[i] = n[i];
	}
    }
 
    if (NULL != lag) sf_fileclose(lag);

    regrid (dim, m, n, aa);

    if (!sf_getbool ("adj",&adj)) adj=false;
    /* if y, do adjoint operation */
    if (!sf_getint ("ns",&ns)) sf_error("Need ns=");
    /* scaling */

    nx = 1;
    for( i=0; i < dim; i++) {
	nx *= n[i];
    }
  
    pp = sf_floatalloc (nx);
    qq = sf_floatalloc (nx);

    if (adj) {
	sf_floatread (qq,nx,in);
    } else {
	sf_floatread (pp,nx,in);
    }

    hshape_init (nx,ns,aa);
    hshape_lop (adj,false,nx,nx,pp,qq);

    if (adj) {
	sf_floatwrite (pp,nx,out);
    } else {
	sf_floatwrite (qq,nx,out);
    }


    exit (0);
}
Example #26
0
int main (int argc, char* argv[]) 
{
    int *sft[SF_MAX_DIM];
    int box[SF_MAX_DIM], n[SF_MAX_DIM];
    int dim, dim1, i, n1, n2, i1, i2, b, nrep;
    float *data, *smoo, *rct[SF_MAX_DIM];
    char key[8];
    sf_file in, out, rect[SF_MAX_DIM], shift[SF_MAX_DIM];

    sf_init (argc, argv);
    in = sf_input ("in");
    out = sf_output ("out");

    if (SF_FLOAT != sf_gettype(in)) sf_error("Need float input");
 
    if (!sf_getint("repeat",&nrep)) nrep=1;
    /* repeat filtering several times */

    dim = sf_filedims (in,n);

    dim1 = -1;
    for (i=0; i < dim; i++) {
	snprintf(key,6,"rect%d",i+1);
	if (NULL != sf_getstring(key)) {
	    /*( rect# size of the smoothing stencil in #-th dimension /auxiliary input file/ )*/
	    rect[i] = sf_input(key);
	    if (SF_FLOAT != sf_gettype(rect[i])) sf_error("Need float %s",key);
	    dim1 = i;
	    snprintf(key,8,"shift%d",i+1);
	    if (NULL != sf_getstring(key)) {
		/*( shift# shifting of the smoothing stencil in #-th dimension /auxiliary input file/ )*/
		shift[i] = sf_input(key);
		if (SF_INT != sf_gettype(shift[i])) sf_error("Need int %s",key);
	    } else {
		shift[i] = NULL;
	    }
	} else {
	    rect[i] = NULL;
	    shift[i] = NULL;
	}
    }

    n1 = n2 = 1;
    for (i=0; i < dim; i++) {
	if (i <= dim1) {
	    n1 *= n[i];
	} else {
	    n2 *= n[i];
	}
    }

    data = sf_floatalloc (n1);
    smoo = sf_floatalloc (n1);

    for (i=0; i <= dim1; i++) {
	box[i] = 1;
	if (NULL != rect[i]) {
	    rct[i] = sf_floatalloc (n1);
	    sft[i] = sf_intalloc (n1);

	    sf_floatread(rct[i],n1,rect[i]);
	    sf_fileclose(rect[i]);

	    if (NULL != shift[i]) {
		sf_intread(sft[i],n1,shift[i]);
		sf_fileclose(shift[i]);
	    } else {
		for (i1=0; i1 < n1; i1++) {
		    sft[i][i1] = 0;
		}
	    }

		
	    for (i1=0; i1 < n1; i1++) {
		b = ceilf(rct[i][i1])+SF_ABS(sft[i][i1]);
		if (b > box[i]) box[i] = b;
	    }	    
	} else {
	    rct[i] = NULL;
	    sft[i] = NULL;
	}
    }

    ntrianglen_init(dim1+1,box,n,rct,sft,nrep);

    for (i2=0; i2 < n2; i2++) {
	sf_floatread(data,n1,in);

	ntrianglen_lop(false,false,n1,n1,data,smoo);
	
	sf_floatwrite(smoo,n1,out);
    }    


    exit (0);
}
Example #27
0
int main(int argc, char* argv[])
{
    int n[SF_MAX_DIM], a[SF_MAX_DIM], center[SF_MAX_DIM], gap[SF_MAX_DIM];
    int *pch, *nh, dim, n123, nf, i, niter, nbf, nbp, id, ip, ig, np;
    int *kk, *pp;
    float *dd, eps, dabs, di;
    nfilter aa, bb;
    char varname[6], *lagfile;
    sf_file in, flt, lag, mask, patch, reg;

    sf_init(argc,argv);
    in = sf_input("in");
    flt = sf_output("out");

    dim = sf_filedims(in,n);

    if (NULL == (lagfile = sf_getstring("lag"))) sf_error("Need lag=");
    /* output file for filter lags */

    lag = sf_output(lagfile);
    sf_settype(lag,SF_INT);

    sf_putstring(flt,"lag",lagfile);

    sf_putints(lag,"n",n,dim);

    if (!sf_getints("a",a,dim)) sf_error("Need a=");

    if (!sf_getints("center",center,dim)) {
        for (i=0; i < dim; i++) {
            center[i] = (i+1 < dim && a[i+1] > 1)? a[i]/2: 0;
        }
    }

    if (!sf_getints("gap",gap,dim)) {
        for (i=0; i < dim; i++) {
            gap[i] = 0;
        }
    }

    n123 = 1;
    for (i=0; i < dim; i++) {
        n123 *= n[i];
    }

    dd = sf_floatalloc(n123);
    kk = sf_intalloc(n123);

    if (NULL != sf_getstring("maskin")) {
        /* optional input mask file */
        mask = sf_input("maskin");

        switch (sf_gettype(mask)) {
        case SF_INT:
            sf_intread (kk,n123,mask);
            break;
        case SF_FLOAT:
            sf_floatread (dd,n123,mask);
            for (i=0; i < n123; i++) {
                kk[i] = (dd[i] != 0.);
            }
            break;
        default:
            sf_error ("Wrong data type in maskin");
            break;
        }

        sf_fileclose (mask);
    } else {
        for (i=0; i < n123; i++) {
            kk[i] = 1;
        }
    }

    sf_floatread(dd,n123,in);

    dabs = fabsf(dd[0]);
    for (i=1; i < n123; i++) {
        di = fabsf(dd[i]);
        if (di > dabs) dabs=di;
    }

    random_init(2004);
    for (i=0; i < n123; i++) {
        dd[i] = dd[i]/dabs+ 100.*FLT_EPSILON*(random0()-0.5);;
    }

    pp = sf_intalloc(n123);
    if (NULL != sf_getstring("pch")) {
        patch = sf_input("pch");
        if (SF_INT != sf_gettype(patch)) sf_error("Need int pch");

        sf_intread(pp,n123,patch);

        np = pp[0];
        for (i=1; i < n123; i++) {
            if (pp[i] > np) np = pp[i];
        }

        sf_fileclose(patch);
    } else {
        np = n123;
        for (i=0; i < n123; i++) {
            pp[i] = i;
        }
    }

    aa = createnhelix(dim, n, center, gap, a, pp);
    free (pp);

    nf = aa->hlx[0]->nh;
    nfind_mask(n123, kk, aa);

    if(!sf_getint("niter",&niter)) niter=100;
    /* number of iterations */
    if (!sf_getfloat("epsilon",&eps)) eps=0.01;
    /* regularization parameter */

    sf_putint(flt,"n1",nf);
    sf_putint(flt,"n2",np);

    sf_putint(lag,"n1",nf);
    sf_putint(lag,"n2",np);

    for (i=2; i < dim; i++) {
        sprintf(varname,"n%d",i+1);
        sf_putint(flt,varname,1);
        sf_putint(lag,varname,1);
    }

    for (ip=0; ip < np; ip++) {
        sf_intwrite(aa->hlx[ip]->lag,nf,lag);
    }
    sf_fileclose(lag);

    if (NULL != sf_getstring("maskout")) {
        /* optional output mask file */
        mask = sf_output("maskout");

        for (i=0; i < n123; i++) {
            kk[i] = aa->mis[i]? 0.: 1.;
        }

        sf_settype(mask,SF_INT);
        sf_intwrite (kk,n123,mask);
    }

    reg = sf_input("filt");
    if (!sf_histint(reg,"n1",&nbf)) sf_error("No n1= in filt");
    if (!sf_histint(reg,"n2",&nbp)) sf_error("No n2= in filt");

    if (NULL != sf_getstring("filt_pch")) {
        patch = sf_input("filt_pch");
        if (SF_INT != sf_gettype(patch)) sf_error("Need int filt_pch");


        pp = sf_intalloc(np);
        sf_intread(pp,np,patch);
    } else {
        if (nbp != np) sf_error ("Wrong filter size: %d != %d",nbp,np);
        pp = NULL;
    }

    pch = sf_intalloc(nf*np);
    nh = sf_intalloc(nbp);

    for (i=0; i < nbp; i++) {
        nh[i] = nbf;
    }

    for (id=ig=0; ig < nf; ig++) {
        for (ip=0; ip < np; ip++, id++) {
            pch[id] = (NULL != pp)? pp[ip]: ip;
        }
    }

    bb = nallocate (nbp, nf*np, nh, pch);

    if (NULL == (lagfile = sf_getstring("filt_lag")) &&
            NULL == (lagfile = sf_histstring(reg,"lag")))
        sf_error("Need filt_lag=");
    /* input file for double-helix filter lags */

    lag = sf_input(lagfile);
    if (SF_INT != sf_gettype(lag)) sf_error("Need int filt_lag");

    for (ip=0; ip < nbp; ip++) {
        sf_intread (kk,nbf,lag);
        for (i=0; i < nbf; i++) {
            bb->hlx[ip]->lag[i] = kk[i]*nf;
        }
    }

    for (ip=0; ip < nbp; ip++) {
        sf_floatread (bb->hlx[ip]->flt,nbf,reg);
    }

    nfind_pef (n123, dd, aa, bb, niter, eps, nf);

    for (ip=0; ip < np; ip++) {
        sf_floatwrite (aa->hlx[ip]->flt,nf,flt);
    }


    exit(0);
}
Example #28
0
int main (int argc, char* argv[])
{
    fint1 nmo;
    bool half, squared, slow;
    int ix,ih,it,iv, nt,nx,nw, nh, nh2, m, CDPtype, mute, *mask, nv, *fold;
    float dt, t0, h0,dh,h, dy, str, v0,dv,v;
    float **traces, *trace, *off, *stack;
    double *dstack;
    mapfunc nmofunc;
    sf_file cmp, stk, offset, msk;

    sf_init (argc,argv);
    cmp = sf_input("in");
    stk = sf_output("out");
    nmofunc =  nmo_map;
    
    if (SF_FLOAT != sf_gettype(cmp)) sf_error("Need float input");
    if (!sf_histint  (cmp,"n1",&nt)) sf_error("No n1= in input");
    if (!sf_histfloat(cmp,"d1",&dt)) sf_error("No d1= in input");
    if (!sf_histfloat(cmp,"o1",&t0)) sf_error("No o1= in input");
    if (!sf_histint  (cmp,"n2",&nh)) sf_error("No n2= in input");
    nx = sf_leftsize(cmp,2);

    if (!sf_getbool("half",&half)) half=true;
    /* if y, the second axis is half-offset instead of full offset */
    if (!sf_getfloat("str",&str)) str=0.5;
    /* maximum stretch allowed */

    if (!sf_getint("mute",&mute)) mute=12;
    /* mute zone */

    if (!sf_getint("nv",&nv)) sf_error("Need nv=");
    /* number of velocities */
    
    if (!sf_getfloat("v0",&v0)) sf_error("Need v0=");
    /* first velocity */
    
    if (!sf_getfloat("dv",&dv)) sf_error("Need dv=");
    /* step in velocity */

    sf_putint(stk,"n2",nv);
    sf_putfloat(stk,"o2",v0);
    sf_putfloat(stk,"d2",dv);

    CDPtype=1;
    if (NULL != sf_getstring("offset")) {
	offset = sf_input("offset");
	if (SF_FLOAT != sf_gettype(offset)) sf_error("Need float offset");
	nh2 = sf_filesize(offset);
	if (nh2 != nh && nh2 != nh*nx) sf_error("Wrong dimensions in offset");

	off = sf_floatalloc(nh2);	
	sf_floatread (off,nh2,offset);
	sf_fileclose(offset);
    } else {
	if (!sf_histfloat(cmp,"d2",&dh)) sf_error("No d2= in input");
	if (!sf_histfloat(cmp,"o2",&h0)) sf_error("No o2= in input");

	if (sf_histfloat(cmp,"d3",&dy) && !sf_getint("CDPtype",&CDPtype)) {
	    CDPtype=half? 0.5+dh/dy : 0.5+0.5*dh/dy;
	    if (CDPtype < 1) {
		CDPtype=1;
	    } else if (1 != CDPtype) {
		sf_histint(cmp,"CDPtype",&CDPtype);
	    	sf_warning("CDPtype=%d",CDPtype);
	    }
	} 	    

	nh2 = nh;
	off = sf_floatalloc(nh2);
	for (ih = 0; ih < nh; ih++) {
	    off[ih] = h0 + ih*dh; 
	}

	offset = NULL;
    }
    
    if (NULL != sf_getstring("mask")) {
	msk = sf_input("mask");
	if (SF_INT != sf_gettype(msk)) sf_error("Need integer mask");
	nh2 = sf_filesize(msk);
	if (nh2 != nh && nh2 != nh*nx) sf_error("Wrong dimensions in mask");
	mask = sf_intalloc(nh2);
	sf_intread (mask,nh2,msk);
	sf_fileclose(msk);
    } else {
	msk = NULL;
	mask = NULL;
    }

    if (!sf_getbool("slowness",&slow)) slow=false;
    /* if y, use slowness instead of velocity */

    if (!sf_getbool("squared",&squared)) squared=false;
    /* if y, the slowness or velocity is squared */

    if (!sf_getfloat ("h0",&h0)) h0=0.;
    /* reference offset */
    if (half) h0 *= 2.;
    if (!sf_getint("extend",&nw)) nw=4;
    /* trace extension */

    traces = sf_floatalloc2(nt,nh);
    trace  = sf_floatalloc(nt);
    stack  = sf_floatalloc(nt);
    fold   = sf_intalloc(nt);
    dstack = (double*) sf_alloc(nt,sizeof(double));

    nmo = fint1_init (nw, nt, mute);
    
    for (ix = 0; ix < nx; ix++) {
	sf_warning("CMP %d of %d;",ix+1,nx);
	sf_floatread (traces[0],nt*nh,cmp);

	for (iv=0; iv < nv; iv++) {
	    v = v0+iv*dv;
	    if (!squared) v *=v;

	    for (it=0; it < nt; it++) {
		dstack[it] = 0.0;
		fold[it] = 0;
	    }

	    for (ih = 0; ih < nh; ih++) {
		/* skip dead traces */
		if (NULL != msk) {
		    m = (nh2 == nh)? mask[ih] + (dh/CDPtype)*(ix%CDPtype) : 
			mask[ix*nh+ih];	
		    if (0==m) continue;
		}
		
		for (it=0; it < nt; it++) {
		    trace[it] = traces[ih][it];
		}
	    
		fint1_set(nmo,trace);

		h = (nh2 == nh)? off[ih] + (dh/CDPtype)*(ix%CDPtype) : 
		    off[ix*nh+ih];
		if (half) h *= 2;
		h = h*h - h0*h0;
		v2 = slow ? h*v : h/v;

		stretch(nmo,nmofunc,nt,dt,t0,nt,dt,t0,trace,str);

		for (it=0; it < nt; it++) {
		    if (trace[it] != 0.0f) {
			fold[it]++;
			dstack[it] += trace[it];
		    }
		}
	    }

	    for (it=0; it < nt; it++) {
		if (fold[it] > 0) {
		    stack[it] = dstack[it]/fold[it];
		} else {
		    stack[it] = 0.0f;
		}
	    }
			
	    sf_floatwrite (stack,nt,stk);
	}
    }
    sf_warning(".");

    exit (0);
}
Example #29
0
int main(int argc, char* argv[])
{
    int n123, n1, i, ik, dim, nk, nf, sf, niter, nw;
    int n[SF_MAX_DIM], w[SF_MAX_DIM], k[SF_MAX_DIM];
    int sa[SF_MAX_DIM], na[SF_MAX_DIM], sc[SF_MAX_DIM], nc[SF_MAX_DIM];
    int ma[SF_MAX_DIM], mc[SF_MAX_DIM]; 
    float *data, *wind, *sign, eps, di, dabs;
    char varname[6], *lagfile;
    sf_filter saa, naa, sbb, nbb, scc, ncc;
    sf_file dat, signal, spef, npef, slag, nlag;

    sf_init (argc,argv);
    dat = sf_input("in");
    signal = sf_output("out");

    spef = sf_input("sfilt");
    npef = sf_input("nfilt");

    n123 = sf_filesize(dat);
    if (!sf_histint(spef,"dim",&dim)) sf_error("No dim= in sfilt");

    n1 = 1;
    for (i=0; i < dim; i++) {
	sprintf(varname,"n%d",i+1);
	if (!sf_histint(dat,varname,n+i)) 
	    sf_error("No %s= in input",varname);
	n1 *= n[i];
    }

    if (!sf_histints(spef,"w",w,dim)) sf_error("No w= in sfilt");
    if (!sf_histints(spef,"k",k,dim)) sf_error("No k= in sfilt");

    if (!sf_histints(spef,"a",sa,dim)) sf_error("No a= in sfilt");
    if (!sf_histints(npef,"a",na,dim)) sf_error("No a= in nfilt");

    if (!sf_histints(spef,"center",sc,dim)) sf_error("No center= in sfilt");
    if (!sf_histints(npef,"center",nc,dim)) sf_error("No center= in nfilt");

    nk=nw=1;
    for (i=0; i < dim; i++) {
	nw *= w[i];
	nk *= k[i];
    }

    if (!sf_histint(spef,"n1",&sf)) sf_error("No n1= in sfilt");
    if (!sf_histint(npef,"n1",&nf)) sf_error("No n1= in nfilt");

    sbb = sf_allocatehelix(sf);
    nbb = sf_allocatehelix(nf);

    if (NULL == (lagfile = sf_histstring(spef,"lag")) &&
	NULL == (lagfile = sf_getstring("slag"))) 
	sf_error("Need slag=");
    slag = sf_input(lagfile);
    if (NULL == (lagfile = sf_histstring(npef,"lag")) &&
	NULL == (lagfile = sf_getstring("nlag"))) 
	sf_error("Need nlag=");
    nlag = sf_input(lagfile);

    sf_intread(sbb->lag,sf,slag);
    sf_intread(nbb->lag,nf,nlag);

    if (!sf_getfloat("eps",&eps)) sf_error("Need eps=");
    /* regularization parameter */
    if (!sf_getint("niter",&niter)) niter=20;
    /* number of iterations */

    data = sf_floatalloc(n123);
    sign = sf_floatalloc(n123);

    sf_floatread(data,n123,dat);

    dabs = fabsf(data[0]);
    for (i=1; i < n123; i++) {
	di = fabsf(data[i]);
	if (di > dabs) dabs=di;
    }

    for (i=0; i < n123; i++) {
	data[i] /= dabs;
    }

    saa = (sf_filter) sf_alloc(nk,sizeof(*saa));
    naa = (sf_filter) sf_alloc(nk,sizeof(*naa));

    for (ik=0; ik < nk; ik++) {
	scc = saa+ik;
	ncc = naa+ik;
	scc->nh = sf;
	ncc->nh = nf;
	scc->flt = sf_floatalloc(sf);
	ncc->flt = sf_floatalloc(nf);
	scc->lag = sbb->lag;
	ncc->lag = nbb->lag;
	scc->mis = NULL;
	ncc->mis = NULL;
    }

    wind = sf_floatalloc(nw);

    for (i=0; i < dim; i++) {
	mc[i] = SF_MIN(sc[i],nc[i]);
	ma[i] = SF_MIN(sa[i],na[i]);
    }

    tent (dim, w, mc, ma, wind);
 
    for (i=0; i < n123-n1+1; i += n1) {
	signoi_init (naa, saa, niter, nw, eps, false);
	for (ik=0; ik < nk; ik++) {
	    sf_floatread((naa+ik)->flt,nf,npef);
	    sf_floatread((saa+ik)->flt,sf,spef);
	}
	patching (signoi_lop, data+i, sign+i, dim, k, n, w, wind);
    }

    sf_floatwrite (sign,n123,signal);

    exit(0);
}
Example #30
0
int main(int argc, char* argv[]) 
{
    int i1, i2;  /* Counters over input */
    int n1, n2, nonzero;  /* Input dims, nr of nonzero elements */
    int i; /* Counter over output */
    int n; /* Output size */
    int ndims_in = 2; /* Input dimensionality */
    int n2_out; /* Output n2 */
    int   *trci=NULL; /* Input trace (int data) */
    float *trcf=NULL; /* Input trace (float data) */
    float *oa=NULL; /* Output array */
    float o1, d1, o2, d2; /* Input axes origin and sampling */
    sf_file in=NULL, out=NULL; /* Input, output files */
    sf_datatype inp_type; /* Input data type */

    sf_init(argc,argv);

    in = sf_input("in");
    out = sf_output("out");

    if (!sf_histint(in, "n1", &n1)) sf_error("Need n1=");
    /* number of histogram samples */
    if (!sf_histfloat(in, "o1", &o1)) sf_error("Need o1=");
    /* histogram origin */
    if (!sf_histfloat(in, "d1", &d1)) sf_error("Need d1=");
    /* histogram sampling */
    if (!sf_histint(in, "n2", &n2)) sf_error("Need n2=");
    /* number of histogram samples in dimension 2 */
    if (!sf_histfloat(in, "o2", &o2)) sf_error("Need o2=");
    /* histogram origin for dimension 2 */
    if (!sf_histfloat(in, "d2", &d2)) sf_error("Need d2=");
    /* histogram sampling for dimension 2 */

    if (!sf_getint("nonzero",&nonzero)) nonzero = n1*n2;
    /* Number of nonzero elements in input */

    inp_type = sf_gettype(in);

    if (inp_type == SF_INT) {
        trci = sf_intalloc(n1);
        sf_settype(out,SF_FLOAT);
    }
    else if (inp_type != SF_FLOAT) {
        sf_error("Need float or int input");
    }

    n2_out = ndims_in + 1;
    n = n2_out * nonzero;
    trcf = sf_floatalloc(n1);
    oa = sf_floatalloc(n);

    sf_putint(out, "n1", nonzero);
    sf_putint(out, "n2", n2_out);

    i = 0;

    /* Duplicating boilerplate code to avoid conditionals inside loops */

    for (i2=0; i2 < n2; i2++) {

        if (inp_type == SF_INT) {
            sf_intread(trci, n1, in);
            for (i1=0; i1 < n1; i1++) {
                trcf[i1] = trci[i1];
            }
        } else {
            sf_floatread(trcf,n1,in);
        }

        for (i1=0; i1 < n1; i1++) {
            if (trcf[i1] != 0) {
                if (i==nonzero) sf_error("nonzero was too small!");
                oa[i            ] = trcf[i1];
                oa[i + nonzero  ] = o1 + i1*d1;
                oa[i + nonzero*2] = o2 + i2*d2;
                i++;
            }
        }
    }
    if (i<nonzero-1) sf_error("nonzero was too big!");
    sf_floatwrite(oa, n, out);

    exit(0);
}