Exemple #1
0
 cross_cov_model_mark_ii_t(double p12, primary_cov_model_t * primary_cov_model, secondary_cov_model_t * secondary_cov_model)
     : m_secondary_cov_model(secondary_cov_model)
 {
     double primary_variance = (*primary_cov_model)(coord_t(0,0,0), coord_t(0,0,0));
     double secondary_variance = (*secondary_cov_model)(coord_t(0,0,0), coord_t(0,0,0));
     m_coef = p12 * sqrt( secondary_variance / primary_variance );
 }
/*
Creational method
@return fully constructed MDHistoDimension instance.
*/
MDHistoDimension *MDHistoDimensionBuilder::createRaw() {
  if (m_name.empty()) {
    throw std::invalid_argument(
        "Cannot create MDHistogramDimension without setting a name.");
  }
  if (m_id.empty()) {
    throw std::invalid_argument(
        "Cannot create MDHistogramDimension without setting a id.");
  }
  if (m_units.ascii().empty()) {
    throw std::invalid_argument(
        "Cannot create MDHistogramDimension without setting a unit type.");
  }
  if (!m_minSet) {
    throw std::invalid_argument(
        "Cannot create MDHistogramDimension without setting min.");
  }
  if (!m_maxSet) {
    throw std::invalid_argument(
        "Cannot create MDHistogramDimension without setting max.");
  }
  if (m_min >= m_max) {
    throw std::invalid_argument(
        "Cannot create MDHistogramDimension with min >= max.");
  }
  if (m_nbins <= 0) {
    throw std::invalid_argument(
        "Cannot create MDHistogramDimension without setting a n bins.");
  }
  return new MDHistoDimension(m_name, m_id, m_units, coord_t(m_min),
                              coord_t(m_max), m_nbins);
}
/** function extracts the coordinates from additional workspace properties and
*places them to proper position within
*  the vector of MD coordinates for the particular workspace.
*
*  @param inWS2D -- input workspace
*  @param dimPropertyNames  -- names of properties which should be treated as
*dimensions
*  @param AddCoord --
*
*  @return AddCoord       -- vector of additional coordinates (derived from WS
*properties) for current multidimensional event
*/
void MDWSDescription::fillAddProperties(
    Mantid::API::MatrixWorkspace_const_sptr inWS2D,
    const std::vector<std::string> &dimPropertyNames,
    std::vector<coord_t> &AddCoord) {
  size_t nDimPropNames = dimPropertyNames.size();
  if (AddCoord.size() != nDimPropNames)
    AddCoord.resize(nDimPropNames);

  for (size_t i = 0; i < nDimPropNames; i++) {
    // HACK: A METHOD, Which converts TSP into value, correspondent to time
    // scale of matrix workspace has to be developed and deployed!
    Kernel::Property *pProperty =
        (inWS2D->run().getProperty(dimPropertyNames[i]));
    Kernel::TimeSeriesProperty<double> *run_property =
        dynamic_cast<Kernel::TimeSeriesProperty<double> *>(pProperty);
    if (run_property) {
      AddCoord[i] = coord_t(run_property->firstValue());
    } else {
      // e.g Ei can be a property and dimension
      Kernel::PropertyWithValue<double> *proc_property =
          dynamic_cast<Kernel::PropertyWithValue<double> *>(pProperty);
      if (!proc_property) {
        std::string ERR =
            " Can not interpret property, used as dimension.\n Property: " +
            dimPropertyNames[i] + " is neither a time series (run) property "
                                  "nor a property with value<double>";
        throw(std::invalid_argument(ERR));
      }
      AddCoord[i] = coord_t(*(proc_property));
    }
  }
}
int movable_monster_obj::do_find_path(const coord_t &from,
                                      const coord_t &to,
                                      const bool can_chuan_tou)
{
  static coord_t path[MAX_MONSTER_FIND_PATH_DISTANCE];

  int got_steps = 0;
  if (scene_mgr::instance()->find_path(this->scene_id_,
                                       from,
                                       to,
                                       can_chuan_tou,
                                       sizeof(path) / sizeof(path[0]),
                                       path,
                                       got_steps) != 0)
  {
    e_log->wning("monster %d find path failed! in %d from %d.%d to %d.%d.",
                 this->cid(),
                 this->scene_cid_,
                 from.x_, from.y_,
                 to.x_, to.y_);
    return -1;
  }
  for (int i = 1; i < got_steps; ++i)
    this->path_.push_back(coord_t(path[i].x_, path[i].y_));
  return 0;
}
 //----------------------------------------------------------------------------------------------
 /// Advance to the next cell. If the current cell is the last one in the workspace
 /// do nothing and return false.
 /// @return true if you can continue iterating
 bool MDHistoWorkspaceIterator::next()
 {
   if (m_function)
   {
     do
     {
       m_pos++;
       Utils::NestedForLoop::Increment(m_nd, m_index, m_indexMax);
       // Calculate the center
       for (size_t d=0; d<m_nd; d++)
       {
         m_center[d] = m_origin[d] + (coord_t(m_index[d]) + 0.5f) * m_binWidth[d];
         //          std::cout << m_center[d] << ",";
       }
       //        std::cout<<std::endl;
       // Keep incrementing until you are in the implicit function
     } while (!m_function->isPointContained(m_center)
       && m_pos < m_max);
   }
   else
   {
     ++m_pos;
   }
   //Keep calling next if the current position is masked.
   bool ret = m_pos < m_max;
   while(m_skippingPolicy->keepGoing())
   {
     ret = this->next();
     if(!ret)
       break;
   }
   // Go through every point;
   return ret;
 }
Exemple #6
0
  /**
   * Generate the vtkDataSet from the objects input IMDEventWorkspace
   * @param progressUpdating : Reporting object to pass progress information up the stack.
   * @return fully constructed vtkDataSet.
   */
  vtkDataSet* vtkSplatterPlotFactory::create(ProgressAction& progressUpdating) const
  {
    UNUSED_ARG(progressUpdating);

    // If initialize() wasn't run, we don't have a workspace.
    if(!m_workspace)
    {
      throw std::runtime_error("Invalid vtkSplatterPlotFactory. Workspace is null");
    }

    size_t nd = m_workspace->getNumDims();
     
    Mantid::Kernel::ReadLock lock(*m_workspace);
    if (nd > 3)
    {
      // Slice from >3D down to 3D
      this->slice = true;
      this->sliceMask = new bool[nd];
      this->sliceImplicitFunction = new MDImplicitFunction();
      // Make the mask of dimensions
      // TODO: Smarter mapping
      for (size_t d = 0; d < nd; d++)
        this->sliceMask[d] = (d < 3);

      // Define where the slice is in 4D
      // TODO: Where to slice? Right now is just 0
      std::vector<coord_t> point(nd, 0);
      point[3] = coord_t(m_time); //Specifically for 4th/time dimension.

      // Define two opposing planes that point in all higher dimensions
      std::vector<coord_t> normal1(nd, 0);
      std::vector<coord_t> normal2(nd, 0);
      for (size_t d = 3; d < nd; d++)
      {
        normal1[d] = +1.0;
        normal2[d] = -1.0;
      }
      // This creates a 0-thickness region to slice in.
      sliceImplicitFunction->addPlane(MDPlane(normal1, point));
      sliceImplicitFunction->addPlane(MDPlane(normal2, point));
    }
    else
    {
      // Direct 3D, so no slicing
      this->slice = false;
    }

    // Macro to call the right instance of the
    CALL_MDEVENT_FUNCTION(this->doCreate, m_workspace);

    // Clean up
    if (this->slice)
    {
      delete[] this->sliceMask;
      delete this->sliceImplicitFunction;
    }

    // The macro does not allow return calls, so we used a member variable.
    return this->dataSet;
  }
void  MDEventWSWrapper::createEmptyEventWS(const Strings &targ_dim_names,const Strings &targ_dim_ID,const Strings &targ_dim_units,
                                           const std::vector<double> &dimMin, const std::vector<double> &dimMax,const std::vector<size_t> &numBins)
{

  boost::shared_ptr<MDEvents::MDEventWorkspace<MDEvents::MDEvent<nd>,nd> > ws = 
    boost::shared_ptr<MDEvents::MDEventWorkspace<MDEvents::MDEvent<nd>, nd> >(new MDEvents::MDEventWorkspace<MDEvents::MDEvent<nd>, nd>());

  size_t nBins(10);
  // Give all the dimensions
  for (size_t d=0; d<nd; d++)
  {
    if(!numBins.empty()) nBins=numBins[d];

    Geometry::MDHistoDimension * dim = new Geometry::MDHistoDimension(targ_dim_names[d], targ_dim_ID[d], targ_dim_units[d], 
                                                                      coord_t(dimMin[d]), coord_t(dimMax[d]), nBins);
     ws->addDimension(Geometry::MDHistoDimension_sptr(dim));
  }
  ws->initialize();

  // Build up the box controller
  // bc = ws->getBoxController();
  // Build up the box controller, using the properties in BoxControllerSettingsAlgorithm 
  //     this->setBoxController(bc);
  // We always want the box to be split (it will reject bad ones)
  //ws->splitBox();
   m_Workspace = ws;
}
TEST(load_point_cloud, reads_a_point_cloud_by_storing_all_the_points) {
  FILE *in_stream = tmpfile();
  fprintf(in_stream, "# size=3\n");
  fprintf(in_stream, "12345\t67890\n");
  fprintf(in_stream, "45678\t90123\n");
  fprintf(in_stream, "86793\t57364\n");
  rewind(in_stream);

  point_cloud test_cloud;
  load_point_cloud(in_stream, &test_cloud);

  ASSERT_EQ(coord_t(12345), test_cloud.points[0].x);
  ASSERT_EQ(coord_t(67890), test_cloud.points[0].y);

  ASSERT_EQ(coord_t(86793), test_cloud.points[2].x);
  ASSERT_EQ(coord_t(57364), test_cloud.points[2].y);
}
AffineMatrixParameter *AffineMatrixParameterParser::createParameter(
    Poco::XML::Element *parameterElement) {
  std::string typeName = parameterElement->getChildElement("Type")->innerText();
  if (AffineMatrixParameter::parameterName() != typeName) {
    throw std::runtime_error(std::string(
        "AffineMatrixParameterParser cannot parse parameter of type: " +
        typeName));
  } else {
    // Convenience typedefs
    typedef std::vector<std::string> VecStrings;
    typedef std::vector<coord_t> VecDoubles;

    std::string sParameterValue =
        parameterElement->getChildElement("Value")->innerText();

    VecStrings vecStrRows;
    VecStrings vecStrCols;

    boost::split(vecStrRows, sParameterValue, boost::is_any_of(";"));
    size_t nRows = vecStrRows.size();

    auto row_it = vecStrRows.begin();
    VecStrings::iterator col_it;

    size_t nCols = 0;
    VecDoubles elements;

    // Process each row and column and extract each element as a double.
    while (row_it != vecStrRows.end()) {
      boost::split(vecStrCols, *row_it, boost::is_any_of(","));
      nCols = vecStrCols.size();
      col_it = vecStrCols.begin();
      while (col_it != vecStrCols.end()) {
        coord_t val = coord_t(atof(col_it->c_str()));
        elements.push_back(val);
        ++col_it;
      }
      ++row_it;
    }

    // Create the Matrix.
    AffineMatrixType m(nRows, nCols);
    size_t count = 0;
    for (size_t i = 0; i < nRows; i++) {
      for (size_t j = 0; j < nCols; j++) {
        m[i][j] = elements[count];
        count++;
      }
    }

    // Create the parameter and set the matrix.
    auto parameter = new AffineMatrixParameter(nRows - 1, nCols - 1);
    parameter->setMatrix(m);

    // Now return the fully constructed parameter.
    return parameter;
  }
}
 //----------------------------------------------------------------------------------------------
 /// Returns the position of the center of the box pointed to.
 Mantid::Kernel::VMD MDHistoWorkspaceIterator::getCenter() const
 {
   // Get the indices
   Utils::NestedForLoop::GetIndicesFromLinearIndex(m_nd, m_pos, m_indexMaker, m_indexMax, m_index);
   // Find the center
   for (size_t d=0; d<m_nd; d++)
     m_center[d] = m_origin[d] + (coord_t(m_index[d]) + 0.5f) * m_binWidth[d];
   return VMD(m_nd, m_center);
 }
Exemple #11
0
    void merge(const Contour3D& ctr) {
        auto s3 = coord_t(points.size());
        auto s = indices.size();

        points.insert(points.end(), ctr.points.begin(), ctr.points.end());
        indices.insert(indices.end(), ctr.indices.begin(), ctr.indices.end());

        for(size_t n = s; n < indices.size(); n++) {
            auto& idx = indices[n]; x(idx) += s3; y(idx) += s3; z(idx) += s3;
        }
    }
/*
Creational method
@return fully constructed MDHistoDimension instance.
*/
MDHistoDimension *MDHistoDimensionBuilder::createRaw() {
  if (m_name.empty()) {
    throw std::invalid_argument(
        "Cannot create MDHistogramDimension without setting a name.");
  }
  if (m_id.empty()) {
    throw std::invalid_argument(
        "Cannot create MDHistogramDimension without setting a id.");
  }
  if (m_units.ascii().empty()) {
    throw std::invalid_argument(
        "Cannot create MDHistogramDimension without setting a unit type.");
  }
  if (!m_minSet) {
    throw std::invalid_argument(
        "Cannot create MDHistogramDimension without setting min.");
  }
  if (!m_maxSet) {
    throw std::invalid_argument(
        "Cannot create MDHistogramDimension without setting max.");
  }
  if (m_min >= m_max) {
    throw std::invalid_argument(
        "Cannot create MDHistogramDimension with min >= max.");
  }
  if (m_nbins <= 0) {
    throw std::invalid_argument(
        "Cannot create MDHistogramDimension without setting a n bins.");
  }

  // Select a Mantid Frame. Use FrameName if available else just use name.
  auto frameFactory = Mantid::Geometry::makeMDFrameFactoryChain();
  std::string frameNameForFactory = m_frameName.empty() ? m_name : m_frameName;
  Mantid::Geometry::MDFrameArgument frameArgument(frameNameForFactory, m_units);
  auto frame = frameFactory->create(frameArgument);

  return new MDHistoDimension(m_name, m_id, *frame, coord_t(m_min),
                              coord_t(m_max), m_nbins);
}
Exemple #13
0
/*
 * This function is executed in a parallel region based on layer_nr.
 * When modifying make sure any changes does not introduce data races.
 *
 * this function may only read/write the skin and infill from the *current* layer.
 */
void SkinInfillAreaComputation::applySkinExpansion(const Polygons& original_outline, Polygons& upskin, Polygons& downskin)
{
    // First we set the amount of distance we want to expand, as indicated in settings
    coord_t top_outset = top_skin_expand_distance;
    coord_t bottom_outset = bottom_skin_expand_distance;

    coord_t top_min_width = mesh.getSettingInMicrons("min_skin_width_for_expansion") / 2;
    coord_t bottom_min_width = top_min_width;

    // Compensate for the pre-shrink applied because of the Skin Removal Width.
    // The skin removal width is satisfied by applying a close operation and
    // it's done in the calculateTopSkin and calculateBottomSkin, by expanding the infill.
    // The inset of that close operation is applied in calculateTopSkin and calculateBottomSkin
    // The outset of the close operation is applied at the same time as the skin expansion.
    top_outset += top_reference_wall_expansion;
    bottom_outset += bottom_reference_wall_expansion;

    // Calculate the shrinkage needed to fulfill the minimum skin with for expansion
    top_min_width = std::max(coord_t(0), top_min_width - top_reference_wall_expansion / 2); // if the min width is smaller than the pre-shrink then areas smaller than min_width will exist
    bottom_min_width = std::max(coord_t(0), bottom_min_width - bottom_reference_wall_expansion / 2); // if the min width is smaller than the pre-shrink then areas smaller than min_width will exist

    // skin areas are to be enlarged by skin_expand_distance but before they are expanded
    // the skin areas are shrunk by min_width so that very narrow regions of skin
    // (often caused by the model's surface having a steep incline) are not expanded

    top_outset += top_min_width; // increase the expansion distance to compensate for the min_width shrinkage
    bottom_outset += bottom_min_width; // increase the expansion distance to compensate for the min_width shrinkage

    // Execute shrinkage and expansion in the same operation
    if (top_outset)
    {
        upskin = upskin.offset(-top_min_width).offset(top_outset).unionPolygons(upskin).intersection(original_outline);
    }

    if (bottom_outset)
    {
        downskin = downskin.offset(-bottom_min_width).offset(bottom_outset).unionPolygons(downskin).intersection(original_outline);
    }
}
Exemple #14
0
void build_system(
    const coord_t & center,
    const std::vector<coord_t> & coords,
    const primary_cov_model_t & primary_cov,
    const cross_cov_model_t & cross_cov,
    double secondary_variance,
    std::vector<double> & A,
    std::vector<double> & b)
{
    int neighbour_count = coords.size();
    int matrix_size = neighbour_count + 1;

    A.resize(matrix_size * matrix_size);

    b.resize(matrix_size);

    for (int i = 0; i < neighbour_count; ++i)
    {
        for (int j = i; j < neighbour_count; ++j)
        {
            A[i * matrix_size + j] = primary_cov(coords[i], coords[j]);
            A[j * matrix_size + i] = A[i * matrix_size + j];
        }
    }

    for (int i = 0; i < neighbour_count; ++i)
    {
        A[neighbour_count * matrix_size + i] = cross_cov(center, coords[i]);
        A[i * matrix_size + neighbour_count] = A[neighbour_count * matrix_size + i];
        b[i] = primary_cov(coords[i], center);
    }

    b[neighbour_count] = cross_cov(coord_t(0,0,0), coord_t(0,0,0));

    A[matrix_size * matrix_size - 1] = secondary_variance;
}
void movable_monster_obj::do_simple_find_path(const short from_x,
                                              const short from_y,
                                              const short to_x,
                                              const short to_y)
{
  short cur_x = from_x;
  short cur_y = from_y;
  while (true)
  {
    int next_dir = util::calc_next_dir(cur_x, cur_y, to_x, to_y);
    if (next_dir == DIR_XX) break; // equal
    cur_x += s_dir_step[next_dir][0];
    cur_y += s_dir_step[next_dir][1];
    if (!scene_config::instance()->can_move(this->scene_cid_,
                                            cur_x,
                                            cur_y))
      break;
    this->path_.push_back(coord_t(cur_x, cur_y));
  }
}
Exemple #16
0
static inline Polyline make_wave_vertical(
    double width, double height, double x0,
    double segmentSize, double scaleFactor,
    double z_cos, double z_sin, bool flip)
{
    Polyline polyline;
    polyline.points.emplace_back(Point(coord_t(clamp(0., width, x0) * scaleFactor), 0));
    double phase_offset_sin = (z_cos < 0 ? M_PI : 0) + M_PI;
    double phase_offset_cos = (z_cos < 0 ? M_PI : 0) + M_PI + (flip ? M_PI : 0.);
    for (double y = 0.; y < height + segmentSize; y += segmentSize) {
        y = std::min(y, height);
        double a   = sin(y + phase_offset_sin);
        double b   = - z_cos;
        double res = z_sin * cos(y + phase_offset_cos);
        double r   = sqrt(sqr(a) + sqr(b));
        double x   = clamp(0., width, asin(a/r) + asin(res/r) + M_PI + x0);
        polyline.points.emplace_back(convert_to<Point>(Pointf(x, y) * scaleFactor));
    }
    if (flip)
        std::reverse(polyline.points.begin(), polyline.points.end());
    return polyline;
}
Exemple #17
0
static inline Polyline make_wave_horizontal(
    double width, double height, double y0, 
    double segmentSize, double scaleFactor,
    double z_cos, double z_sin, bool flip)
{
    Polyline polyline;
    polyline.points.emplace_back(Point(0, coord_t(clamp(0., height, y0) * scaleFactor)));
    double phase_offset_sin = (z_sin < 0 ? M_PI : 0) + (flip ? 0 : M_PI);
    double phase_offset_cos = z_sin < 0 ? M_PI : 0.;
    for (double x=0.; x < width + segmentSize; x += segmentSize) {
        x = std::min(x, width);
        double a   = cos(x + phase_offset_cos);
        double b   = - z_sin;
        double res = z_cos * sin(x + phase_offset_sin);
        double r   = sqrt(sqr(a) + sqr(b));
        double y   = clamp(0., height, asin(a/r) + asin(res/r) + 0.5 * M_PI + y0);
        polyline.points.emplace_back(convert_to<Point>(Pointf(x, y) * scaleFactor));
    }
    if (flip)
        std::reverse(polyline.points.begin(), polyline.points.end());
    return polyline;
}
    /**
    Create the vtkStructuredGrid from the provided workspace
    @param progressUpdating: Reporting object to pass progress information up the stack.
    @return fully constructed vtkDataSet.
    */
    vtkDataSet* vtkMDHistoLineFactory::create(ProgressAction& progressUpdating) const
    {
      vtkDataSet* product = tryDelegatingCreation<MDHistoWorkspace, 1>(m_workspace, progressUpdating);
      if(product != NULL)
      {
        return product;
      }
      else
      {
        g_log.warning() << "Factory " << this->getFactoryTypeName() << " is being used. You are viewing data with less than three dimensions in the VSI. \n";

        Mantid::Kernel::ReadLock lock(*m_workspace);
        const int nBinsX = static_cast<int>( m_workspace->getXDimension()->getNBins() );

        const coord_t maxX = m_workspace-> getXDimension()->getMaximum();
        const coord_t minX = m_workspace-> getXDimension()->getMinimum();

        coord_t incrementX = (maxX - minX) / coord_t(nBinsX-1);

        const int imageSize = nBinsX;
        vtkPoints *points = vtkPoints::New();
        points->Allocate(static_cast<int>(imageSize));

        vtkFloatArray * signal = vtkFloatArray::New();
        signal->Allocate(imageSize);
        signal->SetName(vtkDataSetFactory::ScalarName.c_str());
        signal->SetNumberOfComponents(1);

        UnstructuredPoint unstructPoint;
        const int nPointsX = nBinsX;
        Column column(nPointsX);

        NullCoordTransform transform;
        //Mantid::API::CoordTransform* transform = m_workspace->getTransformFromOriginal();
        Mantid::coord_t in[3]; 
        Mantid::coord_t out[3];

        double progressFactor = 0.5/double(nBinsX);
        double progressOffset = 0.5;

        //Loop through dimensions
        for (int i = 0; i < nPointsX; i++)
        {
          progressUpdating.eventRaised(progressFactor * double(i));
          in[0] = minX + static_cast<coord_t>(i) * incrementX; //Calculate increment in x;

          float signalScalar = static_cast<float>(m_workspace->getSignalNormalizedAt(i));

          if (isSpecial( signalScalar ) || !m_thresholdRange->inRange(signalScalar))
          {
            //Flagged so that topological and scalar data is not applied.
            unstructPoint.isSparse = true;
          }
          else
          {
            if (i < (nBinsX -1))
            {
              signal->InsertNextValue(static_cast<float>(signalScalar));
            }
            unstructPoint.isSparse = false;
          }

          transform.apply(in, out);

          unstructPoint.pointId = points->InsertNextPoint(out);
          column[i] = unstructPoint;

        }

        points->Squeeze();
        signal->Squeeze();

        vtkUnstructuredGrid *visualDataSet = vtkUnstructuredGrid::New();
        visualDataSet->Allocate(imageSize);
        visualDataSet->SetPoints(points);
        visualDataSet->GetCellData()->SetScalars(signal);

        for (int i = 0; i < nBinsX - 1; i++)
        {
          progressUpdating.eventRaised((progressFactor * double(i)) + progressOffset);
          //Only create topologies for those cells which are not sparse.
          if (!column[i].isSparse)
          {
            vtkLine* line = vtkLine::New();
            line->GetPointIds()->SetId(0, column[i].pointId);
            line->GetPointIds()->SetId(1, column[i + 1].pointId);
            visualDataSet->InsertNextCell(VTK_LINE, line->GetPointIds());
          }
        }

        points->Delete();
        signal->Delete();
        visualDataSet->Squeeze();

        // Hedge against empty data sets
        if (visualDataSet->GetNumberOfPoints() <= 0)
        {
          visualDataSet->Delete();
          vtkNullUnstructuredGrid nullGrid;
          visualDataSet = nullGrid.createNullData();
        }

        return visualDataSet;
      }
    }
Exemple #19
0
        Size Font::measureText(const String& text) const
        {
            jni::Object paint = jni::Class("android/graphics/Paint").newInstance();

            paint.call<jni::Object>("setTypeface(Landroid/graphics/Typeface;)Landroid/graphics/Typeface;", (jni::Object*) getHandle());
            paint.call<void>("setTextSize", _size);

            return { (coord_t) paint.call<float>("measureText(Ljava/lang/String;)F", text.toArray()), coord_t(_size * 1.4) /* TODO: Actually measure this? */ };
        }
Exemple #20
0
TEST_F(SettingsTest, AddSettingCoordT)
{
    settings.add("test_setting", "8589934.592"); //2^33 microns, so this MUST be a 64-bit integer! (Or at least 33-bit, but those don't exist.)
    EXPECT_EQ(coord_t(8589934592), settings.get<coord_t>("test_setting")) << "Coordinates must be entered in the setting as millimetres, but are converted to micrometres.";
}
bool point_struct_t::isNeighbour(point_struct_t const& point, uint16_t resolution)
{
    return isNeighbour(coord_t(point.x, point.y), resolution);
}
Exemple #22
0
/// get the scaled clipper units for a millimeter value
inline coord_t mm(double v) { return coord_t(v/SCALING_FACTOR); }
Exemple #23
0
 cross_cov_model_mark_i_t(double p12, double d2, cov_model_t * cov_model)
     : m_cov_model(cov_model)
 {
     m_coef = p12 * sqrt(d2) / sqrt((*cov_model)(coord_t(0,0,0), coord_t(0,0,0)));
 }
Exemple #24
0
		Rectangle Rectangle::scale(float factor) const noexcept
		{
			return { coord_t(x * factor), coord_t(y * factor), coord_t(width * factor), coord_t(height * factor) };
		}
Exemple #25
0
		Rectangle Rectangle::deflate(float hamount, float vamount) const noexcept
		{
			return { x + coord_t(hamount), y + coord_t(vamount), width - coord_t(2 * hamount), height - coord_t(2 * vamount) };
		}
Exemple #26
0
void FillGyroid::_fill_surface_single(
    const FillParams                &params, 
    unsigned int                     thickness_layers,
    const std::pair<float, Point>   &direction, 
    ExPolygon                       &expolygon, 
    Polylines                       &polylines_out)
{
    // no rotation is supported for this infill pattern
    BoundingBox bb = expolygon.contour.bounding_box();
    coord_t     distance = coord_t(scale_(this->spacing) / (params.density*this->scaling));

    // align bounding box to a multiple of our grid module
    bb.merge(_align_to_grid(bb.min, Point(2*M_PI*distance, 2*M_PI*distance)));
    
    // generate pattern
    Polylines   polylines = make_gyroid_waves(
        scale_(this->z),
        params.density*this->scaling,
        this->spacing,
        ceil(bb.size().x / distance) + 1.,
        ceil(bb.size().y / distance) + 1.);
    
    // move pattern in place
    for (Polyline &polyline : polylines)
        polyline.translate(bb.min.x, bb.min.y);

    // clip pattern to boundaries
    polylines = intersection_pl(polylines, (Polygons)expolygon);

    // connect lines
    if (! params.dont_connect && ! polylines.empty()) { // prevent calling leftmost_point() on empty collections
        ExPolygon expolygon_off;
        {
            ExPolygons expolygons_off = offset_ex(expolygon, (float)SCALED_EPSILON);
            if (! expolygons_off.empty()) {
                // When expanding a polygon, the number of islands could only shrink. Therefore the offset_ex shall generate exactly one expanded island for one input island.
                assert(expolygons_off.size() == 1);
                std::swap(expolygon_off, expolygons_off.front());
            }
        }
        Polylines chained = PolylineCollection::chained_path_from(
            std::move(polylines), 
            PolylineCollection::leftmost_point(polylines), false); // reverse allowed
        bool first = true;
        for (Polyline &polyline : chained) {
            if (! first) {
                // Try to connect the lines.
                Points &pts_end = polylines_out.back().points;
                const Point &first_point = polyline.points.front();
                const Point &last_point = pts_end.back();
                // TODO: we should also check that both points are on a fill_boundary to avoid 
                // connecting paths on the boundaries of internal regions
                // TODO: avoid crossing current infill path
                if (first_point.distance_to(last_point) <= 5 * distance && 
                    expolygon_off.contains(Line(last_point, first_point))) {
                    // Append the polyline.
                    pts_end.insert(pts_end.end(), polyline.points.begin(), polyline.points.end());
                    continue;
                }
            }
            // The lines cannot be connected.
            polylines_out.emplace_back(std::move(polyline));
            first = false;
        }
    }
}
Exemple #27
0
void FakeMDEventData::addFakeRegularData(
    const std::vector<double> &params,
    typename MDEventWorkspace<MDE, nd>::sptr ws) {
  // the parameters for regular distribution of events over the box
  std::vector<double> startPoint(nd), delta(nd);
  std::vector<size_t> indexMax(nd);
  size_t gridSize(0);

  // bool RandomizeSignal = getProperty("RandomizeSignal");

  size_t num = size_t(params[0]);
  if (num == 0)
    throw std::invalid_argument(
        " number of distributed events can not be equal to 0");

  Progress prog(this, 0.0, 1.0, 100);
  size_t progIncrement = num / 100;
  if (progIncrement == 0)
    progIncrement = 1;

  // Inserter to help choose the correct event type
  auto eventHelper =
      MDEvents::MDEventInserter<typename MDEventWorkspace<MDE, nd>::sptr>(ws);

  gridSize = 1;
  for (size_t d = 0; d < nd; ++d) {
    double min = ws->getDimension(d)->getMinimum();
    double max = ws->getDimension(d)->getMaximum();
    double shift = params[d * 2 + 1];
    double step = params[d * 2 + 2];
    if (shift < 0)
      shift = 0;
    if (shift >= step)
      shift = step * (1 - FLT_EPSILON);

    startPoint[d] = min + shift;
    if ((startPoint[d] < min) || (startPoint[d] >= max))
      throw std::invalid_argument("RegularData: starting point must be within "
                                  "the box for all dimensions.");

    if (step <= 0)
      throw(std::invalid_argument(
          "Step of the regular grid is less or equal to 0"));

    indexMax[d] = size_t((max - min) / step);
    if (indexMax[d] == 0)
      indexMax[d] = 1;
    // deal with round-off errors
    while ((startPoint[d] + double(indexMax[d] - 1) * step) >= max)
      step *= (1 - FLT_EPSILON);

    delta[d] = step;

    gridSize *= indexMax[d];
  }
  // Create all the requested events
  std::vector<size_t> indexes;
  size_t cellCount(0);
  for (size_t i = 0; i < num; ++i) {
    coord_t centers[nd];

    Kernel::Utils::getIndicesFromLinearIndex(cellCount, indexMax, indexes);
    ++cellCount;
    if (cellCount >= gridSize)
      cellCount = 0;

    for (size_t d = 0; d < nd; d++) {
      centers[d] = coord_t(startPoint[d] + delta[d] * double(indexes[d]));
    }

    // Default or randomized error/signal
    float signal = 1.0;
    float errorSquared = 1.0;
    // if (RandomizeSignal)
    //{
    //  signal = float(0.5 + genUnit());
    //  errorSquared = float(0.5 + genUnit());
    //}

    // Create and add the event.
    eventHelper.insertMDEvent(signal, errorSquared, 1, pickDetectorID(),
                              centers); // 1 = run number
    // Progress report
    if ((i % progIncrement) == 0)
      prog.report();
  }
}