Beispiel #1
0
/* The function returns the stability measure B1 vector of the given
   S-parameter matrix vector. */
vector b1 (matvec m) {
  assert (m.getCols () >= 2 && m.getRows () >= 2);
  vector res (m.getSize ());
  for (int i = 0; i < m.getSize (); i++) res.set (b1 (m.get (i)), i);
  return res;
}
int test_main(int, char* [])
{
    typedef bg::model::d2::point_xy<boost::long_long_type> point;
    typedef bg::model::segment<point> segment;

    typedef bg::strategy::side::side_of_intersection side;

    point no_fb(-99, -99);

    segment a(point(20, 10), point(10, 20));

    segment b1(point(11, 16), point(20, 14));  // IP with a: (14.857, 15.143)
    segment b2(point(10, 16), point(20, 14));  // IP with a: (15, 15)

    segment c1(point(15, 16), point(13, 8));
    segment c2(point(15, 16), point(14, 8));
    segment c3(point(15, 16), point(15, 8));


    BOOST_CHECK_EQUAL( 1, side::apply(a, b1, c1, no_fb));
    BOOST_CHECK_EQUAL(-1, side::apply(a, b1, c2, no_fb));
    BOOST_CHECK_EQUAL(-1, side::apply(a, b1, c3, no_fb));

    BOOST_CHECK_EQUAL( 1, side::apply(a, b2, c1, no_fb));
    BOOST_CHECK_EQUAL( 1, side::apply(a, b2, c2, no_fb));
    BOOST_CHECK_EQUAL( 0, side::apply(a, b2, c3, no_fb));

    // Collinear cases
    // 1: segments intersecting are collinear (with a fallback point):
    {
        point fb(5, 5);
        segment col1(point(0, 5), point(5, 5));
        segment col2(point(5, 5), point(10, 5)); // One IP with col1 at (5,5)
        segment col3(point(5, 0), point(5, 5));
        BOOST_CHECK_EQUAL( 0, side::apply(col1, col2, col3, fb));
    }
    // 2: segment of side calculation collinear with one of the segments
    {
        point fb(5, 5);
        segment col1(point(0, 5), point(10, 5));
        segment col2(point(5, 5), point(5, 12)); // IP with col1 at (5,5)
        segment col3(point(5, 1), point(5, 5)); // collinear with col2
        BOOST_CHECK_EQUAL( 0, side::apply(col1, col2, col3, fb));
    }
    {
        point fb(5, 5);
        segment col1(point(10, 5), point(0, 5));
        segment col2(point(5, 5), point(5, 12)); // IP with col1 at (5,5)
        segment col3(point(5, 1), point(5, 5)); // collinear with col2
        BOOST_CHECK_EQUAL( 0, side::apply(col1, col2, col3, fb));
    }
    {
        point fb(5, 5);
        segment col1(point(0, 5), point(10, 5));
        segment col2(point(5, 12), point(5, 5)); // IP with col1 at (5,5)
        segment col3(point(5, 1), point(5, 5)); // collinear with col2
        BOOST_CHECK_EQUAL( 0, side::apply(col1, col2, col3, fb));
    }

    {
        point fb(517248, -517236);
        segment col1(point(-172408, -517236), point(862076, -517236));
        segment col2(point(517248, -862064), point(517248, -172408));
        segment col3(point(517248, -172408), point(517248, -517236));
        BOOST_CHECK_EQUAL( 0, side::apply(col1, col2, col3, fb));
    }
    {
        point fb(-221647, -830336);
        segment col1(point(-153817, -837972), point(-222457, -830244));
        segment col2(point(-221139, -833615), point(-290654, -384388));
        segment col3(point(-255266, -814663), point(-264389, -811197));
        BOOST_CHECK_EQUAL(1, side::apply(col1, col2, col3, fb)); // Left of segment...
    }


    {
        point fb(27671131, 30809240);
        segment col1(point(27671116, 30809247), point(27675474, 30807351));
        segment col2(point(27666779, 30811130), point(27671139, 30809237));
        segment col3(point(27671122, 30809244), point(27675480, 30807348));
        BOOST_CHECK_EQUAL(1, side::apply(col1, col2, col3, fb)); // Left of segment...
    }

    // TODO: we might add a check calculating the IP, determining the side
    // with the normal side strategy, and verify the results are equal

    return 0;
}
Beispiel #3
0
/**
 *  generateBezier :
 *  Use least-squares method to find Bezier control points for region.
 *
 */
QPointF* generateBezier(QPolygonF &points, int first, int last, double *uPrime,FitVector tHat1,FitVector tHat2)
{
    int i;
    FitVector A[MAXPOINTS][2];    /* Precomputed rhs for eqn    */
    int nPts;            /* Number of pts in sub-curve */
    double C[2][2];            /* Matrix C        */
    double X[2];            /* Matrix X            */
    double det_C0_C1,        /* Determinants of matrices    */
    det_C0_X,
    det_X_C1;
    double alpha_l = 0,        /* Alpha values, left and right    */
    alpha_r = 0;
    FitVector tmp;            /* Utility variable        */
    QPointF *curve;
    
    curve = new QPointF[4];
    nPts = last - first + 1;
 
    /* Compute the A's    */
    for (i = 0; i < nPts; i++) {
         FitVector v1, v2;
         v1 = tHat1;
         v2 = tHat2;
         v1.scale(b1(uPrime[i]));
         v2.scale(b2(uPrime[i]));
         A[i][0] = v1;
         A[i][1] = v2;
    }

    /* Create the C and X matrices    */
    C[0][0] = 0.0;
    C[0][1] = 0.0;
    C[1][0] = 0.0;
    C[1][1] = 0.0;
    X[0]    = 0.0;
    X[1]    = 0.0;

    for (i = 0; i < nPts; i++) {
         C[0][0] += (A[i][0]).dot(A[i][0]);
         C[0][1] += A[i][0].dot(A[i][1]);
         C[1][0] = C[0][1];
         C[1][1] += A[i][1].dot(A[i][1]);

         FitVector vfirstp1(points[first+i]);
         FitVector vfirst(points[first]);
         FitVector vlast(points[last]);

         tmp = vectorSub(vfirstp1,
               vectorAdd(vectorScale(vfirst, b0(uPrime[i])),
               vectorAdd(vectorScale(vfirst, b1(uPrime[i])),
               vectorAdd(vectorScale(vlast, b2(uPrime[i])),
               vectorScale(vlast, b3(uPrime[i])) ))));
    
         X[0] += A[i][0].dot(tmp);
         X[1] += A[i][1].dot(tmp);
    }

    /* Compute the determinants of C and X    */
    det_C0_C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1];
    det_C0_X  = C[0][0] * X[1]    - C[0][1] * X[0];
    det_X_C1  = X[0]    * C[1][1] - X[1]    * C[0][1];

    /* Finally, derive alpha values    */
    if (det_C0_C1 == 0.0)
        det_C0_C1 = (C[0][0] * C[1][1]) * 10e-12;
    
    if (det_C0_C1 != 0.0f) {
        alpha_l = det_X_C1 / det_C0_C1;
        alpha_r = det_C0_X / det_C0_C1;
    }
    // FIXME: else???
    
    /*  If alpha negative, use the Wu/Barsky heuristic (see text) */
    /* (if alpha is 0, you get coincident control points that lead to
    * divide by zero in any subsequent newtonRaphsonRootFind() call. */
    if (alpha_l < 1.0e-6 || alpha_r < 1.0e-6) {
        double    dist = distance(points[last], points[first]) / 3.0;
        curve[0] = points[first];
        curve[3] = points[last];

        tHat1.scale(dist);
        tHat2.scale(dist);

        curve[1] = tHat1 + curve[0];
        curve[2] = tHat2 + curve[3];

        return curve;
    }

    /*  First and last control points of the Bezier curve are */
    /*  positioned exactly at the first and last data points */
    /*  Control points 1 and 2 are positioned an alpha distance out */
    /*  on the tangent vectors, left and right, respectively */
    curve[0] = points[first];
    curve[3] = points[last];

    tHat1.scale(alpha_l);
    tHat2.scale(alpha_r);

    curve[1] = tHat1 + curve[0];
    curve[2] = tHat2 + curve[3];
    
    return (curve);
}
float fi(int k){
  return(atan(b1(k)/a1(k)));}
Beispiel #5
0
TEST(BubblePlopping, FromNone)
{
  bbs::Bubble b1(1, 1, bbs::colors_t::NONE);
  b1.plopp();
  EXPECT_EQ(b1.getStatus(), bbs::colors_t::NONE);
}
Beispiel #6
0
int
BeamContact2D::update(void)
// this function updates variables for an incremental step n to n+1
{
    double tensileStrength;
	Vector a1(BC2D_NUM_DIM);
    Vector b1(BC2D_NUM_DIM);
	Vector a1_n(BC2D_NUM_DIM);
    Vector b1_n(BC2D_NUM_DIM);
    Vector disp_a(3);
    Vector disp_b(3);
    Vector disp_L(BC2D_NUM_DIM);
    double rot_a;
    double rot_b;
    Vector x_c(BC2D_NUM_DIM);

	// update slave node coordinates
	mDcrd_s = mIcrd_s + theNodes[2]->getTrialDisp();

	// update Lagrange multiplier value
	disp_L  = theNodes[3]->getTrialDisp();
	mLambda = disp_L(0);

	// update nodal coordinates
	disp_a = theNodes[0]->getTrialDisp();
	disp_b = theNodes[1]->getTrialDisp();

	for (int i = 0; i < 2; i++) {
	    mDcrd_a(i) = mIcrd_a(i) + disp_a(i);
		mDcrd_b(i) = mIcrd_b(i) + disp_b(i);
	}

	// compute incremental rotation from step n to step n+1
	rot_a = disp_a(2) - mDisp_a_n(2);
	rot_b = disp_b(2) - mDisp_b_n(2);

	// get tangent vectors from last converged step
	a1_n = Geta1();
	b1_n = Getb1();

	// linear update of tangent vectors
	a1 = a1_n + rot_a*mEyeS*a1_n;
	b1 = b1_n + rot_b*mEyeS*b1_n;

	// update centerline projection coordinate
	x_c = mDcrd_a*mShape(0) + a1*mLength*mShape(1) + mDcrd_b*mShape(2) + b1*mLength*mShape(3);

	// update gap
	mGap = (mNormal^(mDcrd_s - x_c)) - mRadius;

	// get tensile strength from contact material
	tensileStrength = theMaterial->getTensileStrength();

	// set the boolean release condition
	should_be_released = (mLambda <= -mForceTol);

    // determine trial strain vector based on contact state
	if (inContact) {
	    Vector strain(3);
		double slip;
		Vector c1n1(2);
		Vector c2n1(2);

        // tangent at the centerline projection in step n+1
		c1n1 = mDshape(0)*mDcrd_a + mDshape(1)*mLength*ma_1 + mDshape(2)*mDcrd_b + mDshape(3)*mLength*mb_1;

		// update vector c2 for step n+1
		c2n1 = (mDcrd_s - x_c)/((mDcrd_s - x_c).Norm());
		
		// update vector c2 for step n+1
		c2n1(0) = -c1n1(1);
		c2n1(1) = c1n1(0);

		// compute the slip
		slip = mg_xi^(mDcrd_s - x_c - mrho*c2n1);

		// set the strain vector
		strain(0) = mGap;
		strain(1) = slip;
		strain(2) = mLambda;
		
		theMaterial->setTrialStrain(strain);
	}
	
	else if (to_be_released) {
	    Vector strain(3);

        // set the strain vector
		strain(0) = mGap;
		strain(1) = 0.0;
		strain(2) = mLambda;
		
		theMaterial->setTrialStrain(strain);
	}

	return 0;
}
Beispiel #7
0
void CLightD::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) 
{
	// TODO: Add your message handler code here and/or call default
//	GetDlgItem(
	UpdateData(TRUE);
	m_ssr.Format("%f",(float)m_sr/255);
	m_ssg.Format("%f",(float)m_sg/255);

	CDC* hdc=m_sl.GetWindowDC();
	CRect rect;
	m_sl.GetClientRect(&rect);
	CBrush b(RGB(m_sr,m_sr,m_sr));
	CBrush* ob=hdc->SelectObject(&b);
	hdc->Rectangle(&rect);
	hdc->SelectObject(ob);
	ReleaseDC(hdc);

	m_sar.Format("%d",m_ar);
	m_sag.Format("%d",m_ag);
	m_sab.Format("%d",m_ab);

	m_sdr.Format("%d",m_dr);
	m_sdg.Format("%d",m_dg);
	m_sdb.Format("%d",m_db);

	hdc=m_al.GetWindowDC();
	m_al.GetClientRect(&rect);
	CBrush b1(RGB(m_ar,m_ag,m_ab));
	ob=hdc->SelectObject(&b1);
	hdc->Rectangle(&rect);
	hdc->SelectObject(ob);
	ReleaseDC(hdc);

	hdc=m_dl.GetWindowDC();
	m_dl.GetClientRect(&rect);
	CBrush b2(RGB(m_dr,m_dg,m_db));
	ob=hdc->SelectObject(&b2);
	hdc->Rectangle(&rect);
	hdc->SelectObject(ob);
	ReleaseDC(hdc);
	
	
	UpdateData(FALSE);

	void* param[3];
	float spec[3];
	spec[0]=(m_sr>0)?(float)m_sr/255:m_sr;
	spec[1]=(m_sg>0)?(float)m_sg/255:m_sg;

	float amb[3];
	amb[0]=(m_ar>0)?(float)m_ar/255:m_ar;
	amb[1]=(m_ag>0)?(float)m_ag/255:m_ag;
	amb[2]=(m_ab>0)?(float)m_ab/255:m_ab;

	float diff[3];
	diff[0]=(m_dr>0)?(float)m_dr/255:m_dr;
	diff[1]=(m_dg>0)?(float)m_dg/255:m_dg;
	diff[2]=(m_db>0)?(float)m_db/255:m_db;

	float pos[3];
	pos[0]=m_x;
	pos[1]=m_y;
	pos[2]=m_z;

	param[0]=spec;
	param[1]=amb;
	param[2]=diff;
	param[3]=pos;

	for(vector<CObserver*>::iterator it=observers.begin();it!=observers.end();it++)
	{
		(*it)->SendNotify("Light",param);
	}
	CCadView* v=(CCadView*)view;
	v->change=true;
	v->Invalidate();

	CDialog::OnHScroll(nSBCode, nPos, pScrollBar);
}
Beispiel #8
0
void sLinsysRootAug::solveReduced( sData *prob, SimpleVector& b)
{
  assert(locmz==0||gOuterSolve<3);

  int myRank; MPI_Comm_rank(mpiComm, &myRank);

#ifdef TIMING
  t_start=MPI_Wtime();
  troot_total=tchild_total=tcomm_total=0.0; 
#endif

  assert(locnx+locmy+locmz==b.length());
  SimpleVector& r = (*redRhs);
  assert(r.length() <= b.length());
  SparseGenMatrix& C = prob->getLocalD();

  ///////////////////////////////////////////////////////////////////////
  // LOCAL SOLVE
  ///////////////////////////////////////////////////////////////////////
 
  ///////////////////////////////////////////////////////////////////////
  // b=[b1;b2;b3] is a locnx+locmy+locmz vector 
  // the new rhs should be 
  //           r = [b1-C^T*(zDiag)^{-1}*b3; b2]
  ///////////////////////////////////////////////////////////////////////

  r.copyFromArray(b.elements()); //will copy only as many elems as r has

  // aliases to parts (no mem allocations)
  SimpleVector r3(&r[locnx+locmy], locmz); //r3 is used as a temp
                                           //buffer for b3
  SimpleVector r2(&r[locnx],       locmy);
  SimpleVector r1(&r[0],           locnx);

  ///////////////////////////////////////////////////////////////////////
  // compute r1 = b1 - C^T*(zDiag)^{-1}*b3
  ///////////////////////////////////////////////////////////////////////
  if(locmz>0) {
    assert(r3.length() == zDiag->length());
    r3.componentDiv(*zDiag);//r3 is a copy of b3
    C.transMult(1.0, r1, -1.0, r3);
  }
  ///////////////////////////////////////////////////////////////////////
  // r contains all the stuff -> solve for it
  ///////////////////////////////////////////////////////////////////////

  if(gInnerSCsolve==0) {
    // Option 1. - solve with the factors
    solver->Dsolve(r);
  } else if(gInnerSCsolve==1) {
    // Option 2 - solve with the factors and perform iter. ref.
    solveWithIterRef(prob, r);
  } else {
    assert(gInnerSCsolve==2);
    // Option 3 - use the factors as preconditioner and apply BiCGStab
    solveWithBiCGStab(prob, r);
  }
  ///////////////////////////////////////////////////////////////////////
  // r is the sln to the reduced system
  // the sln to the aug system should be 
  //      x = [r1; r2;  (zDiag)^{-1} * (b3-C*r1);
  ///////////////////////////////////////////////////////////////////////
  SimpleVector b1(&b[0],           locnx);
  SimpleVector b2(&b[locnx],       locmy);
  SimpleVector b3(&b[locnx+locmy], locmz);
  b1.copyFrom(r1);
  b2.copyFrom(r2);

  if(locmz>0) {
    C.mult(1.0, b3, -1.0, r1);
    b3.componentDiv(*zDiag);
  }
#ifdef TIMING
  if(myRank==0 && gInnerSCsolve>=1)
    cout << "Root - Refin times: child=" << tchild_total << " root=" << troot_total
	 << " comm=" << tcomm_total << " total=" << MPI_Wtime()-t_start << endl;
#endif
}
/**********************************
 *  Run Trinomial American option  *
 **********************************/
int main(int argc, char* argv[])
{
    // parameters
    double T = 1;
    double K = 40;
    double S = 41;
    double r = 0.03;
    double q = 0.01;
    double vol = 0.3;
    bool isAmerican = true;
    int N=8;

    // print precision
    int p=9;

    PutPayoff vanillaPut(K);
    TrinomialTree b1(vanillaPut, T, S, r, q, vol);
    double bsPrice = 3.970043924;
    double bsDelta = -0.388620465;
    double bsGamma = 0.032101174;
    double bsTheta = -1.990533559;

    std::cout << "Exact solution:,"
              << std::fixed
              << std::setprecision(p)
              << "," << bsPrice
              << "," << bsDelta
              << "," << bsGamma
              << "," << bsTheta
              << std::endl;

    int n=10;
    for (int k=0; k<N; k++) {
        std::cout << n << std::fixed << std::setprecision(p);
        OptionValue v = b1.evaluate(n,isAmerican);
        std::cout << "," << v.price
                  << "," << std::fabs(v.price-bsPrice)
                  << "," << n*std::fabs(v.price-bsPrice)
                  << "," << n*n*std::fabs(v.price-bsPrice)
                  << "," << v.delta << "," << std::fabs(v.delta-bsDelta)
                  << "," << v.gamma << "," << std::fabs(v.gamma-bsGamma)
                  << "," << v.theta << "," << std::fabs(v.theta-bsTheta);

        // Trinomial Black-Scholes (TBS)
        OptionValue vTBS = b1.evaluateTBS(n,isAmerican);
        std::cout << "," << vTBS.price
                  << "," << std::fabs(vTBS.price-bsPrice)
                  << "," << n*std::fabs(vTBS.price-bsPrice)
                  << "," << n*n*std::fabs(vTBS.price-bsPrice)
                  << "," << vTBS.delta << "," << std::fabs(vTBS.delta-bsDelta)
                  << "," << vTBS.gamma << "," << std::fabs(vTBS.gamma-bsGamma)
                  << "," << vTBS.theta << "," << std::fabs(vTBS.theta-bsTheta);

        // Trinomial Black-Scholes
        // with Richardson extrapolation (TBSR)
        if (n/2>0) {
            OptionValue vBbsOld = b1.evaluateTBS(n/2,isAmerican);
            double vTBSR = 2*vTBS.price-vBbsOld.price;
            double tbsrDelta = 2*vTBS.delta-vBbsOld.delta;
            double tbsrGamma = 2*vTBS.gamma-vBbsOld.gamma;
            double tbsrTheta = 2*vTBS.theta-vBbsOld.theta;
            std::cout << "," << vTBSR
                      << "," << std::fabs(vTBSR-bsPrice)
                      << "," << n*std::fabs(vTBSR-bsPrice)
                      << "," << n*n*std::fabs(vTBSR-bsPrice)
                      << "," << tbsrDelta << "," << std::fabs(tbsrDelta-bsDelta)
                      << "," << tbsrGamma << "," << std::fabs(tbsrGamma-bsGamma)
                      << "," << tbsrTheta << "," << std::fabs(tbsrTheta-bsTheta);
        }

        std::cout << std::endl;

        n *= 2; // double the tree size
    }

    return 0;
}
Beispiel #10
0
void DiscreteHeat::calculateP(const DoubleVector &f, const DoubleVector &u, DoubleMatrix &psi, DoubleVector &g)
{
    C_UNUSED(f);
    C_UNUSED(g);

    double lamda = -(a*ht)/(hx*hx);
    double k = 1.0-2.0*lamda;

    psi.clear();
    psi.resize(M+1, N+1);

    DoubleVector a1(N-1);
    DoubleVector b1(N-1);
    DoubleVector c1(N-1);
    DoubleVector d1(N-1);
    DoubleVector x1(N-1);

    for (unsigned int m=0; m<=M; m++)
    {
        unsigned int j = M-m;

        if (j==M)
        {
            for (unsigned int i=1; i<=N-1; i++)
            {
                a1[i-1] = lamda;
                b1[i-1] = k;
                c1[i-1] = lamda;
                d1[i-1] = -2.0*hx*(u[i]-U[i]);
            }
            a1[0]   = 0.0;
            c1[N-2] = 0.0;
            tomasAlgorithm(a1.data(), b1.data(), c1.data(), d1.data(), x1.data(), x1.size());

            for (unsigned int i=1; i<=N-1; i++)
            {
                psi[j][i] = x1[i-1];
            }
            psi[j][0] = -lamda*psi[j][1]   -2.0*hx*0.5*(u[0]-U[0]);
            psi[j][N] = -lamda*psi[j][N-1] -2.0*hx*0.5*(u[N]-U[N]);
        }
        else if (j==0)
        {
            psi[j][0] = -lamda*psi[j][1];
            psi[j][N] = -lamda*psi[j][N-1];

            for (unsigned int i=1; i<=N-1; i++)
            {
                psi[j][i] = psi[j+1][i];
            }
        }
        else
        {
            for (unsigned int i=1; i<=N-1; i++)
            {
                a1[i-1] = lamda;
                b1[i-1] = k;
                c1[i-1] = lamda;
                d1[i-1] = +psi[j+1][i];
            }
            a1[0]   = 0.0;
            c1[N-2] = 0.0;
            tomasAlgorithm(a1.data(), b1.data(), c1.data(), d1.data(), x1.data(), x1.size());

            for (unsigned int i=1; i<=N-1; i++)
            {
                psi[j][i] = x1[i-1];
            }
            psi[j][0] = -lamda*psi[j][1];
            psi[j][N] = -lamda*psi[j][N-1];
        }
    }
    a1.clear();
    b1.clear();
    c1.clear();
    d1.clear();
    x1.clear();
}
Beispiel #11
0
typename Evaluator::EvalResult csConditionEvaluator::EvaluateInternal (
  Evaluator& eval, csConditionID condition)
{
  typedef typename Evaluator::EvalResult EvResult;
  typedef typename Evaluator::BoolType EvBool;
  typedef typename Evaluator::FloatType EvFloat;
  typedef typename Evaluator::IntType EvInt;
  EvResult result (eval.GetDefaultResult());

  CondOperation op = conditions.GetCondition (condition);

  switch (op.operation)
  {
    case opAnd:
      result = eval.LogicAnd (op.left, op.right);
      break;
    case opOr:
      result = eval.LogicOr (op.left, op.right);
      break;
    case opEqual:
      {
	if ((op.left.type == operandFloat) 
	  || (op.left.type == operandSVValueFloat)
	  || (op.left.type == operandSVValueX)
	  || (op.left.type == operandSVValueY)
	  || (op.left.type == operandSVValueZ)
	  || (op.left.type == operandSVValueW)
	  || (op.right.type == operandFloat) 
	  || (op.right.type == operandSVValueX) 
	  || (op.right.type == operandSVValueY) 
	  || (op.right.type == operandSVValueZ) 
	  || (op.right.type == operandSVValueW) 
	  || (op.right.type == operandSVValueFloat))
	{
	  EvFloat f1 (eval.Float (op.left));
	  EvFloat f2 (eval.Float (op.right));
          result = f1 == f2;
	}
	else if (OpTypesCompatible (op.left.type, operandBoolean) 
	  && OpTypesCompatible (op.right.type, operandBoolean))
	{
	  EvBool b1 (eval.Boolean (op.left));
	  EvBool b2 (eval.Boolean (op.right));
	  result = b1 == b2;
	}
	else
	{
	  EvInt i1 (eval.Int (op.left));
	  EvInt i2 (eval.Int (op.right));
	  result = i1 == i2;
	}
	break;
      }
    case opNEqual:
      {
	if ((op.left.type == operandFloat) 
	  || (op.left.type == operandSVValueFloat)
	  || (op.left.type == operandSVValueX)
	  || (op.left.type == operandSVValueY)
	  || (op.left.type == operandSVValueZ)
	  || (op.left.type == operandSVValueW)
	  || (op.right.type == operandFloat) 
	  || (op.right.type == operandSVValueX) 
	  || (op.right.type == operandSVValueY) 
	  || (op.right.type == operandSVValueZ) 
	  || (op.right.type == operandSVValueW) 
	  || (op.right.type == operandSVValueFloat))
	{
	  EvFloat f1 (eval.Float (op.left));
	  EvFloat f2 (eval.Float (op.right));
          result = f1 != f2;
	}
	else if (OpTypesCompatible (op.left.type, operandBoolean) 
	  && OpTypesCompatible (op.right.type, operandBoolean))
	{
	  EvBool b1 (eval.Boolean (op.left));
	  EvBool b2 (eval.Boolean (op.right));
	  result = b1 != b2;
	}
	else
	{
	  EvInt i1 (eval.Int (op.left));
	  EvInt i2 (eval.Int (op.right));
	  result = i1 != i2;
	}
	break;
      }
    case opLesser:
      {
	if ((op.left.type == operandFloat) 
	  || (op.left.type == operandSVValueFloat)
	  || (op.left.type == operandSVValueX)
	  || (op.left.type == operandSVValueY)
	  || (op.left.type == operandSVValueZ)
	  || (op.left.type == operandSVValueW)
	  || (op.right.type == operandFloat) 
	  || (op.right.type == operandSVValueX) 
	  || (op.right.type == operandSVValueY) 
	  || (op.right.type == operandSVValueZ) 
	  || (op.right.type == operandSVValueW) 
	  || (op.right.type == operandSVValueFloat))
	{
	  EvFloat f1 (eval.Float (op.left));
	  EvFloat f2 (eval.Float (op.right));
	  result = (f1 < f2);
	}
	else
	{
	  EvInt i1 (eval.Int (op.left));
	  EvInt i2 (eval.Int (op.right));
	  result = i1 < i2;
	}
	break;
      }
    case opLesserEq:
      {
	if ((op.left.type == operandFloat) 
	  || (op.left.type == operandSVValueFloat)
	  || (op.left.type == operandSVValueX)
	  || (op.left.type == operandSVValueY)
	  || (op.left.type == operandSVValueZ)
	  || (op.left.type == operandSVValueW)
	  || (op.right.type == operandFloat) 
	  || (op.right.type == operandSVValueX) 
	  || (op.right.type == operandSVValueY) 
	  || (op.right.type == operandSVValueZ) 
	  || (op.right.type == operandSVValueW) 
	  || (op.right.type == operandSVValueFloat))
	{
	  EvFloat f1 (eval.Float (op.left));
	  EvFloat f2 (eval.Float (op.right));
	  result = (f1 <= f2);
	}
	else
	{
	  EvInt i1 (eval.Int (op.left));
	  EvInt i2 (eval.Int (op.right));
	  result = i1 <= i2;
	}
	break;
      }
    default:
      CS_ASSERT (false);
  }

  return result;
}
Beispiel #12
0
/*
 * We try a get_configuration uscsi cmd.  If that fails, try a
 * atapi_capabilities cmd.  If both fail then this is an older CD-ROM.
 */
static int
get_cdrom_drvtype(int fd)
{
	union scsi_cdb cdb;
	struct uscsi_cmd cmd;
	uchar_t buff[SCSIBUFLEN];

	fill_general_page_cdb_g1(&cdb, SCMD_GET_CONFIGURATION, 0,
	    b0(sizeof (buff)), b1(sizeof (buff)));
	fill_command_g1(&cmd, &cdb, (caddr_t)buff, sizeof (buff));

	if (ioctl(fd, USCSICMD, &cmd) >= 0) {
	    struct get_configuration	*config;
	    struct conf_feature		*feature;
	    int				flen;

	    /* The first profile is the preferred one for the drive. */
	    config = (struct get_configuration *)buff;
	    feature = &config->feature;
	    flen = feature->len / sizeof (struct profile_list);
	    if (flen > 0) {
		int prof_num;

		prof_num = (int)convnum(feature->features.plist[0].profile, 2);

		if (dm_debug > 1) {
		    (void) fprintf(stderr, "INFO: uscsi get_configuration %d\n",
			prof_num);
		}

		switch (prof_num) {
		case PROF_MAGNETO_OPTICAL:
		    return (DM_DT_MO_ERASABLE);
		case PROF_OPTICAL_WO:
		    return (DM_DT_MO_WRITEONCE);
		case PROF_OPTICAL_ASMO:
		    return (DM_DT_AS_MO);
		case PROF_CDROM:
		    return (DM_DT_CDROM);
		case PROF_CDR:
		    return (DM_DT_CDR);
		case PROF_CDRW:
		    return (DM_DT_CDRW);
		case PROF_DVDROM:
		    return (DM_DT_DVDROM);
		case PROF_DVDRAM:
		    return (DM_DT_DVDRAM);
		case PROF_DVDRW_REST:
		    return (DM_DT_DVDRW);
		case PROF_DVDRW_SEQ:
		    return (DM_DT_DVDRW);
		case PROF_DVDRW:
		    return (DM_DT_DVDRW);
		case PROF_DDCD_ROM:
		    return (DM_DT_DDCDROM);
		case PROF_DDCD_R:
		    return (DM_DT_DDCDR);
		case PROF_DDCD_RW:
		    return (DM_DT_DDCDRW);
		}
	    }
	}

	/* see if the atapi capabilities give anything */
	return (check_atapi(fd));
}
Beispiel #13
0
    void BSplineData<Degree,Real>::setDotTables( int flags )
    {
      clearDotTables( flags );
      int size = ( functionCount*functionCount + functionCount )>>1;
      int fullSize = functionCount*functionCount;
      if( flags & VV_DOT_FLAG )
      {
        vvDotTable = new Real[size];
        memset( vvDotTable , 0 , sizeof(Real)*size );
      }
      if( flags & DV_DOT_FLAG )
      {
        dvDotTable = new Real[fullSize];
        memset( dvDotTable , 0 , sizeof(Real)*fullSize );
      }
      if( flags & DD_DOT_FLAG )
      {
        ddDotTable = new Real[size];
        memset( ddDotTable , 0 , sizeof(Real)*size );
      }
      double vvIntegrals[Degree+1][Degree+1];
      double vdIntegrals[Degree+1][Degree  ];
      double dvIntegrals[Degree  ][Degree+1];
      double ddIntegrals[Degree  ][Degree  ];
      int vvSums[Degree+1][Degree+1];
      int vdSums[Degree+1][Degree  ];
      int dvSums[Degree  ][Degree+1];
      int ddSums[Degree  ][Degree  ];
      SetBSplineElementIntegrals< Degree   , Degree   >( vvIntegrals );
      SetBSplineElementIntegrals< Degree   , Degree-1 >( vdIntegrals );
      SetBSplineElementIntegrals< Degree-1 , Degree   >( dvIntegrals );
      SetBSplineElementIntegrals< Degree-1 , Degree-1 >( ddIntegrals );

      for( int d1=0 ; d1<=depth ; d1++ )
        for( int off1=0 ; off1<(1<<d1) ; off1++ )
        {
          int ii = BinaryNode< Real >::CenterIndex( d1 , off1 );
          BSplineElements< Degree > b1( 1<<d1 , off1 , reflectBoundary ? BSplineElements<Degree>::NEUMANN   : BSplineElements< Degree>::NONE );
          BSplineElements< Degree-1 > db1;
          b1.differentiate( db1 );

          int start1 , end1;

          start1 = -1;
          for( int i=0 ; i<int(b1.size()) ; i++ ) for( int j=0 ; j<=Degree ; j++ )
          {
            if( b1[i][j] && start1==-1 ) start1 = i;
            if( b1[i][j] ) end1 = i+1;
          }
          for( int d2=d1 ; d2<=depth ; d2++ )
          {
            for( int off2=0 ; off2<(1<<d2) ; off2++ )
            {
              int start2 = off2-Degree;
              int end2   = off2+Degree+1;
              if( start2>=end1 || start1>=end2 ) continue;
              start2 = std::max< int >( start1 , start2 );
              end2   = std::min< int >(   end1 ,   end2 );
              if( d1==d2 && off2<off1 ) continue;
              int jj = BinaryNode< Real >::CenterIndex( d2 , off2 );
              BSplineElements< Degree > b2( 1<<d2 , off2 , reflectBoundary ? BSplineElements<Degree>::NEUMANN   : BSplineElements< Degree>::NONE );
              BSplineElements< Degree-1 > db2;
              b2.differentiate( db2 );

              int idx = SymmetricIndex( ii , jj );
              int idx1 = Index( ii , jj ) , idx2 = Index( jj , ii );

              memset( vvSums , 0 , sizeof( int ) * ( Degree+1 ) * ( Degree+1 ) );
              memset( vdSums , 0 , sizeof( int ) * ( Degree+1 ) * ( Degree   ) );
              memset( dvSums , 0 , sizeof( int ) * ( Degree   ) * ( Degree+1 ) );
              memset( ddSums , 0 , sizeof( int ) * ( Degree   ) * ( Degree   ) );
              for( int i=start2 ; i<end2 ; i++ )
              {
                for( int j=0 ; j<=Degree ; j++ ) for( int k=0 ; k<=Degree ; k++ ) vvSums[j][k] +=  b1[i][j] *  b2[i][k];
                for( int j=0 ; j<=Degree ; j++ ) for( int k=0 ; k< Degree ; k++ ) vdSums[j][k] +=  b1[i][j] * db2[i][k];
                for( int j=0 ; j< Degree ; j++ ) for( int k=0 ; k<=Degree ; k++ ) dvSums[j][k] += db1[i][j] *  b2[i][k];
                for( int j=0 ; j< Degree ; j++ ) for( int k=0 ; k< Degree ; k++ ) ddSums[j][k] += db1[i][j] * db2[i][k];
              }
              double vvDot = 0 , dvDot = 0 , vdDot = 0 , ddDot = 0;
              for( int j=0 ; j<=Degree ; j++ ) for( int k=0 ; k<=Degree ; k++ ) vvDot += vvIntegrals[j][k] * vvSums[j][k];
              for( int j=0 ; j<=Degree ; j++ ) for( int k=0 ; k< Degree ; k++ ) vdDot += vdIntegrals[j][k] * vdSums[j][k];
              for( int j=0 ; j< Degree ; j++ ) for( int k=0 ; k<=Degree ; k++ ) dvDot += dvIntegrals[j][k] * dvSums[j][k];
              for( int j=0 ; j< Degree ; j++ ) for( int k=0 ; k< Degree ; k++ ) ddDot += ddIntegrals[j][k] * ddSums[j][k];
              vvDot /= (1<<d2);
              ddDot *= (1<<d2);
              vvDot /= ( b1.denominator * b2.denominator );
              dvDot /= ( b1.denominator * b2.denominator );
              vdDot /= ( b1.denominator * b2.denominator );
              ddDot /= ( b1.denominator * b2.denominator );
              if( fabs(vvDot)<1e-15 ) continue;
              if( flags & VV_DOT_FLAG ) vvDotTable [idx] = Real( vvDot );
              if( useDotRatios )
              {
                if( flags & DV_DOT_FLAG ) dvDotTable[idx1] = Real( dvDot / vvDot );
                if( flags & DV_DOT_FLAG ) dvDotTable[idx2] = Real( vdDot / vvDot );
                if( flags & DD_DOT_FLAG ) ddDotTable[idx ] = Real( ddDot / vvDot );
              }
              else
              {
                if( flags & DV_DOT_FLAG ) dvDotTable[idx1] = Real( dvDot );
                if( flags & DV_DOT_FLAG ) dvDotTable[idx2] = Real( dvDot );
                if( flags & DD_DOT_FLAG ) ddDotTable[idx ] = Real( ddDot );
              }
            }
            BSplineElements< Degree > b;
            b = b1;
            b.upSample( b1 );
            b1.differentiate( db1 );
            start1 = -1;
            for( int i=0 ; i<int(b1.size()) ; i++ ) for( int j=0 ; j<=Degree ; j++ )
            {
              if( b1[i][j] && start1==-1 ) start1 = i;
              if( b1[i][j] ) end1 = i+1;
            }
          }
        }
    }
Beispiel #14
0
void DM3d::on_actionAbrir_OFF_triggered()
{
	QString s = QFileDialog::getOpenFileName(this,"Modelo 3D OFF",".off","3D (*.off)");

	if(s!=QString::null){
		QFile file(s);
		ui.widget->scale=ui.widget->scaleX=ui.widget->scaleY=ui.widget->scaleZ=1.0f;
		ui.widget->transX=ui.widget->transY=ui.widget->transZ=0.0f;
		if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
			QMessageBox::information(this,"Error...","No se puede abrir el archivo");
			return;
		}
		QString line = file.readLine();
		line=file.readLine();
		QStringList l=line.split(" ");
        ui.widget->vertex=QVector<CVector3Df>(l.at(0).toInt());
		int tri=l.at(1).toInt();
        CVector3Df b1(-10e30f,-10e30f,-10e30f);
        CVector3Df b2(10e30f,10e30f,10e30f);
        float maximo,maX=float(-0x3f3f3f3f),miX=float(0x3f3f3f3f);
        float maY=maX,miY=miX,maZ=maX,miZ=miX;
		int tVert=ui.widget->vertex.size();
		for(int i=0;i<tVert;++i){
			line=file.readLine();
			l=line.split(" ");
            float a=l.at(0).toDouble();
            float b=l.at(1).toDouble();
            float c=l.at(2).toDouble();
            maX=max(a,maX);
            maY=max(b,maY);
            maZ=max(c,maZ);
            miX=min(a,miX);
            miY=min(b,miY);
            miZ=min(c,miZ);
            ui.widget->vertex[i]=CVector3Df(a,b,c);
            b1.v[0]=max(b1.v[0],a);
            b1.v[1]=max(b1.v[1],b);
            b1.v[2]=max(b1.v[2],c);
            b2.v[0]=min(b2.v[0],a);
            b2.v[1]=min(b2.v[1],b);
            b2.v[2]=min(b2.v[2],c);
		}

        maximo=max(maX-miX,max(maY-miY,maZ-miZ));
        b1/=maximo;
        b2/=maximo;
        ui.widget->centro=CVector3Df((b1.v[0]+b2.v[0])/2.0f,(b1.v[1]+b2.v[1])/2.0f,(b1.v[2]+b2.v[2])/2.0f);
        b1-=ui.widget->centro;
        b2-=ui.widget->centro;

        for(int i=0;i<tVert;++i){
            ui.widget->vertex[i]/=maximo;
            ui.widget->vertex[i]-=ui.widget->centro;
        }

        ui.widget->centro=CVector3Df();
        ui.widget->ma=b1;
        ui.widget->me=b2;

        ui.widget->triangles.clear();
        for(int i=0;i<tri;++i){
            line=file.readLine();
            l=line.split(" ");
            QVector<int> t(0);
            for(int j=1;j<l.size();++j){
                QString temp=l.at(j);
                if(temp!="\n" && temp!="\t" && temp!="\t\n" && temp!="\0")
                    t.push_back(temp.toInt());
            }
            if(t.size()==3) {
                ui.widget->triangles.push_back(t);
            }else{
                for (int j = 0; j < t.size()-2; ++j) {
                    QVector<int> arr3;
                    arr3.push_back(t[0]);
                    arr3.push_back(t[j+1]);
                    arr3.push_back(t[j+2]);
                    ui.widget->triangles.push_back(arr3);
                }
            }
        }
        ui.widget->normals.clear();
        ui.widget->normals2.clear();
        ui.widget->normals=QVector<CVector3Df>(ui.widget->triangles.size());
        ui.widget->normals2=QVector<CVector3Df>(ui.widget->vertex.size(),CVector3Df(0.0,0.0,0.0));
        ui.widget->normalsCCW=QVector<CVector3Df>(ui.widget->triangles.size());
        ui.widget->normals2CCW=QVector<CVector3Df>(ui.widget->vertex.size(),CVector3Df(0.0,0.0,0.0));
        int tamV=ui.widget->vertex.size();
        int tamT=ui.widget->triangles.size();
        QVector<int> cont(ui.widget->vertex.size(),0);
        for(int i=0;i<tamT;++i){
            ui.widget->normals[i]=(ui.widget->vertex[ui.widget->triangles[i][1]]-ui.widget->vertex[ui.widget->triangles[i][0]])*(ui.widget->vertex[ui.widget->triangles[i][2]]-ui.widget->vertex[ui.widget->triangles[i][0]]);
            ui.widget->normals[i].Normalize();

            ui.widget->normalsCCW[i]=(ui.widget->vertex[ui.widget->triangles[i][2]]-ui.widget->vertex[ui.widget->triangles[i][0]])*(ui.widget->vertex[ui.widget->triangles[i][1]]-ui.widget->vertex[ui.widget->triangles[i][0]]);
            ui.widget->normalsCCW[i].Normalize();

            ui.widget->normals2[ui.widget->triangles[i][0]]+=ui.widget->normals[i];
            ui.widget->normals2[ui.widget->triangles[i][1]]+=ui.widget->normals[i];
            ui.widget->normals2[ui.widget->triangles[i][2]]+=ui.widget->normals[i];

            ui.widget->normals2CCW[ui.widget->triangles[i][0]]+=ui.widget->normalsCCW[i];
            ui.widget->normals2CCW[ui.widget->triangles[i][1]]+=ui.widget->normalsCCW[i];
            ui.widget->normals2CCW[ui.widget->triangles[i][2]]+=ui.widget->normalsCCW[i];
            ++cont[ui.widget->triangles[i][0]];
            ++cont[ui.widget->triangles[i][1]];
            ++cont[ui.widget->triangles[i][2]];
        }
        for(int i=0;i<tamV;++i){
            ui.widget->normals2[i]/=float(cont[i]);
            ui.widget->normals2[i].Normalize();
            ui.widget->normals2CCW[i]/=float(cont[i]);
            ui.widget->normals2CCW[i].Normalize();
        }
        /*
        float sumx = 0.0f;
        float sumy = 0.0f;
        float sumz = 0.0f;
        int shared=0;
        int i, j;
        for (i=0; i<tamV; ++i)
        {
        for (j=0; j<tamT; ++j)
        {
        if (ui.widget->triangles[j][0]==i || ui.widget->triangles[j][1]==i || ui.widget->triangles[j][2]==i)
        {
        sumx += ui.widget->normals[j].x;
        sumy += ui.widget->normals[j].y;
        sumz += ui.widget->normals[j].z;
        shared ++;
        }
        }

        punto3d n2(sumx,sumy,sumz);
        n2=n2/float(shared);
        n2.normalize();
        ui.widget->normals2.push_back(n2);
        sumx=0.0;
        sumy=0.0;
        sumz=0.0;
        shared=0;
        }*/
        ui.widget->changeList();
        ui.widget->updateGL();
	}else{
		QMessageBox::information(this,"Error...","No se puede abrir el archivo");
	}
}
Beispiel #15
0
int
BeamContact2Dp::update(void)
// this function updates variables for an incremental step n to n+1
{
    double tensileStrength;
	Vector a1(BC2Dp_NUM_DIM);
    Vector b1(BC2Dp_NUM_DIM);
	Vector a1_n(BC2Dp_NUM_DIM);
    Vector b1_n(BC2Dp_NUM_DIM);
    Vector disp_a(3);
    Vector disp_b(3);
    Vector disp_L(BC2Dp_NUM_DIM);
    double rot_a;
    double rot_b;
    Vector x_c(BC2Dp_NUM_DIM);

	// update slave node coordinates
	mDcrd_s = mIcrd_s + theNodes[2]->getTrialDisp();

	// update nodal coordinates
	disp_a = theNodes[0]->getTrialDisp();
	disp_b = theNodes[1]->getTrialDisp();

	for (int i = 0; i < 2; i++) {
	    mDcrd_a(i) = mIcrd_a(i) + disp_a(i);
		mDcrd_b(i) = mIcrd_b(i) + disp_b(i);
	}

	// compute incremental rotation from step n to step n+1
	rot_a = disp_a(2) - mDisp_a_n(2);
	rot_b = disp_b(2) - mDisp_b_n(2);

	// get tangent vectors from last converged step
	a1_n = Geta1();
	b1_n = Getb1();

	// linear update of tangent vectors
	a1 = a1_n + rot_a*mEyeS*a1_n;
	b1 = b1_n + rot_b*mEyeS*b1_n;

	// update centerline projection coordinate
	x_c = mDcrd_a*mShape(0) + a1*mLength*mShape(1) + mDcrd_b*mShape(2) + b1*mLength*mShape(3);

	// update penetration function
	mGap = (mNormal^(mDcrd_s - x_c)) - mRadius;
    double tol = 0.000001*mRadius;
	if (mGap < tol && in_bounds) {
		inContact = true;
	} else {
		mGap = 0.0;
		inContact = false;
	}

	// update normal contact force
	//if (was_inContact) {
    if (inContact) {
		mLambda = mPenalty*mGap;
	} else {
		mLambda = 0.0;
	}

	// get tensile strength from contact material
	tensileStrength = theMaterial->getTensileStrength();

    // determine trial strain vector based on contact state
	if (inContact) {
	    Vector strain(3);
		double slip;
		Vector c1n1(2);
		Vector c2n1(2);

        // tangent at the centerline projection in step n+1
		c1n1 = mDshape(0)*mDcrd_a + mDshape(1)*mLength*ma_1 + mDshape(2)*mDcrd_b + mDshape(3)*mLength*mb_1;

		// update vector c2 for step n+1
		c2n1 = (mDcrd_s - x_c)/((mDcrd_s - x_c).Norm());
		
		// update vector c2 for step n+1
		c2n1(0) = -c1n1(1);
		c2n1(1) = c1n1(0);

		// compute the slip
		slip = mg_xi^(mDcrd_s - x_c - mrho*c2n1);

		// set the strain vector
		strain(0) = mGap;
		strain(1) = slip;
		strain(2) = -mLambda;
		
		theMaterial->setTrialStrain(strain);
	} else {
	    Vector strain(3);

        // set the strain vector
		strain(0) = mGap;
		strain(1) = 0.0;
		strain(2) = -mLambda;
		
		theMaterial->setTrialStrain(strain);
	}

	return 0;
}
void Foam::threePhaseInterfaceProperties::correctContactAngle
(
    surfaceVectorField::GeometricBoundaryField& nHatb
) const
{
    const volScalarField::GeometricBoundaryField& alpha1 =
        mixture_.alpha1().boundaryField();
    const volScalarField::GeometricBoundaryField& alpha2 =
        mixture_.alpha2().boundaryField();
    const volScalarField::GeometricBoundaryField& alpha3 =
        mixture_.alpha3().boundaryField();
    const volVectorField::GeometricBoundaryField& U =
        mixture_.U().boundaryField();

    const fvMesh& mesh = mixture_.U().mesh();
    const fvBoundaryMesh& boundary = mesh.boundary();

    forAll(boundary, patchi)
    {
        if (isA<alphaContactAngleFvPatchScalarField>(alpha1[patchi]))
        {
            const alphaContactAngleFvPatchScalarField& a2cap =
                refCast<const alphaContactAngleFvPatchScalarField>
                (alpha2[patchi]);

            const alphaContactAngleFvPatchScalarField& a3cap =
                refCast<const alphaContactAngleFvPatchScalarField>
                (alpha3[patchi]);

            scalarField twoPhaseAlpha2(max(a2cap, scalar(0)));
            scalarField twoPhaseAlpha3(max(a3cap, scalar(0)));

            scalarField sumTwoPhaseAlpha
            (
                twoPhaseAlpha2 + twoPhaseAlpha3 + SMALL
            );

            twoPhaseAlpha2 /= sumTwoPhaseAlpha;
            twoPhaseAlpha3 /= sumTwoPhaseAlpha;

            fvsPatchVectorField& nHatp = nHatb[patchi];

            scalarField theta
            (
                convertToRad
              * (
                   twoPhaseAlpha2*(180 - a2cap.theta(U[patchi], nHatp))
                 + twoPhaseAlpha3*(180 - a3cap.theta(U[patchi], nHatp))
                )
            );

            vectorField nf(boundary[patchi].nf());

            // Reset nHatPatch to correspond to the contact angle

            scalarField a12(nHatp & nf);

            scalarField b1(cos(theta));

            scalarField b2(nHatp.size());

            forAll(b2, facei)
            {
                b2[facei] = cos(acos(a12[facei]) - theta[facei]);
            }

            scalarField det(1.0 - a12*a12);

            scalarField a((b1 - a12*b2)/det);
            scalarField b((b2 - a12*b1)/det);

            nHatp = a*nf + b*nHatp;

            nHatp /= (mag(nHatp) + deltaN_.value());
        }
    }
Beispiel #17
0
void templatesSig(double XMIN,double XMAX,double dX,TString cutstring) {
	gROOT->ForceStyle();
	RooMsgService::instance().setSilentMode(kTRUE);
	for(int i=0;i<2;i++) RooMsgService::instance().setStreamStatus(i,kFALSE);

	const int NMASS(1);
	char name[1000];

	TFile *fVBF[NMASS];//,*fGF[NMASS];
	TH1F  *hVBF[NMASS][5],*hPassVBF;
	int H_MASS[1] = {125};
	TString SELECTION[1] = {"jetPt[0]>80 && jetPt[1]>70"};
	int NCAT[1] = {4};
	int LUMI[1] = {19281};
	int XSEC_VBF[1] = {0.911};

//	TH1F  *hGF[NMASS][5],*hVBF[NMASS][5],*hTOT[NMASS][5],*hPassGF,*hPassVBF;
	RooDataHist *RooHistFit[NMASS][5],*RooHistScaled[NMASS][5];
	RooAddPdf *model[NMASS][5];

	TCanvas *can[NMASS];
	TString PATH("rootfiles/");

	RooWorkspace *w = new RooWorkspace("w","workspace");
	int NBINS   = (XMAX-XMIN)/dX;

	RooRealVar x("mbbReg","mbbReg",XMIN,XMAX);
	RooRealVar kJES("CMS_scale_j","CMS_scale_j",1,0.9,1.1);
	RooRealVar kJER("CMS_res_j","CMS_res_j",1,0.8,1.2);
	kJES.setConstant(kTRUE);
	kJER.setConstant(kTRUE);

	TString TRIG_WT[2] = {"trigWtNOM[1]","trigWtVBF"};
	for(int iMass=0;iMass<NMASS;iMass++) {
		cout<<"Mass = "<<H_MASS[iMass]<<" GeV"<<endl;
		int counter(0);
		for(int iSEL=0;iSEL<2;iSEL++) {
//			sprintf(name,"Fit_VBFPowheg%d_sel%s.root",H_MASS[iMass],SELECTION[iSEL].Data());
			sprintf(name,"vbfHbb_uncertainties_JEx.root");
			cout << name << endl;
			fVBF[iMass]  = TFile::Open(PATH+TString(name));
//			hPassVBF = (TH1F*)fVBF[iMass]->Get("TriggerPass");

//			sprintf(name,"Fit_GFPowheg%d_sel%s.root",H_MASS[iMass],SELECTION[iSEL].Data());
//			fGF[iMass]  = TFile::Open(PATH+TString(name)); 
//			hPassGF = (TH1F*)fGF[iMass]->Get("TriggerPass");

			sprintf(name,"HMassTemplate_%d_sel%s",H_MASS[iMass],SELECTION[iSEL].Data());

			can[iMass] = new TCanvas(name,name,1200,800);
			can[iMass]->Divide(2,2);

			for(int icat=0;icat<NCAT[iSEL];icat++) { 
				sprintf(name,"Hbb%d/events",icat);
//				trVBF = (TTree*)fVBF[iMass]->Get(name);
//				trGF  = (TTree*)fGF[iMass]->Get(name);
				can[iMass]->cd(icat+1);
				sprintf(name,"mass_VBF%d_sel%s_CAT%d",H_MASS[iMass],SELECTION[iSEL].Data(),icat);
				
				hVBF[iMass][icat] = (TH1F*)fVBF[iMass]->Get("histos/VBF125/h_NOM_VBF125_Hbb_mbbReg1;1");//new TH1F(name,name,NBINS,XMIN,XMAX);
//				hVBF[iMass][icat]->Sumw2();
//				TCut cut("puWt[0]*"+TRIG_WT[iSEL]+"*(mva"+SELECTION[iSEL]+">-1)");
//				TCut cut(cutstring.Data());
//				trVBF->Draw(MASS_VAR[iSEL]+">>"+TString(name),cut);

//				sprintf(name,"mass_GF%d_sel%s_CAT%d",H_MASS[iMass],SELECTION[iSEL].Data(),icat);
//				hGF[iMass][icat] = new TH1F(name,name,NBINS,XMIN,XMAX);
//				hGF[iMass][icat]->Sumw2();
//				trGF->Draw(MASS_VAR[iSEL]+">>"+TString(name),cut);
//
		//		delete trVBF;
//				delete trGF;
				
				sprintf(name,"roohist_fit_mass%d_sel%s_CAT%d",H_MASS[iMass],SELECTION[iSEL].Data(),icat);
				RooHistFit[iMass][icat] = new RooDataHist(name,name,x,hVBF[iMass][icat]);
				
//				hGF[iMass][icat]->Scale(LUMI[iSEL]*XSEC_GF[iMass]/hPassGF->GetBinContent(1));
				hVBF[iMass][icat]->Scale(LUMI[iSEL]*XSEC_VBF[iMass]/4794398.);//hPassVBF->GetBinContent(1));

//				sprintf(name,"mass_Total%d_sel%s_CAT%d",H_MASS[iMass],SELECTION[iSEL].Data(),icat);
				hTOT[iMass][icat] = (TH1F*)hVBF[iMass][icat]->Clone(name);
//				hTOT[iMass][icat]->Add(hGF[iMass][icat]);
				
				sprintf(name,"yield_signalVBF_mass%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar *YieldVBF = new RooRealVar(name,name,hVBF[iMass][icat]->Integral());
        		
				sprintf(name,"roohist_demo_mass%d_sel%s_CAT%d",H_MASS[iMass],SELECTION[iSEL].Data(),icat);
		        RooHistScaled[iMass][icat] = new RooDataHist(name,name,x,hTOT[iMass][icat]);

      			sprintf(name,"mean_m%d_CAT%d",H_MASS[iMass],counter);
	        	RooRealVar m(name,name,125,100,150);
	        	sprintf(name,"sigma_m%d_CAT%d",H_MASS[iMass],counter);
	        	RooRealVar s(name,name,12,3,30);

				sprintf(name,"mean_shifted_m%d_CAT%d",H_MASS[iMass],counter);
				RooFormulaVar mShift(name,"@0*@1",RooArgList(m,kJES));
				sprintf(name,"sigma_shifted_m%d_CAT%d",H_MASS[iMass],counter);
				RooFormulaVar sShift(name,"@0*@1",RooArgList(s,kJER)); 
				
				sprintf(name,"alpha_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar a(name,name,1,-10,10);
				sprintf(name,"exp_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar n(name,name,1,0,100);
				
				sprintf(name,"b0_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar b0(name,name,0.5,0.,1.);
				sprintf(name,"b1_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar b1(name,name,0.5,0.,1.);
				sprintf(name,"b2_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar b2(name,name,0.5,0.,1.);
				sprintf(name,"b3_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar b3(name,name,0.5,0.,1.);
				
				sprintf(name,"signal_bkg_m%d_CAT%d",H_MASS[iMass],counter);
				RooBernstein bkg(name,name,x,RooArgSet(b0,b1,b2));
				
				sprintf(name,"fsig_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar fsig(name,name,0.7,0.,1.);
				
				sprintf(name,"signal_gauss_m%d_CAT%d",H_MASS[iMass],counter);
				RooCBShape sig(name,name,x,mShift,sShift,a,n);
				
				
				// model(x) = fsig*sig(x) + (1-fsig)*bkg(x)
				sprintf(name,"signal_model_m%d_CAT%d",H_MASS[iMass],counter);
				model[iMass][icat] = new RooAddPdf(name,name,RooArgList(sig,bkg),fsig);
				
				RooFitResult *res = model[iMass][icat]->fitTo(*RooHistFit[iMass][icat],RooFit::Save(),RooFit::SumW2Error(kFALSE),"q");
				//res->Print();
				
				RooPlot* frame = x.frame();
				RooHistScaled[iMass][icat]->plotOn(frame);
				//model[iMass][icat]->plotOn(frame,RooFit::VisualizeError(*res,1,kFALSE),RooFit::FillColor(kGray));
				//RooHist[iMass][icat]->plotOn(frame);
				model[iMass][icat]->plotOn(frame);
				double chi2 = frame->chiSquare(); 
				//model[iMass][icat]->plotOn(frame,RooFit::LineWidth(2));
				model[iMass][icat]->plotOn(frame,RooFit::Components(bkg),RooFit::LineColor(kBlue),RooFit::LineWidth(2),RooFit::LineStyle(kDashed)); 
				frame->GetXaxis()->SetNdivisions(505); 
				frame->GetXaxis()->SetTitle("M_{bb} (GeV)");
				frame->GetYaxis()->SetTitle("Events");
				frame->Draw();
//				hGF[iMass][icat]->SetFillColor(kGreen-8); 
				hVBF[iMass][icat]->SetFillColor(kRed-10); 
				THStack *hs = new THStack("hs","hs");
//				hs->Add(hGF[iMass][icat]);
				hs->Add(hVBF[iMass][icat]);
				hs->Draw("same hist");
				frame->Draw("same");
				gPad->RedrawAxis();
				
				TF1 *tmp_func = model[iMass][icat]->asTF(x,fsig,x);
				double y0 = tmp_func->GetMaximum();
				double x0 = tmp_func->GetMaximumX();
				double x1 = tmp_func->GetX(y0/2,XMIN,x0);
				double x2 = tmp_func->GetX(y0/2,x0,XMAX);
				double FWHM = x2-x1;
				//cout<<"Int = "<<tmp_func->Integral(XMIN,XMAX)<<", Yield = "<<Yield->getVal()<<", y0 = "<<y0<<", x0 = "<<x0<<", x1 = "<<x1<<", x2 = "<<x2<<", FWHM = "<<FWHM<<endl;
				//delete tmp_func;
				double y1 = dX*0.5*y0*(YieldVBF->getVal()+YieldGF->getVal())/tmp_func->Integral(XMIN,XMAX); 
				TLine *ln = new TLine(x1,y1,x2,y1);
				ln->SetLineColor(kMagenta+3);
				ln->SetLineStyle(7);
				ln->SetLineWidth(2);
				ln->Draw(); 
				
				TLegend *leg = new TLegend(0.65,0.35,0.9,0.45);  
				leg->AddEntry(hVBF[iMass][icat],"VBF","F");
//				leg->AddEntry(hGF[iMass][icat],"GF","F");
				leg->SetFillColor(0);
				leg->SetBorderSize(0);
				leg->SetTextFont(42);
				leg->SetTextSize(0.05);
				leg->Draw("same");
				
				TPaveText *pave = new TPaveText(0.65,0.55,0.9,0.92,"NDC");
				sprintf(name,"M_{H} = %d GeV",H_MASS[iMass]);
				TLegend *leg = new TLegend(0.65,0.35,0.9,0.45);  
				leg->AddEntry(hVBF[iMass][icat],"VBF","F");
//				leg->AddEntry(hGF[iMass][icat],"GF","F");
				leg->SetFillColor(0);
				leg->SetBorderSize(0);
				leg->SetTextFont(42);
				leg->SetTextSize(0.05);
				leg->Draw("same");
				
				TPaveText *pave = new TPaveText(0.65,0.55,0.9,0.92,"NDC");
				sprintf(name,"M_{H} = %d GeV",H_MASS[iMass]);
				pave->AddText(name);
				sprintf(name,"%s selection",SELECTION[iSEL].Data());
				pave->AddText(name);
				sprintf(name,"CAT%d",icat);
				pave->AddText(name);
				sprintf(name,"m = %1.1f #pm %1.1f",m.getVal(),m.getError());
				pave->AddText(name);
				sprintf(name,"#sigma = %1.1f #pm %1.1f",s.getVal(),s.getError());
				pave->AddText(name);
				sprintf(name,"FWHM = %1.2f",FWHM);
				pave->AddText(name);
				/*
				sprintf(name,"a = %1.2f #pm %1.2f",a.getVal(),a.getError());
				pave->AddText(name);
				sprintf(name,"n = %1.2f #pm %1.2f",n.getVal(),n.getError());
				pave->AddText(name);
				sprintf(name,"f = %1.2f #pm %1.2f",fsig.getVal(),fsig.getError());
				pave->AddText(name);
				*/
				pave->SetFillColor(0);
				pave->SetBorderSize(0);
				pave->SetTextFont(42);
				pave->SetTextSize(0.05);
				pave->SetTextColor(kBlue);
				pave->Draw();
				
				b0.setConstant(kTRUE);
				b1.setConstant(kTRUE);
				b2.setConstant(kTRUE);
				b3.setConstant(kTRUE);
				
				//m2.setConstant(kTRUE);
				//s2.setConstant(kTRUE); 
				m.setConstant(kTRUE);
				s.setConstant(kTRUE); 
				a.setConstant(kTRUE);
				n.setConstant(kTRUE);
				fsig.setConstant(kTRUE);
				
				w->import(*model[iMass][icat]);
				w->import(*RooHistScaled[iMass][icat]);
				w->import(*res); 
				w->import(*YieldVBF);   
				w->import(*YieldGF);  
				
				counter++;
			}// categories loop
		}// selection loop 
	}// mass loop
	w->Print();
	//x.Print();
	TString selName = "_";
	selName += XMIN;    
	selName += "-";
	selName += XMAX;
	w->writeToFile("signal_shapes_workspace"+selName+".root");
}
Beispiel #18
0
/**
 * Constructs an OverlapStatistics object.  Compares the two input cubes and
 * finds where they overlap.
 *
 * @param x The first input cube
 * @param y The second input cube
 * @param progressMsg (Default value of "Gathering Overlap Statistics") Text
 *         for indicating progress during statistic gathering
 * @param sampPercent (Default value of 100.0) Sampling percent, or the percentage
 *       of lines to consider during the statistic gathering procedure
 *
 * @throws Isis::iException::User - All images must have the same number of
 *                                  bands
 */
OverlapStatistics::OverlapStatistics(Isis::Cube &x, Isis::Cube &y,
                                     std::string progressMsg, double sampPercent) {
    // Test to ensure sampling percent in bound
    if (sampPercent <= 0.0 || sampPercent > 100.0) {
        string msg = "The sampling percent must be a decimal (0.0, 100.0]";
        throw iException::Message(iException::Programmer,msg,_FILEINFO_);
    }

    p_sampPercent = sampPercent;

    // Extract filenames and band number from cubes
    p_xFile = x.Filename();
    p_yFile = y.Filename();

    // Make sure number of bands match
    if (x.Bands() != y.Bands()) {
        string msg = "Number of bands do not match between cubes [" +
                     p_xFile.Name() + "] and [" + p_yFile.Name() + "]";
        throw iException::Message(iException::User,msg,_FILEINFO_);
    }
    p_bands = x.Bands();
    p_stats.resize(p_bands);

    //Create projection from each cube
    Projection *projX = x.Projection();
    Projection *projY = y.Projection();

    // Test to make sure projection parameters match
    if (*projX != *projY) {
        string msg = "Mapping groups do not match between cubes [" +
                     p_xFile.Name() + "] and [" + p_yFile.Name() + "]";
        throw iException::Message(iException::Programmer,msg,_FILEINFO_);
    }

    // Figure out the x/y range for both images to find the overlap
    double Xmin1 = projX->ToProjectionX(0.5);
    double Ymax1 = projX->ToProjectionY(0.5);
    double Xmax1 = projX->ToProjectionX(x.Samples()+0.5);
    double Ymin1 = projX->ToProjectionY(x.Lines()+0.5);

    double Xmin2 = projY->ToProjectionX(0.5);
    double Ymax2 = projY->ToProjectionY(0.5);
    double Xmax2 = projY->ToProjectionX(y.Samples()+0.5);
    double Ymin2 = projY->ToProjectionY(y.Lines()+0.5);

    // Find overlap
    if ((Xmin1<Xmax2) && (Xmax1>Xmin2) && (Ymin1<Ymax2) && (Ymax1>Ymin2)) {
        double minX = Xmin1 > Xmin2 ? Xmin1 : Xmin2;
        double minY = Ymin1 > Ymin2 ? Ymin1 : Ymin2;
        double maxX = Xmax1 < Xmax2 ? Xmax1 : Xmax2;
        double maxY = Ymax1 < Ymax2 ? Ymax1 : Ymax2;

        // Find Sample range of the overlap
        p_minSampX = (int)(projX->ToWorldX(minX) + 0.5);
        p_maxSampX = (int)(projX->ToWorldX(maxX) + 0.5);
        p_minSampY = (int)(projY->ToWorldX(minX) + 0.5);
        p_maxSampY = (int)(projY->ToWorldX(maxX) + 0.5);
        p_sampRange = p_maxSampX - p_minSampX + 1;

        // Test to see if there was only sub-pixel overlap
        if (p_sampRange <= 0) return;

        // Find Line range of overlap
        p_minLineX = (int)(projX->ToWorldY(maxY) + 0.5);
        p_maxLineX = (int)(projX->ToWorldY(minY) + 0.5);
        p_minLineY = (int)(projY->ToWorldY(maxY) + 0.5);
        p_maxLineY = (int)(projY->ToWorldY(minY) + 0.5);
        p_lineRange = p_maxLineX - p_minLineX + 1;

        // Print percent processed
        Progress progress;
        progress.SetText(progressMsg);

        int linc = (int)(100.0 / sampPercent + 0.5); // Calculate our line increment

        // Define the maximum number of steps to be our line range divided by the
        // line increment, but if they do not divide evenly, then because of
        // rounding, we need to do an additional step for each band
        int maxSteps = (int)(p_lineRange / linc + 0.5);

        if (p_lineRange % linc != 0) maxSteps += 1;
        maxSteps *= p_bands;


        progress.SetMaximumSteps(maxSteps);
        progress.CheckStatus();

        // Collect and store off the overlap statistics
        for (int band=1; band<=p_bands; band++) {
            Brick b1(p_sampRange,1,1,x.PixelType());
            Brick b2(p_sampRange,1,1,y.PixelType());

            int i=0;
            while (i<p_lineRange) {
                b1.SetBasePosition(p_minSampX,(i+p_minLineX),band);
                b2.SetBasePosition(p_minSampY,(i+p_minLineY),band);
                x.Read(b1);
                y.Read(b2);
                p_stats[band-1].AddData(b1.DoubleBuffer(), b2.DoubleBuffer(), p_sampRange);

                // Make sure we consider the last line
                if (i+linc > p_lineRange-1 && i != p_lineRange-1) {
                    i = p_lineRange-1;
                    progress.AddSteps(1);
                }
                else i+=linc; // Increment the current line by our incrementer

                progress.CheckStatus();
            }
        }
    }
}
Beispiel #19
0
double
BeamContact2D::Project(double xi)
// this function computes the centerline projection for the current step
{
    double xi_p;
	double H1;
	double H2;
	double H3;
	double H4;
    double dH1;
	double dH2;
	double dH3;
	double dH4;
	double R;
	double DR;
	double dxi;
	Vector a1(BC2D_NUM_DIM);
    Vector b1(BC2D_NUM_DIM);
	Vector x_c_p(BC2D_NUM_DIM);
	Vector t_c(BC2D_NUM_DIM);
	Vector ddx_c(BC2D_NUM_DIM);

	// initialize to previous projection location
	xi_p = xi;

	// update end point tangents
	UpdateEndFrames();

	// set tangent vectors
	a1 = Geta1();
	b1 = Getb1();

	// Hermitian basis functions and first derivatives
	H1 = 1.0 - 3.0*xi_p*xi_p + 2.0*xi_p*xi_p*xi_p;
	H2 = xi_p - 2.0*xi_p*xi_p + xi_p*xi_p*xi_p;
	H3 = 3.0*xi_p*xi_p - 2*xi_p*xi_p*xi_p;
	H4 = -xi_p*xi_p + xi_p*xi_p*xi_p;
	dH1 = -6.0*xi_p + 6.0*xi_p*xi_p;
	dH2 = 1.0 - 4.0*xi_p + 3.0*xi_p*xi_p;
	dH3 = 6.0*xi_p - 6.0*xi_p*xi_p;
	dH4 = -2.0*xi_p + 3.0*xi_p*xi_p;

    // compute current projection coordinate and tangent
	x_c_p = mDcrd_a*H1 + a1*mLength*H2 + mDcrd_b*H3 + b1*mLength*H4;
	t_c   = mDcrd_a*dH1 + a1*mLength*dH2 + mDcrd_b*dH3 + b1*mLength*dH4;
	
	// compute initial value of residual
	R = (mDcrd_s - x_c_p)^t_c;

	// iterate to determine new value of xi
	int Gapcount = 0;
	while (fabs(R/mLength) > mGapTol && Gapcount < 50) {
	
		// compute current curvature vector
		ddx_c = Get_dxc_xixi(xi_p);

		// increment projection location
		DR   = ((mDcrd_s - x_c_p)^ddx_c) - (t_c^t_c);
		dxi  = -R/DR;
		xi_p = xi_p + dxi;

		// Hermitian basis functions and first derivatives
	    H1 = 1.0 - 3.0*xi_p*xi_p + 2.0*xi_p*xi_p*xi_p;
    	H2 = xi_p - 2.0*xi_p*xi_p + xi_p*xi_p*xi_p;
    	H3 = 3.0*xi_p*xi_p - 2*xi_p*xi_p*xi_p;
    	H4 = -xi_p*xi_p + xi_p*xi_p*xi_p;
    	dH1 = -6.0*xi_p + 6.0*xi_p*xi_p;
    	dH2 = 1.0 - 4.0*xi_p + 3.0*xi_p*xi_p;
    	dH3 = 6.0*xi_p - 6.0*xi_p*xi_p;
    	dH4 = -2.0*xi_p + 3.0*xi_p*xi_p;

		// update projection coordinate and tangent
		x_c_p = mDcrd_a*H1 + a1*mLength*H2 + mDcrd_b*H3 + b1*mLength*H4;
	    t_c   = mDcrd_a*dH1 + a1*mLength*dH2 + mDcrd_b*dH3 + b1*mLength*dH4;

		// compute residual
    	R = (mDcrd_s - x_c_p)^t_c;

		Gapcount += 1;
	}

	// update normal vector for current projection
	mNormal = (mDcrd_s - x_c_p)/((mDcrd_s - x_c_p).Norm());

	// update Hermitian basis functions and derivatives
	mShape(0)  = H1;
	mShape(1)  = H2;
	mShape(2)  = H3;
	mShape(3)  = H4;
	mDshape(0) = dH1;
	mDshape(1) = dH2;
	mDshape(2) = dH3;
	mDshape(3) = dH4;

	return xi_p;
}
void construct_b() {
  int a;
  B b1(&a);
  B b2("%d %d", 1, 2);
}
float F(int k){
  return(sqrt(pow(a1(k),2)+pow(b1(k),2)));}
Beispiel #22
0
/**********************************
 *  On binomial American options  *
 **********************************/
int main(int argc, char* argv[])
{
    // parameters
    double T = 7.0/12.0;
    double K = 50;
    double S = 47;
    double r = 0.03;
    double q = 0.01;
    double vol = 0.25;
    PutPayoff vanillaPut(K);
    // maximum number of cases
    int N=10;
    // number steps in the first case
    int n=200;
    // do variance reduction?
    bool varReduction = true;
    // stop until convergence?
    bool stopUntilConverge = true;
    double tol=1e-4;
    // do average odd/even?
    bool doAverageOddEven=false;
    // do binomial Black-Scholes?
    bool doBBS=false;
    // do binomial Black-Scholes with Richardson?
    bool doBBSR=false;
    // have known exact solution?
    bool knowExact = false;
    double exactPrice = 0; 
    double exactDelta = 0;
    double exactGamma = 0; 
    double exactTheta = 0; 
    // print precision
    int p=9;

    BinomialTree b1(vanillaPut, T, S, r, q, vol);

    if (knowExact) {
        std::cout << "Exact solution:,"
                  << std::fixed
                  << std::setprecision(p)
                  << "," << exactPrice
                  << "," << exactDelta
                  << "," << exactGamma
                  << "," << exactTheta
                  << std::endl;
    }

    double vPrevious=0.0;
    for (int k=0; k<N; k++) {
        OptionValue v = b1.evaluate(n,true,false,varReduction);
        std::cout << n << std::fixed << std::setprecision(p);
        std::cout << "," << v.price;
        if (knowExact) {
            std::cout << "," << std::fabs(v.price-exactPrice)
                      << "," << n*std::fabs(v.price-exactPrice)
                      << "," << n*n*std::fabs(v.price-exactPrice);
        }
        std::cout << "," << v.delta;
        if (knowExact) { std::cout << "," << std::fabs(v.delta-exactDelta); } 
        std::cout << "," << v.gamma;
        if (knowExact) { std::cout << "," << std::fabs(v.gamma-exactGamma); }
        std::cout << "," << v.theta;
        if (knowExact) { std::cout << "," << std::fabs(v.theta-exactTheta); }

        // Average of odd/even
        if (doAverageOddEven) {
            OptionValue vNext = b1.evaluate(n+1,true,false,varReduction);
            double vAverage = (v.price+vNext.price)/2;
            double aveDelta = (v.delta+vNext.delta)/2;
            double aveGamma = (v.gamma+vNext.gamma)/2;
            double aveTheta = (v.theta+vNext.theta)/2;
            std::cout << "," << vAverage;
            if (knowExact) {
                std::cout << "," << std::fabs(vAverage-exactPrice)
                          << "," << n*std::fabs(vAverage-exactPrice)
                          << "," << n*n*std::fabs(vAverage-exactPrice);
            }
            std::cout << "," << aveDelta;
            if (knowExact) { std::cout << "," << std::fabs(aveDelta-exactDelta); } 
            std::cout << "," << aveGamma;
            if (knowExact) { std::cout << "," << std::fabs(aveGamma-exactGamma); }
            std::cout << "," << aveTheta;
            if (knowExact) { std::cout << "," << std::fabs(aveTheta-exactTheta); }
        }

        // Binomial Black-Scholes (BBS)
        if (doBBS) {
            OptionValue vBBS = b1.evaluate(n,true,true,varReduction);
            std::cout << "," << vBBS.price;
            if (knowExact) {
                std::cout << "," << std::fabs(vBBS.price-exactPrice)
                          << "," << n*std::fabs(vBBS.price-exactPrice)
                          << "," << n*n*std::fabs(vBBS.price-exactPrice);
            }
            std::cout << "," << vBBS.delta;
            if (knowExact) { std::cout << "," << std::fabs(vBBS.delta-exactDelta); } 
            std::cout << "," << vBBS.gamma;
            if (knowExact) { std::cout << "," << std::fabs(vBBS.gamma-exactGamma); }
            std::cout << "," << vBBS.theta;
            if (knowExact) { std::cout << "," << std::fabs(vBBS.theta-exactTheta); }

            // Binomial Black-Scholes 
            // with Richardson extrapolation (BBSR)
            if (doBBSR) {
                if (n/2>0) {
                    OptionValue vBbsOld = b1.evaluate(n/2,true,true,varReduction);
                    double vBBSR = 2*vBBS.price-vBbsOld.price;
                    double bbsrDelta = 2*vBBS.delta-vBbsOld.delta;
                    double bbsrGamma = 2*vBBS.gamma-vBbsOld.gamma;
                    double bbsrTheta = 2*vBBS.theta-vBbsOld.theta;
                    std::cout << "," << vBBSR;
                    if (knowExact) {
                        std::cout << "," << std::fabs(vBBSR-exactPrice)
                                  << "," << n*std::fabs(vBBSR-exactPrice)
                                  << "," << n*n*std::fabs(vBBSR-exactPrice);
                    }
                    std::cout << "," << bbsrDelta;
                    if (knowExact) { std::cout << "," << std::fabs(bbsrDelta-exactDelta); } 
                    std::cout << "," << bbsrGamma;
                    if (knowExact) { std::cout << "," << std::fabs(bbsrGamma-exactGamma); }
                    std::cout << "," << bbsrTheta;
                    if (knowExact) { std::cout << "," << std::fabs(bbsrTheta-exactTheta); }
                }
            }
        }

        std::cout << std::endl;

        if ( stopUntilConverge && std::fabs(v.price-vPrevious)<tol ) {
            std::cout << "|vCurent-vPrevious| = " 
                      << std::fabs(v.price-vPrevious)
                      << std::endl;
            break;
        }

        vPrevious = v.price;
        
        n *= 2; // double the tree size
    }

    return 0;
}
int main(int argc, char* argv[])
{
    // parameters
    double T = 1;
    double K = 40;
    double S = 41;
    double r = 0.03;
    double q = 0.01;
    double vol = 0.3;
    bool isAmerican = true;
    int N=101;

    // print precision
    int p=9;

    PutPayoff vanillaPut(K);
    BinomialTree b1(vanillaPut, T, S, r, q, vol);
    double vBS = b1.BlackScholesValue().price;

    // output column header
    std::cout << "N,Binomial,ABT,BBS,BBSR,Shanks";
    if (!isAmerican) {
        std::cout << ",Black-Scholes";
        std::cout << ",Binomial Error,ABT Error";
        std::cout << ",BBS Error,BBSR Error,Shanks Error";
    }
    std::cout << std::endl;

    double vOld = vanillaPut(K);
    double vOld2 = vOld;
    for (int n=1; n<=N; n++) {
        double v = b1.evaluate(n,isAmerican).price;
        // Average of odd/even
        double vAverage = (v+vOld)/2;
        // Binomial Black-Scholes (BBS)
        double vBBS = b1.evaluateBBS(n,isAmerican).price;

        // Record convergence
        std::cout << n 
                  << std::fixed
                  << std::setprecision(p)
                  << "," << v
                  << "," << vAverage
                  << "," << vBBS;

        // Binomial Black-Scholes 
        // with Richardson extrapolation (BBSR)
        double vBBSR = 0;
        if (n/2>0) {
            double vBbsOld = b1.evaluateBBS(n/2,isAmerican).price;
            vBBSR = 2*vBBS-vBbsOld;
            std::cout << "," << vBBSR;
        }

        // Shanks transformation
        double vShanks = 0;
        if (n>2) {
            vShanks = (v*vOld2-vOld*vOld)/(v-2*vOld+vOld2);
            std::cout << "," << vShanks;
        }

        // If European option, compare with Black-Scholes
        if (!isAmerican) {
            std::cout << "," << vBS
                      << "," << std::fabs(v-vBS)
                      << "," << std::fabs(vAverage-vBS)
                      << "," << std::fabs(vBBS-vBS);
            if (n/2>0) {std::cout << "," << std::fabs(vBBSR-vBS);}
            if (n>2) {std::cout << "," << std::fabs(vShanks-vBS);}
        }
        std::cout << std::endl;

        // Update old values
        vOld2 = vOld;
        vOld = v;
    }

    return 0;
}
Beispiel #24
0
void cover_sc_bit()
{
    sc_bit bdef;
    sc_bit bf(false);
    sc_bit bt(true);
    sc_bit b0(0);
    sc_bit b1(1);
    try {
	sc_bit foo(2);
    }
    catch (sc_report) {
	cout << "Caught exception for sc_bit(2)\n";
    }
    sc_bit bc0('0');
    sc_bit bc1('1');
    try {
	sc_bit foo('2');
    }
    catch (sc_report) {
	cout << "Caught exception for sc_bit('2')\n";
    }
    sc_bit blc0(sc_logic('0'));
    sc_bit blc1(sc_logic('1'));
    sc_bit blcx(sc_logic('X'));
    sc_bit bcop(bt);
    cout << bdef << bf << bt << b0 << b1 << bc0 << bc1 << blc0 << blc1
	 << blcx << bcop << endl;
    sc_bit b;
    b = bt;
    assert(b);
    b = 0;
    assert(!b);
    b = true;
    assert(b.to_bool());
    b = '0';
    assert(!b.to_bool());
    b = sc_logic('1');
    assert(b.to_char() == '1');
    b = bf;
    assert(~b);
    b |= bt;
    assert(b);
    b &= bf;
    assert(!b);
    b |= 1;
    assert(b);
    b &= 0;
    assert(!b);
    b |= '1';
    assert(b);
    b &= '0';
    assert(!b);
    b |= true;
    assert(b);
    b &= false;
    assert(!b);
    b ^= bt;
    assert(b);
    b ^= 1;
    assert(!b);
    b ^= '1';
    assert(b);
    b ^= true;
    assert(!b);

    assert(b == bf);
    assert(b == 0);
    assert(b == '0');
    assert(b == false);
    b = 1;
    assert(b == bt);
    assert(b == 1);
    assert(b == '1');
    assert(b == true);
    assert(1 == b);
    assert('1' == b);
    assert(true == b);
    assert(equal(b, bt));
    assert(equal(b, 1));
    assert(equal(b, '1'));
    assert(equal(b, true));
    assert(equal(1, b));
    assert(equal('1', b));
    assert(equal(true, b));
    b = 0;
    assert(b != bt);
    assert(b != 1);
    assert(b != '1');
    assert(b != true);
    assert(1 != b);
    assert('1' != b);
    assert(true != b);
    assert(not_equal(b, bt));
    assert(not_equal(b, 1));
    assert(not_equal(b, '1'));
    assert(not_equal(b, true));
    assert(not_equal(1, b));
    assert(not_equal('1', b));
    assert(not_equal(true, b));

    // the following assertion is incorrect, because the b_not() method
    // is destructive, i.e., it implements something like b ~= void.
    /// assert(b == b_not(b.b_not()));
    b.b_not();
    assert(b);
    sc_bit bx;
    b_not(bx, b0);
    assert(bx);
    b_not(bx, b1);
    assert(!bx);

    cout << (b0|b0) << (b0|b1) << (b1|b0) << (b1|b1) << endl;
    cout << (b0&b0) << (b0&b1) << (b1&b0) << (b1&b1) << endl;
    cout << (b0^b0) << (b0^b1) << (b1^b0) << (b1^b1) << endl;

    cout << (b0|0) << (b0|1) << (b1|0) << (b1|1) << endl;
    cout << (b0&0) << (b0&1) << (b1&0) << (b1&1) << endl;
    cout << (b0^0) << (b0^1) << (b1^0) << (b1^1) << endl;

    cout << (b0|'0') << (b0|'1') << (b1|'0') << (b1|'1') << endl;
    cout << (b0&'0') << (b0&'1') << (b1&'0') << (b1&'1') << endl;
    cout << (b0^'0') << (b0^'1') << (b1^'0') << (b1^'1') << endl;

    cout << (b0|true) << (b0|false) << (b1|true) << (b1|false) << endl;
    cout << (b0&true) << (b0&false) << (b1&true) << (b1&false) << endl;
    cout << (b0^true) << (b0^false) << (b1^true) << (b1^false) << endl;

    cout << (0|b0) << (0|b1) << (1|b0) << (1|b1) << endl;
    cout << (0&b0) << (0&b1) << (1&b0) << (1&b1) << endl;
    cout << (0^b0) << (0^b1) << (1^b0) << (1^b1) << endl;

    cout << ('0'|b0) << ('0'|b1) << ('1'|b0) << ('1'|b1) << endl;
    cout << ('0'&b0) << ('0'&b1) << ('1'&b0) << ('1'&b1) << endl;
    cout << ('0'^b0) << ('0'^b1) << ('1'^b0) << ('1'^b1) << endl;

    cout << (false|b0) << (false|b1) << (true|b0) << (true|b1) << endl;
    cout << (false&b0) << (false&b1) << (true&b0) << (true&b1) << endl;
    cout << (false^b0) << (false^b1) << (true^b0) << (true^b1) << endl;

    cout << b_or(b0,b0) << b_or(b0,b1) << b_or(b1,b0) << b_or(b1,b1) << endl;
    cout << b_and(b0,b0) << b_and(b0,b1) << b_and(b1,b0) << b_and(b1,b1)
         << endl;
    cout << b_xor(b0,b0) << b_xor(b0,b1) << b_xor(b1,b0) << b_xor(b1,b1)
         << endl;

    cout << b_or(b0,0) << b_or(b0,1) << b_or(b1,0) << b_or(b1,1) << endl;
    cout << b_and(b0,0) << b_and(b0,1) << b_and(b1,0) << b_and(b1,1) << endl;
    cout << b_xor(b0,0) << b_xor(b0,1) << b_xor(b1,0) << b_xor(b1,1) << endl;

    cout << b_or(b0,'0') << b_or(b0,'1') << b_or(b1,'0') << b_or(b1,'1')
         << endl;
    cout << b_and(b0,'0') << b_and(b0,'1') << b_and(b1,'0') << b_and(b1,'1')
         << endl;
    cout << b_xor(b0,'0') << b_xor(b0,'1') << b_xor(b1,'0') << b_xor(b1,'1')
         << endl;

    cout << b_or(b0,false) << b_or(b0,true) << b_or(b1,false) << b_or(b1,true)
         << endl;
    cout << b_and(b0,false) << b_and(b0,true) << b_and(b1,false)
         << b_and(b1,true) << endl;
    cout << b_xor(b0,false) << b_xor(b0,true) << b_xor(b1,false)
         << b_xor(b1,true) << endl;

    cout << b_or(0,b0) << b_or(0,b1) << b_or(1,b0) << b_or(1,b1) << endl;
    cout << b_and(0,b0) << b_and(0,b1) << b_and(1,b0) << b_and(1,b1) << endl;
    cout << b_xor(0,b0) << b_xor(0,b1) << b_xor(1,b0) << b_xor(1,b1) << endl;

    cout << b_or('0',b0) << b_or('0',b1) << b_or('1',b0) << b_or('1',b1)
         << endl;
    cout << b_and('0',b0) << b_and('0',b1) << b_and('1',b0) << b_and('1',b1)
         << endl;
    cout << b_xor('0',b0) << b_xor('0',b1) << b_xor('1',b0) << b_xor('1',b1)
         << endl;

    cout << b_or(false,b0) << b_or(false,b1) << b_or(true,b0) << b_or(true,b1)
         << endl;
    cout << b_and(false,b0) << b_and(false,b1) << b_and(true,b0)
         << b_and(true,b1) << endl;
    cout << b_xor(false,b0) << b_xor(false,b1) << b_xor(true,b0)
         << b_xor(true,b1) << endl;

    b_or(b, b0, b1);
    assert(b);
    b_and(b, b0, b1);
    assert(!b);
    b_xor(b, b0, b1);
    assert(b);
}
Beispiel #25
0
void ColorInspector::setColor(QColor newColor)
{
    // this is a UI update function, never emit any signals
    // grab the color from color manager, and then update itself, that's it.

    // compare under the same color spec
    newColor = (isRgbColors) ? newColor.toRgb() : newColor.toHsv();

    if (newColor == mCurrentColor)
    {
        return;
    }

    if(isRgbColors)
    {
        QSignalBlocker b1(ui->red_slider); 
        QSignalBlocker b2(ui->green_slider);
        QSignalBlocker b3(ui->blue_slider);
        QSignalBlocker b4(ui->alpha_slider);

        ui->red_slider->setRgb(newColor);
        ui->green_slider->setRgb(newColor);
        ui->blue_slider->setRgb(newColor);
        ui->alpha_slider->setRgb(newColor);

        QSignalBlocker b5(ui->RedspinBox);
        QSignalBlocker b6(ui->GreenspinBox);
        QSignalBlocker b7(ui->BluespinBox);
        QSignalBlocker b8(ui->AlphaspinBox);

        ui->RedspinBox->setValue(newColor.red());
        ui->GreenspinBox->setValue(newColor.green());
        ui->BluespinBox->setValue(newColor.blue());
        ui->AlphaspinBox->setValue(newColor.alpha());
    }
    else
    {
        QSignalBlocker b1(ui->red_slider);
        QSignalBlocker b2(ui->green_slider);
        QSignalBlocker b3(ui->blue_slider);
        QSignalBlocker b4(ui->alpha_slider);

        ui->red_slider->setHsv(newColor);
        ui->green_slider->setHsv(newColor);
        ui->blue_slider->setHsv(newColor);
        ui->alpha_slider->setHsv(newColor);

        QSignalBlocker b5(ui->RedspinBox);
        QSignalBlocker b6(ui->GreenspinBox);
        QSignalBlocker b7(ui->BluespinBox);
        QSignalBlocker b8(ui->AlphaspinBox);

        ui->RedspinBox->setValue(newColor.hsvHue());
        ui->GreenspinBox->setValue(qRound(newColor.hsvSaturation() / 2.55));
        ui->BluespinBox->setValue(qRound(newColor.value() / 2.55));
        ui->AlphaspinBox->setValue(qRound(newColor.alpha() / 2.55));
    }

    mCurrentColor = newColor;

    QPalette p1 = ui->colorWrapper->palette(), p2 = ui->color->palette();
    p1.setBrush(QPalette::Background, QBrush(QImage(":/background/checkerboard.png")));
    p2.setColor(QPalette::Background, mCurrentColor);
    ui->colorWrapper->setPalette(p1);
    ui->color->setPalette(p2);

    update();
}
Beispiel #26
0
// Compute the normal at a specific point in the patch.
// The s and t values vary between 0 and 1.
QVector3D QGLBezierPatch::normal(qreal s, qreal t) const
{
    qreal a[4];
    qreal b[4];
    qreal tx, ty, tz;
    qreal sx, sy, sz;

    // Compute the derivative of the surface in t.
    a[0] = b0(s);
    a[1] = b1(s);
    a[2] = b2(s);
    a[3] = b3(s);
    b[0] = db0(t);
    b[1] = db1(t);
    b[2] = db2(t);
    b[3] = db3(t);
    tx = 0.0f;
    ty = 0.0f;
    tz = 0.0f;
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            tx += a[i] * points[j * 4 + i].x() * b[j];
            ty += a[i] * points[j * 4 + i].y() * b[j];
            tz += a[i] * points[j * 4 + i].z() * b[j];
        }
    }

    // Compute the derivative of the surface in s.
    a[0] = db0(s);
    a[1] = db1(s);
    a[2] = db2(s);
    a[3] = db3(s);
    b[0] = b0(t);
    b[1] = b1(t);
    b[2] = b2(t);
    b[3] = b3(t);
    sx = 0.0f;
    sy = 0.0f;
    sz = 0.0f;
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            sx += a[i] * points[j * 4 + i].x() * b[j];
            sy += a[i] * points[j * 4 + i].y() * b[j];
            sz += a[i] * points[j * 4 + i].z() * b[j];
        }
    }

    // The normal is the cross-product of the two derivatives,
    // normalized to a unit vector.
    QVector3D n = QVector3D::normal(QVector3D(sx, sy, sz), QVector3D(tx, ty, tz));
    if (n.isNull()) {
        // A zero normal may occur if one of the patch edges is zero-length.
        // We correct for this by substituting an overall patch normal that
        // we compute from two of the sides that are not zero in length.
        QVector3D sides[4];
        QVector3D vectors[2];
        sides[0] = points[3] - points[0];
        sides[1] = points[15] - points[3];
        sides[2] = points[12] - points[15];
        sides[3] = points[0] - points[12];
        int i = 0;
        int j = 0;
        vectors[0] = QVector3D(1.0f, 0.0f, 0.0f);
        vectors[1] = QVector3D(0.0f, 1.0f, 0.0f);
        while (i < 2 && j < 4) {
            if (sides[j].isNull())
                ++j;
            else
                vectors[i++] = sides[j++];
        }
        n = QVector3D::normal(vectors[0], vectors[1]);
    }
    return n;
}