Пример #1
0
void DrawingItemGroup::render(QPainter* painter, const DrawingStyleOptions& styleOptions)
{
#ifdef DEBUG_DRAW_ITEM_SHAPE
	painter->setBrush(Qt::magenta);
	painter->setPen(QPen(Qt::magenta, 1));
	painter->drawPath(shape());
#endif

	for(auto itemIter = mItems.begin(); itemIter != mItems.end(); itemIter++)
	{
		if ((*itemIter)->isVisible())
		{
			qreal scaleFactor = Drawing::unitsScale((*itemIter)->units(), units());

			painter->save();
			painter->translate((*itemIter)->pos());
			painter->scale(scaleFactor, scaleFactor);
			(*itemIter)->render(painter, styleOptions);
			painter->restore();
		}
	}
}
TEST(BoxPointContainment, ComplexInside)
{
    shapes::Box shape(1.0, 1.0, 1.0);
    bodies::Body* box = new bodies::Box(&shape);
    box->setScale(1.01);
    Eigen::Affine3d pose(Eigen::AngleAxisd(M_PI/3.0, Eigen::Vector3d::UnitX()));
    pose.translation() = Eigen::Vector3d(1.0,1.0,1.0); 
    box->setPose(pose);

    bool contains = box->containsPoint(1.5,1.0,1.5);
    EXPECT_TRUE(contains);

    random_numbers::RandomNumberGenerator r;
    Eigen::Vector3d p;
    for (int i = 0 ; i < 100 ; ++i)
    {
        EXPECT_TRUE(box->samplePointInside(r, 100, p));
	EXPECT_TRUE(box->containsPoint(p));
    }

    delete box;
}
Пример #3
0
void AbstractButtonItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event)
{
  if( m_mouseDown )
  {
    m_mouseDown = false;

    this->update();

    if( shape().contains(event->pos()) )
    {
      event->accept();

      m_checked = ! m_checked;

      update();

      emit mouseClicked(m_checked);

      emit toggled(m_checked);
    }
  }
}
Пример #4
0
boost::shared_ptr<btCompoundShape> ConvexDecomp::run(std::vector<boost::shared_ptr<btCollisionShape> > &shapeStorage) {
    HACD::HACD hacd;
    hacd.SetPoints(&points[0]);
    hacd.SetNPoints(points.size());
    hacd.SetTriangles(&triangles[0]);
    hacd.SetNTriangles(triangles.size());
    hacd.SetCompacityWeight(0.1);
    hacd.SetVolumeWeight(0.0);

    // HACD parameters
    // Recommended parameters: 2 100 0 0 0 0
    //size_t nClusters = 2;
    size_t nClusters = 1;
    double concavity = 100;
    bool invert = false;
    bool addExtraDistPoints = false;
    bool addNeighboursDistPoints = false;
    bool addFacesPoints = false;       

    hacd.SetNClusters(nClusters);                     // minimum number of clusters
    hacd.SetNVerticesPerCH(100);                      // max of 100 vertices per convex-hull
    hacd.SetConcavity(concavity);                     // maximum concavity
    hacd.SetAddExtraDistPoints(addExtraDistPoints);   
    hacd.SetAddNeighboursDistPoints(addNeighboursDistPoints);   
    hacd.SetAddFacesPoints(addFacesPoints); 

    hacd.Compute();
    nClusters = hacd.GetNClusters();	

    boost::shared_ptr<btCompoundShape> compound(new btCompoundShape());
    for (int c = 0; c < nClusters; ++c) {
        btVector3 centroid;
        boost::shared_ptr<btConvexHullShape> shape(processCluster(hacd, c, centroid));
        shapeStorage.push_back(shape);
        compound->addChildShape(btTransform(btQuaternion(0, 0, 0, 1), centroid), shape.get());
    }

    return compound;
}
Пример #5
0
int main()
{
	sf::RenderWindow window(sf::VideoMode(200, 200), "SFML Works!");
	sf::CircleShape shape(100.f);
	shape.setFillColor(sf::Color::Green);

	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
		}

		window.clear();
		window.draw(shape);
		window.display();
	}

	return 0;
}
Пример #6
0
    bool getMemoryShapes(const std::vector<MatShape> &inputs,
                         const int requiredOutputs,
                         std::vector<MatShape> &outputs,
                         std::vector<MatShape> &internals) const
    {
        CV_Assert(inputs.size() == 2);

        int layerHeight = inputs[0][2];
        int layerWidth = inputs[0][3];

        // Since all images in a batch has same height and width, we only need to
        // generate one set of priors which can be shared across all images.
        size_t outNum = 1;
        // 2 channels. First channel stores the mean of each prior coordinate.
        // Second channel stores the variance of each prior coordinate.
        size_t outChannels = 2;

        outputs.resize(1, shape(outNum, outChannels,
                                layerHeight * layerWidth * _numPriors * 4));

        return false;
    }
// This test case including path coords and matrix taken from crbug.com/627443.
// Because of inaccuracies in large floating point values this causes the
// the path renderer to attempt to add a path DF to its atlas that is larger
// than the plot size which used to crash rather than fail gracefully.
static void test_far_from_origin(GrDrawContext* drawContext, GrPathRenderer* pr,
                                 GrResourceProvider* rp) {
    SkPath path;
    path.lineTo(49.0255089839f, 0.473541f);
    static constexpr SkScalar mvals[] = {14.0348252854f, 2.13026182736f,
                                         13.6122547187f, 118.309922702f,
                                         1912337682.09f, 2105391889.87f};
    SkMatrix matrix;
    matrix.setAffine(mvals);
    SkMatrix inverse;
    SkAssertResult(matrix.invert(&inverse));
    path.transform(inverse);

    SkStrokeRec rec(SkStrokeRec::kFill_InitStyle);
    rec.setStrokeStyle(1.f);
    rec.setStrokeParams(SkPaint::kRound_Cap, SkPaint::kRound_Join, 1.f);
    GrStyle style(rec, nullptr);

    GrShape shape(path, style);
    shape = shape.applyStyle(GrStyle::Apply::kPathEffectAndStrokeRec, 1.f);

    GrPaint paint;
    paint.setXPFactory(GrPorterDuffXPFactory::Make(SkXfermode::kSrc_Mode));

    GrNoClip noClip;
    GrPathRenderer::DrawPathArgs args;
    args.fPaint = &paint;
    args.fUserStencilSettings = &GrUserStencilSettings::kUnused;
    args.fDrawContext = drawContext;
    args.fClip = &noClip;
    args.fResourceProvider = rp;
    args.fViewMatrix = &matrix;
    args.fShape = &shape;
    args.fAntiAlias = true;
    args.fGammaCorrect = false;
    args.fColor = 0x0;
    pr->drawPath(args);
}
Пример #8
0
int
main()
{
  typedef agg::pixfmt_bgr24 pixel_type;
  
  const unsigned w = 60, h = 50;
  
  unsigned row_size = pixel_type::pix_width * w;
  unsigned buf_size = row_size * h;
  agg::pod_array<unsigned char> img_buf(buf_size);
  
  agg::rendering_buffer rbuf(img_buf.data(), w, h, app_flip_y ? -row_size : row_size);
  pixel_type pixf(rbuf);
  
  typedef agg::renderer_base<pixel_type> renderer_base;
  typedef agg::renderer_scanline_aa_solid<renderer_base> renderer_solid;

  renderer_base rb(pixf);
  renderer_solid rs(rb);
  
  agg::rasterizer_scanline_aa<> ras;
  agg::scanline_p8 sl;

  agg::rgba8 white(255, 255, 255);
  rb.clear(white);

  agg::rgba8 color(160, 0, 0);

  agg::ellipse shape(30.0, 25.0, 12.0, 12.0);
  
  ras.add_path(shape);
  rs.color(color);
  agg::render_scanlines(ras, sl, rs);
  
  save_image_file(rbuf, "output.ppm");
  
  return 0;
}
Пример #9
0
    static BlobShape getBlobShpae(std::vector<Mat> &vmat, int requestedCn = -1)
    {
        BlobShape shape(4);
        int cnSum = 0, matCn;

        CV_Assert(vmat.size() > 0);

        for (size_t i = 0; i < vmat.size(); i++)
        {
            Mat &mat = vmat[i];
            CV_Assert(!mat.empty());
            CV_Assert((mat.dims == 3 && mat.channels() == 1) || mat.dims <= 2);

            matCn = getMatChannels(mat);
            cnSum += getMatChannels(mat);

            if (i == 0)
            {
                shape[-1] = mat.cols;
                shape[-2] = mat.rows;
                shape[-3] = (requestedCn <= 0) ? matCn : requestedCn;
            }
            else
            {
                if (mat.cols != shape[-1] || mat.rows != shape[-2])
                    CV_Error(Error::StsError, "Each Mat.size() must be equal");

                if (requestedCn <= 0 && matCn != shape[-3])
                    CV_Error(Error::StsError, "Each Mat.chnannels() (or number of planes) must be equal");
            }
        }

        if (cnSum % shape[-3] != 0)
            CV_Error(Error::StsError, "Total number of channels in vector is not a multiple of requsted channel number");

        shape[0] = cnSum / shape[-3];
        return shape;
    }
void DelegateVideoControl::paint(QPainter *painter,
        const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    painter->fillPath(shape(), brush());

    qreal frameWidth = rect().height() / 2;
    int position = frameWidth;

    if (mTotalTimeInMs > 0)
    {
        position = frameWidth + (rect().width() - (2 * frameWidth)) / mTotalTimeInMs * mCurrentTimeInMs;
    }

    int radius = rect().height() / 6;
    QRectF r(rect().x() + position - radius, rect().y() + (rect().height() / 4) - radius, radius * 2, radius * 2);

    painter->setBrush(UBSettings::documentViewLightColor);
    painter->drawEllipse(r);

    if(mDisplayCurrentTime)
    {
        painter->setBrush(UBSettings::paletteColor);
        painter->setPen(QPen(Qt::NoPen));
        QRectF balloon(rect().x() + position - frameWidth, rect().y() - (frameWidth * 1.2), 2 * frameWidth, frameWidth);
        painter->drawRoundedRect(balloon, frameWidth/2, frameWidth/2);

        QTime t;
        t = t.addMSecs(mCurrentTimeInMs < 0 ? 0 : mCurrentTimeInMs);
        QFont f = painter->font();
            f.setPointSizeF(f.pointSizeF() * mAntiScale);
        painter->setFont(f);
        painter->setPen(Qt::white);
        painter->drawText(balloon, Qt::AlignCenter, t.toString("m:ss"));
    }
}
Пример #11
0
void ConnEnd::outputCode(FILE *fp, const char *srcDst, unsigned int num) const
{
    if (num == 0)
    {
        num = m_conn_ref->id();
    }

    if (junction())
    {
        fprintf(fp, "    ConnEnd %sPt%u(junctionRef%u);\n", srcDst,
                num, m_anchor_obj->id());
    }
    else if (shape())
    {
        fprintf(fp, "    ConnEnd %sPt%u(shapeRef%u, %u);\n", srcDst,
                num, m_anchor_obj->id(), m_connection_pin_class_id);
    }
    else
    {
        fprintf(fp, "   ConnEnd %sPt%u(Point(%g, %g), (ConnDirFlags) %u);\n",
                srcDst, num, m_point.x, m_point.y, m_directions);
    }
}
Пример #12
0
void AdvancedTabBar::resizeEvent(QResizeEvent * event)
{
    QTabBar::resizeEvent(event);
    switch (shape()) {
    case QTabBar::RoundedNorth:
    case QTabBar::TriangularNorth:
    case QTabBar::RoundedSouth:
    case QTabBar::TriangularSouth:
        setMinimumSize(parentWidget()->width(), 0);
        d->list->setViewMode(QListView::IconMode);
        break;
    case QTabBar::RoundedEast:
    case QTabBar::TriangularEast:
    case QTabBar::RoundedWest:
    case QTabBar::TriangularWest:
        setMinimumSize(0, parentWidget()->height());
        d->list->setViewMode(QListView::ListMode);
        break;
    }
    d->list->setDragEnabled(false);
    d->list->setDragDropMode(QAbstractItemView::NoDragDrop);
    d->list->resize(size());
}
  void ReshapeBlobs(int num_timesteps, int num_instances) {
    blob_bottom_.Reshape(num_timesteps, num_instances, 3, 2);
    vector<int> shape(2);
    shape[0] = num_timesteps;
    shape[1] = num_instances;
    blob_bottom_flush_.Reshape(shape);
    shape.push_back(num_output_);

    shape[0] = 1; shape[1] = num_instances; shape[2] = 4 * num_output_;
    unit_blob_bottom_x_.Reshape(shape);
    shape[0] = 1; shape[1] = num_instances; shape[2] = num_output_;
    unit_blob_bottom_c_prev_.Reshape(shape);
    shape[0] = 1; shape[1] = 1; shape[2] = num_instances;
    unit_blob_bottom_flush_.Reshape(shape);

    FillerParameter filler_param;
    filler_param.set_min(-1);
    filler_param.set_max(1);
    UniformFiller<Dtype> filler(filler_param);
    filler.Fill(&blob_bottom_);
    filler.Fill(&unit_blob_bottom_c_prev_);
    filler.Fill(&unit_blob_bottom_x_);
  }
Пример #14
0
	boost::numeric::ublas::matrix< T > &
	numpy_to_ublas(
		boost::python::object a,
		boost::numeric::ublas::matrix< T > & m )
	{
		boost::python::tuple shape( a.attr("shape") );
		if( boost::python::len( shape ) != 2 )
		{
			throw std::logic_error( "numeric::array must have 2 dimensions" );
		}
		m.resize(
			boost::python::extract< unsigned >( shape[0] ),
			boost::python::extract< unsigned >( shape[1] ) );
		for( unsigned i = 0; i < m.size1(); ++i )
		{
			for( unsigned j = 0; j < m.size2(); ++j )
			{
				m( i, j ) = boost::python::extract< T >( a[ 
boost::python::make_tuple( i, j ) ] );
			}
		}
		return m;
	}
Пример #15
0
TEST(DATA, SourceRetype)
{
	std::vector<ade::DimT> slist = {3, 3, 3};
	ade::Shape shape(slist);

	size_t n = shape.n_elems();
	std::vector<double> data = {
		16, 51, 12, 55, 69, 10, 52, 86, 95,
		6, 78, 18, 100, 11, 52, 66, 55, 30,
		80, 81, 36, 26, 63, 78, 80, 31, 37
	};
	ade::TensptrT ptr(llo::Variable<double>::get(data, shape));

	llo::TensptrT<uint16_t> gd = llo::eval<uint16_t>(ptr);
	auto gotslist = gd->dimensions();
	EXPECT_ARREQ(slist, gotslist);

	uint16_t* gotdata = (uint16_t*) gd->data();
	for (size_t i = 0; i < n; ++i)
	{
		EXPECT_EQ((uint16_t) data[i], gotdata[i]);
	}
}
Пример #16
0
TEST(CylinderPointContainment, CylinderPadding)
{
    shapes::Cylinder shape(1.0, 4.0);
    bodies::Body* cylinder = new bodies::Cylinder(&shape);
    bool contains = cylinder->containsPoint(0,1.01,0);
    EXPECT_FALSE(contains);
    cylinder->setPadding(.02);
    contains = cylinder->containsPoint(0,1.01,0);
    EXPECT_TRUE(contains);
    cylinder->setPadding(0.0);
    bodies::BoundingSphere bsphere;
    cylinder->computeBoundingSphere(bsphere);
    EXPECT_TRUE(bsphere.radius > 2.0);

    random_numbers::RandomNumberGenerator r;
    Eigen::Vector3d p;
    for (int i = 0 ; i < 1000 ; ++i)
    {
        EXPECT_TRUE(cylinder->samplePointInside(r, 100, p));
        EXPECT_TRUE(cylinder->containsPoint(p));
    }
    delete cylinder;
}
Пример #17
0
   void cxios_write_data_k47(const char* fieldid, int fieldid_size, float* data_k4,
                             int data_0size, int data_1size, int data_2size,
                             int data_3size, int data_4size, int data_5size,
                             int data_6size)
   {
      std::string fieldid_str;
      if (!cstr2string(fieldid, fieldid_size, fieldid_str)) return;

      CTimer::get("XIOS").resume();
      CTimer::get("XIOS send field").resume();

      CContext* context = CContext::getCurrent();
      if (!context->hasServer && !context->client->isAttachedModeEnabled())
        context->checkBuffersAndListen();

      CArray<float, 7> data_tmp(data_k4, shape(data_0size, data_1size, data_2size, data_3size, data_4size, data_5size, data_6size), neverDeleteData);
      CArray<double, 7> data(data_0size, data_1size, data_2size, data_3size, data_4size, data_5size, data_6size);
      data = data_tmp;
      CField::get(fieldid_str)->setData(data);

      CTimer::get("XIOS send field").suspend();
      CTimer::get("XIOS").suspend();
    }
Пример #18
0
void tst_QPainterPath::translate()
{
    QPainterPath path;

    // Path with no elements.
    QCOMPARE(path.currentPosition(), QPointF());
    path.translate(50.5, 50.5);
    QCOMPARE(path.currentPosition(), QPointF());
    QCOMPARE(path.translated(50.5, 50.5).currentPosition(), QPointF());

    // path.isEmpty(), but we have one MoveTo element that should be translated.
    path.moveTo(50, 50);
    QCOMPARE(path.currentPosition(), QPointF(50, 50));
    path.translate(99.9, 99.9);
    QCOMPARE(path.currentPosition(), QPointF(149.9, 149.9));
    path.translate(-99.9, -99.9);
    QCOMPARE(path.currentPosition(), QPointF(50, 50));
    QCOMPARE(path.translated(-50, -50).currentPosition(), QPointF(0, 0));

    // Complex path.
    QRegion shape(100, 100, 300, 200, QRegion::Ellipse);
    shape -= QRect(225, 175, 50, 50);
    QPainterPath complexPath;
    complexPath.addRegion(shape);
    QVector<QPointF> untranslatedElements;
    for (int i = 0; i < complexPath.elementCount(); ++i)
        untranslatedElements.append(QPointF(complexPath.elementAt(i)));

    const QPainterPath untranslatedComplexPath(complexPath);
    const QPointF offset(100, 100);
    complexPath.translate(offset);

    for (int i = 0; i < complexPath.elementCount(); ++i)
        QCOMPARE(QPointF(complexPath.elementAt(i)) - offset, untranslatedElements.at(i));

    QCOMPARE(complexPath.translated(-offset), untranslatedComplexPath);
}
void PickAndPlace::set_attached_object(bool attach, const geometry_msgs::Pose &pose,moveit_msgs::RobotState &robot_state)
{
	// get robot state
	robot_state::RobotStatePtr current_state= move_group_ptr->getCurrentState();

	if(attach)
	{

		// constructing shape
		std::vector<shapes::ShapeConstPtr> shapes_array;
		shapes::ShapeConstPtr shape( shapes::constructShapeFromMsg( cfg.ATTACHED_OBJECT.primitives[0]));
		shapes_array.push_back(shape);

		// constructing pose
		tf::Transform attached_tf;
		tf::poseMsgToTF(cfg.ATTACHED_OBJECT.primitive_poses[0],attached_tf);
		EigenSTL::vector_Affine3d pose_array(1);
		tf::transformTFToEigen(attached_tf,pose_array[0]);

		// attaching
		current_state->attachBody(cfg.ATTACHED_OBJECT_LINK_NAME,shapes_array,pose_array,cfg.TOUCH_LINKS,cfg.TCP_LINK_NAME);

		// update box marker
		cfg.MARKER_MESSAGE.header.frame_id = cfg.TCP_LINK_NAME;
		cfg.MARKER_MESSAGE.pose = cfg.TCP_TO_BOX_POSE;
	}
	else
	{

		// detaching
		if(current_state->hasAttachedBody(cfg.ATTACHED_OBJECT_LINK_NAME))
				current_state->clearAttachedBody(cfg.ATTACHED_OBJECT_LINK_NAME);
	}

	// save robot state data
	robot_state::robotStateToRobotStateMsg(*current_state,robot_state);
}
Пример #20
0
Shape ConformShapeToMod( // Return a copy of inshape conformed to the model
    VEC&         b,             // io: eigvec weights, 2n x 1
    const Shape& inshape,       // in: the current position of the landmarks
    const Shape& meanshape,     // in: n x 2
    const VEC&   eigvals,       // in: neigs x 1
    const MAT&   eigvecs,       // in: 2n x neigs
    const MAT&   eigvecsi,      // in: neigs x 2n, inverse of eigvecs
    const double bmax,          // in: for LimitB
    const VEC&   pointweights)  // in: contribution of each point to the pose
{
    Shape shape(inshape.clone());

    // estimate the pose which transforms the shape into the model space
    // (use the b from previous iterations of the ASM)

    MAT modelshape(AsColVec(meanshape) + eigvecs * b);
    modelshape = DimKeep(modelshape, shape.rows, 2); // redim back to 2 columns
    const MAT pose(AlignmentMat(modelshape, shape, Buf(pointweights)));

    // transform the shape into the model space

    modelshape = TransformShape(shape, pose.inv(cv::DECOMP_LU));

    // update shape model params b to match modelshape, then limit b

    b = eigvecsi * AsColVec(modelshape - meanshape);
    LimitB(b, eigvals, bmax);

    // generate conformedshape from the model using the limited b
    // (we generate as a column vec, then redim back to 2 columns)

    const Shape conformedshape(DimKeep(eigvecs * b, shape.rows, 2));

    // back to image space

    return JitterPointsAt00(TransformShape(meanshape + conformedshape, pose));
}
Пример #21
0
Ship::Ship(int mX, int mY, EventHandler e, int align, sf::Color c)
{
	mx = mX;
	my = mY;
	x = 50;
	y = std::abs(mx * align - 50);
	health = 100; // arbitrary value
	start = e.myClock.getElapsedTime();
	end = e.myClock.getElapsedTime();
	radius = 20;
	attackDelay = 100;
	curAtkDelay = attackDelay;
	alignment = align;
	myColor = c;
	curColor = c;
	healthBar.setSize(sf::Vector2f(health * 2, 50));
	healthBar.setFillColor(curColor);
	if(alignment == 0)
		shipTexture.loadFromFile("ShipB.png");
	else
		shipTexture.loadFromFile("ShipG.png");
	shipSprite.setTexture(shipTexture);
	shipRenderTexture.create(shipTexture.getSize().x, shipTexture.getSize().y);
	shipRenderTexture.draw(shipSprite);
	sf::CircleShape shape(radius);
	shape.setOutlineColor(curColor);
	shape.setFillColor(sf::Color(0,0,0,0));
	shape.setOutlineThickness(1);
	shipRenderTexture.draw(shape);	
	shipRenderTexture.display(); // update the texture
	shipSprite.setTexture(shipRenderTexture.getTexture());
	hitColor = sf::Color(255-c.r, 255-c.g,255-c.b);
	moveSpeed = 2;
	specialA = 0;
	specialB = 0;
}
Пример #22
0
/**
 * Get the peaks info for a single peak, defined by the row in the peaks table.
 * @param peaksWorkspace A pointer to a peaks workspace.
 * @param row The row in the peaks table.
 * @param position A reference which holds the position of the peak.
 * @param radius A reference which holds the radius of the peak.
 * @param specialCoordinateSystem The coordinate system.
 */
void ConcretePeaksPresenterVsi::getPeaksInfo(
    Mantid::API::IPeaksWorkspace_sptr peaksWorkspace, int row,
    Mantid::Kernel::V3D &position, double &radius,
    Mantid::Kernel::SpecialCoordinateSystem specialCoordinateSystem) const {

  switch (specialCoordinateSystem) {
  case (Mantid::Kernel::SpecialCoordinateSystem::QLab):
    position = peaksWorkspace->getPeak(row).getQLabFrame();
    break;
  case (Mantid::Kernel::SpecialCoordinateSystem::QSample):
    position = peaksWorkspace->getPeak(row).getQSampleFrame();
    break;
  case (Mantid::Kernel::SpecialCoordinateSystem::HKL):
    position = peaksWorkspace->getPeak(row).getHKL();
    break;
  default:
    throw std::invalid_argument("The coordinate system is invalid.\n");
  }

  // Peak radius
  Mantid::Geometry::PeakShape_sptr shape(
      peaksWorkspace->getPeakPtr(row)->getPeakShape().clone());
  radius = getMaxRadius(shape);
}
Пример #23
0
bool load_blob_from_uint8_binary<double>(const string fn_blob, Blob<double>* blob){
	FILE *f;
	f = fopen(fn_blob.c_str(), "rb");
	if (f==NULL)
		return false;
	int n, c, l, w, h;
	double* buff;
	fread(&n, sizeof(int), 1, f);
	fread(&c, sizeof(int), 1, f);
	fread(&l, sizeof(int), 1, f);
	fread(&h, sizeof(int), 1, f);
	fread(&w, sizeof(int), 1, f);

	vector<int> shape(5);
	shape[0] = n;
	shape[1] = c;
	shape[2] = l;
	shape[3] = h;
	shape[4] = w;
	blob->Reshape(shape);

	buff = blob->mutable_cpu_data();


	int count = n * c * l * h * w;
	unsigned char* temp_buff = new unsigned char[count];

	fread(temp_buff, sizeof(unsigned char), count, f);
	fclose(f);

	for (int i = 0; i < count; i++)
		buff[i] = (double)temp_buff[i];

	delete []temp_buff;
	return true;
}
Пример #24
0
vector<int> DataTransformer<Dtype>::InferBlobShape(const Datum& datum) {

  #ifndef CAFFE_HEADLESS

  if (datum.encoded()) {
    CHECK(!(param_.force_color() && param_.force_gray()))
        << "cannot set both force_color and force_gray";
    cv::Mat cv_img;
    if (param_.force_color() || param_.force_gray()) {
    // If force_color then decode in color otherwise decode in gray.
      cv_img = DecodeDatumToCVMat(datum, param_.force_color());
    } else {
      cv_img = DecodeDatumToCVMatNative(datum);
    }
    // InferBlobShape using the cv::image.
    return InferBlobShape(cv_img);
  }

  #endif

  const int crop_size = param_.crop_size();
  const int datum_channels = datum.channels();
  const int datum_height = datum.height();
  const int datum_width = datum.width();
  // Check dimensions.
  CHECK_GT(datum_channels, 0);
  CHECK_GE(datum_height, crop_size);
  CHECK_GE(datum_width, crop_size);
  // Build BlobShape.
  vector<int> shape(4);
  shape[0] = 1;
  shape[1] = datum_channels;
  shape[2] = (crop_size)? crop_size: datum_height;
  shape[3] = (crop_size)? crop_size: datum_width;
  return shape;
}
Пример #25
0
blitz::Array<T,rank> read_blitz(NcFile &nc, std::string const &var_name)
{
	// Read points vector
	NcVar *vpoints = nc.get_var(var_name.c_str());
	int ndims = vpoints->num_dims();
	if (ndims != rank) {
		fprintf(stderr, "NetCDF variable %s has rank %d, expected rank %d\n",
			var_name.c_str(), ndims, rank);
		throw std::exception();
	}

	blitz::TinyVector<int,rank> shape(0);
	long counts[rank];
	for (int i=0; i<rank; ++i) {
		shape[i] = vpoints->get_dim(i)->size();
printf("read_blitz: shape[%d] = %d\n", i, shape[i]);
		counts[i] = shape[i];
	}

	blitz::Array<T,rank> ret(shape);
for (int i=0; i<rank; ++i) printf("read_blitz: ret.extent(%d) = %d\n", i, ret.extent(i));
	vpoints->get(ret.data(), counts);
	return ret;
}
Пример #26
0
 Kernel::DblMatrix MantidVecHelper::getMatrixFromArray(PyObject *p)
 {       
   _import_array();
   if(PyArray_Check(p)==1)
   {
     boost::python::numeric::array a=boost::python::extract<boost::python::numeric::array>(p);
     a=(boost::python::numeric::array) a.astype('d');//force the array to be of double type (in case it was int)
     boost::python::tuple shape( a.attr("shape") );                  
     if( boost::python::len( shape ) != 2 ) throw std::invalid_argument( "numeric::array must have 2 dimensions" );
     size_t nx,ny,i,j;
     nx=(size_t)(boost::python::extract< unsigned >( shape[0] ));
     ny=(size_t)(boost::python::extract< unsigned >( shape[1] ));
     Kernel::Matrix<double> m(nx,ny);
     for( i = 0; i < nx; i++ )
     {
       for( j = 0; j < ny; j++ )
       {
         m[i][j] = boost::python::extract< double >( a[ boost::python::make_tuple( i, j ) ] );
       }
     }
     return m; 
   }      
   else throw std::invalid_argument("Not a numpy array"); 
 } 
Пример #27
0
	void parse_shapes(const char* json, Array<PhysicsConfigShape>& objects)
	{
		TempAllocator4096 ta;
		JsonObject object(ta);
		sjson::parse(json, object);

		auto begin = map::begin(object);
		auto end = map::end(object);

		for (; begin != end; ++begin)
		{
			const FixedString key = begin->pair.first;
			const char* value     = begin->pair.second;

			JsonObject shape(ta);
			sjson::parse_object(value, shape);

			PhysicsConfigShape ps2;
			ps2.name    = StringId32(key.data(), key.length());
			ps2.trigger = sjson::parse_bool(shape["trigger"]);

			array::push_back(objects, ps2);
		}
	}
Пример #28
0
void IC::print() {
  char* s;
  switch (shape()) {
    case anamorphic : s = "Anamorphic";  break;
    case monomorphic: s = "Monomorphic"; break;
    case polymorphic: s = "Polymorphic"; break;
    case megamorphic: s = "Megamorphic"; break;
    default         : ShouldNotReachHere();
  }
  std->print("%s IC: %d entries\n", s, number_of_targets());

  IC_Iterator* it = iterator();
  it->init_iteration();
  while (!it->at_end()) {
    lprintf("\t- klass: ");
    it->klass()->print_value();
    if (it->is_interpreted()) {
      lprintf(";\tmethod  %#x\n", it->interpreted_method());
    } else {
      lprintf(";\tnmethod %#x\n", it->compiled_method());
    }
    it->advance();
  }
}
Пример #29
0
unique_ptr<BaseSignal> ndarray_to_matrix(bpyn::array a){

    int ndim = bpy::extract<int>(a.attr("ndim"));

    if (ndim == 1){

        int size = bpy::extract<int>(a.attr("size"));
        auto ret = unique_ptr<BaseSignal>(new BaseSignal(size, 1));
        for(unsigned i = 0; i < size; i++){
            (*ret)(i, 0) = bpy::extract<dtype>(a[i]);
        }

        return ret;

    }else{
        int size = bpy::extract<int>(a.attr("size"));
        vector<int> shape(ndim);
        vector<int> strides(ndim);
        bpy::object python_shape = a.attr("shape");
        bpy::object python_strides = a.attr("strides");

        for(unsigned i = 0; i < ndim; i++){
            shape[i] = bpy::extract<int>(python_shape[i]);
            strides[i] = bpy::extract<int>(python_strides[i]);
        }

        auto ret = unique_ptr<BaseSignal>(new BaseSignal(shape[0], shape[1]));
        for(unsigned i = 0; i < shape[0]; i++){
            for(unsigned j = 0; j < shape[1]; j++){
                (*ret)(i, j) = bpy::extract<dtype>(a[i][j]);
            }
        }

        return ret;
    }
}
Пример #30
0
    bool forward_ocl(InputArrayOfArrays inps, OutputArrayOfArrays outs, OutputArrayOfArrays internals)
    {
        std::vector<UMat> inputs;
        std::vector<UMat> outputs;

        inps.getUMatVector(inputs);
        outs.getUMatVector(outputs);

        for (size_t i = 0; i < inputs.size(); i++)
        {
            UMat srcBlob = inputs[i];
            void *src_handle = inputs[i].handle(ACCESS_READ);
            void *dst_handle = outputs[i].handle(ACCESS_WRITE);
            if (src_handle != dst_handle)
            {
                MatShape outShape = shape(outputs[i]);
                UMat umat = srcBlob.reshape(1, (int)outShape.size(), &outShape[0]);
                umat.copyTo(outputs[i]);
            }
        }
        outs.assign(outputs);

        return true;
    }