Beispiel #1
0
  void PlaneGeometry::EnsurePerpendicularNormal( mitk::AffineTransform3D *transform )
  {
    /** \brief ensure column(2) of indexToWorldTransform-matrix to be perpendicular to plane, keep length and handedness. */

    VnlVector normal = vnl_cross_3d( transform->GetMatrix().GetVnlMatrix().get_column(0),
                                     transform->GetMatrix().GetVnlMatrix().get_column(1) );
    normal.normalize(); // Now normal is a righthand normal unit vector, perpendicular to the plane.

    ScalarType len = transform->GetMatrix().GetVnlMatrix().get_column(2).two_norm();
    if (len==0) { len = 1; }
    normal *= len;

    // Get the existing normal vector zed:
    vnl_vector_fixed<double, 3> zed = transform->GetMatrix().GetVnlMatrix().get_column(2);

    /** If det(matrix)<0, multiply normal vector by (-1) to keep geometry lefthanded. */
    if( vnl_determinant( transform->GetMatrix().GetVnlMatrix()) < 0 )
    {
      MITK_DEBUG << "EnsurePerpendicularNormal(): Lefthanded geometry preserved, rh-normal: [ " << normal << " ],";
      normal *= (-1.0);
      MITK_DEBUG << "lh-normal: [ " << normal << " ], original vector zed is: [ " << zed << " ]";
    }


    // Now lets compare and only replace if necessary and only then warn the user:

    // float epsilon is precise enough here, but we need to respect numerical condition:
    // Higham, N., 2002, Accuracy and Stability of Numerical Algorithms,
    // SIAM, page 37, 2nd edition:
    double feps = std::numeric_limits<float>::epsilon();
    double zedsMagnitude = zed.two_norm();
    feps = feps * zedsMagnitude * 2;

    /** Check if normal (3. column) was perpendicular: If not, replace with calculated normal vector: */
    if( normal != zed )
    {
      vnl_vector_fixed<double, 3> parallel;
      for ( unsigned int i = 0; i<3 ; ++i )
      {
        parallel[i] = normal[i] / zed[i]; // Remember linear algebra: checking for parallelity.
      }
      // Checking if really not paralell i.e. non-colinear vectors by comparing these floating point numbers:
      if(    (parallel[0]+feps < parallel[1] || feps+parallel[1] < parallel[0])
          && (parallel[0]+feps < parallel[2] || feps+parallel[2] < parallel[0]) )
      {
        MITK_WARN << "EnsurePerpendicularNormal(): Plane geometry was _/askew/_, so here it gets rectified by substituting"
                  << " the 3rd column of the indexToWorldMatrix with an appropriate normal vector: [ " << normal
                  << " ], original vector zed was: [ " << zed << " ].";

        Matrix3D matrix = transform->GetMatrix();
        matrix.GetVnlMatrix().set_column( 2, normal );
        transform->SetMatrix( matrix );
      }
    }
    else
    {
      // Nothing to do, 3rd column of indexToWorldTransformMatrix already was perfectly perpendicular.
    }
  }
bool PivotCalibration2::ComputeSpinCalibration(bool snapRotation)
{
	if (this->ToolToReferenceMatrices.size() < 10)
	{
		this->ErrorText = "Not enough input transforms are available";
		return false;
	}

	if (this->GetMaximumToolOrientationDifferenceDeg() < this->MinimumOrientationDifferenceDeg)
	{
		this->ErrorText = "Not enough variation in the input transforms";
		return false;
	}

	// Setup our system to find the axis of rotation
	unsigned int rows = 3, columns = 3;

	vnl_matrix<double> A(rows, columns, 0);

	vnl_matrix<double> I(3, 3, 0);
	I.set_identity();

	vnl_matrix<double> RI(rows, columns);


	// this will store the maximum difference in orientation between the first transform and all the other transforms
	double maximumOrientationDifferenceDeg = 0;

	std::vector< vtkSmartPointer<vtkMatrix4x4> >::const_iterator previt = this->ToolToReferenceMatrices.end();
	for (std::vector< vtkSmartPointer<vtkMatrix4x4> >::const_iterator it = this->ToolToReferenceMatrices.begin(); it != this->ToolToReferenceMatrices.end(); it++)
	{
		if (previt == this->ToolToReferenceMatrices.end())
		{
			previt = it;
			continue; // No comparison to make for the first matrix
		}

		vtkSmartPointer< vtkMatrix4x4 > itinverse = vtkSmartPointer< vtkMatrix4x4 >::New();
		vtkMatrix4x4::Invert((*it), itinverse);

		vtkSmartPointer< vtkMatrix4x4 > instRotation = vtkSmartPointer< vtkMatrix4x4 >::New();
		vtkMatrix4x4::Multiply4x4(itinverse, (*previt), instRotation);

		for (int i = 0; i < 3; i++)
		{
			for (int j = 0; j < 3; j++)
			{
				RI(i, j) = instRotation->GetElement(i, j);
			}
		}

		RI = RI - I;
		A = A + RI.transpose() * RI;

		previt = it;
	}

	// Note: If the needle orientation protocol changes, only the definitions of shaftAxis and secondaryAxes need to be changed
	// Define the shaft axis and the secondary shaft axis
	// Current needle orientation protocol dictates: shaft axis -z, orthogonal axis +x
	// If StylusX is parallel to ShaftAxis then: shaft axis -z, orthogonal axis +y
	vnl_vector<double> shaftAxis_Shaft(columns, 0); shaftAxis_Shaft(0) = 0; shaftAxis_Shaft(1) = 0; shaftAxis_Shaft(2) = -1;
	vnl_vector<double> orthogonalAxis_Shaft(columns, 0); orthogonalAxis_Shaft(0) = 1; orthogonalAxis_Shaft(1) = 0; orthogonalAxis_Shaft(2) = 0;
	vnl_vector<double> backupAxis_Shaft(columns, 0); backupAxis_Shaft(0) = 0; backupAxis_Shaft(1) = 1; backupAxis_Shaft(2) = 0;

	// Find the eigenvector associated with the smallest eigenvalue
	// This is the best axis of rotation over all instantaneous rotations
	vnl_matrix<double> eigenvectors(columns, columns, 0);
	vnl_vector<double> eigenvalues(columns, 0);
	vnl_symmetric_eigensystem_compute(A, eigenvectors, eigenvalues);
	// Note: eigenvectors are ordered in increasing eigenvalue ( 0 = smallest, end = biggest )
	vnl_vector<double> shaftAxis_ToolTip(columns, 0);
	shaftAxis_ToolTip(0) = eigenvectors(0, 0);
	shaftAxis_ToolTip(1) = eigenvectors(1, 0);
	shaftAxis_ToolTip(2) = eigenvectors(2, 0);
	shaftAxis_ToolTip.normalize();

	// Snap the direction vector to be exactly aligned with one of the coordinate axes
	// This is if the sensor is known to be parallel to one of the axis, just not which one
	if (snapRotation)
	{
		int closestCoordinateAxis = element_product(shaftAxis_ToolTip, shaftAxis_ToolTip).arg_max();
		shaftAxis_ToolTip.fill(0);
		shaftAxis_ToolTip.put(closestCoordinateAxis, 1); // Doesn't matter the direction, will be sorted out in the next step
	}

	// Make sure it is in the correct direction (opposite the StylusTipToStylus translation)
	vnl_vector<double> toolTipToToolTranslation(3);
	toolTipToToolTranslation(0) = this->ToolTipToToolMatrix->GetElement(0, 3);
	toolTipToToolTranslation(1) = this->ToolTipToToolMatrix->GetElement(1, 3);
	toolTipToToolTranslation(2) = this->ToolTipToToolMatrix->GetElement(2, 3);
	if (dot_product(shaftAxis_ToolTip, toolTipToToolTranslation) > 0)
	{
		shaftAxis_ToolTip = shaftAxis_ToolTip * (-1);
	}

	//set the RMSE
	this->SpinRMSE = (A * shaftAxis_ToolTip).rms();


	// If the secondary axis 1 is parallel to the shaft axis in the tooltip frame, then use secondary axis 2
	vnl_vector<double> orthogonalAxis_ToolTip;
	double angle = acos(dot_product(shaftAxis_ToolTip, orthogonalAxis_Shaft));
	// Force angle to be between -pi/2 and +pi/2
	if (angle > vtkMath::Pi() / 2)
	{
		angle -= vtkMath::Pi();
	}
	if (angle < -vtkMath::Pi() / 2)
	{
		angle += vtkMath::Pi();
	}
	if (fabs(angle) > vtkMath::RadiansFromDegrees(PARALLEL_ANGLE_THRESHOLD_DEGREES)) // If shaft axis and orthogonal axis are not parallel
	{
		orthogonalAxis_ToolTip = orthogonalAxis_Shaft;
	}
	else
	{
		orthogonalAxis_ToolTip = backupAxis_Shaft;
	}

	// Do the registration find the appropriate rotation
	orthogonalAxis_ToolTip = orthogonalAxis_ToolTip - dot_product(orthogonalAxis_ToolTip, shaftAxis_ToolTip) * shaftAxis_ToolTip;
	orthogonalAxis_ToolTip.normalize();

	// Register X,Y,O points in the two coordinate frames (only spherical registration - since pure rotation)
	vnl_matrix<double> ToolTipPoints(3, 3, 0.0);
	vnl_matrix<double> ShaftPoints(3, 3, 0.0);

	ToolTipPoints.put(0, 0, shaftAxis_ToolTip(0));
	ToolTipPoints.put(0, 1, shaftAxis_ToolTip(1));
	ToolTipPoints.put(0, 2, shaftAxis_ToolTip(2));
	ToolTipPoints.put(1, 0, orthogonalAxis_ToolTip(0));
	ToolTipPoints.put(1, 1, orthogonalAxis_ToolTip(1));
	ToolTipPoints.put(1, 2, orthogonalAxis_ToolTip(2));
	ToolTipPoints.put(2, 0, 0);
	ToolTipPoints.put(2, 1, 0);
	ToolTipPoints.put(2, 2, 0);

	ShaftPoints.put(0, 0, shaftAxis_Shaft(0));
	ShaftPoints.put(0, 1, shaftAxis_Shaft(1));
	ShaftPoints.put(0, 2, shaftAxis_Shaft(2));
	ShaftPoints.put(1, 0, orthogonalAxis_Shaft(0));
	ShaftPoints.put(1, 1, orthogonalAxis_Shaft(1));
	ShaftPoints.put(1, 2, orthogonalAxis_Shaft(2));
	ShaftPoints.put(2, 0, 0);
	ShaftPoints.put(2, 1, 0);
	ShaftPoints.put(2, 2, 0);

	vnl_svd<double> ShaftToToolTipRegistrator(ShaftPoints.transpose() * ToolTipPoints);
	vnl_matrix<double> V = ShaftToToolTipRegistrator.V();
	vnl_matrix<double> U = ShaftToToolTipRegistrator.U();
	vnl_matrix<double> Rotation = V * U.transpose();

	// Make sure the determinant is positve (i.e. +1)
	double determinant = vnl_determinant(Rotation);
	if (determinant < 0)
	{
		// Switch the sign of the third column of V if the determinant is not +1
		// This is the recommended approach from Huang et al. 1987
		V.put(0, 2, -V.get(0, 2));
		V.put(1, 2, -V.get(1, 2));
		V.put(2, 2, -V.get(2, 2));
		Rotation = V * U.transpose();
	}

	// Set the elements of the output matrix
	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			this->ToolTipToToolMatrix->SetElement(i, j, Rotation[i][j]);
		}
	}

	this->ErrorText.empty();
	return true;
}
Beispiel #3
0
int MCLR_SM::Active_Query()
{
	stop_training = false;

	// The max_info value and hence the algo converges if the user successively selects 
	//"I am not sure option" .. so whenever the user selects the "I am not sure option
	// delete that info value from max_info;
	if(current_label==0)
		max_info_vector.erase(max_info_vector.begin()+max_info_vector.size()-1);

	
	max_info = -1e9;
	int active_query = 0;
	//vnl_vector<double> diff_info_3_it(3,0);//difference in g vals for last 3 iterations
	//vnl_vector<double> g_3_it(3,0);	// g vals for the last three

	vnl_matrix<double> test_data_just_features =  test_data.transpose();
	//test_data_just_features = test_data_just_features.get_n_rows(0,test_data_just_features.rows()-1);
	vnl_matrix<double> prob = Test_Current_Model(test_data_just_features);
		

	vnl_matrix<double> test_data_bias = Add_Bias(test_data_just_features);
	vnl_vector<double> info_vector(test_data_just_features.cols());

	//Compute Information gain
	for(int i =0; i< test_data_just_features.cols();++i )
	{
		vnl_vector<double> temp_col_prob = prob.get_column(i);
		vnl_vector<double> temp_col_data = test_data_bias.get_column(i);		
		vnl_matrix<double> q = Kron(temp_col_prob,temp_col_data);//Kronecker Product
		vnl_diag_matrix<double> identity_matrix(no_of_classes,1); // Identity Matrix;
		double infoval = (q.transpose() * m.CRB.transpose() * q).get(0,0);
		vnl_matrix<double> info_matrix(no_of_classes,no_of_classes,infoval);
		info_matrix = identity_matrix + info_matrix ;
		info_vector(i) = log(vnl_determinant(info_matrix));
		if(info_vector(i)>max_info)
		{
			active_query = i;
			max_info = info_vector(i);
		}
	}

	max_info_vector.push_back(max_info);

//	std::cout<<max_info_vector.size() << "--" << max_info <<std::endl;

	if(max_info_vector.size()>1)
	  diff_info_3_it((max_info_vector.size()-1)%3) =  max_info_vector.at((max_info_vector.size()-1)) - max_info_vector.at((max_info_vector.size()-2));


	 info_3_it((max_info_vector.size()-1)%3) = max_info;	
	
	if (max_info_vector.size()>3) 
	{
		int sum = 0;
		for(int iter =0; iter < 3; iter++)
		{
			//std::cout<<fabs(diff_info_3_it(iter))/fabs(info_3_it(iter))<<std::endl;

			if(fabs(diff_info_3_it(iter))/fabs(info_3_it(iter)) < stop_cond(1))
			{
				sum = sum + 1;	
			}
		}
		// The algorithm is now confident about the problem
		// Training can be stopped
		if(sum==3)
			stop_training = true;
	}

	return active_query;
}
SEXP invariantSimilarityHelper(
  typename itk::Image< float , ImageDimension >::Pointer image1,
  typename itk::Image< float , ImageDimension >::Pointer image2,
  SEXP r_thetas, SEXP r_lsits, SEXP r_WM, SEXP r_scale,
  SEXP r_doreflection, SEXP r_txfn  )
{
  unsigned int mibins = 20;
  unsigned int localSearchIterations =
    Rcpp::as< unsigned int >( r_lsits ) ;
  std::string whichMetric = Rcpp::as< std::string >( r_WM );
  std::string txfn = Rcpp::as< std::string >( r_txfn );
  bool useprincaxis = true;
  typedef typename itk::ImageMaskSpatialObject<ImageDimension>::ImageType
    maskimagetype;
  typename maskimagetype::Pointer mask = ITK_NULLPTR;
  Rcpp::NumericVector thetas( r_thetas );
  Rcpp::NumericVector vector_r( r_thetas ) ;
  Rcpp::IntegerVector dims( 1 );
  Rcpp::IntegerVector doReflection( r_doreflection );
  unsigned int vecsize = thetas.size();
  dims[0]=0;
  typedef float  PixelType;
  typedef double RealType;
  RealType bestscale = Rcpp::as< RealType >( r_scale ) ;
  typedef itk::Image< PixelType , ImageDimension > ImageType;
  if( image1.IsNotNull() & image2.IsNotNull() )
    {
    typedef typename itk::ImageMomentsCalculator<ImageType> ImageCalculatorType;
    typedef itk::AffineTransform<RealType, ImageDimension> AffineType0;
    typedef itk::AffineTransform<RealType, ImageDimension> AffineType;
    typedef typename ImageCalculatorType::MatrixType       MatrixType;
    typedef itk::Vector<float, ImageDimension>  VectorType;
    VectorType ccg1;
    VectorType cpm1;
    MatrixType cpa1;
    VectorType ccg2;
    VectorType cpm2;
    MatrixType cpa2;
    typename ImageCalculatorType::Pointer calculator1 =
      ImageCalculatorType::New();
    typename ImageCalculatorType::Pointer calculator2 =
      ImageCalculatorType::New();
    calculator1->SetImage(  image1 );
    calculator2->SetImage(  image2 );
    typename ImageCalculatorType::VectorType fixed_center;
    fixed_center.Fill(0);
    typename ImageCalculatorType::VectorType moving_center;
    moving_center.Fill(0);
    try
      {
      calculator1->Compute();
      fixed_center = calculator1->GetCenterOfGravity();
      ccg1 = calculator1->GetCenterOfGravity();
      cpm1 = calculator1->GetPrincipalMoments();
      cpa1 = calculator1->GetPrincipalAxes();
      try
        {
        calculator2->Compute();
        moving_center = calculator2->GetCenterOfGravity();
        ccg2 = calculator2->GetCenterOfGravity();
        cpm2 = calculator2->GetPrincipalMoments();
        cpa2 = calculator2->GetPrincipalAxes();
        }
      catch( ... )
        {
        fixed_center.Fill(0);
        }
      }
    catch( ... )
      {
      // Rcpp::Rcerr << " zero image1 error ";
      }
    if ( vnl_math_abs( bestscale - 1.0 ) < 1.e-6 )
      {
      RealType volelt1 = 1;
      RealType volelt2 = 1;
      for ( unsigned int d=0; d<ImageDimension; d++)
        {
        volelt1 *= image1->GetSpacing()[d];
        volelt2 *= image2->GetSpacing()[d];
        }
      bestscale =
        ( calculator2->GetTotalMass() * volelt2 )/
        ( calculator1->GetTotalMass() * volelt1 );
      RealType powlev = 1.0 / static_cast<RealType>(ImageDimension);
      bestscale = vcl_pow( bestscale , powlev );
    }
    unsigned int eigind1 = 1;
    unsigned int eigind2 = 1;
    if( ImageDimension == 3 )
      {
      eigind1 = 2;
      }
    typedef vnl_vector<RealType> EVectorType;
    typedef vnl_matrix<RealType> EMatrixType;
    EVectorType evec1_2ndary = cpa1.GetVnlMatrix().get_row( eigind2 );
    EVectorType evec1_primary = cpa1.GetVnlMatrix().get_row( eigind1 );
    EVectorType evec2_2ndary  = cpa2.GetVnlMatrix().get_row( eigind2 );
    EVectorType evec2_primary = cpa2.GetVnlMatrix().get_row( eigind1 );
    /** Solve Wahba's problem http://en.wikipedia.org/wiki/Wahba%27s_problem */
    EMatrixType B = outer_product( evec2_primary, evec1_primary );
    if( ImageDimension == 3 )
      {
      B = outer_product( evec2_2ndary, evec1_2ndary )
        + outer_product( evec2_primary, evec1_primary );
      }
    vnl_svd<RealType>    wahba( B );
    vnl_matrix<RealType> A_solution = wahba.V() * wahba.U().transpose();
    A_solution = vnl_inverse( A_solution );
    RealType det = vnl_determinant( A_solution  );
    if( ( det < 0 ) )
      {
      vnl_matrix<RealType> id( A_solution );
      id.set_identity();
      for( unsigned int i = 0; i < ImageDimension; i++ )
        {
        if( A_solution( i, i ) < 0 )
          {
          id( i, i ) = -1.0;
          }
        }
      A_solution =  A_solution * id.transpose();
      }
    if ( doReflection[0] == 1 ||  doReflection[0] == 3 )
      {
        vnl_matrix<RealType> id( A_solution );
        id.set_identity();
        id = id - 2.0 * outer_product( evec2_primary , evec2_primary  );
        A_solution = A_solution * id;
      }
    if ( doReflection[0] > 1 )
      {
        vnl_matrix<RealType> id( A_solution );
        id.set_identity();
        id = id - 2.0 * outer_product( evec1_primary , evec1_primary  );
        A_solution = A_solution * id;
      }
    typename AffineType::Pointer affine1 = AffineType::New();
    typename AffineType::OffsetType trans = affine1->GetOffset();
    itk::Point<RealType, ImageDimension> trans2;
    for( unsigned int i = 0; i < ImageDimension; i++ )
      {
      trans[i] = moving_center[i] - fixed_center[i];
      trans2[i] =  fixed_center[i] * ( 1 );
      }
    affine1->SetIdentity();
    affine1->SetOffset( trans );
    if( useprincaxis )
      {
      affine1->SetMatrix( A_solution );
      }
    affine1->SetCenter( trans2 );
    if( ImageDimension > 3  )
      {
      return EXIT_SUCCESS;
      }
    vnl_vector<RealType> evec_tert;
    if( ImageDimension == 3 )
      { // try to rotate around tertiary and secondary axis
      evec_tert = vnl_cross_3d( evec1_primary, evec1_2ndary );
      }
    if( ImageDimension == 2 )
      { // try to rotate around tertiary and secondary axis
      evec_tert = evec1_2ndary;
      evec1_2ndary = evec1_primary;
      }
    itk::Vector<RealType, ImageDimension> axis2;
    itk::Vector<RealType, ImageDimension> axis1;
    for( unsigned int d = 0; d < ImageDimension; d++ )
      {
      axis1[d] = evec_tert[d];
      axis2[d] = evec1_2ndary[d];
      }
    typename AffineType::Pointer simmer = AffineType::New();
    simmer->SetIdentity();
    simmer->SetCenter( trans2 );
    simmer->SetOffset( trans );
    typename AffineType0::Pointer affinesearch = AffineType0::New();
    affinesearch->SetIdentity();
    affinesearch->SetCenter( trans2 );
    typedef  itk::MultiStartOptimizerv4         OptimizerType;
    typename OptimizerType::MetricValuesListType metricvalues;
    typename OptimizerType::Pointer  mstartOptimizer = OptimizerType::New();
    typedef itk::CorrelationImageToImageMetricv4
      <ImageType, ImageType, ImageType> GCMetricType;
    typedef itk::MattesMutualInformationImageToImageMetricv4
      <ImageType, ImageType, ImageType> MetricType;
    typename MetricType::ParametersType newparams(  affine1->GetParameters() );
    typename GCMetricType::Pointer gcmetric = GCMetricType::New();
    gcmetric->SetFixedImage( image1 );
    gcmetric->SetVirtualDomainFromImage( image1 );
    gcmetric->SetMovingImage( image2 );
    gcmetric->SetMovingTransform( simmer );
    gcmetric->SetParameters( newparams );
    typename MetricType::Pointer mimetric = MetricType::New();
    mimetric->SetNumberOfHistogramBins( mibins );
    mimetric->SetFixedImage( image1 );
    mimetric->SetMovingImage( image2 );
    mimetric->SetMovingTransform( simmer );
    mimetric->SetParameters( newparams );
    if( mask.IsNotNull() )
      {
      typename itk::ImageMaskSpatialObject<ImageDimension>::Pointer so =
        itk::ImageMaskSpatialObject<ImageDimension>::New();
      so->SetImage( const_cast<maskimagetype *>( mask.GetPointer() ) );
      mimetric->SetFixedImageMask( so );
      gcmetric->SetFixedImageMask( so );
      }
    typedef  itk::ConjugateGradientLineSearchOptimizerv4 LocalOptimizerType;
    typename LocalOptimizerType::Pointer  localoptimizer =
      LocalOptimizerType::New();
    RealType     localoptimizerlearningrate = 0.1;
    localoptimizer->SetLearningRate( localoptimizerlearningrate );
    localoptimizer->SetMaximumStepSizeInPhysicalUnits(
      localoptimizerlearningrate );
    localoptimizer->SetNumberOfIterations( localSearchIterations );
    localoptimizer->SetLowerLimit( 0 );
    localoptimizer->SetUpperLimit( 2 );
    localoptimizer->SetEpsilon( 0.1 );
    localoptimizer->SetMaximumLineSearchIterations( 50 );
    localoptimizer->SetDoEstimateLearningRateOnce( true );
    localoptimizer->SetMinimumConvergenceValue( 1.e-6 );
    localoptimizer->SetConvergenceWindowSize( 5 );
    if( true )
      {
      typedef typename MetricType::FixedSampledPointSetType PointSetType;
      typedef typename PointSetType::PointType              PointType;
      typename PointSetType::Pointer      pset(PointSetType::New());
      unsigned int ind=0;
      unsigned int ct=0;
      itk::ImageRegionIteratorWithIndex<ImageType> It(image1,
        image1->GetLargestPossibleRegion() );
      for( It.GoToBegin(); !It.IsAtEnd(); ++It )
        {
        // take every N^th point
        if ( ct % 10 == 0  )
          {
          PointType pt;
          image1->TransformIndexToPhysicalPoint( It.GetIndex(), pt);
          pset->SetPoint(ind, pt);
          ind++;
          }
          ct++;
        }
      mimetric->SetFixedSampledPointSet( pset );
      mimetric->SetUseFixedSampledPointSet( true );
      gcmetric->SetFixedSampledPointSet( pset );
      gcmetric->SetUseFixedSampledPointSet( true );
    }
    if ( whichMetric.compare("MI") == 0  ) {
      mimetric->Initialize();
      typedef itk::RegistrationParameterScalesFromPhysicalShift<MetricType>
      RegistrationParameterScalesFromPhysicalShiftType;
      typename RegistrationParameterScalesFromPhysicalShiftType::Pointer
      shiftScaleEstimator =
      RegistrationParameterScalesFromPhysicalShiftType::New();
      shiftScaleEstimator->SetMetric( mimetric );
      shiftScaleEstimator->SetTransformForward( true );
      typename RegistrationParameterScalesFromPhysicalShiftType::ScalesType
      movingScales( simmer->GetNumberOfParameters() );
      shiftScaleEstimator->EstimateScales( movingScales );
      mstartOptimizer->SetScales( movingScales );
      mstartOptimizer->SetMetric( mimetric );
      localoptimizer->SetMetric( mimetric );
      localoptimizer->SetScales( movingScales );
    }
    if ( whichMetric.compare("MI") != 0  ) {
      gcmetric->Initialize();
      typedef itk::RegistrationParameterScalesFromPhysicalShift<GCMetricType>
        RegistrationParameterScalesFromPhysicalShiftType;
      typename RegistrationParameterScalesFromPhysicalShiftType::Pointer
        shiftScaleEstimator =
        RegistrationParameterScalesFromPhysicalShiftType::New();
      shiftScaleEstimator->SetMetric( gcmetric );
      shiftScaleEstimator->SetTransformForward( true );
      typename RegistrationParameterScalesFromPhysicalShiftType::ScalesType
      movingScales( simmer->GetNumberOfParameters() );
      shiftScaleEstimator->EstimateScales( movingScales );
      mstartOptimizer->SetScales( movingScales );
      mstartOptimizer->SetMetric( gcmetric );
      localoptimizer->SetMetric( gcmetric );
      localoptimizer->SetScales( movingScales );
    }
    typename OptimizerType::ParametersListType parametersList =
      mstartOptimizer->GetParametersList();
    affinesearch->SetIdentity();
    affinesearch->SetCenter( trans2 );
    affinesearch->SetOffset( trans );
    for ( unsigned int i = 0; i < vecsize; i++ )
      {
      RealType ang1 = thetas[i];
      RealType ang2 = 0; // FIXME should be psi
      vector_r[ i ]=0;
      if( ImageDimension == 3 )
        {
        for ( unsigned int jj = 0; jj < vecsize; jj++ )
        {
        ang2=thetas[jj];
        affinesearch->SetIdentity();
        affinesearch->SetCenter( trans2 );
        affinesearch->SetOffset( trans );
        if( useprincaxis )
          {
          affinesearch->SetMatrix( A_solution );
          }
        affinesearch->Rotate3D(axis1, ang1, 1);
        affinesearch->Rotate3D(axis2, ang2, 1);
        affinesearch->Scale( bestscale );
        simmer->SetMatrix(  affinesearch->GetMatrix() );
        parametersList.push_back( simmer->GetParameters() );
        }
        }
      if( ImageDimension == 2 )
        {
        affinesearch->SetIdentity();
        affinesearch->SetCenter( trans2 );
        affinesearch->SetOffset( trans );
        if( useprincaxis )
          {
          affinesearch->SetMatrix( A_solution );
          }
        affinesearch->Rotate2D( ang1, 1);
        affinesearch->Scale( bestscale );
        simmer->SetMatrix(  affinesearch->GetMatrix() );
        typename AffineType::ParametersType pp =
          simmer->GetParameters();
        //pp[1]=ang1;
        //pp[0]=bestscale;
        parametersList.push_back( simmer->GetParameters() );
        }
      }
    mstartOptimizer->SetParametersList( parametersList );
    if( localSearchIterations > 0 )
      {
      mstartOptimizer->SetLocalOptimizer( localoptimizer );
      }
    mstartOptimizer->StartOptimization();
    typename AffineType::Pointer bestaffine = AffineType::New();
    bestaffine->SetCenter( trans2 );
    bestaffine->SetParameters( mstartOptimizer->GetBestParameters() );
    if ( txfn.length() > 3 )
      {
      typename AffineType::Pointer bestaffine = AffineType::New();
      bestaffine->SetCenter( trans2 );
      bestaffine->SetParameters( mstartOptimizer->GetBestParameters() );
      typedef itk::TransformFileWriter TransformWriterType;
      typename TransformWriterType::Pointer transformWriter =
        TransformWriterType::New();
      transformWriter->SetInput( bestaffine );
      transformWriter->SetFileName( txfn.c_str() );
      transformWriter->Update();
      }
    metricvalues = mstartOptimizer->GetMetricValuesList();
    for ( unsigned int k = 0; k < metricvalues.size(); k++ )
      {
      vector_r[k] = metricvalues[k];
      }
    dims[0] = vecsize;
    vector_r.attr( "dim" ) = vecsize;
    return Rcpp::wrap( vector_r );
    }
  else
    {
    return Rcpp::wrap( vector_r );
    }
}
int main(int argc , char** argv)
{

	MCLR *mclr = new MCLR();
	
	vnl_matrix<double> data;
	vnl_vector<double> classes;
	double sparsity = 1;
	int active_query = 1;
	double max_info = -1e9;
	
	int max_label_examples = atoi(argv[1]);

	//Get the training data with the classes
	vnl_matrix<double> Feats = Read_From_File("C:\\ActiveLearning\\spMCLogit_active_updated_06_02_11\\alltrain_gt2.txt");
	
	mclr->Initialize(Feats,sparsity,"ground_truth");
	mclr->Get_Training_Model();

	vnl_vector<double> diff_g_3_it(3,0);//difference in g vals for last 3 iterations
	vnl_vector<double> g_3_it(3,0);	// g vals for the last three

	

	for(int iteration = 0 ; iteration< max_label_examples ; ++ iteration)
	{
		vnl_matrix<double> test_data_just_features =  mclr->test_data.transpose();
		if(mclr->validation == "ground_truth")
		test_data_just_features = test_data_just_features.get_n_rows(0,test_data_just_features.rows()-3);
		else
		test_data_just_features = test_data_just_features.get_n_rows(0,test_data_just_features.rows()-2);

		vnl_matrix<double> prob = mclr->Test_Current_Model(test_data_just_features);
		

		vnl_matrix<double> test_data_bias = mclr->Add_Bias(test_data_just_features);
		vnl_vector<double> info_vector(test_data_just_features.cols());

		//Compute Information gain
		for(int i =0; i< test_data_just_features.cols();++i )
		{
			vnl_vector<double> temp_col_prob = prob.get_column(i);
			vnl_vector<double> temp_col_data = test_data_bias.get_column(i);		
			vnl_matrix<double> q = mclr->Kron(temp_col_prob,temp_col_data);//Kronecker Product
			vnl_diag_matrix<double> identity_matrix(mclr->no_of_classes,1); // Identity Matrix;
			double infoval = (q.transpose() * mclr->m.CRB.transpose() * q).get(0,0);
			vnl_matrix<double> info_matrix(mclr->no_of_classes,mclr->no_of_classes,infoval);
			info_matrix = identity_matrix + info_matrix ;
			info_vector(i) = log(vnl_determinant(info_matrix));
			if(info_vector(i)>max_info)
			{
				active_query = i;
				max_info = info_vector(i);
			}
		}
		
		mclr->Update_Train_Data(active_query);

		mclr->Get_Training_Model();

		std::cout<< max_info <<std::endl;

		//reset the max_info for next iteration
		max_info = -1e9;
	
	}
	


		vnl_matrix<double> test_data_just_features =  mclr->test_data.transpose();
		if(mclr->validation == "ground_truth")
		test_data_just_features = test_data_just_features.get_n_rows(0,test_data_just_features.rows()-3);
		else
		test_data_just_features = test_data_just_features.get_n_rows(0,test_data_just_features.rows()-2);
		vnl_matrix<double> currprob = mclr->Test_Current_Model(test_data_just_features);
		vnl_vector<double> gt = mclr->y_ground_truth;
		

		double accuracy = 0;

		for(int i = 0; i< currprob.cols() ; ++i)
		{
			vnl_vector<double> curr_col = currprob.get_column(i);
			if(curr_col.arg_max()+1 == gt(i))
				accuracy++;
		}
		
		double p = gt.size();

		std::cout<< accuracy/p <<std::endl;
}
Beispiel #6
0
  void
  PlaneGeometry::InitializeStandardPlane( mitk::ScalarType width, mitk::ScalarType height,
                                          const AffineTransform3D* transform /* = nullptr */,
                                          PlaneGeometry::PlaneOrientation planeorientation /* = Axial */,
                                          mitk::ScalarType zPosition /* = 0 */,
                                          bool frontside /* = true */,
                                          bool rotated /* = false */ )
  {
    Superclass::Initialize();

    /// construct standard view.

    // We define at the moment "frontside" as: axial from above,
    // coronal from front (nose), saggital from right.
    // TODO: Double check with medicals doctors or radiologists [ ].

    // We define the orientation in patient's view, e.g. LAI is in a axial cut
    // (parallel to the triangle ear-ear-nose):
    // first axis: To the left ear of the patient
    // seecond axis: To the nose of the patient
    // third axis: To the legs of the patient.

    // Options are: L/R left/right; A/P anterior/posterior; I/S inferior/superior
    // (AKA caudal/cranial).
    // We note on all cases in the following switch block r.h. for right handed
    // or l.h. for left handed to describe the different cases.
    // However, which system is chosen is defined at the end of the switch block.

    // CAVE / be careful: the vectors right and bottom are relative to the plane
    // and do NOT describe e.g. the right side of the patient.

    Point3D origin;
    /** Bottom means downwards, DV means Direction Vector. Both relative to the image! */
    VnlVector rightDV(3), bottomDV(3);
    /** Origin of this plane is by default a zero vector and implicitly in the top-left corner: */
    origin.Fill(0);
    /** This is different to all definitions in MITK, except the QT mouse clicks.
    *   But it is like this here and we don't want to change a running system.
    *   Just be aware, that IN THIS FUNCTION we define the origin at the top left (e.g. your screen). */

    /** NormalDirection defines which axis (i.e. column index in the transform matrix)
    * is perpendicular to the plane: */
    int normalDirection;

    switch(planeorientation) // Switch through our limited choice of standard planes:
    {
      case None:
        /** Orientation 'None' shall be done like the axial plane orientation,
         *  for whatever reasons. */
      case Axial:
        if(frontside) // Radiologist's view from below. A cut along the triangle ear-ear-nose.
        {
          if(rotated==false)
            /** Origin in the top-left corner, x=[1; 0; 0], y=[0; 1; 0], z=[0; 0; 1],
            *   origin=[0,0,zpos]: LAI (r.h.)
            *
            *  0---rightDV---->                            |
            *  |                                           |
            *  |  Picture of a finite, rectangular plane   |
            *  |  ( insert LOLCAT-scan here ^_^ )          |
            *  |                                           |
            *  v  _________________________________________|
            *
            */
          {
            FillVector3D(origin,   0,  0, zPosition);
            FillVector3D(rightDV,  1,  0,         0);
            FillVector3D(bottomDV, 0,  1,         0);
          }
          else  // Origin rotated to the bottom-right corner, x=[-1; 0; 0], y=[0; -1; 0], z=[0; 0; 1],
               // origin=[w,h,zpos]: RPI (r.h.)
          {   // Caveat emptor:  Still  using  top-left  as  origin  of  index  coordinate  system!
            FillVector3D(origin,   width,  height, zPosition);
            FillVector3D(rightDV,     -1,       0,         0);
            FillVector3D(bottomDV,     0,      -1,         0);
          }
        }
        else // 'Backside, not frontside.' Neuro-Surgeons's view from above patient.
        {
          if(rotated==false) // x=[-1; 0; 0], y=[0; 1; 0], z=[0; 0; 1], origin=[w,0,zpos]:  RAS (r.h.)
          {
            FillVector3D(origin,   width,  0, zPosition);
            FillVector3D(rightDV,     -1,  0,         0);
            FillVector3D(bottomDV,     0,  1,         0);
          }
          else // Origin in the bottom-left corner, x=[1; 0; 0], y=[0; -1; 0], z=[0; 0; 1],
              // origin=[0,h,zpos]:  LPS (r.h.)
          {
            FillVector3D(origin,   0,  height, zPosition);
            FillVector3D(rightDV,  1,       0,         0);
            FillVector3D(bottomDV, 0,      -1,         0);
          }
        }
        normalDirection = 2; // That is S=Superior=z=third_axis=middlefinger in righthanded LPS-system.
      break;

      // Frontal is known as Coronal in mitk. Plane cuts through patient's ear-ear-heel-heel:
      case Frontal:
        if(frontside)
        {
          if(rotated==false) // x=[1; 0; 0], y=[0; 0; 1], z=[0; 1; 0], origin=[0,zpos,0]: LAI (r.h.)
          {
            FillVector3D(origin,   0, zPosition, 0);
            FillVector3D(rightDV,  1, 0,         0);
            FillVector3D(bottomDV, 0, 0,         1);
          }
          else // x=[-1;0;0], y=[0;0;-1], z=[0;1;0], origin=[w,zpos,h]:  RAS  (r.h.)
          {
            FillVector3D(origin,   width, zPosition, height);
            FillVector3D(rightDV,     -1,         0,      0);
            FillVector3D(bottomDV,     0,         0,     -1);
          }
        }
        else
        {
          if(rotated==false) //  x=[-1;0;0], y=[0;0;1], z=[0;1;0], origin=[w,zpos,0]: RPI (r.h.)
          {
            FillVector3D(origin,    width, zPosition,  0);
            FillVector3D(rightDV,      -1,         0,  0);
            FillVector3D(bottomDV,      0,         0,  1);
          }
          else //  x=[1;0;0], y=[0;1;0], z=[0;0;-1], origin=[0,zpos,h]: LPS (r.h.)
          {
            FillVector3D(origin,   0, zPosition,  height);
            FillVector3D(rightDV,  1,         0,       0);
            FillVector3D(bottomDV, 0,         0,      -1);
          }
        }
        normalDirection = 1; // Normal vector = posterior direction.
      break;

      case Sagittal: // Sagittal=Medial plane, the symmetry-plane mirroring your face.
        if(frontside)
        {
          if(rotated==false) //  x=[0;1;0], y=[0;0;1], z=[1;0;0], origin=[zpos,0,0]:  LAI (r.h.)
          {
            FillVector3D(origin,   zPosition, 0, 0);
            FillVector3D(rightDV,  0,         1, 0);
            FillVector3D(bottomDV, 0,         0, 1);
          }
          else //  x=[0;-1;0], y=[0;0;-1], z=[1;0;0], origin=[zpos,w,h]:  LPS (r.h.)
          {
            FillVector3D(origin,   zPosition, width, height);
            FillVector3D(rightDV,          0,    -1,      0);
            FillVector3D(bottomDV,         0,     0,     -1);
          }
        }
        else
        {
          if(rotated==false) //  x=[0;-1;0], y=[0;0;1], z=[1;0;0], origin=[zpos,w,0]:  RPI (r.h.)
          {
            FillVector3D(origin,   zPosition,  width, 0);
            FillVector3D(rightDV,          0,     -1, 0);
            FillVector3D(bottomDV,         0,      0, 1);
          }
          else //  x=[0;1;0], y=[0;0;-1], z=[1;0;0], origin=[zpos,0,h]:  RAS (r.h.)
          {
            FillVector3D(origin,   zPosition,  0, height);
            FillVector3D(rightDV,          0,  1,      0);
            FillVector3D(bottomDV,         0,  0,     -1);
          }
        }
        normalDirection = 0; // Normal vector = Lateral direction: Left in a LPS-system.
      break;

      default:
        itkExceptionMacro("unknown PlaneOrientation");
    }

    /// Checking if lefthanded or righthanded:
    mitk::ScalarType lhOrRhSign=(+1);
    if ( transform != nullptr )
    {
      lhOrRhSign = ( (0 < vnl_determinant( transform->GetMatrix().GetVnlMatrix() )) ? (+1) : (-1) );

      MITK_DEBUG << "mitk::PlaneGeometry::InitializeStandardPlane(): lhOrRhSign, normalDirection, NameOfClass, ObjectName = "
                 << lhOrRhSign << ", " << normalDirection << ", " << transform->GetNameOfClass()
                 << ", " << transform->GetObjectName() << ".";

      origin = transform->TransformPoint( origin );
      rightDV = transform->TransformVector( rightDV );
      bottomDV = transform->TransformVector( bottomDV );

      /// Signing normal vector according to l.h./r.h. coordinate system:
      this->SetMatrixByVectors( rightDV,
                                bottomDV,
                                transform->GetMatrix().GetVnlMatrix().get_column(normalDirection).two_norm() * lhOrRhSign );
    }
    else if ( transform == nullptr )
    {
      this->SetMatrixByVectors( rightDV, bottomDV );
    }

    ScalarType bounds[6]= { 0, width, 0, height, 0, 1 };

    this->SetBounds( bounds );

    this->SetOrigin( origin );
  }