Ejemplo n.º 1
0
vector<MatrixXd> LowRankRepresentation::result(MatrixXd& X, MatrixXd& A, double lambda)
{
    vector<MatrixXd> ZE;
    MatrixXd atx, J, Z, Y1, Y2, inv_a, tmp, xmaz, leq1, leq2;
    VectorXd sigma_tmp;
    int d, n, m, svp, M, N, i, j;
    double stopC, stopC_tmp1, stopC_tmp2;

    d = X.rows();
    n = X.cols();
    m = A.cols();

    atx = A.transpose() * X;
    inv_a = (A.transpose() *A + MatrixXd::Identity(m, m)).inverse();
    J = MatrixXd::Zero(m, n);
    Z = MatrixXd::Zero(m, n);
    Y1 = MatrixXd::Zero(d, n);
    Y2 = MatrixXd::Zero(m, n);
    MatrixXd E;
    E = MatrixXd::Zero(d, n);
//   SparseMatrix<double> E(d, n);
    int iter = 0;

//    FullPivLU<MatrixXd> lu_decomp(Z);
//    cout << "initial, rank=" << lu_decomp.rank() << endl;

    while(iter < MaxIter)
    {
        iter += 1;
        tmp = Z + Y2/Mu;
        M = tmp.rows();
        N = tmp.cols();
        double d_tmp[M*N];
        for(i=0; i<M; i++)
            for(j=0; j<N; j++)
                d_tmp[i + j*N] = tmp(i, j);

        mxArray *U_pro, *sigma_pro, *V_pro, *B;
        mxArray *ppLhs[3];
        B = mxCreateDoubleMatrix(M, N, mxREAL); 
        //ppRhs[0] = B;
        //ppRhs[1] = "econ";
        memcpy(mxGetPr(B), d_tmp, sizeof(double) * M * N);

        mexCallMATLAB(3, ppLhs, 1, &B, "svd");
        U_pro = ppLhs[0]; 
        sigma_pro = ppLhs[1]; 
        V_pro = ppLhs[2]; 

        M = mxGetM(U_pro);
        N = mxGetN(U_pro);
        MatrixXd U(M,N);
        for(i=0;i<M;i++)
            for(j=0; j<N; j++)
                U(i, j) = mxGetPr(U_pro)[i + j*N];

        VectorXd sigma(N);
        for(i=0; i<N; i++)
            sigma(i) = mxGetPr(sigma_pro)[i + i*N];

        N = mxGetN(V_pro);
        MatrixXd V(M,N);
        for(i=0; i<N; i++)
            for(j=0; j<M; j++)
                V(i, j) = mxGetPr(V_pro)[i + j*M];


        mxDestroyArray(U_pro);
        mxDestroyArray(sigma_pro); 
        mxDestroyArray(V_pro); 
        mxDestroyArray(B); 

//        JacobiSVD<MatrixXd> svd(tmp, ComputeThinU | ComputeThinV);
//        sigma = svd.singularValues();
//        //sigma = MatrixXd(sigma.asDiagonal());
//        U = svd.matrixU();
//        V = svd.matrixV();
        svp = (sigma.array() > 1/Mu).count();
        
        if(svp >= 1)
        {
            sigma_tmp = sigma.segment(0,svp)-(1/Mu) * VectorXd::Ones(svp) ;
            sigma = sigma_tmp;
        }
        else
        {
            svp = 1;
            sigma = VectorXd::Zero(1);
        }
        J = U.leftCols(svp) * MatrixXd(sigma.asDiagonal()) * V.leftCols(svp).transpose();
        Z = inv_a * (atx - A.transpose() * E + J + (A.transpose() * Y1 - Y2)/Mu);
     
        xmaz = X - A * Z;
        tmp = xmaz + Y1 / Mu;
        E = solve_l1l2(tmp, lambda/Mu);

        
        leq1 = xmaz - E;
        leq2 = Z - J;
        stopC_tmp1 = leq1.array().abs().maxCoeff();
        stopC_tmp2 = leq2.array().abs().maxCoeff();
        stopC = stopC_tmp1 < stopC_tmp2 ? stopC_tmp2:stopC_tmp1;


        
//        if (iter==1 || (iter % 50)==0 || stopC<Tol)
//        {
//            FullPivLU<MatrixXd> lu_decomp(Z);
            //printf("iter %d, mu=%2.1e, rank=%d, stopALM=%2.3e\n", iter, Mu, lu_decomp.rank(), stopC);
 //           printf("iter %d, mu=%2.1e, stopALM=%2.3e\n", iter, Mu, stopC);
//           cout<< endl;
//        }
        if (stopC<Tol)
        {
            cout << "LRR done." << endl;
            break;
        }
        else
        {
            Y1 = Y1 + Mu*leq1;
            Y2 = Y2 + Mu*leq2;
            Mu = MaxMu > Mu*Rho ? Mu*Rho:MaxMu;
        }
    }
    ZE.push_back(Z);
    ZE.push_back(E);
    return ZE;
}
CFX_PtrArray* CBC_ReedSolomonDecoder::RunEuclideanAlgorithm(
    CBC_ReedSolomonGF256Poly* a,
    CBC_ReedSolomonGF256Poly* b,
    int32_t R,
    int32_t& e) {
  if (a->GetDegree() < b->GetDegree()) {
    CBC_ReedSolomonGF256Poly* temp = a;
    a = b;
    b = temp;
  }
  CBC_ReedSolomonGF256Poly* rsg1 = a->Clone(e);
  BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
  CBC_AutoPtr<CBC_ReedSolomonGF256Poly> rLast(rsg1);
  CBC_ReedSolomonGF256Poly* rsg2 = b->Clone(e);
  BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
  CBC_AutoPtr<CBC_ReedSolomonGF256Poly> r(rsg2);
  CBC_ReedSolomonGF256Poly* rsg3 = m_field->GetOne()->Clone(e);
  BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
  CBC_AutoPtr<CBC_ReedSolomonGF256Poly> sLast(rsg3);
  CBC_ReedSolomonGF256Poly* rsg4 = m_field->GetZero()->Clone(e);
  BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
  CBC_AutoPtr<CBC_ReedSolomonGF256Poly> s(rsg4);
  CBC_ReedSolomonGF256Poly* rsg5 = m_field->GetZero()->Clone(e);
  BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
  CBC_AutoPtr<CBC_ReedSolomonGF256Poly> tLast(rsg5);
  CBC_ReedSolomonGF256Poly* rsg6 = m_field->GetOne()->Clone(e);
  BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
  CBC_AutoPtr<CBC_ReedSolomonGF256Poly> t(rsg6);
  while (r->GetDegree() >= R / 2) {
    CBC_AutoPtr<CBC_ReedSolomonGF256Poly> rLastLast = rLast;
    CBC_AutoPtr<CBC_ReedSolomonGF256Poly> sLastLast = sLast;
    CBC_AutoPtr<CBC_ReedSolomonGF256Poly> tLastlast = tLast;
    rLast = r;
    sLast = s;
    tLast = t;
    if (rLast->IsZero()) {
      e = BCExceptionR_I_1IsZero;
      BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
    }
    CBC_ReedSolomonGF256Poly* rsg7 = rLastLast->Clone(e);
    BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
    CBC_AutoPtr<CBC_ReedSolomonGF256Poly> rTemp(rsg7);
    r = rTemp;
    CBC_ReedSolomonGF256Poly* rsg8 = m_field->GetZero()->Clone(e);
    BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
    CBC_AutoPtr<CBC_ReedSolomonGF256Poly> q(rsg8);
    int32_t denominatorLeadingTerm = rLast->GetCoefficients(rLast->GetDegree());
    int32_t dltInverse = m_field->Inverse(denominatorLeadingTerm, e);
    BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
    while (r->GetDegree() >= rLast->GetDegree() && !(r->IsZero())) {
      int32_t degreeDiff = r->GetDegree() - rLast->GetDegree();
      int32_t scale =
          m_field->Multiply(r->GetCoefficients(r->GetDegree()), dltInverse);
      CBC_ReedSolomonGF256Poly* rsgp1 =
          m_field->BuildMonomial(degreeDiff, scale, e);
      BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
      CBC_AutoPtr<CBC_ReedSolomonGF256Poly> build(rsgp1);
      CBC_ReedSolomonGF256Poly* rsgp2 = q->AddOrSubtract(build.get(), e);
      BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
      CBC_AutoPtr<CBC_ReedSolomonGF256Poly> temp(rsgp2);
      q = temp;
      CBC_ReedSolomonGF256Poly* rsgp3 =
          rLast->MultiplyByMonomial(degreeDiff, scale, e);
      BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
      CBC_AutoPtr<CBC_ReedSolomonGF256Poly> multiply(rsgp3);
      CBC_ReedSolomonGF256Poly* rsgp4 = r->AddOrSubtract(multiply.get(), e);
      BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
      CBC_AutoPtr<CBC_ReedSolomonGF256Poly> temp3(rsgp4);
      r = temp3;
    }
    CBC_ReedSolomonGF256Poly* rsg9 = q->Multiply(sLast.get(), e);
    BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
    CBC_AutoPtr<CBC_ReedSolomonGF256Poly> temp1(rsg9);
    CBC_ReedSolomonGF256Poly* rsg10 = temp1->AddOrSubtract(sLastLast.get(), e);
    BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
    CBC_AutoPtr<CBC_ReedSolomonGF256Poly> temp2(rsg10);
    s = temp2;
    CBC_ReedSolomonGF256Poly* rsg11 = q->Multiply(tLast.get(), e);
    BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
    CBC_AutoPtr<CBC_ReedSolomonGF256Poly> temp5(rsg11);
    CBC_ReedSolomonGF256Poly* rsg12 = temp5->AddOrSubtract(tLastlast.get(), e);
    BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
    CBC_AutoPtr<CBC_ReedSolomonGF256Poly> temp6(rsg12);
    t = temp6;
  }
  int32_t sigmaTildeAtZero = t->GetCoefficients(0);
  if (sigmaTildeAtZero == 0) {
    e = BCExceptionIsZero;
    BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
  }
  int32_t inverse = m_field->Inverse(sigmaTildeAtZero, e);
  BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
  CBC_ReedSolomonGF256Poly* rsg13 = t->Multiply(inverse, e);
  BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
  CBC_AutoPtr<CBC_ReedSolomonGF256Poly> sigma(rsg13);
  CBC_ReedSolomonGF256Poly* rsg14 = r->Multiply(inverse, e);
  BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
  CBC_AutoPtr<CBC_ReedSolomonGF256Poly> omega(rsg14);
  CFX_PtrArray* temp = new CFX_PtrArray;
  temp->Add(sigma.release());
  temp->Add(omega.release());
  return temp;
}
Ejemplo n.º 3
0
    void mcsrch(int size,
                double *x,
                double f, const double *g, double *s,
                double *stp,
                int *info, int *nfev, double *wa, bool orthant, double C) {
      static const double p5 = 0.5;
      static const double p66 = 0.66;
      static const double xtrapf = 4.0;
      static const int maxfev = 20;

      /* Parameter adjustments */
      --wa;
      --s;
      --g;
      --x;

      if (*info == -1) goto L45;
      infoc = 1;

      if (size <= 0 || *stp <= 0.0) return;

      dginit = ddot_(size, &g[1], &s[1]);
      if (dginit >= 0.0) return;

      brackt = false;
      stage1 = true;
      *nfev = 0;
      finit = f;
      dgtest = ftol * dginit;
      width = lb3_1_stpmax - lb3_1_stpmin;
      width1 = width / p5;
      for (int j = 1; j <= size; ++j) {
        wa[j] = x[j];
      }

      stx = 0.0;
      fx = finit;
      dgx = dginit;
      sty = 0.0;
      fy = finit;
      dgy = dginit;

      while (true) {
        if (brackt) {
          stmin = min(stx, sty);
          stmax = max(stx, sty);
        } else {
          stmin = stx;
          stmax = *stp + xtrapf * (*stp - stx);
        }

        *stp = max(*stp, lb3_1_stpmin);
        *stp = min(*stp, lb3_1_stpmax);

        if ((brackt && ((*stp <= stmin || *stp >= stmax) ||
                        *nfev >= maxfev - 1 || infoc == 0)) ||
            (brackt && (stmax - stmin <= xtol * stmax))) {
          *stp = stx;
        }

        if (orthant) {
          for (int j = 1; j <= size; ++j) {
            double grad_neg = 0.0;
            double grad_pos = 0.0;
            double grad = 0.0;
            if (wa[j] == 0.0) {
              grad_neg = g[j] - 1.0 / C;
              grad_pos = g[j] + 1.0 / C;
            } else {
              grad_pos = grad_neg = g[j] + 1.0 * sigma(wa[j]) / C;
            }
            if (grad_neg > 0.0) {
              grad = grad_neg;
            } else if (grad_pos < 0.0) {
              grad = grad_pos;
            } else {
              grad = 0.0;
            }
            const double p = pi(s[j], -grad);
            const double xi = wa[j] == 0.0 ? sigma(-grad) : sigma(wa[j]);
            x[j] = pi(wa[j] + *stp * p, xi);
          }
        } else {
          for (int j = 1; j <= size; ++j) {
            x[j] = wa[j] + *stp * s[j];
          }
        }
        *info = -1;
        return;

      L45:
        *info = 0;
        ++(*nfev);
        double dg = ddot_(size, &g[1], &s[1]);
        double ftest1 = finit + *stp * dgtest;

        if (brackt && ((*stp <= stmin || *stp >= stmax) || infoc == 0)) {
          *info = 6;
        }
        if (*stp == lb3_1_stpmax && f <= ftest1 && dg <= dgtest) {
          *info = 5;
        }
        if (*stp == lb3_1_stpmin && (f > ftest1 || dg >= dgtest)) {
          *info = 4;
        }
        if (*nfev >= maxfev) {
          *info = 3;
        }
        if (brackt && stmax - stmin <= xtol * stmax) {
          *info = 2;
        }
        if (f <= ftest1 && std::abs(dg) <= lb3_1_gtol * (-dginit)) {
          *info = 1;
        }

        if (*info != 0) {
          return;
        }

        if (stage1 && f <= ftest1 && dg >= min(ftol, lb3_1_gtol) * dginit) {
          stage1 = false;
        }

        if (stage1 && f <= fx && f > ftest1) {
          double fm = f - *stp * dgtest;
          double fxm = fx - stx * dgtest;
          double fym = fy - sty * dgtest;
          double dgm = dg - dgtest;
          double dgxm = dgx - dgtest;
          double dgym = dgy - dgtest;
          mcstep(&stx, &fxm, &dgxm, &sty, &fym, &dgym, stp, fm, dgm, &brackt,
                 stmin, stmax, &infoc);
          fx = fxm + stx * dgtest;
          fy = fym + sty * dgtest;
          dgx = dgxm + dgtest;
          dgy = dgym + dgtest;
        } else {
          mcstep(&stx, &fx, &dgx, &sty, &fy, &dgy, stp, f, dg, &brackt,
                 stmin, stmax, &infoc);
        }

        if (brackt) {
          double d1 = 0.0;
          if ((d1 = sty - stx, std::abs(d1)) >= p66 * width1) {
            *stp = stx + p5 * (sty - stx);
          }
          width1 = width;
          width = (d1 = sty - stx, std::abs(d1));
        }
      }

      return;
    }
Ejemplo n.º 4
0
void bug_6()
{
    INT res;
    cout << "should be :  incompatible dimension in  fonction coordinate \n";
    copy(rectangle(Pt2di(-10,-13),Pt2di(103,105)),FZ,sigma(res));
}
Ejemplo n.º 5
0
int main(){
    int i, N;
    char c, file[100];
    
    // check that gnuplot is present on the system
    int gnupl = control();
    if(gnupl == 1){
        printf("\nYou need gnuplot to graph the results.");
        printf("\nInstall it with: sudo apt-get install gnuplot\n\n");
        exit(2);
    }
    
    printf("Enter the name or path of file: ");
    fgets(file,sizeof(file),stdin);
    file[strlen(file)-1] = '\0';
    
    // the file's lines number is the number of points to be saved
    N = linesFile(file);
    if(N <= 2){
        printf("\nError: insufficient data number.\n");
        exit(2);
    }
    
    // creating data's arrays
    double *x = calloc(N,sizeof(double));
    double *y = calloc(N,sizeof(double));
    double *errors = calloc(N,sizeof(double));
    if(x == NULL || y == NULL || errors == NULL){
            perror("\nerror");
            printf("\n");
            exit(1);
    }
    
    // reading from file
    FILE *inputFile = fopen(file,"r");
    if(inputFile == NULL){
        perror("\nError");
        exit(1);
    }
    
    for(i=0; i<N; i++){
        fscanf(inputFile,"%lf %lf %lf\n",&x[i],&y[i],&errors[i]);
    }
    
    fclose(inputFile);
    
    // determine linear coefficients
    double M = Mbest(N,x,y,errors);
    double Q = Qbest(N,x,y,errors,M);
    double sigmaM = fabs(uM(N,x,y,errors,M,Q));
    double sigmaQ = fabs(uQ(N,x,errors,sigmaM));
    
    // defining best sigma(Y) and correlation coefficient
    double sigmaY = fabs(bestSigma(N,x,y,M,Q)); // <-- residuals analysis
    double cov = covariance(N,x,y);
    double cor = correlation(N,x,y);
    double lCov = linearParamCovariance(N,mean(x,N),sigma(x,N,mean(x,N)),sigmaY,M,Q);
    double lCor = linearParamCorrelation(N,x);
    
    // Chi-square test
    int freedomDegrees = N - 2; // infer 2 parameters (): M and Q
    double chi2 = 0, rChi2;
    
    for(i=0; i<N; i++){
        chi2 += pow(y[i] - ((M * x[i]) + Q),2) / pow(errors[i],2);
    }
    
    rChi2 = chi2 / freedomDegrees;
    
    printf("\nThe best linear fit Y = mX + q is:");
    printf("\nm = %.3lf\tsigma(m) = %.3lf\nq = %.3lf\tsigma(q) = %.3lf",M,sigmaM,Q,sigmaQ);
    printf("\n\nBest sigma(Y) = %.3lf",sigmaY);
    printf("\nCov(X,Y) = %.3lf",cov);
    printf("\nCor(X,Y) = %.3lf",cor);
    printf("\nCov(m,c) = %.3lf",lCov);
    printf("\nCor(m,c) = %.3lf",lCor);
    //printf("\nChi square = %.3lf",chi2);
    printf("\nReduced Chi square = %.3lf",rChi2);
    
    // interpolation and extrapolation
    int choice;
    double pointX, pointY, sigmaPointY, alpha;
    printf("\n\nDo you want to extrapolate a point with the calculated linear regression? (1 = YES | 0 = NO): ");
    scanf("%d",&choice);
    if(choice == 1){
        extrapolation(N,x,errors,sigmaY,M,Q);
    }
    
    // creating fit
    printf("\nPlotting fit...\n");
    FILE *data = fopen("data.dat","w");
    if(data == NULL){
        perror("\nError");
        exit(1);
    }
    
    // writing experimental datas
    for(i=0; i<N; i++){
        fprintf(data,"%lf %lf %lf\n",x[i],y[i],errors[i]);
    }
    
    fclose(data);
    
    // creating fit points
    //fit(M,Q,x,N); // gnuplot feature
    
    free(x);
    free(y);
       
    return 0;
}
Ejemplo n.º 6
0
void bug_3()
{
    INT res;
    cout << "should be :  division by 0 \n";
    copy(rectangle(Pt2di(-10,-13),Pt2di(103,105)),FY/FX,sigma(res));
}
Ejemplo n.º 7
0
void bug_4()
{
    REAL res;
    cout << "should be :  division by 0 \n";
    copy(rectangle(Pt2di(-10,-13),Pt2di(103,105)),FY/(FX+1.0),sigma(res));
}
Ejemplo n.º 8
0
     cBenchCorrel (Pt2di aSz) :
         mIm1(aSz.x,aSz.y),
         mDup1(aSz.x,aSz.y),
         mPds1(aSz.x,aSz.y),
         mIm2(aSz.x,aSz.y),
         mDup2(aSz.x,aSz.y),
         mPds2(aSz.x,aSz.y)
     {


           ELISE_COPY(mIm1.all_pts(),frandr(),mIm1.out()|mDup1.out());
           ELISE_COPY(mIm2.all_pts(),frandr(),mIm2.out()|mDup2.out());


           ELISE_COPY(mIm1.all_pts(),frandr(),mPds1.out());
           ELISE_COPY(mIm1.all_pts(),frandr(),mPds2.out());



           ElFFTCorrelCirc(mDup1,mDup2);
           Im2D_REAL8 aCPad = ElFFTCorrelPadded(mIm1, mIm2);


           REAL anEps = (1+10*NRrandom3()) * 1e-2;

           REAL aRatioSurf = aSz.x * aSz.y * (1+NRrandom3()) / 6.0;

           Im2D_REAL8 aCNC = ElFFTCorrelNCPadded(mIm1, mIm2,anEps,aRatioSurf);
           Im2D_REAL8 aPdsCNC = ElFFTPonderedCorrelNCPadded
                          (
                                mIm1.in(),
                                mIm2.in(),
                                aSz,
                                mPds1.in(),
                                mPds2.in(),
                                anEps,
                                aRatioSurf
                          );

           for (INT x =-1 ; x<= aSz.x ; x++)
           {
               for (INT y =-1 ; y<= aSz.y ; y++)
               {
                    REAL aSElise;
                    ELISE_COPY
                    (
	                mIm1.all_pts(),
		          mIm1.in()[Virgule(mod(FX+x,aSz.x),mod(FY+y,aSz.y))] 
		        * mIm2.in(),
		        sigma(aSElise)
                    );

	            REAL aSFFT = mDup1.data()[mod(y,aSz.y)][mod(x,aSz.x)];

	            BENCH_ASSERT(std::abs(aSElise-aSFFT)<epsilon);

                    Pt2di aDec(x,y);
                    VerifCorrelCNC(aDec,false,aCPad, anEps,aCNC,aRatioSurf);
                    VerifCorrelCNC(aDec,true,aCPad, anEps,aPdsCNC,aRatioSurf);

               }
           }
     }
Ejemplo n.º 9
0
void bug_2()
{
    REAL res;
    cout << "should be :  incompatible type in Out Reduction \n";
    copy(rectangle(Pt2di(-10,-13),Pt2di(103,105)),FY+FX*3,sigma(res));
}
Ejemplo n.º 10
0
void main(void) {
	cout << "\nTesting blank constructor";
	tabloid t;

	cout << "\nTesting constructor of a tabloid of shape 311";
	Partition lambda;
	lambda.Add(3);
	lambda.Add(2);
	lambda.Add(1);
	tabloid s(lambda);
	
	cout << "\nGetting the standard tabloid of shape 311";
	s = standardoid(lambda);

	cout << "\nTesting output";
	cout << s;

	cout << "\nTesting Sn action";
	Perm sigma(6);
	sigma[1]=6;
	sigma[2]=3;
	sigma[3]=1;
	sigma[4]=2;
	sigma[5]=5;
	sigma[6]=4;
		cout << "\nApplying ";
	    cout << sigma;
		cout << sigma * s;

	
	cout << "\nNote that ";
	cout << s;
	cout << " has " << s.RowNumber() << " of rows";

	cout << " and the second row is \n";
	rows temp = s.Row(2);
	for (rows::const_iterator iter2 = temp.begin(); iter2 != temp.end(); ++iter2) {
		cout << " " << *iter2;
	}


// reorder the rows of a tabloid Note it no longer have the shape of a paritition

	Perm tau(3);
	tau[1]=2;
	tau[2]=3;
	tau[3]=1;
	
	cout << "\nReordering rows of ";
	cout << s;
	cout << " with ";
	cout << tau;
	tabloid q = reorderrows(tau, s);
	cout << q;

//	void insert(const vector<int> row);
	cout << "\nNow we insert a row of 7, 8, 9";
	vector<int> rowtemp;
	rowtemp.push_back(7);
	rowtemp.push_back(8);
	rowtemp.push_back(9);
	q.insert(rowtemp);
	cout << q;

//	void Add(const int row, const int value);
	cout << "\nNow we add a 10 to row 2";
	q.Add(2,10);
	cout << q;
	int crap;
	cin >> crap;
}
Ejemplo n.º 11
0
Archivo: xygrid.c Proyecto: krzul/dia
/*--------------------------------------------------------*/
int main(int argc, char *argv[])
{	
        char    *parfname, *inpfname, *outfname;
        int     i, nobj, nterm, ik, ik0, delta, niter;
        float   *x, *nx, *nzx, *zx,
                *y, *ny, *nzy, *zy,
                dx, dy, rr, thresh, sx, sy;
        double  *coeffx, *coeffy;
        FILE    *outf;
        PARAMS  par;

/* IO stuff */

  if (argc != 4)
  {
    printf("\n\tUSAGE: xygrid  parameter_file  input_list  coeff_file\n\n");
    exit(1);
  }

  parfname = argv[1];
  inpfname = argv[2];
  outfname = argv[3];

  readpar(parfname, &par);

  nterm = (par.ndeg+1)*(par.ndeg+2)/2;

  nobj=readcoor(inpfname, &x, &y, &zx, &zy);

  if (!(coeffx=(double *)calloc(nterm, sizeof(double))))
    errmess("calloc(coeffx)");
  if (!(coeffy=(double *)calloc(nterm, sizeof(double))))
    errmess("calloc(coeffy)");

/* make initial fit */
  fit(x, y, zx, par.ndeg, nobj, coeffx);
  fit(x, y, zy, par.ndeg, nobj, coeffy);

  sx = sigma(x, y, zx, par.ndeg, nobj, coeffx);
  sy = sigma(x, y, zy, par.ndeg, nobj, coeffy);

  thresh = par.sigmaf*par.sigmaf*(sx*sx + sy*sy);

  ik = nobj;
  delta = 1;
  niter = 0;

  if (!(nx=(float *)calloc(nobj, sizeof(float))))
    errmess("readcoor: calloc(nx)");
  if (!(ny=(float *)calloc(nobj, sizeof(float))))
    errmess("readcoor: calloc(ny)");
  if (!(nzx=(float *)calloc(nobj, sizeof(float))))
    errmess("readcoor: calloc(nzx)");
  if (!(nzy=(float *)calloc(nobj, sizeof(float))))
    errmess("readcoor: calloc(nzy)");

/* sigma clipping of the fit until MAX_NITER reached or nothing changes */

  while ((delta > 0) && (niter < par.maxniter))
  {
    ik0 = ik;
    ik  = 0;

    for (i=0; i<nobj; i++)
    {
      dx  = poly(x[i], y[i], par.ndeg, coeffx) - zx[i];
      dy  = poly(x[i], y[i], par.ndeg, coeffy) - zy[i];

      rr  = dx*dx + dy*dy;

      nx[ik]  = x[i];
      ny[ik]  = y[i];
      nzx[ik] = zx[i];
      nzy[ik] = zy[i];

      if (rr < thresh) ++ik;
    }

    delta = ik0 - ik;

    fit(nx, ny, nzx, par.ndeg, ik, coeffx);
    fit(nx, ny, nzy, par.ndeg, ik, coeffy);

    sx = sigma(nx, ny, nzx, par.ndeg, ik, coeffx);
    sy = sigma(nx, ny, nzy, par.ndeg, ik, coeffy);

    niter++;
  }

  free(x);
  free(y);
  free(zx);
  free(zy);
  free(nx);
  free(ny);
  free(nzx);
  free(nzy);

/* print results and store coefficients in binary file */

  if (par.verbose)
  {
    printf("\n");
    for (i=0; i<nterm; i++)
    {
      printf("coeffx[%d] = %9.6f   ", i, coeffx[i]);
      printf("coeffy[%d] = %9.6f \n", i, coeffy[i]);
    }
  }

  printf("%s:  sigmax= %.4f   sigmay= %.4f   ndata= %d   nleft= %d\n",
          outfname, sx, sy, nobj, ik);

  if (!(outf=fopen(outfname, "w"))) errmess(outfname);

  fwrite(&nterm, sizeof(int), 1, outf);
  fwrite(coeffx, sizeof(double), nterm, outf);
  fwrite(coeffy, sizeof(double), nterm, outf);

  fclose(outf);

  free(coeffx);
  free(coeffy);

  return(0);
}
Ejemplo n.º 12
0
 inline void ExtendedCoxIngersollRoss::generateArguments() {
     phi_ = FittingParameter(termStructure(), theta(), k(), sigma(), x0());
 }
Ejemplo n.º 13
0
void cBenchLeastSquare::TestFoncNVar()
{
    cFormQuadCreuse aFQuad(mNbVar,false);
    aFQuad.SetEpsB(1e-10);
    cOptimSommeFormelle anOSF(mNbVar);
    for (INT kEq=0; kEq<mNbEq ; kEq++)
    {
	Fonc_Num f = Fonc_Num(0);
        for (INT kV=0; kV<mNbVar ; kV++)
        {
	    f = f+mSys.CoefLin(kV,kEq)*kth_coord(kV);
        }
	f = f-mSys.CoefCste(kEq);
	f = Square(f) *  mSys.Pds(kEq);
	anOSF.Add(f,NRrandom3()<0.5);
	aFQuad.AddDiff(f);
    }
    
    // Verif de gradient + fonc sur aFQuad
    for (INT aNb=0 ; aNb<10 ; aNb++)
    {
       Im1D_REAL8 aPt(mNbVar);
       ELISE_COPY(aPt.all_pts(),frandr(),aPt.out());

       REAL aVSom = anOSF.ValFNV(aPt.data());
       REAL aVQ = aFQuad.ValFNV(aPt.data());
       REAL aVSys = mSys.L2SomResiduPond(aPt); 

       REAL aDif =   DiffRel(aVQ,aVSys,epsilon);
       BENCH_ASSERT(aDif<epsilon);


       aDif =   DiffRel(aVSom,aVSys,epsilon);
       BENCH_ASSERT(aDif<epsilon);

       Im1D_REAL8 aGradQ(mNbVar,0.0);
       Im1D_REAL8 aGradSys(mNbVar,0.0);
       Im1D_REAL8 aGradSom(mNbVar,0.0);

        aFQuad.GradFNV(aGradQ.data(),aPt.data());
        GradFNV(aGradSys.data(),aPt.data());
        anOSF.GradFNV(aGradSom.data(),aPt.data());

        for (INT kV=0; kV<mNbVar ; kV++)
	{
	    REAL aGQ = aGradQ.data()[kV];
	    REAL aGSys = aGradSys.data()[kV];
	    REAL aGSom = aGradSom.data()[kV];

            aDif =   DiffRel(aGQ,aGSys,epsilon);
            BENCH_ASSERT(aDif<epsilon);

            aDif =   DiffRel(aGSom,aGSys,epsilon);
            BENCH_ASSERT(aDif<epsilon);
	}
    }

    // Verif de la formule du gradient
	{
    for (INT aNb=0 ; aNb<10 ; aNb++)
    {
       Im1D_REAL8 aPt(mNbVar,0.0);
       Im1D_REAL8 aGrad(mNbVar,0.0);
       GradFNV(aGrad.data(),aPt.data());

       Im1D_REAL8 aDep(mNbVar,0.0);
       ELISE_COPY(aDep.all_pts(),(frandr()-0.5) * 0.0001,aDep.out());

       REAL aScal;
       ELISE_COPY(aDep.all_pts(),aDep.in()*aGrad.in(),sigma(aScal));

       REAL f1 = mSys.L2SomResiduPond(aDep);
       ELISE_COPY(aDep.all_pts(),-aDep.in(),aDep.out());
       REAL f2 =  mSys.L2SomResiduPond(aDep); 

       REAL aDif = DiffRel(f1,f2,epsilon);
       BENCH_ASSERT(aDif<BIG_epsilon);

    }
	}
    Im1D_REAL8 aPt(mNbVar,0.0);
    powel(aPt.data(),1e-8,200);

    REAL aRes1 = mSys.L2SomResiduPond(mSol);
    REAL aRes2 = mSys.L2SomResiduPond(aPt);
    REAL aDif = DiffRel(aRes1,aRes2,epsilon);
    BENCH_ASSERT(aDif<epsilon);


    ELISE_COPY(aPt.all_pts(),frandr(),aPt.out());
    GradConj(aPt.data(),1e-8,200);
    REAL aRes3 = mSys.L2SomResiduPond(aPt);
    aDif =   DiffRel(aRes1,aRes3,epsilon);
    BENCH_ASSERT(aDif<epsilon);

    ELISE_COPY(aPt.all_pts(),frandr(),aPt.out());




    anOSF. GradConjMin(aPt.data(),1e-8,200);
    REAL aRes4 = mSys.L2SomResiduPond(aPt); 
    aDif =   DiffRel(aRes1,aRes4,epsilon);
    BENCH_ASSERT(aDif<epsilon);
}
Ejemplo n.º 14
0
// Beetweenness Centrality. To get exact results we solve single-source shortest-path problem for every node.
// Solving it for a BtwNIdV subset of nodes gives centralitiy values that are about Graph->GetNodes()/BtwNIdV.Len() times lower than exact centrality.
// "A Faster Algorithm for Beetweenness Centrality", Ulrik Brandes, Journal of Mathematical Sociology, 2001
// "Centrality Estimation in Large Networks", Urlik Brandes and Christian Pich, 2006
void GetBetweennessCentr(const PUNGraph& Graph, const TIntV& BtwNIdV, TIntFltH& NodeBtwH, const bool& DoNodeCent, TIntPrFltH& EdgeBtwH, const bool& DoEdgeCent) {
  if (DoNodeCent) { NodeBtwH.Clr(); }
  if (DoEdgeCent) { EdgeBtwH.Clr(); }
  const int nodes = Graph->GetNodes();
  TIntS S(nodes);
  TIntQ Q(nodes);
  TIntIntVH P(nodes); // one vector for every node
  TIntFltH delta(nodes);
  TIntH sigma(nodes), d(nodes);
  // init  
  for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
    if (DoNodeCent) { 
      NodeBtwH.AddDat(NI.GetId(), 0); }
    if (DoEdgeCent) {
      for (int e = 0; e < NI.GetOutDeg(); e++) { 
        if (NI.GetId() < NI.GetOutNId(e)) {
          EdgeBtwH.AddDat(TIntPr(NI.GetId(), NI.GetOutNId(e)), 0); }
      }
    }
    sigma.AddDat(NI.GetId(), 0);
    d.AddDat(NI.GetId(), -1);
    P.AddDat(NI.GetId(), TIntV());
    delta.AddDat(NI.GetId(), 0);
  }
  // calc betweeness
  for (int k=0; k < BtwNIdV.Len(); k++) {
    const TUNGraph::TNodeI NI = Graph->GetNI(BtwNIdV[k]);
    // reset
    for (int i = 0; i < sigma.Len(); i++) {
      sigma[i]=0;  d[i]=-1;  delta[i]=0;  P[i].Clr(false);
    }
    S.Clr(false);
    Q.Clr(false);
    sigma.AddDat(NI.GetId(), 1);
    d.AddDat(NI.GetId(), 0);
    Q.Push(NI.GetId());
    while (! Q.Empty()) {
      const int v = Q.Top();  Q.Pop();
      const TUNGraph::TNodeI NI2 = Graph->GetNI(v);
      S.Push(v);
      const int VDat = d.GetDat(v);
      for (int e = 0; e < NI2.GetOutDeg(); e++) {
        const int w = NI2.GetOutNId(e);
        if (d.GetDat(w) < 0) { // find w for the first time
          Q.Push(w);
          d.AddDat(w, VDat+1);
        }
        //shortest path to w via v ?
        if (d.GetDat(w) == VDat+1) {
          sigma.AddDat(w) += sigma.GetDat(v);
          P.GetDat(w).Add(v);
        }
      }
    }
    while (! S.Empty()) {
      const int w = S.Top();
      const double SigmaW = sigma.GetDat(w);
      const double DeltaW = delta.GetDat(w);
      const TIntV NIdV = P.GetDat(w);
      S.Pop();
      for (int i = 0; i < NIdV.Len(); i++) {
        const int nid = NIdV[i];
        const double c = (sigma.GetDat(nid)*1.0/SigmaW) * (1+DeltaW);
        delta.AddDat(nid) += c;
        if (DoEdgeCent) {
          EdgeBtwH.AddDat(TIntPr(TMath::Mn(nid, w), TMath::Mx(nid, w))) += c; }
      }
      if (DoNodeCent && w != NI.GetId()) {
        NodeBtwH.AddDat(w) += delta.GetDat(w)/2.0; }
    }
  }
}
Ejemplo n.º 15
0
int main(int argc, char *argv[]){
// 
//      Simple program to illustrate the idea of reverse communication
//      in inverse mode for a generalized complex nonsymmetric eigenvalue 
//      problem.
// 
//      We implement example three of ex-complex.doc in DOCUMENTS directory
// 
// \Example-3
//      ... Suppose we want to solve A*x = lambda*B*x in regular mode,
//          where A and B are derived from the finite element discretization
//          of the 1-dimensional convection-diffusion operator
//                    (d^2u/dx^2) + rho*(du/dx)
//          on the interval [0,1] with zero boundary condition using 
//          piecewise linear elements. 
// 
//      ... OP = inv[M]*A  and  B = M.
// 
//      ... Use mode 2 of ZNAUPD.
// 
// \BeginLib
// 
// \Routines called:
//      znaupd  ARPACK reverse communication interface routine.
//      zneupd  ARPACK routine that returns Ritz values and (optionally)
//              Ritz vectors.
//      zgttrf  LAPACK tridiagonal factorization routine.
//      zgttrs  LAPACK tridiagonal solve routine.
//      dlapy2  LAPACK routine to compute sqrt(x**2+y**2) carefully.
//      zaxpy   Level 1 BLAS that computes y <- alpha*x+y.
//      dznrm2  Level 1 BLAS that computes the norm of a vector.
//      av      Matrix vector multiplication routine that computes A*x.
//      mv      Matrix vector multiplication routine that computes M*x.
// 
// \Author
//      Richard Lehoucq
//      Danny Sorensen
//      Chao Yang
//      Dept. of Computational &
//      Applied Mathematics
//      Rice University
//      Houston, Texas
// 
// \SCCS Information: @(#)
//  FILE: ndrv3.F   SID: 2.2   DATE OF SID: 4/22/96   RELEASE: 2
// 
// \Remarks
//      1. None
// 
// \EndLib
// --------------------------------------------------------------------------
// 
	std::complex<double> ax[maxn], bx[maxn], d[maxncv], v[ldv*maxncv];
	OpData op_data;
	double rd[maxncv*3];

	size_t nx = 10;
	size_t n = nx*nx;
	size_t nev = 4;
	size_t ncv = 20;
	
	std::complex<double> sigma(0.0);
	
	// Construct C = A - SIGMA*I, factor C in complex
	// arithmetic (using LAPACK subroutine zgttrf). The
	// matrix A is chosen to be the tridiagonal matrix
	// derived from standard central difference of the
	// 1-d convection diffusion operator - u" + rho*u' on
	// the interval [0, 1] with zero Dirichlet boundary
	// condition.
	const double h = 1.0/(n+1.0);
	for(size_t j = 0; j < n-1; ++j){
		op_data.dl[j] = h;
		op_data.dd[j] = 4*h;
		op_data.du[j] = h;
	}
	op_data.dd[n-1] = 4*h;
	// zgttrf(n, dl, dd, du, du2, ipiv, ierr)
	{
		for(size_t i = 0; i < n; ++i){
			op_data.ipiv[i] = i;
		}
		for(size_t i = 0; i < n-2; ++i){
			op_data.du2[i] = 0;
		}
		for(size_t i = 0; i < n-2; ++i){
			if(_abs1(op_data.dd[i]) >= _abs1(op_data.dl[i])){
				// No row interchange required, eliminate dl[i]
				if(_abs1(op_data.dd[i]) != 0){
					std::complex<double> fact = op_data.dl[i] / op_data.dd[i];
					op_data.dl[i] = fact;
					op_data.dd[i+1] -= fact * op_data.du[i];
				}
			}else{
				// Interchange rows i and i+1, eliminate dl[i]
				std::complex<double> fact = op_data.dd[i] / op_data.dl[i];
				op_data.dd[i] = op_data.dl[i];
				op_data.dl[i] = fact;
				std::complex<double> temp = op_data.du[i];
				op_data.du[i] = op_data.dd[i+1];
				op_data.dd[i+1] = temp - fact*op_data.dd[i+1];
				op_data.du2[i] = op_data.du[i+1];
				op_data.du[i+1] *= -fact;
				op_data.ipiv[i] = i+1;
			}
		}
		if(n > 1){
			size_t i = n - 2;
			if(_abs1(op_data.dd[i]) >= _abs1(op_data.dl[i])){
				if(_abs1(op_data.dd[i]) != 0){
					std::complex<double> fact = op_data.dl[i] / op_data.dd[i];
					op_data.dl[i] = fact;
					op_data.dd[i+1] -= fact*op_data.du[i];
				}
			}else{
				std::complex<double> fact = op_data.dd[i] / op_data.dl[i];
				op_data.dd[i] = op_data.dl[i];
				op_data.dl[i] = fact;
				std::complex<double> temp = op_data.du[i];
				op_data.du[i] = op_data.dd[i+1];
				op_data.dd[i+1] = temp - fact*op_data.dd[i+1];
				op_data.ipiv[i] = i + 1;
			}
		}
	}
	
	int nconv = RNP::IRA::Regular(
		n, &op_, &bv_,
		nev, ncv, &RNP::IRA::LargestMagnitude,
		d, v, ldv,
		NULL,
		NULL,
		(void*)&op_data);
	if(nconv > 0){
		for(int j = 0; j < nconv; ++j) {
			// Compute the residual norm
			//
			//   ||  A*x - lambda*x ||
			//
			// for the NCONV accurately computed eigenvalues and eigenvectors.
			// (iparam(5) indicates how many are accurate to the requested tolerance)

			av_(n, &v[0+j*ldv], ax);
			bv_(n, &v[0+j*ldv], bx, NULL);
			RNP::TBLAS::Axpy(n, -d[j], bx, 1, ax, 1);
			rd[j+0*maxncv] = d[j].real();
			rd[j+1*maxncv] = d[j].imag();
			rd[j+2*maxncv] = RNP::TBLAS::Norm2(n, ax, 1);
			rd[j+2*maxncv] /= std::abs(d[j]);
		}
		
		// Display computed residuals.
		printf("Residuals:\n");
		for(int i = 0; i < nconv; ++i){
			for(size_t j = 0; j < 3; ++j){
				printf("\t%e", rd[i+j*maxncv]);
			}printf("\n");
		}
	}else{
		printf("IRA::Regular returned %d\n", nconv);
	}
	return 0;
}
Ejemplo n.º 16
0
 // A function that prevents us putting too much stock in small sample
 // sets.  Returns a number between 2.0 and 1.0, depending on the number
 // of samples.  5 or more samples yields one; fewer scales linearly from
 // 2.0 at 1 sample to 1.0 at 5.
 double confidence_factor(int samples) {
   if (samples > 4) return 1.0;
   else return  1.0 + sigma() * ((double)(5 - samples))/2.0;
 }
Ejemplo n.º 17
0
const Vector&
FourNodeQuadUP::getResistingForce()
{
    P.Zero();

    // Determine Jacobian for this integration point
    this->shapeFunction();
    double vol = dvol[0] + dvol[1] + dvol[2] + dvol[3];

    int i;
    // Loop over the integration points
    for (i = 0; i < 4; i++) {

        // Get material stress response
        const Vector &sigma = theMaterial[i]->getStress();

        // Perform numerical integration on internal force
        //P = P + (B^ sigma) * intWt(i)*intWt(j) * detJ;
        //P.addMatrixTransposeVector(1.0, B, sigma, intWt(i)*intWt(j)*detJ);
        for (int alpha = 0, ia = 0; alpha < 4; alpha++, ia += 3) {

            P(ia) += dvol[i]*(shp[0][alpha][i]*sigma(0) + shp[1][alpha][i]*sigma(2));

            P(ia+1) += dvol[i]*(shp[1][alpha][i]*sigma(1) + shp[0][alpha][i]*sigma(2));

            // Subtract equiv. body forces from the nodes
            //P = P - (N^ b) * intWt(i)*intWt(j) * detJ;
            //P.addMatrixTransposeVector(1.0, N, b, -intWt(i)*intWt(j)*detJ);

            double r = mixtureRho(i);
            if (applyLoad == 0) {
                P(ia) -= dvol[i]*(shp[2][alpha][i]*r*b[0]);
                P(ia+1) -= dvol[i]*(shp[2][alpha][i]*r*b[1]);
            } else {
                P(ia) -= dvol[i]*(shp[2][alpha][i]*r*appliedB[0]);
                P(ia+1) -= dvol[i]*(shp[2][alpha][i]*r*appliedB[1]);
            }
        }
    }

    // Subtract fluid body force
    for (int alpha = 0, ia = 0; alpha < 4; alpha++, ia += 3) {
        //P(ia+2) += vol*rho*(perm[0]*b[0]*shpBar[0][alpha]
        //		+perm[1]*b[1]*shpBar[1][alpha]);
        for (i = 0; i < 4; i++) {
            if (applyLoad == 0) {
                P(ia+2) += dvol[i]*rho*(perm[0]*b[0]*shp[0][alpha][i] +
                                        perm[1]*b[1]*shp[1][alpha][i]);
            } else {
                P(ia+2) += dvol[i]*rho*(perm[0]*appliedB[0]*shp[0][alpha][i] +
                                        perm[1]*appliedB[1]*shp[1][alpha][i]);
            }
        }
    }

    // Subtract pressure loading from resisting force
    if (pressure != 0.0) {
        //P = P + pressureLoad;
        P.addVector(1.0, pressureLoad, -1.0);
    }

    // Subtract other external nodal loads ... P_res = P_int - P_ext
    //P = P - Q;
    P.addVector(1.0, Q, -1.0);

    return P;
}
Ejemplo n.º 18
0
 double get_new_neg_prediction(TruncatedSeq* seq) {
   return seq->davg() - sigma() * seq->dsd();
 }
void assemble_postvars_rhs (EquationSystems& es,
                      const std::string& system_name)
{

  const Real E    = es.parameters.get<Real>("E");
  const Real NU    = es.parameters.get<Real>("NU");
  const Real KPERM    = es.parameters.get<Real>("KPERM");
  
	Real sum_jac_postvars=0;
	
	Real av_pressure=0;
	Real total_volume=0;

#include "assemble_preamble_postvars.cpp"

  for ( ; el != end_el; ++el)
    {    
 
      const Elem* elem = *el;

      dof_map.dof_indices (elem, dof_indices);
      dof_map.dof_indices (elem, dof_indices_u, u_var);
      dof_map.dof_indices (elem, dof_indices_v, v_var);
      dof_map.dof_indices (elem, dof_indices_p, p_var);
      dof_map.dof_indices (elem, dof_indices_x, x_var);
      dof_map.dof_indices (elem, dof_indices_y, y_var);
      #if THREED
      dof_map.dof_indices (elem, dof_indices_w, w_var);
      dof_map.dof_indices (elem, dof_indices_z, z_var);
      #endif

      const unsigned int n_dofs   = dof_indices.size();
      const unsigned int n_u_dofs = dof_indices_u.size(); 
      const unsigned int n_v_dofs = dof_indices_v.size();
      const unsigned int n_p_dofs = dof_indices_p.size();
      const unsigned int n_x_dofs = dof_indices_x.size(); 
      const unsigned int n_y_dofs = dof_indices_y.size();
      #if THREED
      const unsigned int n_w_dofs = dof_indices_w.size();
      const unsigned int n_z_dofs = dof_indices_z.size();
      #endif
      
      fe_disp->reinit  (elem);
      fe_vel->reinit  (elem);
      fe_pres->reinit (elem);

      Ke.resize (n_dofs, n_dofs);
      Fe.resize (n_dofs);

      Kuu.reposition (u_var*n_u_dofs, u_var*n_u_dofs, n_u_dofs, n_u_dofs);
      Kuv.reposition (u_var*n_u_dofs, v_var*n_u_dofs, n_u_dofs, n_v_dofs);
      Kup.reposition (u_var*n_u_dofs, p_var*n_u_dofs, n_u_dofs, n_p_dofs);
      Kux.reposition (u_var*n_u_dofs, p_var*n_u_dofs + n_p_dofs , n_u_dofs, n_x_dofs);
      Kuy.reposition (u_var*n_u_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_u_dofs, n_y_dofs);
      #if THREED
      Kuw.reposition (u_var*n_u_dofs, w_var*n_u_dofs, n_u_dofs, n_w_dofs);
      Kuz.reposition (u_var*n_u_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_u_dofs, n_z_dofs);
      #endif

      Kvu.reposition (v_var*n_v_dofs, u_var*n_v_dofs, n_v_dofs, n_u_dofs);
      Kvv.reposition (v_var*n_v_dofs, v_var*n_v_dofs, n_v_dofs, n_v_dofs);
      Kvp.reposition (v_var*n_v_dofs, p_var*n_v_dofs, n_v_dofs, n_p_dofs);
      Kvx.reposition (v_var*n_v_dofs, p_var*n_u_dofs + n_p_dofs , n_v_dofs, n_x_dofs);
      Kvy.reposition (v_var*n_v_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_v_dofs, n_y_dofs);
      #if THREED
      Kvw.reposition (v_var*n_u_dofs, w_var*n_u_dofs, n_v_dofs, n_w_dofs);
      Kuz.reposition (v_var*n_u_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_u_dofs, n_z_dofs);
      #endif

      #if THREED
      Kwu.reposition (w_var*n_w_dofs, u_var*n_v_dofs, n_v_dofs, n_u_dofs);
      Kwv.reposition (w_var*n_w_dofs, v_var*n_v_dofs, n_v_dofs, n_v_dofs);
      Kwp.reposition (w_var*n_w_dofs, p_var*n_v_dofs, n_v_dofs, n_p_dofs);
      Kwx.reposition (w_var*n_w_dofs, p_var*n_u_dofs + n_p_dofs , n_v_dofs, n_x_dofs);
      Kwy.reposition (w_var*n_w_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_v_dofs, n_y_dofs);
      Kww.reposition (w_var*n_w_dofs, w_var*n_u_dofs, n_v_dofs, n_w_dofs);
      Kwz.reposition (w_var*n_w_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_u_dofs, n_z_dofs);
      #endif

      Kpu.reposition (p_var*n_u_dofs, u_var*n_u_dofs, n_p_dofs, n_u_dofs);
      Kpv.reposition (p_var*n_u_dofs, v_var*n_u_dofs, n_p_dofs, n_v_dofs);
      Kpp.reposition (p_var*n_u_dofs, p_var*n_u_dofs, n_p_dofs, n_p_dofs);
      Kpx.reposition (p_var*n_v_dofs, p_var*n_u_dofs + n_p_dofs , n_p_dofs, n_x_dofs);
      Kpy.reposition (p_var*n_v_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_p_dofs, n_y_dofs);
      #if THREED
      Kpw.reposition (p_var*n_u_dofs, w_var*n_u_dofs, n_p_dofs, n_w_dofs);
      Kpz.reposition (p_var*n_u_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_p_dofs, n_z_dofs);
      #endif

      Kxu.reposition (p_var*n_u_dofs + n_p_dofs, u_var*n_u_dofs, n_x_dofs, n_u_dofs);
      Kxv.reposition (p_var*n_u_dofs + n_p_dofs, v_var*n_u_dofs, n_x_dofs, n_v_dofs);
      Kxp.reposition (p_var*n_u_dofs + n_p_dofs, p_var*n_u_dofs, n_x_dofs, n_p_dofs);
      Kxx.reposition (p_var*n_u_dofs + n_p_dofs, p_var*n_u_dofs + n_p_dofs , n_x_dofs, n_x_dofs);
      Kxy.reposition (p_var*n_u_dofs + n_p_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_x_dofs, n_y_dofs);
      #if THREED
      Kxw.reposition (p_var*n_u_dofs + n_p_dofs, w_var*n_u_dofs, n_x_dofs, n_w_dofs);
      Kxz.reposition (p_var*n_u_dofs + n_p_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_x_dofs, n_z_dofs);
      #endif


      Kyu.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, u_var*n_u_dofs, n_y_dofs, n_u_dofs);
      Kyv.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, v_var*n_u_dofs, n_y_dofs, n_v_dofs);
      Kyp.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, p_var*n_u_dofs, n_y_dofs, n_p_dofs);
      Kyx.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, p_var*n_u_dofs + n_p_dofs , n_y_dofs, n_x_dofs);
      Kyy.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_y_dofs, n_y_dofs);
      #if THREED
      Kyw.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, w_var*n_u_dofs, n_x_dofs, n_w_dofs);
      Kyz.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_x_dofs, n_z_dofs);
      #endif

      #if THREED
      Kzu.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, u_var*n_u_dofs, n_y_dofs, n_u_dofs);
      Kzv.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, v_var*n_u_dofs, n_y_dofs, n_v_dofs);
      Kzp.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, p_var*n_u_dofs, n_y_dofs, n_p_dofs);
      Kzx.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, p_var*n_u_dofs + n_p_dofs , n_y_dofs, n_x_dofs);
      Kzy.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_y_dofs, n_y_dofs);
      Kzw.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, w_var*n_u_dofs, n_x_dofs, n_w_dofs);
      Kzz.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_x_dofs, n_z_dofs);
      #endif



      Fu.reposition (u_var*n_u_dofs, n_u_dofs);
      Fv.reposition (v_var*n_u_dofs, n_v_dofs);
      Fp.reposition (p_var*n_u_dofs, n_p_dofs);
      Fx.reposition (p_var*n_u_dofs + n_p_dofs, n_x_dofs);
      Fy.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, n_y_dofs);
      #if THREED
      Fw.reposition (w_var*n_u_dofs, n_w_dofs);
      Fz.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, n_y_dofs);
      #endif
    
	    std::vector<unsigned int> undefo_index;
		  PoroelasticConfig material(dphi,psi);

		
      // Now we will build the element matrix.
      for (unsigned int qp=0; qp<qrule.n_points(); qp++)
        {       
		  
		  
		  Number   p_solid = 0.;

		  grad_u_mat(0) = grad_u_mat(1) = grad_u_mat(2) = 0;
		
		  for (unsigned int d = 0; d < dim; ++d) {
			std::vector<Number> u_undefo;
			std::vector<Number> u_undefo_ref;

			//Fills the vector di with the global degree of freedom indices for the element. :dof_indicies
			
			

			
			Last_non_linear_soln.get_dof_map().dof_indices(elem, undefo_index,d);
			Last_non_linear_soln.current_local_solution->get(undefo_index, u_undefo);
			reference.current_local_solution->get(undefo_index, u_undefo_ref);

			for (unsigned int l = 0; l != n_u_dofs; l++){
			   grad_u_mat(d).add_scaled(dphi[l][qp], u_undefo[l]+u_undefo_ref[l]); 
			}
		  }
          
		  for (unsigned int l=0; l<n_p_dofs; l++)
		  {
			p_solid += psi[l][qp]*Last_non_linear_soln.current_local_solution->el(dof_indices_p[l]);
		}
		
		Point rX;
		material.init_for_qp(rX,grad_u_mat, p_solid, qp,0, p_solid,es);
		Real J=material.J;
		 Real I_1=material.I_1;
		 Real I_2=material.I_2;
		 Real I_3=material.I_3;
		 RealTensor sigma=material.sigma;
		 
		 av_pressure=av_pressure + p_solid*JxW[qp];
		 
		 /*
		 		 		std::cout<<"grad_u_mat(0)" << grad_u_mat(0) <<std::endl;

		 		std::cout<<" J " << J <<std::endl;

		std::cout<<" sigma " << sigma <<std::endl;
		*/
		 Real sigma_sum_sq=pow(sigma(0,0)*sigma(0,0)+sigma(0,1)*sigma(0,1)+sigma(0,2)*sigma(0,2)+sigma(1,0)*sigma(1,0)+sigma(1,1)*sigma(1,1)+sigma(1,2)*sigma(1,2)+sigma(2,0)*sigma(2,0)+sigma(2,1)*sigma(2,1)+sigma(2,2)*sigma(2,2),0.5);
		 
		// std::cout<<" J " << J <<std::endl;


		 sum_jac_postvars=sum_jac_postvars+JxW[qp];
 

		
		for (unsigned int i=0; i<n_u_dofs; i++){
          Fu(i) += I_1*JxW[qp]*phi[i][qp];
          Fv(i) += I_2*JxW[qp]*phi[i][qp];
          Fw(i) += I_3*JxW[qp]*phi[i][qp];

	        Fx(i) += sigma_sum_sq*JxW[qp]*phi[i][qp];
          Fy(i) += J*JxW[qp]*phi[i][qp];
          Fz(i) += 0*JxW[qp]*phi[i][qp];
    }
    
    
 
		for (unsigned int i=0; i<n_p_dofs; i++){
            Fp(i) += J*JxW[qp]*psi[i][qp];
		}
    
          

          
          
} // end qp





  system.rhs->add_vector(Fe, dof_indices);

  system.matrix->add_matrix (Ke, dof_indices);

} // end of element loop
  
	
    system.matrix->close();
    system.rhs->close();



    std::cout<<"Assemble postvars rhs->l2_norm () "<<system.rhs->l2_norm ()<<std::endl;

		
	 std::cout<<"sum_jac   "<< sum_jac_postvars <<std::endl;
	 
	  std::cout<<"av_pressure   "<< av_pressure/sum_jac_postvars <<std::endl;

  return;
}
Ejemplo n.º 20
0
  vector<Ref<GF256Poly> > ReedSolomonDecoder::
  runEuclideanAlgorithm(Ref<GF256Poly> a,
                        Ref<GF256Poly> b,
                        int R) {
    // Assume a's degree is >= b's
    if (a->getDegree() < b->getDegree()) {
      Ref<GF256Poly> tmp = a;
      a = b;
      b = tmp;
    }
    
    Ref<GF256Poly> rLast(a);
    Ref<GF256Poly> r(b);
    Ref<GF256Poly> sLast(field.getOne());
    Ref<GF256Poly> s(field.getZero());
    Ref<GF256Poly> tLast(field.getZero());
    Ref<GF256Poly> t(field.getOne());
    
    // Run Euclidean algorithm until r's degree is less than R/2
    while (r->getDegree() >= R / 2) {
      Ref<GF256Poly> rLastLast(rLast);
      Ref<GF256Poly> sLastLast(sLast);
      Ref<GF256Poly> tLastLast(tLast);
      rLast = r;
      sLast = s;
      tLast = t;
      
      // Divide rLastLast by rLast, with quotient q and remainder r
      if (rLast->isZero()) {
        // Oops, Euclidean algorithm already terminated?
        throw ReedSolomonException("r_{i-1} was zero");
      }
      r = rLastLast;
      Ref<GF256Poly> q(field.getZero());
      int denominatorLeadingTerm = rLast->getCoefficient(rLast->getDegree());
      int dltInverse = field.inverse(denominatorLeadingTerm);
      while (r->getDegree() >= rLast->getDegree() && !r->isZero()) {
        int degreeDiff = r->getDegree() - rLast->getDegree();
        int scale = field.multiply(r->getCoefficient(r->getDegree()), 
                                   dltInverse);
        q = q->addOrSubtract(field.buildMonomial(degreeDiff, scale));
        r = r->addOrSubtract(rLast->multiplyByMonomial(degreeDiff, scale));
      }
      
      s = q->multiply(sLast)->addOrSubtract(sLastLast);
      t = q->multiply(tLast)->addOrSubtract(tLastLast);
    }
    
    int sigmaTildeAtZero = t->getCoefficient(0);
    if (sigmaTildeAtZero == 0) {
      throw ReedSolomonException("sigmaTilde(0) was zero");
    }
    
    int inverse = field.inverse(sigmaTildeAtZero);
    Ref<GF256Poly> sigma(t->multiply(inverse));
    Ref<GF256Poly> omega(r->multiply(inverse));
    
#ifdef DEBUG
    cout << "t = " << *t << "\n";
    cout << "r = " << *r << "\n";
    cout << "sigma = " << *sigma << "\n";
    cout << "omega = " << *omega << "\n";
#endif
    
    vector<Ref<GF256Poly> > result(2);
    result[0] = sigma;
    result[1] = omega;
    return result;
  }
const Vector&  TwentyEightNodeBrickUP::getResistingForce( )

{

	int i, j, jk, k, k1;

	double xsj;

	static Matrix B(6, 3);

	double volume = 0.;



//	printf("calling getResistingForce()\n");

	resid.Zero();



	//compute basis vectors and local nodal coordinates

	computeBasis( ) ;

	//gauss loop to compute and save shape functions

	for( i = 0; i < nintu; i++ ) {

		// compute Jacobian and global shape functions

		Jacobian3d(i, xsj, 0);

		//volume element to also be saved

		dvolu[i] = wu[i] * xsj ;

		volume += dvolu[i];

	} // end for i

	//printf("volume = %f\n", volume);

	volume = 0.;

	for( i = 0; i < nintp; i++ ) {

		// compute Jacobian and global shape functions

		Jacobian3d(i, xsj, 1);

		//volume element to also be saved

		dvolp[i] = wp[i] * xsj ;

		volume += dvolp[i];

	} // end for i

	//printf("volume = %f\n", volume);



	// Loop over the integration points

	for (i = 0; i < nintu; i++) {



		// Get material stress response

		const Vector &sigma = materialPointers[i]->getStress();



		// Perform numerical integration on internal force

		//P = P + (B^ sigma) * intWt(i)*intWt(j) * detJ;

		//P.addMatrixTransposeVector(1.0, B, sigma, intWt(i)*intWt(j)*detJ);

		for (j = 0; j < nenu; j++) {

			if (j<nenp)

				jk = j*4;

			else

				jk = nenp*4 + (j-nenp)*3;



			B(0,0) = shgu[0][j][i];

			B(0,1) = 0.;

			B(0,2) = 0.;

			B(1,0) = 0.;

			B(1,1) = shgu[1][j][i];

			B(1,2) = 0.;

			B(2,0) = 0.;

			B(2,1) = 0.;

			B(2,2) = shgu[2][j][i];

			B(3,0) = shgu[1][j][i];

			B(3,1) = shgu[0][j][i];

			B(3,2) = 0.;

			B(4,0) = 0.;

			B(4,1) = shgu[2][j][i];

			B(4,2) = shgu[1][j][i];

			B(5,0) = shgu[2][j][i];

			B(5,1) = 0.;

			B(5,2) = shgu[0][j][i];





			for(k = 0; k < 3; k++) {

				for(k1 = 0; k1 < 6; k1++)

					resid(jk+k) += dvolu[i]*(B(k1,k)*sigma(k1));

			}

			// Subtract equiv. body forces from the nodes

			//P = P - (N^ b) * intWt(i)*intWt(j) * detJ;

			//P.addMatrixTransposeVector(1.0, N, b, -intWt(i)*intWt(j)*detJ);

			double r = mixtureRho(i);

			if (applyLoad == 0) {
				resid(jk) -= dvolu[i]*(shgu[3][j][i]*r*b[0]);
				resid(jk+1) -= dvolu[i]*(shgu[3][j][i]*r*b[1]);
				resid(jk+2) -= dvolu[i]*(shgu[3][j][i]*r*b[2]);
			} else {
				resid(jk) -= dvolu[i]*(shgu[3][j][i]*r*appliedB[0]);
				resid(jk+1) -= dvolu[i]*(shgu[3][j][i]*r*appliedB[1]);
				resid(jk+2) -= dvolu[i]*(shgu[3][j][i]*r*appliedB[2]);
			}

		}

	}



	// Subtract fluid body force

	for (j = 0; j < nenp; j++) {

		jk = j*4+3;

		for (i = 0; i < nintp; i++) {
			
			if (applyLoad == 0) {
				resid(jk) += dvolp[i]*rho*(perm[0]*b[0]*shgp[0][j][i] +
							 perm[1]*b[1]*shgp[1][j][i] + perm[2]*b[2]*shgp[2][j][i]);
			} else {
				resid(jk) += dvolp[i]*rho*(perm[0]*appliedB[0]*shgp[0][j][i] +
							 perm[1]*appliedB[1]*shgp[1][j][i] + perm[2]*appliedB[2]*shgp[2][j][i]);
			}

		}

	}



	// Subtract other external nodal loads ... P_res = P_int - P_ext

//	opserr<<"resid before:"<<resid<<endln;



	if (load != 0)

		resid -= *load;



//	opserr<<"resid "<<resid<<endln;



	return resid ;

}
Ejemplo n.º 22
0
void KinZfitter::MakeModel(/*RooWorkspace &w,*/ KinZfitter::FitInput &input, KinZfitter::FitOutput &output) {

     //lep
     RooRealVar pTRECO1_lep("pTRECO1_lep", "pTRECO1_lep", input.pTRECO1_lep, 5, 500);
     RooRealVar pTRECO2_lep("pTRECO2_lep", "pTRECO2_lep", input.pTRECO2_lep, 5, 500);
     RooRealVar pTMean1_lep("pTMean1_lep", "pTMean1_lep", 
                            input.pTRECO1_lep, max(5.0, input.pTRECO1_lep-2*input.pTErr1_lep), input.pTRECO1_lep+2*input.pTErr1_lep);
     RooRealVar pTMean2_lep("pTMean2_lep", "pTMean2_lep", 
                            input.pTRECO2_lep, max(5.0, input.pTRECO2_lep-2*input.pTErr2_lep), input.pTRECO2_lep+2*input.pTErr2_lep);
     RooRealVar pTSigma1_lep("pTSigma1_lep", "pTSigma1_lep", input.pTErr1_lep);
     RooRealVar pTSigma2_lep("pTSigma2_lep", "pTSigma2_lep", input.pTErr2_lep);
     RooRealVar theta1_lep("theta1_lep", "theta1_lep", input.theta1_lep);
     RooRealVar theta2_lep("theta2_lep", "theta2_lep", input.theta2_lep);
     RooRealVar phi1_lep("phi1_lep", "phi1_lep", input.phi1_lep);
     RooRealVar phi2_lep("phi2_lep", "phi2_lep", input.phi2_lep);
     RooRealVar m1("m1", "m1", input.m1);
     RooRealVar m2("m2", "m2", input.m2);

     //gamma
     RooRealVar pTRECO1_gamma("pTRECO1_gamma", "pTRECO1_gamma", input.pTRECO1_gamma, 5, 500);
     RooRealVar pTRECO2_gamma("pTRECO2_gamma", "pTRECO2_gamma", input.pTRECO2_gamma, 5, 500);
     RooRealVar pTMean1_gamma("pTMean1_gamma", "pTMean1_gamma", 
                              input.pTRECO1_gamma, max(0.5, input.pTRECO1_gamma-2*input.pTErr1_gamma), input.pTRECO1_gamma+2*input.pTErr1_gamma);
     RooRealVar pTMean2_gamma("pTMean2_gamma", "pTMean2_gamma", 
                              input.pTRECO2_gamma, max(0.5, input.pTRECO2_gamma-2*input.pTErr2_gamma), input.pTRECO2_gamma+2*input.pTErr2_gamma);
     RooRealVar pTSigma1_gamma("pTSigma1_gamma", "pTSigma1_gamma", input.pTErr1_gamma);
     RooRealVar pTSigma2_gamma("pTSigma2_gamma", "pTSigma2_gamma", input.pTErr2_gamma);
     RooRealVar theta1_gamma("theta1_gamma", "theta1_gamma", input.theta1_gamma);
     RooRealVar theta2_gamma("theta2_gamma", "theta2_gamma", input.theta2_gamma);
     RooRealVar phi1_gamma("phi1_gamma", "phi1_gamma", input.phi1_gamma);
     RooRealVar phi2_gamma("phi2_gamma", "phi2_gamma", input.phi2_gamma);

     //gauss
     RooGaussian gauss1_lep("gauss1_lep", "gauss1_lep", pTRECO1_lep, pTMean1_lep, pTSigma1_lep);
     RooGaussian gauss2_lep("gauss2_lep", "gauss2_lep", pTRECO2_lep, pTMean2_lep, pTSigma2_lep);
     RooGaussian gauss1_gamma("gauss1_gamma", "gauss1_gamma", pTRECO1_gamma, pTMean1_gamma, pTSigma1_gamma);
     RooGaussian gauss2_gamma("gauss2_gamma", "gauss2_gamma", pTRECO2_gamma, pTMean2_gamma, pTSigma2_gamma);


     TString makeE_lep = "TMath::Sqrt((@0*@0)/((TMath::Sin(@1))*(TMath::Sin(@1)))+@2*@2)";
     RooFormulaVar E1_lep("E1_lep", makeE_lep, RooArgList(pTMean1_lep, theta1_lep, m1));  //w.import(E1_lep);
     RooFormulaVar E2_lep("E2_lep", makeE_lep, RooArgList(pTMean2_lep, theta2_lep, m2));  //w.import(E2_lep);

     TString makeE_gamma = "TMath::Sqrt((@0*@0)/((TMath::Sin(@1))*(TMath::Sin(@1))))";
     RooFormulaVar E1_gamma("E1_gamma", makeE_gamma, RooArgList(pTMean1_gamma, theta1_gamma));  //w.import(E1_gamma);
     RooFormulaVar E2_gamma("E2_gamma", makeE_gamma, RooArgList(pTMean2_gamma, theta2_gamma));  //w.import(E2_gamma);

     //dotProduct 3d
     TString dotProduct_3d = "@0*@1*( ((TMath::Cos(@2))*(TMath::Cos(@3)))/((TMath::Sin(@2))*(TMath::Sin(@3)))+(TMath::Cos(@4-@5)))";
     RooFormulaVar p1v3D2("p1v3D2", dotProduct_3d, RooArgList(pTMean1_lep, pTMean2_lep, theta1_lep, theta2_lep, phi1_lep, phi2_lep));
     RooFormulaVar p1v3Dph1("p1v3Dph1", dotProduct_3d, RooArgList(pTMean1_lep, pTMean1_gamma, theta1_lep, theta1_gamma, phi1_lep, phi1_gamma));
     RooFormulaVar p2v3Dph1("p2v3Dph1", dotProduct_3d, RooArgList(pTMean2_lep, pTMean1_gamma, theta2_lep, theta1_gamma, phi2_lep, phi1_gamma));
     RooFormulaVar p1v3Dph2("p1v3Dph2", dotProduct_3d, RooArgList(pTMean1_lep, pTMean2_gamma, theta1_lep, theta2_gamma, phi1_lep, phi2_gamma));
     RooFormulaVar p2v3Dph2("p2v3Dph2", dotProduct_3d, RooArgList(pTMean2_lep, pTMean2_gamma, theta2_lep, theta2_gamma, phi2_lep, phi2_gamma));
     RooFormulaVar ph1v3Dph2("ph1v3Dph2", dotProduct_3d, RooArgList(pTMean1_gamma, pTMean2_gamma, theta1_gamma, theta2_gamma, phi1_gamma, phi2_gamma));

     TString dotProduct_4d = "@0*@1-@2";
     RooFormulaVar p1D2("p1D2", dotProduct_4d, RooArgList(E1_lep, E2_lep, p1v3D2));  //w.import(p1D2);
     RooFormulaVar p1Dph1("p1Dph1", dotProduct_4d, RooArgList(E1_lep, E1_gamma, p1v3Dph1));//  w.import(p1Dph1);
     RooFormulaVar p2Dph1("p2Dph1", dotProduct_4d, RooArgList(E2_lep, E1_gamma, p2v3Dph1)); // w.import(p2Dph1);
     RooFormulaVar p1Dph2("p1Dph2", dotProduct_4d, RooArgList(E1_lep, E2_gamma, p1v3Dph2));  //w.import(p1Dph2);
     RooFormulaVar p2Dph2("p2Dph2", dotProduct_4d, RooArgList(E2_lep, E2_gamma, p2v3Dph2));  //w.import(p2Dph2);
     RooFormulaVar ph1Dph2("ph1Dph2", dotProduct_4d, RooArgList(E1_gamma, E2_gamma, ph1v3Dph2)); // w.import(ph1Dph2);

     RooRealVar bwMean("bwMean", "m_{Z^{0}}", 91.187); //w.import(bwMean);
     RooRealVar bwGamma("bwGamma", "#Gamma", 2.5); 


     RooProdPdf* PDFRelBW;  
     RooFormulaVar* mZ;
     RooGenericPdf* RelBW;

     //mZ
     mZ = new RooFormulaVar("mZ", "TMath::Sqrt(2*@0+@1*@1+@2*@2)", RooArgList(p1D2, m1, m2));
     RelBW = new RooGenericPdf("RelBW","1/( pow(mZ*mZ-bwMean*bwMean,2)+pow(mZ,4)*pow(bwGamma/bwMean,2) )", RooArgSet(*mZ,bwMean,bwGamma) );
     PDFRelBW = new RooProdPdf("PDFRelBW", "PDFRelBW", RooArgList(gauss1_lep, gauss2_lep, *RelBW));     

     if (input.nFsr == 1) {

        mZ = new RooFormulaVar("mZ", "TMath::Sqrt(2*@0+2*@1+2*@2+@3*@3+@4*@4)", RooArgList(p1D2, p1Dph1, p2Dph1, m1, m2));
        RelBW = new RooGenericPdf("RelBW","1/( pow(mZ*mZ-bwMean*bwMean,2)+pow(mZ,4)*pow(bwGamma/bwMean,2) )", RooArgSet(*mZ,bwMean,bwGamma) );
//        PDFRelBW = new RooProdPdf("PDFRelBW", "PDFRelBW", RooArgList(gauss1_lep, gauss2_lep, gauss1_gamma, *RelBW));

        } 

     if (input.nFsr == 2) {

        mZ = new RooFormulaVar("mZ", "TMath::Sqrt(2*@0+2*@1+2*@2+2*@3+2*@4+2*@5+@6*@6+@7*@7)", RooArgList(p1D2,p1Dph1,p2Dph1,p1Dph2,p2Dph2,ph1Dph2, m1, m2));
        RelBW = new RooGenericPdf("RelBW","1/( pow(mZ*mZ-bwMean*bwMean,2)+pow(mZ,4)*pow(bwGamma/bwMean,2) )", RooArgSet(*mZ,bwMean,bwGamma) );
//        PDFRelBW = new RooProdPdf("PDFRelBW", "PDFRelBW", RooArgList(gauss1_lep, gauss2_lep, gauss1_gamma, gauss2_gamma, *RelBW));

        }

     //true shape
     RooRealVar sg("sg", "sg", sgVal_);
     RooRealVar a("a", "a", aVal_);
     RooRealVar n("n", "n", nVal_);

     RooCBShape CB("CB","CB",*mZ,bwMean,sg,a,n);
     RooRealVar f("f","f", fVal_);

     RooRealVar mean("mean","mean",meanVal_);
     RooRealVar sigma("sigma","sigma",sigmaVal_);
     RooRealVar f1("f1","f1",f1Val_);

     RooAddPdf *RelBWxCB;
     RelBWxCB = new RooAddPdf("RelBWxCB","RelBWxCB", *RelBW, CB, f);
     RooGaussian *gauss;
     gauss = new RooGaussian("gauss","gauss",*mZ,mean,sigma);
     RooAddPdf *RelBWxCBxgauss;
     RelBWxCBxgauss = new RooAddPdf("RelBWxCBxgauss","RelBWxCBxgauss", *RelBWxCB, *gauss, f1);

     RooProdPdf *PDFRelBWxCBxgauss;
     PDFRelBWxCBxgauss = new RooProdPdf("PDFRelBWxCBxgauss","PDFRelBWxCBxgauss", 
                                     RooArgList(gauss1_lep, gauss2_lep, *RelBWxCBxgauss) );


    //make fit
    RooArgSet *rastmp;
    rastmp = new RooArgSet(pTRECO1_lep, pTRECO2_lep);
/*
    if(input.nFsr == 1) {
      rastmp = new RooArgSet(pTRECO1_lep, pTRECO2_lep, pTRECO1_gamma);
      }

    if(input.nFsr == 2) {
      rastmp = new RooArgSet(pTRECO1_lep, pTRECO2_lep, pTRECO1_gamma, pTRECO2_gamma);
      }
*/
    RooDataSet* pTs = new RooDataSet("pTs","pTs", *rastmp);
    pTs->add(*rastmp);

    RooFitResult* r;
    if (mass4lRECO_ > 140) {

       r = PDFRelBW->fitTo(*pTs,RooFit::Save(),RooFit::PrintLevel(-1));

       } else {

              r = PDFRelBWxCBxgauss->fitTo(*pTs,RooFit::Save(),RooFit::PrintLevel(-1));

              }
    //save fit result
    const TMatrixDSym& covMatrix = r->covarianceMatrix();
    const RooArgList& finalPars = r->floatParsFinal();

    for (int i=0 ; i<finalPars.getSize(); i++){
 
        TString name = TString(((RooRealVar*)finalPars.at(i))->GetName());
        if(debug_) cout<<"name list of RooRealVar for covariance matrix "<<name<<endl;

    }

    int size = covMatrix.GetNcols();
    output.covMatrixZ.ResizeTo(size,size);
    output.covMatrixZ = covMatrix;
    
    output.pT1_lep = pTMean1_lep.getVal();
    output.pT2_lep = pTMean2_lep.getVal();
    output.pTErr1_lep = pTMean1_lep.getError();
    output.pTErr2_lep = pTMean2_lep.getError();
/*
    if (input.nFsr >= 1) {

       output.pT1_gamma = pTMean1_gamma.getVal();
       output.pTErr1_gamma = pTMean1_gamma.getError();
    
       }

    if (input.nFsr == 2) {

       output.pT2_gamma = pTMean2_gamma.getVal();
       output.pTErr2_gamma = pTMean2_gamma.getError();

       }
*/
    delete rastmp;
    delete pTs;
    delete PDFRelBW;
    delete mZ;
    delete RelBW;
    delete RelBWxCB;
    delete gauss;
    delete RelBWxCBxgauss;
    delete PDFRelBWxCBxgauss;
}
int

TwentyEightNodeBrickUP::getResponse(int responseID, Information &eleInfo)

{

	static Vector stresses(nintu*6);



	if (responseID == 1)

		return eleInfo.setVector(this->getResistingForce());



	else if (responseID == 2)

		return eleInfo.setMatrix(this->getTangentStiff());



    else if (responseID == 3)

        return eleInfo.setMatrix(this->getMass());



    else if (responseID == 4)

        return eleInfo.setMatrix(this->getDamp());



	else if (responseID == 5) {



		// Loop over the integration points

		int cnt = 0;

		for (int i = 0; i < nintu; i++) {

			// Get material stress response

			const Vector &sigma = materialPointers[i]->getStress();

			stresses(cnt++) = sigma(0);

			stresses(cnt++) = sigma(1);

			stresses(cnt++) = sigma(2);

			stresses(cnt++) = sigma(3);

			stresses(cnt++) = sigma(4);

			stresses(cnt++) = sigma(5);

		}

		return eleInfo.setVector(stresses);



	}

	else



		return -1;

}
Ejemplo n.º 24
0
void cMMTP::ContAndBoucheTrou()
{
   int aDist32Close = 6;
   int aNbErod = 6;

   // 1- Quelques fitre morpho de base, pour calculer les points eligibles au bouche-trou
   int aLabelOut = 0;
   //int aLabelIn = 1;
   int aLabelClose = 2;
   int aLabelFront = 3;

   ELISE_COPY(mImMasqInit.all_pts(),mImMasqInit.in(),mImLabel.out());
   ELISE_COPY(mImLabel.border(2),aLabelOut,mImLabel.out());

      // 1.1 calcul des point dans le fermeture
   ELISE_COPY
   (
          select
          (
             mImLabel.all_pts(),
             close_32(mImLabel.in(0),aDist32Close) && (mImLabel.in()==aLabelOut)
          ),
          aLabelClose,
          mImLabel.out()
   );
   ELISE_COPY(mImLabel.border(2),aLabelOut,mImLabel.out());


      // 1.2 erosion de ces points
   Neighbourhood V4 = Neighbourhood::v4();
   Neighbourhood V8 = Neighbourhood::v8();
   Neigh_Rel aRelV4(V4);

   Liste_Pts_U_INT2 aLFront(2);
   ELISE_COPY
   (
          select
          (
             mImLabel.all_pts(),
             (mImLabel.in(0)==aLabelClose) &&  (aRelV4.red_max(mImLabel.in(0)==aLabelOut))
          ),
          aLabelFront,
          mImLabel.out() | aLFront
    );
    for (int aK=0 ; aK<aNbErod ; aK++)
    {
        Liste_Pts_U_INT2 aLNew(2);
        ELISE_COPY
        (
               dilate
               (
                  aLFront.all_pts(),
                  mImLabel.neigh_test_and_set(Neighbourhood::v4(),2,3,20)
               ),
               aLabelFront,
               aLNew
         );
         aLFront = aLNew;
    }
    ELISE_COPY(select(mImLabel.all_pts(),mImLabel.in()==aLabelFront),0,mImLabel.out());

    // Au cas ou on ferait un export premature
    ELISE_COPY(mImMasqFinal.all_pts(),mImLabel.in()!=0,mImMasqFinal.out());

    int aSomMaskF;
    ELISE_COPY(mImMasqFinal.all_pts(),mImLabel.in()==1,sigma(aSomMaskF));
    if (aSomMaskF < 100) return;
    // std::cout << "aSomMaskFaSomMaskF " << aSomMaskF << "\n";
   // 2- Dequantifiication, adaptee au image a trou

       Im2D_REAL4 aProfCont(mSzTiep.x,mSzTiep.y,0.0);
       {
           Im2D_INT2 aPPV = BouchePPV(mImProf,mImLabel.in()==1);

           ElImplemDequantifier aDeq(mSzTiep);
           aDeq.DoDequantif(mSzTiep,aPPV.in());
           ELISE_COPY(aProfCont.all_pts(),aDeq.ImDeqReelle(),aProfCont.out());

           ELISE_COPY(select(aProfCont.all_pts(),mImLabel.in()!=1),0,aProfCont.out());
       }

       
    //Im2D_REAL4 aImInterp(mSzTiep.x,mSzTiep.y);
    TIm2D<REAL4,REAL8> aTInterp(mContBT);

   // 3- Bouchage "fin" des trour par moinde L2
          // 3.1 Valeur initial

                 // Filtrage gaussien
    Fonc_Num aFMasq = (mImLabel.in(0)==1);
    Fonc_Num aFProf = (aProfCont.in(0) * aFMasq);
    for (int aK=0 ; aK<3 ; aK++)
    {
          aFMasq = rect_som(aFMasq,1) /9.0;
          aFProf = rect_som(aFProf,1) /9.0;
    }

    ELISE_COPY
    (
         mContBT.all_pts(),
         aFProf / Max(aFMasq,1e-9),
         mContBT.out()
    );
                 // On remet la valeur init au point ayant un valeur propre
    ELISE_COPY
    (
         select(mContBT.all_pts(),mImLabel.in()==1),
         aProfCont.in(),
         mContBT.out()
    );
             // Et rien en dehors de l'image
    ELISE_COPY
    (
         select(mContBT.all_pts(),mImLabel.in()==0),
         0,
         mContBT.out()
    );
  
  
  
  
       // 3.2 Iteration pour regulariser les points interpoles
    {
         std::vector<Pt2di> aVInterp;
         {
            Pt2di aP;
            for (aP.x=0 ; aP.x<mSzTiep.x ; aP.x++)
            {
                for (aP.y=0 ; aP.y<mSzTiep.y ; aP.y++)
                {
                   if (mTLab.get(aP)==aLabelClose)
                     aVInterp.push_back(aP);
                }
            }
         }

         for (int aKIter=0 ; aKIter<20 ; aKIter++)
         {
              std::vector<double> aVVals;
              for (int aKP=0 ; aKP<int(aVInterp.size()) ; aKP++)
              {
                   double aSom=0;
                   double aSomPds = 0;
                   Pt2di aPK = aVInterp[aKP];
                   for (int aKV=0 ; aKV<9 ; aKV++)
                   {
                         Pt2di aVois = aPK+TAB_9_NEIGH[aKV];
                         if (mTLab.get(aVois)!=0)
                         {
                             int aPds = PdsGaussl9NEIGH[aKV];
                             aSom +=  aTInterp.get(aVois) * aPds;
                             aSomPds += aPds;
                         }
                   }
                   ELISE_ASSERT(aSomPds!=0,"Assert P!=0");
                   aVVals.push_back(aSom/aSomPds);
              }
              for (int aKP=0 ; aKP<int(aVInterp.size()) ; aKP++)
              {
                 aTInterp.oset(aVInterp[aKP],aVVals[aKP]);
              }
         }
    }
    
/*
*/

#ifdef ELISE_X11
           if(0 && TheWTiePCor)
           {

              ELISE_COPY
              (
                   mImLabel.all_pts(),
                   mContBT.in()*7,
                   TheWTiePCor->ocirc()
              );
              TheWTiePCor->clik_in();
              
              ELISE_COPY
              (
                  mImLabel.all_pts(),
                  nflag_close_sym(flag_front4(mImLabel.in(0)==1)),
                  TheWTiePCor->out_graph(Line_St(TheWTiePCor->pdisc()(P8COL::black)))
              );
              TheWTiePCor->clik_in();

              ELISE_COPY
              (
                  mImLabel.all_pts(),
                  mImLabel.in(0),
                  TheWTiePCor->odisc()
              );
              TheWTiePCor->clik_in();
              ELISE_COPY
              (
                  mImLabel.all_pts(),
                  mImMasqFinal.in(0),
                  TheWTiePCor->odisc()
              );
              TheWTiePCor->clik_in();
           }
#endif
}
int main(int argc, char **argv) {
	clock_t t1, t2;
	t1 = clock();

	IloEnv env;
	IloModel model(env);
	IloCplex cplex(model);

	/************************** Defining the parameters ************************************/
	IloInt N;							//No. of nodes
	IloInt M;							//No. of calls
	Num2DMatrix links(env);				//Defines the topology of the network
	IloNumArray call_demand(env);		//link bandwidth requirement of each call
	IloNumArray call_revenue(env);		//revenue generated from the call
	IloNumArray call_origin(env);		//origin node index of each call
	IloNumArray call_destination(env);	//destination node index of each call
	Num2DMatrix Q(env);					//Bandwidth capacity of each link
	Num2DMatrix sigma(env);				//Standard deviation of service times on link (i,j)
	Num2DMatrix cv(env);				//coefficient of variation of service times on the link (i,j)
	IloNum C;							//Unit queueing delay cost per unit time
	IloNumArray R_approx_init(env);

	ifstream fin;
	const char* filename = "BPP_data_sample - Copy.txt";
	if (argc > 1)
		filename = argv[1];
		
	fin.open(filename);
	//fin.open("BPP_10node_navneet.txt");
	fin >> links >> call_origin >> call_destination >> call_demand >>
		call_revenue >> Q >> cv >> R_approx_init >> C ;
	cout << "Reading Data from the file - "<<filename<<endl;

	N = links.getSize();
	M = call_origin.getSize();

	IloInt H = R_approx_init.getSize();
	Num3DMatrix R_approx(env, N);			//The tangential linear function approximation to R.
	for (IloInt i=0; i<N; i++) {
		R_approx[i] = Num2DMatrix(env, N);
		for (IloInt j=0; j<N; j++) {
			R_approx[i][j] = IloNumArray(env, H);
			for (IloInt h=0; h<H; h++)
				R_approx[i][j][h] = R_approx_init[h];
		}
	}

	/************************** Defining the parameters ENDS ************************************/

	/************* Defining the variables defined in the model formulation **********************/
	IloNumVarArray Y(env, M, 0, 1, ILOINT); //Variable to define whether a call m is routed or not
	IloNumArray Y_sol(env, M); //Solution values

	NumVar3DMatrix X(env, N); //Variable to define whether a call m is routed along path i-j
	Num3DMatrix X_sol(env, N);
	for (IloInt i=0; i<N; i++) {
		X[i] = NumVar2DMatrix(env, N);
		X_sol[i] = Num2DMatrix(env, N);
		for (IloInt j=0; j<N; j++) {
			X[i][j] = IloNumVarArray(env, M, 0, 1, ILOINT);
			X_sol[i][j] = IloNumArray(env, M);
		}
	}

	NumVar3DMatrix W(env, N); //Variable to define whether a call m is routed along path i-j
	for (IloInt i=0; i<N; i++) {
		W[i] = NumVar2DMatrix(env, N);
		for (IloInt j=0; j<N; j++)
			W[i][j] = IloNumVarArray(env, M, 0, 1, ILOINT);
	}

	NumVar2DMatrix R(env, (IloInt)N); //The linearization Variable
	for (IloInt i=0; i<N; i++)
		R[i] = IloNumVarArray(env, (IloInt)N, 0, IloInfinity, ILOFLOAT);
	
	/************* Defining the variables defined in the model formulation ENDS *****************/

	/**************************** Defining the Constraints *******************************/
	// Constraint #1 : Flow Conservation Constraint
	for (IloInt m=0; m<M; m++) {
		for (IloInt i=0; i<N; i++) {
			IloExpr constraint1(env);
			for (IloInt j=0; j<N; j++) {
				if (links[i][j] == 1)
					constraint1 += W[i][j][m];
			}
			for (IloInt j=0; j<N; j++) {
				if (links[j][i] == 1)
					constraint1 += -W[j][i][m];
			}
			
			if (i == call_origin[m])
				model.add(constraint1 == Y[m]);
			else if (i == call_destination[m])
				model.add(constraint1 == -Y[m]);
			else 
				model.add(constraint1 == 0);

			constraint1.end();
		}
	}

	// Constraint #2 :
	for (IloInt m=0; m<M; m++) {
		for (IloInt i=0; i<N; i++) {			
			for (IloInt j=0; j<N; j++) {
				if (links[i][j] == 1)
					model.add(W[i][j][m] + W[j][i][m] <= X[i][j][m]);					
			}			
		}
	}

	// Constraint #3 : Link Capacity Constraint
	for (IloInt i=0; i<N; i++) {
		for (IloInt j=i+1; j<N; j++) {
			if (links[i][j] == 1) {
				IloExpr constraint3(env);
				for (IloInt m=0; m<M; m++)
					constraint3 += call_demand[m]*X[i][j][m];
				model.add(constraint3 <= Q[i][j]);
				constraint3.end();
			}
		}
	}
	
	// Constraint #4 : Defining the constraint for initial values of R_approx, 
	//				   Cuts must be added during the iterations whenever the values are updated
	for (IloInt i=0; i<N; i++) {
		for (IloInt j=i+1; j<N; j++) {	
			if (links[i][j] == 1) {
				for (IloInt h=0; h<H; h++) {
					IloExpr constraint4_lhs(env);
					IloNum constraint4_rhs = 0;
					for (IloInt m=0; m<M; m++)
						constraint4_lhs += call_demand[m]*X[i][j][m];

					constraint4_lhs -= (Q[i][j]/((1+R_approx[i][j][h])*(1+R_approx[i][j][h])))*R[i][j];
					constraint4_rhs = Q[i][j]*((R_approx[i][j][h]/(1+R_approx[i][j][h])) *
											(R_approx[i][j][h]/(1+R_approx[i][j][h])));
					model.add(constraint4_lhs <= constraint4_rhs);
					constraint4_lhs.end();
				}
			}
		}
	}

	/************************** Defining the Constraints ENDS ****************************/

	/************************ Defining the Objective Function ****************************/
	IloExpr Objective(env);
	IloExpr Obj_expr1(env);
	IloExpr Obj_expr2(env);
	
	for (IloInt m=0; m<M; m++)
		Obj_expr1 += call_revenue[m]*Y[m];

	for (IloInt i=0; i<N; i++) {
		for (IloInt j=i+1; j<N; j++) {
			if (links[i][j] == 1) {
				Obj_expr2 += (1+cv[i][j] * cv[i][j])*R[i][j];
				for (IloInt m=0; m<M; m++) 
					Obj_expr2 += ((1-cv[i][j] * cv[i][j])/Q[i][j])*call_demand[m]*X[i][j][m];
			}
		}
	}
	Objective += Obj_expr1 - 0.5*C*Obj_expr2;
	model.add(IloMaximize(env, Objective));
	//model.add(IloMinimize(env, -Objective));

	Objective.end();
	Obj_expr1.end();
	Obj_expr2.end();

	/********************** Defining the Objective Function ENDS **************************/

	IloNum eps = cplex.getParam(IloCplex::EpInt);

	IloNum UB = IloInfinity;
	IloNum LB = -IloInfinity;

	/***************** Solve ***********************/
	do {
		cplex.setParam(IloCplex::MIPInterval, 5);
		cplex.setParam(IloCplex::NodeFileInd ,2);
		cplex.setOut(env.getNullStream());

		cplex.exportModel("BPP_model.lp");

		if(!cplex.solve()) {
			cout << "Infeasible"<<endl;
			system("pause");
		}
		else {
			for (IloInt m=0; m<M; m++) {
				if (cplex.getValue(Y[m]) > eps) {
					cout << "Call(m) = "<<m+1<<" : "<<call_origin[m]+1<<" --> "<<call_destination[m]+1
						<<"; demand = "<<call_demand[m]<<endl;
					cout << "Path : ";
					for (IloInt i=0; i<N; i++) {
						for (IloInt j=i+1; j<N; j++) {
							if (links[i][j] == 1) {
								if (cplex.getValue(X[i][j][m]) > eps) {
									X_sol[i][j][m] = 1;
									cout <<i+1<<"-"<<j+1<<"; ";
								}
							}
						}
					}
					cout << endl << endl;
				}				
			}		

			//system("pause");
		}

		UB = min(UB, cplex.getObjValue());

		IloNum lbound = 0;
		for (IloInt m=0; m<M; m++) 
			if(cplex.getValue(Y[m]) > eps)
				lbound += call_revenue[m];

		for (IloInt i=0; i<N; i++) {
			for (IloInt j=i+1; j<N; j++) {
				if (links[i][j] == 1) {
					IloNum lbound_temp1 = 0;
					IloNum lbound_temp2 = 0;
					for (IloInt m=0; m<M; m++)
						lbound_temp1 += call_demand[m]*X_sol[i][j][m];
					lbound_temp2 = 0.5*(1+cv[i][j]*cv[i][j]) * (lbound_temp1*lbound_temp1) / (Q[i][j]*(Q[i][j]-lbound_temp1));
					lbound_temp2 += lbound_temp1 / Q[i][j];

					lbound -= C*lbound_temp2;
				}
			}
		}

		LB = max(LB, lbound);
		
		Num2DMatrix R_approx_new(env, N);
		for (IloInt i=0; i<N; i++)
			R_approx_new[i] = IloNumArray(env, N);

		for (IloInt i=0; i<N; i++) {			
			for (IloInt j=i+1; j<N; j++) {	
				if (links[i][j] == 1) {
					IloExpr cut_lhs(env);
					IloNum cut_rhs = 0;		

					IloNum cut_temp = 0;
					for (IloInt m=0; m<M; m++) {
						cut_temp += call_demand[m]*X_sol[i][j][m];
					}

					R_approx_new[i][j] = cut_temp / (Q[i][j] - cut_temp);
					//cout << "R_approx_new = "<<R_approx_new<<endl;
										
					for (IloInt m=0; m<M; m++)
						cut_lhs += call_demand[m]*X[i][j][m];					

					cut_lhs -= (Q[i][j]/((1+R_approx_new[i][j])*(1+R_approx_new[i][j])))*R[i][j];
					cut_rhs = Q[i][j]*((R_approx_new[i][j]/(1+R_approx_new[i][j])) *
												(R_approx_new[i][j]/(1+R_approx_new[i][j])));

					model.add(cut_lhs <= cut_rhs);
					cut_lhs.end();
				}				
			}
		}

		cout << "UB = "<<UB<<endl;
		cout << "LB = "<<LB<<endl;
		cout << "Gap (%) = "<<(UB-LB)*100/LB<<endl;
		//system("pause");

	}while ((UB-LB)/UB > eps);
	t2 = clock();
	float secs = (float)t2 - (float)t1;
	secs = secs / CLOCKS_PER_SEC;
	cout << "CPUTIME = "<<secs <<endl<<endl;
}
Ejemplo n.º 26
0
/***********************************************************************//**
 * @brief Return maximum model radius (in radians)
 *
 * Returns \f$5 \sigma\f$ as approximate edge of the Gaussian. This limit
 * is of course arbitrary, but allows to limit the integration region for
 * response computation.
 ***************************************************************************/
double GModelSpatialRadialGauss::theta_max(void) const
{
    // Return value
    return (sigma() * gammalib::deg2rad * 5.0);
}
Ejemplo n.º 27
0
bool Elasticity::evalSol (Vector& s, const Vectors& eV, const FiniteElement& fe,
                          const Vec3& X, bool toLocal, Vec3* pdir) const
{
  if (eV.empty())
  {
    std::cerr <<" *** Elasticity::evalSol: No solutions vector."<< std::endl;
    return false;
  }
  else if (!eV.front().empty() && eV.front().size() != fe.dNdX.rows()*nsd)
  {
    std::cerr <<" *** Elasticity::evalSol: Invalid displacement vector."
	      <<"\n     size(eV) = "<< eV.front().size() <<"   size(dNdX) = "
	      << fe.dNdX.rows() <<","<< fe.dNdX.cols() << std::endl;
    return false;
  }

  // Evaluate the deformation gradient, dUdX, and/or the strain tensor, eps
  Matrix Bmat;
  Tensor dUdX(nDF);
  SymmTensor eps(nsd,axiSymmetry);
  if (!this->kinematics(eV.front(),fe.N,fe.dNdX,X.x,Bmat,dUdX,eps))
    return false;

  // Add strains due to temperature expansion, if any
  double epsT = this->getThermalStrain(eV.back(),fe.N,X);
  if (epsT != 0.0) eps -= epsT;

  // Calculate the stress tensor through the constitutive relation
  Matrix Cmat;
  SymmTensor sigma(nsd, axiSymmetry || material->isPlaneStrain()); double U;
  if (!material->evaluate(Cmat,sigma,U,fe,X,dUdX,eps))
    return false;
  else if (epsT != 0.0 && nsd == 2 && material->isPlaneStrain())
    sigma(3,3) -= material->getStiffness(X)*epsT;

  Vec3 p;
  bool havePval = false;
  if (toLocal && wantPrincipalStress)
  {
    // Calculate principal stresses and associated direction vectors
    if (sigma.size() == 4)
    {
      SymmTensor tmp(2); tmp = sigma; // discard the sigma_zz component
      havePval = pdir ? tmp.principal(p,pdir,2) : tmp.principal(p);
    }
    else
      havePval = pdir ? sigma.principal(p,pdir,2) : sigma.principal(p);

    // Congruence transformation to local coordinate system at current point
    if (locSys) sigma.transform(locSys->getTmat(X));
  }

  s = sigma;

  if (toLocal)
    s.push_back(sigma.vonMises());

  if (havePval)
  {
    s.push_back(p.x);
    s.push_back(p.y);
    if (sigma.dim() == 3)
      s.push_back(p.z);
  }

  return true;
}
Ejemplo n.º 28
-1
 double get_new_prediction(TruncatedSeq* seq) {
   return MAX2(seq->davg() + sigma() * seq->dsd(),
               seq->davg() * confidence_factor(seq->num()));
 }
Ejemplo n.º 29
-1
int KinZfitter::PerZ1Likelihood(double & l1, double & l2, double & lph1, double & lph2)
{

    l1= 1.0; l2 = 1.0;
    lph1 = 1.0; lph2 = 1.0;

    if(debug_) cout<<"start Z refit"<<endl;

    TLorentzVector Z1_1 = p4sZ1_[0]; TLorentzVector Z1_2 = p4sZ1_[1];

    double RECOpT1 = Z1_1.Pt(); double RECOpT2 = Z1_2.Pt();
    double pTerrZ1_1 = pTerrsZ1_[0]; double pTerrZ1_2 = pTerrsZ1_[1];

    if(debug_)cout<<"pT1 "<<RECOpT1<<" pTerrZ1_1 "<<pTerrZ1_1<<endl;
    if(debug_)cout<<"pT2 "<<RECOpT2<<" pTerrZ1_2 "<<pTerrZ1_2<<endl;

    //////////////

    TLorentzVector Z1_ph1, Z1_ph2;
    double pTerrZ1_ph1, pTerrZ1_ph2;
    double RECOpTph1, RECOpTph2;

    TLorentzVector nullFourVector(0, 0, 0, 0);
    Z1_ph1=nullFourVector; Z1_ph2=nullFourVector;
    RECOpTph1 = 0; RECOpTph2 = 0;
    pTerrZ1_ph1 = 0; pTerrZ1_ph2 = 0;

    if(p4sZ1ph_.size()>=1){

      Z1_ph1 = p4sZ1ph_[0]; pTerrZ1_ph1 = pTerrsZ1ph_[0];
      RECOpTph1 = Z1_ph1.Pt();
      if(debug_) cout<<"put in Z1 fsr photon 1 pT "<<RECOpTph1<<" pT err "<<pTerrZ1_ph1<<endl; 
    }
    if(p4sZ1ph_.size()==2){
      //if(debug_) cout<<"put in Z1 fsr photon 2"<<endl;
      Z1_ph2 = p4sZ1ph_[1]; pTerrZ1_ph2 = pTerrsZ1ph_[1];
      RECOpTph2 = Z1_ph2.Pt();     
    }

    RooRealVar* pT1RECO = new RooRealVar("pT1RECO","pT1RECO", RECOpT1, 5, 500);
    RooRealVar* pT2RECO = new RooRealVar("pT2RECO","pT2RECO", RECOpT2, 5, 500);
   
    double RECOpT1min = max(5.0, RECOpT1-2*pTerrZ1_1);
    double RECOpT2min = max(5.0, RECOpT2-2*pTerrZ1_2);

    RooRealVar* pTph1RECO = new RooRealVar("pTph1RECO","pTph1RECO", RECOpTph1, 5, 500);
    RooRealVar* pTph2RECO = new RooRealVar("pTph2RECO","pTph2RECO", RECOpTph2, 5, 500);

    double RECOpTph1min = max(0.5, RECOpTph1-2*pTerrZ1_ph1);
    double RECOpTph2min = max(0.5, RECOpTph2-2*pTerrZ1_ph2);

    // observables pT1,2,ph1,ph2
    RooRealVar* pT1 = new RooRealVar("pT1", "pT1FIT", RECOpT1, RECOpT1min, RECOpT1+2*pTerrZ1_1 );
    RooRealVar* pT2 = new RooRealVar("pT2", "pT2FIT", RECOpT2, RECOpT2min, RECOpT2+2*pTerrZ1_2 );

    RooRealVar* m1 = new RooRealVar("m1","m1", Z1_1.M());
    RooRealVar* m2 = new RooRealVar("m2","m2", Z1_2.M());

    if(debug_) cout<<"m1 "<<m1->getVal()<<" m2 "<<m2->getVal()<<endl;

    double Vtheta1, Vphi1, Vtheta2, Vphi2;
    Vtheta1 = (Z1_1).Theta(); Vtheta2 = (Z1_2).Theta();
    Vphi1 = (Z1_1).Phi(); Vphi2 = (Z1_2).Phi();

    RooRealVar* theta1 = new RooRealVar("theta1","theta1",Vtheta1);
    RooRealVar* phi1   = new RooRealVar("phi1","phi1",Vphi1);
    RooRealVar* theta2 = new RooRealVar("theta2","theta2",Vtheta2);
    RooRealVar* phi2   = new RooRealVar("phi2","phi2",Vphi2);

    // dot product to calculate (p1+p2+ph1+ph2).M()
    RooFormulaVar E1("E1","TMath::Sqrt((@0*@0)/((TMath::Sin(@1))*(TMath::Sin(@1)))+@2*@2)",
                          RooArgList(*pT1,*theta1,*m1));
    RooFormulaVar E2("E2","TMath::Sqrt((@0*@0)/((TMath::Sin(@1))*(TMath::Sin(@1)))+@2*@2)",
                          RooArgList(*pT2,*theta2,*m2));
    if(debug_) cout<<"E1 "<<E1.getVal()<<"; E2 "<<E2.getVal()<<endl;

    /////

    RooRealVar* pTph1 = new RooRealVar("pTph1", "pTph1FIT", RECOpTph1, RECOpTph1min, RECOpTph1+2*pTerrZ1_ph1 );
    RooRealVar* pTph2 = new RooRealVar("pTph2", "pTph2FIT", RECOpTph2, RECOpTph2min, RECOpTph2+2*pTerrZ1_ph2 );

    double Vthetaph1, Vphiph1, Vthetaph2, Vphiph2;
    Vthetaph1 = (Z1_ph1).Theta(); Vthetaph2 = (Z1_ph2).Theta();
    Vphiph1 = (Z1_ph1).Phi(); Vphiph2 = (Z1_ph2).Phi();

    RooRealVar* thetaph1 = new RooRealVar("thetaph1","thetaph1",Vthetaph1);
    RooRealVar* phiph1   = new RooRealVar("phiph1","phiph1",Vphiph1);
    RooRealVar* thetaph2 = new RooRealVar("thetaph2","thetaph2",Vthetaph2);
    RooRealVar* phiph2   = new RooRealVar("phiph2","phi2",Vphiph2);

    RooFormulaVar Eph1("Eph1","TMath::Sqrt((@0*@0)/((TMath::Sin(@1))*(TMath::Sin(@1))))", 
                              RooArgList(*pTph1,*thetaph1));
    RooFormulaVar Eph2("Eph2","TMath::Sqrt((@0*@0)/((TMath::Sin(@1))*(TMath::Sin(@1))))", 
                              RooArgList(*pTph2,*thetaph2));

    //// dot products of 4-vectors

    // 3-vector DOT
    RooFormulaVar* p1v3D2 = new RooFormulaVar("p1v3D2",
         "@0*@1*( ((TMath::Cos(@2))*(TMath::Cos(@3)))/((TMath::Sin(@2))*(TMath::Sin(@3)))+(TMath::Cos(@4-@5)))",
         RooArgList(*pT1,*pT2,*theta1,*theta2,*phi1,*phi2));    
    if(debug_) cout<<"p1 DOT p2 is "<<p1v3D2->getVal()<<endl;
    // 4-vector DOT metric 1 -1 -1 -1
    RooFormulaVar p1D2("p1D2","@0*@1-@2",RooArgList(E1,E2,*p1v3D2));

    //lep DOT fsrPhoton1

    // 3-vector DOT
    RooFormulaVar* p1v3Dph1 = new RooFormulaVar("p1v3Dph1",
         "@0*@1*( (TMath::Cos(@2)*TMath::Cos(@3))/(TMath::Sin(@2)*TMath::Sin(@3))+TMath::Cos(@4-@5))",
         RooArgList(*pT1,*pTph1,*theta1,*thetaph1,*phi1,*phiph1));

    // 4-vector DOT metric 1 -1 -1 -1
    RooFormulaVar p1Dph1("p1Dph1","@0*@1-@2",RooArgList(E1,Eph1,*p1v3Dph1));

    // 3-vector DOT
    RooFormulaVar* p2v3Dph1 = new RooFormulaVar("p2v3Dph1",
         "@0*@1*( (TMath::Cos(@2)*TMath::Cos(@3))/(TMath::Sin(@2)*TMath::Sin(@3))+TMath::Cos(@4-@5))",
         RooArgList(*pT2,*pTph1,*theta2,*thetaph1,*phi2,*phiph1));
    // 4-vector DOT metric 1 -1 -1 -1
    RooFormulaVar p2Dph1("p2Dph1","@0*@1-@2",RooArgList(E2,Eph1,*p2v3Dph1));

    // lep DOT fsrPhoton2 

    // 3-vector DOT
    RooFormulaVar* p1v3Dph2 = new RooFormulaVar("p1v3Dph2",
         "@0*@1*( (TMath::Cos(@2)*TMath::Cos(@3))/(TMath::Sin(@2)*TMath::Sin(@3))+TMath::Cos(@4-@5))",
         RooArgList(*pT1,*pTph2,*theta1,*thetaph2,*phi1,*phiph2));

    // 4-vector DOT metric 1 -1 -1 -1
    RooFormulaVar p1Dph2("p1Dph2","@0*@1-@2",RooArgList(E1,Eph2,*p1v3Dph2));

    // 3-vector DOT
    RooFormulaVar* p2v3Dph2 = new RooFormulaVar("p2v3Dph2",
         "@0*@1*( (TMath::Cos(@2)*TMath::Cos(@3))/(TMath::Sin(@2)*TMath::Sin(@3))+TMath::Cos(@4-@5))",
         RooArgList(*pT2,*pTph2,*theta2,*thetaph2,*phi2,*phiph2));
    // 4-vector DOT metric 1 -1 -1 -1
    RooFormulaVar p2Dph2("p2Dph2","@0*@1-@2",RooArgList(E2,Eph2,*p2v3Dph2));

    // fsrPhoton1 DOT fsrPhoton2

    // 3-vector DOT
    RooFormulaVar* ph1v3Dph2 = new RooFormulaVar("ph1v3Dph2",
         "@0*@1*( (TMath::Cos(@2)*TMath::Cos(@3))/(TMath::Sin(@2)*TMath::Sin(@3))+TMath::Cos(@4-@5))",
         RooArgList(*pTph1,*pTph2,*thetaph1,*thetaph2,*phiph1,*phiph2));    
    // 4-vector DOT metric 1 -1 -1 -1
    RooFormulaVar ph1Dph2("ph1Dph2","@0*@1-@2",RooArgList(Eph1,Eph2,*ph1v3Dph2));

    // mZ1

    RooFormulaVar* mZ1;
    mZ1 = new RooFormulaVar("mZ1","TMath::Sqrt(2*@0+@1*@1+@2*@2)",RooArgList(p1D2,*m1,*m2));
    if(p4sZ1ph_.size()==1)
      mZ1 = new RooFormulaVar("mZ1","TMath::Sqrt(2*@0+2*@1+2*@2+@3*@3+@4*@4)",
                                    RooArgList(p1D2, p1Dph1, p2Dph1, *m1,*m2));
    if(p4sZ1ph_.size()==2)
      mZ1 = new RooFormulaVar("mZ1","TMath::Sqrt(2*@0+2*@1+2*@2+2*@3+2*@4+2*@5+@6*@6+@7*@7)",
                              RooArgList(p1D2,p1Dph1,p2Dph1,p1Dph2,p2Dph2,ph1Dph2, *m1,*m2));

    if(debug_) cout<<"mZ1 is "<<mZ1->getVal()<<endl;

    // pTerrs, 1,2,ph1,ph2
    RooRealVar sigmaZ1_1("sigmaZ1_1", "sigmaZ1_1", pTerrZ1_1);
    RooRealVar sigmaZ1_2("sigmaZ1_2", "sigmaZ1_2", pTerrZ1_2);

    RooRealVar sigmaZ1_ph1("sigmaZ1_ph1", "sigmaZ1_ph1", pTerrZ1_ph1);
    RooRealVar sigmaZ1_ph2("sigmaZ1_ph2", "sigmaZ1_ph2", pTerrZ1_ph2);

    // resolution for decay products
    RooGaussian gauss1("gauss1","gaussian PDF", *pT1RECO, *pT1, sigmaZ1_1);
    RooGaussian gauss2("gauss2","gaussian PDF", *pT2RECO, *pT2, sigmaZ1_2);

    RooGaussian gaussph1("gaussph1","gaussian PDF", *pTph1RECO, *pTph1, sigmaZ1_ph1);
    RooGaussian gaussph2("gaussph2","gaussian PDF", *pTph2RECO, *pTph2, sigmaZ1_ph2);

    RooRealVar bwMean("bwMean", "m_{Z^{0}}", 91.187);
    RooRealVar bwGamma("bwGamma", "#Gamma", 2.5);

    RooRealVar sg("sg", "sg", sgVal_);
    RooRealVar a("a", "a", aVal_);
    RooRealVar n("n", "n", nVal_);

    RooCBShape CB("CB","CB",*mZ1,bwMean,sg,a,n);
    RooRealVar f("f","f", fVal_);

    RooRealVar mean("mean","mean",meanVal_);
    RooRealVar sigma("sigma","sigma",sigmaVal_);
    RooRealVar f1("f1","f1",f1Val_);

    RooGenericPdf RelBW("RelBW","1/( pow(mZ1*mZ1-bwMean*bwMean,2)+pow(mZ1,4)*pow(bwGamma/bwMean,2) )", RooArgSet(*mZ1,bwMean,bwGamma) );

    RooAddPdf RelBWxCB("RelBWxCB","RelBWxCB", RelBW, CB, f);
    RooGaussian gauss("gauss","gauss",*mZ1,mean,sigma);
    RooAddPdf RelBWxCBxgauss("RelBWxCBxgauss","RelBWxCBxgauss", RelBWxCB, gauss, f1);

    RooProdPdf *PDFRelBWxCBxgauss;
    PDFRelBWxCBxgauss = new RooProdPdf("PDFRelBWxCBxgauss","PDFRelBWxCBxgauss", 
                                     RooArgList(gauss1, gauss2, RelBWxCBxgauss) );
    if(p4sZ1ph_.size()==1)    
      PDFRelBWxCBxgauss = new RooProdPdf("PDFRelBWxCBxgauss","PDFRelBWxCBxgauss", 
                                     RooArgList(gauss1, gauss2, gaussph1, RelBWxCBxgauss) );
    if(p4sZ1ph_.size()==2)
      PDFRelBWxCBxgauss = new RooProdPdf("PDFRelBWxCBxgauss","PDFRelBWxCBxgauss", 
                                     RooArgList(gauss1, gauss2, gaussph1, gaussph2, RelBWxCBxgauss) );

    // observable set
    RooArgSet *rastmp;
      rastmp = new RooArgSet(*pT1RECO,*pT2RECO);
    if(p4sZ1ph_.size()==1)
      rastmp = new RooArgSet(*pT1RECO,*pT2RECO,*pTph1RECO);
    if(p4sZ1ph_.size()>=2)
      rastmp = new RooArgSet(*pT1RECO,*pT2RECO,*pTph1RECO,*pTph2RECO);

    RooDataSet* pTs = new RooDataSet("pTs","pTs", *rastmp);
    pTs->add(*rastmp); 

    //RooAbsReal* nll;
    //nll = PDFRelBWxCBxgauss->createNLL(*pTs);
    //RooMinuit(*nll).migrad();

    RooFitResult* r = PDFRelBWxCBxgauss->fitTo(*pTs,RooFit::Save(),RooFit::PrintLevel(-1));
    const TMatrixDSym& covMatrix = r->covarianceMatrix();
   
    const RooArgList& finalPars = r->floatParsFinal();
    for (int i=0 ; i<finalPars.getSize(); i++){
        TString name = TString(((RooRealVar*)finalPars.at(i))->GetName());

        if(debug_) cout<<"name list of RooRealVar for covariance matrix "<<name<<endl;

    }

    int size = covMatrix.GetNcols();
    //TMatrixDSym covMatrixTest_(size);
    covMatrixZ1_.ResizeTo(size,size);
    covMatrixZ1_ = covMatrix;   

    if(debug_) cout<<"save the covariance matrix"<<endl;
    
    l1 = pT1->getVal()/RECOpT1; l2 = pT2->getVal()/RECOpT2;
    double pTerrZ1REFIT1 = pT1->getError(); double pTerrZ1REFIT2 = pT2->getError();

    pTerrsZ1REFIT_.push_back(pTerrZ1REFIT1);
    pTerrsZ1REFIT_.push_back(pTerrZ1REFIT2);

    if(p4sZ1ph_.size()>=1){

      if(debug_) cout<<"set refit result for Z1 fsr photon 1"<<endl;

      lph1 = pTph1->getVal()/RECOpTph1;
      double pTerrZ1phREFIT1 = pTph1->getError();
      if(debug_) cout<<"scale "<<lph1<<" pterr "<<pTerrZ1phREFIT1<<endl;  
   
      pTerrsZ1phREFIT_.push_back(pTerrZ1phREFIT1);

    } 
    if(p4sZ1ph_.size()==2){

      lph2 = pTph2->getVal()/RECOpTph2;
      double pTerrZ1phREFIT2 = pTph2->getError();
      pTerrsZ1phREFIT_.push_back(pTerrZ1phREFIT2);

    }

    //delete nll;
    delete r;
    delete mZ1;
    delete pT1; delete pT2; delete pTph1; delete pTph2;
    delete pT1RECO; delete pT2RECO; delete pTph1RECO; delete pTph2RECO;
    delete ph1v3Dph2; delete p1v3Dph1; delete p2v3Dph1; delete p1v3Dph2; delete p2v3Dph2;
    delete PDFRelBWxCBxgauss;
    delete pTs;
    delete rastmp;

    if(debug_) cout<<"end Z1 refit"<<endl;

    return 0;

}
Ejemplo n.º 30
-1
 inline ext::shared_ptr<OneFactorModel::ShortRateDynamics>
 ExtendedCoxIngersollRoss::dynamics() const {
     return ext::shared_ptr<ShortRateDynamics>(
                         new Dynamics(phi_, theta(), k() , sigma(), x0()));
 }