void Variable::SetValue(const NDArrayViewPtr& value) { if (!IsParameter()) LogicError("Variable::SetValue can be only invoked on a Parameter variable!"); else if (GetDataType() != value->GetDataType()) LogicError("Variable::SetValue: 'source' and 'destination' have different data types!"); else if (Shape() != value->Shape() && (AsTensorShape(Shape()) != AsTensorShape(value->Shape()))) LogicError("Variable::SetValue: 'source' and 'destination' have different shapes!"); bool alreadySet = false; if (m_dataFields->m_initValueFlag) { // In the case of lazy initialization, try to avoid the redundant call to the initializer. std::call_once(*m_dataFields->m_initValueFlag, [=, &value, &alreadySet] { // If the variable hasn't been initialized yet, clone the content of the supplied value and delete the initializer. m_dataFields->m_value = value->DeepClone(*m_dataFields->m_valueInitializationDevice, false); m_dataFields->m_valueInitializer = nullptr; m_dataFields->m_valueInitializationDevice = nullptr; alreadySet = true; }); } assert(m_dataFields->m_value != nullptr); if (!alreadySet) { // alreadySet is false, the lambda above wasn't called and the variable has been initialized before, // get a pointer to its value and simply copy the content of the supplied value. m_dataFields->m_value->CopyFrom(*value); } }
NDArrayViewPtr Variable::Value() const { if (!IsConstant() && !IsParameter()) LogicError("Only Variables of kind Parameter and Constant have a Value!"); if (m_dataFields->m_value == nullptr) { assert(m_dataFields->m_valueInitializer); assert(m_dataFields->m_valueInitializationDevice); switch (GetDataType()) { case DataType::Float: { m_dataFields->m_value = CreateValueFromParameterInitializer<float>(Shape(), *m_dataFields->m_valueInitializer, *m_dataFields->m_valueInitializationDevice); break; } case DataType::Double: { m_dataFields->m_value = CreateValueFromParameterInitializer<double>(Shape(), *m_dataFields->m_valueInitializer, *m_dataFields->m_valueInitializationDevice); break; } default: LogicError("Unsupported DataType %s", DataTypeName(GetDataType())); break; } m_dataFields->m_valueInitializer = nullptr; m_dataFields->m_valueInitializationDevice = nullptr; } assert(m_dataFields->m_value != nullptr); return m_dataFields->m_value; }
AntisymmetricMatrixVectorConvolution_FFT::AntisymmetricMatrixVectorConvolution_FFT(const Matrix &lhs, int dim_x, int dim_y, int dim_z) : MatrixVectorConvolution_FFT(dim_x, dim_y, dim_z, lhs.getShape().getDim(1), lhs.getShape().getDim(2), lhs.getShape().getDim(3)) { assert(lhs.getShape().getDim(0) == 3); // Allocate buffers for (int e=0; e<3; ++e) { if (!is_2d) { N.re[e] = Matrix(Shape(exp_z, exp_x/2+1, exp_y)); N.im[e] = Matrix(Shape(exp_z, exp_x/2+1, exp_y)); } else { N.re[e] = Matrix(Shape(exp_y, exp_z, exp_x/2+1)); N.im[e] = Matrix(Shape(exp_y, exp_z, exp_x/2+1)); } } // Setup tensor field TensorFieldSetup setup(3, dim_x, dim_y, dim_z, exp_x, exp_y, exp_z); ComplexMatrix lhs2 = setup.transformTensorField(lhs); Matrix *foo1[3] = {&N.re[0], &N.re[1], &N.re[2]}; Matrix *foo2[3] = {&N.im[0], &N.im[1], &N.im[2]}; if (!is_2d) { setup.unpackTransformedTensorField_xyz_to_zxy(lhs2, foo1, foo2); } else { setup.unpackTransformedTensorField_xyz_to_yzx(lhs2, foo1, foo2); } }
Neighborhood::Neighborhood(unsigned int size_x, unsigned int size_y) : size_x(size_x), size_y(size_y) { for (double i = 0; (i / (size_x*size_y)) < RATIO_FILLED; i++) { neighborhood_ = new Shape[size_x * size_y]; // fill with non-empty shapes so that the ratio of non-empty to empty // shapes is `RATIO_FILLED` (from `constants.h`) for (int filled = 0; filled < size_x*size_y*RATIO_FILLED; ) { unsigned int x = mtrand(0, size_x - 1); unsigned int y = mtrand(0, size_y - 1); if (this->get(x, y).getType() == "empty") { this->set(x, y, mtrand(0, 1) ? Shape("triangle") : Shape("square")); filled++; } } } }
FreeWill::TensorDescriptorHandle FreeWill::Model::addTensor(const std::string &name, const Shape &shape, DataType dataType, bool isBatchTensor, bool isRandomlyInitialized) { if (m_tensors.find(name) != m_tensors.end()) { return TensorDescriptorHandle(this, std::string(), Shape()); } m_tensors[name] = new FreeWill::TensorDescriptor(name, shape, dataType, isBatchTensor, isRandomlyInitialized); return TensorDescriptorHandle(this, name, Shape()); }
void VigraRFclassifier::learn(std::vector< std::vector<double> >& pfeatures, std::vector<int>& plabels){ if (_rf) delete _rf; int rows = pfeatures.size(); int cols = pfeatures[0].size(); printf("Number of samples and dimensions: %d, %d\n",rows, cols); if ((rows<1)||(cols<1)){ return; } // clock_t start = clock(); std::time_t start, end; std::time(&start); MultiArray<2, float> features(Shape(rows,cols)); MultiArray<2, int> labels(Shape(rows,1)); int numzeros=0; for(int i=0; i < rows; i++){ labels(i,0) = plabels[i]; numzeros += (labels(i,0)==-1?1:0); for(int j=0; j < cols ; j++){ features(i,j) = (float)pfeatures[i][j]; } } printf("Number of merge: %d\n",numzeros); int tre_count = 255; printf("Number of trees: %d\n",tre_count); RandomForestOptions rfoptions = RandomForestOptions().tree_count(tre_count).use_stratification(RF_EQUAL); //RF_EQUAL, RF_PROPORTIONAL _rf= new RandomForest<>(rfoptions); // construct visitor to calculate out-of-bag error visitors::OOB_Error oob_v; visitors::VariableImportanceVisitor varimp_v; _rf->learn(features, labels); _nfeatures = _rf->column_count(); _nclass = _rf->class_count(); std::time(&end); printf("Time required to learn RF: %.2f sec\n", (difftime(end,start))*1.0); // printf("Time required to learn RF: %.2f\n", ((double)clock() - start) / CLOCKS_PER_SEC); printf("with oob :%f\n", oob_v.oob_breiman); }
void createShape(shape_type st) { Shape s = Shape(st, idCounter, TransformTranslate(vec3(0.0,0.0,0.0)), TransformRotate(vec3(0.0,0.0,0.0)), TransformScale(vec3(1.0,1.0,1.0))); listOfShapes.push_back(s); selected = idCounter; idCounter++; }
void MAS::Window::Maximize() { if (extraFlags & W_MINIMIZED) { return; } if (!(extraFlags & W_MAXIMIZED)) { restoreRect = (*this); extraFlags |= W_MAXIMIZED; iconMax.SetBitmap(Skin::ICONRESTORE); Place(GetParent()->topLeft()); Resize(GetParent()->size()); iconMax.SetSample(Skin::SAMPLE_CLOSE, Skin::SAMPLE_ACTIVATE); iconMin.SetSample(Skin::SAMPLE_ACTIVATE, Skin::SAMPLE_ACTIVATE); } else { extraFlags &= ~W_MAXIMIZED; iconMax.SetBitmap(Skin::ICONMAX); Shape(restoreRect); iconMax.SetSample(Skin::SAMPLE_OPEN, Skin::SAMPLE_ACTIVATE); iconMin.SetSample(Skin::SAMPLE_ACTIVATE, Skin::SAMPLE_ACTIVATE); } MsgShape(); }
void TestShape::testPopFromPointArray() { this->testInit(__func__); Shape shape = Shape(); Point *points = new Point[2]; points[0] = Point(1,2,3); points[1] = Point(-1.2,-3.4,-5.6); shape.pushToPointArray(points[0]); shape.pushToPointArray(points[1]); Point point = shape.popFromPointArray(); if (shape.getPointCount() != 1) { this->testFailed(); } if (point.getX() != points[1].getX()) { this->testFailed(); } if (point.getY() != points[1].getY()) { this->testFailed(); } if (point.getZ() != points[1].getZ()) { this->testFailed(); } this->testInterpret(); }
void TestShape::testPushToPointArray() { this->testInit(__func__); Shape shape = Shape(); Point *points = new Point[2]; points[0] = Point(1,2,3); points[1] = Point(-1.2,-3.4,-5.6); shape.pushToPointArray(points[0]); shape.pushToPointArray(points[1]); if (shape.getPointCount() != 2) { this->testFailed(); } for (int i = 0; i < shape.getPointCount(); i++) { Point point = shape.getPointArray()[i]; if (point.getX() != points[i].getX()) { this->testFailed(); } if (point.getY() != points[i].getY()) { this->testFailed(); } if (point.getZ() != points[i].getZ()) { this->testFailed(); } } this->testInterpret(); }
VectorMatrix CalculateStrayfieldForCuboid( int dim_x, int dim_y, int dim_z, double delta_x, double delta_y, double delta_z, int mag_dir, Vector3d pos, Vector3d size, int infinity) { // Check arguments. if ((infinity & INFINITE_POS_X || infinity & INFINITE_NEG_X) && size.x != 0.0) throw std::runtime_error("CalculateStrayfieldForCuboid: cuboid size in x-direction must be zero for infinite extents in x direction"); if ((infinity & INFINITE_POS_Y || infinity & INFINITE_NEG_Y) && size.y != 0.0) throw std::runtime_error("CalculateStrayfieldForCuboid: cuboid size in y-direction must be zero for infinite extents in y direction"); if ((infinity & INFINITE_POS_Z || infinity & INFINITE_NEG_Z) && size.z != 0.0) throw std::runtime_error("CalculateStrayfieldForCuboid: cuboid size in z-direction must be zero for infinite extents in z direction"); if (size.x < 0.0 || size.y < 0.0 || size.z < 0.0) throw std::runtime_error("CalculateStrayfieldForCuboid: cuboid size must be positive"); if (dim_x < 1 || dim_y < 1 || dim_z < 1) throw std::runtime_error("CalculateStrayfieldForCuboid: dim_x,y,z must be positive"); if (!(delta_x > 0.0 && delta_y > 0.0 && delta_z > 0.0)) throw std::runtime_error("CalculateStrayfieldForCuboid: delta_x,y,z must be positive"); if (mag_dir < 0 || mag_dir > 2) throw std::runtime_error("CalculateStrayfieldForCuboid: cuboid_mag_dir must be 0, 1, or 2"); Vector3d p0 = pos; Vector3d p1 = pos + size; VectorMatrix H(Shape(dim_x, dim_y, dim_z)); H.clear(); VectorMatrix::accessor H_acc(H); H_acc.set(0,0,0, Vector3d(1,2,3)); assert(0); }
Shape Shape::map(Transform t) const { return Shape("m" + (t.x_forward.length() ? t.x_forward : " ") + (t.y_forward.length() ? t.y_forward : " ") + (t.z_forward.length() ? t.z_forward : " ") + math, bounds.map(t)); }
/*! \since 5.5 Initializes \a option with the values from this QFrame. This method is useful for subclasses when they need a QStyleOptionFrame but don't want to fill in all the information themselves. \sa QStyleOption::initFrom() */ void QFrame::initStyleOption(QStyleOptionFrame *option) const { if (!option) return; Q_D(const QFrame); option->initFrom(this); int frameShape = d->frameStyle & QFrame::Shape_Mask; int frameShadow = d->frameStyle & QFrame::Shadow_Mask; option->frameShape = Shape(int(option->frameShape) | frameShape); option->rect = frameRect(); switch (frameShape) { case QFrame::Box: case QFrame::HLine: case QFrame::VLine: case QFrame::StyledPanel: case QFrame::Panel: option->lineWidth = d->lineWidth; option->midLineWidth = d->midLineWidth; break; default: // most frame styles do not handle customized line and midline widths // (see updateFrameWidth()). option->lineWidth = d->frameWidth; break; } if (frameShadow == Sunken) option->state |= QStyle::State_Sunken; else if (frameShadow == Raised) option->state |= QStyle::State_Raised; }
RNBoolean R3SceneElement:: Intersects(const R3Ray& ray, R3Shape **hit_shape, R3Point *hit_point, R3Vector *hit_normal, RNScalar *hit_t) const { // Variables RNScalar closest_t = FLT_MAX; R3Point point; R3Vector normal; RNScalar t; // Intersect with shapes for (int i = 0; i < NShapes(); i++) { R3Shape *shape = Shape(i); if (shape->Intersects(ray, &point, &normal, &t)) { if (t < closest_t) { if (hit_shape) *hit_shape = shape; if (hit_point) *hit_point = point; if (hit_normal) *hit_normal = normal; if (hit_t) *hit_t = t; closest_t = t; } } } // Return whether hit any shape return (closest_t == FLT_MAX) ? FALSE : TRUE; }
void Neighborhood::move(unsigned int old_x, unsigned int old_y) { //unsigned int new_x = mtrand(0, (size_x - 1)); //unsigned int new_y = mtrand(0, (size_y - 1)); // // while (neighborhood_[new_x, new_y].getType() != "empty") // { // new_x = mtrand(0, (size_x - 1)); // new_y = mtrand(0, (size_y - 1)); // } // // neighborhood_[new_x, new_y].getType() = neighborhood_[old_x, old_y].getType(); // neighborhood_[old_x, old_y].getType() = "empty"; for (;;) { unsigned int x = mtrand(0, size_x - 1); unsigned int y = mtrand(0, size_y - 1); // not my code, borrowed from HyrekanDragon because mine^^ wouldnt work if (get(x, y).getType() == "empty") { set(x, y, get(old_x, old_y)); set(old_x, old_y, Shape("empty")); break; } } }
/*! \internal Mostly for the sake of Q3Frame */ void QFrame::drawFrame(QPainter *p) { Q_D(QFrame); QStyleOptionFrameV3 opt; opt.init(this); int frameShape = d->frameStyle & QFrame::Shape_Mask; int frameShadow = d->frameStyle & QFrame::Shadow_Mask; opt.frameShape = Shape(int(opt.frameShape) | frameShape); opt.rect = frameRect(); switch (frameShape) { case QFrame::Box: case QFrame::HLine: case QFrame::VLine: case QFrame::StyledPanel: case QFrame::Panel: opt.lineWidth = d->lineWidth; opt.midLineWidth = d->midLineWidth; break; default: // most frame styles do not handle customized line and midline widths // (see updateFrameWidth()). opt.lineWidth = d->frameWidth; break; } if (frameShadow == Sunken) opt.state |= QStyle::State_Sunken; else if (frameShadow == Raised) opt.state |= QStyle::State_Raised; style()->drawControl(QStyle::CE_ShapedFrame, &opt, p, this); }
Shape Document::shape(const QString &shapeName) const { int index = indexOf(shapeName); if (index == -1) return Shape(); return m_shapeList.at(index); }
void NDMask::CopyFrom(const NDMask& source) { if (source.Shape() != Shape()) InvalidArgument("NDMask::CopyFrom: The 'source' mask's shape must be same as the shape of this NDMask"); GetMatrix()->AssignValuesOf(*source.GetMatrix()); }
Matrix calculateDemagTensor_old(long double lx, long double ly, long double lz, int nx, int ny, int nz, int ex, int ey, int ez, int repeat_x, int repeat_y, int repeat_z) { LOG_DEBUG<< "Generating."; Matrix N(Shape(6, ex, ey, ez)); N.fill(0.0); Matrix::wo_accessor N_acc(N); const int dx_len = repeat_x*nx-1; const int dy_len = repeat_y*ny-1; const int dz_len = repeat_z*nz-1; int cnt = 0, percent = 0; for (int dz=0; dz<=+dz_len; dz+=1) { for (int dy=0; dy<=+dy_len; dy+=1) { for (int dx=0; dx<=+dx_len; dx+=1) { computeEntry(N_acc, dx, dy, dz, lx, ly, lz, ex, ey, ez); } cnt += 1; if (100.0 * cnt / ((dy_len+1)*(dz_len+1)) > percent) { LOG_INFO << " " << percent << "%"; percent += 5; } } } LOG_INFO << "Done."; return N; }
void NDArrayView::CopyFrom(const NDArrayView& source) { if (source.Shape() != Shape()) InvalidArgument("NDArrayView::CopyFrom: The 'source' view's shape must be same as the shape of this NDArrayView"); if (IsReadOnly()) RuntimeError("NDArrayView::CopyFrom: Cannot modify contents of a readonly NDArrayView"); switch (m_dataType) { case DataType::Float: { auto sourceMatrix = source.GetMatrix<float>(); auto destMatrix = GetWritableMatrix<float>(); destMatrix->AssignValuesOf(*sourceMatrix); break; } case DataType::Double: { auto sourceMatrix = source.GetMatrix<double>(); auto destMatrix = GetWritableMatrix<double>(); destMatrix->AssignValuesOf(*sourceMatrix); break; } default: LogicError("Unsupported DataType %s", DataTypeName(m_dataType)); break; } }
sf::ConvexShape ConvexHull(vector<sf::Vector2f> Points) { iter_swap(Points.begin(), min_element(Points.begin(), Points.end(), BottomLeftComp)); AngleCompare AngleComp(Points.front()); sort(Points.begin() + 1, Points.end(), AngleComp); int m = 0; for (unsigned int i = 1; i < Points.size(); i++) { while (CCW(Points[m == 0 ? Points.size() - 1 : m - 1], Points[m], Points[i]) >= 0.f) { if (m > 0) m--; else if (i == Points.size() - 1) break; else i++; } m++; swap(Points[m], Points[i]); } sf::ConvexShape Shape(m + 1); for (unsigned int i = 0; i < Shape.getPointCount(); i++) Shape.setPoint(i, Points[i]); return Shape; }
/** * @internal * @brief Initializes the class so it becomes valid. */ bool ShapeManager::init() { // Init line data m_lines = Shape(LINES); // Init manual objects to allow 3d simple primitives drawing (lines...) int estimatedVertexCount = 10000; m_shapesManualObject = GraphicsManager::getSingleton().getSceneManager().createManualObject("Shapes"); m_shapesManualObject->setDynamic(true); m_shapesManualObject->estimateVertexCount( estimatedVertexCount ); // Set to main render queue m_shapesManualObject->setRenderQueueGroup( Ogre::RENDER_QUEUE_MAIN ); // Attach m_polys sceneNode m_shapesSceneNode = GraphicsManager::getSingleton().getSceneManager().getRootSceneNode()->createChildSceneNode(); m_shapesSceneNode->attachObject(m_shapesManualObject); //m_isShapeClosed = true; // The class is now initialized m_bIsValid = true; return true; }
RoundRectTextButton::RoundRectTextButton(int x, int y, int w, int h, double colorH, String text, std::function<void(void)> handler) :LambdaButton(Shape(RoundRect(x, y, w, h, 5)), handler), rect_m(RoundRect(x, y, w, h, 5)), colorH_m(colorH), text_m(text), width_m(w), height_m(h) {}
void MainWindow::addSnowman() { Document *doc = currentDocument(); if (doc == 0) return; // Create a macro command using beginMacro() and endMacro() doc->undoStack()->beginMacro(tr("Add snowman")); doc->undoStack()->push(new AddShapeCommand(doc, Shape(Shape::Circle, Qt::blue, QRect(51, 30, 97, 95)))); doc->undoStack()->push(new AddShapeCommand(doc, Shape(Shape::Circle, Qt::blue, QRect(27, 123, 150, 133)))); doc->undoStack()->push(new AddShapeCommand(doc, Shape(Shape::Circle, Qt::blue, QRect(11, 253, 188, 146)))); doc->undoStack()->endMacro(); }
Neighborhood::Neighborhood(unsigned int size_x, unsigned int size_y) : size_x(size_x), size_y(size_y){ neighborhood_ = new Shape[size_x * size_y](); for (int filled = 0; filled < size_x*size_y*RATIO_FILLED;) { unsigned int x = mtrand(0, size_x - 1); unsigned int y = mtrand(0, size_y - 1); if (this->get(x, y).getType() == "empty") { this->set(x, y, mtrand(0, 1) ? Shape("triangle") : Shape("square")); filled++; } } }
SoftmaxLoss::SoftmaxLoss(const vector<Tensor*>& inputs, const vector<Tensor*>& outputs, const param_tuple& args) : Operation(inputs, outputs) { CHECK_EQ(outputs_[0]->shape(), Shape({1, 1, 1, 1})); CHECK_EQ(inputs_[1]->shape()[0], inputs_[0]->shape()[0]); CHECK_EQ(inputs_[1]->shape()[2], inputs_[0]->shape()[2]); CHECK_EQ(inputs_[1]->shape()[3], inputs_[0]->shape()[3]); }
int main(int argc, const char *argv[]) try { std::vector<RigidBody> rbs; for (auto const &b : bodysizes) { auto verts = genboxverts(b); auto tris = calchull(verts, 8); rbs.push_back(RigidBody({ Shape(verts, tris) }, float3(0, 0, 0))); } rbscalemass(&rbs[0], 5.0f); // make torso heavier than limb bones rbs[0].position.z = 1.0f; // lift a meter off the ground. DXWin mywin("Joint Drive - powered rag doll model", { 800,600 }); std::vector<Mesh> meshes; for (auto &rb : rbs) { meshes.push_back(MeshSmoothish(rb.shapes[0].verts, rb.shapes[0].tris)); // 1 shape each is known rb.damping = 0.8f; //rb.gravscale = 0; } for (auto &joint : joints) { rbs[joint.b0].ignore.push_back(&rbs[joint.b1]); rbs[joint.b1].ignore.push_back(&rbs[joint.b0]); rbs[joint.b1].position = rbs[joint.b0].pose() * joint.p0 - qrot(rbs[joint.b1].orientation,joint.p1); } WingMesh ground_wm = WingMeshBox({ -5, -5, -2.0f }, { 5, 5, -1.0f }); auto ground = MeshFlatShadeTex(ground_wm.verts, WingMeshTris(ground_wm)); ground.hack = { 0.25f, 0.75f, 0.25f, 1 }; Pose camera = { { 0, -8, 0 }, normalize(float4(0.9f, 0, 0, 1)) }; // where we view the rendered scene from. float time = 0; // our global clock, used to generate the circular animation for upper limbs to follow float torquelimit = 38.0f; // how much torque we let each joint apply each frame while (mywin.WindowUp()) { time += 0.06f; std::vector<LimitAngular> angulars; std::vector<LimitLinear> linears; for (auto const &joint : joints) { Append(linears, ConstrainPositionNailed(&rbs[joint.b0], joint.p0, &rbs[joint.b1], joint.p1)); Append(angulars, ConstrainAngularDrive(&rbs[joint.b0], &rbs[joint.b1], (float4(0, joint.a*cos(time), joint.a*sin(time), sqrt(1.0f - joint.a*joint.a))), torquelimit)); } PhysicsUpdate(Addresses<RigidBody>(rbs), linears, angulars, { &ground_wm.verts }); for (unsigned int i = 0; i < rbs.size(); i++) meshes[i].pose = rbs[i].pose(); mywin.RenderScene(camera, Append(Addresses(meshes), std::vector<Mesh*>({ &ground }))); } return 0; } catch (std::exception e) { MessageBoxA(GetActiveWindow(), e.what(), "FAIL", 0); return -1; }
void TestShape::testConstructor() { this->testInit(__func__); Shape shape = Shape(); if (shape.getPointArray() == NULL) { this->testFailed(); } this->testInterpret(); }
void TestShape::testPointCount() { this->testInit(__func__); Shape shape = Shape(); if (shape.getPointCount() != 0) { this->testFailed(); } this->testInterpret(); }
bool SetPiece::operator==(const SetPiece &other) const { if(Color() == other.Color() && Fill() == other.Fill() && Shape() == other.Shape() && Number() == other.Number()) return true; return false; }