double
vpHomography::computeRotation(unsigned int nbpoint,
                              vpPoint *c1P,
                              vpPoint *c2P,
                              vpHomogeneousMatrix &c2Mc1,
                              int userobust
                             )
{
  vpColVector e(2) ;
  double r_1 = -1 ;

  vpColVector p2(3) ;
  vpColVector p1(3) ;
  vpColVector Hp2(3) ;
  vpColVector Hp1(3) ;

  vpMatrix H2(2,3) ;
  vpColVector e2(2) ;
  vpMatrix H1(2,3) ;
  vpColVector e1(2) ;

  int only_1 = 0 ;
  int only_2 = 0 ;
  int iter = 0 ;

  unsigned int n=0 ;
  for (unsigned int i=0 ; i < nbpoint ; i++) {
    //    if ((c2P[i].get_x() !=-1) && (c1P[i].get_x() !=-1))
    if ( (std::fabs(c2P[i].get_x() + 1) > std::fabs(vpMath::maximum(c2P[i].get_x(), 1.))) 
	 && 
	 (std::fabs(c1P[i].get_x() + 1) > std::fabs(vpMath::maximum(c1P[i].get_x(), 1.))) )
      {
	n++ ;
      }
  }
  if ((only_1==1) || (only_2==1))  ; else n *=2 ;

  vpRobust robust(n);
  vpColVector res(n) ;
  vpColVector w(n) ;
  w =1 ;
  robust.setThreshold(0.0000) ;
  vpMatrix W(2*n,2*n)  ;
  W = 0 ;
  vpMatrix c2Rc1(3,3) ;
  double r =0 ;
  while (vpMath::equal(r_1,r,threshold_rotation) == false )
  {

    r_1 =r ;
    // compute current position

    //Change frame (current)
    for (unsigned int i=0 ; i < 3 ; i++)
      for (unsigned int j=0 ; j < 3 ; j++)
        c2Rc1[i][j] = c2Mc1[i][j] ;

    vpMatrix L(2,3), Lp ;
    int k =0 ;
    for (unsigned int i=0 ; i < nbpoint ; i++) {
      //if ((c2P[i].get_x() !=-1) && (c1P[i].get_x() !=-1))
      if ( (std::fabs(c2P[i].get_x() + 1) > std::fabs(vpMath::maximum(c2P[i].get_x(), 1.))) 
	 && 
	   (std::fabs(c1P[i].get_x() + 1) > std::fabs(vpMath::maximum(c1P[i].get_x(), 1.))) )
      {
        p2[0] = c2P[i].get_x() ;
        p2[1] = c2P[i].get_y() ;
        p2[2] = 1.0 ;
        p1[0] = c1P[i].get_x() ;
        p1[1] = c1P[i].get_y() ;
        p1[2] = 1.0 ;

        Hp2 = c2Rc1.t()*p2 ; // p2 = Hp1
        Hp1 = c2Rc1*p1 ;     // p1 = Hp2

        Hp2 /= Hp2[2] ;  // normalisation
        Hp1 /= Hp1[2] ;


        // set up the interaction matrix
        double x = Hp2[0] ;
        double y = Hp2[1] ;

        H2[0][0] = x*y ;   H2[0][1] = -(1+x*x) ; H2[0][2] = y ;
        H2[1][0] = 1+y*y ; H2[1][1] = -x*y ;     H2[1][2] = -x ;
        H2 *=-1 ;
        H2 = H2*c2Rc1.t() ;

        // Set up the error vector
        e2[0] = Hp2[0] - c1P[i].get_x() ;
        e2[1] = Hp2[1] - c1P[i].get_y() ;

        // set up the interaction matrix
        x = Hp1[0] ;
        y = Hp1[1] ;

        H1[0][0] = x*y ;   H1[0][1] = -(1+x*x) ; H1[0][2] = y ;
        H1[1][0] = 1+y*y ; H1[1][1] = -x*y ;     H1[1][2] = -x ;

        // Set up the error vector
        e1[0] = Hp1[0] - c2P[i].get_x() ;
        e1[1] = Hp1[1] - c2P[i].get_y() ;

        if (only_2==1)
        {
          if (k == 0) { L = H2 ; e = e2 ; }
          else
          {
            L = vpMatrix::stackMatrices(L,H2) ;
            e = vpMatrix::stackMatrices(e,e2) ;
          }
        }
        else
          if (only_1==1)
          {
            if (k == 0) { L = H1 ; e= e1 ; }
            else
            {
              L =  vpMatrix::stackMatrices(L,H1) ;
              e = vpMatrix::stackMatrices(e,e1) ;
            }
          }
          else
          {
            if (k == 0) {L = H2 ; e = e2 ; }
            else
            {
              L =  vpMatrix::stackMatrices(L,H2) ;
              e =  vpMatrix::stackMatrices(e,e2) ;
            }
            L =  vpMatrix::stackMatrices(L,H1) ;
            e =  vpMatrix::stackMatrices(e,e1) ;
          }

        k++ ;
      }
    }

    if (userobust)
    {
      robust.setIteration(0);

      for (unsigned int k=0 ; k < n ; k++)
      {
        res[k] = vpMath::sqr(e[2*k]) + vpMath::sqr(e[2*k+1]) ;
      }
      robust.MEstimator(vpRobust::TUKEY, res, w);


      // compute the pseudo inverse of the interaction matrix
      for (unsigned int k=0 ; k < n ; k++)
      {
        W[2*k][2*k] = w[k] ;
        W[2*k+1][2*k+1] = w[k] ;
      }
    }
    else
    {
      for (unsigned int k=0 ; k < 2*n ; k++) W[k][k] = 1 ;
    }
    // CreateDiagonalMatrix(w, W) ;
    (L).pseudoInverse(Lp, 1e-6) ;
    // Compute the camera velocity
    vpColVector c2Rc1, v(6) ;

    c2Rc1 = -2*Lp*W*e  ;
    for (unsigned int i=0 ; i < 3 ; i++) v[i+3] = c2Rc1[i] ;

    // only for simulation

    updatePoseRotation(c2Rc1, c2Mc1) ;
    r =e.sumSquare() ;

    if ((W*e).sumSquare() < 1e-10) break ;
    if (iter>25) break ;
    iter++ ;   // std::cout <<  iter <<"  e=" <<(e).sumSquare() <<"  e=" <<(W*e).sumSquare() <<std::endl ;

  }

  //  std::cout << c2Mc1 <<std::endl ;
  return (W*e).sumSquare() ;
}
Exemple #2
0
///////////////////////////////////////////////////////////////////////////
// Drawing Firework ///////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
void DrawFirework(int no)
{
	/* to display 
	 * each firework particle 
	 * You should calculate and display the trail of each
	 * particle here 
	 */

	int i, j, k, u;
	float interpolated_pt[2];
	float Color[4];

	for (i=0; i< fire[no].total_no; i++)
	{
		// if the paticle is still "alive"
		if (!fire[no].particle[i].death)
		{
			glLineWidth(1.5);
			glBegin(GL_LINE_STRIP); // for each paticle, generate its spline curve
				Color[0] = fire[no].particle[i].col[0];	
				Color[1] = fire[no].particle[i].col[1];	
				Color[2] = fire[no].particle[i].col[2];	
				Color[3] = fire[no].particle[i].col[3];	

				for (k=0; k<3; k++)
					Color[k] = 1.0;

				// print the initial position
				glColor4fv(Color);
				glVertex2fv(fire[no].init_pos);

				// interpolation
				for (u=1; u<=10; u++) 
				{
					for (j=0; j<2; j++) 
						// using the Hermite Spline Interpolation technique to find the interpolated points
						interpolated_pt[j] = fire[no].init_pos[j]*H0(u/10.0)+
											 fire[no].particle[i].pos[j]*H1(u/10.0)+
											 fire[no].particle[i].init_vel[j]*fire[no].t*H2(u/10.0)+
											 fire[no].particle[i].vel[j]*fire[no].t*H3(u/10.0);
					
					// print the interpolated points
					for (k=0; k<3; k++)
						Color[k] = (1-fire[no].particle[i].col[k])*0.49 + fire[no].particle[i].col[k];

					glColor4fv(Color);
					glVertex2fv(interpolated_pt);
				}

				// print the current point
				for (k=0; k<3; k++)
					Color[k] = (1-fire[no].particle[i].col[k])*0.4 + fire[no].particle[i].col[k];

				glColor4fv(Color);
				glVertex2fv(fire[no].particle[i].pos);
			glEnd();
		}
	}	

	

}
Exemple #3
0
void FindMaximum2::Fit(ColumnVector& Theta, int n_it)
{
   Tracer tr("FindMaximum2::Fit");
   enum State {Start, Restart, Continue, Interpolate, Extrapolate,
      Fail, Convergence};
   State TheState = Start;
   Real z,w,x,x2,g,l1,l2,l3,d1,d2=0,d3;
   ColumnVector Theta1, Theta2, Theta3;
   int np = Theta.Nrows();
   ColumnVector H1(np), H3, HP(np), K, K1(np);
   bool oorg, conv;
   int counter = 0;
   Theta1 = Theta; HP = 0.0; g = 0.0;

   // This is really a set of gotos and labels, but they do not work
   // correctly in AT&T C++ and Sun 4.01 C++.

   for(;;)
   {
      switch (TheState)
      {
      case Start:
	 tr.ReName("FindMaximum2::Fit/Start");
	 Value(Theta1, true, l1, oorg);
	 if (oorg) Throw(ProgramException("invalid starting value\n"));

      case Restart:
	 tr.ReName("FindMaximum2::Fit/ReStart");
	 conv = NextPoint(H1, d1);
	 if (conv) { TheState = Convergence; break; }
	 if (counter++ > n_it) { TheState = Fail; break; }

	 z = 1.0 / sqrt(d1);
	 H3 = H1 * z; K = (H3 - HP) * g; HP = H3;
	 g = 0.0;                     // de-activate to use curved projection
	 if (g==0.0) K1 = 0.0; else K1 = K * 0.2 + K1 * 0.6;
	 // (K - K1) * alpha + K1 * (1 - alpha)
	 //     = K * alpha + K1 * (1 - 2 * alpha)
	 K = K1 * d1; g = z;

      case Continue:
	 tr.ReName("FindMaximum2::Fit/Continue");
	 Theta2 = Theta1 + H1 + K;
	 Value(Theta2, false, l2, oorg);
	 if (counter++ > n_it) { TheState = Fail; break; }
	 if (oorg)
	 {
	    H1 *= 0.5; K *= 0.25; d1 *= 0.5; g *= 2.0;
	    TheState =  Continue; break;
	 }
	 d2 = LastDerivative(H1 + K * 2.0);

      case Interpolate:
	 tr.ReName("FindMaximum2::Fit/Interpolate");
	 z = d1 + d2 - 3.0 * (l2 - l1);
	 w = z * z - d1 * d2;
	 if (w < 0.0) { TheState = Extrapolate; break; }
	 w = z + sqrt(w);
	 if (1.5 * w + d1 < 0.0)
	    { TheState = Extrapolate; break; }
	 if (d2 > 0.0 && l2 > l1 && w > 0.0)
	    { TheState = Extrapolate; break; }
	 x = d1 / (w + d1); x2 = x * x; g /= x;
	 Theta3 = Theta1 + H1 * x + K * x2;
	 Value(Theta3, true, l3, oorg);
	 if (counter++ > n_it) { TheState = Fail; break; }
	 if (oorg)
	 {
	    if (x <= 1.0)
	       { x *= 0.5; x2 = x*x; g *= 2.0; d1 *= x; H1 *= x; K *= x2; }
	    else
	    {
	       x = 0.5 * (x-1.0); x2 = x*x; Theta1 = Theta2;
	       H1 = (H1 + K * 2.0) * x;
	       K *= x2; g = 0.0; d1 = x * d2; l1 = l2;
	    }
	    TheState = Continue; break;
	 }

	 if (l3 >= l1 && l3 >= l2)
	    { Theta1 = Theta3; l1 = l3; TheState =  Restart; break; }

	 d3 = LastDerivative(H1 + K * 2.0);
	 if (l1 > l2)
	    { H1 *= x; K *= x2; Theta2 = Theta3; d1 *= x; d2 = d3*x; }
	 else
	 {
	    Theta1 = Theta2; Theta2 = Theta3;
	    x -= 1.0; x2 = x*x; g = 0.0; H1 = (H1 + K * 2.0) * x;
	    K *= x2; l1 = l2; l2 = l3; d1 = x*d2; d2 = x*d3;
	    if (d1 <= 0.0) { TheState = Start; break; }
	 }
	 TheState =  Interpolate; break;

      case Extrapolate:
	 tr.ReName("FindMaximum2::Fit/Extrapolate");
	 Theta1 = Theta2; g = 0.0; K *= 4.0; H1 = (H1 * 2.0 + K);
	 d1 = 2.0 * d2; l1 = l2;
	 TheState = Continue; break;

      case Fail:
	 Throw(ConvergenceException(Theta));

      case Convergence:
	 Theta = Theta1; return;
      }
   }
}
Exemple #4
0
/*****************************************************************************
 * Help:
 *****************************************************************************/
static void Help( x264_param_t *defaults, int b_longhelp )
{
#define H0 printf
#define H1 if(b_longhelp) printf
    H0( "x264 core:%d%s\n"
        "Syntax: x264 [options] -o outfile infile [widthxheight]\n"
        "\n"
        "Infile can be raw YUV 4:2:0 (in which case resolution is required),\n"
        "  or YUV4MPEG 4:2:0 (*.y4m),\n"
        "  or AVI or Avisynth if compiled with AVIS support (%s).\n"
        "Outfile type is selected by filename:\n"
        " .264 -> Raw bytestream\n"
        " .mkv -> Matroska\n"
        " .mp4 -> MP4 if compiled with GPAC support (%s)\n"
        "\n"
        "Options:\n"
        "\n"
        "  -h, --help                  List the more commonly used options\n"
        "      --longhelp              List all options\n"
        "\n",
        X264_BUILD, X264_VERSION,
#ifdef AVIS_INPUT
        "yes",
#else
        "no",
#endif
#ifdef MP4_OUTPUT
        "yes"
#else
        "no"
#endif
      );
    H0( "Frame-type options:\n" );
    H0( "\n" );
    H0( "  -I, --keyint <integer>      Maximum GOP size [%d]\n", defaults->i_keyint_max );
    H1( "  -i, --min-keyint <integer>  Minimum GOP size [%d]\n", defaults->i_keyint_min );
    H1( "      --scenecut <integer>    How aggressively to insert extra I-frames [%d]\n", defaults->i_scenecut_threshold );
    H1( "      --pre-scenecut          Faster, less precise scenecut detection.\n"
        "                                  Required and implied by multi-threading.\n" );
    H0( "  -b, --bframes <integer>     Number of B-frames between I and P [%d]\n", defaults->i_bframe );
    H1( "      --b-adapt               Adaptive B-frame decision method [%d]\n"
        "                                  Higher values may lower threading efficiency.\n"
        "                                  - 0: Disabled\n"
        "                                  - 1: Fast\n"
        "                                  - 2: Optimal (slow with high --bframes)\n", defaults->i_bframe_adaptive );
    H1( "      --b-bias <integer>      Influences how often B-frames are used [%d]\n", defaults->i_bframe_bias );
    H0( "      --b-pyramid             Keep some B-frames as references\n" );
    H0( "      --no-cabac              Disable CABAC\n" );
    H0( "  -r, --ref <integer>         Number of reference frames [%d]\n", defaults->i_frame_reference );
    H1( "      --no-deblock            Disable loop filter\n" );
    H0( "  -f, --deblock <alpha:beta>  Loop filter AlphaC0 and Beta parameters [%d:%d]\n",
                                       defaults->i_deblocking_filter_alphac0, defaults->i_deblocking_filter_beta );
    H0( "      --interlaced            Enable pure-interlaced mode\n" );
    H0( "\n" );
    H0( "Ratecontrol:\n" );
    H0( "\n" );
    H0( "  -q, --qp <integer>          Set QP (0=lossless) [%d]\n", defaults->rc.i_qp_constant );
    H0( "  -B, --bitrate <integer>     Set bitrate (kbit/s)\n" );
    H0( "      --crf <float>           Quality-based VBR (nominal QP)\n" );
    H1( "      --vbv-maxrate <integer> Max local bitrate (kbit/s) [%d]\n", defaults->rc.i_vbv_max_bitrate );
    H0( "      --vbv-bufsize <integer> Enable CBR and set size of the VBV buffer (kbit) [%d]\n", defaults->rc.i_vbv_buffer_size );
    H1( "      --vbv-init <float>      Initial VBV buffer occupancy [%.1f]\n", defaults->rc.f_vbv_buffer_init );
    H1( "      --qpmin <integer>       Set min QP [%d]\n", defaults->rc.i_qp_min );
    H1( "      --qpmax <integer>       Set max QP [%d]\n", defaults->rc.i_qp_max );
    H1( "      --qpstep <integer>      Set max QP step [%d]\n", defaults->rc.i_qp_step );
    H0( "      --ratetol <float>       Allowed variance of average bitrate [%.1f]\n", defaults->rc.f_rate_tolerance );
    H0( "      --ipratio <float>       QP factor between I and P [%.2f]\n", defaults->rc.f_ip_factor );
    H0( "      --pbratio <float>       QP factor between P and B [%.2f]\n", defaults->rc.f_pb_factor );
    H1( "      --chroma-qp-offset <integer>  QP difference between chroma and luma [%d]\n", defaults->analyse.i_chroma_qp_offset );
    H1( "      --aq-mode <integer>     AQ method [%d]\n"
        "                                  - 0: Disabled\n"
        "                                  - 1: Variance AQ (complexity mask)\n", defaults->rc.i_aq_mode );
    H0( "      --aq-strength <float>   Reduces blocking and blurring in flat and\n"
        "                              textured areas. [%.1f]\n"
        "                                  - 0.5: weak AQ\n"
        "                                  - 1.5: strong AQ\n", defaults->rc.f_aq_strength );
    H0( "\n" );
    H0( "  -p, --pass <1|2|3>          Enable multipass ratecontrol\n"
        "                                  - 1: First pass, creates stats file\n"
        "                                  - 2: Last pass, does not overwrite stats file\n"
        "                                  - 3: Nth pass, overwrites stats file\n" );
    H0( "      --stats <string>        Filename for 2 pass stats [\"%s\"]\n", defaults->rc.psz_stat_out );
    H0( "      --qcomp <float>         QP curve compression: 0.0 => CBR, 1.0 => CQP [%.2f]\n", defaults->rc.f_qcompress );
    H1( "      --cplxblur <float>      Reduce fluctuations in QP (before curve compression) [%.1f]\n", defaults->rc.f_complexity_blur );
    H1( "      --qblur <float>         Reduce fluctuations in QP (after curve compression) [%.1f]\n", defaults->rc.f_qblur );
    H0( "      --zones <zone0>/<zone1>/...  Tweak the bitrate of some regions of the video\n" );
    H1( "                              Each zone is of the form\n"
        "                                  <start frame>,<end frame>,<option>\n"
        "                                  where <option> is either\n"
        "                                      q=<integer> (force QP)\n"
        "                                  or  b=<float> (bitrate multiplier)\n" );
    H1( "      --qpfile <string>       Force frametypes and QPs for some or all frames\n"
        "                              Format of each line: framenumber frametype QP\n"
        "                              QP of -1 lets x264 choose. Frametypes: I,i,P,B,b.\n" );
    H0( "\n" );
    H0( "Analysis:\n" );
    H0( "\n" );
    H0( "  -A, --partitions <string>   Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
        "                                  - p8x8, p4x4, b8x8, i8x8, i4x4\n"
        "                                  - none, all\n"
        "                                  (p4x4 requires p8x8. i8x8 requires --8x8dct.)\n" );
    H0( "      --direct <string>       Direct MV prediction mode [\"%s\"]\n"
        "                                  - none, spatial, temporal, auto\n",
                                       strtable_lookup( x264_direct_pred_names, defaults->analyse.i_direct_mv_pred ) );
    H0( "  -w, --weightb               Weighted prediction for B-frames\n" );
    H0( "      --me <string>           Integer pixel motion estimation method [\"%s\"]\n",
                                       strtable_lookup( x264_motion_est_names, defaults->analyse.i_me_method ) );
    H1( "                                  - dia: diamond search, radius 1 (fast)\n"
        "                                  - hex: hexagonal search, radius 2\n"
        "                                  - umh: uneven multi-hexagon search\n"
        "                                  - esa: exhaustive search\n"
        "                                  - tesa: hadamard exhaustive search (slow)\n" );
    else H0( "                                  - dia, hex, umh\n" );
int main(void){
  
  std::cout  << " ---- Programa de Tests de la pseudoinverse de Mansard ----" << std::endl;

  unsigned int nq = 10;  
  unsigned int nx1 = 7;

  Eigen::MatrixXd H1(Eigen::MatrixXd::Zero(nx1,nx1));
  H1(0,0) = 0;
  H1(1,1) = 0.2;
  H1(2,2) = 0;  
  H1(3,3) = 0.5;
  H1(4,4) = 0;
  H1(5,5) = 0;
  H1(6,6) = 0.7;
  
  std::vector<unsigned int> active_joints;
  for (unsigned int i=0; i<nx1; ++i)  if (H1(i,i))    active_joints.push_back(i);
  unsigned int n_active_joints = active_joints.size();
  std::cout << "n_active_joints: " << n_active_joints << std::endl;
  
  // Initialize pseudoinverse to zero
  Eigen::MatrixXd pJ1(Eigen::MatrixXd::Zero(nq,nx1));
  
//  // Per cada grup de 'i' elements
//  for (unsigned int i=1; i<=n_active_joints; ++i){
  
//    std::vector<bool> v(n_active_joints);
//    std::fill(v.begin(), v.begin() + i, true);

//    do {

//      Eigen::MatrixXd J_sum(Eigen::MatrixXd::Zero(nx1,nq));
      
//      double h_prod = 1.0;
      
//      for (int j = 0; j < n_active_joints; ++j) {
//	unsigned int qi = active_joints[j];
	
//	if (v[j]) {
//// 	  std::cout << j << " ";
//	  std::cout << qi << " ";
	  
// 	  J_sum(qi,qi+3) = 1.0;
//	  h_prod *= H1(qi,qi);
//	}
//	else	h_prod *= 1.0 - H1(qi,qi);
//      }
//      std::cout << "\n";
////       std::cout << "  -  P h: " << h_prod << "\n";
      
//      std::cout << " J_sum: " << "\n" << J_sum << "\n";

//      Eigen::MatrixXd pJ_sum(pinv(J_sum,0.00001));
//      std::cout << " h_prod * pJ_sum: " << "\n" << h_prod * pJ_sum << "\n";
      
//      pJ1 = pJ1 + h_prod * pJ_sum;
//      std::cout << " pJ1: " << "\n" << pJ1 << "\n";
      
//    } while (std::prev_permutation(v.begin(), v.end()));
    
//     std::cout << "-----\n";
//  }
//  std::cout << " pJ1: " << "\n" << pJ1 << "\n";
  
  
 // Per cada grup de 'i' elements
  pJ1 = Eigen::MatrixXd::Zero(nq,nx1);
  for (unsigned int i=1; i<=n_active_joints; ++i){
  
    std::vector<bool> v(n_active_joints);
    std::fill(v.begin(), v.begin() + i, true);

    do {
      Eigen::MatrixXd J_sum(Eigen::MatrixXd::Zero(nx1,nq));
      double h_prod = 1.0;
      for (unsigned int j = 0; j < n_active_joints; ++j) {
    unsigned int qi = active_joints[j];
	
    if (v[j]) {
      J_sum(qi,qi+3) = 1.0;
      h_prod *= H1(qi,qi);
    }
    else
      h_prod *= 1.0 - H1(qi,qi);
      }
      pJ1 = pJ1 + h_prod * pinv(J_sum,0.00001);
      
    } while (std::prev_permutation(v.begin(), v.end()));

  }
  std::cout << " pJ1: " << "\n" << pJ1 << "\n";
  


//    Eigen::MatrixXd m_id(Eigen::MatrixXd::Identity(6,6));
//    m_id(1,1) = 0.2;
//    m_id(4,4) = -3;

//    Eigen::VectorXi TS(3);
//    TS(0) = 2;
//    TS(1) = 3;
//    TS(2) = 1;

//    Eigen::VectorXd H(3);
//    H(0) = 0.1;
//    H(1) = 0.6;
//    H(2) = 0.4;

//    std::cout << " cinv: " << "\n" << cinv(m_id,TS,H) << "\n";

    double tol = 0.0000001;

    Eigen::MatrixXd m_id(Eigen::MatrixXd::Identity(nx1,nx1));

    Eigen::VectorXi TS(nx1);
    for (unsigned int i=0; i<nx1; ++i)  TS(i) = 1.0;

    Eigen::VectorXd H(nx1);
    H(0) = 0;
    H(1) = 0.2;
    H(2) = 0;
    H(3) = 0.5;
    H(4) = 0;
    H(5) = 0;
    H(6) = 0.7;

    std::cout << "cinv: " << "\n" << cinv(m_id,TS,H) << "\n";

    Eigen::MatrixXd lH(nx1,nx1);
    lH(0,0) = 0;
    lH(1,1) = 0.2;
    lH(2,2) = 0;
    lH(3,3) = 0.5;
    lH(4,4) = 0;
    lH(5,5) = 0;
    lH(6,6) = 0.7;

    std::cout << "cinv: " << "\n" << cinv(m_id,TS,lH) << "\n";
    std::cout << "left cinv: " << "\n" << left_cinv(m_id,TS,lH) << "\n";
    std::cout << "right cinv: " << "\n" << right_cinv(m_id,TS,lH) << "\n";

    return 0;
}
Exemple #6
0
Big PFC::hash_to_group(char *ID)
{
	Big m=H1(ID);
	return m%(*ord);
}
Exemple #7
0
void tSecureStream::m_setupClient(const tRSA& rsa, string appGreeting)
{
    // This block is protected by constant timing in case
    // there is a man-in-the-middle who is causing the client
    // connection to fail over-and-over and analysing the time
    // it takes for the client to re-start the connection.
    // This block prevents info from being leaked about the
    // particular pre_secret that is being used by the current
    // connection attempt.
    vector<u8> rand_c, pre_secret, enc;
    {
        tConstTimeBlock ctb(&gClientInitTimingHistory);

        // Generate the client random vector.
        rand_c = s_genRand(kRandVectLen);

        // Generate the pre-secret random vector.
        pre_secret = s_genRand(kPreSecretLen);

        // Encrypt the pre-secret under the server's RSA public key.
        enc = rsa.encrypt(pre_secret);
    }

    // Send all this to the server.
    pack(m_internal_writable, kLibrhoGreeting);
    pack(m_internal_writable, appGreeting);
    pack(m_internal_writable, rand_c);
    pack(m_internal_writable, enc);
    s_flush(m_internal_writable);

    // Read the greeting from the server.
    // We don't care if timing info is leaked here
    // because 'kSuccessfulGreeting' is not a secret.
    string greetingResponse;
    try {
        unpack(m_internal_readable, greetingResponse,
               (u32)(std::max(kSuccessfulGreeting.length(), kFailedGreeting.length())));
    } catch (ebObject& e) {
        throw eRuntimeError("The secure server didn't reply with its greeting.");
    }
    if (greetingResponse != kSuccessfulGreeting)
        throw eRuntimeError("The secure server sent a failure greeting.");

    // Read the random server bytes.
    // Again, we don't care about leaking timing info here.
    vector<u8> rand_s;
    try {
        unpack(m_internal_readable, rand_s, kRandVectLen);
    } catch (ebObject& e) {
        throw eRuntimeError("The secure server sent a random vector of the wrong length.");
    }
    if (rand_s.size() != kRandVectLen)
        throw eRuntimeError("The secure server sent a random vector of the wrong length.");

    // Another const timing block.
    vector<u8> secret, fPrime, g;
    {
        tConstTimeBlock ctb(&gClientProcessResponseTimingHistory);

        // Calculated the shared secret (from the pre-secret).
        secret = H1(pre_secret, rand_c, rand_s);

        // Calculate the correct response from the server.
        fPrime = H2(secret, rand_c, rand_s);

        // Calculate the proof-of-client.
        g = H3(secret, rand_c, rand_s);
    }

    // Read the proof-of-server hash.
    vector<u8> f;
    try {
        unpack(m_internal_readable, f, (u32)fPrime.size());
    } catch (ebObject& e) {
        throw eRuntimeError("The secure server failed to verify itself.");
    }
    if (!s_constTimeIsEqual(f, fPrime))
        throw eRuntimeError("The secure server failed to verify itself.");

    // Send the proof-of-client. (That is, prove we are not just replaying some other connection.)
    pack(m_internal_writable, g);
    s_flush(m_internal_writable);

    // Setup secure streams with the server.
    vector<u8> ksw = H4(pre_secret, secret, rand_c, rand_s);   // <-- the Key for the Server Writer
    vector<u8> kcw = H5(pre_secret, secret, rand_c, rand_s);   // <-- the Key for the Client Writer
    m_readable = new tReadableAES(m_internal_readable, kOpModeCBC,
                                  &ksw[0], s_toKeyLen(ksw.size()));
    m_writable = new tWritableAES(m_internal_writable, kOpModeCBC,
                                  &kcw[0], s_toKeyLen(kcw.size()));
}
Exemple #8
0
static int get_hash_1(int index)
{
	H1(crypt_out[index]);
}
// Fonction d'intérpolation Hermite
void SolveTCB ( float t, int *x, int *y, int *z)
{
// Déclaration des Keyframes utilisés
Key *NextKey, *NextNextKey, *CurKey, *PrevKey;

// Varaible d'incrémentation
int i;

// Taille du tableau de Keyframe
const int NumKeys = ((double)sizeof(TabKey))/((double)sizeof(Key));
const int NumKeysMinusOne = NumKeys-1;


// Boucle de parcours des Keyframes
//..

for(i = 0; i < NumKeys;i++)
{
	NextKey = &TabKey[i];
	if (t<NextKey->t){
		
		if(i==0) {
			CurKey = &TabKey[NumKeysMinusOne];
			PrevKey = &TabKey[NumKeysMinusOne-1];	
			NextNextKey = &TabKey[1];	
			}
				
		else if(i==1){
			CurKey = &TabKey[0];
			PrevKey = &TabKey[NumKeysMinusOne];	
			NextNextKey = &TabKey[2];	
			}

		else if(i==NumKeysMinusOne){
			CurKey = &TabKey[i-1];
			PrevKey = &TabKey[i-2];	
			NextNextKey = &TabKey[0];	
			}

		else   {
			CurKey = &TabKey[i-1];	
			PrevKey = &TabKey[i-2];	
			NextNextKey = &TabKey[i+1];
			}
		
		// calcul tangents	
			//curent
			float u = ((t-CurKey->t) / (NextKey->t - CurKey->t));
			float ctx,cty,ctz;
			float ntx,nty,ntz;
			
			ctx  = Tn(CurKey->tension,CurKey->bias,CurKey->continuity,PrevKey->pos.x,CurKey->pos.x);
			cty  = Tn(CurKey->tension,CurKey->bias,CurKey->continuity,PrevKey->pos.y,CurKey->pos.y);
			ctz  = Tn(CurKey->tension,CurKey->bias,CurKey->continuity,PrevKey->pos.z,CurKey->pos.z);

			//printf("ctx -- > %lf \n",ctx);
			
			//next
			ntx  = Tn1(CurKey->tension,CurKey->bias,CurKey->continuity,PrevKey->pos.x,CurKey->pos.x,NextKey->pos.x,NextNextKey->pos.x);
			nty  = Tn1(CurKey->tension,CurKey->bias,CurKey->continuity,PrevKey->pos.y,CurKey->pos.y,NextKey->pos.y,NextNextKey->pos.y);
			ntz  = Tn1(CurKey->tension,CurKey->bias,CurKey->continuity,PrevKey->pos.z,CurKey->pos.z,NextKey->pos.z,NextNextKey->pos.z);

			//printf(" ntx -- > %lf \n",ntx);
			

		// mise a jour des positions
			*x = (int) (H0(u)*CurKey->pos.x + H1(u)*NextKey->pos.x + H2(u)*ctx + H3(u)*ntx);
			*y = (int) (H0(u)*CurKey->pos.y + H1(u)*NextKey->pos.y + H2(u)*cty + H3(u)*nty);
			*z = (int) (H0(u)*CurKey->pos.z + H1(u)*NextKey->pos.z + H2(u)*ctz + H3(u)*ntz);
			printf("\n%lf\n",( CurKey->pos.x ));
			printf("\n%lf, %lf\n",H1(t),( NextKey->pos.x ));
			printf("\n%lf\n",( H2(t)*CurKey->tension ));				
			printf("\n%lf\n",( H3(t)*NextKey->tension ));
	 		//printf(" time -> %f X -- > %d \n",t,*x);
			//printf(" H0(t) = %f , H1(t) = %f , H2(t) = %f , H3(t) = %f \n",H0(t),H1(t),H2(t),H3(t));
			//if(*x < (-8000) || *x > 8000)
			//exit(0);
	//break;
	return;	
	}
}
 time = 0;
 return;


}
Exemple #10
0
int main(int argc, char* argv[])
{
    bool verb,fsrf,snap,expl,dabc,sout,uses;
    int  jsnap,ntsnap,jdata;
    char *atype;
#ifdef _OPENMP
    int ompnth=1;
#endif

    /* I/O files */
    sf_file Fwav=NULL; /* wavelet   */
    sf_file Fsou=NULL; /* sources   */
    sf_file Frec=NULL; /* receivers */
    sf_file Fvel=NULL; /* velocity  */
    sf_file Fang=NULL; /* angles    */
    sf_file Fdat=NULL; /* data      */
    sf_file Fwfl=NULL; /* wavefield */

    /* cube axes */
    sf_axis at,az,ax;
    sf_axis as,ar;

    int     nt,nz,nx,ns,nr,nb;
    int     it,iz,ix;
    float   dt,dz,dx,dt2;

    /* FDM structure */
    fdm2d    fdm=NULL;
    abcone2d abc=NULL;
    sponge   spo=NULL;

    /* I/O arrays */
    float  *ww=NULL;           /* wavelet   */
    pt2d   *ss=NULL;           /* sources   */
    pt2d   *rr=NULL;           /* receivers */
    float  *dd=NULL;           /* data      */

    float **tt=NULL;
    float **vp=NULL;           /* velocity */

    float **vpn=NULL;
    float **vpz=NULL;
    float **vpx=NULL;
    float **vsz=NULL;

    float **tht=NULL,**sit=NULL,**cot=NULL;
    float st,ct;

    float **pm=NULL,**po=NULL,**pp=NULL,**pa=NULL,**pt=NULL; /*      main wavefield */
    float **qm=NULL,**qo=NULL,**qp=NULL,**qa=NULL,**qt=NULL; /* auxiliary wavefield */
    float **sf=NULL; /* "stress" field */

    /* linear inteppolation weights/indices */
    lint2d cs,cr;

    /* FD operator size */
    float cox,cax,cbx,c1x,c2x;
    float coz,caz,cbz,c1z,c2z;

    /* wavefield cut params */
    sf_axis   acz=NULL,acx=NULL;
    int       nqz,nqx;
    float     oqz,oqx;
    float     dqz,dqx;
    float     **pc=NULL;

    float H1p,H2p,H1q,H2q;

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

    /* select anisotropy model */
    if (NULL == (atype = sf_getstring("atype"))) atype = "i";
    switch(atype[0]) {
	case 't':
	    sf_warning("TTI model");
	    break;

	case 'v':
	    sf_warning("VTI model");
	    break;

	case 'i':
	default:
	    sf_warning("ISO model");
	    break;
    }

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

    /*------------------------------------------------------------*/
    if(! sf_getbool("verb",&verb)) verb=false; /* verbosity */
    if(! sf_getbool("snap",&snap)) snap=false; /* wavefield snapshots */
    if(! sf_getbool("free",&fsrf)) fsrf=false; /* free surface */
    if(! sf_getbool("expl",&expl)) expl=false; /* "exploding reflector" */
    if(! sf_getbool("dabc",&dabc)) dabc=false; /* absorbing BC */
    if(! sf_getbool("sout",&sout)) sout=false; /* stress output */
    if(! sf_getbool("uses",&uses)) uses=false; /* use vsz */
    /*------------------------------------------------------------*/

    /*------------------------------------------------------------*/
    /* I/O files */
    Fwav = sf_input ("in" ); /* wavelet   */
    Fvel = sf_input ("vel"); /* velocity  */
    Fsou = sf_input ("sou"); /* sources   */
    Frec = sf_input ("rec"); /* receivers */
    Fang = sf_input ("ang"); /* angles    */
    Fwfl = sf_output("wfl"); /* wavefield */
    Fdat = sf_output("out"); /* data      */

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

    as = sf_iaxa(Fsou,2); sf_setlabel(as,"s"); if(verb) sf_raxa(as); /* sources */
    ar = sf_iaxa(Frec,2); sf_setlabel(ar,"r"); if(verb) sf_raxa(ar); /* receivers */

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

    ns = sf_n(as);
    nr = sf_n(ar);
    /*------------------------------------------------------------*/

    /*------------------------------------------------------------*/
    /* other execution parameters */
    if(! sf_getint("jdata",&jdata)) jdata=1;
    if(snap) {  /* save wavefield every *jsnap* time steps */
	if(! sf_getint("jsnap",&jsnap)) jsnap=nt;        
    }
    /*------------------------------------------------------------*/

    /*------------------------------------------------------------*/
    /* setup output data header */
    sf_oaxa(Fdat,ar,1);

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

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

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

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

	acz = sf_maxa(nqz,oqz,dqz); sf_raxa(acz);
	acx = sf_maxa(nqx,oqx,dqx); sf_raxa(acx);
	/* check if the imaging window fits in the wavefield domain */

	pc=sf_floatalloc2(sf_n(acz),sf_n(acx));

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

	sf_oaxa(Fwfl,acz,1);
	sf_oaxa(Fwfl,acx,2);
	sf_oaxa(Fwfl,at, 3);
    }

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

    fdm=fdutil_init(verb,fsrf,az,ax,nb,1);

    sf_setn(az,fdm->nzpad); sf_seto(az,fdm->ozpad); if(verb) sf_raxa(az);
    sf_setn(ax,fdm->nxpad); sf_seto(ax,fdm->oxpad); if(verb) sf_raxa(ax);
    /*------------------------------------------------------------*/

    if(expl) {
	ww = sf_floatalloc( 1);
    } else {
	ww = sf_floatalloc(ns);
    }
    dd = sf_floatalloc(nr);

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

    pt2dread1(Fsou,ss,ns,2); /* read (x,z) coordinates */
    pt2dread1(Frec,rr,nr,2); /* read (x,z) coordinates */

    cs = lint2d_make(ns,ss,fdm);
    cr = lint2d_make(nr,rr,fdm);

    /*------------------------------------------------------------*/
    /* setup FD coefficients */
    cox = C0 / (dx*dx);
    cax = CA / (dx*dx);
    cbx = CB / (dx*dx);
    c1x = C1 / dx;
    c2x = C2 / dx;

    coz = C0 / (dz*dz);
    caz = CA / (dz*dz);
    cbz = CB / (dz*dz);
    c1z = C1 / dz;
    c2z = C2 / dz;

    /* precompute dt^2*/
    dt2 = dt*dt;

    /*------------------------------------------------------------*/ 
    tt = sf_floatalloc2(nz,nx); 
    /*------------------------------------------------------------*/

    /* input velocity */
    vp  =sf_floatalloc2(fdm->nzpad,fdm->nxpad); 

    vpz =sf_floatalloc2(fdm->nzpad,fdm->nxpad); 
    sf_floatread(tt[0],nz*nx,Fvel ); 
    expand(tt,vpz,fdm); /* VPz */

    for    (ix=0; ix<fdm->nxpad; ix++) {
	for(iz=0; iz<fdm->nzpad; iz++) {	    
	    vp [ix][iz] = vpz[ix][iz];
	    vpz[ix][iz] = vpz[ix][iz] * vpz[ix][iz];
	}
    }
    if(fsrf) { /* free surface */
	for    (ix=0; ix<fdm->nxpad; ix++) {
	    for(iz=0; iz<fdm->nb; iz++) {
		vpz[ix][iz]=0;
	    }
	}
    }

    if(atype[0] != 'i') {
	vpn =sf_floatalloc2(fdm->nzpad,fdm->nxpad);     
	sf_floatread(tt[0],nz*nx,Fvel );    
	expand(tt,vpn,fdm); /* VPn */

	vpx =sf_floatalloc2(fdm->nzpad,fdm->nxpad); 
	sf_floatread(tt[0],nz*nx,Fvel );    
	expand(tt,vpx,fdm); /* VPx */

	for    (ix=0; ix<fdm->nxpad; ix++) {
	    for(iz=0; iz<fdm->nzpad; iz++) {	    
		vpn[ix][iz] = vpn[ix][iz] * vpn[ix][iz];
		vpx[ix][iz] = vpx[ix][iz] * vpx[ix][iz];
	    }
	}

	if(fsrf) { /* free surface */
	    for    (ix=0; ix<fdm->nxpad; ix++) {
		for(iz=0; iz<fdm->nb; iz++) {
		    vpn[ix][iz]=0;
		    vpx[ix][iz]=0;
		}
	    }
	}

	if(uses) {
	    vsz =sf_floatalloc2(fdm->nzpad,fdm->nxpad);
	    sf_floatread(tt[0],nz*nx,Fvel );    
	    expand(tt,vsz,fdm); /* VSz */
	    for    (ix=0; ix<fdm->nxpad; ix++) {
		for(iz=0; iz<fdm->nzpad; iz++) {
		    vsz[ix][iz] = vsz[ix][iz] * vsz[ix][iz];
		}
	    }
	}
    }

    /*------------------------------------------------------------*/
    if( atype[0]=='t') {
	/* input tilt angle */
	tht =sf_floatalloc2(fdm->nzpad,fdm->nxpad); 

	sit =sf_floatalloc2(fdm->nzpad,fdm->nxpad); 
	cot =sf_floatalloc2(fdm->nzpad,fdm->nxpad); 

	sf_floatread(tt[0],nz*nx,Fang); 
	expand(tt,tht,fdm);
	
	for    (ix=0; ix<fdm->nxpad; ix++) {
	    for(iz=0; iz<fdm->nzpad; iz++) {	    
		tht[ix][iz] *= SF_PI/180.;
		sit[ix][iz] =   sinf(tht[ix][iz]);
		cot[ix][iz] =   cosf(tht[ix][iz]);
	    }
	}

	free(*tht); free(tht);
    }

    /*------------------------------------------------------------*/
    free(*tt); free(tt);    
    /*------------------------------------------------------------*/

    /*------------------------------------------------------------*/
    /* allocate wavefield arrays */
    pm=sf_floatalloc2(fdm->nzpad,fdm->nxpad);
    po=sf_floatalloc2(fdm->nzpad,fdm->nxpad);
    pp=sf_floatalloc2(fdm->nzpad,fdm->nxpad);
    pa=sf_floatalloc2(fdm->nzpad,fdm->nxpad);
    for    (ix=0; ix<fdm->nxpad; ix++) {
	for(iz=0; iz<fdm->nzpad; iz++) {
	    pm[ix][iz]=0;
	    po[ix][iz]=0;
	    pp[ix][iz]=0;
	    pa[ix][iz]=0;
	}
    }
    
    if(atype[0] != 'i') {
	qm=sf_floatalloc2(fdm->nzpad,fdm->nxpad);
	qo=sf_floatalloc2(fdm->nzpad,fdm->nxpad);
	qp=sf_floatalloc2(fdm->nzpad,fdm->nxpad);
	qa=sf_floatalloc2(fdm->nzpad,fdm->nxpad);
	for    (ix=0; ix<fdm->nxpad; ix++) {
	    for(iz=0; iz<fdm->nzpad; iz++) {
		qm[ix][iz]=0;
		qo[ix][iz]=0;
		qp[ix][iz]=0;
		qa[ix][iz]=0;
	    }
	}

	if(sout) sf=sf_floatalloc2(fdm->nzpad,fdm->nxpad);
    }

    /*------------------------------------------------------------*/
    if(dabc) {
	abc = abcone2d_make(NOP,dt,vp,fsrf,fdm); /* one-way */
	spo = sponge_make(fdm->nb);              /* sponge  */
    }

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

	/* compute acceleration */
	switch(atype[0]) {
	    case 't':

		if(uses) {
#ifdef _OPENMP
#pragma omp parallel for						\
    schedule(dynamic,fdm->ompchunk)					\
    private(ix,iz,H1p,H2p,H1q,H2q,st,ct)				\
    shared(fdm,pa,po,qa,qo,						\
	   cox,cax,cbx,c1x,c2x,						\
	   coz,caz,cbz,c1z,c2z,						\
	   vpn,vpz,vpx,vsz,						\
	   sit,cot)
#endif
		    for    (ix=NOP; ix<fdm->nxpad-NOP; ix++) {
			for(iz=NOP; iz<fdm->nzpad-NOP; iz++) {
			    
			    st=sit[ix][iz];
			    ct=cot[ix][iz];
			    
			    H1p = H1(po,ix,iz,				\
				     st,ct,				\
				     cox,cax,cbx,c1x,c2x,		\
				     coz,caz,cbz,c1z,c2z);
			    
			    H2p = H2(po,ix,iz,				\
				     st,ct,				\
				     cox,cax,cbx,c1x,c2x,		\
				     coz,caz,cbz,c1z,c2z);
			    
			    H1q = H1(qo,ix,iz,				\
				     st,ct,				\
				     cox,cax,cbx,c1x,c2x,		\
				     coz,caz,cbz,c1z,c2z);
			    
			    H2q = H2(qo,ix,iz,				\
				     st,ct,				\
				     cox,cax,cbx,c1x,c2x,		\
				     coz,caz,cbz,c1z,c2z);
			    
			    /* p - main field */
			    pa[ix][iz] = 
				H1p * vsz[ix][iz] +
				H2p * vpx[ix][iz] + 
				H1q * vpz[ix][iz] -
				H1q * vsz[ix][iz];
			    
			    /* q - auxiliary field */
			    qa[ix][iz] = 
				H2p * vpn[ix][iz] -
				H2p * vsz[ix][iz] +
				H1q * vpz[ix][iz] +
				H2q * vsz[ix][iz];
			    
			}
		    }
		} else {
#ifdef _OPENMP
#pragma omp parallel for						\
    schedule(dynamic,fdm->ompchunk)					\
    private(ix,iz,H2p,H1q,st,ct)					\
    shared(fdm,pa,po,qa,qo,						\
	   cox,cax,cbx,c1x,c2x,						\
	   coz,caz,cbz,c1z,c2z,						\
	   vpn,vpz,vpx,							\
	   sit,cot)
#endif
		    for    (ix=NOP; ix<fdm->nxpad-NOP; ix++) {
			for(iz=NOP; iz<fdm->nzpad-NOP; iz++) {
			    
			    st=sit[ix][iz];
			    ct=cot[ix][iz];
			    
			    H2p = H2(po,ix,iz,				\
				     st,ct,				\
				     cox,cax,cbx,c1x,c2x,		\
				     coz,caz,cbz,c1z,c2z);
			    
			    H1q = H1(qo,ix,iz,				\
				     st,ct,				\
				     cox,cax,cbx,c1x,c2x,		\
				     coz,caz,cbz,c1z,c2z);
			    
			    /* p - main field */
			    pa[ix][iz] = 
				H2p * vpx[ix][iz] + 
				H1q * vpz[ix][iz];
			    
			    /* q - auxiliary field */
			    qa[ix][iz] = 
				H2p * vpn[ix][iz] +
				H1q * vpz[ix][iz];
			}
		    }

		}
		break;
		    
	    case 'v':

		if(uses) {
#ifdef _OPENMP
#pragma omp parallel for						\
    schedule(dynamic,fdm->ompchunk)					\
    private(ix,iz,H1p,H2p,H1q,H2q)					\
    shared(fdm,pa,po,qa,qo,						\
	   cox,cax,cbx,							\
	   coz,caz,cbz,							\
	   vpn,vpz,vpx,vsz)
#endif
		    for    (ix=NOP; ix<fdm->nxpad-NOP; ix++) {
			for(iz=NOP; iz<fdm->nzpad-NOP; iz++) {
			    
			    H1p = Dzz(po,ix,iz,coz,caz,cbz);
			    H1q = Dzz(qo,ix,iz,coz,caz,cbz);
			    
			    H2p = Dxx(po,ix,iz,cox,cax,cbx);
			    H2q = Dxx(qo,ix,iz,cox,cax,cbx);
			    
			    /* p - main field */
			    pa[ix][iz] = 
				H1p * vsz[ix][iz] +
				H2p * vpx[ix][iz] + 
				H1q * vpz[ix][iz] -
				H1q * vsz[ix][iz];
			    
			    /* q - auxiliary field */
			    qa[ix][iz] = 
				H2p * vpn[ix][iz] -
				H2p * vsz[ix][iz] +
				H1q * vpz[ix][iz] +
				H2q * vsz[ix][iz];
			}
		    } 
		} else {
#ifdef _OPENMP
#pragma omp parallel for					\
    schedule(dynamic,fdm->ompchunk)				\
    private(ix,iz,H2p,H1q)					\
    shared(fdm,pa,po,qa,qo,					\
	   cox,cax,cbx,						\
	   coz,caz,cbz,						\
	   vpn,vpx,vpz)
#endif
		    for    (ix=NOP; ix<fdm->nxpad-NOP; ix++) {
			for(iz=NOP; iz<fdm->nzpad-NOP; iz++) {
			    
			    H1q = Dzz(qo,ix,iz,coz,caz,cbz);			    
			    H2p = Dxx(po,ix,iz,cox,cax,cbx);
			    
			    /* p - main field */
			    pa[ix][iz] = 
				H2p * vpx[ix][iz] + 
				H1q * vpz[ix][iz];
			    
			    /* q - auxiliary field */
			    qa[ix][iz] = 
				H2p * vpn[ix][iz] +
				H1q * vpz[ix][iz];
			}
		    } 
		}
		break;
		
	    case 'i':
	    default:
#ifdef _OPENMP
#pragma omp parallel for					\
    schedule(dynamic,fdm->ompchunk)				\
    private(ix,iz)						\
    shared(fdm,pa,po,						\
	   cox,cax,cbx,						\
	   coz,caz,cbz,						\
	   vpz)
#endif
		for    (ix=NOP; ix<fdm->nxpad-NOP; ix++) {
		    for(iz=NOP; iz<fdm->nzpad-NOP; iz++) {
			
			pa[ix][iz] = ( Dxx(po,ix,iz,cox,cax,cbx) + 
				       Dzz(po,ix,iz,coz,caz,cbz) ) * vpz[ix][iz];
			
		    }
		}   
		break;
	}

	/* inject acceleration source */
	if(expl) {
	    sf_floatread(ww, 1,Fwav);
	    ;                   lint2d_inject1(pa,ww[0],cs);
	    if(atype[0] != 'i') lint2d_inject1(qa,ww[0],cs);
	} else {
	    sf_floatread(ww,ns,Fwav);	
	    ;                   lint2d_inject(pa,ww,cs);
	    if(atype[0] != 'i') lint2d_inject(qa,ww,cs);
	}

	/* step forward in time */
#ifdef _OPENMP
#pragma omp parallel for	    \
    schedule(dynamic,fdm->ompchunk) \
    private(ix,iz)		    \
    shared(fdm,pa,po,pm,pp,dt2)
#endif
	for    (ix=0; ix<fdm->nxpad; ix++) {
	    for(iz=0; iz<fdm->nzpad; iz++) {
		pp[ix][iz] = 2*po[ix][iz] 
		    -          pm[ix][iz] 
		    +          pa[ix][iz] * dt2;
	    }
	}
	/* circulate wavefield arrays */
	pt=pm;
	pm=po;
	po=pp;
	pp=pt;
	
	if(atype[0] != 'i') {
	    
#ifdef _OPENMP
#pragma omp parallel for			\
    schedule(dynamic,fdm->ompchunk)		\
    private(ix,iz)				\
    shared(fdm,qa,qo,qm,qp,dt2)
#endif
	    for    (ix=0; ix<fdm->nxpad; ix++) {
		for(iz=0; iz<fdm->nzpad; iz++) {
		    qp[ix][iz] = 2*qo[ix][iz] 
			-          qm[ix][iz] 
			+          qa[ix][iz] * dt2;
		}
	    }
	    /* circulate wavefield arrays */
	    qt=qm;
	    qm=qo;
	    qo=qp;
	    qp=qt;
	}

	/* one-way abc apply */
	if(dabc) {
	    abcone2d_apply(po,pm,NOP,abc,fdm);
	    sponge2d_apply(pm,spo,fdm);
	    sponge2d_apply(po,spo,fdm);
	    
	    if(atype[0] != 'i') {
		abcone2d_apply(qo,qm,NOP,abc,fdm);
		sponge2d_apply(qm,spo,fdm);
		sponge2d_apply(qo,spo,fdm);
	    }
	}
	
	/* compute stress */
	if(sout && (atype[0] != 'i')) {
#ifdef _OPENMP
#pragma omp parallel for			\
    schedule(dynamic,fdm->ompchunk)		\
    private(ix,iz)				\
    shared(fdm,po,qo,sf)
#endif
	    for    (ix=0; ix<fdm->nxpad; ix++) {
		for(iz=0; iz<fdm->nzpad; iz++) {
		    sf[ix][iz] = po[ix][iz] + qo[ix][iz];
		}
	    }
	}

	/* extract data at receivers */
	if(sout && (atype[0] != 'i')) {lint2d_extract(sf,dd,cr);
	} else {                       lint2d_extract(po,dd,cr);}
	if(it%jdata==0) sf_floatwrite(dd,nr,Fdat);

	/* extract wavefield in the "box" */
	if(snap && it%jsnap==0) {
	    if(sout && (atype[0] != 'i')) {cut2d(sf,pc,fdm,acz,acx);
	    } else {                       cut2d(po,pc,fdm,acz,acx);}
	    sf_floatwrite(pc[0],sf_n(acz)*sf_n(acx),Fwfl);
	}

    }
    if(verb) fprintf(stderr,"\n");    

    /*------------------------------------------------------------*/
    /* deallocate arrays */

    free(*pm); free(pm);
    free(*pp); free(pp);
    free(*po); free(po);
    free(*pa); free(pa);
    free(*pc); free(pc);

    free(*vp);  free(vp);
    free(*vpz); free(vpz);

    if(atype[0] != 'i') {
	free(*qm); free(qm);
	free(*qp); free(qp);
	free(*qo); free(qo);
	free(*qa); free(qa);

	free(*vpn); free(vpn);
	free(*vpx); free(vpx);

	if(uses){ free(*vsz); free(vsz); }
	if(sout){ free(*sf);  free(sf);  }
    }

    if(atype[0] == 't') {
	free(*sit); free(sit);
	free(*cot); free(cot);
    }

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

    exit (0);
}
Exemple #11
0
static int binary_hash_1(void *binary)
{
	H1((char *)binary);
}
Exemple #12
0
void Tower::hanoiStart()
{
	H1(0, 3, counter);

}
Exemple #13
0
void Tower::H2(int source, int dest, int & counter)
{
	//source = 3, dest = 1
	move(source, dest, counter);
	H1(dest + 1, source, counter);
}
Exemple #14
0
static int get_hash_1(int index)
{
	H1(buffer[index].out);
}
double
vpHomography::computeDisplacement(unsigned int nbpoint,
                                  vpPoint *c1P,
                                  vpPoint *c2P,
                                  vpPlane *oN,
                                  vpHomogeneousMatrix &c2Mc1,
                                  vpHomogeneousMatrix &c1Mo,
                                  int userobust
                                 )
{


  vpColVector e(2) ;
  double r_1 = -1 ;



  vpColVector p2(3) ;
  vpColVector p1(3) ;
  vpColVector Hp2(3) ;
  vpColVector Hp1(3) ;

  vpMatrix H2(2,6) ;
  vpColVector e2(2) ;
  vpMatrix H1(2,6) ;
  vpColVector e1(2) ;


  int only_1 = 1 ;
  int only_2 = 0 ;
  int iter = 0 ;
  unsigned int i ;
  unsigned int n=0 ;
  n = nbpoint ;
  if ((only_1==1) || (only_2==1))  ; else n *=2 ;

  vpRobust robust(n);
  vpColVector res(n) ;
  vpColVector w(n) ;
  w =1 ;
  robust.setThreshold(0.0000) ;
  vpMatrix W(2*n,2*n)  ;
  W = 0 ;

  vpColVector N1(3), N2(3) ;
  double d1, d2 ;

  double r =1e10 ;
  iter =0 ;
  while (vpMath::equal(r_1,r,threshold_displacement) == false )
  {

    r_1 =r ;
    // compute current position


    //Change frame (current)
    vpHomogeneousMatrix c1Mc2, c2Mo ;
    vpRotationMatrix c1Rc2, c2Rc1  ;
    vpTranslationVector c1Tc2, c2Tc1 ;
    c1Mc2 = c2Mc1.inverse() ;
    c2Mc1.extract(c2Rc1) ;
    c2Mc1.extract(c2Tc1) ;
    c2Mc1.extract(c1Rc2) ;
    c1Mc2.extract(c1Tc2) ;

    c2Mo = c2Mc1*c1Mo ;



    vpMatrix L(2,3), Lp ;
    int k =0 ;
    for (i=0 ; i < nbpoint ; i++)
    {
      getPlaneInfo(oN[i], c1Mo, N1, d1) ;
      getPlaneInfo(oN[i], c2Mo, N2, d2) ;
      p2[0] = c2P[i].get_x() ;
      p2[1] = c2P[i].get_y() ;
      p2[2] = 1.0 ;
      p1[0] = c1P[i].get_x() ;
      p1[1] = c1P[i].get_y() ;
      p1[2] = 1.0 ;

      vpMatrix H(3,3) ;

      Hp2 = ((vpMatrix)c1Rc2 + ((vpMatrix)c1Tc2*N2.t())/d2)*p2 ;  // p2 = Hp1
      Hp1 = ((vpMatrix)c2Rc1 + ((vpMatrix)c2Tc1*N1.t())/d1)*p1 ;  // p1 = Hp2

      Hp2 /= Hp2[2] ;  // normalisation
      Hp1 /= Hp1[2] ;


      // set up the interaction matrix
      double x = Hp2[0] ;
      double y = Hp2[1] ;
      double Z1  ;

      Z1 = (N1[0]*x+N1[1]*y+N1[2])/d1 ;        // 1/z


      H2[0][0] = -Z1 ;  H2[0][1] = 0  ;       H2[0][2] = x*Z1 ;
      H2[1][0] = 0 ;     H2[1][1] = -Z1 ;     H2[1][2] = y*Z1 ;
      H2[0][3] = x*y ;   H2[0][4] = -(1+x*x) ; H2[0][5] = y ;
      H2[1][3] = 1+y*y ; H2[1][4] = -x*y ;     H2[1][5] = -x ;
      H2 *=-1 ;

      vpMatrix c1CFc2(6,6) ;
      {
        vpMatrix sTR = c1Tc2.skew()*(vpMatrix)c1Rc2 ;
        for (unsigned int k=0 ; k < 3 ; k++)
          for (unsigned int l=0 ; l<3 ; l++)
          {
            c1CFc2[k][l] = c1Rc2[k][l] ;
            c1CFc2[k+3][l+3] = c1Rc2[k][l] ;
            c1CFc2[k][l+3] = sTR[k][l] ;
          }
      }
      H2 = H2*c1CFc2 ;



      // Set up the error vector
      e2[0] = Hp2[0] - c1P[i].get_x() ;
      e2[1] = Hp2[1] - c1P[i].get_y() ;

      x = Hp1[0] ;
      y = Hp1[1] ;

      Z1 = (N2[0]*x+N2[1]*y+N2[2])/d2 ; // 1/z

      H1[0][0] = -Z1 ;  H1[0][1] = 0  ;       H1[0][2] = x*Z1 ;
      H1[1][0] = 0 ;     H1[1][1] = -Z1 ;     H1[1][2] = y*Z1;
      H1[0][3] = x*y ;   H1[0][4] = -(1+x*x) ; H1[0][5] = y ;
      H1[1][3] = 1+y*y ; H1[1][4] = -x*y ;     H1[1][5] = -x ;

      // Set up the error vector
      e1[0] = Hp1[0] - c2P[i].get_x() ;
      e1[1] = Hp1[1] - c2P[i].get_y() ;


      if (only_2==1)
      {
        if (k == 0) { L = H2 ; e = e2 ; }
        else
        {
          L = vpMatrix::stackMatrices(L,H2) ;
          e = vpMatrix::stackMatrices(e,e2) ;
        }
      }
      else
        if (only_1==1)
        {
          if (k == 0) { L = H1 ; e= e1 ; }
          else
          {
            L = vpMatrix::stackMatrices(L,H1) ;
            e = vpMatrix::stackMatrices(e,e1) ;
          }
        }
        else
        {
          if (k == 0) {L = H2 ; e = e2 ; }
          else
          {
            L = vpMatrix::stackMatrices(L,H2) ;
            e = vpMatrix::stackMatrices(e,e2) ;
          }
          L = vpMatrix::stackMatrices(L,H1) ;
          e = vpMatrix::stackMatrices(e,e1) ;
        }


      k++ ;
    }

    if (userobust)
    {
      robust.setIteration(0);
      for (unsigned int k=0 ; k < n ; k++)
      {
        res[k] = vpMath::sqr(e[2*k]) + vpMath::sqr(e[2*k+1]) ;
      }
      robust.MEstimator(vpRobust::TUKEY, res, w);


      // compute the pseudo inverse of the interaction matrix
      for (unsigned int k=0 ; k < n ; k++)
      {
        W[2*k][2*k] = w[k] ;
        W[2*k+1][2*k+1] = w[k] ;
      }
    }
    else
    {
      for (unsigned int k=0 ; k < 2*n ; k++) W[k][k] = 1 ;
    }
    (W*L).pseudoInverse(Lp, 1e-16) ;
    // Compute the camera velocity
    vpColVector c2Tcc1 ;

    c2Tcc1 = -1*Lp*W*e  ;

    // only for simulation

    c2Mc1 = vpExponentialMap::direct(c2Tcc1).inverse()*c2Mc1 ; ;
    //   UpdatePose2(c2Tcc1, c2Mc1) ;
    r =(W*e).sumSquare() ;



  if (r < 1e-15)  {break ; }
    if (iter>1000){break ; }
    if (r>r_1) {  break ; }
    iter++ ;
  }

  return (W*e).sumSquare() ;

}
Exemple #16
0
Big PFC::hash_to_group(char *ID)
{
	Big m=H1(ID);
	Big o=pow((Big)2,2*S);
	return m%o;
}
Exemple #17
0
void PFC::hash_and_map(G1& w,char *ID)
{
    Big x0=H1(ID);
    while (!w.g.set(x0,x0)) x0+=1;
	w.g*=*cof;
}
Exemple #18
0
Molecule C6H6()
{
    int nAtoms = 12;

    // These are in Angstrom
    Eigen::Vector3d C1(5.274,  1.999, -8.568);
    Eigen::Vector3d C2(6.627,  2.018, -8.209);
    Eigen::Vector3d C3(7.366,  0.829, -8.202);
    Eigen::Vector3d C4(6.752, -0.379, -8.554);
    Eigen::Vector3d C5(5.399, -0.398, -8.912);
    Eigen::Vector3d C6(4.660,  0.791, -8.919);
    Eigen::Vector3d H1(4.704,  2.916, -8.573);
    Eigen::Vector3d H2(7.101,  2.950, -7.938);
    Eigen::Vector3d H3(8.410,  0.844, -7.926);
    Eigen::Vector3d H4(7.322, -1.296, -8.548);
    Eigen::Vector3d H5(4.925, -1.330, -9.183);
    Eigen::Vector3d H6(3.616,  0.776, -9.196);
    // Scale
    C1 /= convertBohrToAngstrom;
    C2 /= convertBohrToAngstrom;
    C3 /= convertBohrToAngstrom;
    C4 /= convertBohrToAngstrom;
    C5 /= convertBohrToAngstrom;
    C6 /= convertBohrToAngstrom;
    H1 /= convertBohrToAngstrom;
    H2 /= convertBohrToAngstrom;
    H3 /= convertBohrToAngstrom;
    H4 /= convertBohrToAngstrom;
    H5 /= convertBohrToAngstrom;
    H6 /= convertBohrToAngstrom;

    Eigen::MatrixXd geom(3, nAtoms);
    geom.col(0) = C1.transpose();
    geom.col(1) = C2.transpose();
    geom.col(2) = C3.transpose();
    geom.col(3) = C4.transpose();
    geom.col(4) = C5.transpose();
    geom.col(5) = C6.transpose();
    geom.col(6) = H1.transpose();
    geom.col(7) = H2.transpose();
    geom.col(8) = H3.transpose();
    geom.col(9) = H4.transpose();
    geom.col(10) = H5.transpose();
    geom.col(11) = H6.transpose();
    Eigen::VectorXd charges(12), masses(12);
    charges << 6.0, 6.0, 6.0, 6.0, 6.0, 6.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0;
    masses  << 12.00, 12.0, 12.0, 12.0, 12.0, 12.0, 1.0078250, 1.0078250, 1.0078250,
            1.0078250, 1.0078250, 1.0078250;

    double radiusC = 1.70 / convertBohrToAngstrom;
    double radiusH = 1.20 / convertBohrToAngstrom;
    std::vector<Atom> atoms;
    atoms.push_back( Atom("Carbon",   "C",  charges(0), masses(0), radiusC, C1, 1.0) );
    atoms.push_back( Atom("Carbon",   "C",  charges(1), masses(1), radiusC, C2, 1.0) );
    atoms.push_back( Atom("Carbon",   "C",  charges(2), masses(2), radiusC, C3, 1.0) );
    atoms.push_back( Atom("Carbon",   "C",  charges(3), masses(3), radiusC, C4, 1.0) );
    atoms.push_back( Atom("Carbon",   "C",  charges(4), masses(4), radiusC, C5, 1.0) );
    atoms.push_back( Atom("Carbon",   "C",  charges(5), masses(5), radiusC, C6, 1.0) );
    atoms.push_back( Atom("Hydrogen", "H",  charges(6), masses(6), radiusH, H1, 1.0) );
    atoms.push_back( Atom("Hydrogen", "H",  charges(7), masses(7), radiusH, H2, 1.0) );
    atoms.push_back( Atom("Hydrogen", "H",  charges(8), masses(8), radiusH, H3, 1.0) );
    atoms.push_back( Atom("Hydrogen", "H",  charges(9), masses(9), radiusH, H4, 1.0) );
    atoms.push_back( Atom("Hydrogen", "H", charges(10), masses(10), radiusH, H5, 1.0) );
    atoms.push_back( Atom("Hydrogen", "H", charges(11), masses(11), radiusH, H6, 1.0) );

    std::vector<Sphere> spheres;
    Sphere sph1(C1, radiusC);
    Sphere sph2(C2, radiusC);
    Sphere sph3(C3, radiusC);
    Sphere sph4(C4, radiusC);
    Sphere sph5(C5, radiusC);
    Sphere sph6(C6, radiusC);

    Sphere sph7(H1, radiusH);
    Sphere sph8(H2, radiusH);
    Sphere sph9(H3, radiusH);
    Sphere sph10(H4, radiusH);
    Sphere sph11(H5, radiusH);
    Sphere sph12(H6, radiusH);

    spheres.push_back(sph1);
    spheres.push_back(sph2);
    spheres.push_back(sph3);
    spheres.push_back(sph4);
    spheres.push_back(sph5);
    spheres.push_back(sph6);
    spheres.push_back(sph7);
    spheres.push_back(sph8);
    spheres.push_back(sph9);
    spheres.push_back(sph10);
    spheres.push_back(sph11);
    spheres.push_back(sph12);

    // D2h as generated by Oxy, Oxz, Oyz
    Symmetry pGroup = buildGroup(0, 0, 0, 0);

    return Molecule(nAtoms, charges, masses, geom, atoms, spheres, pGroup);
};
Exemple #19
0
BamX::BamX(pars & Params1)	// optional constructor
{
    // parameters
    Params=Params1;
    Nread=0;
    Npair=0;
    Nproper=0;
    Nout=0;
    LFlow=INT_MIN;
    LFhigh=INT_MAX;
    region.limit=false;
    IlluminizeBam=0;

    outFragTailBam=false;
    outInterChromBam=false;
    outUniqueMultipleBam=false;
    outUniquePartialBam=false;
    outUniqueUnmappedBam=false;
    outAllPairsBam=false;
    outReadPairPosBam=false;
    
    //output file
	//samfile_t *fp;
    bam_header_t *bam_header;
    
    string s = Params.getInput();
    BamUtil bam1(s);
    Bam = bam1;

    string filename=extractfilename(s);
    
    // parameters
    string fragPosFile = Params.getString("ReadPairPosFile");
    string r = Params.getString("ChromRegion");
    int maxReads = Params.getInt("MaxReads");
    Qmin = Params.getInt("Qmin");
    LRmin = Params.getInt("MinReadLength");
    maxmismatchPC=Params.getDouble("FractionMaxMisMatches");
    FragLengthWindow=Params.getInt("FragmentLengthWindow");
    int cmd_MateMode=Params.getInt("ReadPairSenseConfig");
    string ReferenceFastaFile=Params.getString("ReferenceFastaFile");
    FragmentTailPercent=Params.getDouble("FragmentTailPercent");
    IlluminizeBam=Params.getInt("Illuminize")>0;
    outputDirectory=Params.getString("OutputDirectory");
    int minLR=Params.getInt("MinReadLength"); 
    int SplitBracketMin=Params.getInt("SplitBracketMin"); 
    int SplitBaseQmin=Params.getInt("SplitBaseQmin"); 
    
    string StatFile=Params.getString("StatFile");
    if (StatFile.size()>0) {
        hists H1(StatFile);
        hist HLF=H1.h["LF"];
        hist HLR=H1.h["LR"];
        Params.setHist("LF",HLF);
        Params.setHist("LR",HLR);        
        H1.h.clear();  // free some memory 
        if (FragmentTailPercent>0) {
            LFlow=int(HLF.p2xTrim(FragmentTailPercent/100.));   
            LFhigh=int(HLF.p2xTrim(1-FragmentTailPercent/100.));   
        }
    }
    
    int dbg = Params.getInt("Dbg");
    time(&tprev);
    
    if (ReferenceFastaFile.size()>0) {
        FastaObj RF1(ReferenceFastaFile, "");
        Reference=RF1;
        RF1.seq.clear();  // free some memory 
    }
    
    bam_header= Bam.fp->header;
    string bamheadertext = bam_header->text;
    ReadGroup = extractBamTag(bamheadertext,"@RG");
    
    outAllPairsBam=(r.size()>0);
    if (!outAllPairsBam) { 
        outFragTailBam=true; //FragmentTailPercent>=0;
        outInterChromBam=true;
        outUniqueMultipleBam=true;
        outUniquePartialBam=true;
        outUniqueUnmappedBam=true;
    }
    // output Bams
    outputBam.clear();
    
    /*
    // test BamHeaderContainer
    vector<BamHeaderContainer> x;
    string sv=SpannerVersion;    
    string q="@PG\tID:FragmentTail\tPN:SpannerX\tVN"+sv+"\tCL:"+Params.getCmdLine();
    while (true) {
        string outfile=outputDirectory+"/"+filename+".fragtail.bam";
        q=q+"\n@PG\tID:FragmentTail\tPN:SpannerX\tVN"+sv+"\tCL:"+Params.getCmdLine();
        BamHeaderContainer x1( bam_header, q); 
        x.push_back(x1);
        bam_header_t* h1=x[x.size()-1].header();
        cout<< h1->text << endl;
    }
    cout << x.size() << endl;
    */
    
    samfile_t *fpFT=0;
    samfile_t *fpIC=0;
    samfile_t *fpUM=0;
    samfile_t *fpUP=0;
    samfile_t *fpUZ=0;
    samfile_t *fpAP=0;
    samfile_t *fpWP=0;
    
    //region
    if (r.size()>0) {
        int r1,r2,r3;
        C_region r0(r); 
        region=r0;
        string bamRegion=region.region;
        size_t k=bamRegion.find("chr");
        if (k!=string::npos) {
            bamRegion=bamRegion.substr(3);
        }

        if ( bam_parse_region(bam_header, bamRegion.c_str(), &r1, &r2, &r3)==0) {
            region.limit=true;
            region.anchor=r1;
            region.start=r2;
            region.end=r3;
        } else {
            cerr << "region not found\t" << r << endl;
            exit(111);
        }
        
    }
    
    
    //fragPosFile
    if (fragPosFile.size()>0) {
        
        FragmentPosFileObj fp(fragPosFile);
        if (fp.fragmentPosList.size()>0) {
            FragPos=fp;
        } else {
            cerr << "Read Pair Pos file not found\t" <<  fragPosFile << endl;
            exit(112);
        }
        outFragTailBam=false; 
        outInterChromBam=false;
        outUniqueMultipleBam=false;
        outUniquePartialBam=false;
        outUniqueUnmappedBam=false;
        outReadPairPosBam=true;
        
    }

    
    if (outAllPairsBam) {
        string outfile=outputDirectory+"/"+filename+"."+r+".bam";
        string sv=SpannerVersion;
        string q="@PG\tID:Region\tPN:SpannerX\tVN"+sv+"\tCL:"+Params.getCmdLine();
        outputBam["AP"]=BamHeaderContainer(bam_header,q); 
        bam_header_t* h1=outputBam["AP"].header();
        if ((fpAP = samopen(outfile.c_str(), "wb", h1)) == 0) {
            fprintf(stderr, "samopen: Fail to open output BAM file %s\n", filename.c_str());
            exit(160);
        }
    }

    
    if (outFragTailBam) {
        string outfile=outputDirectory+"/"+filename+".fragtail.bam";
        string sv=SpannerVersion;
        string q="@PG\tID:FragmentTail\tPN:SpannerX\tVN"+sv+"\tCL:"+Params.getCmdLine();
        outputBam["FT"]=BamHeaderContainer(bam_header,q); 
        bam_header_t* h1=outputBam["FT"].header();
        if ((fpFT = samopen(outfile.c_str(), "wb", h1)) == 0) {
            fprintf(stderr, "samopen: Fail to open output BAM file %s\n", filename.c_str());
            exit(161);
        }
    }
     
    if (outInterChromBam) {
        string outfile=outputDirectory+"/"+filename+".interchrom.bam";
        string sv=SpannerVersion;
        string q="@PG\tID:InterChromPairs\tPN:SpannerX\tVN"+sv+"\tCL:"+Params.getCmdLine();
        outputBam["IC"]=BamHeaderContainer(bam_header,q);   
        bam_header_t* h1=outputBam["IC"].header();
        if ((fpIC = samopen(outfile.c_str(), "wb", h1)) == 0) {
            fprintf(stderr, "samopen: Fail to open output BAM file %s\n", filename.c_str());
            exit(162);
        }
    }
    
    if (outUniqueMultipleBam) {
        string outfile=outputDirectory+"/"+filename+".uMult.bam";
        string sv=SpannerVersion;
        string q="@PG\tID:uniqMultiplyMappedPairs\tPN:SpannerX\tVN"+sv+"\tCL:"+Params.getCmdLine();
        outputBam["UM"]=BamHeaderContainer(bam_header,q); 
        bam_header_t* h1=outputBam["IUM"].header();
        if ((fpUM = samopen(outfile.c_str(), "wb", h1)) == 0) {
            fprintf(stderr, "samopen: Fail to open output BAM file %s\n", filename.c_str());
            exit(163);
        }
    }
    
    if (outUniquePartialBam) {        
        string outfile=outputDirectory+"/"+filename+".uPart.bam";
        string sv=SpannerVersion;
        string q="@PG\tID:uniqPartiallyMappedPairs\tPN:SpannerX\tVN"+sv+"\tCL:"+Params.getCmdLine();
        outputBam["UP"]=BamHeaderContainer(bam_header,q);  
        bam_header_t* h1=outputBam["UP"].header();
        if ((fpUP = samopen(outfile.c_str(), "wb", h1)) == 0) {
            fprintf(stderr, "samopen: Fail to open output BAM file %s\n", filename.c_str());
            exit(164);
        }
    }

    if (outUniqueUnmappedBam) {        
        string outfile=outputDirectory+"/"+filename+".uUnmapped.bam";
        string sv=SpannerVersion;
        string q="@PG\tID:uniqUnMappedPairs\tPN:SpannerX\tVN"+sv+"\tCL:"+Params.getCmdLine();
        outputBam["UZ"]=BamHeaderContainer(bam_header,q); 
        bam_header_t* h1=outputBam["UZ"].header();
        if ((fpUZ = samopen(outfile.c_str(), "wb", h1)) == 0) {
            fprintf(stderr, "samopen: Fail to open output BAM file %s\n", filename.c_str());
            exit(165);
        }

    }

    if (outReadPairPosBam) {        
        string outfile=outputDirectory+"/"+filename+".weirdpairs.bam";
        string sv=SpannerVersion;
        string q="@PG\tID:weirdpairs\tPN:SpannerX\tVN"+sv+"\tCL:"+Params.getCmdLine();
        outputBam["WP"]=BamHeaderContainer(bam_header,q); 
        bam_header_t* h1=outputBam["WP"].header();
        if ((fpWP = samopen(outfile.c_str(), "wb", h1)) == 0) {
            fprintf(stderr, "samopen: Fail to open output BAM file %s\n", filename.c_str());
            exit(165);
        }
        
    }

    
    cout << ReadGroup << endl << endl;
    
    //extractMateMode();
    
    if (cmd_MateMode>=0)   MateMode=cmd_MateMode;          
     
    BamContainerPair bampair;
    
    bool more = true;
    while (more)
    {
        bampair=Bam.getNextBamPair();
        // skip if neither end within region
        more=(bampair.BamEnd.size()>1);
        
        Npair++;
        if (Npair>=maxReads) break; 

        //
        if ( (dbg!=0)&&(elapsedtime()>float(dbg))) {
			time(&tprev);
			cout << " pairs:" << Npair << "\toutput:" << Nout;
			cout << "\tchr:" << bampair.BamEnd[0].b.core.tid+1;
            cout << "\tpos:" << bampair.BamEnd[0].b.core.pos;
            cout << endl;			
		}  
        
        if (!more) continue; 
        if (region.limit) {
            bool overlap = false;
            for (int e=0; e<=1; e++) {                 
                int a1=bampair.BamEnd[e].b.core.tid;
                int p1=bampair.BamEnd[e].b.core.pos;
                int p2=p1+bampair.BamEnd[e].len;
                overlap=region.overlap(a1,p1,p2);
                if (overlap) break; 
            }        
            if (!overlap) continue;
        }
    
        
        bampair.Illuminize(IlluminizeBam);  
        bampair.calcFragmentLengths();
        more=(bampair.BamEnd[1].packeddata.size()>1);
        //if (bampair.BamEnd[0].b.core.tid==bampair.BamEnd[1].b.core.tid) 
        //    cout<< bampair << endl;
        
        bool bothmap = ((bampair.BamEnd[0].b.core.flag&BAM_FUNMAP)==0)&&((bampair.BamEnd[0].b.core.flag&BAM_FMUNMAP)==0);
            
        
        if (outAllPairsBam) {
            Nout++;
            int s1=samwrite(fpAP, &(bampair.BamEnd[0].b));
            int s2=samwrite(fpAP, &(bampair.BamEnd[1].b));
            if ((s1*s2)>0) {
                continue;
            } else {
                cerr << "bad write to pairs.bam" << endl;
                exit(150);
            }
        }

        
        if (outReadPairPosBam) {
            int ichr1=bampair.BamEnd[0].b.core.tid+1;
            int istd1=bampair.BamEnd[0].sense=='+'? 0: 1;
            int ista1=bampair.BamEnd[0].b.core.pos+1;
            int iq1=bampair.BamEnd[0].q;
            int ichr2=bampair.BamEnd[1].b.core.tid+1;
            int istd2=bampair.BamEnd[1].sense=='+'? 0: 1;
            int ista2=bampair.BamEnd[1].b.core.pos+1;
            int iq2=bampair.BamEnd[1].q;
            
            FragmentPosObj  fp1(0,ichr1,istd1,ista1,0,ichr2,istd2,ista2,0,iq1, iq2,0);
            
            /*
             if ((fp1.chr1==10)&&(fp1.start1>=89687801)&&(fp1.end1<=89700722)) {
                cout << "read "<< fp1 << endl;                
            }
            */
            if (FragPos.find(fp1)) {
                Nout++;
                int s1=samwrite(fpWP, &(bampair.BamEnd[0].b));
                int s2=samwrite(fpWP, &(bampair.BamEnd[1].b));
                if ((s1*s2)>0) {
                    continue;
                } else {
                    cerr << "bad write to weirdpairs.bam" << endl;
                    exit(156);
                }
            }
        }        
        bool ok[2];
        for (int e=0; e<2; e++) {
            uint8_t*  bq=bam1_qual(&(bampair.BamEnd[e].b));
            int LR=bampair.BamEnd[0].b.core.l_qseq;
            double bok=0;
            for (int ib=0; ib<LR; ib++) {
                if (bq[ib]>SplitBaseQmin) {
                    bok++;
                }
            }
            ok[e]=(bok>LRmin);
        }
        
        if (! (ok[0]&ok[1]) )
            continue;
        
        if ( (outFragTailBam) & ((bampair.BamEnd[0].q>=Qmin)|(bampair.BamEnd[1].q>=Qmin)) ) {            
            bool FT=(bampair.FragmentLength>LFhigh)|((bampair.FragmentLength<LFlow)&(bampair.FragmentLength>INT_MIN))&bothmap;
            if (FT && (fpFT!=0)) {
                Nout++;
                int s1=samwrite(fpFT, &(bampair.BamEnd[0].b));
                int s2=samwrite(fpFT, &(bampair.BamEnd[1].b));
                //if (outputBam["FT"].write(&(bampair.BamEnd[0].b),&(bampair.BamEnd[1].b))) {
                if ((s1*s2)>0) {
                    continue;
                } else {
                    cerr << "bad write to fragtail.bam" << endl;
                    exit(151);
                }
            }
        }
        
        if ((outInterChromBam) & ((bampair.BamEnd[0].q>=Qmin)&(bampair.BamEnd[1].q>=Qmin))) { 
            bool IC=(bampair.BamEnd[0].b.core.tid!=bampair.BamEnd[1].b.core.tid)&&bothmap;
            if (IC && (fpIC!=0)) {
                Nout++;
                int s1=samwrite(fpIC, &(bampair.BamEnd[0].b));
                int s2=samwrite(fpIC, &(bampair.BamEnd[1].b));
                if ((s1*s2)>0) {
                    continue;
                } else {
                    cerr << "bad write to interchrom.bam" << endl;
                    exit(152);
                }
            }
        }
        if ((outUniqueMultipleBam) & ((bampair.BamEnd[0].q>=Qmin)|(bampair.BamEnd[1].q>=Qmin))){
            int im=bampair.BamEnd[0].nmap>1? 0: 1;
            int iu=bampair.BamEnd[0].q>=Qmin? 0: 1;
            bool UM=(bampair.BamEnd[iu].nmap>1)&&(iu!=im)&&bothmap;            
            if (UM && (fpUM!=0)) {
                Nout++;
                int s1=samwrite(fpUM, &(bampair.BamEnd[0].b));
                int s2=samwrite(fpUM, &(bampair.BamEnd[1].b));
                if ((s1*s2)>0) {
                    continue;
                } else {
                    cerr << "bad write to uMult.bam" << endl;
                    exit(153);
                }
            }
        }
        if ( (outUniquePartialBam) && ((bampair.BamEnd[0].q>=Qmin)|(bampair.BamEnd[1].q>=Qmin)) && bothmap) {            
            int c0=bampair.BamEnd[0].clip[0]+bampair.BamEnd[0].clip[1];
            int LR=bampair.BamEnd[0].b.core.l_qseq;
            bool split0=((LR-c0)>SplitBracketMin)&(c0>SplitBracketMin);
            int ib0=0;
            if ((split0)&(bampair.BamEnd[0].clip[0]>SplitBracketMin)) {
                ib0=bampair.BamEnd[0].clip[0];
            } else if ((split0)&(bampair.BamEnd[0].clip[1]>SplitBracketMin) ) {
                ib0=LR-bampair.BamEnd[0].clip[1];
            }
            split0=split0&(ib0>0);
            if (split0) {
                uint8_t*  bq=bam1_qual(&(bampair.BamEnd[0].b));
                for (int ib=(ib0-SplitBracketMin); ib<(ib0+SplitBracketMin); ib++) {
                    if (bq[ib]<SplitBaseQmin) {
                        split0=false;
                        break;
                    }
                }
            }
            
            int c1=bampair.BamEnd[1].clip[0]+bampair.BamEnd[1].clip[1];
            LR=bampair.BamEnd[1].b.core.l_qseq;
            bool split1=((LR-c0)>SplitBracketMin)&(c1>SplitBracketMin);;
            int ib1=0;
            if ((split1)&(bampair.BamEnd[1].clip[0]>SplitBracketMin)) {
                ib1=bampair.BamEnd[1].clip[0];
            } else if ((split1)&(bampair.BamEnd[1].clip[1]>SplitBracketMin) ) {
                ib1=LR-bampair.BamEnd[1].clip[1];
            }
            split1=split1&(ib1>0);
            if (split1) {
                uint8_t*  bq=bam1_qual(&(bampair.BamEnd[1].b));
                for (int ib=(ib1-SplitBracketMin); ib<(ib1+SplitBracketMin); ib++) {
                    if (bq[ib]<SplitBaseQmin) {
                        split1=false;
                        break;
                    }
                }
            }
            bool UP=(split0|split1)&((c1+c0)>minLR);
            if (UP && (fpUP!=0)) {
                Nout++;
                int s1=samwrite(fpUP, &(bampair.BamEnd[0].b));
                int s2=samwrite(fpUP, &(bampair.BamEnd[1].b));
                if ((s1*s2)>0) {
                    continue;
                } else {
                    cerr << "bad write to uPart.bam" << endl;
                    exit(154);
                }
            }
        }
        if ( (outUniqueUnmappedBam) & ((bampair.BamEnd[0].q>=Qmin)|(bampair.BamEnd[1].q>=Qmin)) ) {
            bool z0=((bampair.BamEnd[0].b.core.flag&BAM_FUNMAP)>0);
            bool z1=((bampair.BamEnd[1].b.core.flag&BAM_FUNMAP)>0);  
            
            
            uint8_t*  bq=bam1_qual(&(bampair.BamEnd[0].b));
            for (int nb,ib=0; ib<bampair.BamEnd[0].b.core.l_qseq; ib++) {
                if (bq[ib]<SplitBaseQmin) {
                    nb++;
                }
            }

            
            bool UZ=(z0|z1)&(!(z1&z0));
            if (UZ && (fpUZ!=0)) {
                Nout++;
                int s1=samwrite(fpUZ, &(bampair.BamEnd[0].b));
                int s2=samwrite(fpUZ, &(bampair.BamEnd[1].b));
                if ((s1*s2)>0) {
                    continue;
                } else {
                    cerr << "bad write to uUnmapped.bam" << endl;
                    exit(155);
                }
            }
        }
        
        
        //cout<< bampair.Orientation << "\t"<< bampair.FragmentLength << "\t" <<bampair.BamEnd[1].b.core.pos << endl;
        
    }
    
    if (outReadPairPosBam) {
        samclose(fpWP);
    } else {        
        if (outAllPairsBam) {
            samclose(fpAP);
        } else {       
            samclose(fpFT);
            samclose(fpIC);    
            samclose(fpUP);    
            samclose(fpUM);
            samclose(fpUZ);
        }
    }
    
    /*
     for (ioutputBam=outputBam.begin(); ioutputBam!=outputBam.end(); ioutputBam++) {
        (*ioutputBam).second.close();
    }
     
    if (FragmentTailPercent>0) 
        outputBam["FT"].close();
    */
    
    samclose(Bam.fp);
    
    
}
Exemple #20
0
void tSecureStream::m_setupServer(const tRSA& rsa, string appGreeting)
{
    // Read the greeting (part 1) from the client.
    // Note: The following DOES leak timing information, but we don't
    //       care because 'kLibrhoGreeting' isn't a secret.
    string receivedLibrhoGreeting;
    try {
        unpack(m_internal_readable, receivedLibrhoGreeting, (u32)kLibrhoGreeting.size());
    } catch (ebObject& e) {
        s_failConnection(m_internal_writable, "The secure client did not greet me properly.");
    }
    if (receivedLibrhoGreeting != kLibrhoGreeting)
        s_failConnection(m_internal_writable, "The secure client did not greet me properly.");

    // Read the greeting (part 2) from the client.
    // Note: The following DOES leak timing information, but we don't
    //       care because 'appGreeting' isn't a secret.
    string receivedAppGreeting;
    try {
        unpack(m_internal_readable, receivedAppGreeting, (u32)appGreeting.size());
    } catch (ebObject& e) {
        s_failConnection(m_internal_writable, "The secure client requested a different application.");
    }
    if (receivedAppGreeting != appGreeting)
        s_failConnection(m_internal_writable, "The secure client requested a different application.");

    // Read the client's random bytes.
    // Again, we don't care about the leaked info here because the correct
    // random vector length is not a secret.
    vector<u8> rand_c;
    try {
        unpack(m_internal_readable, rand_c, kRandVectLen);
    } catch (ebObject& e) {
        s_failConnection(m_internal_writable, "The secure client sent a random byte vector of the wrong length.");
    }
    if (rand_c.size() != kRandVectLen)
        s_failConnection(m_internal_writable, "The secure client sent a random byte vector of the wrong length.");

    // Read the encrypted pre-secret from the client.
    // (No info is leaked by this section.)
    vector<u8> enc;
    try {
        unpack(m_internal_readable, enc, rsa.maxMessageLength()+5);
    } catch (ebObject& e) {
        s_failConnection(m_internal_writable, "The secure client failed to send an encrypted pre-secret.");
    }

    // Now that the server has read everything from the client, it
    // will do some calculations.
    // We will protect this section with a const time block to
    // protect against timing side-channel attacks.
    vector<u8> pre_secret, rand_s, secret, f, gPrime;
    {
        // This object is constructed in this code block, and it
        // will be destructed when this block ends. The d'tor of
        // this class calls sleep() in order to enforce consistent
        // timing of the execution of this block.
        tConstTimeBlock ctb(&gServerProcessGreetingTimingHistory);

        // Decrypt the pre-secret and make sure it looks okay.
        pre_secret = rsa.decrypt(enc);
        if (pre_secret.size() != kPreSecretLen)
            s_failConnection(m_internal_writable, "The secure client gave a pre-secret that is the wrong length.");

        // Generate the server random byte vector.
        rand_s = s_genRand(kRandVectLen);

        // Calculated the shared secret (from the pre-secret).
        secret = H1(pre_secret, rand_c, rand_s);

        // Calculate the proof-of-server hash. (The convinces the client that we are the actual server.)
        f = H2(secret, rand_c, rand_s);

        // Calculate what the client correct response would be.
        gPrime = H3(secret, rand_c, rand_s);
    }

    // Write back to the client all this stuff.
    pack(m_internal_writable, kSuccessfulGreeting);
    pack(m_internal_writable, rand_s);
    pack(m_internal_writable, f);
    s_flush(m_internal_writable);

    // Have the client prove that it is a real client, not a reply attack.
    vector<u8> g;
    try {
        unpack(m_internal_readable, g, (u32)gPrime.size());
    } catch (ebObject& e) {
        throw eRuntimeError("The secure client failed to show proof that it is real.");
    }
    if (!s_constTimeIsEqual(g, gPrime))
        throw eRuntimeError("The secure client failed to show proof that it is real.");

    // Setup secure streams with the client.
    vector<u8> ksw = H4(pre_secret, secret, rand_c, rand_s);   // <-- the Key for the Server Writer
    vector<u8> kcw = H5(pre_secret, secret, rand_c, rand_s);   // <-- the Key for the Client Writer
    m_readable = new tReadableAES(m_internal_readable, kOpModeCBC,
                                  &kcw[0], s_toKeyLen(kcw.size()));
    m_writable = new tWritableAES(m_internal_writable, kOpModeCBC,
                                  &ksw[0], s_toKeyLen(ksw.size()));
}