Пример #1
0
void checkcentrality(TString datafilename, TString mcfilename)
{
  TFile *fdt = new TFile(datafilename);
  TFile *fmc = new TFile(mcfilename);

  auto tdt = (TTree *)fdt->Get("nt");
  auto tmc = (TTree *)fmc->Get("nt");

  auto hdt = new TH1F("centrdt","centrdt",50,0,200); hdt->SetMarkerColor(kBlack);
  auto hmc = new TH1F("centrmc","centrmc",50,0,200); hmc->SetMarkerColor(kBlue);

  SetMC({hmc}); SetInc({hmc});
  SetData({hdt});


  tdt->Project("centrdt","bin","weight*(jtpt1>120 && jtpt2>30 && dphi21>2. && hiHF<5500)");
  tmc->Project("centrmc","bin","weight*(jtpt1>120 && jtpt2>30 && dphi21>2. && pthatsample>30)");

  hmc->Scale(hdt->Integral()/hmc->Integral());

  fout->cd();
  hdt->Write();
  hmc->Write();
  fdt->Close();
  fmc->Close();

}
Пример #2
0
  LinearProblem prob(const Mesh& mesh) const
    {
      CellFilter left = domain().left();
      CellFilter right = domain().right();


      Expr u = new UnknownFunction(new Lagrange(3), "u");
      Expr v = new UnknownFunction(new Lagrange(1), "v");
      Expr du = new TestFunction(new Lagrange(3), "du");
      Expr dv = new TestFunction(new Lagrange(1), "dv");

      Expr dx = gradient(1);
      Expr x = coord(0);


      QuadratureFamily quad = new GaussianQuadrature(10);

      Expr eqn = Integral(interior(), 
        (dx*du)*(dx*u) + du*v + (dx*dv)*(dx*v) + x*dv, 
        quad);

      Expr bc = EssentialBC(left, du*u + dv*v, quad)
        + EssentialBC(right, du*u + dv*v, quad);


      return LinearProblem(mesh, eqn, bc, 
        List(dv,du), List(v,u), vecType());
      
    }  
Пример #3
0
int surfDetDes(IplImage *img,  /* image to find Ipoints in */
                       Ipoint *ipts, /* reference to vector of Ipoints */
                       int upright, /* run in rotation invariant mode? */
                       int octaves, /* number of octaves to calculate */
                       int intervals, /* number of intervals per octave */
                       int init_sample, /* initial sampling step */
                       float thres, /* blob response threshold */
					   int size /*Size of Array */)
{	
  int ipts_size;
  FastHessian fh;	

  // Create integral-image representation of the image
  IplImage *int_img = Integral(img);

  // Create Fast Hessian Object
  FastH(&fh,int_img);

  // Extract interest points and store in vector ipts
  ipts_size = getIpoints(&fh);
  
  // Create Surf Descriptor Object
  Surf_Constractor(int_img, &fh, upright, ipts, size);

  // Deallocate the integral image
  cvReleaseImage(&int_img);

  return ipts_size;
}
Пример #4
0
double Envelope::Average( double t0, double t1 )
{
  if( t0 == t1 )
    return GetValue( t0 );
  else
    return Integral( t0, t1 ) / (t1 - t0);
}
Пример #5
0
Expr NitscheStokesNoSlipBC(const CellFilter& cells,
  const QuadratureFamily& quad,
  const Expr& nu,
  const Expr& v,
  const Expr& q,
  const Expr& u,
  const Expr& p,
  const Expr& uBC,
  const double& gamma1,
  const double& gamma2
  )
{
  TEUCHOS_TEST_FOR_EXCEPT(nu.size() != 1);
  TEUCHOS_TEST_FOR_EXCEPT(v.size() != u.size());
  TEUCHOS_TEST_FOR_EXCEPT(uBC.size() != u.size());

  int dim = uBC.size();

  Expr grad = gradient(dim);
  Expr n = CellNormalExpr(dim,"n");
  Expr h = new CellDiameterExpr();
  
  return Integral(cells,
    -nu*(v*((n*grad)*u /*- (n*grad)*uBC*/) + (u-uBC)*((n*grad)*v))
    + p*(v*n) + q*((u-uBC)*n)
    + gamma1/h * v*(u-uBC) + gamma2/h * (v*n) * ((u-uBC)*n),
    quad);
}
Пример #6
0
Double_t RegionIntegratorMultiDim::RegionIntegral(const ROOT::Math::IMultiGenFunction &f, const Regions &reg)
{
    Double_t result = 0;
    Double_t xlow[2], xhigh[2];
    for (UInt_t i=0; i<reg.size(); i++)
    {
        if (fUseCenters == true)
        {
            xlow[0] = reg[i].cntr_xlow;
            xlow[1] = reg[i].cntr_ylow;

            xhigh[0] = reg[i].cntr_xhigh;
            xhigh[1] = reg[i].cntr_yhigh;
        }
        else
        {
            xlow[0] = reg[i].grid_xlow;
            xlow[1] = reg[i].grid_ylow;

            xhigh[0] = reg[i].grid_xhigh;
            xhigh[1] = reg[i].grid_yhigh;
        }

        result += Integral(f, xlow, xhigh);
    }

    return result;
}
Пример #7
0
// We should be able to write a very efficient memoizer for this
// but make sure it gets reset when the envelope is changed.
double Envelope::Integral( double t0, double t1 )
{
   if(t0 == t1)
      return 0.0;
   if(t0 > t1)
   {
      return -Integral(t1, t0); // this makes more sense than returning the default value
   }

   unsigned int count = mEnv.Count();
   if(count == 0) // 'empty' envelope
      return (t1 - t0) * mDefaultValue;

   double total = 0.0, lastT, lastVal;
   unsigned int i; // this is the next point to check
   if(t0 < mEnv[0]->GetT()) // t0 preceding the first point
   {
      if(t1 <= mEnv[0]->GetT())
         return (t1 - t0) * mEnv[0]->GetVal();
      i = 1;
      lastT = mEnv[0]->GetT();
      lastVal = mEnv[0]->GetVal();
      total += (lastT - t0) * lastVal;
   }
   else if(t0 >= mEnv[count - 1]->GetT()) // t0 following the last point
   {
      return (t1 - t0) * mEnv[count - 1]->GetVal();
   }
   else // t0 enclosed by points
   {
      // Skip any points that come before t0 using binary search
      int lo, hi;
      BinarySearchForTime(lo, hi, t0);
      lastVal = InterpolatePoints(mEnv[lo]->GetVal(), mEnv[hi]->GetVal(), (t0 - mEnv[lo]->GetT()) / (mEnv[hi]->GetT() - mEnv[lo]->GetT()), mDB);
      lastT = t0;
      i = hi; // the point immediately after t0.
   }

   // loop through the rest of the envelope points until we get to t1
   while (1)
   {
      if(i >= count) // the requested range extends beyond the last point
      {
         return total + (t1 - lastT) * lastVal;
      }
      else if(mEnv[i]->GetT() >= t1) // this point follows the end of the range
      {
         double thisVal = InterpolatePoints(mEnv[i - 1]->GetVal(), mEnv[i]->GetVal(), (t1 - mEnv[i - 1]->GetT()) / (mEnv[i]->GetT() - mEnv[i - 1]->GetT()), mDB);
         return total + IntegrateInterpolated(lastVal, thisVal, t1 - lastT, mDB);
      }
      else // this point preceeds the end of the range
      {
         total += IntegrateInterpolated(lastVal, mEnv[i]->GetVal(), mEnv[i]->GetT() - lastT, mDB);
         lastT = mEnv[i]->GetT();
         lastVal = mEnv[i]->GetVal();
         i++;
      }
   }
}
double L2Norm(const Mesh& mesh, const CellFilter& domain,
  const Expr& f, const QuadratureFamily& quad,
  const WatchFlag& watch)
{
  Expr I2 = Integral(domain, f*f, quad, watch);

  return sqrt(evaluateIntegral(mesh, I2));
}
Пример #9
0
int main()
{
	double a=0.0, b, eps=0.005, l, t;

	while (scanf("%lf %lf %lf", &l, &b, &t) != EOF)
		printf("%.2f\n", Integral(a, b, f0, eps, l, t));

	return 0;
}
Пример #10
0
  /** 
   * Return a LP for the specified mesh. This function implements the
   * prob() pure virtual function of class LPTestBase.
   */
  LinearProblem prob(const Mesh& mesh) const
    {
      const double pi = 4.0*atan(1.0);
      CellFilter left = domain().left();

      Expr u = new UnknownFunction(new Lagrange(2), "u");
      Expr v = new TestFunction(new Lagrange(2), "v");
      Expr dx = gradient(1);
      Expr x = coord(0);

      QuadratureFamily quad = new GaussianQuadrature(4);

      Expr eqn = Integral(interior(), (dx*v)*(dx*u), quad)
        + Integral(interior(), -0.25*pi*pi*sin(pi*x/2.0)*v, quad);

      Expr bc = EssentialBC(left, v*u, quad);
      
      return LinearProblem(mesh, eqn, bc, v, u, vecType());
    }
Пример #11
0
void checkvertex(TString datafilename, TString mcfilename)
{

  TFile *fmc = new TFile(mcfilename);
  auto ntmc = (TTree *)fmc->Get("nt");
  TFile *fdt = new TFile(datafilename);
  auto ntdt = (TTree *)fdt->Get("nt");

  auto vdt0 = new TH1F("vdt0","Data no weighting",30,-15,15); vdt0->Sumw2();
  auto vmc0 = new TH1F("vmc0","MC no weighting",30,-15,15); vmc0->Sumw2();

  ntdt->Project("vdt0","vz","weight*(jtpt2>120 && jtpt2>30)");
  ntmc->Project("vmc0","vz","pthatweight*(jtpt2>120 && jtpt2>30 && pthatsample>30)");
  
  vdt0->Scale(1/vdt0->Integral());
  vmc0->Scale(1/vmc0->Integral());

  plotylog = false;
  Draw({vdt0,vmc0});

  auto vdt = new TH1F("vdt","Data weighted",30,-15,15); vdt->Sumw2();
  auto vmc = new TH1F("vmc","MC weighted",30,-15,15); vmc->Sumw2();

  ntdt->Project("vdt","vz","weight*(jtpt2>120 && jtpt2>30)");
  ntmc->Project("vmc","vz","weight*(jtpt2>120 && jtpt2>30 && pthatsample>30)");
  
  vdt->Scale(1/vdt->Integral());
  vmc->Scale(1/vmc->Integral());


  SetMC({vmc, vmc0});
  SetData({vdt,vdt0});
  SetInc({vmc, vmc0});


  fout->cd();
  vdt->Write();
  vmc->Write();
  vdt0->Write();
  vmc0->Write();
  fmc->Close();
  fdt->Close();
}
Пример #12
0
double H1Norm(
  const Mesh& mesh,
  const CellFilter& filter,
  const Expr& f,
  const QuadratureFamily& quad,
  const WatchFlag& watch)
{
  Expr grad = gradient(mesh.spatialDim());
  Expr g = grad*f;
  Expr I2 = Integral(filter, f*f + g*g, quad, watch);

  return sqrt(evaluateIntegral(mesh, I2));  
}
Пример #13
0
  LinearProblem prob(const Mesh& mesh) const
    {
      Expr u = new UnknownFunction(basis_, "u");
      Expr v = new TestFunction(basis_, "v");
      Expr x = coord(0);

      int p = basis_.order();
      QuadratureFamily quad = new GaussianQuadrature(2*p);

      Expr ex = exactSoln();
      Expr eqn = Integral(interior(), v*(u-ex), quad);
      Expr bc;
      
      return LinearProblem(mesh, eqn, bc, v, u, vecType());
    }
Пример #14
0
Expr NitschePoissonDirichletBC(int dim,
  const CellFilter& cells,
  const QuadratureFamily& quad,
  const Expr& kappa,
  const Expr& v,
  const Expr& u,
  const Expr& uBC,
  const double& gamma)
{
  Expr grad = gradient(dim);
  Expr n = CellNormalExpr(dim,"n");
  Expr h = new CellDiameterExpr();

  return Integral(cells, -kappa*(v*((n*grad)*u) + (u-uBC)*((n*grad)*v))
    + gamma/h * v*(u-uBC), quad);
}
Пример #15
0
  LinearProblem prob(const Mesh& mesh) const
    {
      CellFilter left = domain().left();
      CellFilter right = domain().right();

      Expr u = new UnknownFunction(new Lagrange(2), "u");
      Expr v = new TestFunction(new Lagrange(2), "v");
      Expr dx = gradient(1);
      Expr x = coord(0);

      QuadratureFamily quad = new GaussianQuadrature(4);

      Expr eqn = Integral(interior(), (dx*v)*(dx*u) - v*u, quad);
      Expr bc = EssentialBC(left, v*(u-cos(x)), quad);
      
      return LinearProblem(mesh, eqn, bc, v, u, vecType());
    }
Пример #16
0
//计算LC
static void CalcStd(u8 *pu8Gray, f32 *pf32Contrast, l32 * pl32IImg, l32 *pl32IImg2, l32 l32Width, l32 l32Height, l32 l32BlockW, l32 l32BlockH)
{
    l32 l32Row, l32Col, l32BlockSize;
    l32 l32Left, l32Right, l32Top, l32Bot;
    f32 f32Std, f32Var, f32EX, f32EX2;

    memset(pl32IImg, 0, (l32Width + 1) * (l32Height + 1) * sizeof(l32));
    memset(pl32IImg2, 0, (l32Width + 1) * (l32Height + 1) * sizeof(l32));

    //计算积分图像
    Integral(pu8Gray, pl32IImg, l32Width, l32Height);
    Integral2(pu8Gray, pl32IImg2, l32Width, l32Height);

    for(l32Row = 0; l32Row < l32Height; l32Row++)
    {
        for(l32Col = 0; l32Col < l32Width; l32Col++)
        {
            //compute local contrast
            l32Left  = MAX(l32Col - l32BlockW/2, 0);
            l32Right = MIN(l32Col + l32BlockW/2 + 1, l32Width);
            l32Top = MAX(l32Row - l32BlockH/2, 0);
            l32Bot = MIN(l32Row + l32BlockH/2 + 1, l32Height);
            l32BlockSize = (l32Right - l32Left) * (l32Bot - l32Top);

            f32EX = 1.0f * (pl32IImg[l32Bot * (l32Width + 1) + l32Right]  - pl32IImg[l32Bot * (l32Width + 1) + l32Left] 
            - pl32IImg[l32Top * (l32Width + 1) + l32Right] + pl32IImg[l32Top * (l32Width + 1) + l32Left]) / l32BlockSize;
            f32EX2 = 1.0f * (pl32IImg2[l32Bot * (l32Width + 1) + l32Right] - pl32IImg2[l32Bot * (l32Width + 1) + l32Left] 
            - pl32IImg2[l32Top * (l32Width + 1) + l32Right] + pl32IImg2[l32Top * (l32Width + 1) + l32Left]) / l32BlockSize;

            //计算方差
            f32Var = f32EX2 - f32EX * f32EX;
            f32Std = sqrt(f32Var);    
            *pf32Contrast = f32Std;
            pf32Contrast++;
        }
    }
}
Пример #17
0
int scaling(SDL_Surface *image, feature feat)
{ 
    int a,b,c,d,e,f;
    
    int n,w,i,j,h;
    int **arr = Integral(image);

    if(feat.t == 1)
    {
	int x = 1;
	n = 2*feat.w*feat.h;
	i = (int)(round((feat.i*image->h)/24));
	j = (int)(round((feat.j*image->h)/24));
	h = (int)(round((feat.h*image->h)/24));
	while(x < (((int)(round(1+(2*feat.w*image->h)/24)))/2)&& 2*x<((image->h-j+1)))
	{
	    x++;
	}
	int S1,S2;
	w = x;
	a = i+h-1;
	b = j+w-1;
	c = j-1;
	d = i-1;
	e = j+2*w-1;
	S1=(((a<0)|(b<0))?0:arr[a][b])-(((a<0)|(c<0))?0:arr[a][c])-(((d<0)|(b<0))?0:arr[d][b])+(((d<0)|(c<0))?0:arr[d][c]);
	S2=(((a<0)|(e<0))?0:arr[a][e])-(((a<0)|(b<0))?0:arr[a][b])-(((d<0)|(e<0))?0:arr[d][e])+(((d<0)|(b<0))?0:arr[d][b]);
    
       return ((S1-S2)*n)/(2*w*h);
    }

    if(feat.t==2)
    {	
	int x=1;
	i = (int)(round((feat.i*image->h)/24));
	j = (int)(round((feat.j*image->h)/24));
	h = (int)(round((feat.h*image->h)/24));
	n = 3*feat.w*feat.h;
	while(x < (((int)(round(1+(3*feat.w*image->h)/24)))/3)&& 3*x<((image->h-j+1)))
	{
	    x++;
	}
	w=x;
	int S1,S2,S3;
	a = i+h-1;
	b = j+w-1;
	c = j-1;
	d = i-1;
	e = j+2*w-1;
	f = j+3*w-1;
 	S1 = (((a<0)|(b<0))?0:arr[a][b])-(((a<0)|(c<0))?0:arr[a][c])-(((d<0)|(b<0))?0:arr[d][b])+(((d<0)|(c<0))?0:arr[d][c]);
	S2=(((a<0)|(e<0))?0:arr[a][e])-(((a<0)|(b<0))?0:arr[a][b])-(((d<0)|(e<0))?0:arr[d][e])+(((d<0)|(b<0))?0:arr[d][b]);
	S3 = (((a<0)|(f<0))?0:arr[a][f])-(((a<0)|(e<0))?0:arr[a][e])-(((d<0)|(f<0))?0:arr[d][f])+(((d<0)|(e<0))?0:arr[d][e]);

    return ((S1-S2+S3)*n)/(3*w*h);
    }

    if(feat.t==3)
    {
	int x=1;
	i = (int)(round((feat.i*image->h)/24));
	j = (int)(round((feat.j*image->h)/24));
	w = (int)(round((feat.w*image->h)/24));
	n = 2*feat.w*feat.h;
	while(x < (((int)(round(1+(2*feat.h*image->h)/24)))/2)&& 2*x<((image->h-j+1)))
	{
	    x++;
	}
	h=x;
	int S1,S2;
	a = i+h-1;
	b = j+w-1;
	c = j-1;
	d = i-1;
	e = i+2*h-1;
  	S1=(((a<0)|(b<0))?0:arr[a][b])-(((a<0)|(c<0))?0:arr[a][c])-(((d<0)|(b<0))?0:arr[d][b])+(((d<0)|(c<0))?0:arr[d][c]);
        S2=(((e<0)|(b<0))?0:arr[e][b])-(((e<0)|(c<0))?0:arr[e][c])-(((a<0)|(b<0))?0:arr[a][b])+(((a<0)|(c<0))?0:arr[a][c]);

    return ((S1-S2)*n)/(2*w*h);
    }
    
    if(feat.t==4)
    {
	int x=1;
	i = (int)(round((feat.i*image->h)/24));
	j = (int)(round((feat.j*image->h)/24));
	w = (int)(round((feat.w*image->h)/24));
	n = 3*feat.w*feat.h;
	while(x < (((int)(round(1+(3*feat.h*image->h)/24)))/3)&& 3*x<((image->h-j+1)))
	{
	    x++;
	}
	h=x;
	int S1,S2,S3;
	a = i+h-1;
	b = j+w-1;
	c = j-1;
	d = i-1;
	e = i+2*h-1;
	f = i+3*h-1;
	S1 = (((a<0)|(b<0))?0:arr[a][b])-(((a<0)|(c<0))?0:arr[a][c])-(((d<0)|(b<0))?0:arr[d][b])+(((d<0)|(c<0))?0:arr[d][c]);
	S2=(((e<0)|(b<0))?0:arr[e][b])-(((e<0)|(c<0))?0:arr[e][c])-(((a<0)|(b<0))?0:arr[a][b])+(((a<0)|(c<0))?0:arr[a][c]);
	S3=(((f<0)|(b<0))?0:arr[f][b])-(((f<0)|(c<0))?0:arr[f][c])-(((e<0)|(b<0))?0:arr[e][b])+(((e<0)|(c<0))?0:arr[e][c]);
	
    return ((S1-S2+S3)*n)/(3*w*h);
    }
    
    if(feat.t==5)
    {
	int x=1;
	i = (int)(round((feat.i*image->h)/24));
	j = (int)(round((feat.j*image->h)/24));
	n = 4*feat.w*feat.h;
	while(x < (((int)(round(1+(2*feat.h*image->h)/24)))/2)&& 2*x<((image->h-j+1)))
	{
	    x++;
	}
	h=x;
	x=1;	
	while(x < (((int)(round(1+(2*feat.w*image->h)/24)))/2)&& 2*x<((image->h-j+1)))
	{
	    x++;
	}
	w=x;
	int S1,S2,S3,S4;
	a = i+h-1;
	b = j+w-1;
	c = j-1;
	d = i-1;
	e = i+2*h-1;
	f = j+2*w-1;
	S1=(((a<0)|(b<0))?0:arr[a][b])-(((a<0)|(c<0))?0:arr[a][c])-(((d<0)|(b<0))?0:arr[d][b])+(((d<0)|(c<0))?0:arr[d][c]);
	S2=(((e<0)|(b<0))?0:arr[e][b])-(((e<0)|(c<0))?0:arr[e][c])-(((a<0)|(b<0))?0:arr[a][b])+(((a<0)|(c<0))?0:arr[a][c]);
	S3=(((a<0)|(f<0))?0:arr[a][f])-(((a<0)|(b<0))?0:arr[a][b])-(((d<0)|(f<0))?0:arr[d][f])+(((d<0)|(b<0))?0:arr[d][b]);
	S4=(((e<0)|(f<0))?0:arr[e][f])-(((e<0)|(b<0))?0:arr[e][b])-(((a<0)|(f<0))?0:arr[a][f])+(((a<0)|(b<0))?0:arr[a][b]);
	
    return ((S1-S2-S3+S4)*n)/(4*w*h);
    }
  return 0;
}
Пример #18
0
void Envelope::testMe()
{
   double t0=0, t1=0;

   SetInterpolateDB(false);
   Mirror(false);

   SetDefaultValue(0.5);
   Flatten(0.5);
   checkResult( 1, Integral(0.0,100.0), 50);
   checkResult( 2, Integral(-10.0,10.0), 10);

   SetDefaultValue(1.0);
   Flatten(0.5);
   checkResult( 3, Integral(0.0,100.0), 50);
   checkResult( 4, Integral(-10.0,10.0), 10);
   checkResult( 5, Integral(-20.0,-10.0), 5);

   SetDefaultValue(0.5);
   Flatten(0.5);
   Insert( 5.0, 0.5 );
   checkResult( 6, Integral(0.0,100.0), 50);
   checkResult( 7, Integral(-10.0,10.0), 10);

   SetDefaultValue(0.5);
   Flatten(0.0);
   Insert( 0.0, 0.0 );
   Insert( 5.0, 1.0 );
   Insert( 10.0, 0.0 );
   t0 = 10.0 - .1;
   t1 = 10.0 + .1;
   double result = Integral(0.0,t1);
   double resulta = Integral(0.0,t0);
   double resultb = Integral(t0,t1);
   // Integrals should be additive
   checkResult( 8, result - resulta - resultb, 0);

   SetDefaultValue(0.5);
   Flatten(0.0);
   Insert( 0.0, 0.0 );
   Insert( 5.0, 1.0 );
   Insert( 10.0, 0.0 );
   t0 = 10.0 - .1;
   t1 = 10.0 + .1;
   checkResult( 9, Integral(0.0,t1), 5);
   checkResult( 10, Integral(0.0,t0), 4.999);
   checkResult( 11, Integral(t0,t1), .001);

   WX_CLEAR_ARRAY(mEnv);
   Insert( 0.0, 0.0 );
   Insert( 5.0, 1.0 );
   Insert( 10.0, 0.0 );
   checkResult( 12, NumberOfPointsAfter( -1 ), 3 );
   checkResult( 13, NumberOfPointsAfter( 0 ), 2 );
   checkResult( 14, NumberOfPointsAfter( 1 ), 2 );
   checkResult( 15, NumberOfPointsAfter( 5 ), 1 );
   checkResult( 16, NumberOfPointsAfter( 7 ), 1 );
   checkResult( 17, NumberOfPointsAfter( 10 ), 0 );
   checkResult( 18, NextPointAfter( 0 ), 5 );
   checkResult( 19, NextPointAfter( 5 ), 10 );
}
Пример #19
0
// This one scales the y-axis before integrating.
// To re-scale [0,1] to [minY,maxY] we use the mapping y -> minY + (maxY - minY)y
// So we want to find the integral of (minY + (maxY - minY)f(t)), where f is our envelope.
// But that's just (t1 - t0)minY + (maxY - minY)Integral( t0, t1 ).
double Envelope::Integral( double t0, double t1, double minY, double maxY )
{
   return ((t1 - t0) * minY) + ((maxY - minY) * Integral( t0, t1 ));
}
Пример #20
0
void
Triangle_Processor::Process( Stack<AtomicRegion>&  Offspring)
  {
  TimesCalled ++;
  if (TimesCalled == 1)
    {
    TheRule->Apply(LocalIntegrand(),Geometry(),Integral(),AbsoluteError());
    Offspring.MakeEmpty();
    return;
    };
  if(TimesCalled == 2)
    {
    real NewVolume
          = Geometry().Volume()/2;
    Stack<Triangle> Parts;
    Vector<unsigned int> DiffOrder(Diffs.Size());
    const real difffac = real(1)/real(0.45);    
    const real difftreshold = 1e-3;

    TheRule->ComputeDiffs(LocalIntegrand(),Geometry(),Diffs); 

    // Sort the differences in descending order.
    for (unsigned int ik=0 ; ik<=2 ; ik++)  { DiffOrder[ik] = ik; }
    for (unsigned int i=0 ; i<=1 ; i++)  
      {
     for (unsigned int k=i+1 ; k<=2 ; k++)
         if (Diffs[DiffOrder[k]]>Diffs[DiffOrder[i]])
            {
            unsigned int h = DiffOrder[i];
            DiffOrder[i] = DiffOrder[k];
            DiffOrder[k] = h;
            }
      }

    if (Diffs[DiffOrder[0]] < difftreshold)
      {
      TheDivisor4->Apply(Geometry(),Parts,DiffOrder);
      NewVolume /=2;
      }
    else 
      {
      if (Diffs[DiffOrder[0]]>difffac*Diffs[DiffOrder[2]])
        {
        TheDivisor2->Apply (Geometry(),Parts,DiffOrder);
        }
      else 
        { 
        TheDivisor4->Apply(Geometry(),Parts,DiffOrder);
        NewVolume /=2;
        }	
      };

    unsigned int N = Parts.Size();
    for (unsigned int ii =0;ii<N;ii++)
      {
      Triangle* g = Parts.Pop();
      g->Volume(NewVolume);
      Processor<Triangle>* p = Descendant();
      Atomic<Triangle>* a = new Atomic<Triangle>(g,p);
      a->LocalIntegrand(&LocalIntegrand());
      Offspring.Push(a);
      };
    return;
    };
   Error(TimesCalled > 2,
     "Triangle_Processor : more than two calls of Process()");
   }
int main(int argc, char** argv)
{
  try
  {
    int nx = 32;
    double convTol = 1.0e-8;
    double lambda = 0.5;
    Sundance::setOption("nx", nx, "Number of elements");
    Sundance::setOption("tol", convTol, "Convergence tolerance");
    Sundance::setOption("lambda", lambda, "Lambda (parameter in Bratu's equation)");

    Sundance::init(&argc, &argv);

    Out::root() << "Bratu problem (lambda=" << lambda << ")" << endl;
    Out::root() << "Newton's method, linearized by hand" << endl << endl;

    VectorType<double> vecType = new EpetraVectorType();

    MeshType meshType = new BasicSimplicialMeshType();
    MeshSource mesher = new PartitionedLineMesher(0.0, 1.0, nx, meshType);
    Mesh mesh = mesher.getMesh();

    CellFilter interior = new MaximalCellFilter();
    CellFilter sides = new DimensionalCellFilter(mesh.spatialDim()-1);
    CellFilter left = sides.subset(new CoordinateValueCellPredicate(0, 0.0));
    CellFilter right = sides.subset(new CoordinateValueCellPredicate(0, 1.0));
    
    BasisFamily basis = new Lagrange(1);
    Expr w = new UnknownFunction(basis, "w");
    Expr v = new TestFunction(basis, "v");

    Expr grad = gradient(1);

    Expr x = new CoordExpr(0);



    const double pi = 4.0*atan(1.0);
    Expr uExact = sin(pi*x);
    Expr R = pi*pi*uExact - lambda*exp(uExact);

    QuadratureFamily quad4 = new GaussianQuadrature(4);
    QuadratureFamily quad2 = new GaussianQuadrature(2);

    DiscreteSpace discSpace(mesh, basis, vecType);
    Expr uPrev = new DiscreteFunction(discSpace, 0.5);
    Expr stepVal = copyDiscreteFunction(uPrev);

    Expr eqn 
      = Integral(interior, (grad*v)*(grad*w) + (grad*v)*(grad*uPrev) 
        - v*lambda*exp(uPrev)*(1.0+w) - v*R, quad4);

    Expr h = new CellDiameterExpr();
    Expr bc = EssentialBC(left+right, v*(uPrev+w)/h, quad2); 

    LinearProblem prob(mesh, eqn, bc, v, w, vecType);

    LinearSolver<double> linSolver 
      = LinearSolverBuilder::createSolver("amesos.xml");

    Out::root() << "Newton iteration" << endl;
    int maxIters = 20;
    Expr soln ;
    bool converged = false;

    for (int i=0; i<maxIters; i++)
    {
      /* solve for the next u */
      prob.solve(linSolver, stepVal);
      Vector<double> stepVec = getDiscreteFunctionVector(stepVal);
      double deltaU = stepVec.norm2();
      Out::root() << "Iter=" << setw(3) << i << " ||Delta u||=" << setw(20)
                  << deltaU << endl;
      addVecToDiscreteFunction(uPrev, stepVec);
      if (deltaU < convTol) 
      {
        soln = uPrev;
        converged = true;
        break;
      }
    } 
    TEUCHOS_TEST_FOR_EXCEPTION(!converged, std::runtime_error, 
      "Newton iteration did not converge after " 
      << maxIters << " iterations");
    
    FieldWriter writer = new DSVWriter("HandCodedBratu.dat");
    writer.addMesh(mesh);
    writer.addField("soln", new ExprFieldWrapper(soln[0]));
    writer.write();

    Out::root() << "Converged!" << endl << endl;

    double L2Err = L2Norm(mesh, interior, soln-uExact, quad4);
    Out::root() << "L2 Norm of error: " << L2Err << endl;
    
    Sundance::passFailTest(L2Err, 1.5/((double) nx*nx));
  }
	catch(std::exception& e) 
  {
    Sundance::handleException(e);
  }
  Sundance::finalize(); 
}
Пример #22
0
bool CNBugTest()
{
  /* We will do our linear algebra using Epetra */
  VectorType<double> vecType = new EpetraVectorType();

  MeshType meshType = new BasicSimplicialMeshType();
  int nx = 1;

  MeshSource mesher = new PartitionedLineMesher(0.0, 1.0, nx, meshType);
  Mesh mesh = mesher.getMesh();

  /* Create a cell filter that will identify the maximal cells
   * in the interior of the domain */
  CellFilter interior = new MaximalCellFilter(); 

  /* Create unknown function */
  BasisFamily L1=new Lagrange(1);
  Expr u = new UnknownFunction(L1, "u");
  Expr w = new TestFunction(L1, "w");

  Expr dx = new Derivative(0);
      
  Expr x = new CoordExpr(0);

  /* We need a quadrature rule for doing the integrations */
  QuadratureFamily quad = new GaussianQuadrature(4);

  DiscreteSpace discSpaceL1(mesh, L1, vecType);
  Expr ud = x; //proj.project();
    
  WatchFlag watch("watch");
  watch.setParam("evaluation", 5);
  watch.setParam("evaluator setup", 5);
  watch.setParam("discrete function evaluation", 1);
  watch.setParam("integration setup", 0);
  watch.setParam("symbolic preprocessing", 3);
  watch.setParam("integration", 0);

  Expr eqn1 = Integral(interior, w*(dx*(u+ud)), quad, watch);
  Expr eqn2 = Integral(interior, w*(dx*u)+w*(dx*ud), 
    quad, watch);
  Expr bc;

  Out::root() << " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n" 
              << " @@@@@@@@@@@@@@@ creating BAD operator @@@@@@@@@@@@@\n" 
              << " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n" 
              << endl;
    
  LinearProblem prob1(mesh, eqn1, bc, w, u, vecType);
  LinearOperator<double> A1 = prob1.getOperator();

    
  Out::root() << "BAD operator = " << endl << A1 << endl << endl << endl;


  Out::root() << " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n" 
              << " @@@@@@@@@@@@@@@ creating GOOD operator @@@@@@@@@@@@\n" 
              << " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n"
              << endl;
  LinearProblem prob2(mesh, eqn2, bc, w, u, vecType);
  LinearOperator<double> A2 = prob2.getOperator();
  Out::root() << "GOOD operator = " << endl << A2 << endl;

  Vector<double> b = A2.domain().createMember();
  b.randomize();

  Vector<double> r = A2*b - A1*b;

  Out::root() << "difference in operator application = " 
              << r.norm2() << endl;
    
  double tol = 1000.0;
  return SundanceGlobal::checkTest(r.norm2(), tol);

}
void FaceMasker::Run(int min_depth, int min_pixels, int open_size,
                     int head_width, int head_height, int head_depth,
                     int face_size, int extended_size,
                     int window_size, int width, int height,
                     float focal_length, const Depth *depth,
                     Color *color) {
  width_ = width;
  height_ = height;
  window_size_ = window_size;

  if (size_ < (width_ * height_)) {
    size_ = width_ * height_;

    if (valid_mask_ != NULL)
      delete [] valid_mask_;
    if (head_mask_ != NULL)
      delete [] head_mask_;
    if (depth_integral_ != NULL)
      delete [] depth_integral_;
    if (valid_integral_ != NULL)
      delete [] valid_integral_;
    if (head_integral_ != NULL)
      delete [] head_integral_;
    if (min_sizes_ != NULL)
      delete [] min_sizes_;
    if (max_sizes_ != NULL)
      delete [] max_sizes_;

    valid_mask_ = new bool[size_];
    head_mask_ = new bool[size_];
    depth_integral_ = new int[size_];
    valid_integral_ = new int[size_];
    head_integral_ = new int[size_];
    min_sizes_ = new float[size_];
    max_sizes_ = new float[size_];
  }

  int max_depth = (head_width * focal_length) / min_pixels;

  #pragma omp parallel for
  for (int i = 0; i < (width * height); i++) {
    valid_mask_[i] = ((depth[i] > min_depth) && (depth[i] < max_depth)) ?
                     true : false;
  }

  Integral(width, height, true, valid_mask_, valid_integral_);
  Integral(width, height, valid_mask_, depth, depth_integral_);

  #pragma omp parallel for
  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      int i = x + y * width;

      head_mask_[i] = false;
      if (valid_mask_[i]) {
        int head_cols = (int)((head_width * focal_length) / depth[i]);
        int head_rows = (int)((head_height * focal_length) / depth[i]);

        int center_average = Mean(width, height,
            x - head_cols / 2, x + head_cols / 2,
            y - head_rows / 2, y + head_rows / 2,
            depth_integral_, valid_integral_);

        int left_average = Mean(width, height,
            x - (5 * head_cols / 4), x - (3 * head_cols / 4),
            y - head_rows / 2, y + head_rows / 2,
            depth_integral_, valid_integral_);

        int right_average = Mean(width, height,
            x + (3 * head_cols / 4), x + (5 * head_cols / 4),
            y - head_rows / 2, y + head_rows / 2,
            depth_integral_, valid_integral_);

        int top_average = Mean(width, height,
            x - head_cols / 2, x + head_cols / 2,
            y - (5 * head_rows / 4), y - (3 * head_rows / 4),
            depth_integral_, valid_integral_);

        int top_left_average = Mean(width, height,
            x - (5 * head_cols / 4), x - (3 * head_cols / 4),
            y - (5 * head_rows / 4), y - (3 * head_rows / 4),
            depth_integral_, valid_integral_);

        int top_right_average = Mean(width, height,
            x + (3 * head_cols / 4), x + (5 * head_cols / 4),
            y - (5 * head_rows / 4), y - (3 * head_rows / 4),
            depth_integral_, valid_integral_);

        int center_difference = ABS(depth[i] - center_average);
        int left_difference = ABS(depth[i] - left_average);
        int right_difference = ABS(depth[i] - right_average);
        int top_difference = ABS(depth[i] - top_average);
        int top_left_difference = ABS(depth[i] - top_left_average);
        int top_right_difference = ABS(depth[i] - top_right_average);

        int alpha = head_depth;
        int beta = 2 * head_depth;
        head_mask_[i] = ((center_difference < alpha) &&
                         (left_difference > beta) &&
                         (right_difference > beta) &&
                         (top_difference > beta) &&
                         (top_left_difference > beta) &&
                         (top_right_difference > beta)) ? true : false;
      }
    }
  }

  Integral(width, height, false, head_mask_, head_integral_);
  Erode(width, height, open_size, head_integral_, head_mask_);
  Integral(width, height, true, head_mask_, head_integral_);
  Dilate(width, height, open_size, head_integral_, head_mask_);

  Integral(width, height, true, head_mask_, head_integral_);

  #pragma omp parallel for
  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      int i = x + y * width;

      min_sizes_[i] = max_sizes_[i] = 0.0f;
      if (valid_mask_[i]) {
        int face_pixels = (int)((face_size * focal_length) / depth[i]);

        if (Sum(width, height, x - face_pixels / 2, x + face_pixels / 2,
                y - face_pixels / 2, y + face_pixels / 2, head_integral_) > 0) {
          int extended_pixels =(int)((extended_size * focal_length) / depth[i]);

          min_sizes_[i] = face_pixels - extended_pixels;
          max_sizes_[i] = face_pixels + extended_pixels;
        }
      }
    }
  }

  frame_++;
  scale_ = 0;

//#define HEAD_DEBUG
#ifdef HEAD_DEBUG
  Mat image(height_, width_, CV_8UC3, color);
  Mat head_region = Mat::zeros(height_, width_, CV_8UC3);

  #pragma omp parallel for
  for (int y = 0; y < height_; y++) {
    for (int x = 0; x < width_; x++) {
      int i = x + y * width_;

      if (head_mask_[i])
        head_region.at<Vec3b>(y, x) = Vec3b(255, 255, 255);
    }
  }

  char filename[256];
  sprintf(filename, "head-%d.png", frame_);

  Mat output;
  addWeighted(image, 0.5, head_region, 0.5, 0.0, output);

  imwrite(filename, output);
  scale_++;
#endif
}
Пример #24
0
int main(int argc, char** argv)
{
  try
		{
			Sundance::init(&argc, &argv);
      int np = MPIComm::world().getNProc();
      
      int nx = 64;
      const double pi = 4.0*atan(1.0);
      MeshType meshType = new BasicSimplicialMeshType();
      MeshSource mesher = new PartitionedLineMesher(0.0, pi, nx, meshType);

      Mesh mesh = mesher.getMesh();
      CellFilter interior = new MaximalCellFilter();
      CellFilter bdry = new BoundaryCellFilter();
      
      /* Create a vector space factory, used to 
       * specify the low-level linear algebra representation */
      VectorType<double> vecType = new EpetraVectorType();

      /* create symbolic coordinate functions */
      Expr x = new CoordExpr(0);

      /* create target function */
      double R = 0.01;
      Expr sx = sin(x);
      Expr cx = cos(x);
      Expr ssx = sin(sx);
      Expr sx2 = sx*sx;
      Expr cx2 = cx*cx;
      Expr f = sx2 - sx - ssx;
      Expr uStar = 2.0*R*(sx2-cx2) + R*sx2*ssx + sx;

      /* Form exact solution */
      Expr uEx = sx;
      Expr lambdaEx = R*sx2;
      Expr alphaEx = -lambdaEx/R;
      

      /* create a discrete space on the mesh */
      BasisFamily bas = new Lagrange(1);
      DiscreteSpace discreteSpace(mesh, bas, vecType);

      /* initialize the design, state, and multiplier vectors to constants */
      Expr alpha0 = new DiscreteFunction(discreteSpace, 0.25, "alpha0");
      Expr u0 = new DiscreteFunction(discreteSpace, 0.5, "u0");
      Expr lambda0 = new DiscreteFunction(discreteSpace, 0.25, "lambda0");

      /* create symbolic objects for test and unknown functions */
      Expr u = new UnknownFunction(bas, "u");
      Expr lambda = new UnknownFunction(bas, "lambda");
      Expr alpha = new UnknownFunction(bas, "alpha");

      /* create symbolic differential operators */
      Expr dx = new Derivative(0);
      Expr grad = dx;

      /* create quadrature rules of different orders */
      QuadratureFamily q1 = new GaussianQuadrature(1);
      QuadratureFamily q2 = new GaussianQuadrature(2);
      QuadratureFamily q4 = new GaussianQuadrature(4);

      /* Form objective function */
      Expr reg = Integral(interior, 0.5 * R * alpha*alpha, q2);
      Expr fit = Integral(interior, 0.5 * pow(u-uStar, 2.0), q4);

      Expr constraintEqn = Integral(interior, 
        (grad*lambda)*(grad*u) + lambda*(alpha + sin(u) + f), q4);
      Expr L = reg + fit + constraintEqn;

      Expr constraintBC = EssentialBC(bdry, lambda*u, q2);

      Functional Lagrangian(mesh, L, constraintBC, vecType);
      
      LinearSolver<double> adjSolver 
        = LinearSolverBuilder::createSolver("amesos.xml");
      ParameterXMLFileReader reader("nox-amesos.xml");
      ParameterList noxParams = reader.getParameters();
      NOXSolver nonlinSolver(noxParams);

      RCP<PDEConstrainedObjBase> obj = rcp(new NonlinearPDEConstrainedObj(
        Lagrangian, u, u0, lambda, lambda0, alpha, alpha0,
        nonlinSolver, adjSolver));

      Vector<double> xInit = obj->getInit();

      bool doFDCheck = true;
      if (doFDCheck)
      {
        Out::root() << "Doing FD check of gradient..." << endl;
        bool fdOK = obj->fdCheck(xInit, 1.0e-6, 0);
        if (fdOK) 
        {
          Out::root() << "FD check OK" << endl;
        }
        else
        {
          Out::root() << "FD check FAILED" << endl;
          TEUCHOS_TEST_FOR_EXCEPT(!fdOK);
        }
      }

      RCP<UnconstrainedOptimizerBase> opt 
          = OptBuilder::createOptimizer("basicLMBFGS.xml");
      opt->setVerb(3);

      OptState state = opt->run(obj, xInit);

      if (state.status() != Opt_Converged)
      {
        Out::root()<< "optimization failed: " << state.status() << endl;
        TEUCHOS_TEST_FOR_EXCEPT(state.status() != Opt_Converged);
      }
      else
      {
        Out::root() << "opt converged: " << state.iter() << " iterations"
                    << endl;
      }
      FieldWriter w = new MatlabWriter("NonlinControl1D");
      w.addMesh(mesh);
      w.addField("u", new ExprFieldWrapper(u0));
      w.addField("alpha", new ExprFieldWrapper(alpha0));
      w.addField("lambda", new ExprFieldWrapper(lambda0));
      w.write();

      double uErr = L2Norm(mesh, interior, u0-uEx, q4);
      double lamErr = L2Norm(mesh, interior, lambda0-lambdaEx, q4);
      double aErr = L2Norm(mesh, interior, alpha0-alphaEx, q4);
      Out::root() << "error in u = " << uErr << endl;
      Out::root() << "error in lambda = " << lamErr << endl;
      Out::root() << "error in alpha = " << aErr << endl;

      double tol = 0.05;
      Sundance::passFailTest(uErr + lamErr + aErr, tol);
    }
	catch(exception& e)
		{
      cerr << "main() caught exception: " << e.what() << endl;
		}
	Sundance::finalize();
  return Sundance::testStatus(); 
}
Пример #25
0
int main(int argc, char** argv)
{
  try
  {
    const double pi = 4.0*atan(1.0);
    double lambda = 1.25*pi*pi;

    int nx = 32;
    int nt = 10;
    double tFinal = 1.0/lambda;

    Sundance::setOption("nx", nx, "Number of elements");
    Sundance::setOption("nt", nt, "Number of timesteps");
    Sundance::setOption("tFinal", tFinal, "Final time");
    
    Sundance::init(&argc, &argv);

    /* Creation of vector type */
    VectorType<double> vecType = new EpetraVectorType();

    /* Set up mesh */
    MeshType meshType = new BasicSimplicialMeshType();
      
    MeshSource meshSrc = new PartitionedRectangleMesher(
      0.0, 1.0, nx,
      0.0, 1.0, nx,
      meshType);
    Mesh mesh = meshSrc.getMesh();

    /* 
     * Specification of cell filters
     */
    CellFilter interior = new MaximalCellFilter();
    CellFilter edges = new DimensionalCellFilter(1);
    CellFilter west = edges.coordSubset(0, 0.0);
    CellFilter east = edges.coordSubset(0, 1.0);
    CellFilter south = edges.coordSubset(1, 0.0);
    CellFilter north = edges.coordSubset(1, 1.0);

    /* set up test and unknown functions */
    BasisFamily basis = new Lagrange(1);
    Expr u = new UnknownFunction(basis, "u");
    Expr v = new TestFunction(basis, "v");

    /* set up differential operators */
    Expr grad = gradient(2);

    Expr x = new CoordExpr(0);
    Expr y = new CoordExpr(1);

    Expr t = new Sundance::Parameter(0.0);
    Expr tPrev = new Sundance::Parameter(0.0);


    DiscreteSpace discSpace(mesh, basis, vecType);
    Expr uExact = cos(0.5*pi*y)*sin(pi*x)*exp(-lambda*t);
    L2Projector proj(discSpace, uExact);
    Expr uPrev = proj.project();


    /* 
     * We need a quadrature rule for doing the integrations 
     */
    QuadratureFamily quad = new GaussianQuadrature(2);

    double deltaT = tFinal/nt;

    Expr gWest = -pi*exp(-lambda*t)*cos(0.5*pi*y);
    Expr gWestPrev = -pi*exp(-lambda*tPrev)*cos(0.5*pi*y);
    
    /* Create the weak form */
    Expr eqn = Integral(interior, v*(u-uPrev)/deltaT
      + 0.5*(grad*v)*(grad*u + grad*uPrev), quad)
      + Integral(west, -0.5*v*(gWest+gWestPrev), quad);

    Expr bc = EssentialBC(east + north, v*u, quad);

    
    LinearProblem prob(mesh, eqn, bc, v, u, vecType);

    
    LinearSolver<double> solver 
      = LinearSolverBuilder::createSolver("amesos.xml");

    FieldWriter w0 = new VTKWriter("TransientHeat2D-0");
    w0.addMesh(mesh);
    w0.addField("T", new ExprFieldWrapper(uPrev[0]));
    w0.write();

    for (int i=0; i<nt; i++)
    {
      t.setParameterValue((i+1)*deltaT);
      tPrev.setParameterValue(i*deltaT);
      Out::root() << "t=" << (i+1)*deltaT << endl;
      Expr uNext = prob.solve(solver);
      
      ostringstream oss;
      oss << "TransientHeat2D-" << i+1;
      FieldWriter w = new VTKWriter(oss.str());
      w.addMesh(mesh);
      w.addField("T", new ExprFieldWrapper(uNext[0]));
      w.write();

      updateDiscreteFunction(uNext, uPrev);
    }


    
    double err = L2Norm(mesh, interior, uExact-uPrev, quad);
    Out::root() << "error norm=" << err << endl;

    double h = 1.0/(nx-1.0);
    double tol = 0.1*(pow(h,2.0) + pow(lambda*deltaT, 2.0));
    Out::root() << "tol=" << tol << endl;
    
    
    Sundance::passFailTest(err, tol);
  }
	catch(std::exception& e) 
  {
    Sundance::handleException(e);
  }
  Sundance::finalize(); 
  return Sundance::testStatus();
}
Пример #26
0
int main(int argc, char** argv)
{
  try
		{
      Sundance::init(&argc, &argv);
      int np = MPIComm::world().getNProc();

      /* We will do our linear algebra using Epetra */
      VectorType<double> vecType = new EpetraVectorType();

      /* Create a mesh. It will be of type BasisSimplicialMesh, and will
       * be built using a PartitionedLineMesher. */
      MeshType meshType = new BasicSimplicialMeshType();
      MeshSource mesher = new PartitionedLineMesher(0.0, 1.0, 1*np, meshType);
      Mesh mesh = mesher.getMesh();

      /* Create a cell filter that will identify the maximal cells
       * in the interior of the domain */
      CellFilter interior = new MaximalCellFilter();

      /* Create the Spectral Basis */
      int ndim = 1;
      int order = 2;
      SpectralBasis sbasis = new HermiteSpectralBasis(ndim, order); 
      
      /* Create unknown and test functions, discretized using first-order
       * Lagrange interpolants */
      Expr u = new UnknownFunction(new Lagrange(1), sbasis, "u");
      Expr v = new TestFunction(new Lagrange(1), sbasis, "v");

      /* Create the stochastic input function. */
      Expr a0 = new Sundance::Parameter(1.0);
      Expr a1 = new Sundance::Parameter(0.1);
      Expr a2 = new Sundance::Parameter(0.01);
      Expr alpha = new SpectralExpr(sbasis, tuple(a0, a1, a2));

      /* Create a discrete space, and discretize the function 1.0 on it */
      cout << "forming discrete space" << std::endl;
      DiscreteSpace discSpace(mesh, new Lagrange(1), sbasis, vecType);
      cout << "forming discrete func" << std::endl;
      Expr u0 = new DiscreteFunction(discSpace, 0.5, "u0");

      /* We need a quadrature rule for doing the integrations */
      QuadratureFamily quad = new GaussianQuadrature(2);

      /* Now we set up the weak form of our equation. */
      Expr eqn = Integral(interior, v*(u*u-alpha), quad);

      cout << "equation = " << eqn << std::endl;

      /* There are no boundary conditions for this problem, so the
       * BC expression is empty */
      Expr bc;

      /* We can now set up the nonlinear problem! */

      NonlinearProblem prob(mesh, eqn, bc, v, u, u0, vecType);



#ifdef HAVE_CONFIG_H
      ParameterXMLFileReader reader(searchForFile("SolverParameters/nox.xml"));
#else
      ParameterXMLFileReader reader("nox.xml");
#endif
      ParameterList noxParams = reader.getParameters();

      std::cerr << "solver params = " << noxParams << std::endl;

      NOXSolver solver(noxParams);

      prob.solve(solver);

      /* Inspect solution values. The solution is constant in space,
       * so we can simply take the first NTerms entries in the vector */
      Vector<double> vec = DiscreteFunction::discFunc(u0)->getVector();

      int k=0;
      for (SequentialIterator<double> i=vec.space().begin(); i!=vec.space().end(); i++, k++)
        {
          cout << "u[" << k << "] = " << vec[i] << std::endl;
        }

      double tol = 1.0e-12;
      double errorSq = 0.0;
      Sundance::passFailTest(errorSq, tol);
    }
	catch(std::exception& e)
		{
      std::cerr << e.what() << std::endl;
		}
  Sundance::finalize(); return Sundance::testStatus(); 
}
Пример #27
0
int main(int argc, char** argv)
{
  try
		{
			Sundance::init(&argc, &argv);
      int np = MPIComm::world().getNProc();
      
      int nx = 48;
      int ny = 48;
      int npx = -1;
      int npy = -1;
      PartitionedRectangleMesher::balanceXY(np, &npx, &npy);
      TEUCHOS_TEST_FOR_EXCEPT(npx < 1);
      TEUCHOS_TEST_FOR_EXCEPT(npy < 1);
      TEUCHOS_TEST_FOR_EXCEPT(npx * npy != np);
      MeshType meshType = new BasicSimplicialMeshType();
      MeshSource mesher = new PartitionedRectangleMesher(0.0, 1.0, nx, npx, 
        0.0,  1.0, ny, npy, meshType);

      Mesh mesh = mesher.getMesh();
      CellFilter interior = new MaximalCellFilter();
      CellFilter bdry = new BoundaryCellFilter();
      
      /* Create a vector space factory, used to 
       * specify the low-level linear algebra representation */
      VectorType<double> vecType = new EpetraVectorType();
  
      /* create a discrete space on the mesh */
      DiscreteSpace discreteSpace(mesh, new Lagrange(1), vecType);

      /* initialize the design, state, and multiplier vectors */
      Expr alpha0 = new DiscreteFunction(discreteSpace, 1.0, "alpha0");
      Expr u0 = new DiscreteFunction(discreteSpace, 1.0, "u0");
      Expr lambda0 = new DiscreteFunction(discreteSpace, 1.0, "lambda0");

      /* create symbolic objects for test and unknown functions */
      Expr u = new UnknownFunction(new Lagrange(1), "u");
      Expr lambda = new UnknownFunction(new Lagrange(1), "lambda");
      Expr alpha = new UnknownFunction(new Lagrange(1), "alpha");

      /* create symbolic differential operators */
      Expr dx = new Derivative(0);
      Expr dy = new Derivative(1);
      Expr grad = List(dx, dy);

      /* create symbolic coordinate functions */
      Expr x = new CoordExpr(0);
      Expr y = new CoordExpr(1);

      /* create target function */
      const double pi = 4.0*atan(1.0);
      Expr uStar = sin(pi*x)*sin(pi*y);
      
      /* create quadrature rules of different orders */
      QuadratureFamily q1 = new GaussianQuadrature(1);
      QuadratureFamily q2 = new GaussianQuadrature(2);
      QuadratureFamily q4 = new GaussianQuadrature(4);

      /* Regularization weight */
      double R = 0.001;
      double U0 = 1.0/(1.0 + 4.0*pow(pi,4.0)*R);
      double A0 = -2.0*pi*pi*U0;

      /* Form objective function */
      Expr reg = Integral(interior, 0.5 * R * alpha*alpha, q2);
      Expr fit = Integral(interior, 0.5 * pow(u-uStar, 2.0), q4);

      Expr constraintEqn = Integral(interior, 
        (grad*lambda)*(grad*u) + lambda*alpha, q2);
      Expr L = reg + fit + constraintEqn;

      Expr constraintBC = EssentialBC(bdry, lambda*u, q2);
      Functional Lagrangian(mesh, L, constraintBC, vecType);
      
      LinearSolver<double> solver 
        = LinearSolverBuilder::createSolver("amesos.xml");

      RCP<ObjectiveBase> obj = rcp(new LinearPDEConstrainedObj(
        Lagrangian, u, u0, lambda, lambda0, alpha, alpha0,
        solver));

      Vector<double> xInit = obj->getInit();

      bool doFDCheck = false;
      if (doFDCheck)
      {
        Out::root() << "Doing FD check of gradient..." << endl;
        bool fdOK = obj->fdCheck(xInit, 1.0e-6, 2);
        if (fdOK) 
        {
          Out::root() << "FD check OK" << endl;
        }
        else
        {
          Out::root() << "FD check FAILED" << endl;
        }
      }

      RCP<UnconstrainedOptimizerBase> opt 
          = OptBuilder::createOptimizer("basicLMBFGS.xml");
      opt->setVerb(2);

      OptState state = opt->run(obj, xInit);

      bool ok = true;
      if (state.status() != Opt_Converged)
      {
        Out::root()<< "optimization failed: " << state.status() << endl;
        TEUCHOS_TEST_FOR_EXCEPT(state.status() != Opt_Converged);
      }

      Out::root() << "opt converged: " << state.iter() << " iterations"
                  << endl;
      Out::root() << "exact solution: U0=" << U0 << " A0=" << A0 << endl;
      FieldWriter w = new VTKWriter("PoissonSourceInversion");
      w.addMesh(mesh);
      w.addField("u", new ExprFieldWrapper(u0));
      w.addField("alpha", new ExprFieldWrapper(alpha0));
      w.addField("lambda", new ExprFieldWrapper(lambda0));
      w.write();
      
      
      double uErr = L2Norm(mesh, interior, u0-U0*uStar, q4);
      double aErr = L2Norm(mesh, interior, alpha0-A0*uStar, q4);
      Out::root() << "error in u = " << uErr << endl;
      Out::root() << "error in alpha = " << aErr << endl;

      double tol = 0.01;
      Sundance::passFailTest(uErr + aErr, tol);
    }
	catch(std::exception& e)
		{
      cerr << "main() caught exception: " << e.what() << endl;
		}
	Sundance::finalize();
  return Sundance::testStatus(); 
}
Пример #28
0
int main(int argc, char** argv)
{
  
  try
		{
      Sundance::init(&argc, &argv);
      int np = MPIComm::world().getNProc();

      //  DOFMapBase::classVerbosity() = VerbExtreme;

      const double density = 1000.0; // kg/m^3
      const double porosity = 0.442; // dimensionless %
      const double A = 175.5; // dimensionless fit parameter
      const double B = 1.83;  // dimensionless fit parameter
      const double criticalRe = 36.73;  // dimensionless fit parameter
      const double dynvisc = 1.31;  // kg/(m-s)
      const double graindia = 1.9996e-4;  // m 
      const double charvel = 1.0;  // m/s

      
      double Reynolds = density*graindia*charvel/(dynvisc*porosity);

      Expr Re = new Parameter(Reynolds);

      /* We will do our linear algebra using Epetra */
      VectorType<double> vecType = new EpetraVectorType();

      /* Create a mesh. It will be of type BasisSimplicialMesh, and will
       * be built using a PartitionedLineMesher. */
      MeshType meshType = new BasicSimplicialMeshType();
      MeshSource mesher = new PartitionedLineMesher(0.0, 1000.0, 100*np, meshType);
      Mesh mesh = mesher.getMesh();

      /* Create a cell filter that will identify the maximal cells
       * in the interior of the domain */
      CellFilter interior = new MaximalCellFilter();
      CellFilter points = new DimensionalCellFilter(0);
      CellPredicate leftPointFunc = new PositionalCellPredicate(leftPointTest);
      CellPredicate rightPointFunc = new PositionalCellPredicate(rightPointTest);
      CellFilter leftPoint = points.subset(leftPointFunc);
      CellFilter rightPoint = points.subset(rightPointFunc);
      
      /* Create unknown and test functions, discretized using first-order
       * Lagrange interpolants */
      
      Expr p = new UnknownFunction(new Lagrange(2), "p");
      Expr q = new UnknownFunction(new Lagrange(2), "q");
 
      Expr u = new TestFunction(new Lagrange(2), "u");
      Expr v = new TestFunction(new Lagrange(2), "v");

      /* Create differential operator and coordinate function */
      Expr dx = new Derivative(0);
      Expr x = new CoordExpr(0);

      /* We need a quadrature rule for doing the integrations */
      QuadratureFamily quad = new GaussianQuadrature(4);

      /* Define the weak form */
      Expr MassEqn = Integral(interior, q*(dx*u), quad)
	+ Integral(leftPoint, - q*u,quad)
	+ Integral(rightPoint,  - q*u,quad);
      Expr MomEqn = Integral(interior, (density/porosity)*q*q*(dx*v) + porosity*p*(dx*v) - porosity*q*v*A - (porosity*q*v*B*Re*Re)/((Re+criticalRe)*(1-porosity)), quad)
	+ Integral(leftPoint, - density*q*q*v/porosity - porosity*p*v,quad)
	+ Integral(rightPoint,- density*q*q*v/porosity - porosity*p*v,quad);

      /* Define the Dirichlet BC */
      Expr leftbc = EssentialBC(leftPoint, v*(q-charvel), quad);
      Expr rightbc = EssentialBC(rightPoint, v*(q-charvel), quad);

      /* Create a discrete space, and discretize the function 1.0 on it */
      BasisFamily L2 = new Lagrange(2);
      Array<BasisFamily> basis = tuple(L2, L2);
      DiscreteSpace discSpace(mesh, basis, vecType);
      Expr u0 = new DiscreteFunction(discSpace, 1.0, "u0");
      Expr p0 = u0[0];
      Expr q0 = u0[1];
     
 
/* Create a TSF NonlinearOperator object */
      std::cerr << "about to make nonlinear object" << std::endl;
      std::cerr.flush();

      NonlinearOperator<double> F 
        = new NonlinearProblem(mesh, MassEqn+MomEqn, leftbc+rightbc, Sundance::List(u,v),Sundance::List(p,q) , u0, vecType);
    
      //      F.verbosity() = VerbExtreme;
      /* Get the initial guess */
  
      Vector<double> x0 = F.getInitialGuess();
   
      
      /* Create an Aztec solver for solving the linear subproblems */
      std::map<int,int> azOptions;
      std::map<int,double> azParams;
      
      azOptions[AZ_solver] = AZ_gmres;
      azOptions[AZ_precond] = AZ_dom_decomp;
      azOptions[AZ_subdomain_solve] = AZ_ilu;
      azOptions[AZ_graph_fill] = 1;
      azOptions[AZ_max_iter] = 1000;
      azParams[AZ_tol] = 1.0e-13;
      
      LinearSolver<double> linSolver = new AztecSolver(azOptions,azParams);

      /* Now let's create a NOX solver */

      NOX::TSF::Group grp(x0, F, linSolver);

      grp.verbosity() = VerbExtreme;

      // Set up the status tests
      NOX::StatusTest::NormF statusTestA(grp, 1.0e-10);
      NOX::StatusTest::MaxIters statusTestB(20);
      NOX::StatusTest::Combo statusTestsCombo(NOX::StatusTest::Combo::OR, statusTestA, statusTestB);

      // Create the list of solver parameters
      NOX::Parameter::List solverParameters;

      // Set the solver (this is the default)
      solverParameters.setParameter("Nonlinear Solver", "Line Search Based");

      // Create the line search parameters sublist
      NOX::Parameter::List& lineSearchParameters = solverParameters.sublist("Line Search");

      // Set the line search method
      lineSearchParameters.setParameter("Method","More'-Thuente");

      // Create the solver
      NOX::Solver::Manager solver(grp, statusTestsCombo, solverParameters);

      // Solve the nonlinear system
      NOX::StatusTest::StatusType status = solver.solve();

      // Print the answer
      cout << "\n" << "-- Parameter List From Solver --" << "\n";
      solver.getParameterList().print(cout);

      // Get the answer
      grp = solver.getSolutionGroup();

      // Print the answer
      cout << "\n" << "-- Final Solution From Solver --" << "\n";
      grp.print();

      

      double tol = 1.0e-12;
      Sundance::passFailTest(0, tol);

    }
	catch(std::exception& e)
		{
      Sundance::handleException(e);
		}
  Sundance::finalize(); return Sundance::testStatus(); 
}
Пример #29
0
double Parameters::Mean(double time1, double time2) const
{
   double total = Integral(time1,time2);
   return total/(time2-time1);
}
Пример #30
0
void detectAndDisplay(IplImage *frame)
{
    IplImage *frame_gray;
    int ForCount1, ForCount2;
    ForCount1 = ForCount2 = 0;

    memset(pointXY, 0, sizeof(char)*column*row);

    frame_gray = cvCreateImage( cvGetSize(frame),IPL_DEPTH_8U,1);
    //frame_gray = cvCreateImage( cvSize(column, row),IPL_DEPTH_8U,1);
    dst = cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U,1);
    //dst = cvCreateImage(cvSize(column,row),IPL_DEPTH_8U,1);
   
#ifdef showXY
    showSumX = cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U,1);
    showSumY = cvCreateImage(cvSize(row,column),IPL_DEPTH_8U,1);
#endif

    cvCvtColor(frame, frame_gray, CV_BGR2GRAY);
    //cvCanny(frame_gray, dst, 40, 40*3, 3);
    cvThreshold(frame_gray, dst, Threshold, 255, CV_THRESH_BINARY);
 
    for(ForCount1 = 0; ForCount1 < column; ForCount1++)
    {
        for(ForCount2 = 0; ForCount2 < row; ForCount2++)
        {
            CvScalar s = cvGet2D(dst,ForCount2,ForCount1); 
            //char s = ((uchar *)(dst->imageData + ForCount1*dst->widthStep))[ForCount2];
#ifdef Detail
            printf("%3d %3d %f\n",ForCount1,ForCount2, s.val[0]);
#endif
            /*if( s.val[0] <= Threshold)
            {
                pointXY[ForCount1][ForCount2] = 1; 
            }*/
            if(s.val[0] <= Threshold)
            {
                pointXY[ForCount1][ForCount2] = 0;
            }
            else
            {
                pointXY[ForCount1][ForCount2] = 1;
            }
        }
    }

    Integral(row);
    Integral(column);
    Error1();
    Error2();

    cvShowImage("Webcam",dst);
    cvShowImage("Webcam1",frame_gray);

#ifdef Detail
    for(ForCount1 = 0; ForCount1 < column; ForCount1++)
    {
        printf("x[%3d]:%d\n", ForCount1, SumX[ForCount1]);
    }
    printf("\n");
    for(ForCount1 = 0; ForCount1 < row; ForCount1++)
    {
        printf("y[%3d]:%d\n", ForCount1, SumY[ForCount1]);
    }
    printf("\n");
#endif

#ifdef showXY
    for(ForCount1 = 0; ForCount1 < column; ForCount1++)
    {
        for(ForCount2 = 0; ForCount2 < (int)SumX[ForCount1]; ForCount2++)
        {
            CvScalar s = cvGet2D(showSumX,ForCount2,ForCount1); 
            s.val[0] = 255;
            cvSet2D(showSumX, ForCount2, ForCount1, s);
        }
    }
    cvShowImage("SumX", showSumX);

    for(ForCount1 = 0; ForCount1 < row; ForCount1++)
    {
        for(ForCount2 = 0; ForCount2 < (int)SumY[ForCount1]; ForCount2++)
        {
            CvScalar s = cvGet2D(showSumY,ForCount2,ForCount1); 
            s.val[0] = 255;
            cvSet2D(showSumY, ForCount2, ForCount1, s);
   
        }
    }

#endif

    //cvShowImage("SumY", showSumY);
    cvReleaseImage( &dst );
    cvReleaseImage( &frame_gray );
#ifdef showXY
    cvReleaseImage( &showSumX );
    cvReleaseImage( &showSumY );
#endif
}