//Generate a square DEM with a high wall around its edge and a single outlet in
//the lower left corner. This arrangement is an adversarial input for the
//Garbrecht algorithm.
void GenerateDEM(int size, std::string outputname, std::string analysis){
  Array2D<uint8_t> dem(size,size,6);
  for(unsigned int i=0;i<dem.size();i++)
    if(dem.isEdgeCell(i))
      dem(i) = 9;

  dem(2,size-1) = 5;

  dem.saveGDAL(outputname,analysis);
}
Exemple #2
0
void demSimulation(int argc, char** argv){
    SDsystem sd_sys;
    DEMsystem dem(sd_sys);
    /* lubrication correction is not used.
     */
    int lub_correction = 0;
	dem.setParameterFileDEM(argv[2]);
    /* Import positions of the cluster: (file, skip lines)*/
	dem.importCluster(argv[3], atoi(argv[4]));
    /* You can add arbitary string for name of outpuf file. */
    dem.setVersion(argv[5]);
    /* Read parameter file */
    dem.readParameterFileDEM();
    dem.readParameterBond();
    dem.readParameterShearProcess();
	/* Setup simulation */
	dem.initDEM();
    if (dem.method_hydroint > 0){
        sd_sys.setFlowType('s'); // Set shear flow in SD.
        sd_sys.initFlowModel(dem.np, lub_correction, false);
    }
    /* Main simulation */
	if ( dem.shear_process == "stepwise"){
        shearStepwiseIncreaseTest(sd_sys, dem);
    } else if ( dem.shear_process == "you_can_define_test"){
        // youCanDefineTest(sd_sys, dem);
    } else {
        cerr << dem.shear_process << " is not programmed." << endl;
    }
	return;
}
Exemple #3
0
void
AMDemod (AMD am)
{
	int i;
	REAL demout;
	switch (am->mode)
	{
		case SAMdet:
			for (i = 0; i < am->size; i++)
			{
				pll (am, CXBdata (am->ibuf, i));
				demout = dem (am);
				CXBdata (am->obuf, i) = Cmplx (demout, demout);
			}
			break;
		case AMdet:
			for (i = 0; i < am->size; i++)
			{
				am->lock.curr = Cmag (CXBdata (am->ibuf, i));
				am->dc = 0.9999f * am->dc + 0.0001f * am->lock.curr;
				am->smooth = 0.5f * am->smooth + 0.5f * (am->lock.curr /*- am->dc*/);
				/* demout = am->smooth; */
				CXBdata (am->obuf, i) = Cmplx (am->smooth, am->smooth);
			}
			break;
	}
}
// création du vecteur de demande totale
void Calculs::vdem()
{
      //cout << dem(0)<<endl;
      for(k=0;k<34;k++)
      {
                       D[k] = dem(k);
                       //cout << deman[k] << "  " << k << endl;
                      // system("pause");
      }
}
Exemple #5
0
//////////////////
// MAIN ROUTINE //
//////////////////
// The main loop returns the value 0 to the shell, if the program terminated
// successfully, and 1 if an error occured which caused the program to crash.
int main(const int argc, const char *argv[]) 
{
    // Default values
    int verbose = 1;
    int dry = 0;
    int nfiles = 0;
    int darcy = 1;

    // Process input parameters
    int i;
    for (i=1; i<argc; ++i) {	// skip argv[0]

        std::string argvi = std::string(argv[i]);

        // Display help if requested
        if (argvi == "-h" || argvi == "--help") {
            std::cout << argv[0] << ": particle dynamics simulator\n"
                << "Usage: " << argv[0] << " [OPTION[S]]... [FILE1 ...]\nOptions:\n"
                << "-h, --help\t\tprint help\n"
                << "-n, --dry\t\tshow key experiment parameters and quit\n"
                << std::endl;
            return 0; // Exit with success
        }

        else if (argvi == "-n" || argvi == "--dry")
            dry = 1;

        // The rest of the values must be input binary files
        else {
            nfiles++;

            if (verbose == 1)
                std::cout << argv[0] << ": processing input file: " << argvi <<
                    std::endl;

            // Create DEM class, read data from input binary,
            // check values, init cuda, transfer const mem, solve Darcy flow
            DEM dem(argvi, verbose, 1, dry, 1, 1, darcy);
            if (dry == 0)
                dem.startTime();
        }
    }

    // Check whether there are input files specified
    if (!argv[0] || argc == 1 || nfiles == 0) {
        std::cerr << argv[0] << ": missing input binary file\n"
            << "See `" << argv[0] << " --help` for more information"
            << std::endl;
        return 1; // Return unsuccessful exit status
    }

    return 0; // Return successfull exit status
}
Exemple #6
0
  void GradGrad<D>::T_CalcElementMatrix (const FiniteElement & base_fel,
			    const ElementTransformation & eltrans, 
			    FlatMatrix<SCAL> elmat,
			    LocalHeap & lh) const {
    
    const CompoundFiniteElement &  cfel  // product space 
      =  dynamic_cast<const CompoundFiniteElement&> (base_fel);

    const ScalarFiniteElement<D> & fel_u =  // u space
      dynamic_cast<const ScalarFiniteElement<D>&> (cfel[GetInd1()]);
    const ScalarFiniteElement<D> & fel_e =  // e space
      dynamic_cast<const ScalarFiniteElement<D>&> (cfel[GetInd2()]);

    elmat = SCAL(0.0);

    // u dofs [ru.First() : ru.Next()-1],  e dofs [re.First() : re.Next()-1]
    IntRange ru = cfel.GetRange(GetInd1()); 
    IntRange re = cfel.GetRange(GetInd2()); 
    int ndofe = re.Size();
    int ndofu = ru.Size();

    FlatMatrixFixWidth<D> dum(ndofu,lh); // to store grad(u-basis)  
    FlatMatrixFixWidth<D> dem(ndofe,lh); // to store grad(e-basis)

    ELEMENT_TYPE eltype                  // get the type of element: 
      = fel_u.ElementType();             // ET_TRIG in 2d, ET_TET in 3d.

    const IntegrationRule &              // Note: p = fel_u.Order()-1
      ir = SelectIntegrationRule(eltype, fel_u.Order()+fel_e.Order()-2);
    
    FlatMatrix<SCAL> submat(ndofe,ndofu,lh);
    submat = 0.0;

    for(int k=0; k<ir.GetNIP(); k++) {	
      
      MappedIntegrationPoint<D,D> mip (ir[k],eltrans);
      // set grad(u-basis) and grad(e-basis) at mapped pts in dum and dem.
      fel_u.CalcMappedDShape( mip, dum ); 
      fel_e.CalcMappedDShape( mip, dem );

      // evaluate coefficient
      SCAL fac = coeff_a -> T_Evaluate<SCAL>(mip);
      fac *= mip.GetWeight() ;
      
      //             [ndofe x D] * [D x ndofu]
      submat +=  fac *  dem     * Trans(dum) ;
    }
    
    elmat.Rows(re).Cols(ru) += submat;
    if (GetInd1() != GetInd2())
      elmat.Rows(ru).Cols(re) += Conj(Trans(submat));
    
  }
Exemple #7
0
String demangleAndSimplify(const String & mangled, int isDataMember, int entryType)
{
	String buildingResult;
	const char *m = mangled;
	//int mlen = mangled.length();
	String	saveMangled = mangled; // dem may modify the string

	//const char *d = demangle_withlen(m, mlen);
	char	buf[MAXDBUF];
	char	sbuf[MAXDBUF];
	DEM	dm;
	int	putbackUnder = 0;
	
        if (*m == '_' && hasextra_(entryType) && !isDataMember)
        {
		putbackUnder = 1;
        }

	if( dem((char*)m, &dm, sbuf) < 0 || //Error
		 dm.type == DEM_PTBL 	||
		 dm.type == DEM_STI 	||
		 dm.type == DEM_STD )
	{
		buildingResult = saveMangled;
		beVerbose(saveMangled, saveMangled, entryType, isDataMember);
		return buildingResult;
	}

	dem_print( &dm, buf );

	postProcess(isDataMember, saveMangled, buildingResult, buf);

	//postProcess may decide to use the mangled name even if the name is
	// demangleable, for instance, after-first instance of overloading 
	// function name using -d option
	if( ( buildingResult != saveMangled ) && ( putbackUnder == 1 ) )
		buildingResult = "_" + buildingResult;

	// convert the non C function name char in function name to a
	// C string
	if( prepareDebug )
		translate( buildingResult );

	beVerbose(saveMangled, buildingResult, entryType, isDataMember);
	return buildingResult;
}
void meshGRegionExtruded::operator() (GRegion *gr)
{
  gr->model()->setCurrentMeshEntity(gr);

  if(gr->geomType() == GEntity::DiscreteVolume) return;

  ExtrudeParams *ep = gr->meshAttributes.extrude;

  if(!ep || !ep->mesh.ExtrudeMesh || ep->geo.Mode != EXTRUDED_ENTITY) return;

  Msg::Info("Meshing volume %d (extruded)", gr->tag());

  // destroy the mesh if it exists
  deMeshGRegion dem;
  dem(gr);

  // build an rtree with all the vertices on the boundary of gr
  MVertexRTree pos(CTX::instance()->geom.tolerance * CTX::instance()->lc);
  insertAllVertices(gr, pos);

  // volume is extruded from a surface
  GFace *from = gr->model()->getFaceByTag(std::abs(ep->geo.Source));
  if(!from){
    Msg::Error("Unknown source surface %d for extrusion", ep->geo.Source);
    return;
  }

  extrudeMesh(from, gr, pos);

  // carve holes if any (only do it now if the mesh is final, i.e., if
  // the mesh is recombined)
  if(ep->mesh.Holes.size() && ep->mesh.Recombine){
    std::map<int, std::pair<double, std::vector<int> > >::iterator it;
    for(it = ep->mesh.Holes.begin(); it != ep->mesh.Holes.end(); it++)
      carveHole(gr, it->first, it->second.first, it->second.second);
  }
}
Exemple #9
0
//////////////////
// MAIN ROUTINE //
//////////////////
// The main loop returns the value 0 to the shell, if the program terminated
// successfully, and 1 if an error occured which caused the program to crash.
int main(const int argc, const char *argv[]) 
{
    // Default values
    int verbose = 0;
    int nfiles = 0; // number of input files
    int slices = 10; // number of vertical slices

    // Process input parameters
    int i;
    for (i=1; i<argc; ++i) {	// skip argv[0]

        std::string argvi = std::string(argv[i]);

        // Display help if requested
        if (argvi == "-h" || argvi == "--help") {
            std::cout << argv[0] << ": sphere porosity calculator\n"
                "Usage: " << argv[0] << " [OPTION[S]]... [FILE1 ...]\n"
                "Options:\n"
                "-h, --help\t\tprint help\n"
                "-V, --version\t\tprint version information and exit\n"
                "-v, --verbose\t\tdisplay in-/output file names\n"
                "-s. --slices\t\tnumber of vertical slices to find porosity "
                "within\n"
                "The porosity values are stored in the output/ folder"
                << std::endl;
            return 0; // Exit with success
        }

        // Display version with fancy ASCII art
        else if (argvi == "-V" || argvi == "--version") {
            std::cout << "Porosity calculator, sphere version " << VERSION
                << std::endl;
            return 0;
        }

        else if (argvi == "-v" || argvi == "--verbose")
            verbose = 1;

        else if (argvi == "-s" || argvi == "--slices") {
            slices = atoi(argv[++i]); 
            if (slices < 1) {
                std::cerr << "Error: The number of slices must be a positive, "
                    "real number (was " << slices << ")" << std::endl;
                return 1;
            }
        }

        // The rest of the values must be input binary files
        else {
            nfiles++;

            if (verbose == 1)
                std::cout << argv[0] << ": processing input file: " << argvi <<
                    std::endl;

            // Create DEM class, read data from input binary, check values
            DEM dem(argvi, verbose, 0, 0, 0, 0);

            // Calculate porosity and save as file
            dem.porosity(slices);

        }
    }

    // Check whether there are input files specified
    if (!argv[0] || argc == 1 || nfiles == 0) {
        std::cerr << argv[0] << ": missing input binary file\n"
            << "See `" << argv[0] << " --help` for more information"
            << std::endl;
        return 1; // Return unsuccessful exit status
    }

    return 0; // Return successfull exit status
} 
Exemple #10
0
//Open files, Initialize grid memory, makes function calls to set flowDir, slope, and resolvflats, writes files
int setdird8(char* demfile, char* pointfile, char *slopefile, char *flowfile, int useflowfile)
{
    MPI_Init(NULL,NULL);

    int rank,size;
    MPI_Comm_rank(MCW,&rank);
    MPI_Comm_size(MCW,&size);

    if (rank==0) {
        printf("D8FlowDir version %s\n",TDVERSION);

        if (strlen(pointfile) == 0) {
            printf("WARNING: no output p file specified\n");
        }

        if (strlen(slopefile) == 0) {
            printf("WARNING: no output sd8 file specified\n");
        }

        fflush(stdout);
    }

    MPITimer t;

    t.start("Total");
    t.start("Header read");

    //Read DEM from file
    tiffIO dem(demfile, FLOAT_TYPE);

    long totalX = dem.getTotalX();
    long totalY = dem.getTotalY();
    double dx = dem.getdxA();
    double dy = dem.getdyA();

    linearpart<float> elevDEM(totalX, totalY, dx, dy, MPI_FLOAT, *(float*) dem.getNodata());

    int xstart, ystart;
    int nx = elevDEM.getnx();
    int ny = elevDEM.getny();
    elevDEM.localToGlobal(0, 0, xstart, ystart);
    elevDEM.savedxdyc(dem);

    t.end("Header read");

    if (rank==0) {
        float timeestimate=(2.8e-9*pow((double)(totalX*totalY),1.55)/pow((double) size,0.65))/60+1;  // Time estimate in minutes
        //fprintf(stderr,"%d %d %d\n",totalX,totalY,size);
        fprintf(stderr,"This run may take on the order of %.0f minutes to complete.\n",timeestimate);
        fprintf(stderr,"This estimate is very approximate. \nRun time is highly uncertain as it depends on the complexity of the input data \nand speed and memory of the computer. This estimate is based on our testing on \na dual quad core Dell Xeon E5405 2.0GHz PC with 16GB RAM.\n");
        fflush(stderr);
    }

    uint64_t bytes_to_read = (uint64_t) nx * ny * sizeof(float);
    if (rank == 0) { 
        fprintf(stderr, "Reading input data (%s)... ", humanReadableSize(bytes_to_read).c_str());
    }

    t.start("Data read");

    dem.read(xstart, ystart, ny, nx, elevDEM.getGridPointer(), elevDEM.getGridPointerStride());
    elevDEM.share();
    double data_read_time = t.end("Data read");
   
    if (rank == 0) {
        fprintf(stderr, "done (%s/s).\n", humanReadableSize(bytes_to_read / data_read_time).c_str());
    }

    //Creates empty partition to store new flow direction
    short flowDirNodata = MISSINGSHORT;

    linearpart<short> flowDir(totalX, totalY, dx, dy, MPI_SHORT, flowDirNodata);

    //If using a flowfile, read it in
    if (useflowfile == 1) {
        tiffIO flow(flowfile, SHORT_TYPE);

        linearpart<short> imposedflow(flow.getTotalX(), flow.getTotalY(),
                flow.getdxA(), flow.getdyA(), MPI_SHORT, *(short*) flow.getNodata());

        if (!dem.compareTiff(flow)) {
            printf("Error using imposed flow file.\n");
            return 1;
        }

        for (int j=0; j < elevDEM.getny(); j++) {
            for (int i=0; i < elevDEM.getnx(); i++ ) {
                short data = imposedflow.getData(i,j);

                if (imposedflow.isNodata(i,j) || !imposedflow.hasAccess(i-1,j) || !imposedflow.hasAccess(i+1,j) ||
                        !imposedflow.hasAccess(i,j-1) || !imposedflow.hasAccess(i,j+1)) {
                    //Do nothing
                } else if (data > 0 && data <= 8) {
                    flowDir.setData(i,j,data);
                }
            }
        }
    }

    if (rank == 0) fprintf(stderr, "Calculating flow directions... ");
    t.start("Calculate flow directions");
    uint64_t numFlat = setPosDir(elevDEM, flowDir);
    t.end("Calculate flow directions");
  
    flowDir.share();

    if (strlen(slopefile) > 0)
    {
        t.start("Calculate slope");
        
        //Creates empty partition to store new slopes
        float slopeNodata = -1.0f;
        linearpart<float> slope(totalX, totalY, dx, dy, MPI_FLOAT, slopeNodata);

        calcSlope(flowDir, elevDEM, slope);

        t.end("Calculate slope");

        t.start("Write slope");
        tiffIO slopeIO(slopefile, FLOAT_TYPE, &slopeNodata, dem);
        slopeIO.write(xstart, ystart, ny, nx, slope.getGridPointer(), slope.getGridPointerStride());
        t.end("Write slope");
    }

    uint64_t totalNumFlat = 0;
    MPI_Allreduce(&numFlat, &totalNumFlat, 1, MPI_UINT64_T, MPI_SUM, MCW);
   
    if (rank == 0) {
        fprintf(stderr, "done. %" PRIu64 " flats to resolve.\n", totalNumFlat);
        fflush(stderr);
    }

    t.start("Resolve flats");

    if (totalNumFlat > 0) {
        if (rank == 0) {
            fprintf(stderr, "Finding flat islands...\n");
        }

        std::vector<std::vector<node>> islands;
        std::vector<std::vector<node>> borderingIslands;

        t.start("Find islands");
        findIslands<D8>(flowDir, islands, borderingIslands);
        t.end("Find islands");

        uint64_t localSharedFlats = 0, sharedFlats = 0;
        for (auto& island : borderingIslands) {
            localSharedFlats += island.size();
        }

        t.start("Resolve shared flats");
        MPI_Allreduce(&localSharedFlats, &sharedFlats, 1, MPI_UINT64_T, MPI_SUM, MCW);

        if (rank == 0 && size > 1) {
            fprintf(stderr, "Processing partial flats\n");

            printf("PRL: %llu flats shared across processors (%llu local -> %.2f%% shared)\n",
                    sharedFlats, totalNumFlat - sharedFlats, 100. * sharedFlats / totalNumFlat);
        }

        if (sharedFlats > 0) {
            SparsePartition<int> inc(totalX, totalY, 0);
            size_t lastNumFlat = resolveFlats_parallel_async<D8>(elevDEM, inc, flowDir, borderingIslands);

            if (rank==0) {
                fprintf(stderr, "PRL: Iteration complete. Number of flats remaining: %zu\n", lastNumFlat);
                fflush(stderr);
            }

            // Repeatedly call resolve flats until there is no change across all processors
            while (lastNumFlat > 0) {
                SparsePartition<int> newInc(totalX, totalY, 0);

                lastNumFlat = resolveFlats_parallel_async<D8>(inc, newInc, flowDir, borderingIslands);
                inc = std::move(newInc);

                if (rank==0) {
                    fprintf(stderr, "PRL: Iteration complete. Number of flats remaining: %zu\n", lastNumFlat);
                    fflush(stderr);
                }
            }
        }
        t.end("Resolve shared flats");

        //printf("rank %d: Done, %d islands. Took %.2f seconds\n", rank, numIslands, MPI_Wtime() - flatFindStart);
        //printf("rank %d: %lu bordering islands with %d flats\n", rank, bordering_islands.size(), localSharedFlats);

        t.start("Resolve local flats");
        if (!islands.empty()) {
            SparsePartition<int> inc(totalX, totalY, 0);
            size_t lastNumFlat = resolveFlats<D8>(elevDEM, inc, flowDir, islands);

            if (rank==0) {
                fprintf(stderr, "Iteration complete. Number of flats remaining: %zu\n\n", lastNumFlat);
                fflush(stderr);
            }

            // Repeatedly call resolve flats until there is no change
            while (lastNumFlat > 0)
            {
                SparsePartition<int> newInc(totalX, totalY, 0);

                lastNumFlat = resolveFlats<D8>(inc, newInc, flowDir, islands); 
                inc = std::move(newInc);

                if (rank==0) {
                    fprintf(stderr, "Iteration complete. Number of flats remaining: %zu\n\n", lastNumFlat);
                    fflush(stderr);
                }
            } 
        }
        t.end("Resolve local flats");
    }

    t.end("Resolve flats");

    if (strlen(pointfile) > 0) {
        t.start("Write directions");
        tiffIO pointIO(pointfile, SHORT_TYPE, &flowDirNodata, dem);
        pointIO.write(xstart, ystart, ny, nx, flowDir.getGridPointer(), flowDir.getGridPointerStride());
        t.end("Write directions");
    }

    t.end("Total");
    t.stop();
    //t.save("timing_info");

    MPI_Finalize();
    return 0;
}
IMP_Eigen::MatrixXd GaussianProcessInterpolationRestraint::get_hessian() const {
  // update everything
  ss_->do_before_evaluate();
  // get how many and which particles are optimized
  unsigned mnum = gpi_->get_number_of_m_particles();
  std::vector<bool> mopt;
  unsigned mnum_opt = 0;
  for (unsigned i = 0; i < mnum; i++) {
    mopt.push_back(gpi_->get_m_particle_is_optimized(i));
    if (mopt.back()) mnum_opt++;
  }
  unsigned Onum = gpi_->get_number_of_Omega_particles();
  std::vector<bool> Oopt;
  unsigned Onum_opt = 0;
  for (unsigned i = 0; i < Onum; i++) {
    Oopt.push_back(gpi_->get_Omega_particle_is_optimized(i));
    if (Oopt.back()) Onum_opt++;
  }
  unsigned num_opt = mnum_opt + Onum_opt;
  // Only upper corner of hessian will be computed
  IMP_Eigen::MatrixXd Hessian(IMP_Eigen::MatrixXd::Zero(num_opt, num_opt));

  // d2E/(dm_k dm_l) * dm^k/dTheta_i dm^l/dTheta_j
  IMP_Eigen::MatrixXd dmdm = mvn_->evaluate_second_derivative_FM_FM();
  std::vector<IMP_Eigen::VectorXd> funcm;
  for (unsigned i = 0; i < mnum; i++)
    if (mopt[i]) funcm.push_back(gpi_->get_m_derivative(i));
  //     dm_k/dTheta_i = 0 if i is a covariance particle
  //     only fill upper triangle e.g. j>=i
  for (unsigned i = 0; i < mnum_opt; ++i) {
    IMP_Eigen::VectorXd tmp(funcm[i].transpose() * dmdm);
    for (unsigned j = i; j < mnum_opt; ++j)
      Hessian(i, j) += tmp.transpose() * funcm[j];
  }
  // dmdm.resize(0,0); // free up some space

  // d2E/(dOm_kl dOm_mn) * dOm_kl/dTheta_i * dOm_mn/dTheta_j
  std::vector<std::vector<IMP_Eigen::MatrixXd> > dodo;
  //  get values
  for (unsigned m = 0; m < M_; ++m)  // row of second matrix
  {
    std::vector<IMP_Eigen::MatrixXd> tmp;
    for (unsigned n = 0; n < M_; ++n)  // column of second matrix
      tmp.push_back(mvn_->evaluate_second_derivative_Sigma_Sigma(m, n));
    dodo.push_back(tmp);
  }
  std::vector<IMP_Eigen::MatrixXd> funcO;
  for (unsigned i = 0; i < Onum; ++i)
    if (Oopt[i]) funcO.push_back(gpi_->get_Omega_derivative(i));
  //  compute contribution
  for (unsigned i = mnum_opt; i < num_opt; ++i) {
    IMP_Eigen::MatrixXd tmp(M_, M_);
    for (unsigned m = 0; m < M_; ++m)
      for (unsigned n = 0; n < M_; ++n)
        tmp(m, n) = (dodo[m][n].transpose() * funcO[i - mnum_opt]).trace();
    for (unsigned j = i; j < num_opt; ++j)
      Hessian(i, j) += (tmp * funcO[j - mnum_opt]).trace();
  }
  for (unsigned i = 0; i < dodo.size(); ++i) dodo[i].clear();
  dodo.clear();

  // d2E/(dm_k dOm_lm) * (  dm^k/dTheta_j dOm^lm/dTheta_i
  //                     + dm^k/dTheta_i dOm^lm/dTheta_j)
  // when i<=j, simplifies to i mean particles and j covariance particles:
  // d2E/(dm_k dOm_lm) * (  dm^k/dTheta_i dOm^lm/dTheta_j)
  //
  // get values
  std::vector<IMP_Eigen::MatrixXd> dmdo;
  for (unsigned k = 0; k < M_; k++)
    dmdo.push_back(mvn_->evaluate_second_derivative_FM_Sigma(k));
  // compute hessian
  for (unsigned j = mnum_opt; j < num_opt; ++j) {
    IMP_Eigen::VectorXd tmp(M_);
    for (unsigned k = 0; k < M_; ++k)
      tmp(k) = (dmdo[k].transpose() * funcO[j - mnum_opt]).trace();
    for (unsigned i = 0; i < mnum_opt; ++i)
      Hessian(i, j) += funcm[i].transpose() * tmp;
  }
  // deallocate both dmdo and all function derivatives
  dmdo.clear();
  funcm.clear();
  funcO.clear();

  // dE/dm_k * d2m^k/(dTheta_i dTheta_j)
  IMP_Eigen::VectorXd dem(mvn_->evaluate_derivative_FM());
  for (unsigned i = 0, iopt = 0; i < mnum; i++) {
    if (!mopt[i]) continue;
    for (unsigned j = i, jopt = iopt; j < mnum; j++) {
      if (!mopt[j]) continue;
      Hessian(iopt, jopt) +=
          dem.transpose() * gpi_->get_m_second_derivative(i, j);
      jopt++;
    }
    iopt++;
  }

  // dem.resize(0);

  // dE/dOm_kl * d2Om^kl/(dTheta_i dTheta_j)
  IMP_Eigen::MatrixXd dOm(mvn_->evaluate_derivative_Sigma());
  for (unsigned i = mnum, iopt = mnum_opt; i < mnum + Onum; i++) {
    if (!Oopt[i - mnum]) continue;
    for (unsigned j = i, jopt = iopt; j < mnum + Onum; j++) {
      if (!Oopt[j - mnum]) continue;
      Hessian(iopt, jopt) +=
          (dOm.transpose() *
           gpi_->get_Omega_second_derivative(i - mnum, j - mnum)).trace();
      jopt++;
    }
    iopt++;
  }
  // dOm.resize(0,0);

  // return hessian as full matrix
  for (unsigned i = 0; i < num_opt; ++i)
    for (unsigned j = i + 1; j < num_opt; ++j) Hessian(j, i) = Hessian(i, j);
  // return Hessian.selfadjointView<IMP_Eigen::Upper>();
  return Hessian;
}
Exemple #12
0
void meshGEdge::operator() (GEdge *ge)
{
#if defined(HAVE_ANN)
  FieldManager *fields = ge->model()->getFields();
  BoundaryLayerField *blf = 0;
  Field *bl_field = fields->get(fields->getBoundaryLayerField());
  blf = dynamic_cast<BoundaryLayerField*> (bl_field);
#else
  bool blf = false;
#endif

  ge->model()->setCurrentMeshEntity(ge);

  if(ge->geomType() == GEntity::DiscreteCurve) return;
  if(ge->geomType() == GEntity::BoundaryLayerCurve) return;
  if(ge->meshAttributes.method == MESH_NONE) return;
  if(CTX::instance()->mesh.meshOnlyVisible && !ge->getVisibility()) return;

  // look if we are doing the STL triangulation
  std::vector<MVertex*> &mesh_vertices = ge->mesh_vertices ;
  std::vector<MLine*> &lines = ge->lines ;

  deMeshGEdge dem;
  dem(ge);

  if(MeshExtrudedCurve(ge)) return;

  if (ge->meshMaster() != ge){
    GEdge *gef = dynamic_cast<GEdge*> (ge->meshMaster());
    if (gef->meshStatistics.status == GEdge::PENDING) return;
    Msg::Info("Meshing curve %d (%s) as a copy of %d", ge->tag(),
              ge->getTypeString().c_str(), ge->meshMaster()->tag());
    copyMesh(gef, ge, ge->masterOrientation);
    ge->meshStatistics.status = GEdge::DONE;
    return;
  }

  Msg::Info("Meshing curve %d (%s)", ge->tag(), ge->getTypeString().c_str());

  // compute bounds
  Range<double> bounds = ge->parBounds(0);
  double t_begin = bounds.low();
  double t_end = bounds.high();

  // first compute the length of the curve by integrating one
  double length;
  std::vector<IntPoint> Points;
  if(ge->geomType() == GEntity::Line &&
      ge->getBeginVertex() == ge->getEndVertex() &&
      //do not consider closed lines as degenerated
      (ge->position(0.5) - ge->getBeginVertex()->xyz()).norm() < CTX::instance()->geom.tolerance)
    length = 0.; // special case t avoid infinite loop in integration
  else
    length = Integration(ge, t_begin, t_end, F_One, Points, 1.e-8 * CTX::instance()->lc);
  ge->setLength(length);
  Points.clear();

  if(length < CTX::instance()->mesh.toleranceEdgeLength){
    ge->setTooSmall(true);
  }

  // Integrate detJ/lc du
  double a;
  int N;
  if(length == 0. && CTX::instance()->mesh.toleranceEdgeLength == 0.){
    Msg::Warning("Curve %d has a zero length", ge->tag());
    a = 0.;
    N = 1;
  }
  else if(ge->degenerate(0)){
    a = 0.;
    N = 1;
  }
  else if(ge->meshAttributes.method == MESH_TRANSFINITE){
    a = Integration(ge, t_begin, t_end, F_Transfinite, Points,
                    CTX::instance()->mesh.lcIntegrationPrecision);
    N = ge->meshAttributes.nbPointsTransfinite;
    if(CTX::instance()->mesh.flexibleTransfinite && CTX::instance()->mesh.lcFactor)
      N /= CTX::instance()->mesh.lcFactor;
  }
  else{
    if (CTX::instance()->mesh.algo2d == ALGO_2D_BAMG || blf){
      a = Integration(ge, t_begin, t_end, F_Lc_aniso, Points,
                      CTX::instance()->mesh.lcIntegrationPrecision);
    }
    else{
       a = Integration(ge, t_begin, t_end, F_Lc, Points,
                      CTX::instance()->mesh.lcIntegrationPrecision);
    }

    // we should maybe provide an option to disable the smoothing
    for (unsigned int i = 0; i < Points.size(); i++){
      IntPoint &pt = Points[i];
      SVector3 der = ge->firstDer(pt.t);
      pt.xp = der.norm();
    }
    a = smoothPrimitive(ge, sqrt(CTX::instance()->mesh.smoothRatio), Points);
    N = std::max(ge->minimumMeshSegments() + 1, (int)(a + 1.99));
  }

  // force odd number of points if blossom is used for recombination
  if((ge->meshAttributes.method != MESH_TRANSFINITE ||
      CTX::instance()->mesh.flexibleTransfinite) &&
     CTX::instance()->mesh.algoRecombine != 0){
    if(CTX::instance()->mesh.recombineAll){
      if (N % 2 == 0) N++;
      if (CTX::instance()->mesh.algoRecombine == 2)
	N = increaseN(N);
    }
    else{
      std::list<GFace*> faces = ge->faces();
      for(std::list<GFace*>::iterator it = faces.begin(); it != faces.end(); it++){
        if((*it)->meshAttributes.recombine){
	  if (N % 2 == 0) N ++;
	  if (CTX::instance()->mesh.algoRecombine == 2)
	    N = increaseN(N);
          break;
        }
      }
    }
  }

  // printFandPrimitive(ge->tag(),Points);

  // if the curve is periodic and if the begin vertex is identical to
  // the end vertex and if this vertex has only one model curve
  // adjacent to it, then the vertex is not connecting any other
  // curve. So, the mesh vertex and its associated geom vertex are not
  // necessary at the same location
  GPoint beg_p, end_p;
  if(ge->getBeginVertex() == ge->getEndVertex() &&
     ge->getBeginVertex()->edges().size() == 1){
    end_p = beg_p = ge->point(t_begin);
    Msg::Debug("Meshing periodic closed curve");
  }
  else{
    MVertex *v0 = ge->getBeginVertex()->mesh_vertices[0];
    MVertex *v1 = ge->getEndVertex()->mesh_vertices[0];
    beg_p = GPoint(v0->x(), v0->y(), v0->z());
    end_p = GPoint(v1->x(), v1->y(), v1->z());
  }

  // do not consider the first and the last vertex (those are not
  // classified on this mesh edge)
  if(N > 1){
    const double b = a / (double)(N - 1);
    int count = 1, NUMP = 1;
    IntPoint P1, P2;
    mesh_vertices.resize(N - 2);
    while(NUMP < N - 1) {
      P1 = Points[count - 1];
      P2 = Points[count];
      const double d = (double)NUMP * b;
      if((fabs(P2.p) >= fabs(d)) && (fabs(P1.p) < fabs(d))) {
        double dt = P2.t - P1.t;
        double dlc = P2.lc - P1.lc;
        double dp = P2.p - P1.p;
        double t   = P1.t + dt / dp * (d - P1.p);
        SVector3 der = ge->firstDer(t);
        const double d = norm(der);
        double lc  = d/(P1.lc + dlc / dp * (d - P1.p));
        GPoint V = ge->point(t);
        mesh_vertices[NUMP - 1] = new MEdgeVertex(V.x(), V.y(), V.z(), ge, t, lc);
        NUMP++;
      }
      else {
        count++;
      }
    }
    mesh_vertices.resize(NUMP - 1);
  }

  for(unsigned int i = 0; i < mesh_vertices.size() + 1; i++){
    MVertex *v0 = (i == 0) ?
      ge->getBeginVertex()->mesh_vertices[0] : mesh_vertices[i - 1];
    MVertex *v1 = (i == mesh_vertices.size()) ?
      ge->getEndVertex()->mesh_vertices[0] : mesh_vertices[i];
    lines.push_back(new MLine(v0, v1));
  }

  if(ge->getBeginVertex() == ge->getEndVertex() &&
     ge->getBeginVertex()->edges().size() == 1){
    MVertex *v0 = ge->getBeginVertex()->mesh_vertices[0];
    v0->x() = beg_p.x();
    v0->y() = beg_p.y();
    v0->z() = beg_p.z();
  }

  ge->meshStatistics.status = GEdge::DONE;
}