示例#1
0
double OblDeflectionTOA::psi_outgoing_u ( const double& b, const double& rspot,
				       					const double& b_max, const double& psi_max, 
				       					bool *prob ) const{

  	double dummy;

  	if ( b > b_max || b < 0.0 ) {
    	std::cerr << "ERROR in OblDeflectionTOA::psi_outgoing_u(): b out-of-range." << std::endl;
    	*prob = true;
    	dummy = -7888.0;
    	return dummy;
  	}

  	if ( fabs( b - b_max ) < 1e-7 ) { // essentially the same as b=b_max
    	return psi_max;
	}
  	else {  // set globals
    	OblDeflectionTOA_object = this;
    	OblDeflectionTOA_b_over_r = b/rspot;     // this will be fed to another function

    	double psi(0.0);

    	if ( b != 0.0 ) {
	  //psi = Integration( 0.0, 1.0, OblDeflectionTOA_psi_integrand_wrapper_u ); // integrating from r_surf to ~infinity
	  if ( b > 0.995*b_max){
	    double split(0.95);  	
	    psi = Integration( 0.0, split, OblDeflectionTOA_psi_integrand_wrapper_u,TRAPEZOIDAL_INTEGRAL_N );
	    psi += Integration( split, 1.0, OblDeflectionTOA_psi_integrand_wrapper_u,TRAPEZOIDAL_INTEGRAL_N_1 );
	  }
	  else
	    psi = Integration( 0.0, 1.0, OblDeflectionTOA_psi_integrand_wrapper_u,TRAPEZOIDAL_INTEGRAL_N );
    	}				
    	return psi;
  	}
}
示例#2
0
double OblDeflectionTOA::toa_outgoing_u ( const double& b, const double& rspot, bool *prob ) {
	// costheta_check(cos_theta);
  	//double dummy;

  	// set globals

  double b_max=bmax_outgoing(rspot);

  OblDeflectionTOA_object = this;
  OblDeflectionTOA_b_over_r = b/rspot;

  	// Note: Use an approximation to the integral near the surface
  	// to avoid divergence problems, and then use the real
  	// integral afterwards. See astro-ph/07030123 for the formula.

  	// The idea is to compute the time for a ray emitted from the
  	// surface, and subtract the time for a b=0 ray from r=rpole.
  	// To avoid large numbers, part of the subtraction is accomplished in the integrand.

  	// Note that for a b=0 ray, Delta T = int(1/(1-2*M/r), r),
  	// which is r + 2 M ln (r - 2M)

  	//double rsurf = modptr->R_at_costheta(cos_theta);
 
  	double rsurf = rspot;
  	double rpole = modptr->R_at_costheta(1.0);

  	//std::cout << "toa_outgoing: rpole = " << rpole << std::endl;
	double toa(0.0);
	double split(0.99);

	if (b < 0.95*b_max)
	  toa = Integration( 0.0, 1.0, OblDeflectionTOA_toa_integrand_minus_b0_wrapper_u,TRAPEZOIDAL_INTEGRAL_N/10 );
	else
	  if ( b < 0.9999999*b_max){
	      	
	    toa = Integration( 0.0, split, OblDeflectionTOA_toa_integrand_minus_b0_wrapper_u,TRAPEZOIDAL_INTEGRAL_N );
	    toa += Integration( split, 1.0, OblDeflectionTOA_toa_integrand_minus_b0_wrapper_u,TRAPEZOIDAL_INTEGRAL_N_1/10 );
	    //std::cout << "b/r = " << b/rspot << " b_max/r = " << b_max/rspot 
	    //	      << " b/b_max = " << b/b_max << " toa = " << toa << std::endl; 

	  }
	  else{
	    toa = Integration( 0.0, split, OblDeflectionTOA_toa_integrand_minus_b0_wrapper_u,TRAPEZOIDAL_INTEGRAL_N );
	    toa += Integration( split, 1.0, OblDeflectionTOA_toa_integrand_minus_b0_wrapper_u,TRAPEZOIDAL_INTEGRAL_N_1*10 );
	    //std::cout << "*******b/r = " << b/rspot << " b_max/r = " << b_max/rspot 
	    //	      << " b/b_max = " << b/b_max << " toa = " << toa << std::endl; 


	  }
	  
	    
  	//double toa = Integration( 0.0, 1.0, OblDeflectionTOA_toa_integrand_minus_b0_wrapper_u );

  	double toa_b0_polesurf = (rsurf - rpole) + 2.0 * get_mass() * ( log( rsurf - 2.0 * get_mass() )
		       				 - log( rpole - 2.0 * get_mass() ) );

  	return double( toa - toa_b0_polesurf);
}
示例#3
0
double OblDeflectionTOA::dpsi_db_outgoing_u( const double& b, const double& rspot, bool *prob ) const {
  	//costheta_check(cos_theta);
  
  	double dummy; //

	double b_max = bmax_outgoing(rspot);

  	if ( (b > b_max || b < 0.0) ) { 
    	std::cerr << "ERROR inOblDeflectionTOA::dpsi_db_outgoing(): b out-of-range." << std::endl;
    	std::cerr << "b = " << b << ", bmax = " << bmax_outgoing(rspot) << ", |b - bmax| = " << fabs(b - bmax_outgoing(rspot)) << std::endl;
    	*prob = true;
    	dummy = -7888.0;
    	return dummy;
  	}
  
  	// set globals
  	OblDeflectionTOA_object = this;
  	OblDeflectionTOA_b_over_r = b/rspot;

  	//double rsurf = modptr->R_at_costheta(cos_theta);

  	//rsurf = rspot;

	double dpsidb(0.0);
	double split(0.9);

	if (b < 0.95*b_max)
	  dpsidb = Integration( 0.0, 1.0, OblDeflectionTOA_dpsi_db_integrand_wrapper_u,TRAPEZOIDAL_INTEGRAL_N );
	else
	  if ( b < 0.99995*b_max){
	      	
	    dpsidb = Integration( 0.0, split, OblDeflectionTOA_dpsi_db_integrand_wrapper_u,TRAPEZOIDAL_INTEGRAL_N );
	    dpsidb += Integration( split, 1.0, OblDeflectionTOA_dpsi_db_integrand_wrapper_u,TRAPEZOIDAL_INTEGRAL_N_1 );
	    //std::cout << "b/r = " << b/rspot << " b_max/r = " << b_max/rspot 
	    //	      << " b/b_max = " << b/b_max << " dpsidb = " << dpsidb << std::endl; 

	  }
	  else{
	    dpsidb = Integration( 0.0, split, OblDeflectionTOA_dpsi_db_integrand_wrapper_u,TRAPEZOIDAL_INTEGRAL_N );
	    dpsidb += Integration( split, 1.0, OblDeflectionTOA_dpsi_db_integrand_wrapper_u,TRAPEZOIDAL_INTEGRAL_N_1*100 );
	    //std::cout << "*******b/r = " << b/rspot << " b_max/r = " << b_max/rspot 
	    //	      << " b/b_max = " << b/b_max << " dpsidb = " << dpsidb << std::endl; 


	  }
	  
	    

	  //double dpsidb = Integration( 0.0, 1.0, OblDeflectionTOA_dpsi_db_integrand_wrapper_u );
  	
  	return dpsidb;
}
示例#4
0
void testIntegration(){
 
 long int r;
 r=1867;
 
 printf("\nIntergration\n");
 Integration(funcTest,simpsonsRule,0.0,1.0);
 Integration(funcTest,trapizoidalRule,0.0,1.0);
 printf("monteCarloIntegration1D: %f\n",monteCarloIntegration1D(funcTest,0.0,1.0,1e7));
 printf("simpsonsRule: %f\n",simpsonsRule(funcTest,0.0,1.0,100));
 printf("random01:%f\n",random01());
 printf("random01Self: %f\n",random01Self(&r));
 printf("trapizoidalRule2D: %f\n",trapizoidalRule2D(funcTest5, 0, 1, 0, 1, 10,10)); 
 printf("trapizoidalRule2D: %f\n",trapizoidalRule2D(funcTest6, 1, 2, 3, 5, 40,40));
 
} 
示例#5
0
double OblDeflectionTOA::toa_outgoing ( const double& b, const double& rspot, bool *prob ) {
	// costheta_check(cos_theta);
  	//double dummy;

  	// set globals
  	OblDeflectionTOA_object = this;
  	OblDeflectionTOA_b_value = b;

  	// Note: Use an approximation to the integral near the surface
  	// to avoid divergence problems, and then use the real
  	// integral afterwards. See astro-ph/07030123 for the formula.

  	// The idea is to compute the time for a ray emitted from the
  	// surface, and subtract the time for a b=0 ray from r=rpole.
  	// To avoid large numbers, part of the subtraction is accomplished in the integrand.

  	// Note that for a b=0 ray, Delta T = int(1/(1-2*M/r), r),
  	// which is r + 2 M ln (r - 2M)

  	//double rsurf = modptr->R_at_costheta(cos_theta);
 
  	double rsurf = rspot;
  	double rpole = modptr->R_at_costheta(1.0);

  	//std::cout << "toa_outgoing: rpole = " << rpole << std::endl;

  	double toa = Integration( rsurf, get_rfinal(), OblDeflectionTOA_toa_integrand_minus_b0_wrapper );

  	double toa_b0_polesurf = (rsurf - rpole) + 2.0 * get_mass() * ( log( rsurf - 2.0 * get_mass() )
		       				 - log( rpole - 2.0 * get_mass() ) );

  	return double( toa - toa_b0_polesurf);
}
示例#6
0
double OblDeflectionTOA::dpsi_db_outgoing( const double& b, const double& rspot, bool *prob ) {
  	//costheta_check(cos_theta);
  
  	double dummy; //

  	if ( (b > bmax_outgoing(rspot) || b < 0.0) ) { 
    	std::cerr << "ERROR inOblDeflectionTOA::dpsi_db_outgoing(): b out-of-range." << std::endl;
    	std::cerr << "b = " << b << ", bmax = " << bmax_outgoing(rspot) << ", |b - bmax| = " << fabs(b - bmax_outgoing(rspot)) << std::endl;
    	*prob = true;
    	dummy = -7888.0;
    	return dummy;
  	}
  
  	// set globals
  	OblDeflectionTOA_object = this;
  	OblDeflectionTOA_b_value = b;

  	//double rsurf = modptr->R_at_costheta(cos_theta);

  	//rsurf = rspot;

  	double dpsidb = Integration( rspot, get_rfinal(), OblDeflectionTOA_dpsi_db_integrand_wrapper );
  	
  	return dpsidb;
}
示例#7
0
double OblDeflectionTOA::psi_outgoing ( const double& b, const double& rspot,
				       					const double& b_max, const double& psi_max, 
				       					bool *prob ) const{

  	double dummy;

  	if ( b > b_max || b < 0.0 ) {
    	std::cerr << "ERROR in OblDeflectionTOA::psi_outgoing(): b out-of-range." << std::endl;
    	*prob = true;
    	dummy = -7888.0;
    	return dummy;
  	}

  	if ( fabs( b - b_max ) < 1e-7 ) { // essentially the same as b=b_max
    	return psi_max;
	}
  	else {  // set globals
    	OblDeflectionTOA_object = this;
    	OblDeflectionTOA_b_value = b;     // this will be fed to another function

    	double psi(0.0);

    	if ( b != 0.0 ) {
      		psi = Integration( rspot, get_rfinal(), OblDeflectionTOA_psi_integrand_wrapper ); // integrating from r_surf to ~infinity
    	}				
    	return psi;
  	}
}
示例#8
0
BOOL IsMorrowind () {
	if (ItsMorrowind) return false;
	BOOL status = false;
	HINSTANCE hInstance = GetModuleHandleA (NULL);

	char *origFilename = new char[MAX_PATH];
	MWVersion = GetModuleNameAndVersion(hInstance, origFilename, MAX_PATH);
	if (!_stricmp (origFilename, "Morrowind.exe")) {
		LOG::open ("mwse-mge log.txt");
		LOG::log (WelcomeMessage);
		LOG::log ("DLL injected\r\n");
		if (!MWVersion) {
			ERRORMSG ("Unable to get Morrowind's version number.");
		}
		ItsMorrowind = status = true;
	}
	if (!PatchDisabled) lpPatchTree = PatchTree::BuildPatchTree();
	if (ItsMorrowind) ForceTextDll(GetModuleHandle(TEXT_DLL_NAME));
	if (strstr(origFilename, ".") == NULL) strcat_s(origFilename, MAX_PATH, ".exe");
	if (!IntegrationDisabled) Integration(hInstance, origFilename, MWVersion, ItsMorrowind);
	if (!PatchDisabled) PatchProcessMemory(hInstance, origFilename, MWVersion, ItsMorrowind);
	delete [] origFilename;

	return status;
}
示例#9
0
double OblDeflectionTOA::psi_max_outgoing_u ( const double& b, const double& rspot, bool *prob ) const{
  	double dummy;
  	if ( b > bmax_outgoing(rspot) || b < 0.0 ) {
    	std::cerr << "ERROR in OblDeflectionTOA::psi_outgoing(): b out-of-range." << std::endl;
    	*prob = true;
    	dummy = -7888.0;
    	return dummy;
  	}

  	// set globals
  	OblDeflectionTOA_object = this;
  	OblDeflectionTOA_b_over_r = b/rspot;

	double split(0.9);  	
  	double psi = Integration( 0.0, split, OblDeflectionTOA_psi_integrand_wrapper_u,TRAPEZOIDAL_INTEGRAL_N_MAX_1 );
	psi += Integration( split, 1.0, OblDeflectionTOA_psi_integrand_wrapper_u,TRAPEZOIDAL_INTEGRAL_N_MAX );
					
	std::cout << "Psi_max_u: b/r = " << b/rspot << " rspot = " << rspot << " r_final = " << get_rfinal() << std::endl;
	std::cout << "psi = " << psi << std::endl;

  	return psi;
}
示例#10
0
double OblDeflectionTOA::psi_max_outgoing ( const double& b, const double& rspot, bool *prob ) {
  	double dummy;
  	if ( b > bmax_outgoing(rspot) || b < 0.0 ) {
    	std::cerr << "ERROR in OblDeflectionTOA::psi_outgoing(): b out-of-range." << std::endl;
    	*prob = true;
    	dummy = -7888.0;
    	return dummy;
  	}

  	// set globals
  	OblDeflectionTOA_object = this;
  	OblDeflectionTOA_b_value = b;
  	
  	double psi = Integration( rspot, get_rfinal(), OblDeflectionTOA_psi_integrand_wrapper );
					
	std::cout << "Psi_max: b/r = " << b/rspot << " rspot = " << rspot << " r_final = " << get_rfinal() << std::endl;
	std::cout << "psi = " << psi << std::endl;

  	return psi;
}
示例#11
0
double Iteg(char chaine[], char variable, double valeur, void *donnees)
{
    if (!donnees)
       return ERR_PARAM;
    OptionsAlgo *optn = (OptionsAlgo*) donnees;

    double param[4] = {0};
    char *tab[4] = {NULL};
    tab[0] = malloc(MAX_CHAINE);
    tab[0][0] = '\0';
    tab[1] = malloc(MAX_CHAINE);
    tab[1][0] = '\0';

    RecupererParametres(chaine, param, 4, variable, valeur, tab, MAX_CHAINE);
    if (param[2] >= CODE_ERREUR || !tab[0][0] || !tab[1][0] || tab[1][1] || param[3] >= CODE_ERREUR)
    {
       free(tab[0]); free(tab[1]);
       return ERR_PARAM;
    }

    double a = Integration(tab[0], tab[1][0], param[2], param[3], *optn);
    free(tab[0]); free(tab[1]);
    return a;
}
Spectrum PathTracer::Integration (
	const Scene * thisScene,
	const Ray & ray,
	size_t currentDepth
) const
{
	// Russian Roulette
	// probility to stop this path
	double rr = 0.01;
	double randnum = getUniformRandomNumber( 0.0, 0.99 );
	if ( randnum < rr && currentDepth > 5 )
		return Spectrum();

	if ( currentDepth == maxDepth )
		return Spectrum();

	Intersection intersectionInfo;

	// check intersection between ray and scene
	if ( ! thisScene->IntersectionWithScene( ray, intersectionInfo ) )
		return Spectrum();

	// if there is an intersection
	Spectrum intensity;
	Spectrum emission;

	Objects * obj = intersectionInfo.object;

	if ( obj->emitter )
	{
		emission = obj->emission;
	}

	BRDFModels * brdf = obj->brdf_model;

	// Get surface (macro) normal direction
	Vector geometryNormalDirection ( 0 , 0 , 0 );
	Vector sampledNextDirection ( 0 , 0 , 0 );

	geometryNormalDirection = intersectionInfo.normal;

	double pdf = 0;

	Attenuation attenuationFactor = 
		brdf->SampleBRDF(
			ray.direction,
			sampledNextDirection,
			geometryNormalDirection,
			pdf
		);

	Ray newRay(
		intersectionInfo.intersectionPoint,
		sampledNextDirection
	);

	Spectrum Li =
		Integration(
			thisScene,
			newRay,
			currentDepth + 1
		);


	if ( !Li.isEmpty() )
	{
		attenuationFactor.Scaled_by_Spectrum_Value( obj->material_type->color );

		double cos_i = AbsDot( sampledNextDirection, geometryNormalDirection );

		intensity +=
			Attenuate_Light_Spectrum( attenuationFactor, Li ) * cos_i / pdf;
	}

	// weight the radiance back after Ruassian Roulette
	intensity = ( currentDepth > 5 ) ? ( intensity / ( 1 - rr ) ) : intensity;

	ASSERT_NAN( intensity );

	return emission + intensity;
}
示例#13
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;
}
示例#14
0
void MolecularDynamicsSimulation(void)
{
  int i,j,k;
  REAL ran;

  // for a crash-recovery we skip the initialization and jump to the
  // position right after the crash-file was written in the production run
  if(ContinueAfterCrash)
  {
    if(SimulationStage==POSITION_INITIALIZATION) goto ContinueAfterCrashLabel1;
    else if(SimulationStage==VELOCITY_EQUILIBRATION) goto ContinueAfterCrashLabel2;
    else goto ContinueAfterCrashLabel3;
  }

  // compute gas properties
  // here the pressure is converted to fugacities
  ComputeGasPropertiesForAllSystems();

  // open output-file
  OpenOutputFile();

  // print all the pre-simulations data
  PrintPreSimulationStatus();

  // allocate memory
  SampleRadialDistributionFunction(ALLOCATE);
  SampleProjectedLengthsDistributionFunction(ALLOCATE);
  SampleProjectedAnglesDistributionFunction(ALLOCATE);
  SampleNumberOfMoleculesHistogram(ALLOCATE);
  SamplePositionHistogram(ALLOCATE);
  SampleFreeEnergyProfile(ALLOCATE);
  SampleEndToEndDistanceHistogram(ALLOCATE);
  SampleEnergyHistogram(ALLOCATE);
  SampleFrameworkSpacingHistogram(ALLOCATE);
  SampleResidenceTimes(ALLOCATE);
  SampleDistanceHistogram(ALLOCATE);
  SampleBendAngleHistogram(ALLOCATE);
  SampleDihedralAngleHistogram(ALLOCATE);
  SampleAngleBetweenPlanesHistogram(ALLOCATE);
  SampleMoleculePropertyHistogram(ALLOCATE);
  SampleInfraRedSpectra(ALLOCATE);
  SampleMeanSquaredDisplacementOrderN(ALLOCATE);
  SampleVelocityAutoCorrelationFunctionOrderN(ALLOCATE);
  SampleRotationalVelocityAutoCorrelationFunctionOrderN(ALLOCATE);
  SampleMolecularOrientationAutoCorrelationFunctionOrderN(ALLOCATE);
  SampleBondOrientationAutoCorrelationFunctionOrderN(ALLOCATE);
  SampleMeanSquaredDisplacement(ALLOCATE);
  SampleVelocityAutoCorrelationFunction(ALLOCATE);
  SampleDensityProfile3DVTKGrid(ALLOCATE);
  SampleCationAndAdsorptionSites(ALLOCATE);
  SampleDcTSTConfigurationFiles(ALLOCATE);
  SamplePDBMovies(ALLOCATE,-1);


  // initialize
  InitializesEnergiesAllSystems();
  InitializeSmallMCStatisticsAllSystems();
  InitializeMCMovesStatisticsAllSystems();

  // compute initial energy
  CalculateTotalEnergyAllSystems();


  // Monte-Carlo initializing period to achieve a rapid equilibration of the positions
  SimulationStage=POSITION_INITIALIZATION;
  for(CurrentCycle=0;CurrentCycle<NumberOfInitializationCycles;CurrentCycle++)
  {
    if((CurrentCycle%PrintEvery)==0)
      for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
        PrintIntervalStatusInit(CurrentCycle,NumberOfInitializationCycles,OutputFilePtr[CurrentSystem]);

    for(j=0;j<NumberOfSystems*NumberOfComponents;j++)
    {
      // choose a random system
      CurrentSystem=(int)(RandomNumber()*(REAL)NumberOfSystems);

      for(k=0;k<MAX2(MinimumInnerCycles,NumberOfAdsorbateMolecules[CurrentSystem]);k++)
      {
        // choose a random component
        CurrentComponent=(int)(RandomNumber()*(REAL)NumberOfComponents);

        // choose any of the MC moves randomly with the selected probability
        ran=RandomNumber();

        if(ran<Components[CurrentComponent].ProbabilityTranslationMove)
          TranslationMove();
        else if(ran<Components[CurrentComponent].ProbabilityRandomTranslationMove)
          RandomTranslationMove();
        else if(ran<Components[CurrentComponent].ProbabilityRotationMove)
          RotationMove();
        else if(ran<Components[CurrentComponent].ProbabilityPartialReinsertionMove)
          PartialReinsertionMove();
        else if(ran<Components[CurrentComponent].ProbabilityReinsertionMove)
          ReinsertionMove();
        else if(ran<Components[CurrentComponent].ProbabilityReinsertionInPlaceMove)
          ReinsertionInPlaceMove();
        else if(ran<Components[CurrentComponent].ProbabilityReinsertionInPlaneMove)
          ReinsertionInPlaneMove();
        else if(ran<Components[CurrentComponent].ProbabilityIdentityChangeMove)
          IdentityChangeMove();
        else if(ran<Components[CurrentComponent].ProbabilitySwapMove)
        {
          if(RandomNumber()<0.5) SwapAddMove();
          else SwapRemoveMove();
        }
        else if(ran<Components[CurrentComponent].ProbabilityCFSwapLambdaMove)
          CFSwapLambaMove();
        else if(ran<Components[CurrentComponent].ProbabilityCBCFSwapLambdaMove)
          CBCFSwapLambaMove();
        else if(ran<Components[CurrentComponent].ProbabilityWidomMove)
          ;
        else if(ran<Components[CurrentComponent].ProbabilitySurfaceAreaMove)
          ;
        else if(ran<Components[CurrentComponent].ProbabilityGibbsChangeMove)
          GibbsParticleTransferMove();
        else if(ran<Components[CurrentComponent].ProbabilityGibbsIdentityChangeMove)
          GibbsIdentityChangeMove();
        else if(ran<Components[CurrentComponent].ProbabilityCFGibbsChangeMove)
          CFGibbsParticleTransferMove();
        else if(ran<Components[CurrentComponent].ProbabilityCBCFGibbsChangeMove)
          CBCFGibbsParticleTransferMove();
        else if(ran<Components[CurrentComponent].ProbabilityParallelTemperingMove)
          ParallelTemperingMove();
        else if(ran<Components[CurrentComponent].ProbabilityHyperParallelTemperingMove)
          HyperParallelTemperingMove();
        else if(ran<Components[CurrentComponent].ProbabilityParallelMolFractionMove)
          ParallelMolFractionMove();
        else if(ran<Components[CurrentComponent].ProbabilityChiralInversionMove)
          ChiralInversionMove();
        else if(ran<Components[CurrentComponent].ProbabilityHybridNVEMove)
          HybridNVEMove();
        else if(ran<Components[CurrentComponent].ProbabilityHybridNPHMove)
          HybridNPHMove();
        else if(ran<Components[CurrentComponent].ProbabilityHybridNPHPRMove)
          HybridNPHPRMove();
        else if(ran<Components[CurrentComponent].ProbabilityVolumeChangeMove)
          VolumeMove();
        else if(ran<Components[CurrentComponent].ProbabilityBoxShapeChangeMove)
          BoxShapeChangeMove();
        else if(ran<Components[CurrentComponent].ProbabilityGibbsVolumeChangeMove)
          GibbsVolumeMove();
        else if(ran<Components[CurrentComponent].ProbabilityFrameworkChangeMove)
          FrameworkChangeMove();
        else if(ran<Components[CurrentComponent].ProbabilityFrameworkShiftMove)
          FrameworkShiftMove();
      }
    }

    if(CurrentCycle%PrintEvery==0)
    {
      for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
      {
        OptimizeVolumeChangeAcceptence();
        OptimizeTranslationAcceptence();
        if(Framework[CurrentSystem].FrameworkModel==FLEXIBLE)
        {
          OptimizeFrameworkChangeAcceptence();
          OptimizeFrameworkShiftAcceptence();
        }
        RescaleMaximumRotationAnglesSmallMC();
      }
    }

    if((CurrentCycle>0)&&(WriteBinaryRestartFileEvery>0)&&(CurrentCycle%WriteBinaryRestartFileEvery==0))
      WriteBinaryRestartFiles();

    ContinueAfterCrashLabel1:;
  }

  // initialize
  InitializesEnergiesAllSystems();
  InitializeSmallMCStatisticsAllSystems();
  InitializeMCMovesStatisticsAllSystems();

  SimulationStage=VELOCITY_SCALING;
  if(ReinitializeVelocities)
  {
    for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
    {
      InitializeAdsorbateVelocities();
      InitializeCationVelocities();
      if(Framework[CurrentSystem].FrameworkModel==FLEXIBLE)
        InitializeFrameworkVelocities();

      RemoveVelocityDrift();
      //AdjustSystemAngularRotationToZero();
    }
  }

  //InitializeNoseHooverCurrentSystem();
  InitializeNoseHooverAllSystems();

  // compute initial energy
  InitializeForcesAllSystems();

  // Molecular-Dynamics initializing period to remove excessive kinetic energy due to
  // poor equilibration of the positions (use with caution)
  // Velocity-scaling scales the velocities at each time step to the desired temperature
/*
  for(CurrentCycle=0;CurrentCycle<NumberOfVelocityScalingCycles;CurrentCycle++)
  {
    for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
    {
      // scake the velocity to the exact temperature
      AdjustVelocitiesToTemperature();

      // regularly output system status and restart files
      if(CurrentCycle%PrintEvery==0)
      {
        PrintIntervalStatusEquilibration(CurrentCycle,NumberOfEquilibrationCycles,OutputFilePtr[CurrentSystem]);
        PrintRestartFile();
      }
      // evolve the system a full time-step
      Integration();
    }
  }
*/

  // set the current ensemble to the initialization ensemble
  for(i=0;i<NumberOfSystems;i++)
    Ensemble[i]=InitEnsemble[i];

  InitializesEnergyAveragesAllSystems();

  for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
  {
    ReferenceEnergy[CurrentSystem]=ConservedEnergy[CurrentSystem];
    Drift[CurrentSystem]=0.0;
  }

  // Molecular-Dynamics initializing period to achieve a rapid equilibration of the velocities
  SimulationStage=VELOCITY_EQUILIBRATION;
  for(CurrentCycle=0;CurrentCycle<NumberOfEquilibrationCycles;CurrentCycle++)
  {
    for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
    {
      // regularly output system status and restart files
      if(CurrentCycle%PrintEvery==0)
      {
        PrintIntervalStatusEquilibration(CurrentCycle,NumberOfEquilibrationCycles,OutputFilePtr[CurrentSystem]);
        PrintRestartFile();
      }

      // insertion/deletion for the osmotic-ensemble
      if(Ensemble[CurrentSystem]==MuPT)
      {
        CurrentComponent=(int)(RandomNumber()*NumberOfComponents);
        if((CurrentCycle%(Components[CurrentComponent].SwapEvery)==0)&&
           (Components[CurrentComponent].ProbabilitySwapMove>0.0))
        {
          if(RandomNumber()<0.5) SwapAddMove();
          else SwapRemoveMove();
        }
      }

      // evolve the system a full time-step
      Integration();

      // prevent heating of the core-shells
      AdjustCoreShellVelocities();

      // update the current energy-drift
      Drift[CurrentSystem]+=fabs((ConservedEnergy[CurrentSystem]-ReferenceEnergy[CurrentSystem])/ReferenceEnergy[CurrentSystem]);
    }

    if((CurrentCycle>0)&&(WriteBinaryRestartFileEvery>0)&&(CurrentCycle%WriteBinaryRestartFileEvery==0))
      WriteBinaryRestartFiles();

    ContinueAfterCrashLabel2:;
  }


  // initialize sampling-routines at the start of the production run
  for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
  {
    Ensemble[CurrentSystem]=RunEnsemble[CurrentSystem];

    ReferenceEnergy[CurrentSystem]=ConservedEnergy[CurrentSystem];
    Drift[CurrentSystem]=0.0;

    SampleRadialDistributionFunction(INITIALIZE);
    SampleProjectedLengthsDistributionFunction(INITIALIZE);
    SampleProjectedAnglesDistributionFunction(INITIALIZE);
    SampleNumberOfMoleculesHistogram(INITIALIZE);
    SamplePositionHistogram(INITIALIZE);
    SampleFreeEnergyProfile(INITIALIZE);
    SampleEndToEndDistanceHistogram(INITIALIZE);
    SampleEnergyHistogram(INITIALIZE);
    SampleFrameworkSpacingHistogram(INITIALIZE);
    SampleResidenceTimes(INITIALIZE);
    SampleDistanceHistogram(INITIALIZE);
    SampleBendAngleHistogram(INITIALIZE);
    SampleDihedralAngleHistogram(INITIALIZE);
    SampleAngleBetweenPlanesHistogram(INITIALIZE);
    SampleMoleculePropertyHistogram(INITIALIZE);
    SampleInfraRedSpectra(INITIALIZE);
    SampleMeanSquaredDisplacementOrderN(INITIALIZE);
    SampleVelocityAutoCorrelationFunctionOrderN(INITIALIZE);
    SampleRotationalVelocityAutoCorrelationFunctionOrderN(INITIALIZE);
    SampleMolecularOrientationAutoCorrelationFunctionOrderN(INITIALIZE);
    SampleBondOrientationAutoCorrelationFunctionOrderN(INITIALIZE);
    SampleMeanSquaredDisplacement(INITIALIZE);
    SampleVelocityAutoCorrelationFunction(INITIALIZE);
    SampleDensityProfile3DVTKGrid(INITIALIZE);
    SampleCationAndAdsorptionSites(INITIALIZE);
    SampleDcTSTConfigurationFiles(INITIALIZE);
    SamplePDBMovies(INITIALIZE,-1);
  }

  // Molecular-Dynamics production run
  // loop over the amount of production cycles (MD integration steps)
  SimulationStage=PRODUCTION;
  for(CurrentCycle=0;CurrentCycle<NumberOfCycles;CurrentCycle++)
  {
    // detect erroneous chirality changes
    for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
      CheckChiralityMolecules();

    // loop over all the systems and handle one by one
    for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
    {
      // update all the average energies
      UpdateEnergyAveragesCurrentSystem();

      if(CurrentCycle%PrintPropertiesEvery==0)
        PrintPropertyStatus(CurrentCycle,NumberOfCycles,OutputFilePtr[CurrentSystem]);

      if(CurrentCycle%PrintEvery==0)
      {
        PrintIntervalStatus(CurrentCycle,NumberOfCycles,OutputFilePtr[CurrentSystem]);
        PrintRestartFile();
      }

      // insertion/deletion for the osmotic-ensemble
      if(Ensemble[CurrentSystem]==MuPT)
      {
        CurrentComponent=(int)(RandomNumber()*NumberOfComponents);
        if((CurrentCycle%(Components[CurrentComponent].SwapEvery)==0)&&
           (Components[CurrentComponent].FractionOfSwapMove>0.0))
        {
          if(RandomNumber()<0.5) SwapAddMove();
          else SwapRemoveMove();
        }
      }

      for(CurrentComponent=0;CurrentComponent<NumberOfComponents;CurrentComponent++)
      {
        if(Components[CurrentComponent].FractionOfWidomMove>0.0)
          WidomMove();
      }

      // evolve the system a full time step
      Integration();

      // update the current energy-drift
      Drift[CurrentSystem]+=fabs((ConservedEnergy[CurrentSystem]-ReferenceEnergy[CurrentSystem])/
            ReferenceEnergy[CurrentSystem]);

      if(Drift[CurrentSystem]/(CurrentCycle+1.0)>1e2)
      {
        fprintf(OutputFilePtr[CurrentSystem],"\n\nERROR: unstable integration (energy drift %g > 1e2, simulation stopped)\n\n",Drift[CurrentSystem]/(CurrentCycle+1.0));
        fprintf(OutputFilePtr[CurrentSystem],"Check that: 1) all interaction are defined properly\n");
        fprintf(OutputFilePtr[CurrentSystem],"            2) the time step is not too large\n");
        fprintf(OutputFilePtr[CurrentSystem],"            3) the system is equilibrated\n\n");
        fflush(OutputFilePtr[CurrentSystem]);
        exit(0);
      }
    }

    for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
    {
      SampleRadialDistributionFunction(SAMPLE);
      SampleProjectedLengthsDistributionFunction(SAMPLE);
      SampleProjectedAnglesDistributionFunction(SAMPLE);
      SampleNumberOfMoleculesHistogram(SAMPLE);
      SamplePositionHistogram(SAMPLE);
      SampleFreeEnergyProfile(SAMPLE);
      SampleEndToEndDistanceHistogram(SAMPLE);
      SampleEnergyHistogram(SAMPLE);
      SampleFrameworkSpacingHistogram(SAMPLE);
      SampleResidenceTimes(SAMPLE);
      SampleDistanceHistogram(SAMPLE);
      SampleBendAngleHistogram(SAMPLE);
      SampleDihedralAngleHistogram(SAMPLE);
      SampleAngleBetweenPlanesHistogram(SAMPLE);
      SampleMoleculePropertyHistogram(SAMPLE);
      SampleInfraRedSpectra(SAMPLE);
      SampleMeanSquaredDisplacementOrderN(SAMPLE);
      SampleVelocityAutoCorrelationFunctionOrderN(SAMPLE);
      SampleRotationalVelocityAutoCorrelationFunctionOrderN(SAMPLE);
      SampleMolecularOrientationAutoCorrelationFunctionOrderN(SAMPLE);
      SampleBondOrientationAutoCorrelationFunctionOrderN(SAMPLE);
      SampleMeanSquaredDisplacement(SAMPLE);
      SampleVelocityAutoCorrelationFunction(SAMPLE);
      SampleDensityProfile3DVTKGrid(SAMPLE);
      SampleCationAndAdsorptionSites(SAMPLE);
      SampleDcTSTConfigurationFiles(SAMPLE);
      SamplePDBMovies(SAMPLE,-1);
    }

    if((CurrentCycle>0)&&(WriteBinaryRestartFileEvery>0)&&(CurrentCycle%WriteBinaryRestartFileEvery==0))
      WriteBinaryRestartFiles();

    ContinueAfterCrashLabel3:;

    for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
    {
      // regulary output sampling function
      SampleRadialDistributionFunction(PRINT);
      SampleProjectedLengthsDistributionFunction(PRINT);
      SampleProjectedAnglesDistributionFunction(PRINT);
      SampleNumberOfMoleculesHistogram(PRINT);
      SamplePositionHistogram(PRINT);
      SampleFreeEnergyProfile(PRINT);
      SampleEndToEndDistanceHistogram(PRINT);
      SampleEnergyHistogram(PRINT);
      SampleFrameworkSpacingHistogram(PRINT);
      SampleResidenceTimes(PRINT);
      SampleDistanceHistogram(PRINT);
      SampleBendAngleHistogram(PRINT);
      SampleDihedralAngleHistogram(PRINT);
      SampleAngleBetweenPlanesHistogram(PRINT);
      SampleMoleculePropertyHistogram(PRINT);
      SampleInfraRedSpectra(PRINT);
      SampleMeanSquaredDisplacementOrderN(PRINT);
      SampleVelocityAutoCorrelationFunctionOrderN(PRINT);
      SampleRotationalVelocityAutoCorrelationFunctionOrderN(PRINT);
      SampleMolecularOrientationAutoCorrelationFunctionOrderN(PRINT);
      SampleBondOrientationAutoCorrelationFunctionOrderN(PRINT);
      SampleMeanSquaredDisplacement(PRINT);
      SampleVelocityAutoCorrelationFunction(PRINT);
      SampleDensityProfile3DVTKGrid(PRINT);
      SampleCationAndAdsorptionSites(PRINT);
      SampleDcTSTConfigurationFiles(PRINT);
      if(Movies[CurrentSystem]&&(CurrentCycle%WriteMoviesEvery[CurrentSystem]==0))
        SamplePDBMovies(PRINT,-1);
    }
  }

  if(WriteBinaryRestartFileEvery>0)
    WriteBinaryRestartFiles();

  // finalize and clean up
  for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
  {
    SampleRadialDistributionFunction(FINALIZE);
    SampleProjectedLengthsDistributionFunction(FINALIZE);
    SampleProjectedAnglesDistributionFunction(FINALIZE);
    SampleNumberOfMoleculesHistogram(FINALIZE);
    SamplePositionHistogram(FINALIZE);
    SampleFreeEnergyProfile(FINALIZE);
    SampleEndToEndDistanceHistogram(FINALIZE);
    SampleEnergyHistogram(FINALIZE);
    SampleFrameworkSpacingHistogram(FINALIZE);
    SampleResidenceTimes(FINALIZE);
    SampleDistanceHistogram(FINALIZE);
    SampleBendAngleHistogram(FINALIZE);
    SampleDihedralAngleHistogram(FINALIZE);
    SampleAngleBetweenPlanesHistogram(FINALIZE);
    SampleMoleculePropertyHistogram(FINALIZE);
    SampleInfraRedSpectra(FINALIZE);
    SampleMeanSquaredDisplacementOrderN(FINALIZE);
    SampleVelocityAutoCorrelationFunctionOrderN(FINALIZE);
    SampleRotationalVelocityAutoCorrelationFunctionOrderN(FINALIZE);
    SampleMolecularOrientationAutoCorrelationFunctionOrderN(FINALIZE);
    SampleBondOrientationAutoCorrelationFunctionOrderN(FINALIZE);
    SampleMeanSquaredDisplacement(FINALIZE);
    SampleVelocityAutoCorrelationFunction(FINALIZE);
    SampleDensityProfile3DVTKGrid(FINALIZE);
    SampleCationAndAdsorptionSites(FINALIZE);
    SampleDcTSTConfigurationFiles(FINALIZE);
    SamplePDBMovies(FINALIZE,-1);
  }

  // print post-status
  PrintPostSimulationStatus();
  CloseOutputFile();
}