Ejemplo n.º 1
0
int main(int argc, char* argv[])
{
  // Load the mesh.
  Mesh basemesh;
  H2DReader mloader;
  mloader.load("domain.mesh", &basemesh);

  // Initialize the meshes.
  Mesh mesh_flow, mesh_concentration;
  mesh_flow.copy(&basemesh);
  mesh_concentration.copy(&basemesh);

  for(unsigned int i = 0; i < INIT_REF_NUM_CONCENTRATION; i++)
    mesh_concentration.refine_all_elements(0);

  mesh_concentration.refine_towards_boundary(BDY_DIRICHLET_CONCENTRATION, INIT_REF_NUM_CONCENTRATION_BDY);

  for(unsigned int i = 0; i < INIT_REF_NUM_FLOW; i++)
    mesh_flow.refine_all_elements();

  // Initialize boundary condition types and spaces with default shapesets.
  // For the concentration.
  EssentialBCs bcs_concentration;
  
  bcs_concentration.add_boundary_condition(new DefaultEssentialBCConst(BDY_DIRICHLET_CONCENTRATION, CONCENTRATION_EXT));
  
  L2Space space_rho(&mesh_flow, P_INIT_FLOW);
  L2Space space_rho_v_x(&mesh_flow, P_INIT_FLOW);
  L2Space space_rho_v_y(&mesh_flow, P_INIT_FLOW);
  L2Space space_e(&mesh_flow, P_INIT_FLOW);
  // Space for concentration.
  H1Space space_c(&mesh_concentration, &bcs_concentration, P_INIT_CONCENTRATION);

  int ndof = Space::get_num_dofs(Hermes::vector<Space*>(&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e, &space_c));
  info("ndof: %d", ndof);

  // Initialize solutions, set initial conditions.
  InitialSolutionEulerDensity prev_rho(&mesh_flow, RHO_EXT);
  InitialSolutionEulerDensityVelX prev_rho_v_x(&mesh_flow, RHO_EXT * V1_EXT);
  InitialSolutionEulerDensityVelY prev_rho_v_y(&mesh_flow, RHO_EXT * V2_EXT);
  InitialSolutionEulerDensityEnergy prev_e(&mesh_flow, QuantityCalculator:: calc_energy(RHO_EXT, RHO_EXT * V1_EXT, RHO_EXT * V2_EXT, P_EXT, KAPPA));
  InitialSolutionConcentration prev_c(&mesh_concentration, 0.0);

  // Numerical flux.
  OsherSolomonNumericalFlux num_flux(KAPPA);

  // Initialize weak formulation.
  EulerEquationsWeakFormExplicitCoupled wf(&num_flux, KAPPA, RHO_EXT, V1_EXT, V2_EXT, P_EXT, BDY_SOLID_WALL,
    BDY_INLET, BDY_OUTLET, BDY_NATURAL_CONCENTRATION, &prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e, &prev_c, EPSILON);
  
  wf.set_time_step(time_step);

  // Initialize the FE problem.
  bool is_linear = true;
  DiscreteProblem dp(&wf, Hermes::vector<Space*>(&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e, &space_c), is_linear);

  // If the FE problem is in fact a FV problem.
  //if(P_INIT == 0) dp.set_fvm();  

  // Filters for visualization of Mach number, pressure and entropy.
  MachNumberFilter Mach_number(Hermes::vector<MeshFunction*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e), KAPPA);
  PressureFilter pressure(Hermes::vector<MeshFunction*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e), KAPPA);
  EntropyFilter entropy(Hermes::vector<MeshFunction*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e), KAPPA, RHO_EXT, P_EXT);

  /*
  ScalarView pressure_view("Pressure", new WinGeom(0, 0, 600, 300));
  ScalarView Mach_number_view("Mach number", new WinGeom(700, 0, 600, 300));
  ScalarView entropy_production_view("Entropy estimate", new WinGeom(0, 400, 600, 300));

  ScalarView s5("Concentration", new WinGeom(700, 400, 600, 300));
  */
  
  ScalarView s1("1", new WinGeom(0, 0, 600, 300));
  ScalarView s2("2", new WinGeom(700, 0, 600, 300));
  ScalarView s3("3", new WinGeom(0, 400, 600, 300));
  ScalarView s4("4", new WinGeom(700, 400, 600, 300));
  ScalarView s5("Concentration", new WinGeom(350, 200, 600, 300));
  

  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix* matrix = create_matrix(matrix_solver);
  Vector* rhs = create_vector(matrix_solver);
  Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

  // Set up CFL calculation class.
  CFLCalculation CFL(CFL_NUMBER, KAPPA);

  // Set up Advection-Diffusion-Equation stability calculation class.
  ADEStabilityCalculation ADES(ADVECTION_STABILITY_CONSTANT, DIFFUSION_STABILITY_CONSTANT, EPSILON);

  int iteration = 0; double t = 0;
  for(t = 0.0; t < 83.0; t += time_step) {
    info("---- Time step %d, time %3.5f.", iteration++, t);

    // Set the current time step.
    wf.set_time_step(time_step);

    bool rhs_only = (iteration == 1 ? false : true);
    // Assemble stiffness matrix and rhs or just rhs.
    if (rhs_only == false) {
      info("Assembling the stiffness matrix and right-hand side vector.");
      dp.assemble(matrix, rhs);
    }

    else {
      info("Assembling the right-hand side vector (only).");
      dp.assemble(NULL, rhs);
    }

    // Solve the matrix problem.
    info("Solving the matrix problem.");
    scalar* solution_vector = NULL;
    if(solver->solve()) {
      solution_vector = solver->get_solution();
      Solution::vector_to_solutions(solution_vector, Hermes::vector<Space *>(&space_rho, &space_rho_v_x, 
      &space_rho_v_y, &space_e, &space_c), Hermes::vector<Solution *>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e, &prev_c));
    }
    else
    error ("Matrix solver failed.\n");

    if(SHOCK_CAPTURING) {
      DiscontinuityDetector discontinuity_detector(Hermes::vector<Space *>(&space_rho, &space_rho_v_x, 
        &space_rho_v_y, &space_e), Hermes::vector<Solution *>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e));

      std::set<int> discontinuous_elements = discontinuity_detector.get_discontinuous_element_ids(DISCONTINUITY_DETECTOR_PARAM);

      FluxLimiter flux_limiter(solution_vector, Hermes::vector<Space *>(&space_rho, &space_rho_v_x, 
        &space_rho_v_y, &space_e), Hermes::vector<Solution *>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e));

      flux_limiter.limit_according_to_detector(discontinuous_elements);
    }

    util_time_step = time_step;

    if((iteration - 1) % CFL_CALC_FREQ == 0)
      CFL.calculate(Hermes::vector<Solution *>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e), &mesh_flow, util_time_step);

    time_step = util_time_step;

    ADES.calculate(Hermes::vector<Solution *>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y), &mesh_concentration, util_time_step);

    if(util_time_step < time_step)
      time_step = util_time_step;

    // Visualization.
    if((iteration - 1) % EVERY_NTH_STEP == 0) {
      // Hermes visualization.
      if(HERMES_VISUALIZATION) {
        /*
        Mach_number.reinit();
        pressure.reinit();
        entropy.reinit();
        pressure_view.show(&pressure);
        entropy_production_view.show(&entropy);
        Mach_number_view.show(&Mach_number);
        s5.show(&prev_c);
        */
        s1.show(&prev_rho);
        s2.show(&prev_rho_v_x);
        s3.show(&prev_rho_v_y);
        s4.show(&prev_e);
        s5.show(&prev_c);
        //s5.wait_for_close();
        
      }
      // Output solution in VTK format.
      if(VTK_VISUALIZATION) {
        pressure.reinit();
        Mach_number.reinit();
        Linearizer lin;
        char filename[40];
        sprintf(filename, "pressure-%i.vtk", iteration - 1);
        lin.save_solution_vtk(&pressure, filename, "Pressure", false);
        sprintf(filename, "pressure-3D-%i.vtk", iteration - 1);
        lin.save_solution_vtk(&pressure, filename, "Pressure", true);
        sprintf(filename, "Mach number-%i.vtk", iteration - 1);
        lin.save_solution_vtk(&Mach_number, filename, "MachNumber", false);
        sprintf(filename, "Mach number-3D-%i.vtk", iteration - 1);
        lin.save_solution_vtk(&Mach_number, filename, "MachNumber", true);
        sprintf(filename, "Concentration-%i.vtk", iteration - 1);
        lin.save_solution_vtk(&prev_c, filename, "Concentration", true);
        sprintf(filename, "Concentration-3D-%i.vtk", iteration - 1);
        lin.save_solution_vtk(&prev_c, filename, "Concentration", true);
 
      }
    }
  }
  
  /*
  pressure_view.close();
  entropy_production_view.close();
  Mach_number_view.close();
  s5.close();
  */
  
  s1.close();
  s2.close();
  s3.close();
  s4.close();
  s5.close();

  return 0;
}
inline T bessel_y_derivative_small_z_series(T v, T x, const Policy& pol)
{
   BOOST_MATH_STD_USING
   static const char* function = "bessel_y_derivative_small_z_series<%1%>(%1%,%1%)";
   T prefix;
   T gam;
   T p = log(x / 2);
   T scale = 1;
   bool need_logs = (v >= boost::math::max_factorial<T>::value) || (boost::math::tools::log_max_value<T>() / v < fabs(p));
   if (!need_logs)
   {
      gam = boost::math::tgamma(v, pol);
      p = pow(x / 2, v + 1) * 2;
      if (boost::math::tools::max_value<T>() * p < gam)
      {
         scale /= gam;
         gam = 1;
         if (boost::math::tools::max_value<T>() * p < gam)
         {
            // This term will overflow to -INF, when combined with the series below it becomes +INF:
            return boost::math::policies::raise_overflow_error<T>(function, 0, pol);
         }
      }
      prefix = -gam / (boost::math::constants::pi<T>() * p);
   }
   else
   {
      gam = boost::math::lgamma(v, pol);
      p = (v + 1) * p + constants::ln_two<T>();
      prefix = gam - log(boost::math::constants::pi<T>()) - p;
      if (boost::math::tools::log_max_value<T>() < prefix)
      {
         prefix -= log(boost::math::tools::max_value<T>() / 4);
         scale /= (boost::math::tools::max_value<T>() / 4);
         if (boost::math::tools::log_max_value<T>() < prefix)
         {
            return boost::math::policies::raise_overflow_error<T>(function, 0, pol);
         }
      }
      prefix = -exp(prefix);
   }
   bessel_y_derivative_small_z_series_term_a<T, Policy> s(v, x);
   boost::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<Policy>();
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))
   T zero = 0;
   T result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter, zero);
#else
   T result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter);
#endif
   boost::math::policies::check_series_iterations<T>("boost::math::bessel_y_derivative_small_z_series<%1%>(%1%,%1%)", max_iter, pol);
   result *= prefix;

   p = pow(x / 2, v - 1) / 2;
   if (!need_logs)
   {
      prefix = boost::math::tgamma(-v, pol) * boost::math::cos_pi(v) * p / boost::math::constants::pi<T>();
   }
   else
   {
      int sgn;
      prefix = boost::math::lgamma(-v, &sgn, pol) + (v - 1) * log(x / 2) - constants::ln_two<T>();
      prefix = exp(prefix) * sgn / boost::math::constants::pi<T>();
   }
   bessel_y_derivative_small_z_series_term_b<T, Policy> s2(v, x);
   max_iter = boost::math::policies::get_max_series_iterations<Policy>();
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))
   T b = boost::math::tools::sum_series(s2, boost::math::policies::get_epsilon<T, Policy>(), max_iter, zero);
#else
   T b = boost::math::tools::sum_series(s2, boost::math::policies::get_epsilon<T, Policy>(), max_iter);
#endif
   result += scale * prefix * b;
   return result;
}
Ejemplo n.º 3
0
int main(int argc, char **argv)
{
 PetscInitialize(&argc,&argv,PETSC_NULL,PETSC_NULL);
 //PetscInitializeNoArguments();
 int iter = 1;

 double Re = 10;
 double We = 1;
 double c1 = 1.0;  // lagrangian
 double c2 = 0.0;  // smooth vel
 double c3 = 0.0;  // smooth coord (fujiwara)
 double d1 = 1.0;  // surface tangent velocity u_n=u-u_t 
 double d2 = 0.0;  // surface smooth cord (fujiwara)
 double alpha = 1;

 double mu_in = 1.0;
 double mu_out = 0.1;

 double rho_in = 1.0;
 double rho_out = 0.01;

 double cfl = 0.8;

 string meshFile = "0.20.msh";
 
 Solver *solverP = new PetscSolver(KSPGMRES,PCILU);
 Solver *solverV = new PetscSolver(KSPCG,PCICC);
 Solver *solverC = new PetscSolver(KSPCG,PCICC);

 const char *binFolder  = "./bin/";
 const char *vtkFolder  = "./vtk/";
 const char *mshFolder  = "./msh/";
 const char *datFolder  = "./dat/";
 string meshDir = (string) getenv("DATA_DIR");
 meshDir += "/gmsh/3d/torus/curvature/" + meshFile;
 const char *mesh = meshDir.c_str();

 Model3D m1;
 Simulator3D s1;

 if( *(argv+1) == NULL )     
 {
  cout << endl;
  cout << "--------------> STARTING FROM 0" << endl;
  cout << endl;

  const char *mesh1 = mesh;

  m1.readMSH(mesh1);
  m1.setInterfaceBC();
  m1.setTriEdge();
  m1.mesh2Dto3D();
  m1.setMapping();
#if NUMGLEU == 5
 m1.setMiniElement();
#else
 m1.setQuadElement();
#endif
  m1.setSurfaceConfig();
  m1.setInitSurfaceVolume();
  m1.setInitSurfaceArea();
  m1.setGenericBC();

  s1(m1);

  s1.setRe(Re);
  s1.setWe(We);
  s1.setC1(c1);
  s1.setC2(c2);
  s1.setC3(c3);
  s1.setD1(d1);
  s1.setD2(d2);
  s1.setAlpha(alpha);
  s1.setMu(mu_in,mu_out);
  s1.setRho(rho_in,rho_out);
  s1.setCfl(cfl);
  s1.init();
  s1.setDtALETwoPhase();
  s1.setSolverPressure(solverP);
  s1.setSolverVelocity(solverV);
  s1.setSolverConcentration(solverC);
 }
 else  
 {
  cout << endl;
  cout << "--------------> RE-STARTING..." << endl;
  cout << endl;

  // load surface mesh
  string aux = *(argv+2);
  string file = (string) "./msh/newMesh-" + *(argv+2) + (string) ".msh";
  const char *mesh2 = file.c_str();
  m1.readMSH(mesh2);
  m1.setInterfaceBC();
  m1.setTriEdge();
  m1.mesh2Dto3D();

  s1(m1);

  // load 3D mesh
  file = (string) "./vtk/sim-" + *(argv+2) + (string) ".vtk";
  const char *vtkFile = file.c_str();

  m1.readVTK(vtkFile);
  m1.setMapping();
#if NUMGLEU == 5
  m1.setMiniElement();
#else
  m1.setQuadElement();
#endif
  m1.readVTKHeaviside(vtkFile);
  m1.setSurfaceConfig();
  m1.setInitSurfaceVolume();
  m1.setInitSurfaceArea();
  m1.setGenericBC();

  s1(m1);

  s1.setSolverPressure(solverP);
  s1.setSolverVelocity(solverV);
  s1.setSolverConcentration(solverC);

  iter = s1.loadSolution("./","sim",atoi(*(argv+2)));
 }

 // Point's distribution
 Helmholtz3D h1(m1);
 h1.setBC();
 h1.initRisingBubble();
 h1.assemble();
 h1.setk(0.2);
 h1.matMountC();
 h1.setUnCoupledCBC(); 
 h1.setCRHS();
 h1.unCoupledC();
 //h1.saveVTK(vtkFolder,"edge");
 h1.setModel3DEdgeSize();

 InOut save(m1,s1); // cria objeto de gravacao
 save.saveVTK(vtkFolder,"geometry");
 save.saveVTKSurface(vtkFolder,"geometry");
 save.saveMeshInfo(datFolder);
 save.saveInfo(datFolder,"info",mesh);

 int nIter = 3000;
 int nReMesh = 1;
 for( int i=1;i<=nIter;i++ )
 {
  for( int j=0;j<nReMesh;j++ )
  {

   cout << color(none,magenta,black);
   cout << "____________________________________ Iteration: " 
	    << iter << endl << endl;
   cout << resetColor();

   s1.setDtALETwoPhase();

   InOut save(m1,s1); // cria objeto de gravacao
   save.printSimulationReport();

   //s1.stepLagrangian();
   s1.stepALE();
   s1.movePoints();
   s1.assemble();
   s1.matMount();
   s1.setUnCoupledBC();
   s1.setRHS();
   //s1.setGravity("-Z");
   //s1.setInterface();
   s1.setInterfaceGeo();
   s1.unCoupled();

   save.saveMSH(mshFolder,"newMesh",iter);
   save.saveVTK(vtkFolder,"sim",iter);
   save.saveVTKSurface(vtkFolder,"sim",iter);
   save.saveSol(binFolder,"sim",iter);
   save.saveBubbleInfo(datFolder);
   //save.chordalPressure(datFolder,"chordalPressure",iter);
   //save.crossSectionalVoidFraction(datFolder,"voidFraction",iter);

   s1.saveOldData();

   s1.timeStep();

   cout << color(none,magenta,black);
   cout << "________________________________________ END of " 
	    << iter << endl << endl;;
   cout << resetColor();

   iter++;
  }
  Helmholtz3D h2(m1,h1);
  h2.setBC();
  h2.initRisingBubble();
  h2.assemble();
  h2.setk(0.2);
  h2.matMountC();
  h2.setUnCoupledCBC(); 
  h2.setCRHS();
  h2.unCoupledC();
  h2.saveVTK(vtkFolder,"edge",iter-1);
  h2.saveChordalEdge(datFolder,"edge",iter-1);
  h2.setModel3DEdgeSize();

  Model3D mOld = m1; 

  /* *********** MESH TREATMENT ************* */
  // set normal and kappa values
  m1.setNormalAndKappa();
  m1.initMeshParameters();

  // 3D operations
  //m1.insert3dMeshPointsByDiffusion();
  m1.remove3dMeshPointsByDiffusion();
  //m1.removePointByVolume();
  //m1.removePointsByInterfaceDistance();
  //m1.remove3dMeshPointsByDistance();
  m1.remove3dMeshPointsByHeight();
  m1.delete3DPoints();

  // surface operations
  m1.smoothPointsByCurvature();

  m1.insertPointsByLength("flat");
  m1.contractEdgesByLength("flat");
  m1.flipTriangleEdges();

  m1.removePointsByNeighbourCheck();
  //m1.checkAngleBetweenPlanes();
  /* **************************************** */

  //m1.mesh2Dto3DOriginal();
  m1.mesh3DPoints();
  m1.setMapping();
#if NUMGLEU == 5
 m1.setMiniElement();
#else
 m1.setQuadElement();
#endif
  m1.setSurfaceConfig();
  m1.setGenericBC();

  Simulator3D s2(m1,s1);
  s2.applyLinearInterpolation(mOld);
  s1 = s2;
  s1.setSolverPressure(solverP);
  s1.setSolverVelocity(solverV);
  s1.setSolverConcentration(solverC);

  InOut saveEnd(m1,s1); // cria objeto de gravacao
  saveEnd.printMeshReport();
  saveEnd.saveMeshInfo(datFolder);
 }

 PetscFinalize();
 return 0;
}
int main( int argc, char** argv ) {
	if( argc < 6 || argc & 1) {
		std::cout << "usage: " << argv[0] 
			<< " <threshold> <nions> <nbright> [<n> <template> ...]" 
			<< std::endl;
		return -1;
	}

	size_t threshold = 0, nimages = 0, nions = 0, nbright = 0;
	std::stringstream s( argv[1] );
	s >> threshold;

	std::stringstream s3( argv[2] );
	s3 >> nions;

	std::stringstream s4( argv[3] );
	s4 >> nbright;

	std::vector<IonDetector::result_type> res;

	size_t argc_i = 4;
	while( argc_i < argc ) {
	std::stringstream s2( argv[argc_i++] );
	s2 >> nimages;
	for( size_t i = 0; i < nimages; ++i ) {

		char image_name[1024];
		sprintf( image_name, argv[argc_i], i );

		image_type data = load_file( image_name );
		if( !data.extents.first ) { 	// Failed to load image
			return -1;
		}
		
		IonDetector det;
		det.blob_threshold = threshold;
		image_type result = det.hot_pixels( data );
		save_file( "hot.fits", result );

		IonDetector::result_type results = det( result );
		res.push_back( results );
		
		if( results.size() > nbright ) {
			std::cout << "Too many ions in: " << image_name << std::endl;
		} else if( results.size() < nbright ) {
			std::cout << "Too few ions in: " << image_name << std::endl;
		}

	}
	++argc_i;
	}

	std::vector< std::pair< size_t, IonData > > positions;
	for( size_t i = 0; i < res.size(); ++i ) {
		if( res[i].size() != nbright )
			continue;

		for( size_t ion = 0; ion < res[i].size(); ++ion ) {
			size_t pos = 0;
			for( ; pos < positions.size(); ++pos ) {
				if( fabs( positions[pos].second.x - res[i][ion].x ) < 6 &&
					fabs( positions[pos].second.y - res[i][ion].y ) < 6 ) {
					++ positions[pos].first;
					break;
				}
			}
			if( pos == positions.size() )
				positions.push_back( std::make_pair( 1, res[i][ion] ) );
		}
	}

	std::sort( positions.begin(), positions.end() );
	std::reverse( positions.begin(), positions.end() );
	if( positions.size() > nions )
		positions.resize( nions );

	std::sort( positions.begin(), positions.end(), CompareSecond() );
	std::cout << "Detected ion locations: " << std::endl;
	for( size_t i = 0; i < positions.size(); ++i ) {
		std::cout << positions[i].second.x << ", " << positions[i].second.y
			<< std::endl;
	}

	std::cout << std::endl;
	std::cout << "Ion patterns: " << std::endl;
	std::vector< std::string > bits;
	for( size_t i = 0; i < res.size(); ++i ) {
		bits.push_back( "" );
		for( size_t pos = 0; pos < positions.size(); ++pos ) {
			size_t ion = 0;
			for( ; ion < res[i].size(); ++ion ) {
				if( fabs( positions[pos].second.x - res[i][ion].x ) < 6 &&
					fabs( positions[pos].second.y - res[i][ion].y ) < 6 ) {
					bits.back() += "1";
					break;
				}
			}

			if( ion == res[i].size() )
				bits.back() += "0";
		}

		std::cout << i << ":\t" << bits.back() << std::endl;
	}	

	size_t reorder = 0;
	std::string order = bits[0];
	for( size_t i = 1; i < bits.size(); ++i ) {
		if( bits[i] != order ) {
			++reorder;
			order = bits[i];
		}	
	}
	
	std::cout << "Reordered " << reorder << " times." << std::endl;
	std::cout << "Probability: " << (float)reorder / (nimages-1) << std::endl;
	return 0;
}
Ejemplo n.º 5
0
int main()
{
	{
		boost::shared_ptr<int> sp(new int(10));
		assert(sp.unique());

		boost::shared_ptr<int> sp2 = sp;
		assert(sp == sp2 && sp.use_count() == 2);

		*sp2 = 100;
		assert(*sp == 100);

		sp.reset();
		assert(!sp);

		boost::shared_ptr<int> p(new int(100));
		shared s1(p), s2(p);

		s1.print();
		s2.print();

		*p = 20;
		print_func(p);
		s1.print();
	}

	{
		//factory function
		//template<class T,class... Args>
		//boost::shared_ptr<T> boost::make_shared(Args && ... args);
		boost::shared_ptr<std::string> sp = 
			boost::make_shared<std::string>("make_shared");
		boost::shared_ptr<std::vector<int> > spv =
			boost::make_shared<std::vector<int> >(10,2);
		assert(spv->size() == 10);
	}

	{
		typedef std::vector<boost::shared_ptr<int> > vs;
		vs v(10);

		int i = 0;
		for(vs::iterator pos=v.begin();pos!=v.end();++pos)
		{
			(*pos) = boost::make_shared<int>(++i);
			std::cout << *(*pos) << ", ";
		}
		std::cout << std::endl;

		boost::shared_ptr<int> p = v[9];
		*p = 100;
		std::cout << *v[9] << std::endl;

		for(auto& ptr : v)
		{
			ptr = boost::make_shared<int>(++i);
			std::cout << *ptr << ", ";
		}
		std::cout << std::endl;
	}

	{
		//bridge pattern

		sample s;
		s.print();
	}

	return 0;
}
Ejemplo n.º 6
0
int QgsStringUtils::levenshteinDistance( const QString& string1, const QString& string2, bool caseSensitive )
{
  int length1 = string1.length();
  int length2 = string2.length();

  //empty strings? solution is trivial...
  if ( string1.isEmpty() )
  {
    return length2;
  }
  else if ( string2.isEmpty() )
  {
    return length1;
  }

  //handle case sensitive flag (or not)
  QString s1( caseSensitive ? string1 : string1.toLower() );
  QString s2( caseSensitive ? string2 : string2.toLower() );

  const QChar* s1Char = s1.constData();
  const QChar* s2Char = s2.constData();

  //strip out any common prefix
  int commonPrefixLen = 0;
  while ( length1 > 0 && length2 > 0 && *s1Char == *s2Char )
  {
    commonPrefixLen++;
    length1--;
    length2--;
    s1Char++;
    s2Char++;
  }

  //strip out any common suffix
  while ( length1 > 0 && length2 > 0 && s1.at( commonPrefixLen + length1 - 1 ) == s2.at( commonPrefixLen + length2 - 1 ) )
  {
    length1--;
    length2--;
  }

  //fully checked either string? if so, the answer is easy...
  if ( length1 == 0 )
  {
    return length2;
  }
  else if ( length2 == 0 )
  {
    return length1;
  }

  //ensure the inner loop is longer
  if ( length1 > length2 )
  {
    qSwap( s1, s2 );
    qSwap( length1, length2 );
  }

  //levenshtein algorithm begins here
  QVector< int > col;
  col.fill( 0, length2 + 1 );
  QVector< int > prevCol;
  prevCol.reserve( length2 + 1 );
  for ( int i = 0; i < length2 + 1; ++i )
  {
    prevCol << i;
  }
  const QChar* s2start = s2Char;
  for ( int i = 0; i < length1; ++i )
  {
    col[0] = i + 1;
    s2Char = s2start;
    for ( int j = 0; j < length2; ++j )
    {
      col[j + 1] = qMin( qMin( 1 + col[j], 1 + prevCol[1 + j] ), prevCol[j] + (( *s1Char == *s2Char ) ? 0 : 1 ) );
      s2Char++;
    }
    col.swap( prevCol );
    s1Char++;
  }
  return prevCol[length2];
}
Ejemplo n.º 7
0
QString QgsStringUtils::longestCommonSubstring( const QString& string1, const QString& string2, bool caseSensitive )
{
  if ( string1.isEmpty() || string2.isEmpty() )
  {
    //empty strings, solution is trivial...
    return QString();
  }

  //handle case sensitive flag (or not)
  QString s1( caseSensitive ? string1 : string1.toLower() );
  QString s2( caseSensitive ? string2 : string2.toLower() );

  if ( s1 == s2 )
  {
    //another trivial case, identical strings
    return s1;
  }

  int* currentScores = new int [ s2.length()];
  int* previousScores = new int [ s2.length()];
  int maxCommonLength = 0;
  int lastMaxBeginIndex = 0;

  const QChar* s1Char = s1.constData();
  const QChar* s2Char = s2.constData();
  const QChar* s2Start = s2Char;

  for ( int i = 0; i < s1.length(); ++i )
  {
    for ( int j = 0; j < s2.length(); ++j )
    {
      if ( *s1Char != *s2Char )
      {
        currentScores[j] = 0;
      }
      else
      {
        if ( i == 0 || j == 0 )
        {
          currentScores[j] = 1;
        }
        else
        {
          currentScores[j] = 1 + previousScores[j - 1];
        }

        if ( maxCommonLength < currentScores[j] )
        {
          maxCommonLength = currentScores[j];
          lastMaxBeginIndex = i;
        }
      }
      s2Char++;
    }
    qSwap( currentScores, previousScores );
    s1Char++;
    s2Char = s2Start;
  }
  delete [] currentScores;
  delete [] previousScores;
  return string1.mid( lastMaxBeginIndex - maxCommonLength + 1, maxCommonLength );
}
Ejemplo n.º 8
0
int main(int argc, char** argv)
{
    int exitCode = 0;

    /*
        create a pi|engine instance and initialize it.
        Initialization step loads and prepares the resources,
        initializes the engine and sets up game window
        unless application configuration states otherwise.
    */

    application app;

    gcString s = "Test_";
    gcString s2("shit");
    gcString s3 = gcString("coca") + "cola" + "[]";
    gcString s4 = "OLD";
    s4 = ">" + s + " " + s3 + " " + s4;   //Test cocacola[] OLD
    gcString s5 = gcString::gcFromInt(600);
    gcString s6 = s + s5 + " " + s2;
    s6 += " [";
    s6 += gcString::gcFromInt(60) + "]";

    for(int i=1;i<=100;i++)
    {
        s += gcString::gcFromInt(i) +",";
    }
    s += s + s;  //selfref test

    gcArray<gcString>* a = new gcArray<gcString>;
    a->setSize(13);

    // strings test
    (*a)[0] = "2500";
    (*a)[0].setw(8,"0");
    (*a)[1] = "Pesho";
    (*a)[1].setw(20,"[abc]");
    (*a)[2] = "acbdefghijkl";
    (*a)[2].setw(4);
    (*a)[3] = "5300";
    (*a)[3].setw(10);
    (*a)[4] = "681";
    (*a)[4].setw(10,"");   //case that is not allowed
    (*a)[5] = "123";
    (*a)[5].setw(10,"-");
    (*a)[6] = "Peter";
    (*a)[6].setrw(10,"-");
    (*a)[7] = "Peter";
    (*a)[7].setrw(3);
    (*a)[8] = "*-PeterSvP1870_test[100]-*X";
    (*a)[10] = (*a)[8].digits();
    (*a)[8] = (*a)[8].letters();
    (*a)[9] = (*a)[8].toLower();

    (*a)[11] = (*a)[8][0] + (*a)[8][1];

    (*a)[12] = "Pes*o";
    (*a)[12].setchar(3,"h");


    //show them:
    for(int i=0;i<a->count();i++)
    {
        gcString output;
        output = "a[" + gcString::gcFromInt(i) + "]= " + (*a)[i] + "\n";
        std::cout << output;
    }


    std::cout
        << "s = " << s  << std::endl
        << "s2= " << s2 << std::endl
        << "s3= " << s3 << std::endl
        << "s4= " << s4 << std::endl
        << "s5= " << s5 << std::endl
        << "s6= " << s6 << std::endl
    ;




#define PRINTINT(gc_array_var) \
    for(int i=0;i<gc_array_var.count();++i) \
        std::cout << "int[" << gcString::gcFromInt(i) << "] = " << gcString::gcFromInt( gc_array_var.gcAt(i) ) << std::endl;

#define PRINTS(gc_array_var) \
    for(int i=0;i<gc_array_var.count();++i) \
        std::cout << "string[" << gcString::gcFromInt(i) << "] = " << gc_array_var.gcAt(i) << std::endl;
    /*  gcArray test */

    // INT
    {
        gcArray<int> a;
        a.setSize(5);   //must add 5 zeros
        a << 1 << 2 << 50 << 100;   //and add 1,2,50,100 finally

        std::cout << "A:\n";
        PRINTINT(a);
        std::cout << "B:\n";
        gcArray<int>* b = a.clone();
        b->removeDuplicates();
        (*b) << 75;
        b->sort();
        PRINTINT( (*b) );
    }

    // STRING
    {
        gcArray<gcString> *a = new gcArray<gcString>, *b = new gcArray<gcString>, *c = a;
        //c i s same as a?
        (*c) << "1" << "2";
        (*a) << "3" << "4";
        (*c) << "5" << "6";
        a->setSize(10);
        (*c) << "5" << "Pi-Dev";
        (*a).insertAfter(5,"7");
        (*a).insertBefore(0,"begin");
        (*a).insertAfter( (*a).count()-1, "Appended" );

        //delete b;   //These calls must be somehow inserted by gameScript optimizer directly;

        b = a->clone(); //this will effectively invalidate b! There MUST be an memory manager
        b->removeDuplicates();
        c = c->clone();  //it is internally okay ;] C is now copy of a
        c = c->getDuplicates();  //c will only need to show "" and 5 now ;]
        b->sort();

        std::cout << "A[]:\n";
        PRINTS((*a));
        std::cout << "B[]:\n";
        PRINTS((*b));
        std::cout << "C[]:\n";
        PRINTS((*c));

    }

    {
        std::cout << "POINTER TYPE sort\n";
        gcArray<int*> a;
        a << new int(4) << new int(2) << new int(100) << new int(3);
        a.sort();

        std::cout<<"Count: "<<a.count() << "\n";

        for(int i=0;i<a.count();++i)
        {
            std::cout << *(a[i]) << std::endl;
        }
    }

    {
        gcArray<std::string>* a = new gcArray<std::string>;
        (*a) << "Dimo" << "Pesho" << "Atanas";

        a->sort();

        for(int i=0;i<a->count();++i)
        {
            std::cout << (*a)[i] << std::endl;
        }
    }

    {
        //2d Array test:
        gcArray2D<int> ia;
        ia.setSize(3,5);
        ia(0,1) = 10;
        ia(1,1) = 20;
        ia(2,4) = 45;
        for(int y=0;y<ia.yCount();++y)
        {
            for(int x=0;x<ia.xCount();++x)
                std::cout << gcString::gcFromInt(ia(x,y)).setw(6,".") << " ";
            std::cout << "\n";
        }
    }

    {
        /* 3D Array test */
        gcArray3D<gcString> a;
        a.setSize(5,4,3);
        for(int x=0;x<3;++x)
            for(int y=0;y<3;++y)
                a(x,y,2) = "Stone";

        a(0,0,0) = "Cloud";
        a(1,0,0) = "Cloud";
        a(0,0,1) = "Player";
        a(1,0,1) = "Item";
        a(1,1,1) = "Item";
        a(4,3,2) = "Bound";

        for(int z=0;z<a.zCount();++z)
        {
            std::cout<<"z = "<< gcString::gcFromInt(z) << "\n";
            for(int y=0;y<a.yCount();++y)
            {
                for(int x=0;x<a.xCount();++x)std::cout<<"["<<a(x,y,z).setw(6,"-")<<"]";
                std::cout<<"\n";
            }
            std::cout<<"\n";
        }
    }


#undef PRINTS
#undef PRINTINT

    if(app.init())exitCode = app.run();
    else std::cout
            << "Initialization failed with following error:\n"
            << app.lastException->text
            << "\n";

    std::cout<<"Application closed with exit code "<<exitCode<<"!\n\n";
    return exitCode;
}
void SecureDataMgrTests::testSecureDataManager()
{
	ByteString soPIN = "3132333435363738"; // "12345678"
	ByteString userPIN = "4041424344454647"; // "ABCDEFGH"
	ByteString newSOPIN = "3837363534333231"; // "87654321"
	ByteString newUserPIN = "4746454443424140"; // "HGFEDCBA"

	// Instantiate a blank secure data manager
	SecureDataManager s1;
	ByteString plaintext = "010203040506070809";
	ByteString emptyPlaintext = "";
	ByteString encrypted;

	// Verify that no function other than setting the SO PIN works
	CPPUNIT_ASSERT(!s1.setUserPIN(userPIN));
	CPPUNIT_ASSERT(!s1.loginSO(soPIN));
	CPPUNIT_ASSERT(!s1.loginUser(userPIN));
	CPPUNIT_ASSERT(!s1.encrypt(plaintext, encrypted));
	CPPUNIT_ASSERT(!s1.decrypt(encrypted, plaintext));
	CPPUNIT_ASSERT(s1.getSOPINBlob().size() == 0);
	CPPUNIT_ASSERT(s1.getUserPINBlob().size() == 0);

	// Now set the SO PIN
	CPPUNIT_ASSERT(s1.setSOPIN(soPIN));

	// Check that it is still not possible to set the user PIN
	CPPUNIT_ASSERT(!s1.setUserPIN(userPIN));

	// Check that it is possible to log in with the SO PIN
	CPPUNIT_ASSERT(s1.loginSO(soPIN));

	// Check that it is now possible to also set the user PIN
	CPPUNIT_ASSERT(s1.setUserPIN(userPIN));

	// Check that is is now also possible to log in with the user PIN
	CPPUNIT_ASSERT(s1.loginUser(userPIN));

	// Check that it is possible to encrypt and decrypt some data
	ByteString decrypted;

	CPPUNIT_ASSERT(s1.encrypt(plaintext, encrypted));
	CPPUNIT_ASSERT(encrypted != plaintext);

	CPPUNIT_ASSERT(s1.decrypt(encrypted, decrypted));
	CPPUNIT_ASSERT(decrypted == plaintext);

	// Log out
	s1.logout();

	// Check that it is no longer possible to set the SO PIN
	CPPUNIT_ASSERT(!s1.setSOPIN(soPIN));

	// Check that it is no longer possible to set the user PIN
	CPPUNIT_ASSERT(!s1.setUserPIN(userPIN));

	// Check that encrypting/decrypting no longer works
	CPPUNIT_ASSERT(!s1.encrypt(plaintext, encrypted));
	CPPUNIT_ASSERT(!s1.decrypt(encrypted, plaintext));

	// Export the key blobs
	ByteString soPINBlob = s1.getSOPINBlob();
	ByteString userPINBlob = s1.getUserPINBlob();

	// Create a new instance with the exported key blobs
	SecureDataManager s2(soPINBlob, userPINBlob);

	// Check that the key blobs match
	CPPUNIT_ASSERT(s1.getSOPINBlob() == s2.getSOPINBlob());
	CPPUNIT_ASSERT(s1.getUserPINBlob() == s2.getUserPINBlob());

	// Check that it is not possible to set the SO PIN
	CPPUNIT_ASSERT(!s2.setSOPIN(soPIN));

	// Check that it is possible to log in with the SO PIN
	CPPUNIT_ASSERT(s2.loginSO(soPIN));

	// Check that is is now also possible to log in with the user PIN
	CPPUNIT_ASSERT(s2.loginUser(userPIN));

	// Check that encrypting the data results in different ciphertext because of the random IV
	ByteString encrypted2;

	CPPUNIT_ASSERT(s2.encrypt(plaintext, encrypted2));
	CPPUNIT_ASSERT(encrypted != encrypted2);

	// Check that decrypting earlier data can be done with the recreated key
	CPPUNIT_ASSERT(s2.decrypt(encrypted, decrypted));
	CPPUNIT_ASSERT(decrypted == plaintext);

	// Log in with the SO PIN
	CPPUNIT_ASSERT(s2.loginSO(soPIN));

	// Check that the SO PIN can be changed
	CPPUNIT_ASSERT(s2.setSOPIN(newSOPIN));
	
	// Check that it is no longer possible to log in with the old SO PIN
	CPPUNIT_ASSERT(!s2.loginSO(soPIN));

	// Check that encrypting/decrypting no longer works
	CPPUNIT_ASSERT(!s2.encrypt(plaintext, encrypted));
	CPPUNIT_ASSERT(!s2.decrypt(encrypted, plaintext));

	// Check that the key blobs differ
	CPPUNIT_ASSERT(s1.getSOPINBlob() != s2.getSOPINBlob());

	// Check that it is possible to log in with the new SO PIN
	CPPUNIT_ASSERT(s2.loginSO(newSOPIN));

	// Log in with the user PIN
	CPPUNIT_ASSERT(s2.loginUser(userPIN));

	// Check that it is possible to change the user PIN
	CPPUNIT_ASSERT(s2.setUserPIN(newUserPIN));

	// Check that it is no longer possible to log in with the old user PIN
	CPPUNIT_ASSERT(!s2.loginUser(userPIN));

	// Check that encrypting/decrypting no longer works
	CPPUNIT_ASSERT(!s2.encrypt(plaintext, encrypted));
	CPPUNIT_ASSERT(!s2.decrypt(encrypted, plaintext));

	// Check that it is possible to log in with the new user PIN
	CPPUNIT_ASSERT(s2.loginUser(newUserPIN));
	
	// Check that encrypting the data results in the different ciphertext because of the random IV
	CPPUNIT_ASSERT(s2.encrypt(plaintext, encrypted2));
	CPPUNIT_ASSERT(encrypted != encrypted2);

	// Check that decrypting earlier data can be done with the recreated key
	CPPUNIT_ASSERT(s2.decrypt(encrypted, decrypted));
	CPPUNIT_ASSERT(decrypted == plaintext);

	// Check that empty plaintext can be handled
	CPPUNIT_ASSERT(s2.encrypt(emptyPlaintext, encrypted));
	CPPUNIT_ASSERT(s2.decrypt(encrypted, decrypted));
	CPPUNIT_ASSERT(decrypted == emptyPlaintext);
}
Ejemplo n.º 10
0
void test()
{
   //Single unique_ptr
   reset_counters();
   {
   def_constr_deleter<A> d;
   bml::unique_ptr<B, def_constr_deleter<A>&> s(new B, d);
   A* p = s.get();
   bml::unique_ptr<A, def_constr_deleter<A>&> s2(boost::move(s));
   BOOST_TEST(s2.get() == p);
   BOOST_TEST(s.get() == 0);
   BOOST_TEST(A::count == 1);
   BOOST_TEST(B::count == 1);
   d.set_state(6);
   BOOST_TEST(s2.get_deleter().state() == d.state());
   BOOST_TEST(s.get_deleter().state() ==  d.state());
   }
   BOOST_TEST(A::count == 0);
   BOOST_TEST(B::count == 0);
   //Unbounded array unique_ptr
   reset_counters();
   {
   def_constr_deleter<volatile A[]> d;
   bml::unique_ptr<A[], def_constr_deleter<volatile A[]>&> s(new A[2], d);
   A* p = s.get();
   bml::unique_ptr<volatile A[], def_constr_deleter<volatile A[]>&> s2(boost::move(s));
   BOOST_TEST(s2.get() == p);
   BOOST_TEST(s.get() == 0);
   BOOST_TEST(A::count == 2);
   d.set_state(6);
   BOOST_TEST(s2.get_deleter().state() == d.state());
   BOOST_TEST(s.get_deleter().state() ==  d.state());
   }
   BOOST_TEST(A::count == 0);
   //Bounded array unique_ptr
   reset_counters();
   {
   def_constr_deleter<volatile A[2]> d;
   bml::unique_ptr<A[2], def_constr_deleter<volatile A[2]>&> s(new A[2], d);
   A* p = s.get();
   bml::unique_ptr<volatile A[2], def_constr_deleter<volatile A[2]>&> s2(boost::move(s));
   BOOST_TEST(s2.get() == p);
   BOOST_TEST(s.get() == 0);
   BOOST_TEST(A::count == 2);
   d.set_state(6);
   BOOST_TEST(s2.get_deleter().state() == d.state());
   BOOST_TEST(s.get_deleter().state() ==  d.state());
   }
   BOOST_TEST(A::count == 0);
   {
   def_constr_deleter<volatile A[]> d;
   bml::unique_ptr<A[2], def_constr_deleter<volatile A[]>&> s(new A[2], d);
   A* p = s.get();
   bml::unique_ptr<volatile A[], def_constr_deleter<volatile A[]>&> s2(boost::move(s));
   BOOST_TEST(s2.get() == p);
   BOOST_TEST(s.get() == 0);
   BOOST_TEST(A::count == 2);
   d.set_state(6);
   BOOST_TEST(s2.get_deleter().state() == d.state());
   BOOST_TEST(s.get_deleter().state() ==  d.state());
   }
   BOOST_TEST(A::count == 0);
}