Esempio n. 1
0
void Reduced_grid::set_dimensions( int nx, int ny, int nz,
				     double xsize, double ysize, double zsize,
             std::vector<bool> mask, float rotation_angle_z ) 
{

  Cartesian_grid::set_dimensions( nx, ny, nz );
  GsTLCoordVector dims( xsize, ysize, zsize );
  geometry_->set_cell_dims( dims );
  this->set_rotation_z(rotation_angle_z);

  mask_ = mask;
  mgrid_cursor_ = new MaskedGridCursor(nx, ny, nz);
  grid_cursor_ = dynamic_cast<SGrid_cursor*>(mgrid_cursor_);


  build_ijkmap_from_mask();
	mgrid_cursor_->set_mask(&original2reduced_, &reduced2original_, &mask_ );
//  mgrid_cursor_ = new MaskedGridCursor(nx, ny, nz,
//                  &original2reduced_, &reduced2original_, &mask_ );
  
  active_size_ = mgrid_cursor_->max_index();
	property_manager_.set_prop_size( mgrid_cursor_->max_index() );
  region_manager_.set_region_size( mgrid_cursor_->max_index() );
}
Esempio n. 2
0
Domi::MDArrayRCP< T >
convertToMDArrayRCP(PyArrayObject * pyArray)
{
  // Get the number of dimensions and initialize the dimensions and
  // strides arrays
  int numDims = PyArray_NDIM(pyArray);
  Teuchos::Array< Domi::dim_type  > dims(   numDims);
  Teuchos::Array< Domi::size_type > strides(numDims);

  // Set the dimensions and strides
  for (int axis = 0; axis < numDims; ++axis)
  {
    dims[   axis] = (Domi::dim_type ) PyArray_DIM(   pyArray, axis);
    strides[axis] = (Domi::size_type) PyArray_STRIDE(pyArray, axis);
  }

  // Get the data pointer and layout
  T * data = (T*) PyArray_DATA(pyArray);
  Domi::Layout layout = PyArray_IS_C_CONTIGUOUS(pyArray) ? Domi::C_ORDER :
    Domi::FORTRAN_ORDER;

  // Return the result
  return Domi::MDArrayRCP< T >(dims, strides, data, layout);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void AvizoRectilinearCoordinateWriter::dataCheck()
{
  setErrorCondition(0);

  DataContainer::Pointer dc = getDataContainerArray()->getPrereqDataContainer<AbstractFilter>(this, getFeatureIdsArrayPath().getDataContainerName(), false);
  if (getErrorCondition() < 0) { return; }

  ImageGeom::Pointer image = dc->getPrereqGeometry<ImageGeom, AbstractFilter>(this);
  if (getErrorCondition() < 0 || NULL == image.get()) { return; }

  if(m_OutputFile.isEmpty() == true)
  {
    QString ss = QObject::tr("The output file must be set before executing this filter.");
    notifyErrorMessage(getHumanLabel(), ss, -1);
    setErrorCondition(-1);
  }
  if(m_WriteFeatureIds == true)
  {
    QVector<size_t> dims(1, 1);
    m_FeatureIdsPtr = getDataContainerArray()->getPrereqArrayFromPath<DataArray<int32_t>, AbstractFilter>(this, getFeatureIdsArrayPath(), dims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
    if( NULL != m_FeatureIdsPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
    { m_FeatureIds = m_FeatureIdsPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
  }
}
void
ctMode3D::Init()
{
	Parent::Init();

	vsBox3D dims( vsVector3D(-30.f, 0.f, -30.f), vsVector3D(30.f, 15.f, 30.f) );
	
	m_stage = new ctStage3D( dims );
	m_player = new ctPlayer3D( dims );
	m_player->SetPosition( vsVector2D(-25.f, 0.f) );
	
	m_stage->RegisterOnScene(0);
	m_player->RegisterOnScene(0);
	
	m_camera = new ctCamera3D;
	m_camera->Follow( m_player );
	vsSystem::GetScreen()->GetScene(0)->Set3D(true);
	vsSystem::GetScreen()->GetScene(0)->SetCamera3D(m_camera);
	
	
	//m_stage->AddBox( vsBox2D( vsVector2D(0.f,-2.f), vsVector2D(5.f,-1.f) ) );
	//m_stage->AddBox( vsBox2D( vsVector2D(10.f,-4.f), vsVector2D(15.f,-3.f) ) );
	//m_stage->AddBox( vsBox2D( vsVector2D(18.f,-5.f), vsVector2D(25.f,-4.f) ) );
}
Esempio n. 5
0
ExprVector::ExprVector(const ExprNode** comp, int n, bool in_row) :
		ExprNAryOp(comp, n, vec_dim(dims(comp,n),in_row)) {
}
Esempio n. 6
0
 dim_type array::dims(unsigned dim) const
 {
     return dims()[dim];
 }
  int NoiseAdjustGadget::process(GadgetContainerMessage<ISMRMRD::AcquisitionHeader>* m1, GadgetContainerMessage< hoNDArray< std::complex<float> > >* m2)
  {
    bool is_noise = m1->getObjectPtr()->isFlagSet(ISMRMRD::ISMRMRD_ACQ_IS_NOISE_MEASUREMENT);
    unsigned int channels = m1->getObjectPtr()->active_channels;
    unsigned int samples = m1->getObjectPtr()->number_of_samples;

    //TODO: Remove this
    if ( measurement_id_.empty() ) {
      unsigned int muid = m1->getObjectPtr()->measurement_uid;
      std::ostringstream ostr;
      ostr << muid;
      measurement_id_ = ostr.str();
    }

    if ( is_noise ) {
      if (noiseCovarianceLoaded_) {
	m1->release(); //Do not accumulate noise when we have a loaded noise covariance
	return GADGET_OK;
      }
      
      // this noise can be from a noise scan or it can be from the built-in noise
      if ( number_of_noise_samples_per_acquisition_ == 0 ) {
	number_of_noise_samples_per_acquisition_ = samples;
      }

      if ( noise_dwell_time_us_ < 0 ) {
	if (noise_dwell_time_us_preset_ > 0.0) {
	  noise_dwell_time_us_ = noise_dwell_time_us_preset_;
	} else {
	  noise_dwell_time_us_ = m1->getObjectPtr()->sample_time_us;
	}
      }

      //If noise covariance matrix is not allocated
      if (noise_covariance_matrixf_.get_number_of_elements() != channels*channels) {
	std::vector<size_t> dims(2, channels);
	try {
	  noise_covariance_matrixf_.create(&dims);
	  noise_covariance_matrixf_once_.create(&dims);
	} catch (std::runtime_error& err) {
	  GEXCEPTION(err, "Unable to allocate storage for noise covariance matrix\n" );
	  return GADGET_FAIL;
	}

	Gadgetron::clear(noise_covariance_matrixf_);
	Gadgetron::clear(noise_covariance_matrixf_once_);
	number_of_noise_samples_ = 0;
      }

      std::complex<float>* cc_ptr = noise_covariance_matrixf_.get_data_ptr();
      std::complex<float>* data_ptr = m2->getObjectPtr()->get_data_ptr();
      
      hoNDArray< std::complex<float> > readout(*m2->getObjectPtr());
      gemm(noise_covariance_matrixf_once_, readout, true, *m2->getObjectPtr(), false);
      Gadgetron::add(noise_covariance_matrixf_once_, noise_covariance_matrixf_, noise_covariance_matrixf_);

      number_of_noise_samples_ += samples;
      m1->release();
      return GADGET_OK;
    }


    //We should only reach this code if this data is not noise.
    if ( perform_noise_adjust_ ) {
      //Calculate the prewhitener if it has not been done
      if (!noise_decorrelation_calculated_ && (number_of_noise_samples_ > 0)) {
	if (number_of_noise_samples_ > 1) {
	  //Scale
	  noise_covariance_matrixf_ *= std::complex<float>(1.0/(float)(number_of_noise_samples_-1));
	  number_of_noise_samples_ = 1; //Scaling has been done
	}
	computeNoisePrewhitener();
	acquisition_dwell_time_us_ = m1->getObjectPtr()->sample_time_us;
	if ((noise_dwell_time_us_ == 0.0f) || (acquisition_dwell_time_us_ == 0.0f)) {
	  noise_bw_scale_factor_ = 1.0f;
	} else {
	  noise_bw_scale_factor_ = (float)std::sqrt(2.0*acquisition_dwell_time_us_/noise_dwell_time_us_*receiver_noise_bandwidth_);
	}

	noise_prewhitener_matrixf_ *= std::complex<float>(noise_bw_scale_factor_,0.0);

	GDEBUG("Noise dwell time: %f\n", noise_dwell_time_us_);
	GDEBUG("Acquisition dwell time: %f\n", acquisition_dwell_time_us_);
	GDEBUG("receiver_noise_bandwidth: %f\n", receiver_noise_bandwidth_);
	GDEBUG("noise_bw_scale_factor: %f", noise_bw_scale_factor_);
      }

      if (noise_decorrelation_calculated_) {
          //Apply prewhitener
          if ( noise_prewhitener_matrixf_.get_size(0) == m2->getObjectPtr()->get_size(1) ) {
               hoNDArray<std::complex<float> > tmp(*m2->getObjectPtr());
               gemm(*m2->getObjectPtr(), tmp, noise_prewhitener_matrixf_);
          } else {
               if (!pass_nonconformant_data_) {
                     m1->release();
                     GERROR("Number of channels in noise prewhitener %d is incompatible with incoming data %d\n", noise_prewhitener_matrixf_.get_size(0), m2->getObjectPtr()->get_size(1));
                     return GADGET_FAIL;
               }
          }
      }
    }

    if (this->next()->putq(m1) == -1) {
      GDEBUG("Error passing on data to next gadget\n");
      return GADGET_FAIL;
    }
    
    return GADGET_OK;

  }
Esempio n. 8
0
 void dims(std::vector<T> x, std::vector<size_t> ds) {
   ds.push_back(x.size());
   if (x.size() > 0)
     dims(x[0],ds);
 }
    /**
     *
     * @param parentId
     * @return
     */
    virtual int writeH5Data(hid_t parentId)
    {

      int err = 0;

      // Generate the number of neighbors array and also compute the total number
      // of elements that would be needed to flatten the array
      std::vector<int32_t> numNeighbors(_data.size());

      size_t total = 0;
      for(size_t dIdx = 0; dIdx < _data.size(); ++dIdx)
      {
        numNeighbors[dIdx] = static_cast<int32_t>(_data[dIdx]->size());
        total += _data[dIdx]->size();
      }

      // Check to see if the NumNeighbors is already written to the file
      bool rewrite = false;
      if (H5Lite::datasetExists(parentId, DREAM3D::FieldData::NumNeighbors) == false)
      {
        rewrite = true;
      }
      else
      {
        std::vector<int32_t> fileNumNeigh(_data.size());
        err = H5Lite::readVectorDataset(parentId, DREAM3D::FieldData::NumNeighbors, fileNumNeigh);
        if (err < 0)
        {
          return -602;
        }

        // Compare the 2 vectors to make sure they are exactly the same;
        if (fileNumNeigh.size() != numNeighbors.size())
        {
          rewrite = true;
        }
        // The sizes are the same, now compare each value;
        int32_t* numNeighPtr = &(numNeighbors.front());
        int32_t* fileNumNeiPtr = &(fileNumNeigh.front());
        size_t nBytes = numNeighbors.size() * sizeof(int32_t);
        if (::memcmp(numNeighPtr, fileNumNeiPtr, nBytes) != 0)
        {
          rewrite = true;
        }
      }

      // Write out the NumNeighbors Array
      if(rewrite == true)
      {
        std::vector<hsize_t> dims(1, numNeighbors.size());
        err = H5Lite::writeVectorDataset(parentId, DREAM3D::FieldData::NumNeighbors, dims, numNeighbors);
        if(err < 0)
        {
          return -603;
        }
        err = H5Lite::writeScalarAttribute(parentId, DREAM3D::FieldData::NumNeighbors, std::string(H5_NUMCOMPONENTS), 1);
        if(err < 0)
        {
          return -605;
        }
        err = H5Lite::writeStringAttribute(parentId, DREAM3D::FieldData::NumNeighbors, DREAM3D::HDF5::ObjectType, "DataArray<T>");
        if(err < 0)
        {
          return -604;
        }
      }

      // Allocate an array of the proper size to we can concatenate all the arrays together into a single array that
      // can be written to the HDF5 File. This operation can ballon the memory size temporarily until this operation
      // is complete.
      std::vector<T> flat (total);
      size_t currentStart = 0;
      for(size_t dIdx = 0; dIdx < _data.size(); ++dIdx)
      {
        size_t nEle = _data[dIdx]->size();
        if (nEle == 0) { continue; }
        T* start = &(_data[dIdx]->front()); // Get the pointer to the front of the array
        //    T* end = start + nEle; // Get the pointer to the end of the array
        T* dst = &(flat.front()) + currentStart;
        ::memcpy(dst, start, nEle*sizeof(T));

        currentStart += _data[dIdx]->size();
      }

      int32_t rank = 1;
      hsize_t dims[1] = { total };
      if (total > 0)
      {
        err = H5Lite::writePointerDataset(parentId, GetName(), rank, dims, &(flat.front()));
        if(err < 0)
        {
          return -605;
        }
        err = H5Lite::writeScalarAttribute(parentId, GetName(), std::string(H5_NUMCOMPONENTS), 1);
        if(err < 0)
        {
          return -606;
        }

        err = H5Lite::writeStringAttribute(parentId, GetName(), DREAM3D::HDF5::ObjectType, getNameOfClass());
        if(err < 0)
        {
          return -607;
        }

        err = H5Lite::writeStringAttribute(parentId, GetName(), "Linked NumNeighbors Dataset", DREAM3D::FieldData::NumNeighbors);
        if(err < 0)
        {
          return -608;
        }
      }
      return err;
    }
Esempio n. 10
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
  void TestDataArray()
  {
    int32_t* ptr = NULL;
    {
      Int32ArrayType::Pointer d = Int32ArrayType::CreateArray(0, "Test7");
      DREAM3D_REQUIRE_EQUAL(0, d->getSize());
      DREAM3D_REQUIRE_EQUAL(0, d->getNumberOfTuples());
      ptr = d->getPointer(0);
      DREAM3D_REQUIRE_EQUAL(ptr, 0);
      DREAM3D_REQUIRE_EQUAL(d->isAllocated(), false);
    }

    {
      QVector<size_t> dims(1, NUM_COMPONENTS);
      Int32ArrayType::Pointer int32Array = Int32ArrayType::CreateArray(NUM_ELEMENTS, dims, "Test8");
      ptr = int32Array->getPointer(0);
      DREAM3D_REQUIRE_EQUAL(int32Array->isAllocated(), true);
      DREAM3D_REQUIRE_EQUAL(NUM_ELEMENTS, int32Array->getNumberOfTuples());
      DREAM3D_REQUIRE_EQUAL(NUM_ELEMENTS * NUM_COMPONENTS, int32Array->getSize());

      for (int i = 0; i < NUM_TUPLES; ++i)
      {
        for (int c = 0; c < NUM_COMPONENTS; ++c)
        {
          int32Array->setComponent(i, c, i + c);
        }
      }

      // Resize Larger
      int32Array->resize(NUM_TUPLES_2);
      DREAM3D_REQUIRE_EQUAL(NUM_TUPLES_2, int32Array->getNumberOfTuples());
      DREAM3D_REQUIRE_EQUAL(NUM_ELEMENTS_2, int32Array->getSize());
      DREAM3D_REQUIRE_EQUAL(int32Array->isAllocated(), true);

      // This should have saved our data so lets look at the data and compare it
      for (int i = 0; i < NUM_TUPLES; ++i)
      {
        for (int c = 0; c < NUM_COMPONENTS; ++c)
        {
          DREAM3D_REQUIRE_EQUAL( (int32Array->getComponent(i, c)), (i + c))
        }
      }

      // Resize Smaller - Which should have still saved some of our data
      int32Array->resize(NUM_TUPLES_3);
      DREAM3D_REQUIRE_EQUAL(NUM_TUPLES_3, int32Array->getNumberOfTuples());
      DREAM3D_REQUIRE_EQUAL(NUM_ELEMENTS_3, int32Array->getSize());
      DREAM3D_REQUIRE_EQUAL(int32Array->isAllocated(), true);

      // This should have saved our data so lets look at the data and compare it
      for (int i = 0; i < NUM_TUPLES; ++i)
      {
        for (int c = 0; c < NUM_COMPONENTS; ++c)
        {
          DREAM3D_REQUIRE_EQUAL( (int32Array->getComponent(i, c)), (i + c))
        }
      }

      // Change number of components
      //    dims[0] = NUM_COMPONENTS_4;
      //    int32Array->setDims(dims);
      //    DREAM3D_REQUIRE_EQUAL(NUM_TUPLES_4, int32Array->getNumberOfTuples());
      //    DREAM3D_REQUIRE_EQUAL(NUM_ELEMENTS_4, int32Array->getSize());

      double temp = 9999;
      int32Array->initializeTuple(0, temp );
      for (int c = 0; c < NUM_COMPONENTS; ++c)
      {
        DREAM3D_REQUIRE_EQUAL( (int32Array->getComponent(0, c)), (9999))
      }


      ptr = int32Array->getPointer(0);
    }

  }
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void VisualizeGBCDPoleFigure::execute()
{
  setErrorCondition(0);
  dataCheck();
  if(getErrorCondition() < 0) { return; }

  // Make sure any directory path is also available as the user may have just typed
  // in a path without actually creating the full path
  QFileInfo fi(getOutputFile());

  QDir dir(fi.path());
  if(!dir.mkpath("."))
  {
    QString ss;
    ss = QObject::tr("Error creating parent path '%1'").arg(dir.path());
    setErrorCondition(-1);
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
    return;
  }

  QFile file(getOutputFile());
  if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
  {
    QString ss = QObject::tr("Error opening output file '%1'").arg(getOutputFile());
    setErrorCondition(-100);
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
    return;
  }

  FloatArrayType::Pointer gbcdDeltasArray = FloatArrayType::CreateArray(5, "GBCDDeltas");
  gbcdDeltasArray->initializeWithZeros();

  FloatArrayType::Pointer gbcdLimitsArray = FloatArrayType::CreateArray(10, "GBCDLimits");
  gbcdLimitsArray->initializeWithZeros();

  Int32ArrayType::Pointer gbcdSizesArray = Int32ArrayType::CreateArray(5, "GBCDSizes");
  gbcdSizesArray->initializeWithZeros();

  float* gbcdDeltas = gbcdDeltasArray->getPointer(0);
  int* gbcdSizes = gbcdSizesArray->getPointer(0);
  float* gbcdLimits = gbcdLimitsArray->getPointer(0);

  // Original Ranges from Dave R.
  //m_GBCDlimits[0] = 0.0f;
  //m_GBCDlimits[1] = cosf(1.0f*m_pi);
  //m_GBCDlimits[2] = 0.0f;
  //m_GBCDlimits[3] = 0.0f;
  //m_GBCDlimits[4] = cosf(1.0f*m_pi);
  //m_GBCDlimits[5] = 2.0f*m_pi;
  //m_GBCDlimits[6] = cosf(0.0f);
  //m_GBCDlimits[7] = 2.0f*m_pi;
  //m_GBCDlimits[8] = 2.0f*m_pi;
  //m_GBCDlimits[9] = cosf(0.0f);

  // Greg R. Ranges
  gbcdLimits[0] = 0.0f;
  gbcdLimits[1] = 0.0f;
  gbcdLimits[2] = 0.0f;
  gbcdLimits[3] = 0.0f;
  gbcdLimits[4] = 0.0f;
  gbcdLimits[5] = SIMPLib::Constants::k_PiOver2;
  gbcdLimits[6] = 1.0f;
  gbcdLimits[7] = SIMPLib::Constants::k_PiOver2;
  gbcdLimits[8] = 1.0f;
  gbcdLimits[9] = SIMPLib::Constants::k_2Pi;

  // reset the 3rd and 4th dimensions using the square grid approach
  gbcdLimits[3] = -sqrtf(SIMPLib::Constants::k_PiOver2);
  gbcdLimits[4] = -sqrtf(SIMPLib::Constants::k_PiOver2);
  gbcdLimits[8] = sqrtf(SIMPLib::Constants::k_PiOver2);
  gbcdLimits[9] = sqrtf(SIMPLib::Constants::k_PiOver2);

  // get num components of GBCD
  QVector<size_t> cDims = m_GBCDPtr.lock()->getComponentDimensions();

  gbcdSizes[0] = cDims[0];
  gbcdSizes[1] = cDims[1];
  gbcdSizes[2] = cDims[2];
  gbcdSizes[3] = cDims[3];
  gbcdSizes[4] = cDims[4];

  gbcdDeltas[0] = (gbcdLimits[5] - gbcdLimits[0]) / float(gbcdSizes[0]);
  gbcdDeltas[1] = (gbcdLimits[6] - gbcdLimits[1]) / float(gbcdSizes[1]);
  gbcdDeltas[2] = (gbcdLimits[7] - gbcdLimits[2]) / float(gbcdSizes[2]);
  gbcdDeltas[3] = (gbcdLimits[8] - gbcdLimits[3]) / float(gbcdSizes[3]);
  gbcdDeltas[4] = (gbcdLimits[9] - gbcdLimits[4]) / float(gbcdSizes[4]);

  float vec[3] = { 0.0f, 0.0f, 0.0f };
  float vec2[3] = { 0.0f, 0.0f, 0.0f };
  float rotNormal[3] = { 0.0f, 0.0f, 0.0f };
  float rotNormal2[3] = { 0.0f, 0.0f, 0.0f };
  float sqCoord[2] = { 0.0f, 0.0f };
  float dg[3][3] = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } };
  float dgt[3][3] = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } };
  float dg1[3][3] = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } };
  float dg2[3][3] = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } };
  float sym1[3][3] = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } };
  float sym2[3][3] = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } };
  float sym2t[3][3] = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } };
  float mis_euler1[3] = { 0.0f, 0.0f, 0.0f };

  float misAngle = m_MisorientationRotation.angle * SIMPLib::Constants::k_PiOver180;
  float normAxis[3] = { m_MisorientationRotation.h, m_MisorientationRotation.k, m_MisorientationRotation.l };
  MatrixMath::Normalize3x1(normAxis);
  // convert axis angle to matrix representation of misorientation
  FOrientArrayType om(9, 0.0f);
  FOrientTransformsType::ax2om(FOrientArrayType(normAxis[0], normAxis[1], normAxis[2], misAngle), om);
  om.toGMatrix(dg);

  // take inverse of misorientation variable to use for switching symmetry
  MatrixMath::Transpose3x3(dg, dgt);

  // Get our SpaceGroupOps pointer for the selected crystal structure
  SpaceGroupOps::Pointer orientOps = m_OrientationOps[m_CrystalStructures[m_PhaseOfInterest]];

  // get number of symmetry operators
  int32_t n_sym = orientOps->getNumSymOps();

  int32_t xpoints = 100;
  int32_t ypoints = 100;
  int32_t zpoints = 1;
  int32_t xpointshalf = xpoints / 2;
  int32_t ypointshalf = ypoints / 2;
  float xres = 2.0f / float(xpoints);
  float yres = 2.0f / float(ypoints);
  float zres = (xres + yres) / 2.0;
  float x = 0.0f, y = 0.0f;
  float sum = 0;
  int32_t count = 0;
  bool nhCheck = false;
  int32_t hemisphere = 0;

  int32_t shift1 = gbcdSizes[0];
  int32_t shift2 = gbcdSizes[0] * gbcdSizes[1];
  int32_t shift3 = gbcdSizes[0] * gbcdSizes[1] * gbcdSizes[2];
  int32_t shift4 = gbcdSizes[0] * gbcdSizes[1] * gbcdSizes[2] * gbcdSizes[3];

  int64_t totalGBCDBins = gbcdSizes[0] * gbcdSizes[1] * gbcdSizes[2] * gbcdSizes[3] * gbcdSizes[4] * 2;

  QVector<size_t> dims(1, 1);
  DoubleArrayType::Pointer poleFigureArray = DoubleArrayType::NullPointer();
  poleFigureArray = DoubleArrayType::CreateArray(xpoints * ypoints, dims, "PoleFigure");
  poleFigureArray->initializeWithZeros();
  double* poleFigure = poleFigureArray->getPointer(0);

  for (int32_t k = 0; k < ypoints; k++)
  {
    for (int32_t l = 0; l < xpoints; l++)
    {
      // get (x,y) for stereographic projection pixel
      x = float(l - xpointshalf) * xres + (xres / 2.0);
      y = float(k - ypointshalf) * yres + (yres / 2.0);
      if ((x * x + y * y) <= 1.0)
      {
        sum = 0.0f;
        count = 0;
        vec[2] = -((x * x + y * y) - 1) / ((x * x + y * y) + 1);
        vec[0] = x * (1 + vec[2]);
        vec[1] = y * (1 + vec[2]);
        MatrixMath::Multiply3x3with3x1(dgt, vec, vec2);

        // Loop over all the symetry operators in the given cystal symmetry
        for (int32_t i = 0; i < n_sym; i++)
        {
          //get symmetry operator1
          orientOps->getMatSymOp(i, sym1);
          for (int32_t j = 0; j < n_sym; j++)
          {
            // get symmetry operator2
            orientOps->getMatSymOp(j, sym2);
            MatrixMath::Transpose3x3(sym2, sym2t);
            // calculate symmetric misorientation
            MatrixMath::Multiply3x3with3x3(dg, sym2t, dg1);
            MatrixMath::Multiply3x3with3x3(sym1, dg1, dg2);
            // convert to euler angle
            FOrientArrayType eu(mis_euler1, 3);
            FOrientTransformsType::om2eu(FOrientArrayType(dg2), eu);
            if (mis_euler1[0] < SIMPLib::Constants::k_PiOver2 && mis_euler1[1] < SIMPLib::Constants::k_PiOver2 && mis_euler1[2] < SIMPLib::Constants::k_PiOver2)
            {
              mis_euler1[1] = cosf(mis_euler1[1]);
              // find bins in GBCD
              int32_t location1 = int32_t((mis_euler1[0] - gbcdLimits[0]) / gbcdDeltas[0]);
              int32_t location2 = int32_t((mis_euler1[1] - gbcdLimits[1]) / gbcdDeltas[1]);
              int32_t location3 = int32_t((mis_euler1[2] - gbcdLimits[2]) / gbcdDeltas[2]);
              //find symmetric poles using the first symmetry operator
              MatrixMath::Multiply3x3with3x1(sym1, vec, rotNormal);
              //get coordinates in square projection of crystal normal parallel to boundary normal
              nhCheck = getSquareCoord(rotNormal, sqCoord);
              // Note the switch to have theta in the 4 slot and cos(Phi) int he 3 slot
              int32_t location4 = int32_t((sqCoord[0] - gbcdLimits[3]) / gbcdDeltas[3]);
              int32_t location5 = int32_t((sqCoord[1] - gbcdLimits[4]) / gbcdDeltas[4]);
              if (location1 >= 0 && location2 >= 0 && location3 >= 0 && location4 >= 0 && location5 >= 0 &&
                  location1 < gbcdSizes[0] && location2 < gbcdSizes[1] && location3 < gbcdSizes[2] && location4 < gbcdSizes[3] && location5 < gbcdSizes[4])
              {
                hemisphere = 0;
                if (nhCheck == false) { hemisphere = 1; }
                sum += m_GBCD[(m_PhaseOfInterest * totalGBCDBins) + 2 * ((location5 * shift4) + (location4 * shift3) + (location3 * shift2) + (location2 * shift1) + location1) + hemisphere];
                count++;
              }
            }

            // again in second crystal reference frame
            // calculate symmetric misorientation
            MatrixMath::Multiply3x3with3x3(dgt, sym2, dg1);
            MatrixMath::Multiply3x3with3x3(sym1, dg1, dg2);
            // convert to euler angle
            FOrientTransformsType::om2eu(FOrientArrayType(dg2), eu);
            if (mis_euler1[0] < SIMPLib::Constants::k_PiOver2 && mis_euler1[1] < SIMPLib::Constants::k_PiOver2 && mis_euler1[2] < SIMPLib::Constants::k_PiOver2)
            {
              mis_euler1[1] = cosf(mis_euler1[1]);
              // find bins in GBCD
              int32_t location1 = int32_t((mis_euler1[0] - gbcdLimits[0]) / gbcdDeltas[0]);
              int32_t location2 = int32_t((mis_euler1[1] - gbcdLimits[1]) / gbcdDeltas[1]);
              int32_t location3 = int32_t((mis_euler1[2] - gbcdLimits[2]) / gbcdDeltas[2]);
              // find symmetric poles using the first symmetry operator
              MatrixMath::Multiply3x3with3x1(sym1, vec2, rotNormal2);
              // get coordinates in square projection of crystal normal parallel to boundary normal
              nhCheck = getSquareCoord(rotNormal2, sqCoord);
              // Note the switch to have theta in the 4 slot and cos(Phi) int he 3 slot
              int32_t location4 = int32_t((sqCoord[0] - gbcdLimits[3]) / gbcdDeltas[3]);
              int32_t location5 = int32_t((sqCoord[1] - gbcdLimits[4]) / gbcdDeltas[4]);
              if (location1 >= 0 && location2 >= 0 && location3 >= 0 && location4 >= 0 && location5 >= 0 &&
                  location1 < gbcdSizes[0] && location2 < gbcdSizes[1] && location3 < gbcdSizes[2] && location4 < gbcdSizes[3] && location5 < gbcdSizes[4])
              {
                hemisphere = 0;
                if (nhCheck == false) { hemisphere = 1; }
                sum += m_GBCD[(m_PhaseOfInterest * totalGBCDBins) + 2 * ((location5 * shift4) + (location4 * shift3) + (location3 * shift2) + (location2 * shift1) + location1) + hemisphere];
                count++;
              }
            }
          }
        }
        if (count > 0)
        {
          poleFigure[(k * xpoints) + l] = sum / float(count);
        }
      }
    }
  }

  FILE* f = NULL;
  f = fopen(m_OutputFile.toLatin1().data(), "wb");
  if (NULL == f)
  {
    QString ss = QObject::tr("Error opening output file '%1'").arg(m_OutputFile);
    setErrorCondition(-1);
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
    return;
  }

  // Write the correct header
  fprintf(f, "# vtk DataFile Version 2.0\n");
  fprintf(f, "data set from DREAM3D\n");
  fprintf(f, "BINARY");
  fprintf(f, "\n");
  fprintf(f, "DATASET RECTILINEAR_GRID\n");
  fprintf(f, "DIMENSIONS %d %d %d\n", xpoints + 1, ypoints + 1, zpoints + 1);

  // Write the Coords
  writeCoords(f, "X_COORDINATES", "float", xpoints + 1, (-float(xpoints)*xres / 2.0f), xres);
  writeCoords(f, "Y_COORDINATES", "float", ypoints + 1, (-float(ypoints)*yres / 2.0f), yres);
  writeCoords(f, "Z_COORDINATES", "float", zpoints + 1, (-float(zpoints)*zres / 2.0f), zres);

  int32_t total = xpoints * ypoints * zpoints;
  fprintf(f, "CELL_DATA %d\n", total);

  fprintf(f, "SCALARS %s %s 1\n", "Intensity", "float");
  fprintf(f, "LOOKUP_TABLE default\n");
  {
    float* gn = new float[total];
    float t;
    count = 0;
    for (int32_t j = 0; j < ypoints; j++)
    {
      for (int32_t i = 0; i < xpoints; i++)
      {
        t = float(poleFigure[(j * xpoints) + i]);
        SIMPLib::Endian::FromSystemToBig::convert(t);
        gn[count] = t;
        count++;
      }
    }
    size_t totalWritten = fwrite(gn, sizeof(float), (total), f);
    delete[] gn;
    if (totalWritten != (total))
    {
      QString ss = QObject::tr("Error writing binary VTK data to file '%1'").arg(m_OutputFile);
      setErrorCondition(-1);
      notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
      fclose(f);
      return;
    }
  }
  fclose(f);

  /* Let the GUI know we are done with this filter */
  notifyStatusMessage(getHumanLabel(), "Complete");
}
void HDF5GeneralDataLayer<Dtype>::LoadGeneralHDF5FileData(const char* filename) {
  DLOG(INFO) << "Loading The general HDF5 file" << filename;
  hid_t file_id = H5Fopen(filename, H5F_ACC_RDONLY, H5P_DEFAULT);
  if (file_id < 0) {
    LOG(ERROR) << "Failed opening HDF5 file" << filename;
  }

  HDF5GeneralDataParameter data_param = this->layer_param_.hdf5_general_data_param();
  int fieldNum = data_param.field_size();
  hdf_blobs_.resize(fieldNum);

  const int MIN_DATA_DIM = 1;
  const int MAX_DATA_DIM = 4;
  for(int i = 0; i < fieldNum; ++i){
	  //LOG(INFO) << "Data type: " << data_param.datatype(i).data();
	  if(i < data_param.datatype_size() && 
      strcmp(data_param.datatype(i).data(), "int8") == 0){
		  
      // We take out the io functions here
      const char* dataset_name_ = data_param.field(i).data();
      hdf_blobs_[i] = shared_ptr<Blob<Dtype> >(new Blob<Dtype>());

		  CHECK(H5LTfind_dataset(file_id, dataset_name_))
        << "Failed to find HDF5 dataset " << dataset_name_;
      // Verify that the number of dimensions is in the accepted range.
      herr_t status;
      int ndims;
      status = H5LTget_dataset_ndims(file_id, dataset_name_, &ndims);
      CHECK_GE(status, 0) << "Failed to get dataset ndims for " << dataset_name_;
      CHECK_GE(ndims, MIN_DATA_DIM);
      CHECK_LE(ndims, MAX_DATA_DIM);
      
      // Verify that the data format is what we expect: int8
      std::vector<hsize_t> dims(ndims);
      H5T_class_t class_;
      status = H5LTget_dataset_info(file_id, dataset_name_, dims.data(), &class_, NULL);
      CHECK_GE(status, 0) << "Failed to get dataset info for " << dataset_name_;
      CHECK_EQ(class_, H5T_INTEGER) << "Expected integer data";

      vector<int> blob_dims(dims.size());
      for (int j = 0; j < dims.size(); ++j) {
        blob_dims[j] = dims[j];
      }
      hdf_blobs_[i]->Reshape(blob_dims);
      std::cout<<"Trying to allocate memories!\n";
		  int* buffer_data = new int[hdf_blobs_[i]->count()];
      std::cout<<"Memories loaded!!!\n";
		  status = H5LTread_dataset_int(file_id, dataset_name_, buffer_data);
		  CHECK_GE(status, 0) << "Failed to read int8 dataset " << dataset_name_;

		  Dtype* target_data = hdf_blobs_[i]->mutable_cpu_data();
		  for(int j = 0; j < hdf_blobs_[i]->count(); j++){
			  //LOG(INFO) << Dtype(buffer_data[j]);
			  target_data[j] = Dtype(buffer_data[j]);
		  }
		  delete buffer_data;

	  }else{
      // The dataset is still the float32 datatype
      hdf_blobs_[i] = shared_ptr<Blob<Dtype> >(new Blob<Dtype>());
		  hdf5_load_nd_dataset(file_id, data_param.field(i).data(),
        MIN_DATA_DIM, MAX_DATA_DIM, hdf_blobs_[i].get());
	  }
  }

  herr_t status = H5Fclose(file_id);
  CHECK_GE(status, 0) << "Failed to close HDF5 file " << filename;

  for(int i = 1; i < fieldNum; ++i){
	  CHECK_EQ(hdf_blobs_[0]->num(), hdf_blobs_[i]->num());
  }
  data_permutation_.clear();
  data_permutation_.resize(hdf_blobs_[0]->shape(0));
  for (int i = 0; i < hdf_blobs_[0]->shape(0); i++)
    data_permutation_[i] = i;
  //TODO: DATA SHUFFLE
  //LOG(INFO) << "Successully loaded " << data_blob_.num() << " rows";
}
Esempio n. 13
0
void TensorflowTensor::create(tensorflow::Tensor&& tensorflowTensor) {
    m_tensorflowTensor = tensorflowTensor;
    auto shape = m_tensorflowTensor.shape();
    for(int i = 0; i < shape.dims(); ++i)
        m_shape.addDimension(shape.dim_size(i));
}
Esempio n. 14
0
void testArrayPropHashes()
{
    std::string archiveName = "arrayHashTest.abc";
    {
        AO::WriteArchive w;
        ABCA::ArchiveWriterPtr a = w(archiveName, ABCA::MetaData());
        ABCA::ObjectWriterPtr archive = a->getTop();
        ABCA::ObjectWriterPtr child;

        // add a time sampling for later use
        std::vector < double > timeSamps(1,-4.0);
        ABCA::TimeSamplingType tst(3.0);
        ABCA::TimeSampling ts(tst, timeSamps);
        a->addTimeSampling(ts);

        // 2 objects without any properties whatsoever
        archive->createChild(ABCA::ObjectHeader("emptyA", ABCA::MetaData()));
        archive->createChild(ABCA::ObjectHeader("emptyB", ABCA::MetaData()));

        // 2 objects with with the same property with no samples
        child = archive->createChild(ABCA::ObjectHeader(
            "1propA", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("empty",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);

        child = archive->createChild(ABCA::ObjectHeader(
            "1propB", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("empty",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);

        // 2 objects with with the same property with a differnt name from above
        child = archive->createChild(ABCA::ObjectHeader(
            "1propAName", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("null",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);

        child = archive->createChild(ABCA::ObjectHeader(
            "1propBName", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("null",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);

        // 2 objects with with the same property with a differnt MetaData
        ABCA::MetaData m;
        m.set("Bleep", "bloop");
        child = archive->createChild(ABCA::ObjectHeader(
            "1propAMeta", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("empty", m,
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);

        child = archive->createChild(ABCA::ObjectHeader(
            "1propBMeta", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("empty", m,
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);

        // 2 objects with with the same property with a different POD
        child = archive->createChild(ABCA::ObjectHeader(
            "1propAPod", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("empty",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kFloat32POD, 1), 0);

        child = archive->createChild(ABCA::ObjectHeader(
            "1propBPod", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("empty",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kFloat32POD, 1), 0);

        // 2 objects with with the same property with a different extent
        child = archive->createChild(ABCA::ObjectHeader(
            "1propAExtent", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("empty",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 2), 0);

        child = archive->createChild(ABCA::ObjectHeader(
            "1propBExtent", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("empty",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 2), 0);

        // 2 objects with with the same property with a differnt time sampling
        child = archive->createChild(ABCA::ObjectHeader(
            "1propATS", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("empty",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 1);

        child = archive->createChild(ABCA::ObjectHeader(
            "1propBTS", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("empty",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 1);

        // 2 objects with 1 sample
        ABCA::ArrayPropertyWriterPtr awp;
        std::vector <Alembic::Util::int32_t> vali(4, 0);
        Alembic::Util::Dimensions dims(4);
        ABCA::DataType i32d(Alembic::Util::kInt32POD, 1);

        child = archive->createChild(ABCA::ObjectHeader(
            "1propA1Samp", ABCA::MetaData()));
        awp = child->getProperties()->createArrayProperty("int",
            ABCA::MetaData(), ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);
        awp->setSample(ABCA::ArraySample(&(vali.front()), i32d, dims));

        child = archive->createChild(ABCA::ObjectHeader(
            "1propB1Samp", ABCA::MetaData()));
        awp = child->getProperties()->createArrayProperty("int",
            ABCA::MetaData(), ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);
        awp->setSample(ABCA::ArraySample(&(vali.front()), i32d, dims));

        // 2 objects with 2 samples, no repeats
        std::vector <Alembic::Util::int32_t> valiB(4, 1);

        child = archive->createChild(ABCA::ObjectHeader(
            "1propA2Samp", ABCA::MetaData()));
        awp = child->getProperties()->createArrayProperty("int",
            ABCA::MetaData(), ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);
        awp->setSample(ABCA::ArraySample(&(vali.front()), i32d, dims));
        awp->setSample(ABCA::ArraySample(&(valiB.front()), i32d, dims));

        child = archive->createChild(ABCA::ObjectHeader(
            "1propB2Samp", ABCA::MetaData()));
        awp = child->getProperties()->createArrayProperty("int",
            ABCA::MetaData(), ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);
        awp->setSample(ABCA::ArraySample(&(vali.front()), i32d, dims));
        awp->setSample(ABCA::ArraySample(&(valiB.front()), i32d, dims));

        // 2 objects with 4 samples, with repeats
        child = archive->createChild(ABCA::ObjectHeader(
            "1propA4Samp", ABCA::MetaData()));
        awp = child->getProperties()->createArrayProperty("int",
            ABCA::MetaData(), ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);
        awp->setSample(ABCA::ArraySample(&(vali.front()), i32d, dims));
        awp->setSample(ABCA::ArraySample(&(vali.front()), i32d, dims));
        awp->setSample(ABCA::ArraySample(&(valiB.front()), i32d, dims));
        awp->setSample(ABCA::ArraySample(&(valiB.front()), i32d, dims));

        child = archive->createChild(ABCA::ObjectHeader(
            "1propB4Samp", ABCA::MetaData()));
        awp = child->getProperties()->createArrayProperty("int",
            ABCA::MetaData(), ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);
        awp->setSample(ABCA::ArraySample(&(vali.front()), i32d, dims));
        awp->setSample(ABCA::ArraySample(&(vali.front()), i32d, dims));
        awp->setSample(ABCA::ArraySample(&(valiB.front()), i32d, dims));
        awp->setSample(ABCA::ArraySample(&(valiB.front()), i32d, dims));

        // 2 objects with 1 samplem different dimensions
        Alembic::Util::Dimensions dimsB;
        dimsB.setRank(2);
        dimsB[0] = 2;
        dimsB[1] = 2;

        child = archive->createChild(ABCA::ObjectHeader(
            "1propA1Dims", ABCA::MetaData()));
        awp = child->getProperties()->createArrayProperty("int",
            ABCA::MetaData(), ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);
        awp->setSample(ABCA::ArraySample(&(vali.front()), i32d, dimsB));

        child = archive->createChild(ABCA::ObjectHeader(
            "1propB1Dims", ABCA::MetaData()));
        awp = child->getProperties()->createArrayProperty("int",
            ABCA::MetaData(), ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);
        awp->setSample(ABCA::ArraySample(&(vali.front()), i32d, dimsB));

        // 2 objects with with the same 2 properties with no samples
        child = archive->createChild(ABCA::ObjectHeader(
            "2propA", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("empty", ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);
        child->getProperties()->createArrayProperty("null",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);

        child = archive->createChild(ABCA::ObjectHeader(
            "2propB", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("empty",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);
        child->getProperties()->createArrayProperty("null",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);

        // 2 objects with with the same 2 properties created in opposite order
        child = archive->createChild(ABCA::ObjectHeader(
            "2propASwap", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("null",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);
        child->getProperties()->createArrayProperty("empty",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);

        child = archive->createChild(ABCA::ObjectHeader(
            "2propBSwap", ABCA::MetaData()));
        child->getProperties()->createArrayProperty("null",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);
        child->getProperties()->createArrayProperty("empty",  ABCA::MetaData(),
            ABCA::DataType(Alembic::Util::kInt32POD, 1), 0);
    }

    {
        AO::ReadArchive r;
        ABCA::ArchiveReaderPtr a = r( archiveName );
        ABCA::ObjectReaderPtr archive = a->getTop();

        TESTING_ASSERT(archive->getNumChildren() == 26);

        // every 2 hashes should be the same
        for (size_t i = 0; i < archive->getNumChildren(); i += 2)
        {
            Alembic::Util::Digest dA, dB;
            TESTING_ASSERT(archive->getChild(i)->getPropertiesHash(dA) &&
                archive->getChild(i+1)->getPropertiesHash(dB));
            TESTING_ASSERT(dA == dB);
        }

        // make sure that every 2 child objects have different properties hashes
        for (size_t i = 0; i < archive->getNumChildren() / 2; ++i)
        {
            Alembic::Util::Digest dA;
            archive->getChild(i*2)->getPropertiesHash(dA);
            for (size_t j = i + 1; j < archive->getNumChildren() / 2; ++j)
            {
                Alembic::Util::Digest dB;
                archive->getChild(j*2)->getPropertiesHash(dB);
                TESTING_ASSERT(dA != dB);
            }
        }
    }
}
void CoordinateTransformation::process() {

    // do nothing, if neither input data nor coordinate system selection has changed
    if (!geometryInport_.hasChanged() && !volumeInport_.hasChanged() && !forceUpdate_)
        return;

    // clear output
    delete geometryOutport_.getData();
    geometryOutport_.setData(0);
    forceUpdate_ = false;

    // return if no input data present
    if (!geometryInport_.hasData() || !volumeInport_.hasData())
        return;

    // retrieve and check geometry from inport
    PointListGeometryVec3* geometrySrc = dynamic_cast<PointListGeometryVec3*>(geometryInport_.getData());
    PointSegmentListGeometryVec3* geometrySegmentSrc = dynamic_cast<PointSegmentListGeometryVec3*>(geometryInport_.getData());
    if (!geometrySrc && !geometrySegmentSrc) {
        LWARNING("Geometry of type TGTvec3PointListGeometry or TGTvec3PointSegmentListGeometry expected");
        return;
    }

    // retrieve volume handle from inport
    VolumeHandle* volumeHandle = volumeInport_.getData();
    tgtAssert(volumeHandle, "No volume handle");
    tgtAssert(volumeHandle->getVolume(), "No volume");

    // create output geometry object
    PointListGeometryVec3* geometryConv = 0;
    PointSegmentListGeometryVec3* geometrySegmentConv = 0;
    if (geometrySrc)
        geometryConv = new PointListGeometryVec3();
    else if (geometrySegmentSrc)
        geometrySegmentConv = new PointSegmentListGeometryVec3();

    //
    // convert points
    //

    // voxel coordinates (no transformation necessary)
    if (targetCoordinateSystem_.isSelected("voxel-coordinates")) {
        // pointlist
        if (geometrySrc) {
            std::vector<tgt::vec3> geomPointsConv = std::vector<tgt::vec3>(geometrySrc->getData());
            geometryConv->setData(geomPointsConv);
        }
        // segmentlist
        else if (geometrySegmentSrc) {
            std::vector< std::vector<tgt::vec3> >geomPointsConv = std::vector< std::vector<tgt::vec3> >(geometrySegmentSrc->getData());
            geometrySegmentConv->setData(geomPointsConv);
        }
    }
    // volume coordinates
    else if (targetCoordinateSystem_.isSelected("volume-coordinates")) {
        tgt::vec3 dims(volumeHandle->getVolume()->getDimensions());
        tgt::vec3 cubeSize = volumeHandle->getVolume()->getCubeSize();
        // pointlist
        if (geometrySrc) {
            std::vector<tgt::vec3> geomPointsConv = std::vector<tgt::vec3>(geometrySrc->getData());
            for (size_t i=0; i<geomPointsConv.size(); i++)
                geomPointsConv[i] = ((geomPointsConv[i]/dims) - 0.5f) * cubeSize;
            geometryConv->setData(geomPointsConv);
        }
        // segmentlist
        else if (geometrySegmentSrc) {
            std::vector< std::vector<tgt::vec3> >geomPointsConv = std::vector< std::vector<tgt::vec3> >(geometrySegmentSrc->getData());
            for (size_t i=0; i<geomPointsConv.size(); ++i) {
                for (size_t j=0; j<geomPointsConv[i].size(); ++j) {
                    geomPointsConv[i][j] = ((geomPointsConv[i][j]/dims) - 0.5f) * cubeSize;
                }
                geometrySegmentConv->addSegment(geomPointsConv[i]);
            }
        }
    }
    // world coordinates
    else if (targetCoordinateSystem_.isSelected("world-coordinates")) {
        tgt::mat4 voxelToWorldTrafo = volumeHandle->getVolume()->getVoxelToWorldMatrix();
        // pointlist
        if (geometrySrc) {
            std::vector<tgt::vec3> geomPointsConv = std::vector<tgt::vec3>(geometrySrc->getData());
            for (size_t i=0; i<geomPointsConv.size(); i++)
                geomPointsConv[i] = voxelToWorldTrafo * geomPointsConv[i];
            geometryConv->setData(geomPointsConv);
        }
        // segmentlist
        else if (geometrySegmentSrc) {
            std::vector< std::vector<tgt::vec3> >geomPointsConv = std::vector< std::vector<tgt::vec3> >(geometrySegmentSrc->getData());
            for (size_t i=0; i<geomPointsConv.size(); ++i) {
                for (size_t j=0; j<geomPointsConv[i].size(); ++j) {
                    geomPointsConv[i][j] = voxelToWorldTrafo * geomPointsConv[i][j];
                }
                geometrySegmentConv->addSegment(geomPointsConv[i]);
            }
        }
    }
    // texture coordinates: [0:1.0]^3
    else if (targetCoordinateSystem_.isSelected("texture-coordinates")) {
        tgt::vec3 dims(volumeHandle->getVolume()->getDimensions());
        // pointlist
        if (geometrySrc) {
            std::vector<tgt::vec3> geomPointsConv = std::vector<tgt::vec3>(geometrySrc->getData());
            for (size_t i=0; i<geomPointsConv.size(); i++)
                geomPointsConv[i] /= dims;
            geometryConv->setData(geomPointsConv);
        }
        // segmentlist
        else if (geometrySegmentSrc) {
            std::vector< std::vector<tgt::vec3> >geomPointsConv = std::vector< std::vector<tgt::vec3> >(geometrySegmentSrc->getData());
            for (size_t i=0; i<geomPointsConv.size(); ++i) {
                for (size_t j=0; j<geomPointsConv[i].size(); ++j) {
                    geomPointsConv[i][j] /= dims;
                }
                geometrySegmentConv->addSegment(geomPointsConv[i]);
            }
        }
    }

    // assign result to outport
    if (geometrySrc)
        geometryOutport_.setData(geometryConv);
    else if (geometrySegmentSrc)
        geometryOutport_.setData(geometrySegmentConv);
    else {
        LWARNING("No geometry object created");
    }
}
Esempio n. 16
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void SurfaceMeshToVtk::dataCheck()
{
  setErrorCondition(0);
  if (m_OutputVtkFile.isEmpty() == true)
  {
    setErrorCondition(-1003);
    notifyErrorMessage(getHumanLabel(), "Vtk Output file is Not set correctly", -1003);
  }

  QString dcName;
  if (m_SelectedFaceArrays.size() > 0)
  {
    dcName = m_SelectedFaceArrays[0].getDataContainerName();
  }
  else if(m_SelectedVertexArrays.size() > 0)
  {
    dcName = m_SelectedVertexArrays[0].getDataContainerName();
  }

  foreach(DataArrayPath dap, m_SelectedFaceArrays)
  {
    if(dap.getDataContainerName().compare(dcName) != 0)
    {
      setErrorCondition(-385);
      notifyErrorMessage(getHumanLabel(), "The Face arrays and Vertex arrays must come from the same Data Container.", getErrorCondition());
      return;
    }
  }
  foreach(DataArrayPath dap, m_SelectedVertexArrays)
  {
    if(dap.getDataContainerName().compare(dcName) != 0)
    {
      setErrorCondition(-386);
      notifyErrorMessage(getHumanLabel(), "The Face arrays and Vertex arrays must come from the same Data Container.", getErrorCondition());
      return;
    }
  }

  DataContainer::Pointer sm = getDataContainerArray()->getPrereqDataContainer<AbstractFilter>(this, dcName, false);
  if(getErrorCondition() < 0) { return; }

  TriangleGeom::Pointer triangles =  sm->getPrereqGeometry<TriangleGeom, AbstractFilter>(this);
  if(getErrorCondition() < 0) { return; }

  // We MUST have Nodes
  if (NULL == triangles->getVertices().get())
  {
    setErrorCondition(-386);
    notifyErrorMessage(getHumanLabel(), "DataContainer Geometry missing Vertices", getErrorCondition());
  }
  // We MUST have Triangles defined also.
  if (NULL == triangles->getTriangles().get())
  {
    setErrorCondition(-387);
    notifyErrorMessage(getHumanLabel(), "DataContainer Geometry missing Triangles", getErrorCondition());
  }

  QVector<size_t> dims(1, 2);
  m_SurfaceMeshFaceLabelsPtr = getDataContainerArray()->getPrereqArrayFromPath<DataArray<int32_t>, AbstractFilter>(this, getSurfaceMeshFaceLabelsArrayPath(), dims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_SurfaceMeshFaceLabelsPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_SurfaceMeshFaceLabels = m_SurfaceMeshFaceLabelsPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
  dims[0] = 1;
  m_SurfaceMeshNodeTypePtr = getDataContainerArray()->getPrereqArrayFromPath<DataArray<int8_t>, AbstractFilter>(this, getSurfaceMeshNodeTypeArrayPath(), dims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_SurfaceMeshNodeTypePtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_SurfaceMeshNodeType = m_SurfaceMeshNodeTypePtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
}
Esempio n. 17
0
void __TestEraseElements()
{
  // Test dropping of front elements only
  {
    typename DataArray<T>::Pointer array = DataArray<T>::CreateArray(NUM_ELEMENTS, "Test1");
    DREAM3D_REQUIRE_EQUAL(array->isAllocated(), true);
    for(size_t i = 0; i < NUM_ELEMENTS; ++i)
    {
      array->setComponent(i, 0, static_cast<T>(i) );
    }

    QVector<size_t> eraseElements;
    eraseElements.push_back(0);
    eraseElements.push_back(1);

    array->eraseTuples(eraseElements);

    DREAM3D_REQUIRE_EQUAL(array->getValue(0), 2);
    DREAM3D_REQUIRE_EQUAL(array->getValue(1), 3);
    DREAM3D_REQUIRE_EQUAL(array->getValue(2), 4);
    DREAM3D_REQUIRE_EQUAL(array->isAllocated(), true);
  }

  // Test Dropping of internal elements
  {
    QVector<size_t> dims(1, NUM_COMPONENTS_2);
    typename DataArray<T>::Pointer array = DataArray<T>::CreateArray(NUM_ELEMENTS_2, dims, "Test2");
    DREAM3D_REQUIRE_EQUAL(array->isAllocated(), true);
    for(size_t i = 0; i < NUM_TUPLES_2; ++i)
    {
      array->setComponent(i, 0, static_cast<T>(i));
      array->setComponent(i, 1, static_cast<T>(i));
    }

    QVector<size_t> eraseElements;
    eraseElements.push_back(3);
    eraseElements.push_back(6);
    eraseElements.push_back(8);

    array->eraseTuples(eraseElements);

    DREAM3D_REQUIRE_EQUAL(array->getComponent(3, 0), 4);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(3, 1), 4);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(5, 0), 7);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(5, 1), 7);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(6, 0), 9);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(6, 1), 9);
  }

  // Test Dropping of internal elements
  {
    QVector<size_t> dims(1, NUM_COMPONENTS_2);
    typename DataArray<T>::Pointer array = DataArray<T>::CreateArray(NUM_ELEMENTS_2, dims, "Test3");
    DREAM3D_REQUIRE_EQUAL(array->isAllocated(), true);
    for(size_t i = 0; i < NUM_TUPLES_2; ++i)
    {
      array->setComponent(i, 0, static_cast<T>(i));
      array->setComponent(i, 1, static_cast<T>(i));
    }

    QVector<size_t> eraseElements;
    eraseElements.push_back(3);
    eraseElements.push_back(6);
    eraseElements.push_back(9);
    array->eraseTuples(eraseElements);

    DREAM3D_REQUIRE_EQUAL(array->getComponent(3, 0), 4);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(3, 1), 4);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(5, 0), 7);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(5, 1), 7);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(6, 0), 8);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(6, 1), 8);
  }

  // Test Dropping of internal continuous elements
  {
    QVector<size_t> dims(1, NUM_COMPONENTS_2);
    typename DataArray<T>::Pointer array = DataArray<T>::CreateArray(NUM_ELEMENTS_2, dims, "Test4");
    DREAM3D_REQUIRE_EQUAL(array->isAllocated(), true);
    for(size_t i = 0; i < NUM_TUPLES_2; ++i)
    {
      array->setComponent(i, 0, static_cast<T>(i));
      array->setComponent(i, 1, static_cast<T>(i));
    }

    QVector<size_t> eraseElements;
    eraseElements.push_back(3);
    eraseElements.push_back(4);
    eraseElements.push_back(5);
    array->eraseTuples(eraseElements);

    DREAM3D_REQUIRE_EQUAL(array->getComponent(3, 0), 6);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(3, 1), 6);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(4, 0), 7);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(4, 1), 7);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(5, 0), 8);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(5, 1), 8);
  }

  // Test Dropping of Front and Back Elements
  {
    QVector<size_t> dims(1, NUM_COMPONENTS_2);
    typename DataArray<T>::Pointer array = DataArray<T>::CreateArray(NUM_ELEMENTS_2, dims, "Test5");
    DREAM3D_REQUIRE_EQUAL(array->isAllocated(), true);
    for(size_t i = 0; i < NUM_TUPLES_2; ++i)
    {
      array->setComponent(i, 0, static_cast<T>(i));
      array->setComponent(i, 1, static_cast<T>(i));
    }

    QVector<size_t> eraseElements;
    eraseElements.push_back(0);
    eraseElements.push_back(9);

    array->eraseTuples(eraseElements);

    DREAM3D_REQUIRE_EQUAL(array->getComponent(0, 0), 1);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(0, 1), 1);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(7, 0), 8);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(7, 1), 8);
  }

  // Test Dropping of Back Elements
  {
    QVector<size_t> dims(1, NUM_COMPONENTS_2);
    typename DataArray<T>::Pointer array = DataArray<T>::CreateArray(NUM_ELEMENTS_2, dims, "Test6");
    DREAM3D_REQUIRE_EQUAL(array->isAllocated(), true);
    for(size_t i = 0; i < NUM_TUPLES_2; ++i)
    {
      array->setComponent(i, 0, static_cast<T>(i));
      array->setComponent(i, 1, static_cast<T>(i));
    }

    QVector<size_t> eraseElements;
    eraseElements.push_back(7);
    eraseElements.push_back(8);
    eraseElements.push_back(9);
    array->eraseTuples(eraseElements);

    DREAM3D_REQUIRE_EQUAL(array->getComponent(4, 0), 4);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(4, 1), 4);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(5, 0), 5);
    DREAM3D_REQUIRE_EQUAL(array->getComponent(5, 1), 5);
  }

  // Test Dropping of indices larger than the number of tuples
  {
    QVector<size_t> dims(1, NUM_COMPONENTS_2);
    typename DataArray<T>::Pointer array = DataArray<T>::CreateArray(NUM_TUPLES_2, dims, "Test6");
    DREAM3D_REQUIRE_EQUAL(array->isAllocated(), true);
    for(size_t i = 0; i < NUM_TUPLES_2; ++i)
    {
      array->setComponent(i, 0, static_cast<T>(i));
      array->setComponent(i, 1, static_cast<T>(i));
    }

    QVector<size_t> eraseElements;
    eraseElements.push_back(10);
    int err = array->eraseTuples(eraseElements);
    DREAM3D_REQUIRE_EQUAL(err , -100)

    eraseElements.clear();
    err = array->eraseTuples(eraseElements);
    DREAM3D_REQUIRE_EQUAL(err , 0)

    eraseElements.resize(20);
    err = array->eraseTuples(eraseElements);
    DREAM3D_REQUIRE_EQUAL(err , 0)
    size_t nTuples = array->getNumberOfTuples();
    DREAM3D_REQUIRE_EQUAL(nTuples, 0)
  }

}
Esempio n. 18
0
 QVector<size_t> getComponentDimensions()
 {
   QVector<size_t> dims(1, 1);
   return dims;
 }
Esempio n. 19
0
int main(int argc, char** argv)
{
    if (!cmdline(argc, argv))
    {
        printhelp();
        return EXIT_FAILURE;
    }

    NcFile infile(infilename.c_str(), NcFile::ReadOnly);
    if (!infile.is_valid())
    {
        std::cerr << "Error: invalid input file -- '" << infilename << "'" << std::endl;
        infile.close();
        return EXIT_FAILURE;
    }

    NcFile outfile(outfilename.c_str(), NcFile::Replace);
    if (!outfile.is_valid())
    {
        std::cerr << "Error: cannot open output file -- '" << outfilename << "'" << std::endl;
        outfile.close();
        return EXIT_FAILURE;
    }

    if (varstrings.size() == 0)
    {
        std::cerr << "Warning: no variables specified" << std::endl;
    }

    std::vector<NcVar*> invars;
    for (std::vector<std::string>::const_iterator it = varstrings.begin();
         it != varstrings.end(); ++it)
    {
        NcVar* var = infile.get_var((*it).c_str());
        if (var == NULL)
        {
            std::cerr << "Error: " << *it << ": no such variable" << std::endl;
            infile.close();
            outfile.close();
            return EXIT_FAILURE;
        }
        invars.push_back(var);
    }

    // extract the distinct set of dims
    std::map<std::string, NcDim*> indims;
    for (std::vector<NcVar*>::const_iterator it = invars.begin();
         it != invars.end(); ++it)
    {
        NcVar* var = *it;
        for (int i = 0; i < var->num_dims(); ++i)
        {
            NcDim* dim = var->get_dim(i);
            indims[dim->name()] = dim;
        }
    }

    // add dims to outfile
    std::map<std::string, NcDim*> outdims;
    for (std::map<std::string, NcDim*>::const_iterator it = indims.begin();
         it != indims.end(); ++it)
    {
        NcDim* dim = (*it).second;
        NcDim* outdim = NULL;
        if (dim->is_unlimited())
        {
            outdim = outfile.add_dim(dim->name());
        }
        else
        {
            outdim = outfile.add_dim(dim->name(), dim->size());
        }

        if (outdim != NULL)
        {
            outdims[outdim->name()] = outdim;
        }
    }

    // create variables
    for (std::vector<NcVar*>::const_iterator it = invars.begin();
         it != invars.end(); ++it)
    {
        NcVar* var = *it;
        std::vector<const NcDim*> dims(var->num_dims());
        for (int i = 0; i < var->num_dims(); ++i)
        {
            dims[i] = outdims[var->get_dim(i)->name()];
        }
        NcVar* outvar = outfile.add_var(var->name(), var->type(), var->num_dims(), &dims[0]);

        // identify largest dim, if dim (nearly) exceeds main memory, split along that dim
        int maxdim = -1;
        long maxdimsize = 0;
        long totallen = 1;
        for (int i = 0; i < var->num_dims(); ++i)
        {
            NcDim* dim = var->get_dim(i);
            if (dim->size() > maxdimsize)
            {
                maxdim = i;
                maxdimsize = dim->size();
            }
            totallen *= dim->size();
        }

        // TODO: support other data types
        totallen *= sizeof(float);

        // TODO: configurable page size
        const unsigned long pagesize = 1000000000;
#ifdef __linux__
        struct sysinfo info;
        sysinfo(&info);
        if (pagesize >= info.freeram)
        {
            std::cerr << "Warning: page size exceeds free memory" << std::endl;
        }
#endif

        int numpages = 1;
        long pagesizedim = var->get_dim(maxdim)->size();
        if (totallen < pagesize)
        {
        }
        else
        {
            long mul = 1;
            for (int i = 0; i < var->num_dims(); ++i)
            {
                if (i != maxdim)
                {
                    NcDim* dim = var->get_dim(i);
                    mul *= dim->size();
                }
            }
            // TODO: support other data types
            mul *= sizeof(float);

            pagesizedim = pagesize / mul;
            numpages = var->get_dim(maxdim)->size() / pagesizedim;
            if (var->get_dim(maxdim)->size() % pagesizedim > 0)
            {
                ++numpages;
            }
        }

        std::vector< std::vector<long> > curvec;
        std::vector< std::vector<long> > countsvec;
        std::vector<long> lengths;

        int pages = numpages > 0 ? numpages : 1;
        for (int p = 0; p < pages; ++p)
        {
            long len = 1;
            std::vector<long> cur;
            std::vector<long> counts;
            for (int i = 0; i < var->num_dims(); ++i)
            {
                NcDim* dim = var->get_dim(i);
                long current = 0;
                long count = dim->size();
                if (i == maxdim)
                {
                    current = pagesizedim * p;
                    count = pagesizedim;
                    if (p == pages -1)
                    {
                        if (dim->size() % pagesizedim != 0)
                        {
                            count = dim->size() % pagesizedim;
                        }
                    }
                }
                cur.push_back(current);
                counts.push_back(count);
                len *= count;
            }
            curvec.push_back(cur);
            countsvec.push_back(counts);
            lengths.push_back(len);
        }

        std::vector< std::vector<long> >::const_iterator it1;
        std::vector< std::vector<long> >::const_iterator it2;
        std::vector<long>::const_iterator it3;

        for (it1 = curvec.begin(), it2 = countsvec.begin(), it3 = lengths.begin();
             it1 != curvec.end() && it2 != countsvec.end() && it3 != lengths.end(); ++it1, ++it2, ++it3)
        {
            std::vector<long> cur = *it1;
            std::vector<long> counts = *it2;
            long len = *it3;

            var->set_cur(&cur[0]);
            outvar->set_cur(&cur[0]);
            switch (outvar->type())
            {
            case ncByte:
            {
                ncbyte* barr = new ncbyte[len];
                var->get(barr, &counts[0]);
                outvar->put(barr, &counts[0]);
                delete[] barr;
                break;
            }
            case ncChar:
            {
                char* carr = new char[len];
                var->get(carr, &counts[0]);
                outvar->put(carr, &counts[0]);
                delete[] carr;
                break;
            }
            case ncShort:
            {
                short* sarr = new short[len];
                var->get(sarr, &counts[0]);
                outvar->put(sarr, &counts[0]);
                delete[] sarr;
                break;
            }
            case ncInt:
            {
                long* larr = new long[len];
                var->get(larr, &counts[0]);
                outvar->put(larr, &counts[0]);
                delete[] larr;
                break;
            }
            case ncFloat:
            {
                float* farr = new float[len];
                var->get(farr, &counts[0]);
                outvar->put(farr, &counts[0]);
                delete[] farr;
                break;
            }
            case ncDouble:
            {
                double* darr = new double[len];
                var->get(darr, &counts[0]);
                outvar->put(darr, &counts[0]);
                delete[] darr;
                break;
            }
            default:
                break;
            }
        }
    }

    infile.close();
    outfile.close();
    return 0;
}
        Nd4jStatus LegacyReduceBoolOp::validateAndExecute(Context &block) {
            auto x = INPUT_VARIABLE(0);


            int opNum = block.opNum() < 0 ? this->_opNum : block.opNum();
            nd4j_debug("Executing LegacyReduceFloatOp: [%i]\n", opNum);

            auto axis = *block.getAxis();

            bool allAxes = false;

            if (block.width() == 1) {
                auto z = OUTPUT_VARIABLE(0);

                if (axis.size() == x->rankOf())
                    allAxes = true;

                if ((axis.empty()) ||
                    (axis.size() == 1 && axis[0] == MAX_INT) || allAxes) {
                    // scalar
                    NativeOpExcutioner::execReduceBoolScalar(opNum, x->getBuffer(), x->getShapeInfo(), block.getTArguments()->data(), z->buffer(), z->shapeInfo());
                } else {
                    // TAD
                    std::vector<int> dims(axis);

                    for (int e = 0; e < dims.size(); e++)
                        if (dims[e] < 0)
                            dims[e] += x->rankOf();

                    std::sort(dims.begin(), dims.end());

                    REQUIRE_TRUE(dims.size() > 0, 0, "Some dimensions required for reduction!");

                    shape::TAD tad;
                    tad.init(x->getShapeInfo(), dims.data(), dims.size());
                    tad.createTadOnlyShapeInfo();
                    tad.createOffsets();

                    NativeOpExcutioner::execReduceBool(opNum, x->getBuffer(), x->getShapeInfo(), block.getTArguments()->data(), z->getBuffer(), z->getShapeInfo(), dims.data(), (int) dims.size(), tad.tadOnlyShapeInfo, tad.tadOffsets);
                }

                STORE_RESULT(*z);
            } else {
                auto indices = INPUT_VARIABLE(1);
                if (indices->lengthOf() == x->rankOf())
                    allAxes = true;

                //indices->printIndexedBuffer("indices");

                std::vector<int> axis(indices->lengthOf());
                for (int e = 0; e < indices->lengthOf(); e++) {
                    // lol otherwise we segfault on macOS
                    int f = indices->e<int>(e);
                    axis[e] = f >= 0 ? f : f += x->rankOf();
                }

                if ((block.getIArguments()->size() == 1 && INT_ARG(0) == MAX_INT) || allAxes) {
                    auto z = OUTPUT_VARIABLE(0);

                    auto b = x->getBuffer();
                    auto s = x->shapeInfo();
                    auto e = block.numT() > 0 ? block.getTArguments()->data() : nullptr;

                    //x->printIndexedBuffer("x");

                    // scalar
                    NativeOpExcutioner::execReduceBoolScalar(opNum, b, s, e, z->buffer(), z->shapeInfo());
                } else {
                    // TAD
                    if (indices->lengthOf() > 1)
                        std::sort(axis.begin(), axis.end());

                    REQUIRE_TRUE(axis.size() > 0, 0, "Some dimensions required for reduction!");

                    shape::TAD tad;
                    tad.init(x->getShapeInfo(), axis.data(), axis.size());
                    tad.createTadOnlyShapeInfo();
                    tad.createOffsets();

                    auto z = OUTPUT_VARIABLE(0);

                    NativeOpExcutioner::execReduceBool(opNum, x->getBuffer(), x->getShapeInfo(), block.getTArguments()->data(), z->getBuffer(), z->getShapeInfo(), axis.data(), (int) axis.size(), tad.tadOnlyShapeInfo, tad.tadOffsets);
                }
            }

            return Status::OK();
        }
Esempio n. 21
0
int main (int argc, char *argv[]) {
#ifdef TESTING
	input_map inmap;
	std::string prefix;
	symbolic_function<1> f; 
	symbolic_function<2> e1 ,e2, e4, dhdx0;
	blitz::TinyVector<double,2>  x2d(1.0, 0.75), x2da(0.5, 0.25);
		
	inmap["Re"] = "100.0";
	inmap["l1"] = "37.0";
	inmap["f"] = "exp(-x/l1*Re)";
	inmap["e1"] = "sin(-x0/l1*Re+x1)";
	inmap["e2"] = "x0*e1";
	inmap["dhdx0"] = "2*h*ke^2*x0*exp(-ke^2*x0^2)*cos(k*x0-w*t)-h*(1-exp(-ke^2*x0^2))*sin(k*x0-w*t)*k-2*s*(x0-ex0)/denom^2*exp(-(x0-ex0)^2/denom^2)*(1+(2*h*ke^2*x0*exp(-ke^2*x0^2)*cos(k*x0-w*t)-h*(1-exp(-ke^2*x0^2))*sin(k*x0-w*t)*k)^2)^(1/2)-s*(1-exp(-(x0-ex0)^2/denom^2))/(1+(2*h*ke^2*x0*exp(-ke^2*x0^2)*cos(k*x0-w*t)-h*(1-exp(-ke^2*x0^2))*sin(k*x0-w*t)*k)^2)^(1/2)*(2*h*ke^2*x0*exp(-ke^2*x0^2)*cos(k*x0-w*t)-h*(1-exp(-ke^2*x0^2))*sin(k*x0-w*t)*k)*(2*h*ke^2*exp(-ke^2*x0^2)*cos(k*x0-w*t)-4*h*ke^4*x0^2*exp(-ke^2*x0^2)*cos(k*x0-w*t)-4*h*ke^2*x0*exp(-ke^2*x0^2)*sin(k*x0-w*t)*k-h*(1-exp(-ke^2*x0^2))*cos(k*x0-w*t)*k^2)";
	inmap["e4"] = "cos(2*_pi*x1)";
	std::cout << inmap << std::endl;
	inmap.echo = true;

	f.init(inmap,"f");
	std::cout << "f " << f.Eval(1.0) << ' ' << exp(-1.0/37.0*100.0) << std::endl;
 
	e1.init(inmap,"e1");
	std::cout << " e1 eval " << e1.Eval(x2d) << ' ' << sin(-x2d(0)/37.0*100.0 +x2d(1)) << std::endl;
	
	e2.init(inmap,"e2");
	std::cout << " e2 eval " << e2.Eval(x2d) << ' ' << x2d(0)*sin(-x2d(0)/37.0*100.0 +x2d(1)) << std::endl;
	
	symbolic_function<2> e3(e2);
	
	std::cout << " e3 eval " << e3.Eval(x2da) << ' ' << x2da(0)*sin(-x2da(0)/37.0*100.0 +x2da(1)) << std::endl;
	
	e1 = e2;
	std::cout << " = eval " << e1.Eval(x2d) << ' ' << x2d(0)*sin(-x2d(0)/37.0*100.0 +x2d(1)) << std::endl;
	
	
//	dhdx0.init(inmap,"dhdx0");
//	std::cout << "dhdx0 " << dhdx0.Eval(x2d,1.0) << std::endl;
	
	
	/* Vector Function Testing */
	blitz::Array<std::string,1> names;
	blitz::Array<int,1> dims;
	names.resize(3);
	dims.resize(3);
	names(0) = "x";
	names(1) = "u";
	names(2) = "n";
	dims(0) = 2;
	dims(1) = 4;
	dims(2) = 2;
	vector_function vf(3,dims,names);
	
	inmap["Vfunc"] = "V3*u2";
	inmap["V2"] = "u3*x0";
	inmap["V3"] = "n1*t*V2";
	// t*u2*u3*x0
	
	vf.init(inmap,"Vfunc");
	blitz::Array<double,1> x(2);
	x(0) = 0.1;
	x(1) = 0.3;
	double t = 0.7;
	blitz::Array<double,1> u(4);
	u(0) = 1.9;
	u(1) = 2.9;
	u(2) = 3.34;
	u(3) = 5;
	blitz::Array<double,1> n(2);
	n(0) = -100;
	n(1) = -200;
	std::cout << vf.Eval(x,u,n,t) << ' ' << t*u(2)*u(3)*x(0)*n(1) << std::endl;
	

#else
    input_map mymap;
	  
    mymap.input(argv[1]);
	
	symbolic_function<3> f;
	f.init(mymap,"formula");
	
	blitz::TinyVector<double,3> x;
	mymap.get("position",x.data(),3);
	
	double t;
	mymap.getwdefault("time",t,0.0);
	
	std::cout << f.Eval(x) << std::endl;
	
#endif

	return(0);
}
Esempio n. 22
0
    static intptr_t instantiate(char *DYND_UNUSED(static_data), size_t DYND_UNUSED(data_size), char *DYND_UNUSED(data),
                                void *ckb, intptr_t ckb_offset, const ndt::type &dst_tp, const char *dst_arrmeta,
                                intptr_t DYND_UNUSED(nsrc), const ndt::type *src_tp, const char *const *src_arrmeta,
                                kernel_request_t kernreq, const eval::eval_context *DYND_UNUSED(ectx),
                                intptr_t DYND_UNUSED(nkwd), const nd::array *kwds,
                                const std::map<std::string, ndt::type> &DYND_UNUSED(tp_vars))
    {
        int flags;
        if (kwds[2].is_missing()) {
            flags = FFTW_ESTIMATE;
        } else {
            flags = kwds[2].as<int>();
        }

        nd::array shape = kwds[0];
        if (!shape.is_missing()) {
            if (shape.get_type().get_type_id() == pointer_type_id) {
                shape = shape;
            }
        }

        nd::array axes;
        if (!kwds[1].is_missing()) {
            axes = kwds[1];
            if (axes.get_type().get_type_id() == pointer_type_id) {
                axes = axes;
            }
        } else {
            axes = nd::range(src_tp[0].get_ndim());
        }

        const size_stride_t *src_size_stride = reinterpret_cast<const size_stride_t *>(src_arrmeta[0]);
        const size_stride_t *dst_size_stride = reinterpret_cast<const size_stride_t *>(dst_arrmeta);

        int rank = axes.get_dim_size();
        shortvector<fftw_iodim> dims(rank);
        for (intptr_t i = 0; i < rank; ++i) {
            intptr_t j = axes(i).as<intptr_t>();
            dims[i].n = shape.is_missing() ? src_size_stride[j].dim_size : shape(j).as<intptr_t>();
            dims[i].is = src_size_stride[j].stride / sizeof(fftw_src_type);
            dims[i].os = dst_size_stride[j].stride / sizeof(fftw_dst_type);
        }

        int howmany_rank = src_tp[0].get_ndim() - rank;
        shortvector<fftw_iodim> howmany_dims(howmany_rank);
        for (intptr_t i = 0, j = 0, k = 0; i < howmany_rank; ++i, ++j) {
            for (; k < rank && j == axes(k).as<intptr_t>(); ++j, ++k) {
            }
            howmany_dims[i].n = shape.is_missing() ? src_size_stride[j].dim_size : shape(j).as<intptr_t>();
            howmany_dims[i].is = src_size_stride[j].stride / sizeof(fftw_src_type);
            howmany_dims[i].os = dst_size_stride[j].stride / sizeof(fftw_dst_type);
        }

        nd::array src = nd::empty(src_tp[0]);
        nd::array dst = nd::empty(dst_tp);

        fftw_ck::make(ckb, kernreq, ckb_offset,
                      detail::fftw_plan_guru_dft(rank, dims.get(), howmany_rank, howmany_dims.get(),
                              reinterpret_cast<fftw_src_type *>(src.data()),
                              reinterpret_cast<fftw_dst_type *>(dst.data()), sign, flags));

        return ckb_offset;
    }
Esempio n. 23
0
 std::vector<size_t> dims(T x) {
   std::vector<size_t> ds;
   dims(x,ds);
   return ds;
 }
Esempio n. 24
0
ExprVector::ExprVector(const Array<const ExprNode>& comp, bool in_row) :
		ExprNAryOp(comp, vec_dim(dims(comp),in_row)) {
}
Esempio n. 25
0
void ccOctree::RenderOctreeAs(  CC_OCTREE_DISPLAY_TYPE octreeDisplayType,
								ccOctree* theOctree,
								unsigned char level,
								ccGenericPointCloud* theAssociatedCloud,
								int &octreeGLListID,
								bool updateOctreeGLDisplay)
{
	if (!theOctree || !theAssociatedCloud)
		return;

	glPushAttrib(GL_LIGHTING_BIT);

	if (octreeDisplayType == WIRE)
	{
		//cet affichage demande trop de memoire pour le stocker sous forme de liste OpenGL
		//donc on doit le generer dynamiquement
		
		glDisable(GL_LIGHTING); //au cas où la lumiere soit allumee
		ccGL::Color3v(ccColor::green.rgba);

		void* additionalParameters[] = { theOctree->m_frustrumIntersector };
		theOctree->executeFunctionForAllCellsAtLevel(	level,
														&DrawCellAsABox,
														additionalParameters);
	}
	else
	{
		glDrawParams glParams;
		theAssociatedCloud->getDrawingParameters(glParams);

		if (glParams.showNorms)
		{
			//DGM: Strangely, when Qt::renderPixmap is called, the OpenGL version is sometimes 1.0!
			glEnable((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_1_2 ? GL_RESCALE_NORMAL : GL_NORMALIZE));
			glMaterialfv(GL_FRONT_AND_BACK,	GL_AMBIENT,		CC_DEFAULT_CLOUD_AMBIENT_COLOR.rgba  );
			glMaterialfv(GL_FRONT_AND_BACK,	GL_SPECULAR,	CC_DEFAULT_CLOUD_SPECULAR_COLOR.rgba );
			glMaterialfv(GL_FRONT_AND_BACK,	GL_DIFFUSE,		CC_DEFAULT_CLOUD_DIFFUSE_COLOR.rgba  );
			glMaterialfv(GL_FRONT_AND_BACK,	GL_EMISSION,	CC_DEFAULT_CLOUD_EMISSION_COLOR.rgba );
			glMaterialf (GL_FRONT_AND_BACK,	GL_SHININESS,	CC_DEFAULT_CLOUD_SHININESS);
			glEnable(GL_LIGHTING);

			glEnable(GL_COLOR_MATERIAL);
			glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
		}

		if (!glParams.showColors)
			ccGL::Color3v(ccColor::white.rgba);

		if (updateOctreeGLDisplay || octreeGLListID < 0)
		{
			if (octreeGLListID < 0)
				octreeGLListID = glGenLists(1);
			else if (glIsList(octreeGLListID))
				glDeleteLists(octreeGLListID,1);
			glNewList(octreeGLListID,GL_COMPILE);

			if (octreeDisplayType == MEAN_POINTS)
			{
				void* additionalParameters[2] = {	reinterpret_cast<void*>(&glParams),
													reinterpret_cast<void*>(theAssociatedCloud),
				};

				glBegin(GL_POINTS);
				theOctree->executeFunctionForAllCellsAtLevel(	level,
																&DrawCellAsAPoint,
																additionalParameters);
				glEnd();
			}
			else
			{
				//by default we use a box as primitive
				PointCoordinateType cs = theOctree->getCellSize(level);
				CCVector3 dims(cs,cs,cs);
				ccBox box(dims);
				box.showColors(glParams.showColors || glParams.showSF);
				box.showNormals(glParams.showNorms);

				//trick: replace all normal indexes so that they point on the first one
				{
					if (box.arePerTriangleNormalsEnabled())
						for (unsigned i=0;i<box.size();++i)
							box.setTriangleNormalIndexes(i,0,0,0);
				}

				//fake context
				CC_DRAW_CONTEXT context;
				context.flags = CC_DRAW_3D | CC_DRAW_FOREGROUND| CC_LIGHT_ENABLED;
				context._win = 0;

				void* additionalParameters[4] = {	reinterpret_cast<void*>(&glParams),
													reinterpret_cast<void*>(theAssociatedCloud),
													reinterpret_cast<void*>(&box),
													reinterpret_cast<void*>(&context)
				};

				theOctree->executeFunctionForAllCellsAtLevel(	level,
																&DrawCellAsAPrimitive,
																additionalParameters);
			}

			glEndList();
		}

		glCallList(octreeGLListID);

		if (glParams.showNorms)
		{
			glDisable(GL_COLOR_MATERIAL);
			glDisable((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_1_2 ? GL_RESCALE_NORMAL : GL_NORMALIZE));
			glDisable(GL_LIGHTING);
		}
	}

	glPopAttrib();
}
Esempio n. 26
0
    ArrayDesc inferSchema(std::vector< ArrayDesc> schemas, boost::shared_ptr< Query> query)
    {
        assert(schemas.size() == 2);

        if (!hasSingleAttribute(schemas[0]) || !hasSingleAttribute(schemas[1]))
            throw USER_EXCEPTION(SCIDB_SE_INFER_SCHEMA, SCIDB_LE_OP_MULTIPLY_ERROR2);
        if (schemas[0].getDimensions().size() != 2 || schemas[1].getDimensions().size() != 2)
            throw USER_EXCEPTION(SCIDB_SE_INFER_SCHEMA, SCIDB_LE_OP_MULTIPLY_ERROR3);

        if (schemas[0].getDimensions()[0].getLength() == INFINITE_LENGTH
                || schemas[0].getDimensions()[1].getLength() == INFINITE_LENGTH
                || schemas[1].getDimensions()[0].getLength() == INFINITE_LENGTH
                || schemas[1].getDimensions()[1].getLength() == INFINITE_LENGTH)
            throw USER_EXCEPTION(SCIDB_SE_INFER_SCHEMA, SCIDB_LE_OP_MULTIPLY_ERROR4);

        if (schemas[0].getDimensions()[1].getLength() != schemas[1].getDimensions()[1].getLength()
                || schemas[0].getDimensions()[1].getStart() != schemas[1].getDimensions()[1].getStart())
            throw USER_EXCEPTION(SCIDB_SE_INFER_SCHEMA, SCIDB_LE_OP_MULTIPLY_ERROR5);

        // FIXME: This condition needs to go away later
        if (schemas[0].getDimensions()[1].getChunkInterval() != schemas[1].getDimensions()[1].getChunkInterval())
            throw USER_EXCEPTION(SCIDB_SE_INFER_SCHEMA, SCIDB_LE_OP_MULTIPLY_ERROR6);
        if (schemas[0].getAttributes()[0].getType() != schemas[1].getAttributes()[0].getType())
            throw USER_EXCEPTION(SCIDB_SE_INFER_SCHEMA, SCIDB_LE_OP_MULTIPLY_ERROR7);
        if (schemas[0].getAttributes()[0].isNullable() || schemas[1].getAttributes()[0].isNullable())
            throw USER_EXCEPTION(SCIDB_SE_INFER_SCHEMA, SCIDB_LE_OP_MULTIPLY_ERROR8);

		Attributes atts(1);
        TypeId type = schemas[0].getAttributes()[0].getType();
		AttributeDesc multAttr((AttributeID)0, "multiply", type, 0, 0);
		atts[0] = multAttr;

		Dimensions dims(2);
		DimensionDesc const& d1 = schemas[0].getDimensions()[0];
		dims[0] = DimensionDesc(d1.getBaseName(), 
                                d1.getNamesAndAliases(), 
                                d1.getStartMin(), 
                                d1.getCurrStart(), 
                                d1.getCurrEnd(), 
                                d1.getEndMax(), 
                                d1.getChunkInterval(), 
                                0, 
                                d1.getType(), 
                                d1.getFlags(), 
                                d1.getMappingArrayName(), 
                                d1.getComment(),
                                d1.getFuncMapOffset(),
                                d1.getFuncMapScale());

		DimensionDesc const& d2 = schemas[1].getDimensions()[0];
		dims[1] = DimensionDesc(d1.getBaseName() == d2.getBaseName() ? d1.getBaseName() + "2" : d2.getBaseName(), 
                                d2.getNamesAndAliases(), 
                                d2.getStartMin(), 
                                d2.getCurrStart(), 
                                d2.getCurrEnd(), 
                                d2.getEndMax(), 
                                d2.getChunkInterval(), 
                                0, 
                                d2.getType(), 
                                d2.getFlags(), 
                                d2.getMappingArrayName(), 
                                d2.getComment(),
                                d2.getFuncMapOffset(),
                                d2.getFuncMapScale());

        return ArrayDesc("MultiplyRow",atts,dims);
	}
void peano::applications::latticeboltzmann::blocklatticeboltzmann::cca::BlockLatticeBoltzmannBatchJobForRegularGridImplementation::getData(const long long& scope, const double* boundingBoxOffset,long boundingBoxOffset_len, const double* boundingBox,long boundingBox_len, const long long* resolution,long resolution_len, double* data,long data_len){
  std::cout<<"execute 3d query"<<std::endl;
  tarch::la::Vector<DIMENSIONS,double> qOffset(0.0);
  tarch::la::Vector<DIMENSIONS,double> qSize(0.0);
  tarch::la::Vector<DIMENSIONS,int> dims(0.0);
  for(int i=0;i<DIMENSIONS;i++){
      qOffset[i]=boundingBoxOffset[i];
      qSize[i]=boundingBox[i];
      dims[i]=(int)resolution[i];
  }
  int records_per_entry=DIMENSIONS;
  peano::integration::dataqueries::DataQuery query;
  //_queryid++;
  query.setId(0);
  query.setBoundingBoxOffset(qOffset);
  query.setBoundingBox(qSize);
  query.setResolution(dims);
  if (scope==0) {

      query.setRecordsPerEntry(DIMENSIONS);
      query.setScope( peano::applications::latticeboltzmann::blocklatticeboltzmann::mappings::RegularGrid2BlockCCAOutput::Velocity);
  }
  else if (scope==1) {
      query.setRecordsPerEntry(DIMENSIONS);
      query.setScope( peano::applications::latticeboltzmann::blocklatticeboltzmann::mappings::RegularGrid2BlockCCAOutput::Density);
      records_per_entry=1;
  }
  else {

      return;
  }

  tarch::plotter::griddata::regular::cca::CCAGridArrayWriter writer(
      query.getResolution(),
      query.getBoundingBox(),
      query.getBoundingBoxOffset()
  );

  peano::integration::dataqueries::QueryServer::getInstance().addQuery(
      "query",records_per_entry ,query, writer
  );
  switchToRegularBlockSolverAdapter();
  _repository->iterate();
  switchToBlockCCAOutputAdapter();
  _repository->iterate();
  scenario::latticeboltzmann::blocklatticeboltzmann::services::ReceiveBoundaryDataService::getInstance().advance(_repository->getRegularGridState().getDt());

  //std::cout<<"starting cAdapter"<<std::endl;

  //    runner.runCartesianGridAdapter();
  writer.writeToVertexArray(data,data_len);
  //  //  writer.writeToFile(
  //  //      "/home_local/atanasoa/query.vtk");
  //    if (scope==1){
  //        if(_queryid<=3)
  //          for(int i=0;i<10;i++)
  //            runner.runOneStep();
  //        else
  //          runner.runOneStep();
  //    }
}
Esempio n. 28
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void StatsGenODFWidget::on_m_CalculateODFBtn_clicked()
{
  int err = 0;

  QwtArray<float> e1s;
  QwtArray<float> e2s;
  QwtArray<float> e3s;
  QwtArray<float> weights;
  QwtArray<float> sigmas;
  QwtArray<float> odf;
  SGODFTableModel* tableModel = NULL;

  if(weightSpreadGroupBox->isChecked() )
  {
    tableModel = m_ODFTableModel;
  }
  else
  {
    tableModel = m_OdfBulkTableModel;
  }


  e1s = tableModel->getData(SGODFTableModel::Euler1);
  e2s = tableModel->getData(SGODFTableModel::Euler2);
  e3s = tableModel->getData(SGODFTableModel::Euler3);
  weights = tableModel->getData(SGODFTableModel::Weight);
  sigmas = tableModel->getData(SGODFTableModel::Sigma);


  // Convert from Degrees to Radians
  for(int i = 0; i < e1s.size(); i++)
  {
    e1s[i] = e1s[i] * M_PI / 180.0;
    e2s[i] = e2s[i] * M_PI / 180.0;
    e3s[i] = e3s[i] * M_PI / 180.0;
  }
  size_t numEntries = e1s.size();

  int imageSize = pfImageSize->value();
  int lamberSize = pfLambertSize->value();
  int numColors = 16;
  int npoints = pfSamplePoints->value();
  QVector<size_t> dims(1, 3);
  FloatArrayType::Pointer eulers = FloatArrayType::CreateArray(npoints, dims, "Eulers");
  PoleFigureConfiguration_t config;
  QVector<UInt8ArrayType::Pointer> figures;

  if ( Ebsd::CrystalStructure::Cubic_High == m_CrystalStructure)
  {
    // We now need to resize all the arrays here to make sure they are all allocated
    odf.resize(CubicOps::k_OdfSize);
    Texture::CalculateCubicODFData(e1s.data(), e2s.data(), e3s.data(),
                                   weights.data(), sigmas.data(), true,
                                   odf.data(), numEntries);

    err = StatsGen::GenCubicODFPlotData(odf.data(), eulers->getPointer(0), npoints);

    CubicOps ops;
    config.eulers = eulers.get();
    config.imageDim = imageSize;
    config.lambertDim = lamberSize;
    config.numColors = numColors;

    figures = ops.generatePoleFigure(config);
  }
  else if ( Ebsd::CrystalStructure::Hexagonal_High == m_CrystalStructure)
  {
    // We now need to resize all the arrays here to make sure they are all allocated
    odf.resize(HexagonalOps::k_OdfSize);
    Texture::CalculateHexODFData(e1s.data(), e2s.data(), e3s.data(),
                                 weights.data(), sigmas.data(), true,
                                 odf.data(), numEntries);

    err = StatsGen::GenHexODFPlotData(odf.data(), eulers->getPointer(0), npoints);

    HexagonalOps ops;
    config.eulers = eulers.get();
    config.imageDim = imageSize;
    config.lambertDim = lamberSize;
    config.numColors = numColors;

    figures = ops.generatePoleFigure(config);
  }
  else if ( Ebsd::CrystalStructure::OrthoRhombic == m_CrystalStructure)
  {
    //    // We now need to resize all the arrays here to make sure they are all allocated
    odf.resize(OrthoRhombicOps::k_OdfSize);
    Texture::CalculateOrthoRhombicODFData(e1s.data(), e2s.data(), e3s.data(),
                                          weights.data(), sigmas.data(), true,
                                          odf.data(), numEntries);

    err = StatsGen::GenOrthoRhombicODFPlotData(odf.data(), eulers->getPointer(0), npoints);

    OrthoRhombicOps ops;
    config.eulers = eulers.get();
    config.imageDim = imageSize;
    config.lambertDim = lamberSize;
    config.numColors = numColors;

    figures = ops.generatePoleFigure(config);
  }

  if (err == 1)
  {
    //TODO: Present Error Message
    return;
  }

  QImage image = PoleFigureImageUtilities::Create3ImagePoleFigure(figures[0].get(), figures[1].get(), figures[2].get(), config, imageLayout->currentIndex());
  m_PoleFigureLabel->setPixmap(QPixmap::fromImage(image));

  // Enable the MDF tab
  if (m_MDFWidget != NULL)
  {
    m_MDFWidget->setEnabled(true);
    m_MDFWidget->updateMDFPlot(odf);
  }
}
Esempio n. 29
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void YSChoiAbaqusReader::dataCheck()
{
  DataArrayPath tempPath;
  setErrorCondition(0);

  DataContainer::Pointer m = getDataContainerArray()->createNonPrereqDataContainer<AbstractFilter>(this, getDataContainerName());
  if(getErrorCondition() < 0) { return; }

  ImageGeom::Pointer image = ImageGeom::CreateGeometry(DREAM3D::Geometry::ImageGeometry);
  m->setGeometry(image);

  QVector<size_t> tDims(3, 0);
  AttributeMatrix::Pointer cellAttrMat = m->createNonPrereqAttributeMatrix<AbstractFilter>(this, getCellAttributeMatrixName(), tDims, DREAM3D::AttributeMatrixType::Cell);
  if(getErrorCondition() < 0 || NULL == cellAttrMat.get()) { return; }
  tDims.resize(1);
  tDims[0] = 0;

  AttributeMatrix::Pointer cellFeatureAttrMat = m->createNonPrereqAttributeMatrix<AbstractFilter>(this, getCellFeatureAttributeMatrixName(), tDims, DREAM3D::AttributeMatrixType::CellFeature);
  if(getErrorCondition() < 0 || NULL == cellFeatureAttrMat.get()) { return; }

  AttributeMatrix::Pointer cellEnsembleAttrMat = m->createNonPrereqAttributeMatrix<AbstractFilter>(this, getCellEnsembleAttributeMatrixName(), tDims, DREAM3D::AttributeMatrixType::CellEnsemble);
  if(getErrorCondition() < 0 || NULL == cellEnsembleAttrMat.get()) { return; }

  QFileInfo fi(getInputFile());
  if (getInputFile().isEmpty() == true)
  {
    QString ss = QObject::tr("%1 needs the Input File Set and it was not.").arg(ClassName());
    setErrorCondition(-387);
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
  }
  else if (fi.exists() == false)
  {
    QString ss = QObject::tr("The input file does not exist");
    setErrorCondition(-388);
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
  }
  else
  {
    bool ok = false;
    //const unsigned int size(1024);
    // Read header from data file to figure out how many points there are
    QFile in(getInputFile());
    if (!in.open(QIODevice::ReadOnly | QIODevice::Text))
    {
      QString msg = QObject::tr("Abaqus file could not be opened: %1").arg(getInputFile());
      setErrorCondition(-100);
      notifyErrorMessage(getHumanLabel(), "", getErrorCondition());
      return;
    }
    QString word;
    bool headerdone = false;
    int xpoints, ypoints, zpoints;
    float resx, resy, resz;
    while (headerdone == false)
    {
      QByteArray buf = in.readLine();

      if (buf.startsWith(DIMS))
      {
        QList<QByteArray> tokens = buf.split(' ');
        xpoints = tokens[1].toInt(&ok, 10);
        ypoints = tokens[2].toInt(&ok, 10);
        zpoints = tokens[3].toInt(&ok, 10);
        size_t dims[3] = { static_cast<size_t>(xpoints), static_cast<size_t>(ypoints), static_cast<size_t>(zpoints) };
        m->getGeometryAs<ImageGeom>()->setDimensions(dims);
        m->getGeometryAs<ImageGeom>()->setOrigin(0, 0, 0);
      }
      if (RES == word)
      {
        QList<QByteArray> tokens = buf.split(' ');
        resx = tokens[1].toInt(&ok, 10);
        resy = tokens[2].toInt(&ok, 10);
        resz = tokens[3].toInt(&ok, 10);
        float res[3] = {resx, resy, resz};
        m->getGeometryAs<ImageGeom>()->setResolution(res);
      }
    }
  }

  QVector<size_t> dims(1, 3);
  tempPath.update(getDataContainerName(), getCellAttributeMatrixName(), getCellEulerAnglesArrayName() );
  m_CellEulerAnglesPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<float>, AbstractFilter, float>(this,  tempPath, 0, dims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_CellEulerAnglesPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_CellEulerAngles = m_CellEulerAnglesPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
  dims[0] = 4;
  tempPath.update(getDataContainerName(), getCellAttributeMatrixName(), getQuatsArrayName() );
  m_QuatsPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<float>, AbstractFilter, float>(this,  tempPath, 0, dims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_QuatsPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_Quats = m_QuatsPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
  tempPath.update(getDataContainerName(), getCellFeatureAttributeMatrixName(), getAvgQuatsArrayName() );
  m_AvgQuatsPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<float>, AbstractFilter, float>(this,  tempPath, 0, dims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_AvgQuatsPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_AvgQuats = m_AvgQuatsPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
  dims[0] = 1;
  tempPath.update(getDataContainerName(), getCellAttributeMatrixName(), getCellPhasesArrayName() );
  m_CellPhasesPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<int32_t>, AbstractFilter, int32_t>(this,  tempPath, 1, dims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_CellPhasesPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_CellPhases = m_CellPhasesPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
  tempPath.update(getDataContainerName(), getCellFeatureAttributeMatrixName(), getSurfaceFeaturesArrayName() );
  m_SurfaceFeaturesPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<bool>, AbstractFilter, bool>(this,  tempPath, false, dims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_SurfaceFeaturesPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_SurfaceFeatures = m_SurfaceFeaturesPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
  tempPath.update(getDataContainerName(), getCellAttributeMatrixName(), getFeatureIdsArrayName() );
  m_FeatureIdsPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<int32_t>, AbstractFilter, int32_t>(this,  tempPath, 0, dims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_FeatureIdsPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_FeatureIds = m_FeatureIdsPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */

  //typedef DataArray<unsigned int> XTalStructArrayType;
  tempPath.update(getDataContainerName(), getCellEnsembleAttributeMatrixName(), getCrystalStructuresArrayName() );
  m_CrystalStructuresPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<uint32_t>, AbstractFilter, uint32_t>(this,  tempPath, Ebsd::CrystalStructure::Cubic_High, dims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_CrystalStructuresPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_CrystalStructures = m_CrystalStructuresPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
}
Esempio n. 30
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
FloatArrayType::Pointer AngleFileLoader::loadData()
{
  FloatArrayType::Pointer angles = FloatArrayType::NullPointer();

  // Make sure the input file variable is not empty
  if (m_InputFile.size() == 0)
  {
    setErrorMessage("Input File Path is empty");
    setErrorCode(-1);
    return angles;
  }

  QFileInfo fi(getInputFile());

  // Make sure the file exists on disk
  if (fi.exists() == false)
  {
    setErrorMessage("Input File does not exist at path");
    setErrorCode(-2);
    return angles;
  }

  // Make sure we have a valid angle representation
  if(m_AngleRepresentation != EulerAngles
      && m_AngleRepresentation != QuaternionAngles
      && m_AngleRepresentation != RodriguezAngles)
  {
    setErrorMessage("The Angle representation was not set to anything known to this code");
    setErrorCode(-3);
    return angles;
  }


  // The format of the file is quite simple. Comment lines start with a "#" symbol
  // The only Key-Value pair we are looking for is 'Angle Count' which will have
  // the total number of angles that will be read

  int numOrients = 0;
  QByteArray buf;

  // Open the file and read the first line
  QFile reader(getInputFile());
  if (!reader.open(QIODevice::ReadOnly | QIODevice::Text))
  {
    QString msg = QObject::tr("Angle file could not be opened: %1").arg(getInputFile());
    setErrorCode(-100);
    setErrorMessage(msg);
    return angles;
  }

  bool ok = false;
  buf = reader.readLine();
  while(buf[0] == '#')
  {
    buf = reader.readLine();
  }
  buf = buf.trimmed();

  //Split the next line into a pair of tokens delimited by the ":" character
  QList<QByteArray> tokens = buf.split(':');
  if(tokens.count() != 2)
  {
    QString msg = QObject::tr("Proper Header was not detected. The file should have a single header line of 'Angle Count:XXXX'");
    setErrorCode(-101);
    setErrorMessage(msg);
    return angles;
  }

  if(tokens[0].toStdString().compare("Angle Count") != 0)
  {
    QString msg = QObject::tr("Proper Header was not detected. The file should have a single header line of 'Angle Count:XXXX'");
    setErrorCode(-102);
    setErrorMessage(msg);
    return angles;
  }
  numOrients = tokens[1].toInt(&ok, 10);

  // Allocate enough for the angles
  QVector<size_t> dims(1, 5);
  angles = FloatArrayType::CreateArray(numOrients, dims, "EulerAngles_From_File");

  for(int i = 0; i < numOrients; i++)
  {
    float weight = 0.0f;
    float sigma = 1.0f;
    buf = reader.readLine();
    // Skip any lines that start with a '#' character
    if(buf[0] == '#') { continue; }
    buf = buf.trimmed();

    // Remove multiple Delimiters if wanted by the user.
    if (m_IgnoreMultipleDelimiters == true)
    {
      buf = buf.simplified();
    }
    tokens = buf.split( *(getDelimiter().toLatin1().data()));

    FOrientArrayType euler(3);
    if (m_AngleRepresentation == EulerAngles)
    {
      euler[0] = tokens[0].toFloat(&ok);
      euler[1] = tokens[1].toFloat(&ok);
      euler[2] = tokens[2].toFloat(&ok);
      weight = tokens[3].toFloat(&ok);
      sigma = tokens[4].toFloat(&ok);
    }
    else if (m_AngleRepresentation == QuaternionAngles)
    {
      FOrientArrayType quat(4);
      quat[0] = tokens[0].toFloat(&ok);
      quat[1] = tokens[1].toFloat(&ok);
      quat[2] = tokens[2].toFloat(&ok);
      quat[3] = tokens[3].toFloat(&ok);
      FOrientTransformsType::qu2eu(quat, euler);
      weight = tokens[4].toFloat(&ok);
      sigma = tokens[5].toFloat(&ok);
    }
    else if (m_AngleRepresentation == RodriguezAngles)
    {
      FOrientArrayType rod(4, 0.0);
      rod[0] = tokens[0].toFloat(&ok);
      rod[1] = tokens[1].toFloat(&ok);
      rod[2] = tokens[2].toFloat(&ok);
      FOrientTransformsType::ro2eu(rod, euler);
      weight = tokens[3].toFloat(&ok);
      sigma = tokens[4].toFloat(&ok);
    }

    // Values in File are in Radians and the user wants them in Degrees
    if (m_FileAnglesInDegrees == false && m_OutputAnglesInDegrees == true)
    {
      euler[0] = euler[0] * SIMPLib::Constants::k_RadToDeg;
      euler[1] = euler[1] * SIMPLib::Constants::k_RadToDeg;
      euler[2] = euler[2] * SIMPLib::Constants::k_RadToDeg;
    }
    // Values are in Degrees but user wants them in Radians
    else if (m_FileAnglesInDegrees == true && m_OutputAnglesInDegrees == false)
    {
      euler[0] = euler[0] * SIMPLib::Constants::k_DegToRad;
      euler[1] = euler[1] * SIMPLib::Constants::k_DegToRad;
      euler[2] = euler[2] * SIMPLib::Constants::k_DegToRad;
    }

    // Store the values into our array
    angles->setComponent(i, 0, euler[0]);
    angles->setComponent(i, 1, euler[1]);
    angles->setComponent(i, 2, euler[2]);
    angles->setComponent(i, 3, weight);
    angles->setComponent(i, 4, sigma);
    //   qDebug() << "reading line: " << i ;
  }



  return angles;
}