Exemplo n.º 1
0
    Real CPICashFlow::amount() const {
        Real I0 = baseFixing();
        Real I1;

        // what interpolation do we use? Index / flat / linear
        if (interpolation() == CPI::AsIndex ) {
            I1 = index()->fixing(fixingDate());
        } else {
            // work out what it should be
            //std::cout << fixingDate() << " and " << frequency() << std::endl;
            //std::pair<Date,Date> dd = inflationPeriod(fixingDate(), frequency());
            //std::cout << fixingDate() << " and " << dd.first << " " << dd.second << std::endl;
            // work out what it should be
            std::pair<Date,Date> dd = inflationPeriod(fixingDate(), frequency());
            Real indexStart = index()->fixing(dd.first);
            if (interpolation() == CPI::Linear) {
                Real indexEnd = index()->fixing(dd.second+Period(1,Days));
                // linear interpolation
                //std::cout << indexStart << " and " << indexEnd << std::endl;
                I1 = indexStart + (indexEnd - indexStart) * (fixingDate() - dd.first)
                / ( (dd.second+Period(1,Days)) - dd.first); // can't get to next period's value within current period
            } else {
                // no interpolation, i.e. flat = constant, so use start-of-period value
                I1 = indexStart;
            }

        }


        if (growthOnly())
            return notional() * (I1 / I0 - 1.0);
        else
            return notional() * (I1 / I0);
    }
Exemplo n.º 2
0
    SwaptionVolCube1::Cube::Cube(
                                    const std::vector<Date>& optionDates,
                                    const std::vector<Period>& swapTenors,
                                    const std::vector<Time>& optionTimes,
                                    const std::vector<Time>& swapLengths,
                                    Size nLayers,
                                    bool extrapolation)
    : optionTimes_(optionTimes), swapLengths_(swapLengths),
      optionDates_(optionDates), swapTenors_(swapTenors),
      nLayers_(nLayers), extrapolation_(extrapolation) {

        QL_REQUIRE(optionTimes.size()>1,"Cube::Cube(...): optionTimes.size()<2");
        QL_REQUIRE(swapLengths.size()>1,"Cube::Cube(...): swapLengths.size()<2");

        QL_REQUIRE(optionTimes.size()==optionDates.size(),
                   "Cube::Cube(...): optionTimes/optionDates mismatch");
        QL_REQUIRE(swapTenors.size()==swapLengths.size(),
                   "Cube::Cube(...): swapTenors/swapLengths mismatch");

        std::vector<Matrix> points(nLayers_, Matrix(optionTimes_.size(),
                                                    swapLengths_.size(), 0.0));

        for (Size k=0;k<nLayers_;k++) {
            transposedPoints_.push_back(transpose(points[k]));

            boost::shared_ptr<Interpolation2D> interpolation (new
                BilinearInterpolation (optionTimes_.begin(), optionTimes_.end(),
                                       swapLengths_.begin(), swapLengths_.end(),
                                       transposedPoints_[k]));
            interpolators_.push_back(boost::shared_ptr<Interpolation2D>(
                new FlatExtrapolator2D(interpolation)));
            interpolators_[k]->enableExtrapolation();
        }
        setPoints(points);
     }
Exemplo n.º 3
0
///==========================================================================================================================================
/// Friend Functions
///==========================================================================================================================================
inline const AABB3D Interpolate(const AABB3D& start, const AABB3D& end, float fractionFromStartToEnd){
	const Vec3 interpolatedMins = Interpolate(start.mins, end.mins, fractionFromStartToEnd);
	const Vec3 interpolatedMaxs = Interpolate(start.maxs, end.maxs, fractionFromStartToEnd);

	AABB3D interpolation(interpolatedMins, interpolatedMaxs);
	return interpolation;
}
Exemplo n.º 4
0
void Ploter::plotCorrectedHll(string filename){
	ofstream file(filename);
	string line;
	int x1, x2;
	double y1, y2;
	x1 = 0;
	y1 = 0;
	x2 = CARDMAX/STEP-1;
	y2 = 0;
	uint64_t hash;
	uint64_t hash128[2];
	
	vector<double> estimates = makeVector();
	
	int i;
	vector< vector<double> > tab(CARDMAX/STEP, vector<double>(TESTS));
	
	int ca = 0;
	for(i = 0; i < TESTS; i ++){
		cout << i << endl;
		Hll hll(14);
		
		for(int j = 0; j < CARDMAX; j++){
			MurmurHash3_x86_128(&ca, 4, 0, &hash128);
			ca++;
			hash = hash128[0];
			hll.AddItem64(hash);
			if(j%STEP == 0){
				double count = hll.CountRaw64();
				for(int i = 0; i < CARDMAX/STEP-1; i++){
					if(estimates[i] <= count && count < estimates[i+1]){
						x1 = estimates[i];
						y1 = i*STEP;
						x2 = estimates[i+1];
						y2 = (i+1)*STEP;
						count = interpolation(count, x1, y1, x2, y2);
					}
				}
				//count = interpolation(count, x1, y1, x2, y2);
				//count = (double)abs(count-j)/j;
				tab[j/STEP][i]=count;
			}
		}
	}
	
	for(int j = 0; j < CARDMAX/STEP; j++){
		double sum = 0;
		for (int k = 0; k < TESTS; k++){
			sum= sum + tab[j][k];
		}
		//cout << sum << endl;
		double median = percentile(tab[j],0.5);
		double pct01 = percentile(tab[j],0.01);
		double pct99 = percentile(tab[j],0.99);
		file << (j*STEP) << "\t" << (double)sum/TESTS << "\t" << (double)median << "\t" << pct01 << "\t" << pct99 << endl;
	}
	
}
Exemplo n.º 5
0
// equations 28 and 30;
double IonSpectrumInwards(double r, double E)
{
    double flux, dr;
    double term1 = 0, term2 = 0;
    double (*PhiPtr)(double);
    PhiPtr = &Potential_Phi;

    dr = Potential_Phi_Inv( E/q + Potential_Phi(r) );

    if ( dr < r )
        dr = roundf(dr * 10000) / 10000 + 1e-5;

    term1  = 1/q;
    term1 *= pow(dr/r,2);
    term1 *= interpolation(Table->S, dr) / abs(differentiat(*PhiPtr, dr));
    term1 /= 1 - pow(fusor->Tc * g(0,dr),2);

    if ( fusor->a < r )
    {
        // inwards flux outside the cathode
        if ( dr < r || fusor->b < dr )
        {
            printf("IonSpectrumInwards error: dr < r or b < dr:\n \tr = %E\n \tdr = %E\n \tE = %E\n", r, dr, E);

            return NAN;
        }

        term1  *= g(r,dr);

        if ( DELTA(E - ParticleEnergy1(r)) )
            term2  = pow(fusor->b/r,2) * EdgeIonFlux * f(r);

        flux = term1 + term2;
    }
    else
    {
        if ( dr < fusor->a || fusor->b < dr )
        {
            printf("IonSpectrumInwards error: dr < a or b < dr:\n \tr = %E\n \tdr = %E\n \tE = %E\n", r, dr, E);

            return NAN;
        }

        // inwards flux inside the cathode
        term1 *= g(fusor->a,dr) * exp(fusor->ngas* CrosssecCX(ParticleEnergy2(fusor->a,dr)) * (r - fusor->a));

        if ( DELTA(E - ParticleEnergy1(r)) )
        {
            term2  = pow(fusor->b/r,2) * EdgeIonFlux ;
            term2 *= f(fusor->a) * exp(fusor->ngas* CrosssecCX(ParticleEnergy1(fusor->a)) * (r - fusor->a));
        }

        flux = fusor->Tc * (term1 + term2);
    }

    return flux;
}
Exemplo n.º 6
0
float Octave::getValueAt(float x, float y)
{
    float f_dimension = (float)dimension;

    int x_i = (int)(f_dimension*x);
    int y_i = (int)(f_dimension*y);

    float x_r = x*dimension -(float)x_i;
    float y_r = y*dimension - (float)y_i;

    float x0y0 = getValueAt(x_i, y_i);
    float x1y1 = getValueAt(x_i+1, y_i+1);
    float x0y1 = getValueAt(x_i, y_i+1);
    float x1y0 = getValueAt(x_i+1, y_i);

    return ( (1-x_r)*interpolation(x0y0, x0y1, y_r) + x_r*interpolation(x1y0, x1y1, y_r)
            + (1-y_r)*interpolation(x0y0, x1y0, x_r) + y_r*interpolation(x0y1, x1y1, x_r) )*0.5; 
}
Exemplo n.º 7
0
void get_interpolation_res(const del_point2d_t& ball)
{
	triangle tr =searchtri(ball);
	tr.print();
	vector<formation> f2(3);
	for(int i=0;i<3;++i)
	f2[i] = f[tr.x[i]];// , f[tr.x[1]], f[tr.x[2]] };
	formation gg  = interpolation(f2,ball);
	cout << "Result : \n";
		gg.print();

}
Exemplo n.º 8
0
 void SwaptionVolCube1::Cube::updateInterpolators() const {
     for (Size k=0; k<nLayers_; ++k) {
         transposedPoints_[k] = transpose(points_[k]);
         boost::shared_ptr<Interpolation2D> interpolation (
             new BilinearInterpolation (optionTimes_.begin(), optionTimes_.end(),
                                        swapLengths_.begin(), swapLengths_.end(),
                                        transposedPoints_[k]));
         interpolators_[k] = boost::shared_ptr<Interpolation2D>(
             new FlatExtrapolator2D(interpolation));
         interpolators_[k]->enableExtrapolation();
     }
 }
/* from input buffer to acc
 */
static void process_intput_buffer(pitch_t pitch)
{
    register int i, len = pitch->step;

    /* forwards sweep */
    interpolation(pitch, 
                  pitch->buf+pitch->overlap, pitch->step+pitch->overlap, 
                  pitch->tmp, pitch->step,
                  pitch->rate);
    
    for (i=0; i<len; i++)
        pitch->acc[i] = pitch->fade[i]*pitch->tmp[i];

    /* backwards sweep */
    interpolation(pitch,
                  pitch->buf, pitch->step+pitch->overlap,
                  pitch->tmp, pitch->step,
                  -pitch->rate);
    
    for (i=0; i<len; i++)
        pitch->acc[i] += pitch->fade[pitch->step-i-1]*pitch->tmp[i];
}
Exemplo n.º 10
0
void solveProblem(char * filename, int d1, int d2,int B, bool fromPoints)
{
    char * polynomial1, * polynomial2;
    BivariatePolynomial * Bp1;
    BivariatePolynomial * Bp2;
    if(fromPoints == true)
    {
        MatrixXd pointsMatrix, pointsMatrix2;
        Parser::readPoints(pointsMatrix, pointsMatrix2, cin);
        cout<<"Points 1 :"<<endl;
        cout<<pointsMatrix<<endl;
        cout<<"Points 2 :"<<endl;
        cout<<pointsMatrix2<<endl;
        ofstream equationsTxt;
        equationsTxt.open("InterpolationEquations.txt");
        Interpolation interpolation(d1, pointsMatrix), interpolation2(d2 , pointsMatrix2);
        Bp1 = interpolation.find(equationsTxt);
        Bp2 = interpolation2.find(equationsTxt);
        if(Bp1 == NULL || Bp2 == NULL) {
            cout << "Error in interpolation" << endl;
            exit(0);
        }
        equationsTxt.close();
        //interpolation logic
    }
    else
    {
        Parser::readInput(filename, polynomial1, polynomial2);					//read d1, d2, p1, p2
        fprintf(stdout,"Equations \n------- \n%s\n%s\n ", polynomial1, polynomial2);
        int systemDegree=0;
        Bp1 = new BivariatePolynomial(polynomial1, d1);			//initialize Bp1, Bp2
        Bp2 = new BivariatePolynomial(polynomial2, d2);
    }
    SylvesterMatrix * SM = new SylvesterMatrix(Bp1, Bp2);					//construct the sylvester matrix from Bp1 and Bp2
    SylvesterPolynomial * SP = new SylvesterPolynomial(SM->getHiddenDeg(), SM->getRowDimension());	//sylvester polynomial of sylvester matrix hidden variable degree
    SP->SMatrixToSPolynomial(SM);								//convert Sylvester Matrix to sylvester polynomial
    MyMatrix * m = new MyMatrix(SM->getRowDimension(), 1);					//random matrix of 1 column (the vector v)
/*  m->generate();
    cout<<"multiplying Sylvester Matrix with"<<endl;
    m->Print();
    SylvesterMatrix * result;
    SM->multiply(m, result);                    						//multiply the sylvester matrix with the random vector v
    result->Print();                           							//print the result
    //Project 2 code */
    ProblemSolver * PS = new ProblemSolver(SP, B, SP->getDegree());
    PS->Solve();
    findFullSolutions(Bp1, Bp2, PS);
    changeOfVariable(Bp1, Bp2, SM, PS, B);
//    delete result;
    cleanResources(PS, SM, Bp1, Bp2, SP, m);							//clean resources
}
Exemplo n.º 11
0
  Iterator interpolation_search(Iterator first, Iterator last, const Tp& val)
  {
    typedef typename std::iterator_traits<Iterator>::value_type      value_type;
    typedef typename std::iterator_traits<Iterator>::difference_type difference_type;
    
    if (first == last) return first;
    
    value_type front = *first;
    
    // val <= front
    if (! (front < val))
      return (val < front ? last : first);
    
    // we will work with the range of [first, last], not a conventional [first, last)
    Iterator __last = last;
    -- last;
    value_type back = *last;
    
    // back <= val
    if (! (val < back))
      return (back < val ? __last : last);
    
    // search the range [first + 1, last - 1]
    
    value_type pivot;
    Iterator middle;
    difference_type diff;
    difference_type length = std::distance(first, last);
    __interpolation_pivot<sizeof(value_type)> interpolation;
    
    while (length > 1) {
      diff = 1 + interpolation(val - front, back - front, length - 1);
      middle = first;
      std::advance(middle, diff);
      pivot = *middle;
      
      if (pivot < val) {
	first = middle;
	front = pivot;
	length -= diff;
      } else if (val < pivot) {
	last = middle;
	back = pivot;
	length = diff;
      } else
	return middle;
    }
    
    return __last;
  }
Exemplo n.º 12
0
 SwaptionVolCube1::Cube::Cube(const Cube& o) {
     optionTimes_ = o.optionTimes_;
     swapLengths_ = o.swapLengths_;
     optionDates_ = o.optionDates_;
     swapTenors_ = o.swapTenors_;
     nLayers_ = o.nLayers_;
     extrapolation_ = o.extrapolation_;
     transposedPoints_ = o.transposedPoints_;
     for (Size k=0; k<nLayers_; ++k) {
         boost::shared_ptr<Interpolation2D> interpolation (
             new BilinearInterpolation (optionTimes_.begin(), optionTimes_.end(),
                                        swapLengths_.begin(), swapLengths_.end(),
                                        transposedPoints_[k]));
         interpolators_.push_back(boost::shared_ptr<Interpolation2D>(
             new FlatExtrapolator2D(interpolation)));
         interpolators_[k]->enableExtrapolation();
     }
     setPoints(o.points_);
 }
Exemplo n.º 13
0
static void recupere_trou(ZONE l,short *tableau)
  {
  int trame,avant;


  for (trame=l->debut;trame<l->fin;)
    {
    for (; trame<=l->fin && tableau[trame];trame++);
    for (avant=trame; trame<=l->fin && !tableau[trame];trame++);
    while  ( avant > l->debut && trame<l->fin && 
             (!tableau[trame] || !ecart_correct(tableau[avant-1],tableau[trame]) )
           ) trame++;
    if  (avant > l->debut && trame<l->fin && ecart_correct(tableau[avant-1],tableau[trame]) )
      {
      int debut,fin,i;

      debut = avant-1;
      fin   = trame;
      for (i=debut+1;i<fin;i++) tableau[i] = interpolation(debut,tableau[debut],fin,tableau[fin],i);
      }
    }

  }
Exemplo n.º 14
0
int main(int argc, char **argv)
{
  FILE *fpint, *fpcp, *fpcs, *fpro;
  int   example, verbose, writeint, nb;
  int	above, diffrwidth, dtype;
  int   Ngp, Ngs, Ngr, Np, Ns, Nr, Ng, Ni, Nv, Nvi, No, Noi;
  int   jint, jcount, j, ix, iz, nx, nz, nxp, nzp, *zp, nmaxx, nminx, optgrad, poly, gradt; 
  int	ncp, nro, ncs, nvel, skip, rayfile, store_int;
	long lseed;
  size_t  nwrite;
  float *data_out, orig[2], cp0, cs0, ro0;
  float	*x, *z, *var, *interface, **inter;
  float back[3], sizex, sizez, dx, dz;
  float **cp ,**cs, **ro, aver, gradlen, gradcp, gradcs, gradro;
  
  /* Gradient unit flag    */
  /* ------------------    */
  /* - 0 Unit : m/s per dz */
  /* - 1 Unit : m/s per m  */
  int gradunit;
  /* Number of Z-reference points (one per layer) */
  int Nzr=0;
  
  float   **gridcp, **gridcs, **gridro;
  segy    *hdrs;
  FILE    *fpout;
  char    *file, intt[10], *file_base, filename[150];
  
  initargs(argc, argv);
  requestdoc(1);
  
  if (!getparint("example", &example)) example=0;
  else { plotexample(); exit(0); }
  
  if(getparstring("file",&file_base)) 
    vwarn("parameters file is changed to file_base");
  else {
    if(!getparstring("file_base",&file_base))
      verr("file_base not specified.");
  }
  if(getparfloat("back", back)) {
    vwarn("parameters back is not used anymore");
    vwarn("it has changed into cp0 (ro0,cs0 are optional)");
    nb = countparval("back");
    if (nb == 1) {
      vwarn("The new call should be cp0=%.1f",back[0]);
      cp0 = back[0];
    }
    if (nb == 2) {
      vwarn("The new call should be cp0=%.1f",back[0]);
      vwarn("                       ro0=%.1f",back[1]);
      cp0 = back[0];
      ro0 = back[1];
    }
    if (nb == 3) {
      vwarn("The new call should be cp0=%.1f",back[0]);
      vwarn("                       cs0=%.1f",back[1]);
      vwarn("                       ro0=%.1f",back[2]);
      cp0 = back[0];
      cs0 = back[1];
      ro0 = back[2];
    }
    vmess("Don't worry everything still works fine");
  }
  else {
    if(!getparfloat("cp0", &cp0)) verr("cp0 not specified.");
    if(!getparfloat("cs0", &cs0)) cs0 = -1;
    if(!getparfloat("ro0", &ro0)) ro0 = -1;
  }
  if(!getparfloat("sizex", &sizex)) verr("x-model size not specified.");
  if(!getparfloat("sizez", &sizez)) verr("z-model size not specified.");
  if(!getparfloat("dx", &dx)) verr("grid distance dx not specified.");
  if(!getparfloat("dz", &dz)) verr("grid distance dz not specified.");
  if(!getparfloat("orig", orig)) orig[0] = orig[1] = 0.0;
  if(!getparint("gradt", &gradt)) gradt = 1;
  if(!getparint("gradunit", &gradunit)) gradunit = 0;
  if(!getparint("writeint", &writeint)) writeint = 0;
  if(!getparint("rayfile", &rayfile)) rayfile = 0;
  if(!getparint("skip", &skip)) skip = 5;
  if(!getparint("above", &above)) above=0;
  if(!getparint("verbose", &verbose)) verbose=0;
  if(!getparint("dtype", &dtype)) dtype = 0;
  
  if ((writeint == 1) || (rayfile == 1)) store_int = 1;
  else store_int = 0;
  
  /*=================== check parameters =================*/
  
  Np = countparname("cp");
  Ns = countparname("cs");
  Nr = countparname("ro");
  Ng = countparname("grad");
  No = countparname("poly");
  Ni = countparname("intt");
  Nv = countparname("var");
  Ngp = countparname("gradcp");
  Ngs = countparname("gradcs");
  Ngr = countparname("gradro");
  
  Nvi = 0;
  for (jint = 1; jint <= Ni; jint++) {
    getnparstring(jint,"intt", &file);
    strcpy(intt, file);
    if (strstr(intt,"sin") != NULL) Nvi++;
    if (strstr(intt,"rough") != NULL) Nvi++;
    if (strstr(intt,"fract") != NULL) Nvi++;
    if (strstr(intt,"elipse") != NULL) Nvi++;
	if (strstr(intt,"random") != NULL) Nvi++;
//	if (strstr(intt,"randdf") != NULL) Nvi++;
    if (strstr(intt,"diffr") != NULL || strstr(intt,"randdf") != NULL) {
	  Nvi++;
//      if (Ng != 0) Ng++; 
//      if (No != 0) No++;
    }
  }
//  fprintf(stderr,"Nvi=%d ng=%d No=%d np=%d,", Nvi,Ng,No,Np);
  
  if (Np != Nr && ro0 > 0) verr("number of cp and ro not equal.");
  if (Np != Ni) verr("number of cp and interfaces not equal.");
  if (Nvi != Nv) verr("number of interface variables(var) not correct.");
  if (Ns == 0 && Nr == 0) if (verbose>=2) vmess("Velocity model.");
  if (Ns == 0) { if (verbose>=2) vmess("Acoustic model."); }
  else {
    if (verbose>=2) vmess("Elastic model.");
    if (Np != Ns) verr("number of cp and cs not equal");
  }
  
  if (Ng == 0) {
    if (verbose>=2) vmess("No boundary gradients are defined.");
  }
  else if (Ng != Np) {
    verr("number of boundary gradients and interfaces are not equal.");
  }
  if (Ngp == 0) {
    if (verbose>=2) vmess("No interface gradients for cp defined.");
  }
  else if (Ngp != Np) {
    verr("gradcp gradients and interfaces are not equal.");
  }
  if (Ngs == 0) {
    if (verbose>=2) vmess("No interface gradients for cs defined.");
  }
  else if (Ngs != Np) {
    verr("gradcs gradients and interfaces are not equal.");
  }
  if (Ngr == 0) {
    if (verbose>=2) vmess("No interface gradients for rho defined.");
  }
  else if (Ngr != Np) {
    verr("gradro gradients and interfaces are not equal.");
  }
  if (No == 0) {
    if (verbose>=2) vmess("All interfaces are linear.");
  }
//  else if (No != Np) {
//    verr("number of poly variables and interfaces are not equal.");
//  }
  
  if (Np > 0) {
    if (countparname("x") != Np)
      verr("a x array must be specified for each interface.");
    if (countparname("z") != Np)
      verr("a z array must be specified for each interface.");
  } 
  else Np = 1;

  if (Nzr != Np && Nzr !=0) {
    verr("number of zref gradients not equal to number of interfaces");
  }
  
  /*=================== initialization of arrays =================*/
  
  nz = NINT(sizez/dz)+1;
  nx = NINT(sizex/dx)+1;
  
  zp = (int *)malloc(nx*sizeof(int));
  interface = (float *)malloc(nx*sizeof(float));
  var = (float *)malloc(8*sizeof(float));
  gridcp = alloc2float(nz, nx);
  if(gridcp == NULL) verr("memory allocation error gridcp");
  if (Ns || (NINT(cs0*1e3) >= 0)) {
    gridcs = alloc2float(nz, nx);
    if(gridcs == NULL) verr("memory allocation error gridcs");
  }
  else gridcs = NULL;
  if (Nr || (NINT(ro0*1e3) >= 0)) {
    gridro = alloc2float(nz, nx);
    if(gridro == NULL) verr("memory allocation error gridro");
  }
  else gridro = NULL;
  
  cp = alloc2float(nx,3);
  cs = alloc2float(nx,3);
  ro = alloc2float(nx,3);
  if (store_int == 1) inter = alloc2float(nx, 2*Np);
  
  if (verbose) {
    vmess("Origin top left (x,z) . = %.1f, %.1f", orig[0], orig[1]);
    vmess("Base name ............. = %s", file_base);
    vmess("Number of interfaces .. = %d", Np);
    vmess("length in x ........... = %f (=%d)", sizex, nx);
    vmess("length in z ........... = %f (=%d)", sizez, nz);
    vmess("delta x ............... = %f", dx);
    vmess("delta z ............... = %f", dz);
    vmess("cp0 ................... = %f", cp0);
    if (Ns) vmess("cs0 ................... = %f", cs0);
    if (Nr) vmess("ro0 ................... = %f", ro0);
    vmess("write interfaces ...... = %d", writeint);
    vmess("store interfaces ...... = %d", store_int);
    if (above) vmess("define model above interface");
    else vmess("define model below interface");
  }

  /*========== initializing for homogeneous background =============*/
  
  nminx = 0;
  nmaxx = nx;
  for (j = nminx; j < nmaxx; j++) {
    cp[0][j] = cp0;
    cs[0][j] = cs0;
    ro[0][j] = ro0;
    zp[j] = 0;
    cp[1][j] = cp0;
    cs[1][j] = cs0;
    ro[1][j] = ro0;
  }
  
  gradlen = 0.0;
  gradcp = gradcs = gradro = 0.0;
  optgrad = 3;
  if (above == 0) {
    Nvi = 1; Noi = 1;
  } else {
    Nvi = Ngp; Noi = Ngp;
  }
  grid(gridcp, gridcs, gridro, zp, cp, cs, ro, nminx, nmaxx, optgrad,
       gradlen, gradcp, gradcs, gradro, dx, dz, nz);
  
  nxp = nzp = 2;
  x = (float *)malloc(nxp*sizeof(float));
  z = (float *)malloc(nzp*sizeof(float));
  
  if (Ni == 0) {
    if (verbose) vmess("No interfaces are defined, Homogeneous model.");
    Np = 0;
  }
  
  /*========== filling gridded model with interfaces =============*/
  
  for (jcount = 1; jcount <= Np; jcount++) {
    
    /* for above interface definition reverse	*/
    /* order of interfaces to scan 			*/
    if (above == 0) jint=jcount;
    else jint=Np+1-jcount;
    
    if (verbose) vmess("***** Interface number %d *****", jint);
    
    getnparstring(jint,"intt", &file);
    strcpy(intt, file);
    
    nxp = countnparval(jint,"x");
    nzp = countnparval(jint,"z");
    if (nxp != nzp) {
      vmess("nxp = %d nzp =%d for interface %d",nxp, nzp, jint);
      verr("Number of x and z values not equal for interface %d",jint);
    }
    ncp = countnparval(jint,"cp");
    nro = countnparval(jint,"ro");
    ncs = countnparval(jint,"cs");
    
    if (ncp == 1) {
      if (verbose>=2) vmess("No lateral gradient in P velocity");
    }
    else if (ncp == 2) {
      if (verbose) vmess("lateral P-gradient from begin to end");
    }
    else if (ncp != nxp) {
      vmess("ncp = %d nxp =%d for interface %d",ncp, nxp, jint);
      verr("Number of cp's and x not equal for interface %d",jint);
    }
    if (nro <= 1) {
      if (verbose>=2) vmess("No lateral gradient in density");
    }
    else if (nro == 2) {
      if (verbose) vmess("lateral Rho-gradient from begin to end");
    }
    else if (nro != nxp) {
      vmess("nro = %d nxp =%d for interface %d",nro, nxp, jint);
      verr("Number of ro's and x not equal for interface %d",jint);
    }
    if (ncs <= 1) {
      if (verbose>=2) vmess("No lateral gradient in S velocity");
    }
    else if (ncs == 2) {
      if (verbose) vmess("lateral S-gradient from begin to end");
    }
    else if (ncs != nxp) {
      vmess("ncs = %d nxp =%d for interface %d",ncs, nxp, jint);
      verr("Number of cs's and x not equal for interface %d",jint);
    }
    
    nvel = MAX(ncp, MAX(nro, ncs));
    
    free(x);
    free(z);
    x = (float *)malloc(nxp*sizeof(float));
    z = (float *)malloc(nzp*sizeof(float));
	memset(interface, 0, nx*sizeof(float));
    
    getnparfloat(jint,"x",x);
    getnparfloat(jint,"z",z);
    getnparfloat(jint,"cp",cp[2]);
    if (Nr == 0) ro[2][0] = 0.0;
    else getnparfloat(jint,"ro", ro[2]);
    if (Ns == 0) cs[2][0] = 0.0;
    else getnparfloat(jint,"cs", cs[2]);
    if (Ng == 0) gradlen = 0.0;
    else getnparfloat(Noi,"grad", &gradlen);
    if (No == 0) poly = 0;
    else getnparint(Noi,"poly", &poly);
    if (Ngp == 0) gradcp = 0.0;
    else getnparfloat(Noi,"gradcp", &gradcp);
    if (Ngs == 0) gradcs = 0.0;
    else getnparfloat(Noi,"gradcs", &gradcs);
    if (Ngr == 0) gradro = 0.0;
    else getnparfloat(Noi,"gradro", &gradro);
    /* if gradunit is in meters, recalculate gradcp,gradcs and gradro */
    if (gradunit > 0) {
      gradcs = gradcs * dz;
      gradcp = gradcp * dz;
      gradro = gradro * dz;
    }
    
    if (nvel != 1) {
      if (ncp == 1) {
	for (j = 1; j < nvel; j++) cp[2][j] = cp[2][0];
      }
      if (ncs == 1) {
	for (j = 1; j < nvel; j++) cs[2][j] = cs[2][0];
      }
      if (nro == 1) {
	for (j = 1; j < nvel; j++) ro[2][j] = ro[2][0];
      }
    }
    
    if (verbose) {
      vmess("Interface type .......... = %s", intt);
      vmess("Boundary gradient ....... = %f", gradlen);
      vmess("Interface gradient cp ... = %f", gradcp);
      if (Ns) vmess("Interface gradient cs ... = %f", gradcs);
      if (Nr) vmess("Interface gradient ro ... = %f", gradro);
      if (verbose>=2) {
	vmess("Polynomal ............... = %d", poly);
	vmess("Number of (x,z) points... = %d", nxp);
	vmess("P-wave velocities ....... = %d", ncp);
	if (Ns) vmess("S-wave velocities ....... = %d", ncs);
	if (Nr) vmess("Densities ............... = %d", nro);
      }
      for (j = 0; j < nxp; j++) {
	vmess("x = %6.1f \t z = %6.1f", x[j], z[j]);
	if (nvel != 1) {
	  vmess("    cp = %f", cp[2][j]);
	  if (Ns) vmess("    cs = %f", cs[2][j]);
	  if (Nr) vmess("   rho = %f", ro[2][j]);
	}
      }
      if (nvel == 1) {
	vmess("    cp = %f", cp[2][0]);
	if (Ns) vmess("    cs = %f", cs[2][0]);
	if (Nr) vmess("    rho = %f", ro[2][0]);
      }
    }
    
    for (j = 0; j < nxp; j++) {
      x[j] -= orig[0];
      z[j] -= orig[1];
    }
    for (j = 0; j < nxp; j++) {
      if(x[j] > sizex) verr("x coordinate bigger than model");
      if(z[j] > sizez) verr("z coordinate bigger than model");
    }
    if (gradlen > 0) optgrad = gradt;
    else optgrad = 3;
    
	if (strstr(intt,"random") != NULL) {
		Nv = countnparval(Nvi,"var");
		if (Nv != 1) verr("Random interface must have 1 variables.");
		getnparfloat(Nvi,"var", var);
		lseed = (long)var[0];
		srand48(lseed);
		gradcp=gradcs=gradro=var[0];
		optgrad = 4;
        if (above == 0) Noi++; else Noi--;
        if (above == 0) Nvi++; else Nvi--;
	}
	  
    if ((strstr(intt,"diffr") == NULL) && (strstr(intt,"randdf") == NULL)) {
      interpolation(x, z, nxp, nx, poly, &nminx, &nmaxx, dx, 
		    cp, cs, ro, nvel, interface);
    }

    if ( (strstr(intt,"def") != NULL) || (strstr(intt,"random") != NULL) ) {
      linearint(zp, nminx, nmaxx, dz, interface);
      if (above == 0) Noi++; else Noi--;
    }

    if (strstr(intt,"sin") != NULL) {
      Nv = countnparval(Nvi,"var");
      if (Nv != 2) verr("Sinus interface must have 2 variables.");
      getnparfloat(Nvi,"var", var);
      sinusint(zp, nminx, nmaxx, dz, interface, dx, var[0], var[1]);
      if (above == 0) Noi++; else Noi--;
      if (above == 0) Nvi++; else Nvi--;
    }
    else if (strstr(intt,"rough") != NULL) {
      Nv = countnparval(Nvi,"var");
      if (Nv != 3) verr("Rough interface must have 3 variables.");
      getnparfloat(Nvi,"var", var);
      roughint(zp, nminx, nmaxx, dz, interface, var[0],var[1],var[2]);
      if (above == 0) Noi++; else Noi--;
      if (above == 0) Nvi++; else Nvi--;
    }
    else if (strstr(intt,"fract") != NULL) {
      Nv = countnparval(Nvi, "var");
      if (Nv != 6) verr("Fractal interface must have 6 variables.");
      getnparfloat(Nvi,"var", var);
      fractint(zp, nminx, nmaxx, dx, dz, interface, var[0], var[1], 
	       var[2], var[3], var[4], var[5]);
      if (above == 0) Noi++; else Noi--;
      if (above == 0) Nvi++; else Nvi--;
    }
   	else if (strstr(intt,"randdf") != NULL) {
		float x0, z0, dsx, dsz;
		int i;
		Nv = countnparval(Nvi, "var");
		if (Nv != 2) verr("randdf interface must have 2 variables: number of points, width.");
		getnparfloat(Nvi,"var", var);
        if(!getparint("dtype", &dtype)) dtype = -1;
        
        randdf(x, z, nxp, dx, dz, gridcp, gridcs, gridro, cp, cs, ro,
              interface, zp, nx, sizex, sizez, var[0], (int)var[1], dtype);

		if (above == 0) Noi++; else Noi--;
		if (above == 0) Nvi++; else Nvi--;
	}
	else if (strstr(intt,"elipse") != NULL) {
		Nv = countnparval(Nvi, "var");
		if (Nv != 2) verr("Elipse interface must have 2 variables.");
		getnparfloat(Nvi,"var", var);
		elipse(x, z, nxp, dx, dz, gridcp, gridcs, gridro, 
			cp, cs, ro, interface, zp, nz, nx, var[0], var[1], gradcp, gradcs, gradro);
		if (above == 0) Noi++; else Noi--;
		if (above == 0) Nvi++; else Nvi--;
	}
	else if ((strstr(intt,"diffr") != NULL)) {
		Nv = countnparval(Nvi, "var");
        if (Nv == 2 || Nv == 1) {
            getnparfloat(Nvi,"var", var);
            diffrwidth=(int)var[0];
            if (Nv==1) {
            	if(!getparint("dtype", &dtype)) dtype = 0;
			}
            else dtype=(int)var[1];
        }
        else {
            verr("diffr interface must have 1 or 2 variables: width,type.");
        }
        
		diffraction(x, z, nxp, dx, dz, gridcp, gridcs, gridro,
			cp, cs, ro, interface, zp, nx, diffrwidth, dtype);
		if (above == 0) Noi++; else Noi--;
		if (above == 0) Nvi++; else Nvi--;
	}
    else {
		if (above == 0) {
			grid(gridcp, gridcs, gridro, zp, cp, cs, ro, nminx, nmaxx, 
				optgrad, gradlen, gradcp, gradcs, gradro, dx, dz, nz);
		} 
		else {
			gridabove(gridcp, gridcs, gridro, zp, cp, cs, ro, nminx, nmaxx, 
				optgrad, gradlen, gradcp, gradcs, gradro, dx, dz, nz);
		}
	}
    
    if (store_int == 1) {
      for(j = 0; j < nminx; j++) inter[jint-1][j] = 0.0;
      for(j = nminx; j < nmaxx; j++) inter[jint-1][j] = interface[j];
      for(j = nmaxx; j < nx; j++) inter[jint-1][j] = 0.0;
      
      for(j = 0; j < nminx; j++) inter[jint-1+Np][j] = 0.0;
      for(j = nminx; j < nmaxx; j++) inter[jint-1+Np][j] = zp[j]*dz;
      for(j = nmaxx; j < nx; j++) inter[jint-1+Np][j] = 0.0;
    }
  } /* end of loop over interfaces */
  
  if (verbose) vmess("Writing data to disk.");
  
  hdrs = (segy *) calloc(nx,sizeof(segy));
  for(j = 0; j < nx; j++) {
	hdrs[j].f1= orig[1];
	hdrs[j].f2= orig[0];
	hdrs[j].d1= dz;
	hdrs[j].d2= dx;
    hdrs[j].ns= nz;
	hdrs[j].trwf= nx;
	hdrs[j].tracl= j;
	hdrs[j].tracf= j;
    hdrs[j].gx = (orig[0] + j*dx)*1000;
    hdrs[j].scalco = -1000;
    hdrs[j].timbas = 25;
    hdrs[j].trid = TRID_DEPTH;
  }

  /* due to bug in SU, int-file has to be opened before other files are closed */
  if (writeint == 1) {
    strcpy(filename, file_base);
    name_ext(filename, "_int");
    fpint = fopen(filename,"w");
    assert(fpint != NULL);
  }
  
  /* write P-velocities in file */
  strcpy(filename, file_base);
  name_ext(filename, "_cp");
  fpcp = fopen(filename,"w");
  assert(fpcp != NULL);
  
  data_out = (float *)malloc(nx*nz*sizeof(float));
  for(ix = 0; ix < nx; ix++) {
    for(iz = 0; iz < nz; iz++) {
      data_out[ix*nz+iz] = gridcp[ix][iz];
	}
    nwrite = fwrite( &hdrs[ix], 1, TRCBYTES, fpcp);
    assert(nwrite == TRCBYTES);
    nwrite = fwrite( &data_out[ix*nz], sizeof(float), nz, fpcp);
    assert(nwrite == nz);
  }
  fclose(fpcp);
  free2float(gridcp);
  
  /* write S-velocities in file */
  if (Ns > 0 || getparfloat("cs0", &cs0)) {
    strcpy(filename, file_base);
    name_ext(filename, "_cs");
    fpcs = fopen(filename,"w");
    assert(fpcs != NULL);
    
    for(ix = 0; ix < nx; ix++) {
      for(iz = 0; iz < nz; iz++) {
	     data_out[ix*nz+iz] = gridcs[ix][iz];
      }
      nwrite = fwrite( &hdrs[ix], 1, TRCBYTES, fpcs);
      assert(nwrite == TRCBYTES);
      nwrite = fwrite( &data_out[ix*nz], sizeof(float), nz, fpcs);
      assert(nwrite == nz);
    }
    fclose(fpcs);
    free2float(gridcs);
    
  } /* end of writing S-velocity file */
  
  /* write densities in file */
  if (Nr > 0 || getparfloat("ro0", &ro0)) {
    strcpy(filename, file_base);
    name_ext(filename, "_ro");
    fpro = fopen(filename,"w");
    assert(fpro != NULL);
    
    for(ix = 0; ix < nx; ix++) {
      for(iz = 0; iz < nz; iz++) {
	     data_out[ix*nz+iz] = gridro[ix][iz];
      }
      nwrite = fwrite( &hdrs[ix], 1, TRCBYTES, fpro);
      assert(nwrite == TRCBYTES);
      nwrite = fwrite( &data_out[ix*nz], sizeof(float), nz, fpro);
      assert(nwrite == nz);
    }
    fclose(fpro);
    free2float(gridro);
  } /* end of writing density file */
  
  /* write depths of the interfaces */
  if (writeint == 1) {
    free(hdrs);
    hdrs = (segy *) calloc(Np,sizeof(segy));
    for(j = 0; j < Np; j++) {
      hdrs[j].fldr = 1;
      hdrs[j].timbas = 25;
	  hdrs[j].f1= orig[0];
	  hdrs[j].f2= 0.0;
	  hdrs[j].d1= dx;
	  hdrs[j].d2= dz;
	  hdrs[j].ns= nx;
	  hdrs[j].trwf= Np;
	  hdrs[j].tracl= j;
	  hdrs[j].tracf= j;
	  hdrs[j].trid= TRID_DEPTH;
    }
    
    /* note that due to bug in SU, interface file ha salready been opened */
    strcpy(filename, file_base);
    name_ext(filename, "_int");

    free(data_out);
    data_out = (float *)malloc(nx*Np*sizeof(float));
    for(jint = 0; jint < Np; jint++) {
      for(j = 0; j < nx; j++) {
	    data_out[jint*nx+j] = inter[jint][j]+orig[1];
      }
      nwrite = fwrite( &hdrs[ix], 1, TRCBYTES, fpint);
      assert(nwrite == TRCBYTES);
      nwrite = fwrite( &data_out[jint*nx], sizeof(float), nx, fpint);
      assert(nwrite == nx);
    }
    
	for(j = 0; j < Np; j++) hdrs[j].fldr = 2;
    for(jint = 0; jint < Np; jint++) {
      for(j = 0; j < nx; j++) {
	     data_out[jint*nx+j] = inter[jint+Np][j]+orig[1];
      }
      nwrite = fwrite( &hdrs[ix], 1, TRCBYTES, fpint);
      assert(nwrite == TRCBYTES);
      nwrite = fwrite( &data_out[jint*nx], sizeof(float), nx, fpint);
      assert(nwrite == nx);
    }
    fclose(fpint);
    
  } /* end of writing interface file */
  
  if (rayfile == 1) {
    strcpy(filename, file_base);
    strcpy(strrchr(filename, '.'), ".mod");
    
    fpout = fopen(filename, "w+");
    fprintf(fpout,"RAYTRACE MODEL FILE\n");
    fprintf(fpout,"# ASCII file for ray-tracer\n\n");
    fprintf(fpout,"# Top interface\n\n");
    fprintf(fpout,"x=0,%.1f\n", sizex);
    fprintf(fpout,"z=0.,0.\n");
    
    /*		for(i = 1; i <= Np; i++) {
		fprintf(fpout,"\n# %d th interface\n\nx=",i);
		nxp = countnparval(i,"x");
		nzp = countnparval(i,"z");
		free(x);
		free(z);
		x = (float *)malloc(nxp*sizeof(float));
		z = (float *)malloc(nzp*sizeof(float));
		getnparfloat(i,"x",x);
		getnparfloat(i,"z",z);
		for(j = 0; j < (nxp-1); j ++) fprintf(fpout,"%.1f,", x[j]);
		fprintf(fpout,"%.1f\nz=", x[nxp-1]);
		for(j = 0; j < (nxp-1); j ++) fprintf(fpout,"%.1f,", z[j]);
		fprintf(fpout,"%.1f\n", z[nxp-1]);
		}
    */
    for(jint = 0; jint < Np; jint++) {
      fprintf(fpout,"\n# %d th interface\n\nx=0",jint+1);
      for(j = skip; j < nx; j += skip) 
	fprintf(fpout,",%.1f", (float)j*dx);
      
      fprintf(fpout,"\nz=%.1f", inter[jint][0]);
      for(j = skip; j < nx; j += skip) 
	fprintf(fpout,",%.1f", inter[jint][j]);
      fprintf(fpout,"\n");
    }
    fprintf(fpout,"\n# %d th interface\n\nx=0",jint+1);
    for(j = skip; j < nx; j += skip) 
      fprintf(fpout,",%.1f", (float)j*dx);
    
    fprintf(fpout,"\nz=%.1f", sizez);
    for(j = skip; j < nx; j += skip) 
      fprintf(fpout,",%.1f", sizez);
    fprintf(fpout,"\n");
    
    /**/
    fprintf(fpout,"\n\n");
    fprintf(fpout,"cp=%.1f,", back[0]);
    for(jint = 1; jint <= Np; jint++) {
      aver = 0.0;
      ncp = countnparval(jint,"cp");
      getnparfloat(jint,"cp",cp[2]);
      for(j = 0; j < ncp; j++) 
	aver += cp[2][j];
      aver = aver/((float)ncp);
      if (jint == Np ) fprintf(fpout,"%.1f", aver);
      else fprintf(fpout,"%.1f,", aver);
    }
    
    fclose(fpout);
    free2float(inter);
  }
  
  free(hdrs);
  
  return 0;
}
void main()
{
	int i, x, s, value, count;
	float start, finish;
	unsigned long int j;
	unsigned int mask=1;
	long int error, ferror;
	double progress, b;

	FILE *fp;
	if((fp=fopen("data_(63,15)m=1.txt","a"))==NULL)
	{
		printf("Can't open the data.txt\n");
		exit(0);
	}
	fclose(fp);

	srand(1977);

	mono_table();


	printf("\nEnter start SNR: ");
	scanf("%f", &start);
	printf("\nEnter finish SNR: ");
	scanf("%f", &finish);
	printf("\nseq_num: ");
	scanf("%d", &seq_num);


	for(SNR=start;SNR<=finish;SNR++)
	{	
		N0=(1.0/(float(k)/float(n)))/pow(10.0, SNR/10.0);
		sgm=sqrt(N0/2);
		b=1.0;
		error=0;
		//ferror=0; 
		for(j=1;j<=seq_num;j++)
		{

		//printf("\n\n*************For the %dth frame*************:\n", j);
		//Generate binary message
			for(i=0;i<k*p;i++)
				bi_message[i]=rand()%2;

			//Convert to nonbinary
			for(i=0;i<k;i++)
				message[i]=bi_message[p*i]+2*bi_message[p*i+1]+4*bi_message[p*i+2]+8*bi_message[p*i+3]
					   +16*bi_message[p*i+4]+32*bi_message[p*i+5];


			encoder();

	
			//Convert the codeword into binary
			for(i=0;i<n;i++)
			{
				value=codeword[i];
				mask=1;
				for(x=0;x<p;x++) //for(m=p-1;m>=0;m--)
				{
					if((value & mask)>0)
						bi_codeword[p*i+x]=1;
					else
						bi_codeword[p*i+x]=0;
					mask=mask<<1;
				}
			}
		
			modulation();
			
			channel();
			
			/////////To be done?////////////
			demodulation();

			interpolation();

			factorization();
			
			//Number of errors calculation
			//error=0;
			for(i=0;i<p*n;i++)
				if(bi_codeword[i]!=dec_codeword[i])
					error++;
/*			
			if(f_error_temp==1)
				printf("\nerror=%d\n",error);
			f_error_temp=0;
*/			/*
			if(error!=0)
				ferror++;
			*/

			progress=(double)(j*100)/(double)seq_num;
			
			BER=(double)(error)/(double)(n*p*j);
			//FER=(double)(ferror)/(double)(j),
			printf("Progress=%0.1f, SNR=%2.1f, Bit Errors=%2.1d, BER=%E\r", progress, SNR, error, BER);
//			printf(" Progress=%0.1f,dectect=%d\r",progress,dectec);
			
		}
		BER=(double)error/(double)(n*p*seq_num);
		//FER=(double)(ferror)/(double)(seq_num);
		printf("Progress=%0.1f, SNR=%2.1f, Bit Errors=%2.1d, BER=%E\n",progress, SNR, error, BER);
//		printf(" Progress=%0.1f,dectect=%d\r",progress,dectec);
		fp=fopen("data_(63,15)m=1.txt","a");
		fprintf(fp,"Progress=%0.1f, SNR=%2.1f, Bit Errors=%2.1d, BER=%E\n",progress, SNR, error, BER);
		fclose(fp);

	}


	getchar();
	getchar();
		
}
Exemplo n.º 16
0
void SE_BipedController::fillFrame()
{
    int maxFrame = findMaxFrameIndex();    

    std::vector<SE_BipedKeyFrame*> fullFrame;
    //fullFrame.resize(maxFrame,NULL);

    for(int i = 0; i < oneBipAnimation.size(); ++i)
    {
        //get bip one by one
        SE_Biped *bip = oneBipAnimation[i];
         
        if(bip->animationInfo.size() == 0)
        {
            continue;//this bip has no keyframe
        }

        //generate 0 frame, bind_pos relative parent
        SE_Matrix4f bindposT;
        if(bip->parent)
        {
            bindposT = (bip->parent->bind_pose.inverse()).mul(bip->bind_pose);            
        }
        else
        {
            //this bip is ROOT
            bindposT = bip->bind_pose;
        }

        SE_Quat rotate = bindposT.toMatrix3f().toQuat();//no rotate
        rotate = rotate.inverse();
        

        SE_Vector3f translate = bindposT.getTranslate();

        SE_Vector3f scale(1,1,1); //scale no use

        SE_BipedKeyFrame *zeroFrame = new SE_BipedKeyFrame();
        zeroFrame->frameIndex = 0;            

        zeroFrame->rotateQ = rotate;
        zeroFrame->scale = scale;
        zeroFrame->translate = translate;

        //push first (0) frame to target
        fullFrame.push_back(zeroFrame);

        
     
        std::vector<SE_BipedKeyFrame*>::iterator it_s = bip->animationInfo.begin();
        std::vector<SE_BipedKeyFrame*>::iterator it_t = fullFrame.end();
        -- it_t;

        SE_BipedKeyFrame* node_s = NULL;
        SE_BipedKeyFrame* node_t = NULL;
        
        while(it_s != bip->animationInfo.end())
        {            
            node_s = *it_s;
            node_t = *it_t;
            if(needInterpolation(node_t->frameIndex,node_s->frameIndex))
            {
                //interpolation
                interpolation(it_s,it_t,fullFrame);
            
            }
            else if(node_s->frameIndex == node_t->frameIndex)//current source frame index == target frame index
            {
                //goto next frame
                ++it_s;
            }
            else //source frame index - target frame index == 1
            {
                //push source frame to target frame vector
                SE_BipedKeyFrame *nextFrame = new SE_BipedKeyFrame();

                //current source node is just next frame
                nextFrame->frameIndex = node_s->frameIndex;
                nextFrame->rotateQ = node_s->rotateQ;
                nextFrame->translate = node_s->translate;
                nextFrame->scale = node_s->scale;

                fullFrame.push_back(nextFrame);
                it_t = fullFrame.end();
                --it_t;

            }
            
        }

        //total frame little than maxFrame?
        //1.yes fill last frame to vector
        
        int lastframe = bip->animationInfo.size() - 1;
        int lastframeIndex = bip->animationInfo[lastframe]->frameIndex;
        if(lastframeIndex < maxFrame)
        {
            SE_BipedKeyFrame * lastframenode = bip->animationInfo[lastframe];

            for(int needfill = 0; needfill < maxFrame - lastframeIndex; ++needfill)
            {
                SE_BipedKeyFrame *fillFrame = new SE_BipedKeyFrame();

                //next (maxFrame - lastframeIndex) frames are same 
                fillFrame->frameIndex = lastframenode->frameIndex + needfill + 1;
                fillFrame->rotateQ = lastframenode->rotateQ;
                fillFrame->translate = lastframenode->translate;
                fillFrame->scale = lastframenode->scale;

                fullFrame.push_back(fillFrame);

            }
        }

        //2.no,finish this biped,copy target to source,clear target
        for(it_s = bip->animationInfo.begin(); it_s != bip->animationInfo.end(); ++it_s)
        {
            if(*it_s != NULL)
            {
                delete *it_s;
            }
        }
        bip->animationInfo.clear();

        bip->animationInfo.resize(fullFrame.size());
        
        //copy target to source
        std::copy(fullFrame.begin(),fullFrame.end(),bip->animationInfo.begin());

        //clear fullFrame vector
        fullFrame.clear();        

    }

}
Exemplo n.º 17
0
bool RotationInstance::ExecuteOn( View& view )
{
   if ( !view.IsMainView() )
      return false;  // should never reach this point!

   AutoViewLock lock( view );

   ImageVariant image = view.Image();

   if ( image.IsComplexSample() )
      return false;

   double degrees = Round( Deg( p_angle ), 4 );
   if ( degrees == 0 )
   {
      Console().WriteLn( "<end><cbr>&lt;* Identity *&gt;" );
      return true;
   }

   ImageWindow window = view.Window();

   window.RemoveMaskReferences();
   window.RemoveMask();
   window.DeletePreviews();

   Console().EnableAbort();

   StandardStatus status;
   image.SetStatusCallback( &status );

   if ( p_optimizeFast )
      switch ( TruncI( degrees ) )
      {
      case 90:
         Rotate90CCW() >> image;
         return true;
      case -90:
         Rotate90CW() >> image;
         return true;
      case 180:
      case -180:
         Rotate180() >> image;
         return true;
      default:
         break;
      }

   AutoPointer<PixelInterpolation> interpolation( NewInterpolation(
         p_interpolation, 1, 1, 1, 1, true, p_clampingThreshold, p_smoothness, image ) );

   Rotation T( *interpolation, p_angle );

   /*
    * On 32-bit systems, make sure the resulting image requires less than 4 GB.
    */
   if ( sizeof( void* ) == sizeof( uint32 ) )
   {
      int width = image.Width(), height = image.Height();
      T.GetNewSizes( width, height );
      uint64 sz = uint64( width )*uint64( height )*image.NumberOfChannels()*image.BytesPerSample();
      if ( sz > uint64( uint32_max-256 ) )
         throw Error( "Rotation: Invalid operation: Target image dimensions would exceed four gigabytes" );
   }

   T.SetFillValues( p_fillColor );
   T >> image;

   return true;
}
Exemplo n.º 18
0
    std::tuple<
        std::shared_ptr<Matrix>,
        std::shared_ptr<Matrix>
        >
    transfer_operators(const Matrix &A) {
        typedef typename backend::value_type<Matrix>::type Val;
        typedef ptrdiff_t Idx;

        AMGCL_TIC("aggregates");
        Aggregates aggr(A, prm.aggr, prm.nullspace.cols);
        prm.aggr.eps_strong *= 0.5;
        AMGCL_TOC("aggregates");

        AMGCL_TIC("interpolation");
        auto P_tent = tentative_prolongation<Matrix>(
                rows(A), aggr.count, aggr.id, prm.nullspace, prm.aggr.block_size
                );

        // Filter the system matrix
        backend::crs<Val> Af;
        Af.set_size(rows(A), cols(A));
        Af.ptr[0] = 0;

        std::vector<Val> dia(Af.nrows);

#pragma omp parallel for
        for(Idx i = 0; i < static_cast<Idx>(Af.nrows); ++i) {
            Idx row_begin = A.ptr[i];
            Idx row_end   = A.ptr[i+1];
            Idx row_width = row_end - row_begin;

            Val D = math::zero<Val>();
            for(Idx j = row_begin; j < row_end; ++j) {
                Idx c = A.col[j];
                Val v = A.val[j];

                if (c == i)
                    D += v;
                else if (!aggr.strong_connection[j]) {
                    D += v;
                    --row_width;
                }
            }

            dia[i] = D;
            Af.ptr[i+1] = row_width;
        }

        Af.set_nonzeros(Af.scan_row_sizes());

#pragma omp parallel for
        for(Idx i = 0; i < static_cast<Idx>(Af.nrows); ++i) {
            Idx row_begin = A.ptr[i];
            Idx row_end   = A.ptr[i+1];
            Idx row_head  = Af.ptr[i];

            for(Idx j = row_begin; j < row_end; ++j) {
                Idx c = A.col[j];

                if (c == i) {
                    Af.col[row_head] = i;
                    Af.val[row_head] = dia[i];
                    ++row_head;
                } else if (aggr.strong_connection[j]) {
                    Af.col[row_head] = c;
                    Af.val[row_head] = A.val[j];
                    ++row_head;
                }
            }
        }

        std::vector<Val> omega;

        auto P = interpolation(Af, dia, *P_tent, omega);
        auto R = restriction  (Af, dia, *P_tent, omega);
        AMGCL_TOC("interpolation");

        if (prm.nullspace.cols > 0)
            prm.aggr.block_size = prm.nullspace.cols;

        return std::make_tuple(P, R);
    }
Exemplo n.º 19
0
// multigrid v-cycle
void v_cycle( double* P, uint n_dof, cuint nx, cuint ny, cuint nz,
			  cdouble hx, cdouble hy, cdouble hz,
			  cdouble hx2i, cdouble hy2i, cdouble hz2i,
			  cdouble tol, cuint max_iteration, cuint pre_smooth_iteration,
			  cdouble lx, cdouble ly, cdouble lz,
			  cuint level, cuint max_level,
			  double* F,
			  double& Er,
			  double* Uss, double* Vss, double* Wss,
			  cdouble bcs[][6],
			  cdouble dt
			  )
{
	cout<<"level: "<<level<<" n_dof: "<<n_dof<<endl;

	// initialize finite difference matrix (+1 for global constraint)
// 	double** M = new double*[n_dof];
// 	for(int n = 0; n < (n_dof); n++)
// 		M[n] = new double[n_dof];
// 	// initialize 
// #pragma omp parallel for shared(n_dof, M)
// 	for(int i=0; i<n_dof; i++)
// 		for(int j=0; j<n_dof; j++)
// 			M[i][j] = 0;

	cout<<"fd_matrix_sparse"<<endl;
	vector<tuple <uint, uint, double> > M_sp;
	vector<double> val;
	vector<uint> col_ind;
	vector<uint> row_ptr(1,0);
	
	// create finite difference matrix
	cout<<"create finite difference matrix"<<endl;
	// build pressure matrix
	pressure_matrix( M_sp,
					 val, col_ind, row_ptr,
					 nx, ny, nz,
					 hx2i, hy2i, hz2i,
					 n_dof
					 );	
	
	// construct load vector
	// load vector is created only at the level 0
	if(level==0){
		F = new double[n_dof];
		cout<<"create load vector"<<endl;

		pressure_rhs(F, Uss, Vss, Wss, nx, ny, nz, bcs, hx, hy, hz, dt);
		// load_vector(F, n_dof, I,J,K );
	}

	// cout<<"save matrix and vector"<<endl;
	// char matrix_file[100];
	// char vector_file[100];
	// sprintf(vector_file, "vector_%i.dat", level);
	// if(write_vector(n_dof,F,vector_file)) cout<<"write_vector fail"<<endl;
	
	// construct solution vector
	double* U;
	if(level==0) U=P;
	else U = new double[n_dof];
	double* U_tmp = new double[n_dof];
	// initial guess
#pragma omp parallel for shared(U, U_tmp) num_threads(nt)
	for(int n=0; n<n_dof; n++){
	    U[n] = 0.0;
	    U_tmp[n] = 0.0;
    }

	// residual and error
	double* R = new double[n_dof];

	// perform pre-smoothing and compute residual
	cout<<"pre-smoothing "<<pre_smooth_iteration<<" times"<<endl;
	Er = tol*10;
	jacobi_sparse(tol, pre_smooth_iteration, n_dof, U, U_tmp,
				  val, col_ind, row_ptr, F, Er, R);
		
	// restriction of residual on coarse grid
	double* F_coar;
		
	// Restrict the residual
	cuint nx_coar = (nx)/2;
	cuint ny_coar = (ny)/2;
	cuint nz_coar = (nz)/2;
	uint n_dof_coar = nx_coar*ny_coar*nz_coar; 
	F_coar = new double[n_dof_coar];

	// mesh size 
	cdouble hx_coar = lx/(nx_coar);
	cdouble hy_coar = ly/(ny_coar);
	cdouble hz_coar = lz/(nz_coar);
	
	// inverse of square of mesh sizes
	cdouble hx2i_coar = 1.0/(hx_coar*hx_coar);
	cdouble hy2i_coar = 1.0/(hy_coar*hy_coar);
	cdouble hz2i_coar = 1.0/(hz_coar*hz_coar);
		
	// restric residual to the coarrse grid
	cout<<"restriction"<<endl;
	restriction( R, F_coar, nx, ny, nz, nx_coar, ny_coar, nz_coar);
	
	// construct solution vector on coarse grid
	double* U_coar = new double[n_dof_coar];
	double* U_coar_tmp = new double[n_dof_coar];
	
	// if the grid is coarsest
	if( level==max_level){
		cout<<"level: "<<level+1<<" n_dof: "<<n_dof_coar<<endl;

		// initial guess
#pragma omp parallel for shared(U_coar, U_coar_tmp) num_threads(nt)
		for(int n=0; n<n_dof_coar; n++){
			U_coar[n] = 0.0;
			U_coar_tmp[n] = 0.0;
		}

		vector<tuple <uint, uint, double> > M_sp_coar;
		vector<double> val_coar;
		vector<uint> col_ind_coar;
		vector<uint> row_ptr_coar(1,0);
		
		// create finite difference matrix
		cout<<"create finite difference matrix"<<endl;
		// fd_matrix_sparse(M_sp_coar, val_coar, col_ind_coar, row_ptr_coar,
		// 				 nx_coar,ny_coar,nz_coar,
		// 				 hx2i_coar, hy2i_coar, hz2i_coar, n_dof_coar );
		
		pressure_matrix( M_sp_coar, val_coar, col_ind_coar, row_ptr_coar,
						 nx_coar, ny_coar, nz_coar,
						 hx2i_coar, hy2i_coar, hz2i_coar,
						 n_dof_coar
						 );
		
		// residual on coarse grid
		double* R_coar = new double[n_dof_coar];
		
		// exact Jacobi method
		Er = tol*10;
		jacobi_sparse(tol, max_iteration, n_dof_coar, U_coar, U_coar_tmp,
					  val_coar, col_ind_coar, row_ptr_coar, F_coar,
					  Er, R_coar);
		
		// write_results( U_coar,
		// 			   n_dof_coar,
		// 			   I_coar, J_coar, K_coar,
		// 			   dx_coar, dy_coar, dz_coar, level);
		
		delete[] R_coar;
		
		// cout<<"R"<<endl;
		// for(int i=0; i<n_dof; i++)
		// 	cout<<R[i]<<endl;
		 
	}
	else{
		// v_cycle on the coarse grid
		v_cycle( U_coar, n_dof_coar, nx_coar, ny_coar, nz_coar,
						  hx_coar, hy_coar, hz_coar,
						  hx2i_coar, hy2i_coar, hz2i_coar,
						  tol, max_iteration, pre_smooth_iteration,
						  lx, ly, lz,
						  level+1, max_level,
						  F_coar, Er,
						  Uss, Vss, Wss,
						  bcs, dt
						  );
		
		cdouble dx_coar = lx/(nx_coar);
		cdouble dy_coar = ly/(ny_coar);
		cdouble dz_coar = lz/(nz_coar);

		// // write partial results for test purpose
		// write_results( U_coar,
		// 			   n_dof_coar,
		// 			   I_coar, J_coar, K_coar,
		// 			   dx_coar, dy_coar, dz_coar, level);
		 
	}

	// interpolate to fine grid
	double* E = new double[n_dof];
	interpolation(U_coar, E, nx_coar,ny_coar,nz_coar, nx, ny, nz);

	// correct the fine grid approximation
#pragma omp parallel for shared(U,E) num_threads(nt)
	for(int i=0; i<n_dof; i++){
		// cout<<i<<" "<<U[i]<<" "<<E[i]<<" "<<E[i]/U[i]<<endl;
		U[i] += E[i];
	}

	// perform post-smoothing and compute residual
	uint post_smooth_iteration;
	// if(level==0)
		post_smooth_iteration=max_iteration;
	// else
		// post_smooth_iteration=( pre_smooth_iteration+1)*1000;

	cout<<"post-smoothing "<<post_smooth_iteration<<" times on level "
		<<level<<endl;
	// jacobi(tol, post_smooth_iteration, n_dof, U, U_tmp, M, F, Er, R);
	Er = tol*10;
	jacobi_sparse(tol, post_smooth_iteration, n_dof, U, U_tmp,
				  val, col_ind, row_ptr, F, Er, R);

	
	// cleanup
	if (level==0)
		delete[] F;

	delete[] U_tmp;
	delete[] R, F_coar;
	delete[] E;
	delete[] U_coar, U_coar_tmp;
	
}
	bool SIMULATION_core::adaptation(){
		bool adapt;
		if ( pSimPar->userRequiresAdaptation() ){
			// performs an error estimation on saturation and/or pressure solution and verifies if tolerances are obeyed.
			// If error is greater than tolerance then mesh will be adapted to improve solution quality
			adapt = calculate_ErrorAnalysis(pErrorAnalysis,theMesh,pSimPar,pGCData,pPPData->get_FuncPointer_GetGradient());
			if (adapt){
				// retrieve cumulative simulation time
				pSimPar->retrieveSimulationTime();

				pIData->m1 = theMesh;				// auxiliary pointer
				pIData->m2 = MS_newMesh(0);			// initialize auxiliary pointer
				PADMEC_mesh *pm = new PADMEC_mesh;	// temporary pointer

				// preserves current mesh and create a new one adapted
				makeMeshCopy2(pIData->m1,pm,pPPData->getPressure,pPPData->getSw_old);

				// mesh adaptation (adapted mesh saved in file. Bad, bad, bad!)
				pMeshAdapt->rodar(pErrorAnalysis,pIData->m1);

				// delete any trace of FMDB data structure
				deleteMesh(theMesh); theMesh = 0;

				//create a new FMDB data structure with data in file
				pIData->m1 = MS_newMesh(0);
				readmesh(pIData->m1,"Final_01.msh");
				theMesh = pIData->m1;

				// take mesh (coords and connectivities) from temporary matrix to m2 (avoid conflicts with FMDB when deleting m1 and theMesh)
				makeMeshCopy2(pm,pIData->m2,pPPData->setPressure,pPPData->setSaturation);

				// must be vanished from code in very near future
				PADMEC_GAMBIARRA(pIData->m1);

				// structure allocation must be done for saturation and pressure for the new mesh
				// it will receive interpolated data from m2 to m1
				pPPData->allocateTemporaryData(M_numVertices(pIData->m1));

				// interpolate data from m2 to m1
				interpolation(pIData,pSimPar->getInterpolationMethod());

				// transfer Sw and pressure from tmp to main struct
				pPPData->transferTmpData();

				//pSimPar->printOutVTK(theMesh,pPPData,pErrorAnalysis,pSimPar,pGCData,exportSolutionToVTK);

				// waste old data and get ready for new data
				pGCData->deallocatePointers();
				pGCData->initilize(theMesh);

				// mesh pre-processor
				EBFV1_preprocessor(pIData->m1,pGCData);

				// objects (pSimPar, pMData, pGCData, pPPData) must store new data
				updatePointersData(theMesh);

				// data transfer from FMDB to matrices
				pGCData->dataTransfer(theMesh);

				// temporary mesh not necessary any more (goodbye!)
				deleteMesh(pm);
				delete pm; pm = 0;
				deleteMesh(pIData->m2); delete pIData->m2; pIData->m2 = 0;
			}
		}
		return adapt;
	}
Exemplo n.º 21
0
/******************************************************************************
| advection
******************************************************************************/
void advection(PARA_DATA *para, REAL **var, int var_type, REAL *d, REAL *d0)
{
	int i, j, k, p, q, r;
  int imax = para->geom->imax, jmax = para->geom->jmax;
  int kmax = para->geom->kmax;
  int IMAX = imax+2, IJMAX = (imax+2)*(jmax+2);
  int LOCATION;
  REAL x0, y0, z0, x_1, y_1,z_1;
  REAL dt = para->mytime->dt; 
  REAL u0, v0, w0, x_min, x_max, y_min, y_max, z_min, z_max;
  REAL *x = var[X],  *y = var[Y],  *z = var[Z]; 
  REAL *gx = var[GX],  *gy = var[GY],  *gz = var[GZ]; 

  REAL *u = var[VX], *v = var[VY], *w = var[VZ];
  REAL *flagp = var[FLAGP],*flagu = var[FLAGU],*flagv = var[FLAGV],*flagw = var[FLAGW];
  int k1 = para->geom->k1, k2 = para->geom->k2, k3 = para->geom->k3; 
  int i1 = para->geom->i1, i2 = para->geom->i2; 
  int j1 = para->geom->j1, j2 = para->geom->j2;
  REAL z1 = para->geom->z1, z2 = para->geom->z2 ,z3 = para->geom->z3; 
  REAL x1 = para->geom->x1, x2 = para->geom->x2; 
  REAL y1 = para->geom->y1, y2 = para->geom->y2;
  REAL Lx = para->geom->Lx, Ly = para->geom->Ly, Lz = para->geom->Lz; 


  switch (var_type)
  {
	  
  case VX:
   {
  /*---------------------------------------------------------------------------
  | Tracing Back and Interplotaing
  ---------------------------------------------------------------------------*/
  FOR_U_CELL

	if (i>=i1 && i<=i2 && j>j1 && j<=j2 && k<=k2) continue;
    /*-------------------------------------------------------------------------
    | Step 1: Tracing Back
    -------------------------------------------------------------------------*/
    u0 = u[IX(i,j,k)];

    v0 = 0.5f *((v[IX(i,  j,k)]+ v[IX(i,  j-1,k)])*( x[IX(i+1,j,k)]-gx[IX(i,j,k)])
		       +(v[IX(i+1,j,k)]+ v[IX(i+1,j-1,k)])*(gx[IX(i,  j,k)]- x[IX(i,j,k)])) /(x[IX(i+1,j,k)]-x[IX(i,j,k)]);
	
	w0 = 0.5f *((w[IX(i,  j,k)]+ w[IX(i  ,j, k-1)])*( x[IX(i+1,j,k)]-gx[IX(i,j,k)])
		       +(w[IX(i+1,j,k)]+ w[IX(i+1,j, k-1)])*(gx[IX(i,  j,k)]- x[IX(i,j,k)]))/(x[IX(i+1,j,k)]-x[IX(i,j,k)]); 
    
        
    x0 =gx[IX(i,j,k)] - u0*dt; 
    y0 = y[IX(i,j,k)] - v0*dt;
    z0 = z[IX(i,j,k)] - w0*dt;
   
	
	p = i; q = j; r = k;  

  if(u0>0)
  {
	  while(x0<gx[IX(p,q,r)] && flagu[IX(p,q,r)]<0)  p -=1;
      if(flagu[IX(p,q,r)]>0 && x0< gx[IX(p,q,r)]) x0=gx[IX(p,q,r)];
  }
  else
  {
     while(x0>gx[IX(p+1,q,r)] && flagu[IX(p+1,q,r)]<0)  p +=1;
	 if(flagu[IX(p+1,q,r)]>0 && x0>gx[IX(p+1,q,r)])  x0=gx[IX(p+1,q,r)];
  }

  if(v0>0)
  {
	  while(y0<y[IX(p,q,r)] && flagu[IX(p,q,r)]<0)  q -=1;
      if(y0<y[IX(p,q,r)] && flagu[IX(p,q,r)]>0) y0=y[IX(p,q+1,r)];
  }
  else
  {
   while(y0>y[IX(p,q+1,r)] && flagu[IX(p,q+1,r)]<0)  q +=1;
      if(y0>y[IX(p,q+1,r)] && flagu[IX(p,q+1,r)]>0)  y0=y[IX(p,q,r)];
  }

    if(w0>0)
  {
	  while(z0<z[IX(p,q,r)] && flagu[IX(p,q,r)]<0)  r -=1;
      if(z0<z[IX(p,q,r)] && flagu[IX(p,q,r)]>0) z0=z[IX(p,q,r+1)];
  }
  else
  {
   while(z0>z[IX(p,q,r+1)] && flagu[IX(p,q,r+1)]<0)  r +=1;
    if(z0>z[IX(p,q,r+1)] && flagu[IX(p,q,r+1)]>0)  z0=z[IX(p,q,r)];
  }

	     
    x_1 = (x0-gx[IX(p,q,r)]) /(gx[IX(p+1,  q ,r  )]-gx[IX(p,q,r)]); 
    y_1 = (y0- y[IX(p,q,r)]) /(y [IX(p,  q+1, r  )]- y[IX(p,q,r)]);
    z_1 = (z0- z[IX(p,q,r)]) /(z [IX(p,    q, r+1)]- z[IX(p,q,r)]);
             
    /*-------------------------------------------------------------------------
    | Interpolating for all variables
    -------------------------------------------------------------------------*/
    d[IX(i,j,k)] = interpolation(para, d0, x_1, y_1, z_1, p, q, r);
	END_FOR

  /*---------------------------------------------------------------------------
  | define the b.c.
  ---------------------------------------------------------------------------*/
  set_bnd(para, var, var_type, d);

   }
	 break;


  case VY:
  {
	/*---------------------------------------------------------------------------
  | Tracing Back and Interplotaing
  ---------------------------------------------------------------------------*/
  FOR_V_CELL

    if (i>i1 && i<=i2 && j>=j1 && j<=j2 && k<=k2) continue;
    /*-------------------------------------------------------------------------
    | Step 1: Tracing Back
    -------------------------------------------------------------------------*/
    
	u0 = 0.5f* ((u[IX(i,j,k)]   + u[IX(i-1,j,  k)]) *(y [IX(i,j+1,k)]-gy[IX(i,j,k)])
		       +(u[IX(i,j+1,k)] + u[IX(i-1,j+1,k)]) *(gy[IX(i,j,  k)]-y[IX(i,j,k)]))/(y[IX(i,j+1,k)]-y[IX(i,j,k)]);
	
    v0 = v[IX(i,j,k)]; 


   	w0 = 0.5f *((w[IX(i,j,  k)]+ w[IX(i,j  ,k-1)])* (y [IX(i,j+1,k)]- gy[IX(i,j,k)])
		       +(w[IX(i,j+1,k)]+ w[IX(i,j+1,k-1)])* (gy[IX(i,j,  k)]- y [IX(i,j,k)]))/(y[IX(i,j+1,k)]-y[IX(i,j,k)]); 
    
       
    x0 = x[IX(i,j,k)] - u0*dt; 
    y0 = gy[IX(i,j,k)] - v0*dt;
    z0 = z[IX(i,j,k)] - w0*dt;
   
    p = i; q = j; r = k;  


	if(u0>0)
  {
	  while(x0<x[IX(p,q,r)] && flagv[IX(p,q,r)]<0)  p -=1;
      if(flagv[IX(p,q,r)]>0 && x0< x[IX(p,q,r)]) x0=x[IX(p+1,q,r)];
  }
  else
  {
     while(x0>x[IX(p+1,q,r)] && flagv[IX(p+1,q,r)]<0)  p +=1;
	 if(flagv[IX(p+1,q,r)]>0 && x0>x[IX(p+1,q,r)])  x0=x[IX(p,q,r)];
  }

  if(v0>0)
  {
	  while(y0<gy[IX(p,q,r)] && flagv[IX(p,q,r)]<0)  q -=1;
      if(y0<gy[IX(p,q,r)] && flagv[IX(p,q,r)]>0) y0=gy[IX(p,q,r)];
  }
  else
  {
   while(y0>gy[IX(p,q+1,r)] && flagv[IX(p,q+1,r)]<0)  q +=1;
      if(y0>gy[IX(p,q+1,r)] && flagv[IX(p,q+1,r)]>0)  y0=gy[IX(p,q+1,r)];
  }

    if(w0>0)
  {
	  while(z0<z[IX(p,q,r)] && flagv[IX(p,q,r)]<0)  r -=1;
      if(z0<z[IX(p,q,r)] && flagv[IX(p,q,r)]>0) z0=z[IX(p,q,r+1)];
  }
  else
  {
   while(z0>z[IX(p,q,r+1)] && flagv[IX(p,q,r+1)]<0)  r +=1;
    if(z0>z[IX(p,q,r+1)] && flagv[IX(p,q,r+1)]>0)  z0=z[IX(p,q,r)];
  }
  

    
    x_1 = (x0- x[IX(p,q,r)])/(x [IX(p+1,q,    r)]-x [IX(p,q,r)]); 
    y_1 = (y0-gy[IX(p,q,r)])/(gy[IX(p,  q+1,  r)]-gy[IX(p,q,r)]);
    z_1 = (z0- z[IX(p,q,r)])/(z [IX(p,  q,  r+1)]-z [IX(p,q,r)]);
             
    /*-------------------------------------------------------------------------
    | Interpolating for all variables
    -------------------------------------------------------------------------*/
    d[IX(i,j,k)] = interpolation(para, d0, x_1, y_1, z_1, p, q, r);
	END_FOR

  /*---------------------------------------------------------------------------
  | define the b.c.
  ---------------------------------------------------------------------------*/
  set_bnd(para, var, var_type, d);

		  }
      break;

  case VZ:
   {
		  	/*---------------------------------------------------------------------------
  | Tracing Back and Interplotaing
  ---------------------------------------------------------------------------*/
  FOR_W_CELL

	 if (i>i1 && i<=i2 && j>j1 && j<=j2 && k<=k2) continue;

    /*-------------------------------------------------------------------------
    | Step 1: Tracing Back
    -------------------------------------------------------------------------*/
    
	u0 = 0.5f*((u[IX(i,j,k  )]  + u[IX(i-1,j,k  )])*(z [IX(i,j,k+1)]-gz[IX(i,j,k)])
		      +(u[IX(i,j,k+1)]  + u[IX(i-1,j,k+1)])*(gz[IX(i,j,k  )]- z[IX(i,j,k)]))/(z[IX(i,j,k+1)]-z[IX(i,j,k)]);

	v0 = 0.5f*((v[IX(i,j,k  )]  + v[IX(i,j-1,k  )])*(z [IX(i,j,k+1)]-gz[IX(i,j,k)])
		      +(v[IX(i,j,k+1)]  + v[IX(i,j-1,k+1)])*(gz[IX(i,j,k  )]-z [IX(i,j,k)]))/(z[IX(i,j,k+1)]-z[IX(i,j,k)]); 

	w0 = w[IX(i,j,k)]; 
          
    x0 = x[IX(i,j,k)] - u0*dt; 
    y0 = y[IX(i,j,k)] - v0*dt;
    z0 = gz[IX(i,j,k)] - w0*dt;
   
    p = i; q = j; r = k;  


	if(u0>0)
  {
	  while(x0<x[IX(p,q,r)] && flagw[IX(p,q,r)]<0)  p -=1;
      if(flagw[IX(p,q,r)]>0 && x0< x[IX(p,q,r)]) x0=x[IX(p+1,q,r)];
  }
  else
  {
     while(x0>x[IX(p+1,q,r)] && flagw[IX(p+1,q,r)]<0)  p +=1;
	 if(flagw[IX(p+1,q,r)]>0 && x0>x[IX(p+1,q,r)])  x0=x[IX(p,q,r)];
  }

  if(v0>0)
  {
	  while(y0<y[IX(p,q,r)] && flagw[IX(p,q,r)]<0)  q -=1;
      if(y0<y[IX(p,q,r)] && flagw[IX(p,q,r)]>0) y0=y[IX(p,q+1,r)];
  }
  else
  {
   while(y0>y[IX(p,q+1,r)] && flagw[IX(p,q+1,r)]<0)  q +=1;
      if(y0>y[IX(p,q+1,r)] && flagw[IX(p,q+1,r)]>0)  y0=y[IX(p,q,r)];
  }

    if(w0>0)
  {
	  while(z0<gz[IX(p,q,r)] && flagw[IX(p,q,r)]<0)  r -=1;
      if(z0<gz[IX(p,q,r)] && flagw[IX(p,q,r)]>0) z0=gz[IX(p,q,r)];
  }
  else
  {
   while(z0>gz[IX(p,q,r+1)] && flagw[IX(p,q,r+1)]<0)  r +=1;
    if(z0>gz[IX(p,q,r+1)] && flagw[IX(p,q,r+1)]>0)  z0=gz[IX(p,q,r+1)];
  }

     
    x_1 = (x0- x[IX(p,q,r)])/( x[IX(p+1,q,   r  )]- x[IX(p,q,r)]); 
    y_1 = (y0- y[IX(p,q,r)])/( y[IX(p,  q+1, r  )]- y[IX(p,q,r)]);
    z_1 = (z0-gz[IX(p,q,r)])/(gz[IX(p,  q,   r+1)]-gz[IX(p,q,r)]);
             
    /*-------------------------------------------------------------------------
    | Interpolating for all variables
    -------------------------------------------------------------------------*/
    d[IX(i,j,k)] = interpolation(para, d0, x_1, y_1, z_1, p, q, r);
	END_FOR
		  
  /*---------------------------------------------------------------------------
  | define the b.c.
  ---------------------------------------------------------------------------*/
  set_bnd(para, var, var_type, d);
		  
	 }
		  break;
  }
		 

} // End of semi_Lagrangian( )
Exemplo n.º 22
0
/******************************************************************************
  Trace the VX
******************************************************************************/
int trace_vx(PARA_DATA *para, REAL **var, int var_type, REAL *d, REAL *d0, 
             int **BINDEX)
{
  int i, j, k;
  int it;
  int itmax = 20000; // Max number of iterations for backward tracing 
  int imax = para->geom->imax, jmax = para->geom->jmax;
  int kmax = para->geom->kmax;
  int IMAX = imax+2, IJMAX = (imax+2)*(jmax+2);
  REAL x_1, y_1, z_1;
  REAL dt = para->mytime->dt; 
  REAL u0, v0, w0;
  REAL *x = var[X], *y = var[Y],  *z = var[Z]; 
  REAL *gx = var[GX], *gy = var[GY], *gz = var[GZ]; 
  REAL *u = var[VX], *v = var[VY], *w = var[VZ];
  REAL *flagu = var[FLAGU];
  REAL Lx = para->geom->Lx, Ly = para->geom->Ly, Lz = para->geom->Lz; 
  int  COOD[3], LOC[3];
  REAL OL[3];
  int  OC[3];

  FOR_U_CELL
    if(flagu[IX(i,j,k)]>=0) continue;
    /*-----------------------------------------------------------------------
    | Step 1: Tracing Back
    -----------------------------------------------------------------------*/
    // Get velocities at the location of VX
    u0 = u[IX(i,j,k)];
    v0 = 0.5 
        * ((v[IX(i,  j,k)]+v[IX(i,  j-1,k)])*( x[IX(i+1,j,k)]-gx[IX(i,j,k)])
          +(v[IX(i+1,j,k)]+v[IX(i+1,j-1,k)])*(gx[IX(i,  j,k)]- x[IX(i,j,k)])) 
        / (x[IX(i+1,j,k)]-x[IX(i,j,k)]);
    w0 = 0.5 
        * ((w[IX(i,  j,k)]+w[IX(i  ,j, k-1)])*( x[IX(i+1,j,k)]-gx[IX(i,j,k)])
          +(w[IX(i+1,j,k)]+w[IX(i+1,j, k-1)])*(gx[IX(i,  j,k)]- x[IX(i,j,k)]))
        / (x[IX(i+1,j,k)]-x[IX(i,j,k)]); 
    // Find the location at previous time step
    OL[X] =gx[IX(i,j,k)] - u0*dt;
    OL[Y] = y[IX(i,j,k)] - v0*dt;
    OL[Z] = z[IX(i,j,k)] - w0*dt;
    // Initialize the coordinates of previous step 
    OC[X] = i; 
    OC[Y] = j; 
    OC[Z] = k; //OC is the trace back coodinates
    // Initialize the signs for track process
    // Completed: 0; In process: 1
    COOD[X] = 1; 
    COOD[Y] = 1; 
    COOD[Z] = 1; 
    // Initialize the signs for recording if the track back hits the boundary
    // Hit the boundary: 0; Not hit the boundary: 1
    LOC[X] = 1; 
    LOC[Y] = 1; 
    LOC[Z] = 1;
    //Initialize the number of iterations
    it=1;

    // Trace back more if the any of the trace is still in process 
    while(COOD[X]==1 || COOD[Y] ==1 || COOD[Z] ==1)
    {
      it++;
      // If trace in X is in process and donot hit the boundary
      if(COOD[X]==1 && LOC[X]==1) 
        set_x_location(para, var, flagu, gx, u0, i, j, k, OL, OC, LOC, COOD); 
      // If trace in Y is in process and donot hit the boundary
      if(COOD[Y]==1 && LOC[Y]==1) 
        set_y_location(para, var, flagu, y, v0, i, j, k, OL, OC, LOC, COOD); 
      // If trace in Z is in process and donot hit the boundary
      if(COOD[Z]==1 && LOC[Z]==1) 
        set_z_location(para, var, flagu, z, w0, i, j, k, OL, OC, LOC, COOD); 

      if(it>itmax)
      {
        printf("Error: advection.c, can not track the location for VX(%d, %d,%d)",
                i, j, k);
        printf("after %d iterations.\n", it);
        return 1;
      }
    } // End of while() for backward tracing

    // Set the coordinates of previous location if it is as boundary
    if(u0>0 && LOC[X]==0) OC[X] -=1;
    if(v0>0 && LOC[Y]==0) OC[Y] -=1;
    if(w0>0 && LOC[Z]==0) OC[Z] -=1;

    // Fixme: Do not understand here. Should it be
    // if(u0<0 && LOC[X] = 0) OC[X] += 1;
    if(u0<0 && LOC[X]==1) OC[X] -=1; 
    if(v0<0 && LOC[Y]==1) OC[Y] -=1;
    if(w0<0 && LOC[Z]==1) OC[Z] -=1;

    /*-------------------------------------------------------------------------
    | Interpolate
    -------------------------------------------------------------------------*/
    x_1 = (OL[X]-gx[IX(OC[X],OC[Y],OC[Z])]) 
        / (gx[IX(OC[X]+1,OC[Y],OC[Z])]-gx[IX(OC[X],OC[Y],OC[Z])]); 
    y_1 = (OL[Y]-y[IX(OC[X],OC[Y],OC[Z])])
        / (y[IX(OC[X],OC[Y]+1,OC[Z])]-y[IX(OC[X],OC[Y],OC[Z])]);
    z_1 = (OL[Z]-z[IX(OC[X],OC[Y],OC[Z])]) 
        / (z[IX(OC[X],OC[Y],OC[Z]+1)]-z[IX(OC[X],OC[Y],OC[Z])]);

    d[IX(i,j,k)] = interpolation(para, d0, x_1, y_1, z_1, OC[X], OC[Y], OC[Z]);

  END_FOR // End of loop for all cells

  /*---------------------------------------------------------------------------
  | define the b.c.
  ---------------------------------------------------------------------------*/
  set_bnd(para, var, var_type, d, BINDEX);

  return 0;
} // End of trace_vx()
static Point _sogouToGoogleMars(const double lo, const double la) {
    // clock_t start = clock();
#ifdef VERBOSE
    printf("Input: %d, %d\n", (int)lo, (int)la);
#endif
	// 初始化数据
    Node heap[NEIBOR_NUM];
    //double buff0[N], buff1[N];
	
	const int lo1e5 = (int)lo;
	const int la1e5 = (int)la;

    int loIndex = GET_LO_IDX(lo1e5);
    int laIndex = GET_LA_IDX(la1e5);
	loIndex = min(max(loIndex, 0), BUCKET_SIZE_LO - 1);
	laIndex = min(max(laIndex, 0), BUCKET_SIZE_LA - 1);
	
	// printf( "Lo Index: %d, La Index: %d\n", loIndex, laIndex); 
	int len = 0;
	int i, j;
	int64 step = 0;


	

	// step * scale (scale == 1)
	while (1) {
	    int step1 = step - 1;
	    int to_continue = (len < NEIBOR_NUM) || (heap[0].dist > (step1 * step1 * 10000000000ll));
#ifdef VERBOSE1
        int64 step2 = (step * step * 10000000000ll);
        printf("ToContinue: %d, %lld, %lld\n", to_continue, heap[0].dist, step2);
#endif
        if (!to_continue) {
            break;
        }
	    if (step == 0) {
			processList(buckets[loIndex][laIndex], lo1e5, la1e5, heap, &len);

	    } else {
			// including both ends
			j = laIndex - step;
			if (j >= 0) {
			    for (i = max(0, loIndex - step); i <= min(loIndex + step, BUCKET_SIZE_LO - 1); i++) {
				    processList(buckets[i][j], lo1e5, la1e5, heap, &len);
			    }	    
			}
			// not including end points
			i = loIndex + step;
			if (i < BUCKET_SIZE_LO) {
			    for (j = max(0, laIndex - step + 1); j <= min(laIndex + step - 1, BUCKET_SIZE_LA - 1); j++) {
				    processList(buckets[i][j], lo1e5, la1e5, heap, &len);
			    }
			}

			// 下面
			j = laIndex + step;
			if (j < BUCKET_SIZE_LA) {
			    for (i = min(BUCKET_SIZE_LO - 1, loIndex + step); i >= max(0, loIndex - step); --i) {
				    processList(buckets[i][j], lo1e5, la1e5, heap, &len);
			    }
			}
			
			// not including end points
			i = loIndex - step;
			if (i >= 0) {
			    for (j = min(BUCKET_SIZE_LA - 1, laIndex + step - 1); j >= min(0, laIndex - step + 1); --j) {
				    processList(buckets[i][j], lo1e5, la1e5, heap, &len);
			    }
			}
	    }

		step++;
	}

	return interpolation(lo, la, heap);
}
int
main(int argc, char *argv[])
{
	if (argc != 4)
	{
		fprintf(stderr,
			"Usage: %s <bmp frame 1> <bmp frame 2> <bmp MC out>\n",
			argv[0]);
		return -1;
	}

	clock_t start_time = clock();

	int err_code = 0;
	try {
		// Read the input image
		bmp_in in[2];
		if ((err_code = bmp_in__open(&in[0], argv[1])) != 0)
			throw err_code;
		if ((err_code = bmp_in__open(&in[1], argv[2])) != 0)
			throw err_code;

		int width = in[0].cols, height = in[0].rows;
		if ((width != in[1].cols) || (height != in[1].rows))
		{
			fprintf(stderr, "The two input frames have different dimensions.\n");
			return -1;
		}
		my_image_comp mono[2];
		mono[0].init(height, width, 4); // Leave a border of 4 (in case needed)
		mono[1].init(height, width, 4); // Leave a border of 4 (in case needed)

		mono[0].perform_boundary_extension();

		int n, r, c;
		int num_comps = in[0].num_components;
		io_byte *line = new io_byte[width*num_comps];
		for (n = 0; n < 2; n++)
		{
			for (r = height - 1; r >= 0; r--)
			{ // "r" holds the true row index we are reading, since the image
			  // is stored upside down in the BMP file.
				if ((err_code = bmp_in__get_line(&(in[n]), line)) != 0)
					throw err_code;
				io_byte *src = line; // Points to first sample of component n
				int *dst = mono[n].buf + r * mono[n].stride;
				for (c = 0; c < width; c++, src += num_comps)
					dst[c] = *src;
			}
			bmp_in__close(&(in[n]));
		}

		// Allocate storage for the motion compensated output
		my_image_comp output;
		output.init(height, width, 0); // Don't need a border for output

		my_image_comp inter,ref_frame;
		inter.init(height * 2, width * 2, 4);
		ref_frame.init(height * 4, width * 4, 4);
		
		interpolation(&mono[0], &inter);
		interpolation(&inter, &ref_frame);


		my_image_comp output_comps[3];

		for (int i = 0; i < 3; ++i) {
			output_comps[i].init(height, width, 0);
		}

		for (int r = 0; r < height; ++r)
			for (int c = 0; c < width; ++c) {
				output_comps[0].buf[r * output_comps[0].stride + c] = (mono[1].buf[r * mono[1].stride + c] >> 1) + 128;
				output_comps[1].buf[r * output_comps[1].stride + c] = (mono[1].buf[r * mono[1].stride + c] >> 1) + 128;
				output_comps[2].buf[r * output_comps[2].stride + c] = (mono[1].buf[r * mono[1].stride + c] >> 1) + 128;
			}

		// Now perform simple motion estimation and compensation
		int nominal_block_width = nominal_block_size;
		int nominal_block_height = nominal_block_size;
		int block_width, block_height;
		FILE *fp;
		fopen_s(&fp, "Logdata.m", "w");
		fprintf_s(fp, "myvec = [");
		for (r = 0; r < height; r += block_height)
		{
			block_height = nominal_block_height;
			if ((r + block_height) > height)
				block_height = height - r;
			for (c = 0; c < width; c += block_width)
			{
				block_width = nominal_block_width;
				if ((c + block_width) > width)
					block_width = width - c;
				mvector vec = find_motion(&(ref_frame), &(mono[1]),
					r, c, block_width, block_height, 4);
				
				fprintf_s(fp, "%f,%f;\n",vec.x, vec.y);
				
				motion_comp(&(ref_frame), &output, vec,
					r, c, block_width, block_height, 4);
				draw_line(&(mono[1]), &output_comps[1], vec,
					r, c, block_width, block_height);
			
			}
		}
		fprintf_s(fp, "];");
		/*
		for (int r = 0; r < height; ++r)
			for (int c = 0; c < width; ++c) {
				output_comps[0].buf[r * output_comps[0].stride + c] = (output.buf[r * output.stride + c]);
				output_comps[1].buf[r * output_comps[1].stride + c] = (output.buf[r * output.stride + c]);
				output_comps[2].buf[r * output_comps[2].stride + c] = (output.buf[r * output.stride + c]);
			}
		*/
		float sum = 0;
		for (int r = 0; r < height; ++r)
			for (int c = 0; c < width; ++c) {
				float diff = 0;
				diff = mono[1].buf[r * mono[1].stride + c] - output.buf[r * output.stride + c];
				diff *= diff;
				sum += diff;
			}

		sum = sum / (width * height);
		printf("The MSE is %f \r\n", sum);

		// Write the motion compensated image out
		bmp_out out;
		if ((err_code = bmp_out__open(&out, argv[3], width, height, 3)) != 0)
			throw err_code;

		io_byte *out_line = new io_byte[width * 3];
		for (r = height - 1; r >= 0; r--)
		{ // "r" holds the true row index we are writing, since the image is
		  // written upside down in BMP files.
			for (n = 0; n < 3; n++)
			{
				io_byte *dst = out_line + n; // Points to first sample of component n
				int *src = output_comps[n].buf + r * output_comps[n].stride;
				for (int c = 0; c < width; c++, dst += 3) {

					if (src[c] > 255) {
						src[c] = 255;
					}
					else if (src[c] < 0) {
						src[c] = 0;
					}

					*dst = (io_byte)src[c];
				}
			}
			bmp_out__put_line(&out, out_line);
		}
		bmp_out__close(&out);
		delete[] line;

		clock_t end_time = clock();
		float elaps = ((float)(end_time - start_time)) / CLOCKS_PER_SEC;
		printf_s("The runtime is %f seconds!\n\r", elaps);
		system("Pause");
	}
	catch (int exc) {
		if (exc == IO_ERR_NO_FILE)
			fprintf(stderr, "Cannot open supplied input or output file.\n");
		else if (exc == IO_ERR_FILE_HEADER)
			fprintf(stderr, "Error encountered while parsing BMP file header.\n");
		else if (exc == IO_ERR_UNSUPPORTED)
			fprintf(stderr, "Input uses an unsupported BMP file format.\n  Current "
				"simple example supports only 8-bit and 24-bit data.\n");
		else if (exc == IO_ERR_FILE_TRUNC)
			fprintf(stderr, "Input or output file truncated unexpectedly.\n");
		else if (exc == IO_ERR_FILE_NOT_OPEN)
			fprintf(stderr, "Trying to access a file which is not open!(?)\n");
		return -1;
	}
	return 0;
}
Exemplo n.º 25
0
static void extension_zone(int accrochage,int debut,int fin,int to,short *tableau)
  {
#define POURCENTAGE 25
#define SEUIL 20  
#define MAUVAIS_CHEMIN()
#define ECART_CORRECT(a,b) ( (maximum(a,b) - minimum(a,b)) < minimum(SEUIL,(POURCENTAGE * minimum(a,b) / 100)) )

  int trame,avant,i,m,j;
  RESULT table[AVANCE+1][cst_pics_amdf];
  RESULT normal[cst_pics_amdf];

  tableau[accrochage] = avant = to;

/* ---------------on etend a gauche ---------------------------*/

  for (trame=accrochage;trame>debut;)
    {
    table[0][0].rang = avant;
    for (i=1;i<=AVANCE && trame-i >=debut; i++)  
      trier(trame-i,table[i-1][0].rang,table[i]);
    trier( m=maximum(trame-AVANCE , debut) ,avant,normal);
  
    i--;
    
    if ( table[i][0].rang != -1 && normal[0].rang != -1  && table[i][0].rang && normal[0].rang  && avant &&
           abs(TO_FREQ(table[i][0].rang) - TO_FREQ(avant)) > abs(TO_FREQ(normal[0].rang) - TO_FREQ(avant))
       )
        {
        for (j=1;j<=i; j++)  
          tableau[trame-j] = interpolation(trame,avant,m,normal[0].rang,trame-j);
        trame -= i;
        avant = normal[0].rang;
        }
    else  
        {
        if ( table[1][0].rang && ECART_CORRECT(TO_FREQ(avant),TO_FREQ(table[1][0].rang)))
          avant = tableau[--trame] = table[1][0].rang;
        else tableau[--trame] = 0;
        }
    }
    

/* ------------------ on etend a droite -----------------------*/

  avant = tableau[accrochage];
  for (trame=accrochage;trame<fin;)
    {
    table[0][0].rang = avant;
    for (i=1;i<=AVANCE && trame+i <= fin; i++)  
      trier(trame+i,table[i-1][0].rang,table[i]);
    trier( m = minimum(trame+AVANCE , fin) ,avant,normal);
          
    i--;

    if ( table[i][0].rang != -1 && normal[0].rang != -1 && table[i][0].rang && normal[0].rang  && avant &&
         abs(TO_FREQ(table[i][0].rang) - TO_FREQ(avant)) > abs(TO_FREQ(normal[0].rang) - TO_FREQ(avant))
       )
        { 
        for (j=1;j<=i; j++)
          tableau[trame+j] = interpolation(trame,avant,m,normal[0].rang,trame+j);
        trame += i;
        
        avant = normal[0].rang;
        }
    else  
        {
        if ( table[1][0].rang && ECART_CORRECT(TO_FREQ(avant),TO_FREQ(table[1][0].rang)))
          avant = tableau[++trame] = table[1][0].rang;
        else tableau[++trame] = 0;
        }
    }

#undef MAUVAIS_CHEMIN
#undef SEUIL 
#undef ECART_CORRECT
#undef POURCENTAGE
  }
Exemplo n.º 26
0
/* Stabilize given image buffer using stabilization data for
 * a specified frame number.
 *
 * NOTE: frame number should be in clip space, not scene space
 */
ImBuf *BKE_tracking_stabilize_frame(MovieTracking *tracking, int framenr, ImBuf *ibuf,
                                    float translation[2], float *scale, float *angle)
{
	float tloc[2], tscale, tangle;
	MovieTrackingStabilization *stab = &tracking->stabilization;
	ImBuf *tmpibuf;
	int width = ibuf->x, height = ibuf->y;
	float aspect = tracking->camera.pixel_aspect;
	float mat[4][4];
	int j, filter = tracking->stabilization.filter;
	void (*interpolation)(struct ImBuf *, struct ImBuf *, float, float, int, int) = NULL;
	int ibuf_flags;

	if (translation)
		copy_v2_v2(tloc, translation);

	if (scale)
		tscale = *scale;

	/* Perform early output if no stabilization is used. */
	if ((stab->flag & TRACKING_2D_STABILIZATION) == 0) {
		if (translation)
			zero_v2(translation);

		if (scale)
			*scale = 1.0f;

		if (angle)
			*angle = 0.0f;

		return ibuf;
	}

	/* Allocate frame for stabilization result. */
	ibuf_flags = 0;
	if (ibuf->rect)
		ibuf_flags |= IB_rect;
	if (ibuf->rect_float)
		ibuf_flags |= IB_rectfloat;

	tmpibuf = IMB_allocImBuf(ibuf->x, ibuf->y, ibuf->planes, ibuf_flags);

	/* Calculate stabilization matrix. */
	BKE_tracking_stabilization_data_get(tracking, framenr, width, height, tloc, &tscale, &tangle);
	BKE_tracking_stabilization_data_to_mat4(ibuf->x, ibuf->y, aspect, tloc, tscale, tangle, mat);
	invert_m4(mat);

	if (filter == TRACKING_FILTER_NEAREST)
		interpolation = nearest_interpolation;
	else if (filter == TRACKING_FILTER_BILINEAR)
		interpolation = bilinear_interpolation;
	else if (filter == TRACKING_FILTER_BICUBIC)
		interpolation = bicubic_interpolation;
	else
		/* fallback to default interpolation method */
		interpolation = nearest_interpolation;

	/* This function is only used for display in clip editor and
	 * sequencer only, which would only benefit of using threads
	 * here.
	 *
	 * But need to keep an eye on this if the function will be
	 * used in other cases.
	 */
#pragma omp parallel for if (tmpibuf->y > 128)
	for (j = 0; j < tmpibuf->y; j++) {
		int i;
		for (i = 0; i < tmpibuf->x; i++) {
			float vec[3] = {i, j, 0.0f};

			mul_v3_m4v3(vec, mat, vec);

			interpolation(ibuf, tmpibuf, vec[0], vec[1], i, j);
		}
	}

	if (tmpibuf->rect_float)
		tmpibuf->userflags |= IB_RECT_INVALID;

	if (translation)
		copy_v2_v2(translation, tloc);

	if (scale)
		*scale = tscale;

	if (angle)
		*angle = tangle;

	return tmpibuf;
}
	bool SIMULATION_core::adaptation(){

		// let's suppose adaptation will not be necessary
		bool adapt = false;
		pSimPar->set_adapt_occur(false);

		// temporary for debug purposes
		string filename("simulation-parameters/FS-2D-homogeneo/pp-data-files/adapted_mesh_on_wells.msh");

		if ( pSimPar->userRequiresAdaptation() ){
			// performs an error estimation on saturation and/or pressure solution and verifies if tolerances are obeyed.
			// If error is greater than tolerance then mesh will be adapted to improve solution quality

			std::list<int> elemList;
			std::map<int,double> nodeMap;
			bool adapt = calculate_ErrorAnalysis(pErrorAnalysis,pSimPar,pGCData,PhysicPropData::getGradient,elemList,nodeMap);
			pSimPar->printOutVTK(theMesh,pPPData,pErrorAnalysis,pSimPar,pGCData,exportSolutionToVTK);

			if (adapt){
				// let other simulation code parts aware of the occurrence of the adaptation process
				pSimPar->set_adapt_occur(true);

				// retrieve cumulative simulation time
				pSimPar->retrieveSimulationTime();

				pIData->m2 = theMesh;				// auxiliary pointer
				//pIData->m2 = MS_newMesh(0);			// initialize auxiliary pointer
				//PADMEC_mesh *pm = new PADMEC_mesh;	// temporary pointer

				// preserves current mesh and create a new one adapted
				//makeMeshCopy2(pIData->m1,pm,pPPData->getPressure,pPPData->getSw_old);

				// mesh adaptation (adapted mesh saved in file. Bad, bad, bad!)
				//pMeshAdapt->run(pIData->m1,elemList,nodeMap);

				// clean up
				//elemList.clear();
				//nodeMap.clear();

				// delete any trace of FMDB data structure
				//deleteMesh(theMesh); theMesh = 0;

				//create a new FMDB data structure with data in file
				pIData->m1 = MS_newMesh(0);
				readmesh(pIData->m1,filename.c_str());
				theMesh = pIData->m1;

				// take mesh (coords and connectivities) from temporary matrix to m2 (avoid conflicts with FMDB when deleting m1 and theMesh)
				//makeMeshCopy2(pm,pIData->m2,pPPData->setPressure,pPPData->setSaturation);

				// before interpolate data from the old to the new mesh, vectors where pressure and saturation are stored
				// must be allocated for the new mesh (it has just to be created)
				pPPData->allocateTemporaryData(M_numVertices(pIData->m1));

				// interpolate data from m2 to m1
				interpolation(pIData,pSimPar->getInterpolationMethod());

				// transfer Sw and pressure from tmp to main struct
				pPPData->transferTmpData();

				// waste old data and get ready for new data
				pGCData->deallocatePointers(0);

				// mesh pre-processor
				EBFV1_preprocessor(pIData->m1,pGCData);

				// initialize geometric coefficients pointer
				pGCData->initilize(theMesh);

				// objects (pSimPar, pMData, pGCData, pPPData) must store new data
				updatePointersData(theMesh);

				// data transfer from FMDB to matrices
				pGCData->dataTransfer(theMesh);

				pSimPar->printOutVTK(pIData->m1,pPPData,pErrorAnalysis,pSimPar,pGCData,exportSolutionToVTK);

				STOP();

				// temporary mesh not necessary any more (goodbye!)
				//deleteMesh(pm);
				//delete pm; pm = 0;
				deleteMesh(pIData->m2); delete pIData->m2; pIData->m2 = 0;
			}
		}
		return adapt;
	}
Exemplo n.º 28
0
void main()
{
	int i, x, s, start, finish, value, count;
	unsigned long int j;
	unsigned int mask=1;
	long int error, ferror;
	double progress, b;

	srand(1977);

	mono_table();
/*
	//*********debug*********
	printf("mono_table:\n");
	for(j=0;j<mono_size;j++)
	{
		for(i=0;i<mono_size;i++)
			printf("\t%d",mono_order[j][i]);
		printf("\n");
	}
	//*******************
*/

	printf("\nEnter start SNR: ");
	scanf("%d", &start);
	printf("\nEnter finish SNR: ");
	scanf("%d", &finish);
	printf("\nseq_num: ");
	scanf("%d", &seq_num);


	for(SNR=start;SNR<=finish;SNR++)
	{	
		N0=(1.0/(float(k)/float(n)))/pow(10.0, float(SNR)/10.0);
		sgm=sqrt(N0/2);
		b=1.0;
		error=0;
		//ferror=0; 
		for(j=1;j<=seq_num;j++)
		{

		//printf("\n\n*************For the %dth frame*************:\n", j);
		//Generate binary message
			for(i=0;i<k*p;i++)
				bi_message[i]=rand()%2;

			//Convert to nonbinary
			for(i=0;i<k;i++)
				message[i]=bi_message[p*i]+2*bi_message[p*i+1]+4*bi_message[p*i+2]+8*bi_message[p*i+3];

/*			//******debug*******
			message[0]=6;	message[1]=9;	message[2]=2;	message[3]=6;
			message[4]=10;	message[5]=8;	message[6]=2;	message[7]=0;
			message[8]=0;
*/
			//*******************

			encoder();

	
			//Convert the codeword into binary
			for(i=0;i<n;i++)
			{
				value=codeword[i];
				mask=1;
				for(x=0;x<p;x++) //for(m=p-1;m>=0;m--)
				{
					if((value & mask)>0)
						bi_codeword[p*i+x]=1;
					else
						bi_codeword[p*i+x]=0;
					mask=mask<<1;
				}
			}
		
			modulation();
			
			channel();
			
			/////////To be done?////////////
			demodulation();

			interpolation();

			factorization();
			
			//Number of errors calculation
			//error=0;
			for(i=0;i<p*n;i++)
				if(bi_codeword[i]!=dec_codeword[i])
					error++;
/*			
			if(f_error_temp==1)
				printf("\nerror=%d\n",error);
			f_error_temp=0;
*/			/*
			if(error!=0)
				ferror++;
			*/

			progress=(double)(j*100)/(double)seq_num;
			
			BER=(double)(error)/(double)(n*p*j);
			//FER=(double)(ferror)/(double)(j),
			printf("Progress=%0.1f, SNR=%2.1d, Bit Errors=%2.1d, BER=%E\r", progress, SNR, error, BER);
//			printf(" Progress=%0.1f,dectect=%d\r",progress,dectec);
			
		}
		BER=(double)error/(double)(n*p*seq_num);
		//FER=(double)(ferror)/(double)(seq_num);
		printf("Progress=%0.1f, SNR=%2.1d, Bit Errors=%2.1d, BER=%E\n",progress, SNR, error, BER);
//		printf(" Progress=%0.1f,dectect=%d\r",progress,dectec);

	}


	getchar();
	getchar();
		
}
Exemplo n.º 29
0
int main(int argc, char* argv[])
{
    int nang, N;
    float dx, dz;
    int nx, nz;
    float ox, oz;
    int gnx, gnz;
    float gdx, gdz, gox, goz;
    struct point length;
    int inter;
    float TETAMAX, alpha2;
    FILE *outfile;
    int ii;
    int rays, wfront, gap;
    int lomx, first;
    int nr, nrmax, nt;
    int prcube, pr, ste;
    int ns, nou;
    float DSmax, dt, T, freq;
    float *vel;
    float ds, os, goox;
    float xmin, xmax, zmin, zmax;
    float depth;
    struct point *pos;
    struct heptagon *cube;
    struct grid *out;
    sf_file inp, ampl, time;

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

/* GET MODEL PARAMETERS	*/
    if (!sf_histint(inp,"n1",&nz)) sf_error("No n1= in input");
    if (!sf_histint(inp,"n2",&nx)) sf_error("No n2= in input");
    if (!sf_histfloat(inp,"d1",&dz)) sf_error("No d1= in input");
    if (!sf_histfloat(inp,"d2",&dx)) sf_error("No d2= in input");
    if (!sf_histfloat(inp,"o1",&oz)) sf_error("No o1= in input");
    if (!sf_histfloat(inp,"o2",&ox)) sf_error("No o2= in input");

/* GET TRACING PARAMETERS */
    if(!sf_getint("nang",&nang))        nang = 10;    /* Number of take-off angles */
    if(!sf_getint("rays",&rays))        rays = 0;     /* If draw rays */
    if(!sf_getint("wfront",&wfront))    wfront = 0;   /* If draw wavefronts */ 
    if(!sf_getint("gap",&gap))        	gap = 1;      /* Draw wavefronts every gap intervals */
    if(!sf_getint("inter",&inter))      inter = 1;    /* If use linear interpolation */
    if(!sf_getfloat("DSmax",&DSmax))    DSmax = 5;    /* Maximum distance between contiguos points of a wavefront */
    if(!sf_getfloat("dt",&dt))          dt = 0.0005;  /* time step */
    if(!sf_getint("nt",&nt))            nt = 5;       /* Number of time steps between wavefronts */
    if(!sf_getint("nrmax",&nrmax))      nrmax = 2000; /* Maximum number of points that define a wavefront */
    if(!sf_getint("lomx",&lomx))        lomx = 1;     /* Use Lomax's waveray method */
    if(!sf_getint("first",&first))      first = 1;    /* Obtain first arrivals only */
    if(!sf_getint("nou",&nou))      	nou = 6;      

/* GET GRIDDING PARAMETERS */
    if(!sf_getint("gnx",&gnx))		gnx = nx;    /* Coordinates of output grid */
    if(!sf_getint("gnz",&gnz))		gnz = nz;
    if(!sf_getfloat("gdx",&gdx))	gdx = dx;
    if(!sf_getfloat("gdz",&gdz))	gdz = dz;
    if(!sf_getfloat("gox",&goox))	goox = ox;
    if(!sf_getfloat("goz",&goz))	goz = oz;

/* GET LOMAX SPECIFIC PARAMETERS */
    if(!sf_getint("N",&N))                N = 3;         /* Number of control points */
    if(!sf_getfloat("TETAMAX",&TETAMAX))  TETAMAX = 1.5; /* Truncation parameter */
    if(!sf_getfloat("alpha2",&alpha2))    alpha2 = 4.0;  /* Width of gaussian weighting function */
    if(!sf_getfloat("freq",&freq))	  freq = 100.;   /* Pseudo-frequency of waverays */

/* GET DEBUGGING INFO */
    if(!sf_getint("prcube",&prcube)) 	prcube=0;        /* For debugging porpouses */
    if(!sf_getint("pr",&pr)) 		pr=0;            /* For debugging porpouses */

/* GET SOURCE LOCATIONS */
    if(!sf_getint("ns",&ns) || ns==0)	  ns=1;          /* Number of source locations */
    if(!sf_getfloat("ds",&ds))		  ds=1.;         /* interval between sources */
    if(!sf_getfloat("os",&os))		  os=0.;         /* first source location */
    if(!sf_getfloat("depth",&depth))	  depth=dz;      /* Depth location of sources */

    pos = (struct point *) sf_alloc (ns,sizeof(struct point));
    for(ii=0;ii<ns;ii++) {
	pos[ii] = makepoint(ii*ds + os, depth);
    }

/* PREPARE OUTPUT */
    ampl = sf_output("ampl");
    sf_putint(ampl,"n1",gnz);
    sf_putint(ampl,"n2",gnx);
    sf_putint(ampl,"n3",ns);
    sf_putfloat(ampl,"d1",gdz);
    sf_putfloat(ampl,"d2",gdx);
    sf_putfloat(ampl,"d3",ds);
    sf_putfloat(ampl,"o1",goz);
    sf_putfloat(ampl,"o2",goox);
    sf_putfloat(ampl,"o3",os);

    time = sf_output("time");
    sf_putint(time,"n1",gnz);
    sf_putint(time,"n2",gnx);
    sf_putint(time,"n3",ns);
    sf_putfloat(time,"d1",gdz);
    sf_putfloat(time,"d2",gdx);
    sf_putfloat(time,"d3",ds);
    sf_putfloat(time,"o1",goz);
    sf_putfloat(time,"o2",goox);
    sf_putfloat(time,"o3",os);

/* READ VELOCITY MODEL */
    vel = sf_floatalloc(nx*nz+2);
    sf_floatread(vel,nx*nz,inp); 

/* ALLOCATE MEMORY FOR OUTPUT */
    out = (struct grid *) sf_alloc (1,sizeof(struct grid));

    out->time = sf_floatalloc (gnx*gnz);
    out->ampl = sf_floatalloc (gnx*gnz);
    out->flag = sf_intalloc (gnx*gnz);

    T = 1. / freq;

    length = makepoint((nx-1)*dx,(nz-1)*dz);

    cube = (struct heptagon *) sf_alloc (nrmax,sizeof(struct heptagon));

/* FOR DEBUGGING PORPOUSES, PRINT TO FILE */
    if(pr||prcube) {
	outfile = fopen("junk","w");
    } else {
	outfile = NULL;
    }

/*  SET DISPLAY IN ORDER TO SHOW RAYS ON SCREEN */
/*  NOTE: THIS PROGRAM USES DIRECT CALLS TO LIB_VPLOT
 *  TO DRAW THE RAYS AND THE WAVEFRONTS */
    if(rays || wfront) {
	setgraphics(ox, oz, length.x, length.z);
/*
	vp_color(BLUE);
	for(ii=0;ii<gnx;ii++)  {
	    vp_umove(ii*gdx+gox, goz); vp_udraw(ii*gdx+gox, (gnz-1)*gdz+goz); }
	for(ii=0;ii<gnz;ii++) {
	    vp_umove(gox, ii*gdz+goz); vp_udraw((gnx-1)*gdx+gox, ii*gdz+goz); } 
*/
    }

    norsar_init(gnx,gnz,
		TETAMAX,N,alpha2,inter,
		nx,nz,ox,oz,dx,dz,length);

/*  ALGORITHM: 
 *    For every source: */
    for(ii=0;ii<ns;ii++) {
	ste = 0;
	gox = goox + pos[ii].x;
	sf_warning("\nSource #%d\n", ii);

/*	1.- Construct the inital wavefront 			*/
	nr = nang;
    	initial (pos[ii], cube, vel, dt, nt, T, lomx, nr, out);

	gridding_init(gnx,gnz,
		      gdx,gdz,gox,goz,
		      outfile);

/*	run while the wavefront is not too small 		*/
	while (nr > 4) {
	    ste++;

/*	    2.- Propagate wavefront 				*/
	    wavefront (cube, nr, vel, dt, nt, T, lomx);
	    if(prcube || pr) {
		fprintf(outfile,"\n\nwavefront");
		printcube(cube, nr, outfile);
	    }

/*	    3.- Get rid of caustics				*/
            if(first) {
		if(ste%2==1) {			
		    caustics_up (cube, 0, nr);
		} else {
		    caustics_down (cube, nr-1, nr);
		}					
		if(prcube || pr) {	
		    fprintf(outfile,"\n\ncaustics");
		    printcube(cube, nr, outfile);
		}
	    }

/*          4.- Eliminate rays that cross boundaries, defined
		by xmin, xmax, zmin, zmax.
		Note that the computational grid is a little bigger 
		than the ouput grid. 				*/

	    xmin = gox-nou*gdx;	xmax = 2*pos[ii].x-gox+nou*gdx;
	    zmin = oz-nou*gdz;	zmax = length.z+oz+nou*gdz;
            mark_pts_outofbounds (cube, nr, xmin, xmax, zmin, zmax);
	    if(prcube) {
                fprintf(outfile, "\n\nboundaries");
                printcube(cube, nr, outfile);
            }

/*          5.- Rearrange cube                                  */
            makeup(cube, &nr);
	    if(nr<4) break;
	    if(prcube || pr) {	
                fprintf(outfile, "\n\nmakeup");
                printcube(cube, nr, outfile);
            }

/*          6.- Calculate amplitudes for new wavefront 		*/
	    amplitudes (cube, nr); 
	    if(prcube) {
                fprintf(outfile, "\n\namplitudes");
                printcube(cube, nr, outfile);
            }

/*	    7.- Draw rays 					*/
	    if(rays)
		draw_rays (cube, nr); 

/*          8.- Draw wavefront 					*/
	    if(wfront && (ste%gap==0)) 
		draw_wavefronts (cube, nr, DSmax); 

/*          9.- Parameter estimation at receivers 		*/
	    gridding (cube, nr, out, DSmax, (ste-1)*nt*dt, vel, first); /* pos[ii]); */

/*          10.- Interpolate new points of wavefront 		*/
            interpolation (cube, &nr, nrmax, DSmax); /* 0); */
	    if(prcube) {
                fprintf(outfile,"\n\ninterpolation");
                printcube(cube, nr, outfile);
            }

/*	    11.- Prepare to trace new wavefront 		*/
	    movwavf (cube, nr);
	    if(prcube) {
                fprintf(outfile,"\n\nmovwavf");
                printcube(cube, nr, outfile);
            }

	    if((wfront || rays) && (ste%gap==0)) vp_erase();
	}

/*	Finally interpolate amplitude and traveltime values to
        receivers that has not being covered.			*/
	TwoD_interp (out, gnx, gnz);

	sf_floatwrite(out->time, gnx * gnz, time); 
	sf_floatwrite(out->ampl, gnx * gnz, ampl);  
    }

   if(pr||prcube)
	fclose(outfile);

   exit(0);
}
Exemplo n.º 30
0
int main()
{
    interpolation();

    return 0;
}