Example #1
0
void setProperty (Tree t, Tree key, Tree val)
{
	CTree* pl = t->attribut();
	if (pl) t->attribut(updateKey(pl, key, val)); 
	else 	t->attribut(updateKey(nil, key, val));
}
Example #2
0
node_statistics calc_node_statistics_tree( Tree const& tree )
{
    node_statistics stat;
    detail::update_statistics( tree.root() , stat );
    return stat;
}
Example #3
0
	bool TestBTree::testErase()
	{
		status << "Running Test Insert\n";

		Map map;
		Tree tree;
		Vector vector( elements );
		_init( vector );
		
		for( unsigned int i = 0; i < iterations; ++i )
		{
			switch( random() % 2 )
			{
				case 0:
				{
					size_t index = random() % vector.size();
					map.insert( std::make_pair( vector[ index ], i ) );
					Tree::iterator fi = 
						tree.lower_bound( vector[ index ] );
					fi = tree.insert( fi, 
						std::make_pair( vector[ index ], i ) );
					if( fi->first != vector[ index ] )
					{
						status << "Insert failed, returned iterator with key " 
						<< fi->first << " does not match inserted value " 
						<< vector[ index ] << "\n";
						dumpTree( tree, path );
						return false;
					}		
					break;
				}
								
				case 1:
				{
					size_t index = random() % vector.size();
					size_t index1 = random() % vector.size();
					Map::iterator mi = map.find( vector[ index ] );
					Map::iterator mi1 = map.find( vector[ index1 ] );
					Tree::iterator ti = tree.find( vector[ index ] );
					Tree::iterator ti1 = tree.find( vector[ index1 ] );
					
					if( mi == map.end() && mi1 == map.end() )
					{
						break;
					}
					
					if( mi == map.end() && mi1 != map.end() )
					{
						std::swap( mi, mi1 );
						std::swap( ti, ti1 );
					}
					else if( mi != map.end() && mi1 != map.end() )
					{
						if( mi1->first < mi->first )
						{
							std::swap( mi, mi1 );
							std::swap( ti, ti1 );
						}
					}
					
					map.erase( mi, mi1 );
					tree.erase( ti, ti1 );
					break;
				}
			}
		}
			
		{
			Map::iterator mi = map.begin();
			Tree::iterator ti = tree.begin();

			for( ; mi != map.end() && ti != tree.end(); ++mi, ++ti )
			{
				if( mi->first != ti->first )
				{
					status << "Erase failed, map key " << mi->first
						<< " does not match tree key " << ti->first 
						<< "\n";
					dumpTree( tree, path );
					return false;
				}
				if( mi->second != ti->second )
				{
					status << "Erase failed, map value " 
						<< mi->second
						<< " does not match tree value " << ti->second 
						<< "\n";
					dumpTree( tree, path );
					return false;
				}
			}
		}
		
		status << "  Test Erase Passed.\n";
		return true;
	}
// Begin the main program.
int main (int argc, char** argv)
{

LibMeshInit init (argc, argv);
Mesh mesh(3);
EquationSystems equation_systems (mesh);
read_parameters(equation_systems,argc,argv);
std::string result_file_name (equation_systems.parameters.get<std::string>("result_file_name"));

unsigned int n_timesteps = equation_systems.parameters.get<Real>("n_timesteps");
unsigned int N_eles=equation_systems.parameters.get<Real>("N_eles");
 
Real time = 0;
Real end_time = equation_systems.parameters.get<Real>("end_time");
const unsigned int n_nonlinear_steps = 6;
const Real nonlinear_tolerance = 1.e-3;
const Real initial_linear_solver_tol = 1.e-18;

if(!equation_systems.parameters.get<std::string>("problem").compare("cube")){

MeshTools::Generation::build_cube (
mesh,
                                       1,1,2,
                                       0.0, 1.0,
                                       0.0, 1.0,
																			 0.0, 1.0,
                                       HEX8);
                                      

}	


if((!equation_systems.parameters.get<std::string>("problem").compare("lung")) || (!equation_systems.parameters.get<std::string>("problem").compare("cylinder"))){
  
std::string mesh_file_name (equation_systems.parameters.get<std::string>("mesh_input"));
GmshIO(mesh).read(mesh_file_name);

}
 
//Create tree
Tree tree;
tree.read_tree(equation_systems);

mesh.prepare_for_use();

setup_equationsystem(equation_systems);
TransientLinearImplicitSystem& newton_update = equation_systems.get_system<TransientLinearImplicitSystem>("Newton-update");
TransientLinearImplicitSystem& reference = equation_systems.get_system<TransientLinearImplicitSystem>("Reference-Configuration");
TransientLinearImplicitSystem& last_non_linear_soln = equation_systems.get_system<TransientLinearImplicitSystem>("Last-non-linear-soln");
TransientLinearImplicitSystem& postvars = equation_systems.get_system<TransientLinearImplicitSystem>("postvars");




equation_systems.init ();
equation_systems.print_info();
 
/*
const MeshBase::const_node_iterator nd_end_tlc =
      equation_systems.get_mesh().local_nodes_end();
for (MeshBase::const_node_iterator nd = equation_systems.get_mesh().local_nodes_begin();
      nd != nd_end_tlc; ++nd) {
  const Node *node = *nd;

//Copy initial mesh into reference.solution
  for (unsigned int d = 0; d < 3; ++d) {
		//Save the TLC reference
    unsigned int dest_dof = node->dof_number(reference.number(), d+4, 0);
    Real value = (*node)(d);
    reference.current_local_solution->set(dest_dof, value);
    reference.solution->set(dest_dof, value);

	}
}
 */

//Move mesh and tree from inspiration to registered expiration
  
 const Point Aexp = equation_systems.parameters.get<Point>("A");
const Point bexp = equation_systems.parameters.get<Point>("b");

Real facexp=1.4;
//Update the position of the airway tree
std::cout<<"Moving tree to expiratory FRC " <<std::endl;
    for (double j=0; j <tree.number_nodes ; j++) {
			for (unsigned int d = 0; d < 3; ++d) {
				tree.nodes(j)(d)=tree.nodes(j)(d)-facexp*( tree.nodes(j)(d)*Aexp(d)+bexp(d) );
			}
				
				
				//Move mesh a bit more to ecncompass tree on;y do this for N48
				//	if((!equation_systems.parameters.get<std::string>("mesh_input").compare("meshes/lung/N048r_fine2881.msh")) || (!equation_systems.parameters.get<std::string>("mesh_input").compare("meshes/lung/N048_node5036.msh"))){
					  	if( (!equation_systems.parameters.get<std::string>("mesh_input").compare("meshes/lung/N048_node5036.msh"))){
						
						//tree.nodes(j)(0)= tree.nodes(j)(0)*0.98+2; //-paper don't know why ??
						//tree.nodes(j)(1)= tree.nodes(j)(1)*0.98+4; //-paper don't know why ??
						//tree.nodes(j)(2)= tree.nodes(j)(2)*0.98+2; //-paper don't know why ??
											
						tree.nodes_deformed(j)(0)=tree.nodes(j)(0);
						tree.nodes_deformed(j)(1)=tree.nodes(j)(1);
						tree.nodes_deformed(j)(2)=tree.nodes(j)(2);		
						
							
					}	
					
					
						tree.nodes_frc(j)(0)=tree.nodes(j)(0);
						tree.nodes_frc(j)(1)=tree.nodes(j)(1);
						tree.nodes_frc(j)(2)=tree.nodes(j)(2);	
					
     }


tree.fix_tree(equation_systems);
//tree.shrink_rad(equation_systems);

       
//Update the mesh position
std::cout<<"Moving mesh to expiratory FRC" <<std::endl;
Mesh::node_iterator it_node = mesh.nodes_begin();
const Mesh::node_iterator it_last_node = mesh.nodes_end();
for ( ; it_node != it_last_node ; ++it_node)
    {
      Node* node = *it_node;
      for (unsigned int d = 0; d < 3; ++d) {
           (*node)(d)= (*node)(d) - facexp*((*node)(d)*Aexp(d)+bexp(d)) ;
		   
      }
   }



//Calculate volume of frc
MeshBase::const_element_iterator el_jac_frc = mesh.active_local_elements_begin();
const MeshBase::const_element_iterator end_el_jac_frc = mesh.active_local_elements_end();
Real total_volume_frc=0;
for ( ; el_jac_frc != end_el_jac_frc; ++el_jac_frc)
{
const Elem* elem = *el_jac_frc;
Real elem_vol=elem->volume();
total_volume_frc=total_volume_frc+elem_vol;
}
std::cout<<"total_volume frc "<< total_volume_frc << std::endl;




const MeshBase::const_node_iterator nd_end_frc =
      equation_systems.get_mesh().local_nodes_end();
for (MeshBase::const_node_iterator nd = equation_systems.get_mesh().local_nodes_begin();
      nd != nd_end_frc; ++nd) {
	const Node *node = *nd;

	  for (unsigned int d = 0; d < 3; ++d) {
		//Save the FRC reference mesh position
    unsigned int dest_dof = node->dof_number(reference.number(), d+4, 0);
    Real value = (*node)(d);
    reference.current_local_solution->set(dest_dof, value);
    reference.solution->set(dest_dof, value);

	}
}
//////////////////


std::cout<<"Moving tree to reference " <<std::endl;
    for (double j=0; j <tree.number_nodes ; j++) {
			for (unsigned int d = 0; d < 3; ++d) {
				tree.nodes(j)(d)=tree.nodes(j)(d)-( tree.nodes(j)(d)*REFSCALE );
				tree.nodes_deformed(j)(d)=tree.nodes(j)(d);
			}
				
					
     }

 
std::cout<<"Moving mesh to reference " <<std::endl;
Real ref_state=1;
Real NT_ref_final=REFNT;
Real NT_ref=0;
Mesh::node_iterator it_node_ref = mesh.nodes_begin();
const Mesh::node_iterator it_last_node_ref = mesh.nodes_end();
for ( ; it_node_ref != it_last_node_ref ; ++it_node_ref)
    {
      Node* node = *it_node_ref;
      for (unsigned int d = 0; d < 3; ++d) {
		 (*node)(d)= (*node)(d) - (*node)(d)*REFSCALE ;
      }
   }

   
//Copy REF to reference system
const MeshBase::const_node_iterator nd_end =
      equation_systems.get_mesh().local_nodes_end();
for (MeshBase::const_node_iterator nd = equation_systems.get_mesh().local_nodes_begin();
      nd != nd_end; ++nd) {
  const Node *node = *nd;

//Copy ref mesh into reference.solution REF MESH
  for (unsigned int d = 0; d < 3; ++d) {
    unsigned int dest_dof = node->dof_number(reference.number(), d, 0);
    Real value = (*node)(d);
    reference.current_local_solution->set(dest_dof, value);
    reference.solution->set(dest_dof, value);

	}
}


reference.solution->close();
reference.current_local_solution->close();
reference.update();


Real dt = end_time/n_timesteps;
equation_systems.parameters.set<Real> ("dt") = dt;

ExodusII_IO exo= ExodusII_IO(mesh);

#if WRITE_TEC
TecplotIO tec= TecplotIO(equation_systems.get_mesh());
#endif


AutoPtr<NumericVector<Number> > change_in_newton_update (newton_update.solution->clone());
AutoPtr<NumericVector<Number> > newton_solution (newton_update.solution->clone());
newton_solution->zero();

newton_update.assemble_before_solve=false;
newton_update.update();

// Load in the reference mesh as an initial guess (a neater way to do this ?)
last_non_linear_soln.solution->zero();
last_non_linear_soln.solution->add(1.,(*reference.solution));
last_non_linear_soln.solution->close();
last_non_linear_soln.current_local_solution->zero();
last_non_linear_soln.current_local_solution->add(1.,(*reference.current_local_solution));
last_non_linear_soln.current_local_solution->close();
last_non_linear_soln.old_local_solution->zero();
last_non_linear_soln.old_local_solution->add(1.,(*reference.current_local_solution));
last_non_linear_soln.old_local_solution->close();
last_non_linear_soln.update();


MeshBase::const_element_iterator el_jac = mesh.active_local_elements_begin();
const MeshBase::const_element_iterator end_el_jac = mesh.active_local_elements_end();
const DofMap & dof_map = reference .get_dof_map();
std::vector<unsigned int> dof_indices_p;
const unsigned int p_var = reference.variable_number ("vol_ref");
Real total_volume_ref=0;

int el_counter=0;
for ( ; el_jac != end_el_jac; ++el_jac)
{
const Elem* elem = *el_jac;
Real elem_vol=elem->volume();
total_volume_ref=total_volume_ref+elem_vol;
dof_map.dof_indices (elem, dof_indices_p, 3);
reference.current_local_solution->set(dof_indices_p[0], elem_vol);
reference.solution->set(dof_indices_p[0], elem_vol);
el_counter=el_counter+1;
}
std::cout<<"total_volume ref "<< total_volume_ref << std::endl;
std::cout<<"el_counter "<< el_counter << std::endl;


/*
//Save FRC to postvars /// CAN REMOVE ALL THIS ONLY NEEDED FOR AIRWAY RES
/////////////////////
equation_systems.parameters.set<Real>("ref_state")=0;
tree.add_constriction(equation_systems);
equation_systems.parameters.set<Real>("ref_state")=1;

tree.calculate_total_resistance(equation_systems);
//Do some post-processing (calculate stress etc)
///To get airway tree resistances
	postvars.assemble_before_solve=false;
	postvars.matrix->zero();
	postvars.rhs->zero();
	assemble_postvars(equation_systems,"postvars",tree);
	postvars.update();
	postvars.solve();
///
	///To get airway tree resistances at 0th time step !!
std::stringstream file_name_tec;
  file_name_tec <<result_file_name << "_"<< 0<< ".tec" ;
  tec.write_equation_systems (file_name_tec.str(),equation_systems);
  std::cout<<"Wrote "<< file_name_tec.str() <<std::endl;
	/////////
	*/
	


//Write out 0th timestep	
equation_systems.parameters.set<unsigned int>("step") = 0;
tree.write_tree(equation_systems);
std::stringstream file_name;
file_name << equation_systems.parameters.get<std::string>("result_file_name");
file_name << std::setw(2) << std::setfill('0') << 0;
file_name << ".e-s.";
file_name << std::setw(3) << std::setfill('0') << 0;
exo.write_timestep(file_name.str(), equation_systems,1,0);
std::cout<<"Write initial conditions "<< file_name.str() <<std::endl;
exo.write_element_data(equation_systems);


	
//Count dofs
int size_fem=last_non_linear_soln.n_dofs();
int size_tree=tree.number_nodes+tree.number_edges;
std::cout<<"FEM dofs "<< size_fem <<std::endl;
std::cout<<"Tree dofs "<< size_tree <<std::endl;

//Integrate the total outflow
Real total_outflow=0;

#if mats
#include "create_arrays_mats.cpp"
equation_systems.update();
equation_systems.allgather();
equation_systems.reinit();
#endif

PetscLinearSolver<Number>* petsc_linear_solver =dynamic_cast<PetscLinearSolver<Number>*>(newton_update.get_linear_solver());
	
for (unsigned int t_step=1; t_step<=n_timesteps; ++t_step)
{
  

  if(NT_ref>=NT_ref_final && ref_state>0){
	std::cout<<"Changing to normal breathing"<<std::endl;
	ref_state=0;
	time=0;
	equation_systems.parameters.set<Real> ("ref_state") = 0;
	
	tree.add_constriction(equation_systems);
	T=tree.make_tree_matrix( );

  }
	  
  if(ref_state>0 ){
		std::cout<<"Going from reference to FRC"<<std::endl;

    time += REFDT;

	NT_ref=NT_ref+1;
	t_step=t_step-1;
		  	
  }else{
  
  //dt = end_time/n_timesteps;
  double progress = (t_step+0.000000001) / (n_timesteps+0.000000001);
  equation_systems.parameters.set<Real>("progress") = progress;
  equation_systems.parameters.set<unsigned int>("step") = t_step;
  time = progress*end_time;

  std::cout << "\n\n*** Solving time step " << t_step << ", time = " << time << ", progress = " << progress << " ***" << std::endl;
  }
  
  equation_systems.parameters.set<Real> ("time") = time;

	
  *last_non_linear_soln.old_local_solution = *last_non_linear_soln.current_local_solution;

  // Now we begin the nonlinear loop
  for (unsigned int l=0; l<n_nonlinear_steps; ++l)
  {	
	clock_t begin_big_nonlin=clock();
    equation_systems.parameters.set<Real> ("non_lin_step") = l;
    std::cout<<"\nNon-linear iteration " << l << std::endl;
    change_in_newton_update->zero();
    change_in_newton_update->add(*newton_update.solution);
    //Prepare the newton update system for it's linear solve
    *newton_update.old_local_solution = *newton_update.current_local_solution; 
    newton_update.current_local_solution->zero();
    newton_update.solution->zero();
    newton_update.update();
 
    clock_t begin_big_assemble=clock();
	#include "update_big_matrix.cpp"
	clock_t end_big_assemble=clock();

	std::cout<<"Assembly,"<< " total: " << double(diffclock(end_big_assemble,begin_big_assemble)) << " fem: " << double(diffclock(end_assemble_fem,begin_assemble_fem)) << " tree: " << double(diffclock(end_assemble_tree,begin_assemble_tree)) << " ms"<< " coupling: " << double(diffclock(end_assemble_coupling_fast,begin_assemble_coupling_fast)) << " ms"<<std::endl;

	//Finally solve the poroelastic system
	clock_t begin_solid_solve=clock();	
	//std::cout<< "Solving system "<<std::endl;
	
	//petsc_linear_solver->solve(big_AP, big_xp , big_rp, tolerance, m_its);
	petsc_linear_solver->solve( big_AP, big_xp , big_rp, 1.e-15,4);
	clock_t end_solid_solve=clock();

	//Copy FEM solution back to system solution vector, update mesh and tree positions
	clock_t begin_big_update=clock();
	#include "update_solution.cpp"
	clock_t end_big_update=clock();

	//std::cout<< "-------- Residual and convergence info ----------"<<std::endl;
	#include "residual_info.cpp"

	

	//end of nonlinear step computation
	clock_t end_big_nonlin=clock();

	//free memory
	#if mats
	//PetscFree(b_array); 
	//PetscFree(big_cols_t); 
	//PetscFree(vals_new); 
	//PetscFree(cols_new); 
	big_AP.clear();
	big_rp.clear();
	#endif
 
	std::cout<<"Total: " << double(diffclock(end_big_nonlin,begin_big_nonlin)) << " assembly: " << double(diffclock(end_big_assemble,begin_big_assemble)) << " update: " << double(diffclock(end_big_update,begin_big_update)) << " solve: " << double(diffclock(end_solid_solve,begin_solid_solve)) << " ms"<<std::endl;

	if ((norm_delta/l2_soln < nonlinear_tolerance)&&(solid_residual/l2_soln < nonlinear_tolerance) ){
	  std::cout << "Nonlinear solver converged after "<< l+1 <<" steps."<<std::endl;
	  break;
	}
	
  } // end nonlinear loop

 last_non_linear_soln.update();
 newton_update.update();
 // Write out every nth timestep to file.
 const unsigned int write_interval = 1;

 		if(!(ref_state>0)){
		total_outflow=total_outflow+tree.edges_flowrate(0)*dt;
		std::cout<<"total_outflow "<< total_outflow << std::endl;
		} 
		
 //update tree position
  clock_t begin_pos_update=clock();
    tree.update_positions(equation_systems);    
    clock_t end_pos_update=clock();
	std::cout<<"tree position_update: " << double(diffclock(end_pos_update,begin_pos_update)) <<  " ms"<<std::endl;
	
	//Do some post-processing (calculate stress etc)
	postvars.assemble_before_solve=false;
	postvars.matrix->zero();
	postvars.rhs->zero();
		std::cout<<"Assembling postvars !! " <<std::endl;

	assemble_postvars(equation_systems,"postvars",tree);
	postvars.update();
	postvars.solve();
	
 #include "write_variable_results_and_mesh.cpp"
 
} // end timestep loop.
} // end main function.
Example #5
0
int main()
{
	for(int i = 0; i < MAX; i++)
	{
		used[i] = false;
		tree.is_root[i] = true;
		cycle[i] = -1;
	}
	cin >> M;
	for(int i = 1; i <= M; i++)
	{
		int a, b;
		cin >> a >> b;
		used[a] = used[b] = true;
		if(maxtree.Find(a) == maxtree.Find(b))
		{
			for(int v = a; v != b; v = tree.G2[v]) cycle[v] = cycle_next;
			cycle[b] = cycle_next;
			cycle_first[cycle_next] = b;
			cycle_cut[cycle_next] = i;
			cycle_next++;
		}
		else
		{
			tree.is_root[b] = false;
			tree.add_edge(a, b);
			maxtree.add_edge(a, b, i);
		}
	}
	tree.get_dfs_times();
	cin >> Q;
	for(int q = 0; q < Q; q++)
	{
		int first = INF;

		int nt, nf;
		cin >> nt;
		for(int i = 0; i < nt; i++)
		{
			int v;
			cin >> v;
			if(!used[v]) continue;
			True.push_back(v);
			//cout << cycle[v] << ' ' << maxtree.Find(v)<<endl;
			if(cycle[v] != -1) cycle_components[maxtree.Find(v)] = cycle[v];
		}
		cin >> nf;
		for(int i = 0; i < nf; i++)
		{
			int v;
			cin >> v;
			if(!used[v]) continue;
			False.push_back(v);
		}

		sort(True.begin(), True.end(), compare_by_dfs_in);

		segtree.insert(-1, 0, MAX); // reset segtree
		for(int i = 0; i < True.size(); i++)
			segtree.insert(True[i], tree.dfs_times[True[i]][0], tree.dfs_times[True[i]][1]);
		for(int i = 0; i < False.size(); i++)
		{
			int v = False[i];
			int closest_true = segtree.lookup(tree.dfs_times[v][0]);
			//cout << "closest_true="<<closest_true<<endl;
			if(closest_true == -1)
			{
				int Rv = maxtree.Find(v);
				//cout<<maxtree.R[v] << ' '<<Rv << endl;;
				//cout << cycle_cut[cycle_components[Rv]] << ' ';
				if(cycle_components.find(Rv) != cycle_components.end())
					first = min(first, max(cycle_cut[cycle_components[Rv]], maxtree.max_edge(cycle_first[cycle_components[Rv]], v)));
			}
			//cout << "closest of " << False[i] << " is " << closest_true << endl;
			//if(closest_true != -1) cout << "mindist is " << maxtree.max_edge(False[i], closest_true) << endl;
			if(closest_true != -1) first = min(first, maxtree.max_edge(closest_true, v));
		}

		True.clear();
		False.clear();
		cycle_components.clear();

		cout << (first == INF ? -1 : first) << '\n';
	}
	return 0;
}
Example #6
0
void World::touchMove(int id, int x, int y) {
	if(id>1)
		return;

 	touchCurrentX[id] = x;
	touchCurrentY[id] = y;

#if !USE_MOUSE
	if(id == 1) {
		touched[1] = true;
		touchStartX[1] = touchCurrentX[1];
		touchStartY[1] = touchCurrentY[1];

		touchEvent = TE_ZOOM;
		touchStartX[0] = touchCurrentX[0];
		touchStartY[0] = touchCurrentY[0];
		panStart = pos;
		scaleStart = scale;
		return;
	}
#endif

	switch(touchEvent) {
		case TE_ZOOM: 
			setScale(scaleStart * (vec2((float)touchCurrentX[0] - touchCurrentX[1], (float)touchCurrentY[0] - touchCurrentY[1]).length() /
				vec2((float)touchStartX[0] - touchStartX[1], (float)touchStartY[0] - touchStartY[1]).length() ) );
			move(panStart + pointToPos((touchStartX[0] + touchStartX[1]) / 2, (touchStartY[0] + touchStartY[1]) / 2)
				-	pointToPos((touchCurrentX[0] + touchCurrentX[1]) / 2, (touchCurrentY[0] + touchCurrentY[1]) / 2) );
			break;
		case TE_PAN:
			move(panStart + pointToPos(touchStartX[id], touchStartY[id]) - pointToPos(touchCurrentX[id], touchCurrentY[id]));
			break;
		case TE_TRY:
		case TE_CAN_LINK:
		case TE_CAN_UNLINK:
			if(id>0)
				break;
			{
			Planet* targetPlanet = getPlanet( pointToPos(x, y) );
			if(!targetPlanet || targetPlanet == sourcePlanet) {
				touchEvent = TE_TRY;
				break;
			}
			Tree *targetTree = targetPlanet->getTree(currentRace);
			if(targetTree) {
				if(targetTree->isLinked(sourcePlanet)) {
					touchEvent = TE_CAN_UNLINK;
					break;
				}
			}
			Tree *sourceTree = sourcePlanet->getTree(currentRace);
			if(sourceTree) {
				if(sourceTree->isLinked(targetPlanet)) {
					touchEvent = TE_TRY;
					break;
				}
				touchEvent = TE_CAN_LINK;
			}
			}
			break;
	}

}
Example #7
0
EstOutput Parsimony::createProcesses(Tree* t, vector< vector<string> > namesOfGroupCombos, CountTable* ct) {
	try {
        int process = 1;
		vector<int> processIDS;
		
		EstOutput results;

#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
				
		//loop through and create all the processes you want
		while (process != processors) {
			int pid = fork();
			
			if (pid > 0) {
				processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
				process++;
			}else if (pid == 0){
				EstOutput myresults;
				myresults = driver(t, namesOfGroupCombos, lines[process].start, lines[process].num, ct);
				
				if (m->control_pressed) { exit(0); }
				
				//pass numSeqs to parent
				ofstream out;
				string tempFile = outputDir + toString(getpid()) + ".pars.results.temp";
				m->openOutputFile(tempFile, out);
				out << myresults.size() << endl;
				for (int i = 0; i < myresults.size(); i++) {  out << myresults[i] << '\t';  } out << endl;
				out.close();
				
				exit(0);
			}else { 
				m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
				for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
				exit(0); 
			}
		}
		
		results = driver(t, namesOfGroupCombos, lines[0].start, lines[0].num, ct);
		
		//force parent to wait until all the processes are done
		for (int i=0;i<processIDS.size();i++) { 
			int temp = processIDS[i];
			wait(&temp);
		}
		
		if (m->control_pressed) { return results; }
			
		//get data created by processes
		for (int i=0;i<processIDS.size();i++) { 
			ifstream in;
			string s = outputDir + toString(processIDS[i]) + ".pars.results.temp";
			m->openInputFile(s, in);
			
			//get scores
			if (!in.eof()) {
				int num;
				in >> num; m->gobble(in);
				
				if (m->control_pressed) { break; }
				
				double w; 
				for (int j = 0; j < num; j++) {
					in >> w;
					results.push_back(w);
				}
				m->gobble(in);
			}
			in.close();
			m->mothurRemove(s);
		}
#else
        //fill in functions
        vector<parsData*> pDataArray;
		DWORD   dwThreadIdArray[processors-1];
		HANDLE  hThreadArray[processors-1];
        vector<CountTable*> cts;
        vector<Tree*> trees;
		
		//Create processor worker threads.
		for( int i=1; i<processors; i++ ){
            CountTable* copyCount = new CountTable();
            copyCount->copy(ct);
            Tree* copyTree = new Tree(copyCount);
            copyTree->getCopy(t);
            
            cts.push_back(copyCount);
            trees.push_back(copyTree);
            
            parsData* temppars = new parsData(m, lines[i].start, lines[i].num, namesOfGroupCombos, copyTree, copyCount);
			pDataArray.push_back(temppars);
			processIDS.push_back(i);
            
			hThreadArray[i-1] = CreateThread(NULL, 0, MyParsimonyThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);
		}
		
		results = driver(t, namesOfGroupCombos, lines[0].start, lines[0].num, ct);
		
		//Wait until all threads have terminated.
		WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
		
		//Close all thread handles and free memory allocations.
		for(int i=0; i < pDataArray.size(); i++){
            for (int j = 0; j < pDataArray[i]->results.size(); j++) {  results.push_back(pDataArray[i]->results[j]);  }
			delete cts[i];
            delete trees[i];
			CloseHandle(hThreadArray[i]);
			delete pDataArray[i];
		}
		
#endif		
        return results;
	}
Example #8
0
bool Tree::addTree(const Tree& tree, const std::string& tree_name,
        const std::string& hook_name) {
    return this->addTreeRecursive(tree.getSegment("root"), tree_name, hook_name);
}
Example #9
0
double Treescale::updateTreeScale(double &oldLnL) {
	
	Tree *t = modelPtr->getActiveTree();
	Node *rt = t->getRoot();

	double oldtreeprob = getLnTreeProb(t);
	
	if(retune && tuning > scaleVal)
		tuning = scaleVal * 0.5;
		
	double limO = scaleVal + tuning;
	double limY = scaleVal - tuning;
	double rtLB = t->getNodeLowerBoundTime(rt) * scaleVal;
	double lowBound = rtLB;
	
	double hiBound = limO;
	if(treeTimePrior == 4){
		if(hiBound > treeOriginTime)
			hiBound = treeOriginTime;
	}
	
	if(isBounded){
		if(lowBound < yngBound)
			lowBound = yngBound;
		if(hiBound > oldBound)
			hiBound = oldBound;
	}
	
	double oldRH, newRH;
	oldRH = scaleVal;
		
	double u = ranPtr->uniformRv(-0.5,0.5) * (limO - limY);
	newRH = oldRH + u;
	while(newRH < lowBound || newRH > hiBound){
		if(newRH < lowBound)
			newRH = (2 * lowBound) - newRH;
		if(newRH > hiBound)
			newRH = (2 * hiBound) - newRH;
	}
		
	double scaleRatio = oldRH / newRH;
	int numNodes = t->getNumNodes();
	for(int i=0; i<numNodes; i++){
		Node *p = t->getNodeByIndex(i);
		if(p != rt){
			if(p->getIsLeaf() && p->getIsCalibratedDepth() == false){
				p->setNodeDepth(0.0);
			}
			else{
				double oldP = p->getNodeDepth();
				double newP = oldP * scaleRatio;
				p->setNodeDepth(newP);
				p->setFossAttchTime(0.0);
				if(false){
					double oldPhi = p->getFossAttchTime();
					double fA = p->getNodeYngTime();
					double newPhi = oldPhi * scaleRatio;
					if(newPhi*newRH < fA){
						cout << i << " op = " << oldPhi*oldRH << "  np = " << newPhi*newRH << " oRH = " << oldRH << "  nRH = " 
							<< newRH << "  fA = " << fA << endl;
					}
					int x = t->countDecLinsTimeIntersect(p, newPhi, newP);
					p->setFossAttchTime(newPhi);
					p->setNumFossAttchLins(x); 
				}
			}
		}
	}
	scaleVal = newRH;
	t->setTreeScale(scaleVal);
	t->treeScaleUpdateFossilAttchTimes(scaleRatio, oldRH, newRH);
	t->treeUpdateNodeOldestBoundsAttchTimes();
	t->setAllNodeBranchTimes();
		
	double lnPriorRatio = 0.0; 
	double newtreeprob = getLnTreeProb(t);
	lnPriorRatio += (newtreeprob - oldtreeprob);
	if(tsPriorD == 2){
		if(exponHPCalib)
			expoRate = t->getRootCalibExpRate();
		lnPriorRatio += lnExponentialTSPriorRatio(newRH, oldRH);
	}
	double lnProposalRatio = 0.0;
	
	double jacobian = 0.0;
	if(treeTimePrior < 2)
		jacobian = (log(oldRH) - log(newRH)) * (t->getNumTaxa() - 2);


	t->flipAllCls();
	t->flipAllTis();
	t->upDateAllCls();
	t->upDateAllTis();
	modelPtr->setTiProb();
	
	
	return lnPriorRatio + lnProposalRatio + jacobian;
}
Example #10
0
Tree tmap (Tree key, tfun f, Tree t)
{	
	//printf("start tmap\n");
	Tree p; 
	
	if (getProperty(t, key, p)) {
		
		return (isNil(p)) ? t : p;	// truc pour eviter les boucles
		
	} else {
		
		Tree r1=nil;
		switch (t->arity()) {
			
			case 0 : 
				r1 = t; 
				break;
			case 1 : 
				r1 = tree(t->node(), tmap(key,f,t->branch(0))); 
				break;
			case 2 : 
				r1 = tree(t->node(), tmap(key,f,t->branch(0)), tmap(key,f,t->branch(1))); 
				break;
			case 3 : 
				r1 = tree(t->node(), tmap(key,f,t->branch(0)), tmap(key,f,t->branch(1)),
										   tmap(key,f,t->branch(2))); 
				break;
			case 4 : 
				r1 = tree(t->node(), tmap(key,f,t->branch(0)), tmap(key,f,t->branch(1)),
										   tmap(key,f,t->branch(2)), tmap(key,f,t->branch(3))); 
				break;
		}
		Tree r2 = f(r1);
		if (r2 == t) {
			setProperty(t, key, nil);
		} else {
			setProperty(t, key, r2);
		}
		return r2;
	}
}
Example #11
0
static Tree subst (Tree t, Tree propkey, Tree id, Tree val)
{
	Tree p;
	
	if (t==id) {
		return val;
		
	} else if (t->arity() == 0) {
		return t;
	} else if (getProperty(t, propkey, p)) {
		return (isNil(p)) ?  t : p;
	} else {
		Tree r=nil;
		switch (t->arity()) {
			
			case 1 : 
				r = tree(t->node(), 
							subst(t->branch(0), propkey, id, val)); 
				break;
				
			case 2 : 
				r = tree(t->node(), 
							subst(t->branch(0), propkey, id, val), 
							subst(t->branch(1), propkey, id, val)); 
				break;
				
			case 3 : 
				r = tree(t->node(), 
							subst(t->branch(0), propkey, id, val), 
							subst(t->branch(1), propkey, id, val), 
							subst(t->branch(2), propkey, id, val)); 
				break;
				
			case 4 : 
				r = tree(t->node(), 
							subst(t->branch(0), propkey, id, val), 
							subst(t->branch(1), propkey, id, val), 
							subst(t->branch(2), propkey, id, val), 
							subst(t->branch(3), propkey, id, val)); 
				break;
			
		}
		if (r == t) {
			setProperty(t, propkey, nil);
		} else {
			setProperty(t, propkey, r);
		}
		return r;
	}
		
}
Example #12
0
// nouvelle implementation
void setProperty (Tree t, Tree key, Tree val)
{
	t->setProperty(key, val);
}
Example #13
0
bool getProperty (Tree t, Tree key, Tree& val)
{
	CTree* pl = t->attribut();
	if (pl) return findKey(pl, key, val);
	else 	return false;
}
Example #14
0
void remProperty (Tree t, Tree key)
{
	CTree* pl = t->attribut();
	if (pl) t->attribut(removeKey(pl, key));
}
Example #15
0
int main()
{
	Tree tree;
	tree.insert("yiyuan",new HosPartNode(1,"yiyuan"));

	tree.insert("yiyuan",new HosPartNode(10,"louceng"));

	tree.insert("louceng",new HosPartNode(1,"zhongyangdating"));
	tree.insert("louceng",new HosPartNode(4,"peilou"));

	tree.insert("zhongyangdating",new HosPartNode(1,"TV"));
	tree.insert("zhongyangdating",new HosPartNode(2,"sofa"));

	tree.insert("peilou",new HosPartNode(2,"changzoulang"));
	tree.insert("peilou",new HosPartNode(1,"zoulanglianjie"));

	tree.insert("changzoulang",new HosPartNode(21,"bingfang"));

	tree.insert("zoulanglianjie",new HosPartNode(5,"kufang"));

	tree.insert("bingfang",new HosPartNode(1,"washroom"));
	tree.insert("bingfang",new HosPartNode(4,"chazuo"));
	tree.insert("bingfang",new HosPartNode(2,"bingchuang"));

	tree.insert("washroom",new HosPartNode(1,"ximianpen"));
	tree.insert("washroom",new HosPartNode(1,"zuobianqi"));

	tree.insert("chazuo",new HosPartNode(2,"chakou"));
	tree.insert("chazuo",new HosPartNode(1,"mianban"));

//	tree.getParent(tree.Find("bingfang"))->print();
//	tree.Find("bingfang")->print();
//	cout<<endl;
	tree.WithTraverse(tree.getRoot());
	cout<<endl;
	cout<<"每个楼层中病房的数量为 : "<<tree.count("louceng","bingfang")<<endl;
	return 0;
}
Example #16
0
double Treescale::updateTreeScalePropSE(double &oldLnL) {
	
	Tree *t = modelPtr->getActiveTree();
	Node *rt = t->getRoot();
	
	double oldtreeprob = getLnTreeProb(t);
		
	double rtLB = t->getNodeLowerBoundTime(rt) * scaleVal;
	double lowBound = rtLB;
	
	double hiBound = 100000.0;
	if(treeTimePrior == 4){
		if(hiBound > treeOriginTime)
			hiBound = treeOriginTime;
	}
	
	if(isBounded){
		if(lowBound < yngBound)
			lowBound = yngBound;
		if(hiBound > oldBound)
			hiBound = oldBound;
	}
	
	double oldRH, newRH;
	oldRH = scaleVal;
	
	double rv = ranPtr->uniformRv();
	double tv = log(2.0);
	double c = tv * (rv - 0.5);
	newRH = oldRH * exp(c);
	bool validV = false;
	do{
		if(newRH < lowBound)
			newRH = lowBound * lowBound / newRH;
		else if(newRH > hiBound)
			newRH = hiBound * hiBound / newRH;
		else
			validV = true;
	} while(!validV);
	
	double scaleRatio = oldRH / newRH;
	int numNodes = t->getNumNodes();
	for(int i=0; i<numNodes; i++){
		Node *p = t->getNodeByIndex(i);
		if(p != rt){
			if(p->getIsLeaf() && p->getIsCalibratedDepth() == false){
				p->setNodeDepth(0.0);
			}
			else{
				double oldP = p->getNodeDepth();
				double newP = oldP * scaleRatio;
				p->setNodeDepth(newP);
				p->setFossAttchTime(0.0);
			}
		}
	}
	scaleVal = newRH;
	t->setTreeScale(scaleVal);
	t->treeScaleUpdateFossilAttchTimes(scaleRatio, oldRH, newRH);
	t->treeUpdateNodeOldestBoundsAttchTimes();
	t->setAllNodeBranchTimes();
	
	double lnPriorRatio = 0.0;
	double newtreeprob = getLnTreeProb(t);
	lnPriorRatio += (newtreeprob - oldtreeprob);
	if(tsPriorD == 2){
		if(exponHPCalib)
			expoRate = t->getRootCalibExpRate();
		lnPriorRatio += lnExponentialTSPriorRatio(newRH, oldRH);
	}
	double lnProposalRatio = c;
	
	double jacobian = 0.0; 
	if(treeTimePrior < 2)
		jacobian = (log(oldRH) - log(newRH)) * (t->getNumTaxa() - 2);
	
	t->flipAllCls();
	t->flipAllTis();
	t->upDateAllCls();
	t->upDateAllTis();
	modelPtr->setTiProb();
	
	
	return lnPriorRatio + lnProposalRatio + jacobian;
}
Example #17
0
QString Parse::getTypeOfToken(const QString &ident, const QString &className,
                              Scope * scope, bool token_is_function)
{
	/* if we have a variable and already found a local definition, just return it after duplicating */
	if (!token_is_function && scope->localdef.length())
		return scope->localdef;

	/* if the identifier is this-> return the current class */
	if (ident == "this")
		return scope->scope;

	Tree *tree = NULL;
	if (className.length())
	{
		tree = Tree::buildInheritanceTree(className);
		if (!tree)
			return NULL;
	}

	tagFileInfo info;
	tagEntry entry;
	tagFile *tfile = tagsOpen(tagsFilePath.toAscii(), &info);
	if (tfile && info.status.opened)
	{
		if (tagsFind(tfile, &entry, ident.toAscii(), TAG_OBSERVECASE | TAG_FULLMATCH) ==
		        TagSuccess)
		{
			do
			{
				if (tree && !tree->isMemberOfScope(&entry, scope))
					continue;

				const char *kind = tagsField(&entry, "kind");
				if (token_is_function)	/* only list if tag is a function */
				{
					if (!kind
					        || (strcmp(kind, "function") && strcmp(kind, "prototype")))
						continue;
				}
				else		/* or a variable */
				{
					//brc: add externvar for extern variables like cout
					if (!kind
					        || (strcmp(kind, "variable") && strcmp(kind, "externvar")
					            //brc: namespace workarround: add namespace
					            && strcmp(kind, "namespace") && strcmp(kind, "member")))
						continue;
				}

				/* need to duplicate the pattern, don't ask me why */
				QString type = extractTypeQualifier(entry.address.pattern, ident);
				if(tree)
					tree->freeTree();
				tagsClose(tfile);
				return type;
			}
			while (tagsFindNext(tfile, &entry) == TagSuccess);
		}
		tagsClose(tfile);
	}
	return NULL;
}
/*************************************************************************
    Sample specific initialisation goes here.
*************************************************************************/
bool TreeDemoSample::initialiseSample()
   {
   using namespace CEGUI;
   Tree *      theTree;
   TreeItem *  newTreeCtrlEntryLvl1;  // Level 1 TreeCtrlEntry (branch)
   TreeItem *  newTreeCtrlEntryLvl2;  // Level 2 TreeCtrlEntry (branch)
   TreeItem *  newTreeCtrlEntryLvl3;  // Level 3 TreeCtrlEntry (branch)
   TreeItem *  newTreeCtrlEntryParent;
   Image *     iconArray[9];

#if defined( __WIN32__ ) || defined( _WIN32 )
   // Windows specific code.
   srand(time(NULL));
#endif

   // Get window manager which we will use for a few jobs here.
   WindowManager& winMgr = WindowManager::getSingleton();

//   CEGUI::Logger::getSingleton().setLoggingLevel(CEGUI::Standard);
//   CEGUI::Logger::getSingleton().setLoggingLevel(CEGUI::Informative);
   CEGUI::Logger::getSingleton().setLoggingLevel(CEGUI::Insane);

   // Load the scheme to initialise the skin which we use in this sample
   SchemeManager::getSingleton().create(SCHEME_FILE_NAME);

   // set default mouse image
   System::getSingleton().setDefaultMouseCursor(IMAGES_FILE_NAME, "MouseArrow");

   // load an image to use as a background
   ImagesetManager::getSingleton().createFromImageFile("BackgroundImage", "GPN-2000-001437.tga");

   // Load some icon images for our test tree
  // Imageset *iconImages = ImagesetManager::getSingleton().create("TreeIcons.imageset");
   Imageset& drives = ImagesetManager::getSingleton().create("DriveIcons.imageset");

   // here we will use a StaticImage as the root, then we can use it to place a background image
   Window* background = winMgr.createWindow(STATICIMAGE_NAME);

   // set area rectangle
   background->setArea(URect(cegui_reldim(0), cegui_reldim(0), cegui_reldim(1), cegui_reldim(1)));
   // disable frame and standard background
   background->setProperty("FrameEnabled", "false");
   background->setProperty("BackgroundEnabled", "false");
   // set the background image
   background->setProperty("Image", "set:BackgroundImage image:full_image");
   // install this as the root GUI sheet
   System::getSingleton().setGUISheet(background);

//   CEGUI::System::getSingleton().setTooltip(TOOLTIP_NAME);

    FontManager::getSingleton().create("DejaVuSans-10.font");
//	if(!FontManager::getSingleton().isFontPresent("Commonwealth-10"))
//		FontManager::getSingleton().createFont("Commonwealth-10.font");


   TreeDemoWindow = winMgr.loadWindowLayout(LAYOUT_FILE_NAME);

   background->addChildWindow(TreeDemoWindow);

   // listen for key presses on the root window.
   background->subscribeEvent(Window::EventKeyDown, Event::Subscriber(&TreeDemoSample::handleRootKeyDown, this));

   theTree = (Tree *)TreeDemoWindow->getChild(TreeID);
   theTree->initialise();
   theTree->subscribeEvent(Tree::EventSelectionChanged, Event::Subscriber(&TreeDemoSample::handleEventSelectionChanged, this));
   theTree->subscribeEvent(Tree::EventBranchOpened, Event::Subscriber(&TreeDemoSample::handleEventBranchOpened, this));
   theTree->subscribeEvent(Tree::EventBranchClosed, Event::Subscriber(&TreeDemoSample::handleEventBranchClosed, this));

   // activate the background window
   background->activate();

   Imageset& iconImages = drives;
   iconArray[0] = (Image *)&iconImages.getImage("Artic");
   iconArray[1] = (Image *)&iconImages.getImage("Black");
   iconArray[2] = (Image *)&iconImages.getImage("Sunset");
   iconArray[3] = (Image *)&iconImages.getImage("DriveStack");
   iconArray[4] = (Image *)&iconImages.getImage("GlobalDrive");
   iconArray[5] = (Image *)&iconImages.getImage("Blue");
   iconArray[6] = (Image *)&iconImages.getImage("Lime");
   iconArray[7] = (Image *)&iconImages.getImage("Silver");
   iconArray[8] = (Image *)&iconImages.getImage("GreenCandy");

   // Create a top-most TreeCtrlEntry
   newTreeCtrlEntryLvl1 = new TreeItem("Tree Item Level 1a");
   newTreeCtrlEntryLvl1->setIcon(drives.getImage("Black"));
   newTreeCtrlEntryLvl1->setSelectionBrushImage(IMAGES_FILE_NAME, BRUSH_NAME);
//   newTreeCtrlEntryLvl1->setUserData((void *)someData);
   theTree->addItem(newTreeCtrlEntryLvl1);
   // Create a second-level TreeCtrlEntry and attach it to the top-most TreeCtrlEntry
   newTreeCtrlEntryLvl2 = new TreeItem("Tree Item Level 2a (1a)");
   newTreeCtrlEntryLvl2->setIcon(drives.getImage("Artic"));
   newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME, BRUSH_NAME);
   newTreeCtrlEntryLvl1->addItem(newTreeCtrlEntryLvl2);
   // Create a third-level TreeCtrlEntry and attach it to the above TreeCtrlEntry
   newTreeCtrlEntryLvl3 = new TreeItem("Tree Item Level 3a (2a)");
   newTreeCtrlEntryLvl3->setIcon(drives.getImage("Blue"));
   newTreeCtrlEntryLvl3->setSelectionBrushImage(IMAGES_FILE_NAME, BRUSH_NAME);
   newTreeCtrlEntryLvl2->addItem(newTreeCtrlEntryLvl3);
   // Create another third-level TreeCtrlEntry and attach it to the above TreeCtrlEntry
   newTreeCtrlEntryLvl3 = new TreeItem("Tree Item Level 3b (2a)");
   newTreeCtrlEntryLvl3->setIcon(drives.getImage("Lime"));
   newTreeCtrlEntryLvl3->setSelectionBrushImage(IMAGES_FILE_NAME, BRUSH_NAME);
   newTreeCtrlEntryLvl2->addItem(newTreeCtrlEntryLvl3);
   // Create another second-level TreeCtrlEntry and attach it to the top-most TreeCtrlEntry
   newTreeCtrlEntryLvl2 = new TreeItem("Tree Item Level 2b (1a)");
   newTreeCtrlEntryLvl2->setIcon(drives.getImage("Sunset"));
   newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME, BRUSH_NAME);
   newTreeCtrlEntryLvl1->addItem(newTreeCtrlEntryLvl2);
   // Create another second-level TreeCtrlEntry and attach it to the top-most TreeCtrlEntry
   newTreeCtrlEntryLvl2 = new TreeItem("Tree Item Level 2c (1a)");
   newTreeCtrlEntryLvl2->setIcon(drives.getImage("Silver"));
   newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME, BRUSH_NAME);
   newTreeCtrlEntryLvl1->addItem(newTreeCtrlEntryLvl2);

   // Create another top-most TreeCtrlEntry
   newTreeCtrlEntryLvl1 = new TreeItem("Tree Item Level 1b");
   newTreeCtrlEntryLvl1->setSelectionBrushImage(IMAGES_FILE_NAME, BRUSH_NAME);
   newTreeCtrlEntryLvl1->setIcon(drives.getImage("DriveStack"));
   newTreeCtrlEntryLvl1->setDisabled(true); // Let's disable this one just to be sure it works
   theTree->addItem(newTreeCtrlEntryLvl1);
   // Create a second-level TreeCtrlEntry and attach it to the top-most TreeCtrlEntry
   newTreeCtrlEntryLvl2 = new TreeItem("Tree Item Level 2a (1b)");
   newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME, BRUSH_NAME);
   newTreeCtrlEntryLvl1->addItem(newTreeCtrlEntryLvl2);
   // Create another second-level TreeCtrlEntry and attach it to the top-most TreeCtrlEntry
   newTreeCtrlEntryLvl2 = new TreeItem("Tree Item Level 2b (1b)");
   newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME, BRUSH_NAME);
   newTreeCtrlEntryLvl1->addItem(newTreeCtrlEntryLvl2);

   newTreeCtrlEntryLvl1 = new TreeItem("Tree Item Level 1c");
   newTreeCtrlEntryLvl1->setSelectionBrushImage(IMAGES_FILE_NAME, BRUSH_NAME);
   theTree->addItem(newTreeCtrlEntryLvl1);

   // Now let's create a whole bunch of items automatically
   int levelIndex = 3;
   int idepthIndex;
   int childIndex;
   int childCount;
   unsigned int iconIndex;
   String itemText;
   while (levelIndex < 10)
      {
      idepthIndex = 0;
      itemText = "Tree Item Level " + PropertyHelper::intToString(levelIndex) + " Depth " + PropertyHelper::intToString(idepthIndex);
      newTreeCtrlEntryLvl1 = new TreeItem(itemText);
      // Set a random icon for the item.  Sometimes blank (on purpose).
      iconIndex = randInt(0, (sizeof(iconArray) / sizeof(iconArray[0])) + 2);
      if (iconIndex < sizeof(iconArray) / sizeof(iconArray[0]))
         newTreeCtrlEntryLvl1->setIcon(*iconArray[iconIndex]);
      newTreeCtrlEntryLvl1->setSelectionBrushImage(IMAGES_FILE_NAME, BRUSH_NAME);
      theTree->addItem(newTreeCtrlEntryLvl1);
      newTreeCtrlEntryParent = newTreeCtrlEntryLvl1;

#if 1
      childIndex = 0;
      childCount = randInt(0, 3);
      while (childIndex < childCount)
         {
         itemText = "Tree Item Level " + PropertyHelper::intToString(levelIndex) + " Depth " + PropertyHelper::intToString(idepthIndex + 1) + " Child " + PropertyHelper::intToString(childIndex + 1);
         newTreeCtrlEntryLvl2 = new TreeItem(itemText);
         // Set a random icon for the item.  Sometimes blank (on purpose).
         iconIndex = randInt(0, (sizeof(iconArray) / sizeof(iconArray[0]) + 2));
         if (iconIndex < sizeof(iconArray) / sizeof(iconArray[0]))
            newTreeCtrlEntryLvl2->setIcon(*iconArray[iconIndex]);
         newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME, BRUSH_NAME);
         newTreeCtrlEntryParent->addItem(newTreeCtrlEntryLvl2);
         ++childIndex;
         }
#endif

      while (idepthIndex < 15)
         {
         itemText = "Tree Item Level " + PropertyHelper::intToString(levelIndex) + " Depth " + PropertyHelper::intToString(idepthIndex + 1);
         newTreeCtrlEntryLvl2 = new TreeItem(itemText);
         // Set a random icon for the item.  Sometimes blank (on purpose).
         iconIndex = randInt(0, (sizeof(iconArray) / sizeof(iconArray[0]) + 2));
         if (iconIndex < sizeof(iconArray) / sizeof(iconArray[0]))
            newTreeCtrlEntryLvl2->setIcon(*iconArray[iconIndex]);
         newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME, BRUSH_NAME);
         newTreeCtrlEntryParent->addItem(newTreeCtrlEntryLvl2);
         newTreeCtrlEntryParent = newTreeCtrlEntryLvl2;

#if 1
         childIndex = 0;
         childCount = randInt(0, 3);
         while (childIndex < childCount)
            {
            itemText = "Tree Item Level " + PropertyHelper::intToString(levelIndex) + " Depth " + PropertyHelper::intToString(idepthIndex + 1) + " Child " + PropertyHelper::intToString(childIndex + 1);
            newTreeCtrlEntryLvl2 = new TreeItem(itemText);
            // Set a random icon for the item.  Sometimes blank (on purpose).
            iconIndex = randInt(0, (sizeof(iconArray) / sizeof(iconArray[0]) + 2));
            if (iconIndex < sizeof(iconArray) / sizeof(iconArray[0]))
               newTreeCtrlEntryLvl2->setIcon(*iconArray[iconIndex]);
            newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME, BRUSH_NAME);
            newTreeCtrlEntryParent->addItem(newTreeCtrlEntryLvl2);
            ++childIndex;
            }
#endif
         ++idepthIndex;
         }
      ++levelIndex;
      }

   return true;
   }
Example #19
0
int main()
{
   Tree myTree;

 	bool inMenu = true;	// while the user is using the program this var is set to true and the menu keeps looping.
						// when the user wants to quit, it is set to false and the loop ends.
	char keyPressed;	// This var stores which menu selection the user picks.

	while ( inMenu )
	{
		cout<< endl << endl << endl;
		cout << "****************************************************" << endl;
		cout  <<"**  MENU:(press a character to select an option)  **" << endl;
 		cout << "****************************************************" << endl;
		cout<<"Q. [QUIT]     Quit."<<endl;
  		cout<<"D. [Display]  Display all values stored in the tree"<<endl;
 		cout<<"I. [Insert]   Insert an integer"<<endl;
		cout << endl;

		cout<<"M. [Maximum] Determine the maximum of all values stored in the tree" << endl;
		cout<<"A. [Average] Determine the average of all values stored in the tree" << endl;
		cout<<"H. [Height]  Determine the height of the tree" << endl;
		cout << "****************************************************" <<endl<< endl;

		cout<<"Your choice is: ";
		cin >> keyPressed ;

		int value;
		switch(keyPressed)
		{
			case 'M': case 'm'://Maximum
				cout << "[Maximum]:" << endl;
				cout << "Maximum value stored is:" << myTree.FindMaximum() << endl;
				break;

			case 'A': case 'a'://Average
				cout << "[Average]:" << endl;
				cout << "Average of all values stored is:" << myTree.FindAverage() << endl;
				break;

			case 'H': case 'h'://height
				cout << "[Height]:" << endl;
				cout << "Height of the tree is:" << myTree.FindHeight()<< endl;
				break;


			case 'Q': case 'q'://Quit
				cout << "[QUIT]:" << endl;
				inMenu = false;
				break;

			case 'D': case 'd':
				cout << "[Display]:" << endl;
				myTree.Display();
				break;

			case 'I': case 'i':
				cout << "[insert]:" << endl;
				cout << "Value to insert:";
				cin >> value;
				myTree.Insert(value);
				break;

			default:
				cout << "[?? UNKNOWN COMMAND]:" << endl;
				// Unrecognized key, do nothing
				break;
		}


	} // End of while loop

	return 0;
}
Example #20
0
void ProgAlignSubFams()
	{
	MSA msaOut;

	SetOutputFileName(g_pstrOutFileName.get());
	SetInputFileName(g_pstrInFileName.get());

	SetMaxIters(g_uMaxIters.get());
	SetSeqWeightMethod(g_SeqWeight1.get());

	TextFile fileIn(g_pstrInFileName.get());
	SeqVect v;
	v.FromFASTAFile(fileIn);
	const unsigned uSeqCount = v.Length();

	if (0 == uSeqCount)
		Quit("No sequences in input file");

	ALPHA Alpha = ALPHA_Undefined;
	switch (g_SeqType.get())
		{
	case SEQTYPE_Auto:
		Alpha = v.GuessAlpha();
		break;

	case SEQTYPE_Protein:
		Alpha = ALPHA_Amino;
		break;

	case SEQTYPE_DNA:
		Alpha = ALPHA_DNA;
		break;

	case SEQTYPE_RNA:
		Alpha = ALPHA_RNA;
		break;

	default:
		Quit("Invalid seq type");
		}
	SetAlpha(Alpha);
	v.FixAlpha();

	PTR_SCOREMATRIX UserMatrix = 0;
	if (0 != g_pstrMatrixFileName.get())
		{
		const char *FileName = g_pstrMatrixFileName.get();
		const char *Path = getenv("MUSCLE_MXPATH");
		if (Path != 0)
			{
			size_t n = strlen(Path) + 1 + strlen(FileName) + 1;
			char *NewFileName = new char[n];
			sprintf(NewFileName, "%s/%s", Path, FileName);
			FileName = NewFileName;
			}
		TextFile File(FileName);
		UserMatrix = ReadMx(File);
		g_Alpha = ALPHA_Amino;
		g_PPScore = PPSCORE_SP;
		}

	SetPPScore();

	if (0 != UserMatrix)
		g_ptrScoreMatrix = UserMatrix;

	if (ALPHA_DNA == Alpha || ALPHA_RNA == Alpha)
		{
		SetPPScore(PPSCORE_SPN);
		g_Distance1.get() = DISTANCE_Kmer4_6;
		}

	unsigned uMaxL = 0;
	unsigned uTotL = 0;
	for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex)
		{
		unsigned L = v.GetSeq(uSeqIndex).Length();
		uTotL += L;
		if (L > uMaxL)
			uMaxL = L;
		}

	SetIter(1);
	g_bDiags.get() = g_bDiags1.get();
	SetSeqStats(uSeqCount, uMaxL, uTotL/uSeqCount);

	SetMuscleSeqVect(v);

	MSA::SetIdCount(uSeqCount);

// Initialize sequence ids.
// From this point on, ids must somehow propogate from here.
	for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex)
		v.SetSeqId(uSeqIndex, uSeqIndex);

	if (uSeqCount > 1)
		MHackStart(v);

	if (0 == uSeqCount)
		{
		msaOut.Clear();
		return;
		}

	if (1 == uSeqCount && ALPHA_Amino == Alpha)
		{
		const Seq &s = v.GetSeq(0);
		msaOut.FromSeq(s);
		return;
		}

	Tree GuideTree;
	TreeFromSeqVect(v, GuideTree, g_Cluster1.get(), g_Distance1.get(), g_Root1.get());
	SetMuscleTree(GuideTree);

	MSA msa;
	if (g_bLow.get())
		{
		ProgNode *ProgNodes = 0;
		ProgNodes = ProgressiveAlignE(v, GuideTree, msa);
		delete[] ProgNodes;
		}
	else
		ProgressiveAlign(v, GuideTree, msa);
	SetCurrentAlignment(msa);
	TreeFromMSA(msa, GuideTree, g_Cluster2.get(), g_Distance2.get(), g_Root2.get());
	SetMuscleTree(GuideTree);

	unsigned *SubFams = new unsigned[uSeqCount];
	unsigned uSubFamCount;
	SubFam(GuideTree, g_uMaxSubFamCount.get(), SubFams, &uSubFamCount);

	SetProgressDesc("Align node");
	const unsigned uNodeCount = 2*uSeqCount - 1;

	ProgNode *ProgNodes = new ProgNode[uNodeCount];
	bool *NodeIsSubFam = new bool[uNodeCount];
	bool *NodeInSubFam = new bool[uNodeCount];

	for (unsigned i = 0; i < uNodeCount; ++i)
		{
		NodeIsSubFam[i] = false;
		NodeInSubFam[i] = false;
		}

	for (unsigned i = 0; i < uSubFamCount; ++i)
		{
		unsigned uNodeIndex = SubFams[i];
		assert(uNodeIndex < uNodeCount);
		NodeIsSubFam[uNodeIndex] = true;
		SetInFam(GuideTree, uNodeIndex, NodeInSubFam);
		}

	unsigned uJoin = 0;
	unsigned uTreeNodeIndex = GuideTree.FirstDepthFirstNode();
	do
		{
		if (NodeIsSubFam[uTreeNodeIndex])
			{
#if	TRACE
			Log("Node %d: align subfam\n", uTreeNodeIndex);
#endif
			ProgNode &Node = ProgNodes[uTreeNodeIndex];
			AlignSubFam(v, GuideTree, uTreeNodeIndex, Node.m_MSA);
			Node.m_uLength = Node.m_MSA.GetColCount();
			}
		else if (!NodeInSubFam[uTreeNodeIndex])
			{
#if	TRACE
			Log("Node %d: align two subfams\n", uTreeNodeIndex);
#endif
			Progress(uJoin, uSubFamCount - 1);
			++uJoin;

			const unsigned uMergeNodeIndex = uTreeNodeIndex;
			ProgNode &Parent = ProgNodes[uMergeNodeIndex];

			const unsigned uLeft = GuideTree.GetLeft(uTreeNodeIndex);
			const unsigned uRight = GuideTree.GetRight(uTreeNodeIndex);

			ProgNode &Node1 = ProgNodes[uLeft];
			ProgNode &Node2 = ProgNodes[uRight];

			PWPath Path;
			AlignTwoMSAs(Node1.m_MSA, Node2.m_MSA, Parent.m_MSA, Path);
			Parent.m_uLength = Parent.m_MSA.GetColCount();

			Node1.m_MSA.Clear();
			Node2.m_MSA.Clear();
			}
		else
			{
#if	TRACE
			Log("Node %d: in subfam\n", uTreeNodeIndex);
#endif
			;
			}
		uTreeNodeIndex = GuideTree.NextDepthFirstNode(uTreeNodeIndex);
		}
	while (NULL_NEIGHBOR != uTreeNodeIndex);
	ProgressStepsDone();

	unsigned uRootNodeIndex = GuideTree.GetRootNodeIndex();
	ProgNode &RootProgNode = ProgNodes[uRootNodeIndex];

	TextFile fOut(g_pstrOutFileName.get(), true);
	MHackEnd(RootProgNode.m_MSA);
	RootProgNode.m_MSA.ToFile(fOut);

	delete[] NodeInSubFam;
	delete[] NodeIsSubFam;
	delete[] ProgNodes;
	delete[] SubFams;

	ProgNodes = 0;
	NodeInSubFam = 0;
	NodeIsSubFam = 0;
	SubFams = 0;
	}
Example #21
0
void write_simple( std::ostream &out , Tree const& t , bool write_infix , SymbolMapper const& mapper )
{
    if( !t.empty() )
        write_simple_cursor( out , t.root() , write_infix , mapper );
}
Example #22
0
int main(int argc, char **argv)
{
#ifdef MOAB_HAVE_MPI
  int fail = MPI_Init(&argc, &argv);
  if (fail) return fail;
#else
  // silence the warning of parameters not used, in serial; there should be a smarter way :(
  argv[0]=argv[argc-argc];
#endif

  int npoints = 100, dim = 3;
  int dints = 1, dleafs = 1, ddeps = 1, csints = 0;
  
  ProgOptions po;
  po.addOpt<int>( "candidateplaneset,c", "Candidate plane set (0=SUBDIVISION,1=SUBDIV_SNAP,2=VERTEX_MEDIAN,3=VERTEX_SAMPLE", &csints);
  po.addOpt<int>( "ints,i", "Number of doublings of intervals on each side of scd mesh", &dints);
  po.addOpt<int>( "leaf,l", "Number of doublings of maximum number of elements per leaf", &dleafs);
  po.addOpt<int>( "max_depth,m", "Number of 5-intervals on maximum depth of tree", &ddeps);
  po.addOpt<int>( "npoints,n", "Number of query points", &npoints);
//  po.addOpt<void>( "print,p", "Print tree details", &print_tree);
  po.parseCommandLine(argc, argv);

  std::vector<int> ints, deps, leafs;
  ints.push_back(10);
  for (int i = 1; i < dints; i++) ints.push_back(2*ints[i-1]);
  deps.push_back(30);
  for (int i = 1; i < ddeps; i++) deps.push_back(deps[i-1]-5);
  leafs.push_back(6);
  for (int i = 1; i < dleafs; i++) leafs.push_back(2*leafs[i-1]);

  ErrorCode rval = MB_SUCCESS;
  std::cout << "Tree_type" << " "
            << "Elems_per_leaf" << " "
            << "Tree_depth" << " "
            << "Ints_per_side" << " "
            << "N_elements" << " "
            << "search_time" << " "
            << "perc_outside" << " "
            << "initTime" << " "
            << "nodesVisited" << " "
            << "leavesVisited" << " "
            << "numTraversals" << " "
            << "leafObjectTests" << std::endl;

// outermost iteration: # elements
  for (std::vector<int>::iterator int_it = ints.begin(); int_it != ints.end(); ++int_it) {
    Core mb;
    Range elems;
    rval = create_hex_mesh(mb, elems, *int_it, 3);
    if (MB_SUCCESS != rval) return rval;
    
      // iteration: tree depth
    for (std::vector<int>::iterator dep_it = deps.begin(); dep_it != deps.end(); ++dep_it) {
  
        // iteration: tree max elems/leaf
      for (std::vector<int>::iterator leafs_it = leafs.begin(); leafs_it != leafs.end(); ++leafs_it) {
  
          // iteration: tree type
        for (int tree_tp = 1; tree_tp < 2; tree_tp++) {
            // create tree
          Tree *tree;
          if (0 == tree_tp)
            tree = new BVHTree(&mb);
          else
            tree = new AdaptiveKDTree(&mb);

          std::ostringstream opts;
          opts << "MAX_DEPTH=" << *dep_it << ";MAX_PER_LEAF=" << *leafs_it;
          if (csints) {
            if (opts.str().length() > 0) 
              opts << ";";
            opts << "PLANE_SET=" << csints;
          }
          FileOptions fo(opts.str().c_str());
          rval = tree->parse_options(fo);
          if (MB_SUCCESS != rval) return rval;
          SpatialLocator sl(&mb, elems, tree);

            // call evaluation
          double cpu_time, perc_outside;
          rval = test_locator(sl, npoints, cpu_time, perc_outside);
          if (MB_SUCCESS != rval) return rval;

          std::cout << (tree_tp == 0 ? "BVH" : "KD") << " "
                    << *leafs_it << " "
                    << *dep_it << " "
                    << *int_it << " "
                    << (*int_it)*(*int_it)*(dim == 3 ? *int_it : 1) << " "
                    << cpu_time << " "
                    << perc_outside << " ";

          tree->tree_stats().output_all_stats();

        } // tree_tp

      } // max elems/leaf

    } // max depth

  } // # elements

  
#ifdef MOAB_HAVE_MPI
  fail = MPI_Finalize();
  if (fail) return fail;
#endif

  return 0;
}
Example #23
0
void  printWelcome(){
	Menu welcome("BLACK","BLUE","RED", 50,17,15,2);
		char ID[20];
		char passtemp[10];
		char idtemp[10];
		char subtemp;
		int password=0;
		
	
	COORD position;
	position.X=27;
	position.Y=5;


	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),position);
	cout << "Welcome To First Last Bank!";
	
	position.X+=3; position.Y+=4;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),position);
	cout << "Enter ID: ";



	
 position.Y+=2;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),position);
	cout << "Enter Password: "******"*";
	}
	else 
		i--;

	}
	
	password=atoi(passtemp);


	

	if(::found!=NULL && stricmp(::found->ID,ID)==0 && ::found->password==password)
	   {
		::counter=0;
		printMenu();		
		}
	else
	{
		
		::counter++;
		if(::counter == 3)
		{
			system("cls");
			printWarning();
		}
	position.X-=33;	position.Y+=10;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),position);
	cout << "Either the user or passwrod is incorrect, please try it again! " ;
	
	printWelcome();
	

	}


}
Example #24
0
	virtual void init() {
	
		SceneMainLoop::init();


#if 0


		Viewport *vp = memnew( Viewport );
		vp->set_world( Ref<World>( memnew( World )));
		get_root()->add_child(vp);

		vp->set_rect(Rect2(0,0,256,256));
		vp->set_as_render_target(true);
		vp->set_render_target_update_mode(Viewport::RENDER_TARGET_UPDATE_ALWAYS);


		Camera *camera = memnew( Camera );
		vp->add_child(camera);
		camera->make_current();

		TestCube *testcube = memnew( TestCube );
		vp->add_child(testcube);
		testcube->set_transform(Transform( Matrix3().rotated(Vector3(0,1,0),Math_PI*0.25), Vector3(0,0,-8)));

		Sprite *sp = memnew( Sprite );
		sp->set_texture( vp->get_render_target_texture() );
//		sp->set_texture( ResourceLoader::load("res://ball.png") );
		sp->set_pos(Point2(300,300));
		get_root()->add_child(sp);


		return;
#endif

		Panel * frame = memnew( Panel );
		frame->set_anchor( MARGIN_RIGHT, Control::ANCHOR_END );
		frame->set_anchor( MARGIN_BOTTOM, Control::ANCHOR_END );
		frame->set_end( Point2(0,0) );
		
		get_root()->add_child( frame );

		Label *label = memnew( Label );

		label->set_pos( Point2( 80,90 ) );
		label->set_size( Point2( 170,80 ) );
		label->set_align( Label::ALIGN_FILL );
		//label->set_text("There");
		label->set_text("There was once upon a time a beautiful unicorn that loved to play with little girls...");

		frame->add_child(label);

		Button *button = memnew( Button );

		button->set_pos( Point2( 20,20 ) );
		button->set_size( Point2( 1,1 ) );
		button->set_text("This is a biggie button");


		frame->add_child( button );


#if 0
		Sprite *tf = memnew( Sprite );
		frame->add_child(tf);
		Image img;
		ImageLoader::load_image("LarvoClub.png",&img);

		img.resize(512,512);
		img.generate_mipmaps();
		img.compress();
		Ref<Texture> text = memnew( Texture );
		text->create_from_image(img);
		tf->set_texture(text);
		tf->set_pos(Point2(50,50));
		//tf->set_scale(Point2(0.3,0.3));


		return;
#endif

		Tree * tree = memnew( Tree );
		tree->set_columns(2);

		tree->set_pos( Point2( 230,210 ) );
		tree->set_size( Point2( 150,250 ) );


		TreeItem *item = tree->create_item();
		item->set_editable(0,true);
		item->set_text(0,"root");
		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
		item->set_editable(0,true);
		item->set_text(0,"check");
		item->set_cell_mode(1, TreeItem::CELL_MODE_CHECK);
		item->set_editable(1,true);
		item->set_text(1,"check2");
		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
		item->set_editable(0,true);
		item->set_range_config(0,0,20,0.1);
		item->set_range(0,2);
		item->add_button(0,Theme::get_default()->get_icon("folder","FileDialog"));
		item->set_cell_mode(1, TreeItem::CELL_MODE_RANGE);
		item->set_editable(1,true);
		item->set_range_config(1,0,20,0.1);
		item->set_range(1,3);

		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
		item->set_editable(0,true);
		item->set_text(0,"Have,Many,Several,Options!");
		item->set_range(0,2);

		item = tree->create_item( item );
		item->set_editable(0,true);
		item->set_text(0,"Gershwin!");

		frame->add_child(tree);

		//control = memnew( Control );
		//root->add_child( control );


		
		LineEdit *line_edit = memnew( LineEdit );
		
		line_edit->set_pos( Point2( 30,190 ) );
		line_edit->set_size( Point2( 180,1 ) );
		
		frame->add_child(line_edit);
		
		HScrollBar *hscroll = memnew( HScrollBar );
		
		hscroll->set_pos( Point2( 30,290 ) );
		hscroll->set_size( Point2( 180,1 ) );
		hscroll->set_max(10);
		hscroll->set_page(4);
		
		frame->add_child(hscroll);



		SpinBox *spin = memnew( SpinBox );

		spin->set_pos( Point2( 30,260 ) );
		spin->set_size( Point2( 120,1 ) );

		frame->add_child(spin);
		hscroll->share(spin);

		ProgressBar *progress = memnew( ProgressBar );

		progress->set_pos( Point2( 30,330 ) );
		progress->set_size( Point2( 120,1 ) );

		frame->add_child(progress);
		hscroll->share(progress);

		MenuButton *menu_button = memnew( MenuButton );
		
		menu_button->set_text("I'm a menu!");
		menu_button->set_pos( Point2( 30,380 ) );
		menu_button->set_size( Point2( 1,1 ) );
		
		frame->add_child(menu_button);		
		
		PopupMenu *popup = menu_button->get_popup();
		
		popup->add_item("Hello, testing");
		popup->add_item("My Dearest");
		popup->add_separator();
		popup->add_item("Popup");
		popup->add_check_item("Check Popup");
		popup->set_item_checked(4,true);		
				
		OptionButton *options = memnew( OptionButton );
		
		options->add_item("Hello, testing");
		options->add_item("My Dearest");
		
		options->set_pos( Point2( 230,180 ) );
		options->set_size( Point2( 1,1 ) );
		
		frame->add_child(options);		

		/*
		Tree * tree = memnew( Tree );
		tree->set_columns(2);
		
		tree->set_pos( Point2( 230,210 ) );
		tree->set_size( Point2( 150,250 ) );


		TreeItem *item = tree->create_item();
		item->set_editable(0,true);
		item->set_text(0,"root");
		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
		item->set_editable(0,true);
		item->set_text(0,"check");
		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
		item->set_editable(0,true);
		item->set_range_config(0,0,20,0.1);
		item->set_range(0,2);
		item->add_button(0,Theme::get_default()->get_icon("folder","FileDialog"));
		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
		item->set_editable(0,true);
		item->set_text(0,"Have,Many,Several,Options!");
		item->set_range(0,2);
		
		frame->add_child(tree);
*/


		RichTextLabel *richtext = memnew( RichTextLabel );

		richtext->set_pos( Point2( 600,210 ) );
		richtext->set_size( Point2( 180,250 ) );
		richtext->set_anchor_and_margin(MARGIN_RIGHT,Control::ANCHOR_END,20);

		frame->add_child(richtext);


		richtext->add_text("Hello, My Friends!\n\nWelcome to the amazing world of ");

		richtext->add_newline();
		richtext->add_newline();

		richtext->push_color(Color(1,0.5,0.5));
		richtext->add_text("leprechauns");
		richtext->pop();

		richtext->add_text(" and ");
		richtext->push_color(Color(0,1.0,0.5));
		richtext->add_text("faeries.\n");
		richtext->pop();
		richtext->add_text("In this new episode, we will attemp to ");
		richtext->push_font(richtext->get_font("mono_font","Fonts"));
		richtext->push_color(Color(0.7,0.5,1.0));
		richtext->add_text("deliver something nice");
		richtext->pop();
		richtext->pop();
		richtext->add_text(" to all the viewers! Unfortunately, I need to ");
		richtext->push_underline();
		richtext->add_text("keep writing a lot of text");
		richtext->pop();
		richtext->add_text(" so the label control overflows and the scrollbar appears.\n");
		//richtext->push_indent(1);
		//richtext->add_text("By the way, testing indent levels! Yohohoho! Everything should appear to the right sightly here!\n");
		//richtext->pop();
		richtext->push_meta("http://www.scrollingcapabilities.xz");
		richtext->add_text("This allows to test for the scrolling capabilities ");
		richtext->pop();
		richtext->add_text("of the rich text label for huge text (not like this text will really be huge but, you know).\nAs long as it is so long that it will work nicely for a test/demo, then it's welcomed in my book...\nChanging subject, the day is cloudy today and I'm wondering if I'll get che chance to travel somewhere nice. Sometimes, watching the clouds from satellite images may give a nice insight about how pressure zones in our planet work, althogh it also makes it pretty obvious to see why most weather forecasts get it wrong so often.\nClouds are so difficult to predict!\nBut it's pretty cool how our civilization has adapted to having water falling from the sky each time it rains...");
		//richtext->add_text("Hello!\nGorgeous..");


		//richtext->push_meta("http://www.scrollingcapabilities.xz");
		///richtext->add_text("Hello!\n");
		//richtext->pop();

		richtext->set_anchor(MARGIN_RIGHT,Control::ANCHOR_END);


		TabContainer * tabc = memnew( TabContainer );

		Control *ctl= memnew( Control );
		ctl->set_name("tab 1");
		tabc->add_child(ctl);

		ctl= memnew( Control );
		ctl->set_name("tab 2");
		tabc->add_child(ctl);
		label = memnew( Label );
		label->set_text("Some Label");
		label->set_pos( Point2(20,20) );
		ctl->add_child(label);;

		ctl= memnew( Control );
		ctl->set_name("tab 3");
		button = memnew( Button );
		button->set_text("Some Button");
		button->set_pos( Point2(30,50) );
		ctl->add_child(button);;

		tabc->add_child(ctl);

		frame->add_child(tabc);
		
		tabc->set_pos( Point2( 400,210 ) );
		tabc->set_size( Point2( 180,250 ) );

		
		Ref<ImageTexture> text = memnew( ImageTexture );
		text->load("test_data/concave.png");

		Sprite* sprite = memnew(Sprite);
		sprite->set_texture(text);
		sprite->set_pos(Point2(300, 300));
		frame->add_child(sprite);
		sprite->show();

		Sprite* sprite2 = memnew(Sprite);
		sprite->set_texture(text);
		sprite->add_child(sprite2);
		sprite2->set_pos(Point2(50, 50));
		sprite2->show();
	}
Example #25
0
int TreeGroupCommand::process(vector<SharedRAbundVector*> thisLookup) {
	try{
		vector< vector< vector<seqDist> > > calcDistsTotals;  //each iter, one for each calc, then each groupCombos dists. this will be used to make .dist files
        vector< vector<seqDist>  > calcDists; calcDists.resize(treeCalculators.size()); 		
        
        for (int thisIter = 0; thisIter < iters; thisIter++) {
            
            vector<SharedRAbundVector*> thisItersLookup = thisLookup;
            
            if (subsample) {
                SubSample sample;
                vector<string> tempLabels; //dont need since we arent printing the sampled sharedRabunds
                
                //make copy of lookup so we don't get access violations
                vector<SharedRAbundVector*> newLookup;
                for (int k = 0; k < thisItersLookup.size(); k++) {
                    SharedRAbundVector* temp = new SharedRAbundVector();
                    temp->setLabel(thisItersLookup[k]->getLabel());
                    temp->setGroup(thisItersLookup[k]->getGroup());
                    newLookup.push_back(temp);
                }
                
                //for each bin
                for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
                    if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) {  delete newLookup[j];  } return 0; }
                    for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
                }
                
                tempLabels = sample.getSample(newLookup, subsampleSize);
                thisItersLookup = newLookup;
            }
            
            if(processors == 1){
                driver(thisItersLookup, 0, numGroups, calcDists);
            }else{
                int process = 1;
                vector<int> processIDS;
                
#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
                //loop through and create all the processes you want
                while (process != processors) {
                    pid_t pid = fork();
                    
                    if (pid > 0) {
                        processIDS.push_back(pid); 
                        process++;
                    }else if (pid == 0){
                        
                        driver(thisItersLookup, lines[process].start, lines[process].end, calcDists);   
                        
                        string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + m->mothurGetpid(process) + ".dist";
                        ofstream outtemp;
                        m->openOutputFile(tempdistFileName, outtemp);
                        
                        for (int i = 0; i < calcDists.size(); i++) {
                            outtemp << calcDists[i].size() << endl;
                            
                            for (int j = 0; j < calcDists[i].size(); j++) {
                                outtemp << calcDists[i][j].seq1 << '\t' << calcDists[i][j].seq2 << '\t' << calcDists[i][j].dist << endl;
                            }
                        }
                        outtemp.close();
                        
                        exit(0);
                    }else { 
                        m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
                        for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
                        exit(0);
                    }
                }
                
                //parent do your part
                driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);   
                
                //force parent to wait until all the processes are done
                for (int i = 0; i < processIDS.size(); i++) {
                    int temp = processIDS[i];
                    wait(&temp);
                }
                
                for (int i = 0; i < processIDS.size(); i++) {
                    string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(processIDS[i]) +  ".dist";
                    ifstream intemp;
                    m->openInputFile(tempdistFileName, intemp);
                    
                    for (int k = 0; k < calcDists.size(); k++) {
                        int size = 0;
                        intemp >> size; m->gobble(intemp);
                        
                        for (int j = 0; j < size; j++) {
                            int seq1 = 0;
                            int seq2 = 0;
                            float dist = 1.0;
                            
                            intemp >> seq1 >> seq2 >> dist;   m->gobble(intemp);
                            
                            seqDist tempDist(seq1, seq2, dist);
                            calcDists[k].push_back(tempDist);
                        }
                    }
                    intemp.close();
                    m->mothurRemove(tempdistFileName);
                }
#else
                //////////////////////////////////////////////////////////////////////////////////////////////////////
                //Windows version shared memory, so be careful when passing variables through the treeSharedData struct. 
                //Above fork() will clone, so memory is separate, but that's not the case with windows, 
                //Taking advantage of shared memory to pass results vectors.
                //////////////////////////////////////////////////////////////////////////////////////////////////////
                
                vector<treeSharedData*> pDataArray; 
                DWORD   dwThreadIdArray[processors-1];
                HANDLE  hThreadArray[processors-1]; 
                
                //Create processor worker threads.
                for( int i=1; i<processors; i++ ){
                    
                    //make copy of lookup so we don't get access violations
                    vector<SharedRAbundVector*> newLookup;
                    for (int k = 0; k < thisItersLookup.size(); k++) {
                        SharedRAbundVector* temp = new SharedRAbundVector();
                        temp->setLabel(thisItersLookup[k]->getLabel());
                        temp->setGroup(thisItersLookup[k]->getGroup());
                        newLookup.push_back(temp);
                    }
                    
                    //for each bin
                    for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
                        if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) {  delete newLookup[j];  } return 0; }
                        for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
                    }
                    
                    // Allocate memory for thread data.
                    treeSharedData* tempSum = new treeSharedData(m, lines[i].start, lines[i].end, Estimators, newLookup);
                    pDataArray.push_back(tempSum);
                    processIDS.push_back(i);
                    
                    hThreadArray[i-1] = CreateThread(NULL, 0, MyTreeSharedThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);   
                }
                
                //parent do your part
                driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);   
                
                //Wait until all threads have terminated.
                WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
                
                //Close all thread handles and free memory allocations.
                for(int i=0; i < pDataArray.size(); i++){
                    if (pDataArray[i]->count != (pDataArray[i]->end-pDataArray[i]->start)) {
                        m->mothurOut("[ERROR]: process " + toString(i) + " only processed " + toString(pDataArray[i]->count) + " of " + toString(pDataArray[i]->end-pDataArray[i]->start) + " groups assigned to it, quitting. \n"); m->control_pressed = true; 
                    }
                    for (int j = 0; j < pDataArray[i]->thisLookup.size(); j++) {  delete pDataArray[i]->thisLookup[j];  } 
                    
                    for (int k = 0; k < calcDists.size(); k++) {
                        int size = pDataArray[i]->calcDists[k].size();
                        for (int j = 0; j < size; j++) {    calcDists[k].push_back(pDataArray[i]->calcDists[k][j]);    }
                    }
                    
                    CloseHandle(hThreadArray[i]);
                    delete pDataArray[i];
                }
                
#endif
            }
            
            calcDistsTotals.push_back(calcDists);
            
            if (subsample) {  
                
                //clean up memory
                for (int i = 0; i < thisItersLookup.size(); i++) { delete thisItersLookup[i]; }
                thisItersLookup.clear();
                for (int i = 0; i < calcDists.size(); i++) {  calcDists[i].clear(); }
            }
            
            if (m->debug) {  m->mothurOut("[DEBUG]: iter = " + toString(thisIter) + ".\n"); }
		}
        
		if (m->debug) {  m->mothurOut("[DEBUG]: done with iters.\n"); }
            
        if (iters != 1) {
            //we need to find the average distance and standard deviation for each groups distance
            vector< vector<seqDist>  > calcAverages = m->getAverages(calcDistsTotals);  
            
            if (m->debug) {  m->mothurOut("[DEBUG]: found averages.\n"); }
            
            //create average tree for each calc
            for (int i = 0; i < calcDists.size(); i++) {
                vector< vector<double> > matrix; //square matrix to represent the distance
                matrix.resize(thisLookup.size());
                for (int k = 0; k < thisLookup.size(); k++) {  matrix[k].resize(thisLookup.size(), 0.0); }
                
                for (int j = 0; j < calcAverages[i].size(); j++) {
                    int row = calcAverages[i][j].seq1;
                    int column = calcAverages[i][j].seq2;
                    float dist = calcAverages[i][j].dist;
                    
                    matrix[row][column] = dist;
                    matrix[column][row] = dist;
                }
                
                //create a new filename
                map<string, string> variables; 
                variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(inputfile));
                variables["[calc]"] = treeCalculators[i]->getName();
                variables["[distance]"] = thisLookup[0]->getLabel();
                variables["[tag]"] = "ave";
                string outputFile = getOutputFileName("tree",variables);				
                outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile); 
                
                //creates tree from similarity matrix and write out file
                Tree* newTree = createTree(matrix);
                if (newTree != NULL) { writeTree(outputFile, newTree); }                
            }
            
            if (m->debug) {  m->mothurOut("[DEBUG]: done averages trees.\n"); }
            
            //create all trees for each calc and find their consensus tree
            for (int i = 0; i < calcDists.size(); i++) {
                if (m->control_pressed) { break; }
                
                //create a new filename
                //create a new filename
                map<string, string> variables; 
                variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(inputfile));
                variables["[calc]"] = treeCalculators[i]->getName();
                variables["[distance]"] = thisLookup[0]->getLabel();
                variables["[tag]"] = "all";
                string outputFile = getOutputFileName("tree",variables);				
                outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile); 
                
                ofstream outAll;
                m->openOutputFile(outputFile, outAll);
                
                vector<Tree*> trees; 
                for (int myIter = 0; myIter < iters; myIter++) {
                    
                    if(m->control_pressed) { break; }
                    
                    //initialize matrix
                    vector< vector<double> > matrix; //square matrix to represent the distance
                    matrix.resize(thisLookup.size());
                    for (int k = 0; k < thisLookup.size(); k++) {  matrix[k].resize(thisLookup.size(), 0.0); }
                    
                    for (int j = 0; j < calcDistsTotals[myIter][i].size(); j++) {
                        int row = calcDistsTotals[myIter][i][j].seq1;
                        int column = calcDistsTotals[myIter][i][j].seq2;
                        double dist = calcDistsTotals[myIter][i][j].dist;
                       
                        matrix[row][column] = dist;
                        matrix[column][row] = dist;
                    }
                    
                    //creates tree from similarity matrix and write out file
                    Tree* newTree = createTree(matrix);
                    if (newTree != NULL) { 
                        newTree->print(outAll);
                        trees.push_back(newTree);
                    }
                }
                outAll.close();
                if (m->control_pressed) { for (int k = 0; k < trees.size(); k++) { delete trees[k]; } }
                
                if (m->debug) {  m->mothurOut("[DEBUG]: done all trees.\n"); }
                
                Consensus consensus;
                //clear old tree names if any
                m->Treenames.clear(); m->Treenames = m->getGroups(); //may have changed if subsample eliminated groups
                Tree* conTree = consensus.getTree(trees);
                
                if (m->debug) {  m->mothurOut("[DEBUG]: done cons tree.\n"); }
                
                //create a new filename
                variables["[tag]"] = "cons";
                string conFile = getOutputFileName("tree",variables);				
                outputNames.push_back(conFile); outputTypes["tree"].push_back(conFile); 
                ofstream outTree;
                m->openOutputFile(conFile, outTree);
                
                if (conTree != NULL) { conTree->print(outTree, "boot"); delete conTree; }
            }

        }else {
            
            for (int i = 0; i < calcDists.size(); i++) {
                if (m->control_pressed) { break; }
                
                //initialize matrix
                vector< vector<double> > matrix; //square matrix to represent the distance
                matrix.resize(thisLookup.size());
                for (int k = 0; k < thisLookup.size(); k++) {  matrix[k].resize(thisLookup.size(), 0.0); }
                
                for (int j = 0; j < calcDists[i].size(); j++) {
                    int row = calcDists[i][j].seq1;
                    int column = calcDists[i][j].seq2;
                    double dist = calcDists[i][j].dist;
                    
                    matrix[row][column] = dist;
                    matrix[column][row] = dist;
                }
                
                //create a new filename
                map<string, string> variables; 
                variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(inputfile));
                variables["[calc]"] = treeCalculators[i]->getName();
                variables["[distance]"] = thisLookup[0]->getLabel();
                variables["[tag]"] = "";
                string outputFile = getOutputFileName("tree",variables);					
                outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile); 
                
                //creates tree from similarity matrix and write out file
                Tree* newTree = createTree(matrix);
                if (newTree != NULL) { writeTree(outputFile, newTree); delete newTree; }
            }
        }
		
		return 0;
	}
	catch(exception& e) {
		m->errorOut(e, "TreeGroupCommand", "process");
		exit(1);
	}
}
Example #26
0
void ProgressiveAlign(const SeqVect &v, const Tree &GuideTree, MSA &a)
	{
	assert(GuideTree.IsRooted());

#if	TRACE
	Log("GuideTree:\n");
	GuideTree.LogMe();
#endif

	const unsigned uSeqCount = v.Length();
	const unsigned uNodeCount = 2*uSeqCount - 1;

	ProgNode *ProgNodes = new ProgNode[uNodeCount];

	unsigned uJoin = 0;
	unsigned uTreeNodeIndex = GuideTree.FirstDepthFirstNode();
	SetProgressDesc("Align node");
	do
		{
		if (GuideTree.IsLeaf(uTreeNodeIndex))
			{
			if (uTreeNodeIndex >= uNodeCount)
				Quit("TreeNodeIndex=%u NodeCount=%u\n", uTreeNodeIndex, uNodeCount);
			ProgNode &Node = ProgNodes[uTreeNodeIndex];
			unsigned uId = GuideTree.GetLeafId(uTreeNodeIndex);
			if (uId >= uSeqCount)
				Quit("Seq index out of range");
			const Seq &s = *(v[uId]);
			Node.m_MSA.FromSeq(s);
			Node.m_MSA.SetSeqId(0, uId);
			Node.m_uLength = Node.m_MSA.GetColCount();
			}
		else
			{
			Progress(uJoin, uSeqCount - 1);
			++uJoin;

			const unsigned uMergeNodeIndex = uTreeNodeIndex;
			ProgNode &Parent = ProgNodes[uMergeNodeIndex];

			const unsigned uLeft = GuideTree.GetLeft(uTreeNodeIndex);
			const unsigned uRight = GuideTree.GetRight(uTreeNodeIndex);

			ProgNode &Node1 = ProgNodes[uLeft];
			ProgNode &Node2 = ProgNodes[uRight];

			PWPath Path;
			AlignTwoMSAs(Node1.m_MSA, Node2.m_MSA, Parent.m_MSA, Path);
			Parent.m_uLength = Parent.m_MSA.GetColCount();

			Node1.m_MSA.Clear();
			Node2.m_MSA.Clear();
			}
		uTreeNodeIndex = GuideTree.NextDepthFirstNode(uTreeNodeIndex);
		}
	while (NULL_NEIGHBOR != uTreeNodeIndex);
	ProgressStepsDone();

	unsigned uRootNodeIndex = GuideTree.GetRootNodeIndex();
	const ProgNode &RootProgNode = ProgNodes[uRootNodeIndex];
	a.Copy(RootProgNode.m_MSA);

	delete[] ProgNodes;
	ProgNodes = 0;
	}
Example #27
0
void Individual::MakeStepwiseTree(int nTax, int attachesPerTaxon, FLOAT_TYPE optPrecision ){
	treeStruct=new Tree();
	treeStruct->modPart = &modPart;
	treeStruct->AssignCLAsFromMaster();

	Individual scratchI;
	scratchI.treeStruct=new Tree();
	Tree *scratchT = scratchI.treeStruct;
	scratchT->modPart = &scratchI.modPart;
	scratchT->AssignCLAsFromMaster();
	scratchI.CopySecByRearrangingNodesOfFirst(scratchT, this, true);

	int n = nTax;
	Set taxset(n);
	for( int i = 1; i <= n; i++ )
		taxset += i;
		
	int placeInAllNodes=n+1;
//	ofstream stepout("stepwise.log");
	outman.UserMessage("number of taxa added:");

	Bipartition mask;//mask is used for constrained trees
	for(int i = 0;i<3;i++){//add the first 3
		int pos = rnd.random_int( taxset.Size() );
		int k = taxset[pos];
		if(treeStruct->constraints.empty())
			scratchT->AddRandomNode(k, placeInAllNodes  );
		else
			scratchT->AddRandomNodeWithConstraints(k, placeInAllNodes, &mask );
		taxset -= k;
		}
	//use information on the similarity between sequences to choose first stepwise additions
/*	
	const SequenceData *dat = treeStruct->data;
	int nstates = mod->NStates();
	FLOAT_TYPE **pdist = New2DArray<FLOAT_TYPE>(dat->NTax(), dat->NTax());
	for(int i=0;i<nTax;i++){
		pdist[i][i] = 0.0;
		for(int j=i+1;j<nTax;j++){
			pdist[i][j] = CalculateHammingDistance((char*) dat->GetRow(i), (char*) dat->GetRow(j), dat->GetCounts(), dat->NChar(), nstates);
			pdist[j][i] = pdist[i][j];
			}
		}
	//add the first 3
	//be careful because the taxa are indexed from 1->ntax
	int pos = rnd.random_int( taxset.Size() );
	int first = (taxset[pos]);
	scratchT->AddRandomNode(first, placeInAllNodes  );
	taxset -= first;
	
	//add the furthest taxon to that
	int sec = 1;
	FLOAT_TYPE maxDist = pdist[first-1][sec-1];
	for(int i=sec+1;i<=dat->NTax();i++){
		if(pdist[first-1][i-1] > maxDist){
			sec = i; 
			maxDist = pdist[first-1][sec-1];
			}
		}
	scratchT->AddRandomNode(sec, placeInAllNodes  );
	taxset -= sec;
	//add the furthest taxon to that (which may in fact be close to first, but should not have a pdist = 0 to it)
	int third = (first == 1 ? 2 : 1);
	maxDist = pdist[sec-1][third-1];
	for(int i=third+1;i<=dat->NTax();i++){
		if(pdist[sec-1][i] > maxDist && i != first && pdist[first-1][third-1] > ZERO_POINT_ZERO){
			third = i; 
			maxDist = pdist[sec-1][third-1];
			}
		}
	scratchT->AddRandomNode(third, placeInAllNodes  );
	taxset -= third;
*/
	CopySecByRearrangingNodesOfFirst(treeStruct, &scratchI, true);

	for( int i = 3; i < n; i++ ) {
		//select a random node
		int pos = rnd.random_int( taxset.Size() );
		int k = taxset[pos];
		taxset -= k;
		//add the node randomly - this is a little odd, but for the existing swap collecting machinery
		//to work right, the taxon to be added needs to already be in the tree
		if(treeStruct->constraints.empty())
			scratchT->AddRandomNode(k, placeInAllNodes  );
		else
			scratchT->AddRandomNodeWithConstraints(k, placeInAllNodes, &mask );
		TreeNode *added = scratchT->allNodes[k];

		scratchT->SweepDirtynessOverTree(added);
		scratchT->OptimizeBranchesWithinRadius(added->anc, optPrecision, 0, NULL);

		//backup what we have now
		CopySecByRearrangingNodesOfFirst(treeStruct, &scratchI, true);
		FLOAT_TYPE bestScore = scratchT->lnL;
		
		//collect reconnection points - this will automatically filter for constraints
		scratchT->GatherValidReconnectionNodes(scratchT->NTax()*2, added, NULL, &mask);
		
//			stepout << i << "\t" << k << "\t" << bestScore << "\t";

		//start swappin
		int num=0;
		//for(list<ReconNode>::iterator b = scratchT->sprRang.begin();b != scratchT->sprRang.end();b++){
		ReconList attempted;
		while(num < attachesPerTaxon && scratchT->sprRang.size() > 0){
			int connectNum = rnd.random_int(scratchT->sprRang.size());
			listIt broken = scratchT->sprRang.NthElement(connectNum);
			//try a reattachment point
			scratchT->SPRMutate(added->nodeNum, &(*broken), optPrecision, 0);
			//record the score
			broken->chooseProb = scratchT->lnL;
			attempted.AddNode(*broken);
			scratchT->sprRang.RemoveNthElement(connectNum);
//			stepout << scratchT->lnL << "\t";
			//restore the tree
			scratchI.CopySecByRearrangingNodesOfFirst(scratchT, this, true);
			num++;
			}
		//now find the best score
		ReconNode *best = NULL;
		
		//For debugging, add to random place, to check correct filtering of attachment points for constraints
/*
		if(attempted.size() != 0)
			best = attempted.RandomReconNode();
*/
		for(list<ReconNode>::iterator b = attempted.begin();b != attempted.end();b++){
			if((*b).chooseProb > bestScore){
				best = &(*b);
				bestScore = (*b).chooseProb;
				}
			}

		//if we didn't find anything better than the initial random attachment we don't need to do anything
		if(best != NULL){
			scratchT->SPRMutate(added->nodeNum, best, optPrecision, 0);
			}
		else scratchT->Score();
		scratchI.CalcFitness(0);

//		stepout << scratchT->lnL << endl;
		CopySecByRearrangingNodesOfFirst(treeStruct, &scratchI, true);

		//outman.UserMessage(" %d %f", i+1, scratchT->lnL);
		outman.UserMessageNoCR(" %d ", i+1);
		outman.flush();
		//when we've added half the taxa optimize alpha, flex or omega 
		if(i == (n/2)){
			FLOAT_TYPE improve = 0.0;
			for(int modnum = 0;modnum < modPart.NumModels();modnum++){
				Model *mod = scratchI.modPart.GetModel(modnum);
				const ModelSpecification *modSpec = mod->GetCorrespondingSpec();
				if(modSpec->IsCodon())//optimize omega even if there is only 1
					improve += scratchT->OptimizeOmegaParameters(optPrecision, modnum);
				else if(mod->NRateCats() > 1){
					if(modSpec->IsFlexRateHet()){//Flex rates
						//no longer doing alpha first, it was too hard to know if the flex rates had been partially optimized
						//already during making of a stepwise tree
						improve += scratchT->OptimizeFlexRates(optPrecision, modnum);
						}
					else if(modSpec->fixAlpha == false){//normal gamma
						//do NOT let alpha go too low here - on bad or random starting trees the branch lengths get crazy long
						improve += scratchT->OptimizeBoundedParameter(optPrecision, mod->Alpha(), 0, 0.05, 999.9, modnum, &Model::SetAlpha);
						}
					}
				if(modSpec->includeInvariantSites && !modSpec->fixInvariantSites)
					improve += scratchT->OptimizeBoundedParameter(optPrecision, mod->PropInvar(), 0, 1.0e-8, mod->maxPropInvar, modnum, &Model::SetPinv);
				}
			if(modSpecSet.InferSubsetRates()){
				improve += scratchT->OptimizeSubsetRates(optPrecision);
				}
			if(!FloatingPointEquals(improve, 0.0, 1e-8)) outman.UserMessage("\n   Optimizing parameters...    improved %8.3f lnL", improve);
		//	this used to depend on param improvement - not sure why
		//	if(rateOptImprove > 0.0){
				scratchT->Score();
				FLOAT_TYPE start=scratchT->lnL;
				scratchT->OptimizeAllBranches(optPrecision);
				FLOAT_TYPE bimprove = scratchT->lnL - start;
				outman.UserMessage("\nOptimizing branchlengths... improved %f lnL", bimprove);
	//			}
			}
		}		

//	stepout.close();
	outman.UserMessage("");
	scratchI.treeStruct->RemoveTreeFromAllClas();
	delete scratchI.treeStruct;
	scratchI.treeStruct=NULL;
	}
Example #28
0
Tree *Parser::Parse(text closing)
// ----------------------------------------------------------------------------
//   Parse input
// ----------------------------------------------------------------------------
/* XL parsing is not very difficult, but a bit unusual, because it is based
   solely on dynamic information and not, for instance, on keywords.
   Consider the following cases, where p is "prefix-op" and i is "infix-op"
     Write A
       Parses as p(Write,A).
     A and B
       Parses as i(and,A,B) if 'and' has a priority,
              as p(A,p(and,B)) otherwise
     Write -A,B
       This parses as (Write-A),B since "-" has a priority.
       I wish I could fix that one...
       The correct XL syntax is: Write (-A),B
       We hope that semantic will catch such a case later and let us know...
 */
{
    Tree *               result             = NULL;
    Tree *               left               = NULL;
    Tree *               right              = NULL;
    text                 prefix             = "";
    bool                 done               = false;
    int                  default_priority   = syntax.default_priority;
    int                  function_priority  = syntax.function_priority;
    int                  statement_priority = syntax.statement_priority;
    int                  result_priority    = default_priority;
    int                  prefix_priority    = 0;
    int                  prefix_vs_infix    = 0;
    int                  postfix_priority   = 0;
    int                  infix_priority     = 0;
    int                  paren_priority     = syntax.InfixPriority(closing);
    bool                 is_expression      = false;
    bool                 new_statement      = true;
    ulong                pos                = 0;
    uint                 old_indent         = 0;
    text                 infix, name, spelling;
    text                 comment_end;
    token_t              tok;
    char                 separator;
    text                 blk_opening, blk_closing;
    std::vector<Pending> stack;
    CommentsList         pendingComments;

    // When inside a () block, we are in 'expression' mode right away
    if (closing != "" && paren_priority > statement_priority)
    {
        new_statement = false;
        is_expression = true;
    }

    while (!done)
    {
        bool wasBeginningLine = beginningLine;

        // Scan next token
        right = NULL;
        prefix_priority = infix_priority = default_priority;
        tok = NextToken();

        // If we had comments after a token, add them to that token
        if (!wasBeginningLine && comments.size() && commented)
            AddComments(commented, false);

        // Check token result
        pos = scanner.Position();
        switch(tok)
        {
        case tokEOF:
        case tokERROR:
            done = true;
            if (closing != "" && closing != Block::unindent)
                errors.Log(Error("Unexpected end of text, expected $1",
                                 scanner.Position()).Arg(closing));
            break;
        case tokINTEGER:
            right = new Integer(scanner.IntegerValue(), pos);
            prefix_priority = function_priority;
            break;
        case tokREAL:
            right = new Real(scanner.RealValue(), pos);
            prefix_priority = function_priority;
            break;
        case tokLONGSTRING:
            right = new Text(scanner.TextValue(), openquote, closequote, pos);
            if (!result && new_statement)
                is_expression = false;
            prefix_priority = function_priority;
            break;
        case tokSTRING:
        case tokQUOTE:
            separator = scanner.TokenText()[0];
            name = text(1, separator);
            right = new Text(scanner.TextValue(), name, name, pos);
            if (!result && new_statement)
                is_expression = false;
            prefix_priority = function_priority;
            break;
        case tokNAME:
        case tokSYMBOL:
            name = scanner.TokenText();
            spelling = scanner.TextValue();
            if (name == closing)
            {
                done = true;
            }
            else if (Syntax *cs = syntax.HasSpecialSyntax(spelling,blk_closing))
            {
                // Read the input with the special syntax
                ulong pos = scanner.Position();
                Parser childParser(scanner, cs);
                right = childParser.Parse(blk_closing);
                right = new Prefix(new Name(name), right, pos);
            }
            else if (!result)
            {
                prefix_priority = syntax.PrefixPriority(name);
                right = new Name(spelling, pos);
                if (prefix_priority == default_priority)
                    prefix_priority = function_priority;
                if (new_statement && tok == tokNAME)
                    is_expression = false;
            }
            else if (left)
            {
                // This is the right of an infix operator
                // If we have "A and not B", where "not" has
                // higher priority than "and", we want to
                // parse this as "A and (not B)" rather than as
                // "(A and not) B"
                prefix_priority = syntax.PrefixPriority(name);
                right = new Name(spelling, pos);
                if (prefix_priority == default_priority)
                    prefix_priority = function_priority;
            }
            else
            {
                // Complicated case: need to discriminate infix and prefix
                infix_priority = syntax.InfixPriority(name);
                prefix_vs_infix = syntax.PrefixPriority(name);
                if (infix_priority != default_priority &&
                    (prefix_vs_infix == default_priority ||
                     !hadSpaceBefore || hadSpaceAfter))
                {
                    // We got an infix
                    left = result;
                    infix = name;
                }
                else
                {
                    postfix_priority = syntax.PostfixPriority(name);
                    if (postfix_priority != default_priority)
                    {
                        // We have a postfix operator
                        right = new Name(spelling, pos);
                        right = new Postfix(result, right, pos);
                        prefix_priority = postfix_priority;
                        result = NULL;
                    }
                    else
                    {
                        // No priority: take this as a prefix by default
                        right = new Name(spelling, pos);
                        prefix_priority = prefix_vs_infix;
                        if (prefix_priority == default_priority)
                        {
                            prefix_priority = function_priority;
                            if (new_statement && tok == tokNAME)
                                is_expression = false;
                        }
                    }
                }
            }
            break;
        case tokNEWLINE:
            // Consider new-line as an infix operator
            infix = "\n";
            name = infix;
            infix_priority = syntax.InfixPriority(infix);
            left = result;
            break;
        case tokPARCLOSE:
            // Check for mismatched parenthese here
            if (scanner.TokenText() != closing)
                errors.Log(Error("Mismatched parentheses: "
                                 "got $1, expected $2",
                                 pos).Arg(scanner.TokenText()).Arg(closing));
            done = true;
            break;
        case tokUNINDENT:
            // Check for mismatched blocks here
            if (closing != Block::unindent)
                errors.Log(Error("Mismatched identation, expected $1",
                                 pos).Arg(closing));
            done = true;
            break;
        case tokINDENT:
            scanner.SetTokenText(Block::indent);
            // Fall-through
        case tokPAROPEN:
            blk_opening = scanner.TokenText();
            if (!syntax.IsBlock(blk_opening, blk_closing))
                errors.Log(Error("Unknown parenthese type: $1 (internal)",
                                 pos).Arg(blk_opening));
            if (tok == tokPAROPEN)
                old_indent = scanner.OpenParen();
            name = blk_opening;
            paren_priority = syntax.InfixPriority(name);

            // Just like for names, parse the contents of the parentheses
            prefix_priority = paren_priority;
            infix_priority = default_priority;
            pendingComments = comments;
            comments.clear();
            right = Parse(blk_closing);
            if (tok == tokPAROPEN)
                scanner.CloseParen(old_indent);
            if (!right)
                right = new Name("", pos); // Case where we have ()
            right = new Block(right, blk_opening, blk_closing, pos);
            comments.insert(comments.end(),
                            pendingComments.begin(), pendingComments.end());
            break;
        default:
            if (true)
            {
                char buffer[20];
                sprintf(buffer, "%u", tok);
                errors.Log(Error("Internal error: unknown token $1 ($2)",
                                 pos).Arg(scanner.TokenText()).Arg(buffer));
            }
            break;
        } // switch(tok)


        // Attach any comments we may have had and return the result
        if (right)
        {
            commented = right;
            if (comments.size())
                AddComments(commented, true);
        }
        else if (left && (pending == tokNONE || pending == tokNEWLINE))
        {
            // We just got 'then', but 'then' will be an infix
            // so we can't really attach comments to it.
            // Instead, we defer the comment to the next 'right'
            commented = NULL;
        }
            

        // Check what is the current result
        if (!result)
        {
            // First thing we parse
            result = right;
            result_priority = prefix_priority;

            // We are now in the middle of an expression
            if (result && result_priority >= statement_priority)
                new_statement= false;
        }
        else if (left)
        {
            // Check if we had a statement separator
            if (infix_priority < statement_priority)
            {
                new_statement = true;
                is_expression = false;
            }

            // We got left and infix-op, we are now looking for right
            // If we have 'A and not B', where 'not' has higher priority
            // than 'and', we want to finish parsing 'not B' first, rather
            // than seeing this as '(A and not) B'.
            if (prefix_priority != default_priority)
            {
                // Push "A and" in the above example
                ulong st_pos = new_statement ? left->Position() : pos;
                stack.push_back(Pending(infix, left, infix_priority, st_pos));
                left = NULL;

                // Start over with "not"
                result = right;
                result_priority = prefix_priority;
            }
            else
            {
                while (stack.size())
                {
                    Pending &prev = stack.back();

                    // Check priorities compared to stack
                    // A + B * C, we got '*': keep "A+..." on stack
                    // Odd priorities are made right-associative by
                    // turning the low-bit off in the comparison below
                    if (!done &&
                        prev.priority != default_priority &&
                        infix_priority > (prev.priority & ~1))
                        break;
                    if (prev.opcode == prefix)
                        left = CreatePrefix(prev.argument, left, prev.position);
                    else
                        left = new Infix(prev.opcode, prev.argument, left,
                                         prev.position);
                    stack.pop_back();
                }

                // Now, we want to restart with the rightmost operand
                if (done)
                {
                    // End of text: the result is what we just got
                    result = left;
                }
                else
                {
                    // Something like A+B+C, just got second +
                    ulong st_pos = new_statement ? left->Position() : pos;
                    stack.push_back(Pending(infix,left,infix_priority,st_pos));
                    result = NULL;
                }
                left = NULL;
            }
        }
        else if (right)
        {
            // Check if we had a low-priority prefix (e.g. pragmas)
            if (prefix_priority < statement_priority)
            {
                new_statement = true;
                is_expression = false;
            }

            // Check priorities for something like "A.B x,y" -> "(A.B) (x,y)"
            // Odd priorities are made right associative by turning the
            // low bit off for the previous priority
            if (prefix_priority <= result_priority)
            {
                while (stack.size())
                {
                    Pending &prev = stack.back();
                    if (!done &&
                        prev.priority != default_priority &&
                        result_priority > (prev.priority & ~1))
                        break;
                    if (prev.opcode == prefix)
                        result = CreatePrefix(prev.argument, result,
                                              prev.position);
                    else
                        result = new Infix(prev.opcode, prev.argument,
                                           result, prev.position);
                    stack.pop_back();
                }
            }

            // Check if new statement
            if (!is_expression)
                if (result_priority > statement_priority)
                    if (stack.size() == 0 ||
                        stack.back().priority < statement_priority)
                        result_priority = statement_priority;

            // Push a recognized prefix op
            stack.push_back(Pending(prefix,result,result_priority,pos));
            result = right;
            result_priority = prefix_priority;
        }
    } // While(!done)

    if (stack.size())
    {
        if (!result)
        {
            Pending &last = stack.back();
            if (last.opcode != text("\n"))
                result = new Postfix(last.argument,
                                     new Name(last.opcode, last.position));
            else
                result = last.argument;
            stack.pop_back();
        }

        // Check if some stuff remains on stack
        while (stack.size())
        {
            Pending &prev = stack.back();
            if (prev.opcode == prefix)
                result = CreatePrefix(prev.argument, result, prev.position);
            else
                result = new Infix(prev.opcode, prev.argument,
                                   result, prev.position);
            stack.pop_back();
        }
    }

    return result;
}
Example #29
0
	bool TestBTree::testCopy()
	{
		status << "Running Test Copy\n";

		Map map;
		Tree tree;
		Vector vector( elements );
		_init( vector );
		
		for( unsigned int i = 0; i < iterations; ++i )
		{
			switch( random() % 2 )
			{
				case 0:
				{
					size_t index = random() % vector.size();
					map.insert( std::make_pair( vector[ index ], i ) );
					tree.insert( std::make_pair( vector[ index ], i ) );						
					break;
				}
								
				case 1:
				{
					size_t index = random() % vector.size();
					Map::iterator mi = map.find( vector[ index ] );
					Tree::iterator ti = tree.find( vector[ index ] );
					
					if( mi != map.end() )
					{
						map.erase( mi );
						tree.erase( ti );
					}
					break;
				}
			}
		}
		
		Tree copy( tree );
		
		{
			Map::iterator mi = map.begin();
			Tree::iterator ti = copy.begin();

			for( ; mi != map.end() && ti != copy.end(); ++mi, ++ti )
			{
				if( mi->first != ti->first )
				{
					status << "Copy failed, map key " << mi->first
						<< " does not match tree key " << ti->first 
						<< "\n";
					dumpTree( copy, path );
					return false;
				}
				if( mi->second != ti->second )
				{
					status << "Copy failed, map value " 
						<< mi->second
						<< " does not match tree value " << ti->second 
						<< "\n";
					dumpTree( copy, path );
					return false;
				}
			}
		}
		
		copy.clear();
		copy = tree;

		{
			Map::iterator mi = map.begin();
			Tree::iterator ti = copy.begin();

			for( ; mi != map.end() && ti != copy.end(); ++mi, ++ti )
			{
				if( mi->first != ti->first )
				{
					status << "Assign failed, map key " << mi->first
						<< " does not match tree key " << ti->first << "\n";
					dumpTree( copy, path );
					return false;
				}
				if( mi->second != ti->second )
				{
					status << "Assign failed, map value " 
						<< mi->second
						<< " does not match tree value " << ti->second << "\n";
					dumpTree( copy, path );
					return false;
				}
			}
		}
	
		status << "  Test Copy Passed.\n";
		return true;
	}
Example #30
0
bool isBoxReal(Tree t, double* r)	{ return isDouble(t->node(), r); }