Пример #1
0
    void assemble_cortical(const Geometry& geo, Matrix& mat, const Head2EEGMat& M, const std::string& domain_name, const unsigned gauss_order, double alpha, double beta, const std::string &filename)
    {
        // Following the article: M. Clerc, J. Kybic "Cortical mapping by Laplace–Cauchy transmission using a boundary element method".
        // Assumptions:
        // - domain_name: the domain containing the sources is an innermost domain (defined as the interior of only one interface (called Cortex))
        // - Cortex interface is composed of one mesh only (no shared vertices)

        const Domain& SourceDomain  = geo.domain(domain_name);
        const Interface& Cortex     = SourceDomain.begin()->interface();
        const Mesh& cortex          = Cortex.begin()->mesh();
        
        om_error(SourceDomain.size()==1);
        om_error(Cortex.size()==1);

        // shape of the new matrix:
        unsigned Nl = geo.size()-geo.nb_current_barrier_triangles()-Cortex.nb_vertices()-Cortex.nb_triangles();
        unsigned Nc = geo.size()-geo.nb_current_barrier_triangles();
        std::fstream f(filename.c_str());
        Matrix P;
        if ( !f ) {
            // build the HeadMat:
            // The following is the same as assemble_HM except N_11, D_11 and S_11 are not computed.
            SymMatrix mat_temp(Nc);
            mat_temp.set(0.0);
            double K = 1.0 / (4.0 * M_PI);
            // We iterate over the meshes (or pair of domains) to fill the lower half of the HeadMat (since its symmetry)
            for ( Geometry::const_iterator mit1 = geo.begin(); mit1 != geo.end(); ++mit1) {
                for ( Geometry::const_iterator mit2 = geo.begin(); (mit2 != (mit1+1)); ++mit2) {
                    // if mit1 and mit2 communicate, i.e they are used for the definition of a common domain
                    const int orientation = geo.oriented(*mit1, *mit2); // equals  0, if they don't have any domains in common
                    // equals  1, if they are both oriented toward the same domain
                    // equals -1, if they are not
                    if ( orientation != 0) {
                        double Scoeff =   orientation * geo.sigma_inv(*mit1, *mit2) * K;
                        double Dcoeff = - orientation * geo.indicator(*mit1, *mit2) * K;
                        double Ncoeff;
                        if ( !(mit1->current_barrier() || mit2->current_barrier()) && ( (*mit1 != *mit2)||( *mit1 != cortex) ) ) {
                            // Computing S block first because it's needed for the corresponding N block
                            operatorS(*mit1, *mit2, mat_temp, Scoeff, gauss_order);
                            Ncoeff = geo.sigma(*mit1, *mit2)/geo.sigma_inv(*mit1, *mit2);
                        } else {
                            Ncoeff = orientation * geo.sigma(*mit1, *mit2) * K;
                        }
                        if ( !mit1->current_barrier() && (( (*mit1 != *mit2)||( *mit1 != cortex) )) ) {
                            // Computing D block
                            operatorD(*mit1, *mit2, mat_temp, Dcoeff, gauss_order,false);
                        }
                        if ( ( *mit1 != *mit2 ) && ( !mit2->current_barrier() ) ) {
                            // Computing D* block
                            operatorD(*mit1, *mit2, mat_temp, Dcoeff, gauss_order, true);
                        }
                        // Computing N block
                        if ( (*mit1 != *mit2)||( *mit1 != cortex) ) {
                            operatorN(*mit1, *mit2, mat_temp, Ncoeff, gauss_order);
                        }
                    }
                }
            }
            // Deflate all current barriers as one
            deflat(mat_temp,geo);

            mat = Matrix(Nl, Nc);
            mat.set(0.0);
            // copy mat_temp into mat except the lines for cortex vertices [i_vb_c, i_ve_c] and cortex triangles [i_tb_c, i_te_c].
            unsigned iNl = 0;
            for ( Geometry::const_iterator mit = geo.begin(); mit != geo.end(); ++mit) {
                if ( *mit != cortex ) {
                    for ( Mesh::const_vertex_iterator vit = mit->vertex_begin(); vit != mit->vertex_end(); ++vit) {
                        mat.setlin(iNl, mat_temp.getlin((*vit)->index()));
                        ++iNl;
                    }
                    if ( !mit->current_barrier() ) {
                        for ( Mesh::const_iterator tit = mit->begin(); tit != mit->end(); ++tit) {
                            mat.setlin(iNl, mat_temp.getlin(tit->index()));
                            ++iNl;
                        }
                    }
                }
            }
            // ** Construct P: the null-space projector **
            Matrix W;
            {
                Matrix U, s;
                mat.svd(U, s, W);
            }

            SparseMatrix S(Nc,Nc);
            // we set S to 0 everywhere, except in the last part of the diag:
            for ( unsigned i = Nl; i < Nc; ++i) {
                S(i, i) = 1.0;
            }
            P = (W * S) * W.transpose(); // P is a projector: P^2 = P and mat*P*X = 0
            if ( filename.length() != 0 ) {
                std::cout << "Saving projector P (" << filename << ")." << std::endl;
                P.save(filename);
            }
        } else {
            std::cout << "Loading projector P (" << filename << ")." << std::endl;
            P.load(filename);
        }

        // ** Get the gradient of P1&P0 elements on the meshes **
        Matrix MM(M.transpose() * M);
        SymMatrix RR(Nc, Nc); RR.set(0.);
        for ( Geometry::const_iterator mit = geo.begin(); mit != geo.end(); ++mit) {
            mit->gradient_norm2(RR);
        }

        // ** Choose Regularization parameter **
        SparseMatrix alphas(Nc,Nc); // diagonal matrix
        Matrix Z;
        if ( alpha < 0 ) { // try an automatic method... TODO find better estimation
            double nRR_v = RR.submat(0, geo.nb_vertices(), 0, geo.nb_vertices()).frobenius_norm();
            alphas.set(0.);
            alpha = MM.frobenius_norm() / (1.e3*nRR_v);
            beta  = alpha * 50000.;
            for ( Vertices::const_iterator vit = geo.vertex_begin(); vit != geo.vertex_end(); ++vit) {
                alphas(vit->index(), vit->index()) = alpha;
            }
            for ( Meshes::const_iterator mit = geo.begin(); mit != geo.end(); ++mit) {
                if ( !mit->current_barrier() ) {
                    for ( Mesh::const_iterator tit = mit->begin(); tit != mit->end(); ++tit) {
                        alphas(tit->index(), tit->index()) = beta;
                    }
                }
            }
            std::cout << "AUTOMATIC alphas = " << alpha << "\tbeta = " << beta << std::endl;
        } else {
            for ( Vertices::const_iterator vit = geo.vertex_begin(); vit != geo.vertex_end(); ++vit) {
                alphas(vit->index(), vit->index()) = alpha;
            }
            for ( Meshes::const_iterator mit = geo.begin(); mit != geo.end(); ++mit) {
                if ( !mit->current_barrier() ) {
                    for ( Mesh::const_iterator tit = mit->begin(); tit != mit->end(); ++tit) {
                        alphas(tit->index(), tit->index()) = beta;
                    }
                }
            }
            std::cout << "alphas = " << alpha << "\tbeta = " << beta << std::endl;
        }
        Z = P.transpose() * (MM + alphas*RR) * P;

        // ** PseudoInverse and return **
        // X = P * { (M*P)' * (M*P) + (R*P)' * (R*P) }¡(-1) * (M*P)'m
        // X = P * { P'*M'*M*P + P'*R'*R*P }¡(-1) * P'*M'm
        // X = P * { P'*(MM + a*RR)*P }¡(-1) * P'*M'm
        // X = P * Z¡(-1) * P' * M'm
        Matrix rhs = P.transpose() * M.transpose();
        mat = P * Z.pinverse() * rhs;
    }
Пример #2
0
MeshData * JSONDataParser::_parseMesh(const rapidjson::Value & rawData)
{
    const auto mesh = BaseObject::borrowObject<MeshData>();

    const auto rawVertices = rawData[VERTICES].GetArray();
    const auto rawUVs = rawData[UVS].GetArray();
    const auto rawTriangles = rawData[TRIANGLES].GetArray();

    const auto numVertices = (unsigned)(rawVertices.Size() / 2);
    const auto numTriangles = (unsigned)(rawTriangles.Size() / 3);

    std::vector<Matrix> inverseBindPose(this->_armature->getSortedBones().size(), Matrix());

    mesh->skinned = rawData.HasMember(WEIGHTS) && !rawData[WEIGHTS].GetArray().Empty();
    mesh->uvs.resize(numVertices * 2);
    mesh->vertices.resize(numVertices * 2);
    mesh->vertexIndices.resize(numTriangles * 3);

    if (mesh->skinned)
    {
        mesh->boneIndices.resize(numVertices);
        mesh->weights.resize(numVertices);
        mesh->boneVertices.resize(numVertices);

        if (rawData.HasMember(SLOT_POSE))
        {
            const auto& rawSlotPose = rawData[SLOT_POSE].GetArray();
            mesh->slotPose.a = rawSlotPose[0].GetFloat();
            mesh->slotPose.b = rawSlotPose[1].GetFloat();
            mesh->slotPose.c = rawSlotPose[2].GetFloat();
            mesh->slotPose.d = rawSlotPose[3].GetFloat();
            mesh->slotPose.tx = rawSlotPose[4].GetFloat();
            mesh->slotPose.ty = rawSlotPose[5].GetFloat();
        }

        if (rawData.HasMember(BONE_POSE))
        {
            const auto& rawBonePose = rawData[BONE_POSE].GetArray();
            for (std::size_t i = 0, l = rawBonePose.Size(); i < l; i += 7)
            {
                const auto rawBoneIndex = rawBonePose[i].GetUint();
                auto& boneMatrix = inverseBindPose[rawBoneIndex];
                boneMatrix.a = rawBonePose[i + 1].GetFloat();
                boneMatrix.b = rawBonePose[i + 2].GetFloat();
                boneMatrix.c = rawBonePose[i + 3].GetFloat();
                boneMatrix.d = rawBonePose[i + 4].GetFloat();
                boneMatrix.tx = rawBonePose[i + 5].GetFloat();
                boneMatrix.ty = rawBonePose[i + 6].GetFloat();
                boneMatrix.invert();
            }
        }
    }

    for (std::size_t i = 0, iW = 0, l = rawVertices.Size(); i < l; i += 2)
    {
        const auto iN = i + 1;
        const auto vertexIndex = i / 2;

        auto x = mesh->vertices[i] = rawVertices[i].GetFloat() * this->_armatureScale;
        auto y = mesh->vertices[iN] = rawVertices[iN].GetFloat() * this->_armatureScale;
        mesh->uvs[i] = rawUVs[i].GetFloat();
        mesh->uvs[iN] = rawUVs[iN].GetFloat();

        if (mesh->skinned)
        {
            const auto rawWeights = rawData[WEIGHTS].GetArray();
            const auto numBones = rawWeights[iW].GetUint();
            auto& indices = mesh->boneIndices[vertexIndex];
            auto& weights = mesh->weights[vertexIndex];
            auto& boneVertices = mesh->boneVertices[vertexIndex];
            mesh->slotPose.transformPoint(x, y, _helpPoint);
            x = mesh->vertices[i] = _helpPoint.x;
            y = mesh->vertices[iN] = _helpPoint.y;

            for (std::size_t iB = 0; iB < numBones; ++iB)
            {
                const auto iI = iW + 1 + iB * 2;
                const auto rawBoneIndex = rawWeights[iI].GetUint();
                const auto boneData = this->_rawBones[rawBoneIndex];

                const auto iderator = std::find(mesh->bones.cbegin(), mesh->bones.cend(), boneData);
                std::size_t boneIndex = 0;
                if (iderator == mesh->bones.cend())
                {
                    boneIndex = mesh->bones.size();
                    mesh->bones.push_back(boneData);
                    mesh->inverseBindPose.push_back(inverseBindPose[rawBoneIndex]); // copy
                }
                else
                {
                    boneIndex = std::distance(mesh->bones.cbegin(), iderator);
                }

                mesh->inverseBindPose[boneIndex].transformPoint(x, y, _helpPoint);

                indices.push_back(boneIndex);
                weights.push_back(rawWeights[iI + 1].GetFloat());
                boneVertices.push_back(_helpPoint.x);
                boneVertices.push_back(_helpPoint.y);
            }

            iW += numBones * 2 + 1;
        }
    }

    for (std::size_t i = 0, l = rawTriangles.Size(); i < l; ++i)
    {
        mesh->vertexIndices[i] = rawTriangles[i].GetUint();
    }

    return mesh;
}
Пример #3
0
MeshComponent::MeshComponent(Mesh* mesh, float scale) {
	this->mesh = mesh;
	this->scale = Matrix();
	this->scale *= scale;
}
Пример #4
0
MeshComponent::MeshComponent() {
	this->type = EActorComponent::MESH;
	this->scale = Matrix();
}
Пример #5
0
    void assemble_cortical2(const Geometry& geo, Matrix& mat, const Head2EEGMat& M, const std::string& domain_name, const unsigned gauss_order, double gamma, const std::string &filename)
    {
        // Re-writting of the optimization problem in M. Clerc, J. Kybic "Cortical mapping by Laplace–Cauchy transmission using a boundary element method".
        // with a Lagrangian formulation as in see http://www.math.uh.edu/~rohop/fall_06/Chapter3.pdf eq3.3
        // find argmin(norm(gradient(X)) under constraints: 
        // H * X = 0 and M * X = m
        // let G be the gradient norm matrix, l1, l2 the lagrange parameters
        // 
        // [ G  H' M'] [   X    ]   [ 0 ]
        // | H  0    | |   l1   | = | 0 |
        // [ M     0 ] [   l2   ]   [ m ]
        //
        // {----,----}
        //      K
        // we want a submat of the inverse of K (using blockwise inversion, (TODO maybe iterative solution better ?)).
        // Assumptions:
        // - domain_name: the domain containing the sources is an innermost domain (defined as the interior of only one interface (called Cortex)
        // - Cortex interface is composed of one mesh only (no shared vertices)

        const Domain& SourceDomain = geo.domain(domain_name);
        const Interface& Cortex    = SourceDomain.begin()->interface();
        const Mesh& cortex         = Cortex.begin()->mesh();
        
        om_error(SourceDomain.size()==1);
        om_error(Cortex.size()==1);

        // shape of the new matrix:
        unsigned Nl = geo.size()-geo.nb_current_barrier_triangles()-Cortex.nb_vertices()-Cortex.nb_triangles();
        unsigned Nc = geo.size()-geo.nb_current_barrier_triangles();
        std::fstream f(filename.c_str());
        Matrix H;
        if ( !f ) {
            // build the HeadMat:
            // The following is the same as assemble_HM except N_11, D_11 and S_11 are not computed.
            SymMatrix mat_temp(Nc);
            mat_temp.set(0.0);
            double K = 1.0 / (4.0 * M_PI);
            // We iterate over the meshes (or pair of domains) to fill the lower half of the HeadMat (since its symmetry)
            for ( Geometry::const_iterator mit1 = geo.begin(); mit1 != geo.end(); ++mit1) {
                for ( Geometry::const_iterator mit2 = geo.begin(); (mit2 != (mit1+1)); ++mit2) {
                    // if mit1 and mit2 communicate, i.e they are used for the definition of a common domain
                    const int orientation = geo.oriented(*mit1, *mit2); // equals  0, if they don't have any domains in common
                    // equals  1, if they are both oriented toward the same domain
                    // equals -1, if they are not
                    if ( orientation != 0) {
                        double Scoeff =   orientation * geo.sigma_inv(*mit1, *mit2) * K;
                        double Dcoeff = - orientation * geo.indicator(*mit1, *mit2) * K;
                        double Ncoeff;
                        if ( !(mit1->current_barrier() || mit2->current_barrier()) && ( (*mit1 != *mit2)||( *mit1 != cortex) ) ) {
                            // Computing S block first because it's needed for the corresponding N block
                            operatorS(*mit1, *mit2, mat_temp, Scoeff, gauss_order);
                            Ncoeff = geo.sigma(*mit1, *mit2)/geo.sigma_inv(*mit1, *mit2);
                        } else {
                            Ncoeff = orientation * geo.sigma(*mit1, *mit2) * K;
                        }
                        if ( !mit1->current_barrier() && (( (*mit1 != *mit2)||( *mit1 != cortex) )) ) {
                            // Computing D block
                            operatorD(*mit1, *mit2, mat_temp, Dcoeff, gauss_order);
                        }
                        if ( ( *mit1 != *mit2 ) && ( !mit2->current_barrier() ) ) {
                            // Computing D* block
                            operatorD(*mit1, *mit2, mat_temp, Dcoeff, gauss_order, true);
                        }
                        // Computing N block
                        if ( (*mit1 != *mit2)||( *mit1 != cortex) ) {
                            operatorN(*mit1, *mit2, mat_temp, Ncoeff, gauss_order);
                        }
                    }
                }
            }
            // Deflate all current barriers as one
            deflat(mat_temp,geo);

            H = Matrix(Nl + M.nlin(), Nc);
            H.set(0.0);
            // copy mat_temp into H except the lines for cortex vertices [i_vb_c, i_ve_c] and cortex triangles [i_tb_c, i_te_c].
            unsigned iNl = 0;
            for ( Geometry::const_iterator mit = geo.begin(); mit != geo.end(); ++mit) {
                if ( *mit != cortex ) {
                    for ( Mesh::const_vertex_iterator vit = mit->vertex_begin(); vit != mit->vertex_end(); ++vit) {
                        H.setlin(iNl, mat_temp.getlin((*vit)->index()));
                        ++iNl;
                    }
                    if ( !mit->current_barrier() ) {
                        for ( Mesh::const_iterator tit = mit->begin(); tit != mit->end(); ++tit) {
                            H.setlin(iNl, mat_temp.getlin(tit->index()));
                            ++iNl;
                        }
                    }
                }
            }
            if ( filename.length() != 0 ) {
                std::cout << "Saving matrix H (" << filename << ")." << std::endl;
                H.save(filename);
            }
        } else {
            std::cout << "Loading matrix H (" << filename << ")." << std::endl;
            H.load(filename);
        }

        // concat M to H
        for ( unsigned i = Nl; i < Nl + M.nlin(); ++i) {
            for ( unsigned j = 0; j < Nc; ++j) {
                H(i, j) = M(i-Nl, j);
            }
        }

        // ** Get the gradient of P1&P0 elements on the meshes **
        SymMatrix G(Nc);
        G.set(0.);
        for ( Geometry::const_iterator mit = geo.begin(); mit != geo.end(); ++mit) {
            mit->gradient_norm2(G);
        }
        // multiply by gamma the submat of current gradient norm2
        for ( Meshes::const_iterator mit = geo.begin(); mit != geo.end(); ++mit) {
            if ( !mit->current_barrier() ) {
                for ( Mesh::const_iterator tit1 = mit->begin(); tit1 != mit->end(); ++tit1) {
                    for ( Mesh::const_iterator tit2 = mit->begin(); tit2 != mit->end(); ++tit2) {
                        G(tit1->index(), tit2->index()) *= gamma;
                    }
                }
            }
        }
        std::cout << "gamma = " << gamma << std::endl;
        
        G.invert();
        mat = (G * H.transpose() * (H * G * H.transpose()).inverse()).submat(0, Nc, Nl, M.nlin());
    }
Пример #6
0
Response*
ElasticForceBeamColumn2d::setResponse(const char **argv, int argc, OPS_Stream &output)
{
  Response *theResponse = 0;

  output.tag("ElementOutput");
  output.attr("eleType","ElasticForceBeamColumn2d");
  output.attr("eleTag",this->getTag());
  output.attr("node1",connectedExternalNodes[0]);
  output.attr("node2",connectedExternalNodes[1]);

  // global force - 
  if (strcmp(argv[0],"forces") == 0 || strcmp(argv[0],"force") == 0
      || strcmp(argv[0],"globalForce") == 0 || strcmp(argv[0],"globalForces") == 0) {

    output.tag("ResponseType","Px_1");
    output.tag("ResponseType","Py_1");
    output.tag("ResponseType","Mz_1");
    output.tag("ResponseType","Px_2");
    output.tag("ResponseType","Py_2");
    output.tag("ResponseType","Mz_2");

    theResponse =  new ElementResponse(this, 1, theVector);
  
  
  // local force -
  } else if (strcmp(argv[0],"localForce") == 0 || strcmp(argv[0],"localForces") == 0) {

    output.tag("ResponseType","N_1");
    output.tag("ResponseType","V_1");
    output.tag("ResponseType","M_1");
    output.tag("ResponseType","N_2");
    output.tag("ResponseType","V_2");
    output.tag("ResponseType","M_2");

    theResponse =  new ElementResponse(this, 2, theVector);
  

  // basic force -
  } else if (strcmp(argv[0],"basicForce") == 0 || strcmp(argv[0],"basicForces") == 0) {

    output.tag("ResponseType","N");
    output.tag("ResponseType","M_1");
    output.tag("ResponseType","M_2");

    theResponse =  new ElementResponse(this, 7, Vector(3));

  // chord rotation -
  } else if (strcmp(argv[0],"chordRotation") == 0 || strcmp(argv[0],"chordDeformation") == 0 
	     || strcmp(argv[0],"basicDeformation") == 0) {

    output.tag("ResponseType","eps");
    output.tag("ResponseType","theta_1");
    output.tag("ResponseType","theta_2");

    theResponse =  new ElementResponse(this, 3, Vector(3));
  
  // plastic rotation -
  } else if (strcmp(argv[0],"plasticRotation") == 0 || strcmp(argv[0],"plasticDeformation") == 0) {

    output.tag("ResponseType","epsP");
    output.tag("ResponseType","thetaP_1");
    output.tag("ResponseType","thetaP_2");

    theResponse =  new ElementResponse(this, 4, Vector(3));

  // point of inflection
  } else if (strcmp(argv[0],"inflectionPoint") == 0) {
    
    output.tag("ResponseType","inflectionPoint");

    theResponse =  new ElementResponse(this, 5, 0.0);
  
  // tangent drift
  } else if (strcmp(argv[0],"tangentDrift") == 0) {
    theResponse =  new ElementResponse(this, 6, Vector(2));

  // basic forces
  } else if (strcmp(argv[0],"basicForce") == 0)
    theResponse = new ElementResponse(this, 7, Vector(3));

  else if (strcmp(argv[0],"integrationPoints") == 0)
    theResponse = new ElementResponse(this, 10, Vector(numSections));

  else if (strcmp(argv[0],"integrationWeights") == 0)
    theResponse = new ElementResponse(this, 11, Vector(numSections));

  else if (strcmp(argv[0],"basicStiffness") == 0)
    theResponse = new ElementResponse(this, 12, Matrix(3,3));

  // section response -
  else if (strstr(argv[0],"sectionX") != 0) {
    if (argc > 2) {
      double sectionLoc = atof(argv[1]);

      double xi[maxNumSections];
      double L = crdTransf->getInitialLength();
      beamIntegr->getSectionLocations(numSections, L, xi);
      
      sectionLoc /= L;

      double minDistance = fabs(xi[0]-sectionLoc);
      int sectionNum = 0;
      for (int i = 1; i < numSections; i++) {
	if (fabs(xi[i]-sectionLoc) < minDistance) {
	  minDistance = fabs(xi[i]-sectionLoc);
	  sectionNum = i;
	}
	  }

      output.tag("GaussPointOutput");
      output.attr("number",sectionNum+1);
      output.attr("eta",xi[sectionNum]*L);

      theResponse = sections[sectionNum]->setResponse(&argv[2], argc-2, output);
	}
  }

  // section response -
  else if (strstr(argv[0],"section") != 0) {
    if (argc > 2) {
      int sectionNum = atoi(argv[1]);
      if (sectionNum > 0 && sectionNum <= numSections) {

	double xi[maxNumSections];
	double L = crdTransf->getInitialLength();
	beamIntegr->getSectionLocations(numSections, L, xi);

	output.tag("GaussPointOutput");
	output.attr("number",sectionNum);
	output.attr("eta",xi[sectionNum-1]*L);
	
	theResponse = sections[sectionNum-1]->setResponse(&argv[2], argc-2, output);
	
      }
    }
  }
  
  output.endTag(); // ElementOutput

  return theResponse;
}
Пример #7
0
Matrix Matrix::operator/(float f) const
{
    return Matrix(m_Matrix / f);
}
Пример #8
0
int main (int argc, char **argv)
{
#ifdef HAVE_MPI
  MPI_Init(&argc, &argv);
  Epetra_MpiComm Comm(MPI_COMM_WORLD);
#else
  Epetra_SerialComm Comm;
#endif

  // define some Epetra objects

  int n = Comm.NumProc() * 4;
  Epetra_Map Map(n, 0, Comm);
  Epetra_MultiVector x(Map, 2); x.Random();
  Epetra_MultiVector b(Map, 2); x.Random();
  Epetra_CrsMatrix Matrix(Copy, Map, 0);
  // diagonal matrix
  for (int i = 0; i < Map.NumMyElements(); ++i)
  {
    int ii = Map.GID(i);
    double one = 1.0;
    Matrix.InsertGlobalValues(ii, 1, &one, &ii);
  }
  Matrix.FillComplete();

  Teuchos::ParameterList List;
  List.set("int parameter", 10);
  List.set("double parameter", 10.0);
  List.set("std::string parameter", "std::string");

  // ========================= //
  // Part I: generate XML file //
  // ========================= //
  
  EpetraExt::XMLWriter XMLWriter(Comm, "data.xml");

  std::vector<std::string> Content;
  Content.push_back("This is an example of description");
  Content.push_back("The description is as long as desired,");
  Content.push_back("just put it in a std::vector of strings.");

  XMLWriter.Create("MyProblem");
  XMLWriter.Write("Author", "myself and others");
  XMLWriter.Write("Date", "May 2006");
  XMLWriter.Write("MyMap", Map);
  XMLWriter.Write("MyMatrix", Matrix);
  XMLWriter.Write("MyLHS", x);
  XMLWriter.Write("MyRHS", b);
  XMLWriter.Write("MyContent", Content);
  XMLWriter.Write("MyParameters", List);
  XMLWriter.Close();

  // ================== //
  // Part II: read data //
  // ================== //
  
  EpetraExt::XMLReader XMLReader(Comm, "data.xml");

  Epetra_Map* MyMap;
  Epetra_CrsMatrix* MyMatrix;
  Epetra_MultiVector* MyLHS;
  Epetra_MultiVector* MyRHS;
  Teuchos::ParameterList MyParameters;
  std::vector<std::string> Author;
  std::vector<std::string> Date;
  std::vector<std::string> MyContent;

  XMLReader.Read("Author", Author);
  XMLReader.Read("Date", Date);
  XMLReader.Read("MyMap", MyMap);
  XMLReader.Read("MyMatrix", MyMatrix);
  XMLReader.Read("MyLHS", MyLHS);
  XMLReader.Read("MyRHS", MyRHS);
  XMLReader.Read("MyContent", MyContent);
  XMLReader.Read("MyParameters", MyParameters);

  std::cout << *MyMap;
  std::cout << *MyMatrix;
  std::cout << *MyLHS;
  std::cout << *MyRHS;
  if (Comm.MyPID() == 0)
  {
    int Msize = (int) MyContent.size();
    for (int i = 0; i < Msize; ++i)
      std::cout << MyContent[i] << std::endl;

    std::cout << MyParameters;
    std::cout << "Author = " << Author[0] << std::endl;
    std::cout << "Date   = " << Date[0] << std::endl;
  }

  delete MyMap;
  delete MyMatrix;
  delete MyLHS;
  delete MyRHS;

#ifdef HAVE_MPI
  MPI_Finalize();
#endif

  return(EXIT_SUCCESS);
}
Пример #9
0
void Filter::Kalman(Joint joint, double &dx, double &dy)
{
	Kalmans[Kalman_count++] = joint;
	Kalman_count = Kalman_count % Kalman_limit;
	Kalman_num++;
	if (Kalman_num > Kalman_limit)
	{
		Kalman_num = Kalman_limit;
	}
	if (Kalman_num < Kalman_limit)
	{
		dx = joint.Position.X;
		dy = joint.Position.Y;
		return;
	}
	else
	{
		//X, Y
		int haha;
		haha = 1;
		double x[5], y[5];
		int pos = Kalman_count;
		for (int i = 0; i < 5; i++)
		{
			x[i] = Kalmans[pos].Position.X;
			y[i] = Kalmans[pos].Position.Y;
			pos++;
			pos = pos%Kalman_limit;
		}
		//求系数Ax, Ay
		double Ax[5] = {
			/*a0*/ x[0],
			/*a1*/ 4 * (x[1] - x[0]) - 3 * x[2] + 4 * x[3] / 3 - x[4] / 4,
			/*a2*/ 11 * x[4] / 24 - 7 * x[3] / 3 + 19 * x[2] / 4 - 13 * (x[1] - x[0]) / 3,
			/*a3*/ x[4] / 3 - 7 * x[3] / 6 + x[2] - (x[1] - x[0]) / 2,
			/*a4*/ (x[4] - 4 * x[3] + 6 * x[2] + 4 * (x[1] - x[0])) / 24
		};
		double Ay[5] = {
			/*a0*/ y[0],
			/*a1*/ 4 * (y[1] - y[0]) - 3 * y[2] + 4 * y[3] / 3 - y[4] / 4,
			/*a2*/ 11 * y[4] / 24 - 7 * y[3] / 3 + 19 * y[2] / 4 - 13 * (y[1] - y[0]) / 3,
			/*a3*/ y[4] / 3 - 7 * y[3] / 6 + y[2] - (y[1] - y[0]) / 2,
			/*a4*/ (y[4] - 4 * y[3] + 6 * y[2] + 4 * (y[1] - y[0])) / 24
		};

		//求转换矩阵Fx, Fy
		Matrix Fx(4, 4,
							 new double[16]{
			  1, 1, -0.5, (Ax[1] + 6 * Ax[3] - 4 * Ax[4]) / (24 * Ax[4]),
				0, 1, 1, 0.5,
				0, 0, 1, 1,
				0, 0, 0, 1});
		Matrix Fy(4, 4,
							 new double[16]{
			1, 1, -0.5, (Ay[1] + 6 * Ay[3] - 4 * Ay[4]) / (24 * Ay[4]),
				0, 1, 1, 0.5,
				0, 0, 1, 1,
				0, 0, 0, 1});
		//求ε(t|t-1)
		Matrix ex(4, 4), ey(4, 4);
		ex = Fx*Kalman_ex*(!Fx);
		ey = Fy*Kalman_ey*(!Fy);
		//cout << "ex" << endl; ex.print();
		//cout << "ey" << endl; ey.print();

		Matrix Bx(4, 1), By(4, 1);
		//cout << "!Kalman_C" << endl; (!Kalman_C).print();
		//cout << "Kalman_vx" << endl; Kalman_vx.print();
		//cout << "Kalman_C" << endl; Kalman_C.print();
		//cout << "!Kalman_C" << endl; (!Kalman_C).print();
		//cout << "Kalman_C*ex" << endl; (Kalman_C*ex).print();
		//cout << "Kalman_C*ex*(!Kalman_C)" << endl; (Kalman_C*ex*(!Kalman_C)).print();
		//cout << "(~(Kalman_vx + Kalman_C*ex*(!Kalman_C)))" << endl;
		//(~(Kalman_vx + Kalman_C*ex*(!Kalman_C))).print();
		Bx = ex*(!Kalman_C)*(~(Kalman_vx + Kalman_C*ex*(!Kalman_C)));
		//cout << "Bx" << endl; Bx.print();
		By = ey*(!Kalman_C)*(~(Kalman_vy + Kalman_C*ey*(!Kalman_C)));
		
		Matrix I4(4, 4);
		I4.SetIdentity();
		Kalman_Sx = (I4 - Bx*Kalman_C)*(Fx*Kalman_Sx + Kalman_Gx) +
			Bx*Matrix(1, 1, new double[1] {joint.Position.X});
		//cout << "Kalman_Sx" << endl; Kalman_Sx.print();
		Kalman_Sy = (I4 - By*Kalman_C)*(Fy*Kalman_Sy + Kalman_Gy) +
			By*Matrix(1, 1, new double[1] {joint.Position.Y});

		Kalman_ex = ex - Bx*Kalman_C*ex;
		Kalman_ey = ey - By*Kalman_C*ey;

		dx = Kalman_Sx.at(0, 0);
		dy = Kalman_Sy.at(0, 0);
	}
}
inline void  GraphicsSystem::MatrixPush()
{
    MatrixStack << Matrix(MatrixStack[curMatrix]);
    ++curMatrix;
}
Пример #11
0
//==========================================================================
int Ifpack_ICT::Compute() 
{
  if (!IsInitialized()) 
    IFPACK_CHK_ERR(Initialize());

  Time_.ResetStartTime();
  IsComputed_ = false;

  NumMyRows_ = A_.NumMyRows();
  int Length = A_.MaxNumEntries();
  vector<int>    RowIndices(Length);
  vector<double> RowValues(Length);

  bool distributed = (Comm().NumProc() > 1)?true:false;

  if (distributed)
  {
    SerialComm_ = Teuchos::rcp(new Epetra_SerialComm);
    SerialMap_ = Teuchos::rcp(new Epetra_Map(NumMyRows_, 0, *SerialComm_));
    assert (SerialComm_.get() != 0);
    assert (SerialMap_.get() != 0);
  }
  else
    SerialMap_ = Teuchos::rcp(const_cast<Epetra_Map*>(&A_.RowMatrixRowMap()), false);

  int RowNnz;
#ifdef IFPACK_FLOPCOUNTERS
  double flops = 0.0;
#endif

  H_ = Teuchos::rcp(new Epetra_CrsMatrix(Copy,*SerialMap_,0));
  if (H_.get() == 0)
    IFPACK_CHK_ERR(-5); // memory allocation error

  // get A(0,0) element and insert it (after sqrt)
  IFPACK_CHK_ERR(A_.ExtractMyRowCopy(0,Length,RowNnz,
                                     &RowValues[0],&RowIndices[0]));

  // skip off-processor elements
  if (distributed)
  {
    int count = 0;
    for (int i = 0 ;i < RowNnz ; ++i) 
    {
      if (RowIndices[i] < NumMyRows_){
        RowIndices[count] = RowIndices[i];
        RowValues[count] = RowValues[i];
        ++count;
      }
      else
        continue;
    }
    RowNnz = count;
  }

  // modify diagonal
  double diag_val = 0.0;
  for (int i = 0 ;i < RowNnz ; ++i) {
    if (RowIndices[i] == 0) {
      double& v = RowValues[i];
      diag_val = AbsoluteThreshold() * EPETRA_SGN(v) +
        RelativeThreshold() * v;
      break;
    }
  }

  diag_val = sqrt(diag_val);
  int diag_idx = 0;
  EPETRA_CHK_ERR(H_->InsertGlobalValues(0,1,&diag_val, &diag_idx));

  int oldSize = RowNnz;

  // The 10 is just a small constant to limit collisons as the actual keys
  // we store are the indices and not integers
  // [0..A_.MaxNumEntries()*LevelofFill()].
  Ifpack_HashTable Hash( 10 * A_.MaxNumEntries() * LevelOfFill(), 1);

  // start factorization for line 1
  for (int row_i = 1 ; row_i < NumMyRows_ ; ++row_i) {

    // get row `row_i' of the matrix
    IFPACK_CHK_ERR(A_.ExtractMyRowCopy(row_i,Length,RowNnz,
                                       &RowValues[0],&RowIndices[0]));

    // skip off-processor elements
    if (distributed)
    {
      int count = 0;
      for (int i = 0 ;i < RowNnz ; ++i) 
      {
        if (RowIndices[i] < NumMyRows_){
          RowIndices[count] = RowIndices[i];
          RowValues[count] = RowValues[i];
          ++count;
        }
        else
          continue;
      }
      RowNnz = count;
    }

    // number of nonzeros in this row are defined as the nonzeros
    // of the matrix, plus the level of fill 
    int LOF = (int)(LevelOfFill() * RowNnz);
    if (LOF == 0) LOF = 1;

    // convert line `row_i' into hash for fast access
    Hash.reset();

    double h_ii = 0.0;
    for (int i = 0 ; i < RowNnz ; ++i) {
      if (RowIndices[i] == row_i) {
        double& v = RowValues[i];
        h_ii = AbsoluteThreshold() * EPETRA_SGN(v) + RelativeThreshold() * v;
      }
      else if (RowIndices[i] < row_i)
      {
        Hash.set(RowIndices[i], RowValues[i], true);
      }
    }
      
    // form element (row_i, col_j)
    // I start from the first row that has a nonzero column
    // index in row_i.
    for (int col_j = RowIndices[0] ; col_j < row_i ; ++col_j) {

      double h_ij = 0.0, h_jj = 0.0;
      // note: get() returns 0.0 if col_j is not found
      h_ij = Hash.get(col_j);

      // get pointers to row `col_j'
      int* ColIndices;
      double* ColValues;
      int ColNnz;
      H_->ExtractGlobalRowView(col_j, ColNnz, ColValues, ColIndices);

      for (int k = 0 ; k < ColNnz ; ++k) {
        int col_k = ColIndices[k];

        if (col_k == col_j)
          h_jj = ColValues[k];
        else {
          double xxx = Hash.get(col_k);
          if (xxx != 0.0)
          {
            h_ij -= ColValues[k] * xxx;
#ifdef IFPACK_FLOPCOUNTERS
            flops += 2.0;
#endif
          }
        }
      }

      h_ij /= h_jj;

      if (IFPACK_ABS(h_ij) > DropTolerance_)
      {
        Hash.set(col_j, h_ij);
      }
    
#ifdef IFPACK_FLOPCOUNTERS
      // only approx
      ComputeFlops_ += 2.0 * flops + 1.0;
#endif
    }

    int size = Hash.getNumEntries();

    vector<double> AbsRow(size);
    int count = 0;
    
    // +1 because I use the extra position for diagonal in insert
    vector<int> keys(size + 1);
    vector<double> values(size + 1);

    Hash.arrayify(&keys[0], &values[0]);

    for (int i = 0 ; i < size ; ++i)
    {
      AbsRow[i] = IFPACK_ABS(values[i]);
    }
    count = size;

    double cutoff = 0.0;
    if (count > LOF) {
      nth_element(AbsRow.begin(), AbsRow.begin() + LOF, AbsRow.begin() + count, 
                  greater<double>());
      cutoff = AbsRow[LOF];
    }

    for (int i = 0 ; i < size ; ++i)
    {
      h_ii -= values[i] * values[i];
    }

    if (h_ii < 0.0) h_ii = 1e-12;;

    h_ii = sqrt(h_ii);

#ifdef IFPACK_FLOPCOUNTERS
    // only approx, + 1 == sqrt
    ComputeFlops_ += 2 * size + 1;
#endif

    double DiscardedElements = 0.0;

    count = 0;
    for (int i = 0 ; i < size ; ++i)    
    { 
      if (IFPACK_ABS(values[i]) > cutoff)
      {
        values[count] = values[i];
        keys[count] = keys[i];
        ++count;
      }
      else  
        DiscardedElements += values[i];
    }

    if (RelaxValue() != 0.0) {
      DiscardedElements *= RelaxValue();
      h_ii += DiscardedElements;
    }

    values[count] = h_ii;
    keys[count] = row_i;
    ++count;

    H_->InsertGlobalValues(row_i, count, &(values[0]), (int*)&(keys[0]));

    oldSize = size;
  }

  IFPACK_CHK_ERR(H_->FillComplete());

#if 0
  // to check the complete factorization
  Epetra_Vector LHS(Matrix().RowMatrixRowMap());
  Epetra_Vector RHS1(Matrix().RowMatrixRowMap());
  Epetra_Vector RHS2(Matrix().RowMatrixRowMap());
  Epetra_Vector RHS3(Matrix().RowMatrixRowMap());
  LHS.Random();

  Matrix().Multiply(false,LHS,RHS1);
  H_->Multiply(true,LHS,RHS2);
  H_->Multiply(false,RHS2,RHS3);

  RHS1.Update(-1.0, RHS3, 1.0);
  cout << endl;
  cout << RHS1;
#endif
  int MyNonzeros = H_->NumGlobalNonzeros();
  Comm().SumAll(&MyNonzeros, &GlobalNonzeros_, 1);

  IsComputed_ = true;
#ifdef IFPACK_FLOPCOUNTERS
  double TotalFlops; // sum across all the processors
  A_.Comm().SumAll(&flops, &TotalFlops, 1);
  ComputeFlops_ += TotalFlops;
#endif
  ++NumCompute_;
  ComputeTime_ += Time_.ElapsedTime();

  return(0);

}
Пример #12
0
    return *this;
}
Matrix& Matrix::operator=(const NxMat34& mat)
{
    mat.getColumnMajor44(m_Matrix);
    return *this;
}
Matrix& Matrix::operator=(const D3DXMATRIX& mat)
{
    m_Matrix = mat;
    return *this;
}

//Static
const Matrix Matrix::Identity = Matrix(1, 0, 0, 0,
                                       0, 1, 0, 0,
                                       0, 0, 1, 0,
                                       0, 0, 0, 1);


Matrix::~Matrix(void)
{
}

// casting operators
Matrix::operator float*()
{
    return (float*)m_Matrix;
}
Matrix::operator const float*() const
{
    return (const float*)m_Matrix;
Пример #13
0
Matrix Matrix::operator*(float f) const
{
    return Matrix(m_Matrix * f);
}
Пример #14
0
//==============================================================================
int Ifpack_PointRelaxation::
ApplyInverseSGS_RowMatrix(const Epetra_MultiVector& X, Epetra_MultiVector& Y) const
{
  int NumVectors = X.NumVectors();
  int Length = Matrix().MaxNumEntries();
  vector<int> Indices(Length);
  vector<double> Values(Length);

  Teuchos::RefCountPtr< Epetra_MultiVector > Y2;
  if (IsParallel_) {
    Y2 = Teuchos::rcp( new Epetra_MultiVector(Importer_->TargetMap(), NumVectors) );
  }
  else
    Y2 = Teuchos::rcp( &Y, false );

  double** y_ptr, ** y2_ptr, ** x_ptr, *d_ptr;
  X.ExtractView(&x_ptr);
  Y.ExtractView(&y_ptr);
  Y2->ExtractView(&y2_ptr);
  Diagonal_->ExtractView(&d_ptr);
  
  for (int iter = 0 ; iter < NumSweeps_ ; ++iter) {
    
    // only one data exchange per sweep
    if (IsParallel_)
      IFPACK_CHK_ERR(Y2->Import(Y,*Importer_,Insert));

    for (int i = 0 ; i < NumMyRows_ ; ++i) {

      int NumEntries;
      int col;
      double diag = d_ptr[i];

      IFPACK_CHK_ERR(Matrix_->ExtractMyRowCopy(i, Length,NumEntries,
                                               &Values[0], &Indices[0]));

      for (int m = 0 ; m < NumVectors ; ++m) {

        double dtemp = 0.0;

        for (int k = 0 ; k < NumEntries ; ++k) {

          col = Indices[k];
          dtemp += Values[k] * y2_ptr[m][col];
        }

        y2_ptr[m][i] += DampingFactor_ * (x_ptr[m][i] - dtemp) * diag;
      }
    }

    for (int i = NumMyRows_  - 1 ; i > -1 ; --i) {

      int NumEntries;
      int col;
      double diag = d_ptr[i];

      IFPACK_CHK_ERR(Matrix_->ExtractMyRowCopy(i, Length,NumEntries,
                                               &Values[0], &Indices[0]));

      for (int m = 0 ; m < NumVectors ; ++m) {

        double dtemp = 0.0;
        for (int k = 0 ; k < NumEntries ; ++k) {

          col = Indices[k];
          dtemp += Values[k] * y2_ptr[m][col];
        }

        y2_ptr[m][i] += DampingFactor_ * (x_ptr[m][i] - dtemp) * diag;

      }
    }

    if (IsParallel_)
      for (int m = 0 ; m < NumVectors ; ++m) 
        for (int i = 0 ; i < NumMyRows_ ; ++i)
          y_ptr[m][i] = y2_ptr[m][i];
  }

  ApplyInverseFlops_ += NumVectors * (8 * NumGlobalRows_ + 4 * NumGlobalNonzeros_);
  return(0);
}
Пример #15
0
returnValue CondensingExport::setupEvaluation( )
{
	x.setup( "x",        (getN()+1), getNX(), REAL,ACADO_VARIABLES );
	u.setup( "u",        getN(), getNU(),     REAL,ACADO_VARIABLES );
	p.setup( "p",        1, getNP(),          REAL,ACADO_VARIABLES );

	state.setup   ( "state",    1,getNX()*(getNX()+getNU()+1) + getNU() +getNP(), REAL,ACADO_WORKSPACE );

	if ( isInitialStateFixed( ) == BT_FALSE )
	{
		x0Ref.setup ( "x0Ref",  1, getNX(), REAL,ACADO_VARIABLES );
		x0Ref2.setup( "x0Ref2", 1, getNX(), REAL,ACADO_VARIABLES );
	}

	E.setup  ( "E",   getN()*getNX(), getN()*getNU(), REAL,ACADO_WORKSPACE );
	lbA.setup( "lbA", getNumStateBounds(), 1, REAL,ACADO_WORKSPACE );
	ubA.setup( "ubA", getNumStateBounds(), 1, REAL,ACADO_WORKSPACE );

	Matrix zeroXU = zeros( getNX(),getNU() );
	Matrix idX    = eye( getNX() );

	//
	// setupQP
	//
	setupQP.setup( "setupQP" );
    
	if ( performsSingleShooting() == BT_TRUE )
		setupQP.addStatement( state.getCols( 0,getNX() ) == x.getRow(0) );

	// TODO: this part should be preinitialized. More specifically, E & QE matrices should be preinitializes to 0.
	uint run1, run2;
	for( run1 = 0; run1 < getN()-1; run1++ )
		for( run2 = 1+run1; run2 < getN(); run2++ )
			setupQP.addStatement( E.getSubMatrix( run1*getNX(),(run1+1)*getNX(), run2*getNU(),(run2+1)*getNU() ) == zeroXU );


    // Write state bounds to the file
	// TODO: Since the bounds are fixed in this case, they should be preinitialized
	if( getNumStateBounds( ) > 0 )
	{
		Vector xLowerBounds(nxBounds), xUpperBounds(nxBounds);
		for( run1 = 0; run1 < nxBounds; run1++ )
		{
			xLowerBounds(run1) = xBounds.getLowerBound( xBoundsIdx[run1]/getNX(),xBoundsIdx[run1]%getNX() );
			xUpperBounds(run1) = xBounds.getUpperBound( xBoundsIdx[run1]/getNX(),xBoundsIdx[run1]%getNX() );
		}
		
		setupQP.addStatement( lbA == xLowerBounds );
		setupQP.addStatement( ubA == xUpperBounds );
	}
	setupQP.addLinebreak( );


	if ( isInitialStateFixed( ) == BT_FALSE )
	{
		setupQP.addStatement( Dx0  == x.getRow(0) - x0Ref );
		setupQP.addStatement( Dx0b == x.getRow(0) - x0Ref2 );
		setupQP.addLinebreak( );
	}
	
	
	// compute QQF if necessary
	if ( QQF.isGiven( ) == BT_FALSE )
		setupQP.addStatement( QQF == Q + QF );

	ExportIndex reset( String("reset") );
	setupQP.addIndex( reset );
	setupQP.addStatement( reset == 1 );

	ExportIndex run( String("run1") );
	ExportForLoop loop( run, 0,getN() );
	
	setupQP.addIndex( run );

	if ( performsSingleShooting() == BT_FALSE ) {
		loop.addStatement( reset == 1 );
		loop.addStatement( state.getCols( 0,getNX() ) == x.getRow( run ) );
	}
	
	// no free parameters implemented yet!
	uint uIdx = getNX() * ( 1+getNX() );
	uint pIdx = getNX() * ( 1+getNX()+getNU() );
	uIdx = pIdx;
	pIdx = pIdx + getNU();
	loop.addStatement( state.getCols( uIdx,pIdx ) == u.getRow( run ) );
	loop.addStatement( state.getCols( pIdx,pIdx+getNP() ) == p );
	loop.addLinebreak( );
	
	if ( integrator->equidistantControlGrid() )
	{
		loop.addFunctionCall( "integrate", state, reset.makeArgument() );
	}
	else
	{
		loop.addFunctionCall( "integrate", state, reset.makeArgument(), run.makeArgument() );
	}
	if( performsSingleShooting() ) loop.addStatement( reset == 0 );
	
	if ( performsSingleShooting() == BT_TRUE )
	{
		loop.addStatement( x.getRow( run+1 ) == state.getCols( 0,getNX() ) );
	}
	else
	{
		//
		// Multiple shooting
		// TODO: Check the sign here
		//
		loop.addStatement( residuum.getRow( run ) == state.getCols( 0,getNX() ) - x.getRow( run+1 ) );
	}
	
	loop.addLinebreak( );
	
	loop.addFunctionCall( condense1, run.makeArgument(),state );

    setupQP.addStatement( loop );
	setupQP.addLinebreak( );
		
	setupQP.addFunctionCall( condense2 );

	////////////////////////////////////////////////////////////////////////////
	//
	// Get objective value
	//
	////////////////////////////////////////////////////////////////////////////

	ExportVariable tmp("tmp", 1, 1, REAL, ACADO_LOCAL, BT_TRUE);
	ExportVariable tmpDx("tmpDx", 1, getNX(), REAL, ACADO_LOCAL );
	ExportVariable tmpDu("tmpDu", 1, getNU(), REAL, ACADO_LOCAL );

	getObjectiveValue.setup( "getObjectiveValue" );
	getObjectiveValue.setReturnValue( tmp );

	getObjectiveValue.addVariable( tmpDx );
	getObjectiveValue.addVariable( tmpDu );

	getObjectiveValue.addStatement( tmp == 0.0 );
	getObjectiveValue.addLinebreak( );

	for (unsigned i = 0; i < getN(); ++i)
	{
		getObjectiveValue.addStatement( tmpDx == Dx.getRow( i ) * Q );
		getObjectiveValue.addStatement( tmp += Dx.getRow( i ) * tmpDx.getTranspose() );
	}
	getObjectiveValue.addLinebreak( );

	for (unsigned i = 0; i < getN(); ++i)
	{
		getObjectiveValue.addStatement( tmpDu == Du.getRow( i ) * R );
		getObjectiveValue.addStatement( tmp += Du.getRow( i ) * tmpDu.getTranspose() );
	}
	getObjectiveValue.addLinebreak( );

	getObjectiveValue.addStatement( tmp == tmp * Matrix( 0.5 ) );

	return SUCCESSFUL_RETURN;
}
Пример #16
0
//==============================================================================
int Ifpack_PointRelaxation::Compute()
{
  int ierr = 0;
  if (!IsInitialized())
    IFPACK_CHK_ERR(Initialize());

  Time_->ResetStartTime();

  // reset values
  IsComputed_ = false;
  Condest_ = -1.0;

  if (NumSweeps_ == 0) ierr = 1; // Warning: no sweeps performed.
  if (NumSweeps_ < 0)
    IFPACK_CHK_ERR(-2); // at least one application
  
  Diagonal_ = Teuchos::rcp( new Epetra_Vector(Matrix().RowMatrixRowMap()) );

  if (Diagonal_ == Teuchos::null)
    IFPACK_CHK_ERR(-5);

  IFPACK_CHK_ERR(Matrix().ExtractDiagonalCopy(*Diagonal_));

  // check diagonal elements, store the inverses, and verify that
  // no zeros are around. If an element is zero, then by default
  // its inverse is zero as well (that is, the row is ignored).
  for (int i = 0 ; i < NumMyRows_ ; ++i) {
    double& diag = (*Diagonal_)[i];
    if (IFPACK_ABS(diag) < MinDiagonalValue_)
      diag = MinDiagonalValue_;
    if (diag != 0.0)
      diag = 1.0 / diag;
  }
  ComputeFlops_ += NumMyRows_;

#if 0
  // some methods require the inverse of the diagonal, compute it
  // now and store it in `Diagonal_'
  if ((PrecType_ == IFPACK_JACOBI) || (PrecType_ == IFPACK_GS)) {
    Diagonal_->Reciprocal(*Diagonal_);
    // update flops
    ComputeFlops_ += NumMyRows_;
  }
#endif

  // We need to import data from external processors. Here I create an
  // Epetra_Import object because I cannot assume that Matrix_ has one.
  // This is a bit of waste of resources (but the code is more robust).
  // Note that I am doing some strange stuff to set the components of Y
  // from Y2 (to save some time).
  //
  if (IsParallel_ && ((PrecType_ == IFPACK_GS) || (PrecType_ == IFPACK_SGS))) {
    Importer_ = Teuchos::rcp( new Epetra_Import(Matrix().RowMatrixColMap(),
                                  Matrix().RowMatrixRowMap()) );
    if (Importer_ == Teuchos::null) IFPACK_CHK_ERR(-5);
  }

  ++NumCompute_;
  ComputeTime_ += Time_->ElapsedTime();
  IsComputed_ = true;

  IFPACK_CHK_ERR(ierr);
  return(0);
}
Пример #17
0
//==============================================================================
int Ifpack_PointRelaxation::
ApplyInverseGS_RowMatrix(const Epetra_MultiVector& X, Epetra_MultiVector& Y) const
{
  int NumVectors = X.NumVectors();

  int Length = Matrix().MaxNumEntries();
  vector<int> Indices(Length);
  vector<double> Values(Length);

  Teuchos::RefCountPtr< Epetra_MultiVector > Y2;
  if (IsParallel_)
    Y2 = Teuchos::rcp( new Epetra_MultiVector(Importer_->TargetMap(), NumVectors) );
  else
    Y2 = Teuchos::rcp( &Y, false );

  // extract views (for nicer and faster code)
  double** y_ptr, ** y2_ptr, ** x_ptr, *d_ptr;
  X.ExtractView(&x_ptr);
  Y.ExtractView(&y_ptr);
  Y2->ExtractView(&y2_ptr);
  Diagonal_->ExtractView(&d_ptr);

  for (int j = 0; j < NumSweeps_ ; j++) {

    // data exchange is here, once per sweep
    if (IsParallel_)
      IFPACK_CHK_ERR(Y2->Import(Y,*Importer_,Insert));

    // FIXME: do I really need this code below?
    if (NumVectors == 1) {

      double* y0_ptr = y_ptr[0];
      double* y20_ptr = y2_ptr[0];
      double* x0_ptr = x_ptr[0];

      if(!DoBackwardGS_){      
        /* Forward Mode */
        for (int i = 0 ; i < NumMyRows_ ; ++i) {

          int NumEntries;
          int col;
          IFPACK_CHK_ERR(Matrix_->ExtractMyRowCopy(i, Length,NumEntries,
                                                   &Values[0], &Indices[0]));
          
          double dtemp = 0.0;
          for (int k = 0 ; k < NumEntries ; ++k) {
            
            col = Indices[k];
            dtemp += Values[k] * y20_ptr[col];
          }
          
          y20_ptr[i] += DampingFactor_ * d_ptr[i] * (x0_ptr[i] - dtemp);
        }
      }
      else {
        /* Backward Mode */
        for (int i = NumMyRows_  - 1 ; i > -1 ; --i) {

          int NumEntries;
          int col;
          IFPACK_CHK_ERR(Matrix_->ExtractMyRowCopy(i, Length,NumEntries,
                                                   &Values[0], &Indices[0]));
          double dtemp = 0.0;
          for (int k = 0 ; k < NumEntries ; ++k) {

            col = Indices[k];
            dtemp += Values[k] * y20_ptr[i];
          }
          
          y20_ptr[i] += DampingFactor_ * d_ptr[i] * (x0_ptr[i] - dtemp);
        }
      }
      
      // using Export() sounded quite expensive
      if (IsParallel_)
        for (int i = 0 ; i < NumMyRows_ ; ++i)
          y0_ptr[i] = y20_ptr[i];

    }
    else {
      if(!DoBackwardGS_){      
        /* Forward Mode */
        for (int i = 0 ; i < NumMyRows_ ; ++i) {
          
          int NumEntries;
          int col;
          IFPACK_CHK_ERR(Matrix_->ExtractMyRowCopy(i, Length,NumEntries,
                                                   &Values[0], &Indices[0]));
          
          for (int m = 0 ; m < NumVectors ; ++m) {
            
            double dtemp = 0.0;
            for (int k = 0 ; k < NumEntries ; ++k) {
              
              col = Indices[k];
              dtemp += Values[k] * y2_ptr[m][col];
            }
            
            y2_ptr[m][i] += DampingFactor_ * d_ptr[i] * (x_ptr[m][i] - dtemp);
          }
        }
      }
      else {
        /* Backward Mode */
        for (int i = NumMyRows_  - 1 ; i > -1 ; --i) {
          int NumEntries;
          int col;
          IFPACK_CHK_ERR(Matrix_->ExtractMyRowCopy(i, Length,NumEntries,
                                                   &Values[0], &Indices[0]));

          for (int m = 0 ; m < NumVectors ; ++m) {
            
            double dtemp = 0.0;
            for (int k = 0 ; k < NumEntries ; ++k) {

              col = Indices[k];
              dtemp += Values[k] * y2_ptr[m][col];
            }

            y2_ptr[m][i] += DampingFactor_ * d_ptr[i] * (x_ptr[m][i] - dtemp);

          }
        }
      }

      // using Export() sounded quite expensive   
      if (IsParallel_)
        for (int m = 0 ; m < NumVectors ; ++m) 
          for (int i = 0 ; i < NumMyRows_ ; ++i)
            y_ptr[m][i] = y2_ptr[m][i];
      
    }
  }

  ApplyInverseFlops_ += NumVectors * (4 * NumGlobalRows_ + 2 * NumGlobalNonzeros_);

  return(0);
} //ApplyInverseGS_RowMatrix()
Пример #18
0
//==========================================================================
int Ifpack_SPARSKIT::Compute() 
{
  if (!IsInitialized()) 
    IFPACK_CHK_ERR(Initialize());

  IsComputed_ = false;

  // convert the matrix into SPARSKIT format. The matrix is then
  // free'd after method Compute() returns.

  // convert the matrix into CSR format. Note that nnz is an over-estimate,
  // since it contains the nonzeros corresponding to external nodes as well.
  int n   = Matrix().NumMyRows();
  int nnz = Matrix().NumMyNonzeros();

  vector<double> a(nnz);
  vector<int>    ja(nnz);
  vector<int>    ia(n + 1);

  const int MaxNumEntries = Matrix().MaxNumEntries();

  vector<double> Values(MaxNumEntries);
  vector<int>    Indices(MaxNumEntries);

  int count = 0;

  ia[0] = 1;
  for (int i = 0 ; i < n ; ++i)
  {
    int NumEntries;
    int NumMyEntries = 0;
    Matrix().ExtractMyRowCopy(i, MaxNumEntries, NumEntries, &Values[0], 
                              &Indices[0]);

    // NOTE: There might be some issues here with the ILU(0) if the column indices aren't sorted.
    // The other factorizations are probably OK.

    for (int j = 0 ; j < NumEntries ; ++j)
    {
      if (Indices[j] < n) // skip non-local columns
      {
        a[count]  = Values[j];
        ja[count] = Indices[j] + 1; // SPARSKIT is FORTRAN
        ++count;
        ++NumMyEntries;
      }
    }
    ia[i + 1] = ia[i] + NumMyEntries;
  }

  if (mbloc_ == -1) mbloc_ = n;

  int iwk;

  if (Type_ == "ILUT" || Type_ == "ILUTP" || Type_ == "ILUD" ||
      Type_ == "ILUDP")
    iwk = nnz + 2 * lfil_ * n;
  else if (Type_ == "ILUK")
    iwk = (2 * lfil_ + 1) * nnz + 1;
  else if (Type_ == "ILU0")
    iwk = nnz+2;

  int ierr = 0;

  alu_.resize(iwk);
  jlu_.resize(iwk);
  ju_.resize(n + 1);

  vector<int>    jw(n + 1);
  vector<double> w(n + 1);

  if (Type_ == "ILUT")
  {
    jw.resize(2 * n);
    F77_ILUT(&n, &a[0], &ja[0], &ia[0], &lfil_, &droptol_,
             &alu_[0], &jlu_[0], &ju_[0], &iwk, &w[0], &jw[0], &ierr);
  }
  else if (Type_ == "ILUD")
  {
    jw.resize(2 * n);
    F77_ILUD(&n, &a[0], &ja[0], &ia[0], &alph_, &tol_,
             &alu_[0], &jlu_[0], &ju_[0], &iwk, &w[0], &jw[0], &ierr);
  }
  else if (Type_ == "ILUTP")
  {
    jw.resize(2 * n);
    iperm_.resize(2 * n);
    F77_ILUTP(&n, &a[0], &ja[0], &ia[0], &lfil_, &droptol_, &permtol_, 
              &mbloc_, &alu_[0], &jlu_[0], &ju_[0], &iwk, &w[0], &jw[0],
              &iperm_[0], &ierr);
    for (int i = 0 ; i < n ; ++i)
      iperm_[i]--;
  }
  else if (Type_ == "ILUDP")
  {
    jw.resize(2 * n);
    iperm_.resize(2 * n);
    F77_ILUDP(&n, &a[0], &ja[0], &ia[0], &alph_, &droptol_, &permtol_, 
              &mbloc_, &alu_[0], &jlu_[0], &ju_[0], &n, &w[0], &jw[0],
              &iperm_[0], &ierr);
    for (int i = 0 ; i < n ; ++i)
      iperm_[i]--;
  }
  else if (Type_ == "ILUK")
  {
    vector<int> levs(iwk);
    jw.resize(3 * n);
    F77_ILUK(&n, &a[0], &ja[0], &ia[0], &lfil_, 
             &alu_[0], &jlu_[0], &ju_[0], &levs[0], &iwk, &w[0], &jw[0], &ierr);
  }
  else if (Type_ == "ILU0")
  {
    // here w is only of size n
    jw.resize(2 * n);
    F77_ILU0(&n, &a[0], &ja[0], &ia[0], 
             &alu_[0], &jlu_[0], &ju_[0], &jw[0], &ierr);
  }
  IFPACK_CHK_ERR(ierr);

  IsComputed_ = true;
  return(0);
}
Пример #19
0
    FwdPeriodAdapter::FwdPeriodAdapter(
                               const ext::shared_ptr<MarketModel>& largeModel,
                               Size period,
                               Size offset,
                               const std::vector<Spread>& newDisplacements)
    :
      numberOfFactors_(largeModel->numberOfFactors()),
          numberOfRates_((largeModel->numberOfRates()-offset) / (period > 0 ? period : 1) ),
      numberOfSteps_(largeModel->numberOfSteps()),
      pseudoRoots_(numberOfSteps_, Matrix(numberOfRates_,
                                          numberOfFactors_)),
                                          displacements_(newDisplacements)
    {
        QL_REQUIRE( period >0, "period must  be greater than zero in fwdperiodadapter");
        QL_REQUIRE(period > offset, "period must be greater than offset in fwdperiodadapter");

        const std::vector<Spread>& largeDisplacements_ =
            largeModel->displacements();

        if (displacements_.size() == 1)
        {
            Real dis = displacements_[0];
            displacements_.resize(numberOfRates_);
            std::fill(displacements_.begin(), displacements_.end(), dis);
        }

        if (displacements_.size() ==0) // if not specified use average across rate
        {
            displacements_.reserve(numberOfRates_);
            Size m=0;
            Real sum=0.0;
            for (Size k=0; k < numberOfRates_; ++k)
            {
                for (Size l=0; l < period; ++l, ++m)
                    sum+= largeDisplacements_[m];

                displacements_.push_back(sum/period);
            }
        }
        QL_REQUIRE( displacements_.size() == numberOfRates_,"newDisplacements should be empty,1, or number of new rates in fwdperiodadapter");

        LMMCurveState largeCS(largeModel->evolution().rateTimes());
        largeCS.setOnForwardRates(largeModel->initialRates());

        LMMCurveState smallCS(
                ForwardForwardMappings::RestrictCurveState(largeCS,
                                    period, offset
                                        ));

        initialRates_ =smallCS.forwardRates();

        Real finalReset = smallCS.rateTimes()[smallCS.numberOfRates()-1];
        std::vector<Time> oldEvolutionTimes(largeModel->evolution().evolutionTimes());
        std::vector<Time> newEvolutionTimes;
        for (Size i =0; i < oldEvolutionTimes.size() && oldEvolutionTimes[i]<= finalReset; ++i)
            newEvolutionTimes.push_back(oldEvolutionTimes[i]);

        evolution_=EvolutionDescription(smallCS.rateTimes(),
                                        newEvolutionTimes);

        numberOfSteps_ = newEvolutionTimes.size();


        const std::vector<Time>& rateTimes =
            smallCS.rateTimes();
        // we must ensure we step through all rateTimes
        const std::vector<Time>& evolutionTimes =
            evolution_.evolutionTimes();

        std::set<Time> setTimes(evolutionTimes.begin(),evolutionTimes.end());

        for (Size i=0; i < rateTimes.size()-1; ++i)
            QL_REQUIRE(setTimes.find(rateTimes[i]) != setTimes.end(),
                        "every new rate time except last must be an evolution time in fwdperiod adapter");


        Matrix YMatrix =
            ForwardForwardMappings::YMatrix( largeCS,
                                                 largeDisplacements_,
                                                  displacements_,
                                                 period,
                                                 offset
                                                 );

        const std::vector<Size>& alive =
            evolution_.firstAliveRate();

        for (Size k = 0; k<numberOfSteps_; ++k) {
            pseudoRoots_[k]=YMatrix*largeModel->pseudoRoot(k);
            for (Size i=0; i<alive[k]; ++i)
                std::fill(pseudoRoots_[k].row_begin(i),
                          pseudoRoots_[k].row_end(i),
                          0.0);
        }
    }
Пример #20
0
std::vector<double> NNTrainer::gradient( const double lambda)
{
    int numExamples = trainingSet->size();
    //-- Create n matrices with the dimensions of the weight matrices:
    std::vector<Matrix> Delta;

    for (int i = 0; i < (int) nn->getWeights().size(); i++)
	Delta.push_back( Matrix( nn->getWeights().at(i)->getNumRows(), nn->getWeights().at(i)->getNumCols() ));

    //-- Iterate over all training examples
    for (int i = 0; i < numExamples; i++)
    {
	//-- Forward-propagate the network:
	nn->setInput( trainingSet->at(i).x );

	//-- Create vector to store the increments:
	//-- Increments will be stored in reverse order (i.e. the last increment first)
	std::vector<Matrix> inc;

	//-- Increment for output layer
	Matrix output = Matrix(nn->getOutput(), nn->getOutput().size(), 1);
	Matrix y = Matrix(trainingSet->at(i).y , trainingSet->at(i).y.size(), 1);

	inc.push_back( output - y);

	//-- Increment for hidden layers
	for (int l = nn->getL() - 2; l > 0; l--)
	{

	    Matrix aux1 = nn->getWeights().at(l)->transpose() * inc.back();
	    Matrix aux2( aux1.getNumRows()-1, aux1.getNumCols());

	    for (int j = 0; j < aux2.getNumCols(); j++)
		for (int k = 0; k < aux2.getNumRows(); k++)
		    aux2.set( k, j, aux1.get(k+1, j) * sigmoidGradient( nn->getActivation(l).at(k)) );

	    inc.push_back( aux2 );
	}

	//-- Input layer has no error associated (has no weights associated)

	//-- Accumulate error:
	for (int l = 0; l < (int) Delta.size(); l++)
	{
	    Matrix aux1( Delta.at(l).getNumRows(), Delta.at(l).getNumCols() );

	    for (int j = 0; j < aux1.getNumRows(); j++)
		aux1.set( j, 0, inc.at( inc.size()- l -1).get( j, 0) );

	    for (int j = 0; j < aux1.getNumRows(); j++)
		for (int k = 1; k < aux1.getNumCols(); k++)
		    aux1.set( j, k, inc.at( inc.size()- l -1).get( j, 0) * nn->getActivation(l).at(k-1));

	    Delta.at(l) += aux1;
	}


    }

    //-- Divide by number of training examples:
    for (int l = 0; l < (int) Delta.size(); l++)
	Delta.at(l) /= numExamples;

    //-- Regularization
    //------------------------------------------------------------------------
    if (lambda != 0)
    {
	for (int l = 0; l < (int) Delta.size(); l++)
	{
	    Matrix aux(nn->getWeights().at(l)->getNumRows(), nn->getWeights().at(l)->getNumCols() );

	    for (int j = 0; j < aux.getNumRows(); j++)
		for (int k = 1; k < aux.getNumCols(); k++)
		    aux.set( j, k, nn->getWeights().at(l)->get(j, k) * lambda / numExamples);

	    Delta.at(l) += aux;
	}
    }


    //-- Unroll gradient:
    //---------------------------------------------------------------------------
    std::vector<double> unrolled = Delta.front().unroll();

    for (int l = 1; l < (int) Delta.size(); l++)
	for (int j = 0; j < Delta.at(l).getNumRows(); j++)
	    for (int k = 0; k < Delta.at(l).getNumCols(); k++)
		unrolled.push_back( Delta.at(l).get(j, k));


    return unrolled;
}
Пример #21
0
	/*
	====================
	build
	====================
	*/
	VOID Sphere::build()
	{
		GUARD(Sphere::build);

		// clear the old keys
		mKeys.clear();

		#define SPHERE_SEGMENTS	20
		#define SPHERE_ROWS		10

		std::vector<DVTN>vertexes;
		std::vector<U32>indexes;

		F32 l_delta = PI/(F32)SPHERE_ROWS;
		F32 v_delta = 1.0f/(F32)SPHERE_ROWS;

		F32 angle_delta = PI*2.0f/(F32)SPHERE_SEGMENTS;
		F32 texcoord_horz_delta = 1.0f/(F32)SPHERE_SEGMENTS;

		F32 l_base=-PI*0.5f;
		F32 r_base=0.0f;
		F32 z_base=-mRadius;
		F32 v_base=0.0f;
		F32 n_z_base=-1.0f;
		F32 n_ratio_base=0.0f;

		for(U32 rowi=0; rowi<SPHERE_ROWS; ++rowi)
		{
			F32 l_top = l_base+l_delta;
			F32 r_top = GMath::cos(l_top)*mRadius;
			F32 z_top = GMath::sin(l_top)*mRadius;
			F32 v_top = v_base+v_delta;
			F32 n_z_top= GMath::sin(l_top);
			F32 n_ratio_top= GMath::cos(l_top);

			F32 angle = 0.0f;
			F32 texcoord = 0.0f;

			for(U32 topi=0; topi<SPHERE_SEGMENTS;++topi,angle+=angle_delta,texcoord+=texcoord_horz_delta)
			{
				F32 c = GMath::cos(angle);
				F32 s = GMath::sin(angle);

				DVTN v;
				v.normal[0]		= c*n_ratio_top;
				v.normal[1]		= s*n_ratio_top;
				v.normal[2]		= n_z_top;
				v.texcoord[0]	= texcoord;
				v.texcoord[1]	= v_top;
				v.point[0]		= c*r_top;
				v.point[1]		= s*r_top;
				v.point[2]		= z_top;
				vertexes.push_back(v);

				v.normal[0]		= c*n_ratio_base;
				v.normal[1]		= s*n_ratio_base;
				v.normal[2]		= n_z_base;
				v.texcoord[0]	= texcoord;
				v.texcoord[1]	= v_base;
				v.point[0]		= c*r_base;
				v.point[1]		= s*r_base;
				v.point[2]		= z_base;
				vertexes.push_back(v);
			}

			// do last point by hand to ensure no round off errors.
			DVTN v;
			v.normal[0]		= n_ratio_top;
			v.normal[1]		= 0.0f;
			v.normal[2]		= n_z_top;
			v.texcoord[0]	= 1.0f;
			v.texcoord[1]	= v_top;
			v.point[0]		= r_top;
			v.point[1]		= 0.0f;
			v.point[2]		= z_top;
			vertexes.push_back(v);

			v.normal[0]		= n_ratio_base;
			v.normal[1]		= 0.0f;
			v.normal[2]		= n_z_base;
			v.texcoord[0]	= 1.0f;
			v.texcoord[1]	= v_base;
			v.point[0]		= r_base;
			v.point[1]		= 0.0f;
			v.point[2]		= z_base;
			vertexes.push_back(v);

			l_base=l_top;
			r_base=r_top;
			z_base=z_top;
			v_base=v_top;
			n_z_base=n_z_top;
			n_ratio_base=n_ratio_top;
		}

		// QUAD_STRIP
		U32 first = 0;
		U32 count = vertexes.size();
		for(U32 i=3, pos=first;i<count;i+=2,pos+=2)
		{
			indexes.push_back(pos);
			indexes.push_back(pos+1);
			indexes.push_back(pos+2);
			indexes.push_back(pos+1);
			indexes.push_back(pos+3);
			indexes.push_back(pos+2);
		}		

		// build the primitive
		mPrimitivePtr = GNEW(Primitive); CHECK(mPrimitivePtr);
		mPrimitivePtr->SetType(mType);

		// set the wvp
		Constant* wvp_constant_ptr = GNEW(Constant); CHECK(wvp_constant_ptr);
		wvp_constant_ptr->SetMatrix(Matrix());
		mPrimitivePtr->SetConstant("gWVP",wvp_constant_ptr);

		// set the color
		Constant* color_constant_ptr = GNEW(Constant); CHECK(color_constant_ptr);
		color_constant_ptr->SetVector(Vector4(0,0,0,0));
		mPrimitivePtr->SetConstant("gColor",color_constant_ptr);

		// set the shader
		Str key_name = "shader/color.xml";
		KeyPtr key_ptr = Key::Find(key_name.c_str());
		if(key_ptr == NULL)
		{
			Shader*shader = GNEW(Shader); CHECK(shader);
			shader->Load(GLoad(key_name.c_str()));
			key_ptr = GNEW(Key(key_name.c_str(), shader)); CHECK(key_ptr);
		}
		mKeys.push_back(key_ptr);
		mPrimitivePtr->SetShader(dynamic_cast<Shader*>(key_ptr->Ptr()), "p0");

		// build the vertex buffer
		VertexBufferPtr vb_ptr = GNEW(VertexBuffer); CHECK(vb_ptr);
		{
			GDataPtr vd_ptr = GNEW(GData); CHECK(vd_ptr);
			vd_ptr->Size(3*sizeof(U32) + 4*sizeof(U8) + vertexes.size()*sizeof(DVTN));
			U8*data_ptr = (U8*)vd_ptr->Ptr();
			*(U32*)data_ptr = MAKEFOURCC('G','V','B','O');
			data_ptr += sizeof(U32);
			*(U32*)data_ptr = vertexes.size();
			data_ptr += sizeof(U32);
			*(U32*)data_ptr = sizeof(DVTN); 
			data_ptr += sizeof(U32);
			*(U8*)data_ptr = 3;
			data_ptr += sizeof(U8);
			*(U8*)data_ptr = VertexBuffer::VT_3F;
			data_ptr += sizeof(U8);
			*(U8*)data_ptr = VertexBuffer::VT_2F;
			data_ptr += sizeof(U8);
			*(U8*)data_ptr = VertexBuffer::VT_3F;
			data_ptr += sizeof(U8);
			::memcpy(data_ptr, &vertexes[0], vertexes.size()*sizeof(DVTN));
			data_ptr += vertexes.size()*sizeof(DVTN);
			vb_ptr->Load(vd_ptr.Ptr());
		}
		mPrimitivePtr->SetVertexBuffer(vb_ptr.Ptr());

		// build the index
		IndexBufferPtr ib_ptr = GNEW(IndexBuffer); CHECK(ib_ptr);
		{
			GDataPtr id_ptr = GNEW(GData); CHECK(id_ptr);
			id_ptr->Size(3*sizeof(U32) + indexes.size()*sizeof(U32));
			U8*data_ptr = (U8*)id_ptr->Ptr();
			*(U32*)data_ptr = MAKEFOURCC('G','I','B','O');
			data_ptr += sizeof(U32);
			*(U32*)data_ptr = indexes.size(); 
			data_ptr += sizeof(U32);
			*(U32*)data_ptr = sizeof(U32); 
			data_ptr += sizeof(U32);
			::memcpy(data_ptr, &indexes[0], indexes.size()*sizeof(U32));
			data_ptr += indexes.size()*sizeof(U32);
			ib_ptr->Load(id_ptr.Ptr());
		}
		mPrimitivePtr->SetIndexBuffer(ib_ptr.Ptr());	

		// build the bounding box
		mBox.set(MAX_F32,MAX_F32,MAX_F32,MIN_F32,MIN_F32,MIN_F32);
		for(U32 i = 0; i < vertexes.size(); i++)mBox.expand(vertexes[i].point);
		mPrimitivePtr->SetBox(mBox);

		UNGUARD;
	}
Пример #22
0
IO::BinaryStream& operator << (IO::BinaryStream& Stream, CONST MatrixN<N,T>& Matrix)
{
	Stream.Write( &Matrix(0,0), sizeof(T)*N*N );
	return Stream;
}
Пример #23
0
ImagemapRenderRegion::ImagemapRenderRegion(ImagemapFilterOptions ifoOptions) :
RenderRegion(ImagemapFilterOptions::GetSizeOfExportArea(ifoOptions.m_stExportArea), Matrix(), 1)
{
	m_Options=ifoOptions;
}
Пример #24
0
int XC::Concrete01::commitSensitivity(const double &strainGradient, int gradNumber, int numGrads)
  {
    // Initialize unconditaional stress sensitivity
    UniaxialStateVars trialStateSensitivity;
    trialStateSensitivity.Strain()= strainGradient;
    double dktdh= 0.0;

    // Assign values to parameter derivatives (depending on what's random)
    double fpcSensitivity= 0.0;
    double epsc0Sensitivity= 0.0;
    double fpcuSensitivity= 0.0;
    double epscuSensitivity= 0.0;

    if(parameterID == 1)
      { fpcSensitivity= 1.0; }
    else if(parameterID == 2)
      { epsc0Sensitivity= 1.0; }
    else if(parameterID == 3)
      { fpcuSensitivity= 1.0; }
    else if(parameterID == 4)
      { epscuSensitivity= 1.0; }

    // Pick up sensitivity history variables
    UniaxialHistoryVars convergedHistorySensitivity;
    UniaxialStateVars convergedStateSensitivity;

    if(SHVs.isEmpty())
      {
        SHVs= Matrix(5,numGrads);
        convergedHistorySensitivity.UnloadSlope()= (2.0*fpcSensitivity*epsc0-2.0*fpc*epsc0Sensitivity) / (epsc0*epsc0);
      }
    else
      {
        convergedHistorySensitivity.MinStrain()= SHVs(0,(gradNumber-1));
        convergedHistorySensitivity.UnloadSlope()= SHVs(1,(gradNumber-1));
        convergedHistorySensitivity.EndStrain()= SHVs(2,(gradNumber-1));
        convergedStateSensitivity.Stress()= SHVs(3,(gradNumber-1));
        convergedStateSensitivity.Strain()= SHVs(4,(gradNumber-1));
      }

    // Strain increment
    const double dStrain= trialState.getStrain() - convergedState.getStrain();

    // Evaluate stress sensitivity
    if(dStrain < 0.0)
      { // applying more compression to the material
        if(trialState.getStrain() < convergedHistory.MinStrain())
          { // loading along the backbone curve
            if(trialState.getStrain() > epsc0)
              { //on the parabola
                trialStateSensitivity.Stress()= fpcSensitivity*(2.0*trialState.getStrain() /epsc0-(trialState.getStrain() /epsc0)*(trialState.getStrain() /epsc0))
                                     + fpc*( (2.0*trialStateSensitivity.Strain()*epsc0-2.0*trialState.getStrain() *epsc0Sensitivity)/(epsc0*epsc0)
                                     - 2.0*(trialState.getStrain() /epsc0)*(trialStateSensitivity.Strain()*epsc0-trialState.getStrain() *epsc0Sensitivity)/(epsc0*epsc0));

                dktdh= 2.0*((fpcSensitivity*epsc0-fpc*epsc0Sensitivity)/(epsc0*epsc0))
                           * (1.0-trialState.getStrain() /epsc0)
                      - 2.0*(fpc/epsc0)*(trialStateSensitivity.Strain()*epsc0-trialState.getStrain() *epsc0Sensitivity)
                        / (epsc0*epsc0);
              }
            else if(trialState.getStrain() > epscu)
              { // on the straight inclined line

                dktdh= ( (fpcSensitivity-fpcuSensitivity) * (epsc0-epscu)
                        - (fpc-fpcu)
                        * (epsc0Sensitivity-epscuSensitivity) )
                        / ((epsc0-epscu)*(epsc0-epscu));
                const double kt= (fpc-fpcu)/(epsc0-epscu);
                trialStateSensitivity.Stress()= fpcSensitivity
                                     + dktdh*(trialState.getStrain() -epsc0)
                                     + kt*(trialStateSensitivity.Strain()-epsc0Sensitivity);
              }
            else
              { // on the horizontal line
                trialStateSensitivity.Stress()= fpcuSensitivity;
                dktdh= 0.0;
              }
          }
        else if(trialState.getStrain() < convergedHistory.getEndStrain())
          { // reloading after an unloading that didn't go all the way to zero stress
            trialStateSensitivity.Stress()= convergedHistorySensitivity.getUnloadSlope() * (trialState.getStrain() -convergedHistory.getEndStrain())
                                 + convergedHistory.getUnloadSlope() * (trialStateSensitivity.Strain()-convergedHistorySensitivity.EndStrain());
            dktdh= convergedHistorySensitivity.getUnloadSlope();
          }
        else
          {
            trialStateSensitivity.Stress()= 0.0;
            dktdh= 0.0;
          }
      }
    else if(convergedState.getStress()+convergedHistory.getUnloadSlope()*dStrain<0.0)
      {// unloading, but not all the way down to zero stress
	trialStateSensitivity.Stress()= convergedStateSensitivity.getStress()
	  + convergedHistorySensitivity.UnloadSlope()*dStrain
	  + convergedHistory.getUnloadSlope()*(trialStateSensitivity.getStrain()-convergedState.getStrain());
	dktdh= convergedHistorySensitivity.UnloadSlope();
      }
    else
      {// unloading all the way down to zero stress
        trialStateSensitivity.Stress()= 0.0;
        dktdh= 0.0;
      }

    // Commit some history variables
    SHVs(3,(gradNumber-1))= trialStateSensitivity.getStress();
    SHVs(4,(gradNumber-1))= trialStateSensitivity.getStrain();

    // Possibly update history variables for the three ordinary history variable derivatives
    double epsTemp, epsTempSensitivity;
    double eta, etaSensitivity;
    double ratio, ratioSensitivity;
    double temp1, temp1Sensitivity;
    double temp2, temp2Sensitivity;
    UniaxialHistoryVars trialHistorySensitivity;

    if(dStrain<0.0 && trialState.getStrain() <convergedHistory.MinStrain())
      {
        trialHistorySensitivity.MinStrain()= trialStateSensitivity.Strain();
        if(trialState.getStrain() < epscu)
          {
            epsTemp= epscu;
            epsTempSensitivity= epscuSensitivity;
          }
        else
          {
            epsTemp= trialState.getStrain() ;
            epsTempSensitivity= trialStateSensitivity.Strain();
          }
        eta= epsTemp/epsc0;
        etaSensitivity= (epsTempSensitivity*epsc0-epsTemp*epsc0Sensitivity) / (epsc0*epsc0);
        if(eta < 2.0)
          {
            ratio= 0.145 * eta*eta + 0.13*eta;
            ratioSensitivity= 0.29 * eta * etaSensitivity + 0.13 * etaSensitivity;
          }
        else
          {
            ratio= 0.707*(eta-2.0) + 0.834;
            ratioSensitivity= 0.707 * etaSensitivity;
          }
        temp1= trialState.getStrain() - ratio * epsc0;
        temp1Sensitivity= trialStateSensitivity.Strain() - ratioSensitivity * epsc0 - ratio * epsc0Sensitivity;
        temp2= trialState.getStress()  * epsc0 / (2.0*fpc);
        temp2Sensitivity= (2.0*fpc*(trialStateSensitivity.Stress()*epsc0+trialState.getStress() *epsc0Sensitivity)
                        -2.0*trialState.getStress() *epsc0*fpcSensitivity) / (4.0*fpc*fpc);
        if(temp1 == 0.0)
          {
            trialHistorySensitivity.UnloadSlope()= (2.0*fpcSensitivity*epsc0-2.0*fpc*epsc0Sensitivity) / (epsc0*epsc0);
          }
        else if(temp1 < temp2)
          {
            trialHistorySensitivity.EndStrain()= trialStateSensitivity.Strain() - temp1Sensitivity;
            trialHistorySensitivity.UnloadSlope()= (trialStateSensitivity.Stress()*temp1-trialState.getStress()*temp1Sensitivity) / (temp1*temp1);
          }
        else
          {
            trialHistorySensitivity.EndStrain()= trialStateSensitivity.Strain() - temp2Sensitivity;
            trialHistorySensitivity.UnloadSlope()= (2.0*fpcSensitivity*epsc0-2.0*fpc*epsc0Sensitivity) / (epsc0*epsc0);
          }
      }
    else
      { trialHistorySensitivity= convergedHistorySensitivity; }
    SHVs(0,(gradNumber-1))= trialHistorySensitivity.getMinStrain();
    SHVs(1,(gradNumber-1))= trialHistorySensitivity.getUnloadSlope();
    SHVs(2,(gradNumber-1))= trialHistorySensitivity.getEndStrain();
    return 0;
  }
Пример #25
0
Property::Value::Value( Type type )
{
  switch (type)
  {
    case Property::BOOLEAN:
    {
      mImpl = new Impl( false );
      break;
    }
    case Property::FLOAT:
    {
      mImpl = new Impl( 0.f );
      break;
    }
    case Property::INTEGER:
    {
      mImpl = new Impl( 0 );
      break;
    }
    case Property::VECTOR2:
    {
      mImpl = new Impl( Vector2::ZERO );
      break;
    }
    case Property::VECTOR3:
    {
      mImpl = new Impl( Vector3::ZERO );
      break;
    }
    case Property::VECTOR4:
    {
      mImpl = new Impl( Vector4::ZERO );
      break;
    }
    case Property::RECTANGLE:
    {
      mImpl = new Impl( Rect<int>(0,0,0,0) );
      break;
    }
    case Property::ROTATION:
    {
      mImpl = new Impl( Quaternion() );
      break;
    }
    case Property::STRING:
    {
      mImpl = new Impl( std::string() );
      break;
    }
    case Property::MATRIX:
    {
      mImpl = new Impl( Matrix() );
      break;
    }
    case Property::MATRIX3:
    {
      mImpl = new Impl( Matrix3() );
      break;
    }
    case Property::ARRAY:
    {
      mImpl = new Impl( Property::Array() );
      break;
    }
    case Property::MAP:
    {
      mImpl = new Impl( Property::Map() );
      break;
    }
    case Property::NONE:
    {
      mImpl = new Impl();
      break;
    }
  }
}
Пример #26
0
returnValue VariablesGrid::addVector(	const Vector& newVector,
										double newTime
										)
{
	return MatrixVariablesGrid::addMatrix( Matrix(newVector),newTime );
}
Пример #27
0
Matrix Matrix::operator-(const Matrix& mat) const
{
    return Matrix(m_Matrix - mat.m_Matrix);
}
Пример #28
0
VariablesGrid::VariablesGrid(	const Vector& arg,
								const Grid& _grid,
								VariableType _type
								) : MatrixVariablesGrid( Matrix(arg),_grid,_type )
{
}
Пример #29
0
  for (SIZE_T i=0; i<N; i++)
	  R.SetColumn(i,EigenVectors[i]);
}
//-----------------------------------------------------------------------------------------------------------------------------
template<SIZE_T N, class T>
IO::BinaryStream& operator << (IO::BinaryStream& Stream, CONST MatrixN<N,T>& Matrix)
{
	Stream.Write( &Matrix(0,0), sizeof(T)*N*N );
	return Stream;
}
//------------------------------------------------------------------------------------------------------------------------------
template<SIZE_T N, class T>
IO::BinaryStream& operator >> (IO::BinaryStream& Stream, MatrixN<N,T>& Matrix)
{
	Stream.Read( &Matrix(0,0), sizeof(T)*N*N );
	return Stream;
}
//------------------------------------------------------------------------------------------------------------------------------
template<SIZE_T N, class T>
MatrixN<N,T> MatrixN<N,T>::Read( LPCTSTR Filename )
{
  MatrixN<N,T> M;
  Ptr<IO::File> F = IO::File::Open(Filename, IO::FileMode::OPEN, IO::FileAccess::READ);
  F->Read( &M(0,0), sizeof(T)*N*N );
  return M;
}
//------------------------------------------------------------------------------------------------------------------------------
template<SIZE_T N, class T>
VOID MatrixN<N,T>::Write( LPCTSTR Filename )
{
GraphicsSystem::GraphicsSystem()
:   curMatrix(0)
{
    MatrixStack << Matrix().SetIdentity();
}