int SystematicSearchController::run()
{
	const amarsi::State & state = amarsi::Supervisor::instance().state();

	d_duration = 30.0;

	// Write headers in result file
	file_stats << "amplitudeForeHip amplitudeHindHip offsetForeHip offsetHindHip "
		<< "amplitudeForeKnee amplitudeHindKnee offsetKnee kneePhaseLag "
		<< "frequency duration distance angle stability" << std::endl;
	file_time << "time distance" << std::endl;

	//=====================================================================
	// INITIALIZATION OF THE SYSTEMATIC SEARCH
	//=====================================================================
	// Here we initialize the systematic serach, by frozing some parameters
	// to some fixed value, and defining on what interval the other are left
	// open. In this example we made arbritraty choice but its up to you to
	// find the right set of parameter you left open, in term of what
	// interpretation you will be able to get from the result, and time of
	// computation.
	//~ //=====================================================================

//~ //GAIT 1
	//~ d_amplitudeForeHip  = 0.4;
	//~ d_amplitudeHindHip  = 0.4;
	//~ d_amplitudeForeKnee = 0.6333;
	//~ d_amplitudeHindKnee = 0.3667;
	//~ // Offsets
	//~ d_offsetForeHip = 0.0667;
	//~ d_offsetHindHip = -0.0667;
	//~ d_offsetKnee    = 0.2;  //not a variable
	//~ // Phase lag between knee and hip
	//~ d_kneePhaseLag = 0.8;
  //~ //d_kneePhaseLag_t = atof(pref_value.c_str());

	// Frequency of the gait
	//~ d_frequency = 2;     //not a variable
  

  //~ //Best gait
	//~ d_amplitudeForeHip  = 0.5;
	//~ d_amplitudeHindHip  = 0.5;
	//~ d_amplitudeForeKnee = 0.6133;
	//~ d_amplitudeHindKnee = 0.5067;
	//~ // Offsets
	//~ d_offsetForeHip = 0.0667;
	//~ d_offsetHindHip = -0.0667;
	//~ d_offsetKnee    = 0.2;  //not a variable
	//~ // Phase lag between knee and hip
	//~ d_kneePhaseLag = 0.8;
  
	//~ // Frequency of the gait
	//~ d_frequency = 2;     //not a variable
  
  //~ // Fall over gait
	d_amplitudeForeHip  = 0.5;
	d_amplitudeHindHip  = 0.5;
	d_amplitudeForeKnee = 0.6133;
	d_amplitudeHindKnee = 0.5267;
	// Offsets
	d_offsetForeHip = 0.0667;
	d_offsetHindHip = -0.0667;
	d_offsetKnee    = 0.2;  //not a variable
	// Phase lag between knee and hip
	d_kneePhaseLag = 0.8;
  
	// Frequency of the gait
	d_frequency = 2;     //not a variable
  
    
  //Most stable gait
	//~ d_amplitudeForeHip  = 0.25;
	//~ d_amplitudeHindHip  = 0.25;
	//~ d_amplitudeForeKnee = 0.47
  33;
	//~ d_amplitudeHindKnee = 0.2867;
	//~ // Offsets
	//~ d_offsetForeHip = 0.0667;
	//~ d_offsetHindHip = -0.0667;
	//~ d_offsetKnee    = 0.2;  //not a variable
	//~ // Phase lag between knee and hip
	//~ d_kneePhaseLag = 0.8;
  //~ //d_kneePhaseLag_t = atof(pref_value.c_str());
  
	// Frequency of the gait
	//~ d_frequency = 2;     //not a variable


//~ // FASTEST GAIT
	//~ d_amplitudeForeHip  = 0.6;
	//~ d_amplitudeHindHip  = 0.6;
	//~ d_amplitudeForeKnee = 0.4733;
	//~ d_amplitudeHindKnee = 0.2667;
	//~ // Offsets
	//~ d_offsetForeHip = 0.0667;
	//~ d_offsetHindHip = -0.0667;
	//~ d_offsetKnee    = 0.2;  //not a variable
	//~ // Phase lag between knee and hip
	//~ d_kneePhaseLag = 0.8;
	//~ // Frequency of the gait
	//~ d_frequency = 2.0;
  //~ //not a variable


//~ // Second Fastest gait
	//~ d_amplitudeForeHip_t  = 0.6;
	//~ d_amplitudeHindHip_t  = 0.6;
	//~ d_amplitudeForeKnee_t = 0.6133;
	//~ d_amplitudeHindKnee_t = 0.1667;
	//~ // Offsets
	//~ d_offsetForeHip_t = 0.0667;
	//~ d_offsetHindHip_t = -0.0667;
	//~ d_offsetKnee    = 0.2;  //not a variable
	//~ // Phase lag between knee and hip
	//~ d_kneePhaseLag_t = 0.8;
  //~ //d_kneePhaseLag_t = atof(pref_value.c_str());

	//~ // Frequency of the gait
	//~ d_frequency = 2;     //not a variable


	double max_angle(1);
	double stability(0);

	//Get the position of the legs of the robot
	double xForeLeft, xHindLeft;
	double xForeRight, xHindRight;
	double yForeLeft, yHindLeft;
	double yForeRight, yHindRight;
	double fxForeLeft, fxHindLeft, fxForeRight, fxHindRight;
	double fyForeLeft, fyHindLeft, fyForeRight, fyHindRight;

	file_hip_trajectory 
		<< "setHForeLeft setHHindLeft setHForeRight setHHindRight " 
		<< "realHForeLeft realHHindLeft realHForeRight realHHindRight "
		<< "distance" << std::endl;

	file_knee_trajectory 
		<< "setKForeLeft setKHindLeft setKForeRight setKHindRight " 
		<< "realKForeLeft realKHindLeft realKForeRight realKHindRight "
		<< "distance" << std::endl;

	file_leg_trajectory_rframe << "distance xForeLeft yForeLeft xHindLeft yHindLeft "
		<< "xForeRight yForeRight xHindRight yHindRight" << std::endl;
	file_leg_trajectory << "distance xForeLeft yForeLeft xHindLeft yHindLeft "
		<< "xForeRight yForeRight xHindRight yHindRight" << std::endl;
	file_forces << "distance fxForeLeft fyForeLeft fxHindLeft fyHindLeft "
		<< "fxForeRight fyForeRight fxHindRight fyHindRight" << std::endl;
	file_rob_trajectory << "distance x y z pitch roll" << std::endl;
	//const amarsi::State &state = amarsi::Supervisor::instance().state();


	// Run the simulation for d_duration seconds
	while (amarsi::Clock::getTime() < d_duration)
	{
		// Set all the desired joint angles
		generateTrotTrajectories();

		// Simulate one timestep
		step();

		//=============================================================
		// TEST OF THE STATE OF THE ROBOT
		// ============================================================
		// Here we test the state of the robot, and if it is in a bad
		// situation, (for example it as fallen on the ground), we stop
		// the run to spare some computation time. You can (and we
		// encourage you) remove or add test here
		// ============================================================

		//Get the position of the legs of the robot

		Vector3 frontDirection = state.frontDirection;
		frontDirection.y() = 0.0;
		frontDirection.normalize();
		double distance = max(((state.position - state.startingPosition) * frontDirection), 0.0);

		file_time << amarsi::Clock::getTime() << " " << distance << std::endl;

		// positions in robot frame
		Vector3 foreLeft_r = GetLegPosition(amarsi::LEFT_FORE);
		Vector3 hindLeft_r = GetLegPosition(amarsi::LEFT_HIND);
		Vector3 foreRight_r = GetLegPosition(amarsi::RIGHT_FORE);
		Vector3 hindRight_r = GetLegPosition(amarsi::RIGHT_HIND);

		// translate to world frame
		Vector3 foreLeft = state.orientation.conj().rotate(foreLeft_r);
		Vector3 hindLeft = state.orientation.conj().rotate(hindLeft_r);
		Vector3 foreRight = state.orientation.conj().rotate(foreRight_r);
		Vector3 hindRight = state.orientation.conj().rotate(hindRight_r);


		xForeLeft = foreLeft[0];
		xHindLeft = hindLeft[0];
		xForeRight = foreRight[0];
		xHindRight = hindRight[0];

		yForeLeft = foreLeft[1];
		yHindLeft = hindLeft[1];
		yForeRight = foreRight[1];
		yHindRight = hindRight[1];

		// in the world's frame:
		file_leg_trajectory << distance << " "
			<< xForeLeft << " " << yForeLeft << " "
			<< xHindLeft << " " << yHindLeft << " "
			<< xForeRight << " " << yForeRight << " "
			<< xHindRight << " " << yHindRight << std::endl;

		// in the robot's frame:
		file_leg_trajectory_rframe << distance << " "
			<< foreLeft_r[0] << " " << foreLeft_r[1] << " "
			<< hindLeft_r[0] << " " << hindLeft_r[1] << " "
			<< foreRight_r[0] << " " << foreRight_r[1] << " "
			<< hindRight_r[0] << " " << hindRight_r[1] << std::endl;

		fxForeLeft = GetGroundReactionForces(amarsi::LEFT_FORE)[0];
		fxHindLeft = GetGroundReactionForces(amarsi::LEFT_HIND)[0];
		fxForeRight = GetGroundReactionForces(amarsi::RIGHT_FORE)[0];
		fxHindRight = GetGroundReactionForces(amarsi::RIGHT_HIND)[0];

		fyForeLeft = GetGroundReactionForces(amarsi::LEFT_FORE)[1];
		fyHindLeft = GetGroundReactionForces(amarsi::LEFT_HIND)[1];
		fyForeRight = GetGroundReactionForces(amarsi::RIGHT_FORE)[1];
		fyHindRight = GetGroundReactionForces(amarsi::RIGHT_HIND)[1];

		file_forces 
			<< distance << " "
			<< fxForeLeft << " "
			<< fyForeLeft << " "
			<< fxHindLeft << " "
			<< fyHindLeft << " "
			<< fxForeRight << " "
			<< fyForeRight << " "
			<< fxHindRight << " "
			<< fyHindRight << std::endl;

		// POSITION, PITCH, AND ROLL 
		double rob_x = state.position.cx();
		double rob_y = state.position.cy();
		double rob_z = state.position.cz();
		double pitch = getPitchAngle();
		double roll  = getRollAngle();

		file_rob_trajectory 
			<< distance << " "
			<< rob_x << " "
			<< rob_y << " "
			<< rob_z << " "
			<< pitch << " "
			<< roll << std::endl;

		// Hip and knee position, compare set value to real value. Position
		// here means the ANGLE.
		// hips:
		double realHForeLeft;
		double realHForeRight;
		double realHHindLeft;
		double realHHindRight;

		realHForeLeft = actuator(amarsi::LEFT_FORE_HIP).position();
		realHHindLeft = actuator(amarsi::LEFT_HIND_HIP).position();
		realHForeRight = actuator(amarsi::RIGHT_FORE_HIP).position();
		realHHindRight = actuator(amarsi::RIGHT_HIND_HIP).position();

		// set values were already printed by generateTrotTrajectories
		file_hip_trajectory 
			<< realHForeLeft << " " 
			<< realHHindLeft << " " 
			<< realHForeRight << " " 
			<< realHHindRight << " "  
			<< distance << std::endl;

		// knees
		double realKForeLeft;
		double realKForeRight;
		double realKHindLeft;
		double realKHindRight;

		realKForeLeft = kneeEncoder(amarsi::LEFT_FORE).position();
		realKHindLeft = kneeEncoder(amarsi::LEFT_HIND).position();
		realKForeRight = kneeEncoder(amarsi::RIGHT_FORE).position();
		realKHindRight = kneeEncoder(amarsi::RIGHT_HIND).position();

		file_knee_trajectory
			<< realKForeLeft << " " 
			<< realKHindLeft << " " 
			<< realKForeRight << " " 
			<< realKHindRight << " " 
			<< distance << std::endl;


		//MAX ANGLE
		//correxpond a un test si l'angle entre les deux vecteurs est plus grand que 60 degrés
		//if(state.startingUpDirection*state.upDirection < 0.5)
		if (state.startingUpDirection*state.upDirection < max_angle)
			max_angle = state.startingUpDirection*state.upDirection;

		//STABILITY
		//The higher the less stable
		stability += state.startingUpDirection*state.upDirection;


		if (state.upDirection * state.startingUpDirection < cos(80 * PI / 180.0))
		{
			// Here the robot has a roll or pitch of more than 80
			// degrees
			break;
		}
      }
      
	//=====================================================
	// OUTPUT SECTION
	//=====================================================
	// Here we compute the value we monitor. We give some
	// example as comment, but there is better way to do it,
	// and better value to monitor.
	//=====================================================

	// First we output the parameters used for the run
	file_stats << d_amplitudeForeHip << " "
		<< d_amplitudeHindHip << " "
		<< d_offsetForeHip << " "
		<< d_offsetHindHip << " "
		<< d_amplitudeForeKnee << " "
		<< d_amplitudeHindKnee << " "
		<< d_offsetKnee << " "
		<< d_kneePhaseLag << " "
		<< d_frequency << " ";

	double duration = amarsi::Clock::getTime();

	file_stats << duration << " ";

	// Compute the algebraic distance in front direction of
	// the robot

	Vector3 frontDirection = state.frontDirection;

	frontDirection.y() = 0.0;
	frontDirection.normalize();

	double distance = max(((state.position - state.startingPosition) * frontDirection), 0.0);
	file_stats << distance << " ";

	file_stats << max_angle << " ";

	stability /= duration; // normalize by time
	file_stats << stability << " ";

	// Note: You may want to add other values!!!

	// Close the line
	file_stats << std::endl;

	// Reset the position and dynamics of the robot for the
	// next run.
	// amarsi::Supervisor::instance().resetSimulation();
	//cout << image_file << endl;
	//}

	//cout << image_file << endl;
  
	//~ webots::Supervisor().exportImage(image_file, 100);
  
	// amarsi::Supervisor::instance().simulationQuit();
  
	file_time.close();
	file_stats.close();
	file_leg_trajectory.close();
	file_leg_trajectory_rframe.close();
	file_hip_trajectory.close();
	file_knee_trajectory.close();
	file_rob_trajectory.close();
	file_forces.close();

	return 0;
}
Esempio n. 2
0
	~KinectDataDumper() {
		timestampStream.close();
	}
Esempio n. 3
0
	void closefile(){
		ply_file.seekp(pos);
		ply_file << i;
		ply_file.close();
	}
Esempio n. 4
0
int ProjectShell::computeIntersections()
{
  // will start at 2 triangles, and advance an intersection front (2 queues, one for red triangles, one for blue ..)
  // will mark a red triangle that is processed, and add to the queue
  // for each red triangle will find all the blue triangles that are intersected
  // find first 2 triangles that intersect: these will be the seeds for intersection

  int startRed=0;
  int startBlue = 0;
  for (startBlue = 0; startBlue<m_numNeg; startBlue++)
    {
      double area = 0;
      // if area is > 0 , we have intersections
      double P[24]; // max 6 points, but it may grow bigger; why worry
      int nP = 0;
      int n[3];// sides
      computeIntersectionBetweenRedAndBlue(/* red */0, startBlue, P, nP, area,n);
      if (area>0)
	break; // found 2 triangles that intersect; these will be the seeds
    }
  if (startBlue==m_numNeg)
    {
      // can't find any triangle stop
      exit (1);
    }
  // on the red edges, we will keep a list of new points (in 2D)
  // they will be used to create or not new points for points P from intersection
  // (sometimes the points P are either on sides, or on vertices of blue or even red triangles)

  /*
    matlab code: 
    function M=InterfaceMatrix(Na,Ta,Nb,Tb);
    % INTERFACEMATRIX projection matrix for nonmatching triangular grids 
    %   M=InterfaceMatrix(Na,Ta,Nb,Tb); takes two triangular meshes Ta
    %   and Tb with associated nodal coordinates in Na and Nb and
    %   computes the interface projection matrix M

    bl=[1];                        % bl: list of triangles of Tb to treat
    bil=[1];                       % bil: list of triangles Ta to start with
    bd=zeros(size(Tb,1)+1,1);      % bd: flag for triangles in Tb treated 
    bd(end)=1;                     % guard, to treat boundaries
    bd(1)=1;                       % mark first triangle in b list.
    M=sparse(size(Nb,2),size(Na,2));
    while length(bl)>0
    bc=bl(1); bl=bl(2:end);      % bc: current triangle of Tb 
    al=bil(1); bil=bil(2:end);   % triangle of Ta to start with
    ad=zeros(size(Ta,1)+1,1);    % same as for bd
    ad(end)=1;
    ad(al)=1; 
    n=[0 0 0];                   % triangles intersecting with neighbors
    while length(al)>0
    ac=al(1); al=al(2:end);    % take next candidate
    [P,nc,Mc]=Intersect(Nb(:,Tb(bc,1:3)),Na(:,Ta(ac,1:3)));
    if ~isempty(P)             % intersection found
    M(Tb(bc,1:3),Ta(ac,1:3))=M(Tb(bc,1:3),Ta(ac,1:3))+Mc;
    t=Ta(ac,3+find(ad(Ta(ac,4:6))==0)); 
    al=[al t];               % add neighbors 
    ad(t)=1;
    n(find(nc>0))=ac;        % ac is starting candidate for neighbor  
    end
    end
    tmp=find(bd(Tb(bc,4:6))==0); % find non-treated neighbors
    idx=find(n(tmp)>0);          % take those which intersect
    t=Tb(bc,3+tmp(idx));
    bl=[bl t];                   % and add them
    bil=[bil n(tmp(idx))];       % with starting candidates Ta
    bd(t)=1;
    end
  */
  std::queue<int> blueQueue; // these are corresponding to Ta,
  blueQueue.push( startBlue);
  std::queue<int> redQueue;
  redQueue.push (startRed);
  // the flags are used for marking the triangles already considered
  int * blueFlag = new int [m_numNeg+1]; // number of blue triangles + 1, to account for the boundary
  int k=0;
  for (k=0; k<m_numNeg; k++)
    blueFlag[k] = 0;
  blueFlag[m_numNeg] = 1; // mark the "boundary"; stop at the boundary
  blueFlag[startBlue] = 1; // mark also the first one
  // also, red flag is declared outside the loop
  int * redFlag = new int [m_numPos+1];
  
  if (dbg)
    mout.open("patches.m");
  while( !blueQueue.empty() )
    {
      int n[3]; // flags for the side : indices in red mesh start from 0!!! (-1 means not found )
      for (k=0; k<3; k++)
	n[k] = -1; // a paired red not found yet for the neighbors of blue 
      int currentBlue = blueQueue.front();
      blueQueue.pop();
      for (k=0; k<m_numPos; k++)
	redFlag[k] = 0;
      redFlag[m_numPos] = 1; // to guard for the boundary
      int currentRed = redQueue.front(); // where do we check for redQueue???? 
      // red and blue queues are parallel
      redQueue.pop();// 
      redFlag[currentRed] = 1; // 
      std::queue<int> localRed;
      localRed.push(currentRed);
      while( !localRed.empty())
	{
	  // 
	  int redT = localRed.front();
	  localRed.pop();
	  double P[24], area;
          int nP = 0; // intersection points
	  int nc[3]= {0, 0, 0}; // means no intersection on the side (markers)
          computeIntersectionBetweenRedAndBlue(/* red */redT, currentBlue, P, nP, area,nc);
	  if (nP>0) 
	    {
	      // intersection found: output P and original triangles if nP > 2
	      if (dbg && area>0)
		{
		  //std::cout << "area: " << area<< " nP:"<<nP << " sources:" << redT+1 << ":" << m_redMesh[redT].oldId <<
		  //  " " << currentBlue+1<< ":" << m_blueMesh[currentBlue].oldId << std::endl;
		}
              if (dbg)
		{
		  mout << "pa=[\n";
		  
		  for (k=0; k<nP; k++)
		    {
		     
		      mout <<  P[2*k] << "\t " ;
		    }
	
		  mout << "\n";
		  for (k=0; k<nP; k++)
		    {
		    
		      mout << P[2*k+1] << "\t "; 
		    }
	
		  mout << " ]; \n";
		  mout << " patch(pa(1,:),pa(2,:),'m');       \n";
		}
	      // add neighbors to the localRed queue, if they are not marked
	      for (int nn= 0; nn<3; nn++)
		{
		  int neighbor = m_redMesh[redT].t[nn];
		  if (redFlag[neighbor] == 0)
		    {
		      localRed.push(neighbor);
		      redFlag[neighbor] =1; // flag it to not be added anymore
		    }
		  // n(find(nc>0))=ac;        % ac is starting candidate for neighbor
		  if (nc[nn]>0) // intersected  
		    n[nn] = redT;// start from 0!! 
		}
              if (nP>1) // this will also construct triangles, if needed
		findNodes(redT, currentBlue, P, nP);
	    }
	  
	}
      for (int j=0; j<3; j++)
	{
	  int blueNeigh = m_blueMesh[currentBlue].t[j];
	  if (blueFlag[blueNeigh]==0 && n[j] >=0 ) // not treated yet and marked as a neighbor
	    {
              // we identified triangle n[j] as intersecting with neighbor j of the blue triangle
	      blueQueue.push(blueNeigh);
	      redQueue.push(n[j]);
	      if (dbg)
		std::cout << "new triangles pushed: blue, red:" << blueNeigh+1 << " " << n[j]+1 << std::endl;
	      blueFlag[blueNeigh] = 1;
	    }
	}
    }
  delete [] redFlag;
  redFlag = NULL;

  delete [] blueFlag; // get rid of it
  blueFlag = NULL;
  if (dbg)
    mout.close();
  return 0;
}
Esempio n. 5
0
void CProgAndPlay::Update(void) {
	//log("ProgAndPLay::Update begin");

	// std::stringstream ss;

	// try to identify new pull of traces
	char * msg = PP_PopMessage();
	bool tracesComing = msg != NULL;
	// even if trace module is not activated, we pop messages by security in order to
	// avoid to fill shared memory in case of P&P client push traces whereas trace
	// module is not activated.
	while (msg != NULL) {
		std::string line (msg);
		if (traceModuleCorrectlyInitialized){
			if (line.find(EXECUTION_START_TIME) != std::string::npos){ // if we detect a new P&P program execution
				log("CProgAndPlay : new execution detected");
				newExecutionDetected = true;
				endExecutionDetected = false;
				units_idled_frame_counter = 0; // by setting units_idled_frame_counter to 0 we enable computing of units idle
			}
			// we send traces to the parser if traces received are included between an EXECUTION_START_TIME and EXECUTION_END_TIME events
			if (newExecutionDetected && !endExecutionDetected) {
				// we send this log to the parser
				if (missionEnded)
					ppTraces << DELAYED << " ";
				// Write this message on traces file
				ppTraces << msg << std::endl;
			}
			if (line.find(EXECUTION_END_TIME) != std::string::npos){ // if we detect the end of the P&P program execution
				log("CProgAndPlay : end execution detected");
				endExecutionDetected = true;
			}
		}
		// free memory storing this message
		delete[] msg;
		// Get next message
		msg = PP_PopMessage();
	}

	// Check if user asks help by UI (see pp_show_feedback.lua)
	bool askHelp = configHandler->GetString("helpPlease", "", true).compare("enabled") == 0;
	if (askHelp){
		log("CProgAndPlay : user ask help");
		configHandler->SetString("helpPlease", "", true); // reset help notification
	}

	// Check if mission is ended. This depends on engine state (game->gameOver) and/or
	// missions state (victoryState)
	if (!missionEnded) {
		std::string victoryState = configHandler->GetString("victoryState", "", true);
		if (victoryState.compare("") != 0 || game->gameOver) {
			// Log end messages
			if (traceModuleCorrectlyInitialized) {
				ppTraces << MISSION_END_TIME << " " << startTime + (int)std::floor(gu->PP_modGameTime) << std::endl;
				ppTraces << GAME_END << " " << victoryState << " " << missionName << std::endl;
			}
			log ("CProgAndPlay : missionEnded set to true");
			missionEnded = true;
		}
		mission_ended_frame_counter = 0; // reset mission ended counter
	} else{
		if (mission_ended_frame_counter > -1) // check if we have to compute mission ended
			mission_ended_frame_counter++;
	}
	// compute if we reach limits to accept end mission (useful to take in account endless loop)
	if ((mission_ended_frame_counter-1)/GAME_SPEED < MISSION_ENDED_TRIGGER && mission_ended_frame_counter/GAME_SPEED >= MISSION_ENDED_TRIGGER)
		log("CProgAndPlay : mission ended limit time exceed");
	bool missionEndedReach = mission_ended_frame_counter/GAME_SPEED >= MISSION_ENDED_TRIGGER;

	if (traceModuleCorrectlyInitialized) {
		// check if all units are idled or destroyed
		bool unitsIdled = allUnitsIdled() || allUnitsDead();
		if (units_idled_frame_counter > -1){ // check if we have to compute units idle
			if (unitsIdled)
				units_idled_frame_counter++; // increase counter to know how much time all units are idled
			else
			  units_idled_frame_counter = 0; // reset units idle counter
		}
		// compute if we reach limits to accept idle units
		if ((units_idled_frame_counter - 1)/GAME_SPEED < UNITS_IDLED_TRIGGER && units_idled_frame_counter/GAME_SPEED >= UNITS_IDLED_TRIGGER)
			log("CProgAndPlay : units idle limit time exceed");
		bool unitsIdledReach = units_idled_frame_counter/GAME_SPEED >= UNITS_IDLED_TRIGGER;

		// Check if we have to start compression
		if (newExecutionDetected && (missionEndedReach || unitsIdledReach || askHelp) && !onGoingCompression){
			log("CProgAndPlay : ask parser to proceed and compress traces");
			// we ask trace parser to proceed all traces aggregated from the last new execution event
			tp.setProceed(true);
			onGoingCompression = true;
		}
	}

	// Check if it's time to launch analysis of compressed traces
	if (onGoingCompression){
		if (tp.compressionDone()){
			// compression is done then proceed compression result by computing feedback
			// or storing expert solution
			log("CProgAndPlay : compression done");
			onGoingCompression = false;
			// if mission ended we stop thread. Indeed even if compression is done, the
			// thread is steal running. Then we explicitly ask to stop now
			if (missionEnded && traceModuleCorrectlyInitialized) {
				log("CProgAndPlay : turn off trace parser and set traceModuleCorrectlyInitialized to false");
				tp.setEnd();
				tracesThread.join();
				ppTraces.close();
				// then the trace module is no longer initialized
				traceModuleCorrectlyInitialized = false;
			}

			// If we are not in testing mode => build the feedback and send it to Lua context
			if (!testMapMode) {
				// inform trace analyser if we detect an endless loop
				ta.setEndlessLoop(tracesComing && !endExecutionDetected);
				// load expert xml solutions
				std::vector<std::string> experts_xml;
				std::vector<std::string> files = vfsHandler->GetFilesInDir(archiveExpertPath + missionName);
				for (unsigned int i = 0; i < files.size(); i++) {
					if (files.at(i).find(".xml") != std::string::npos && files.at(i).compare("feedbacks.xml") != 0)
						experts_xml.push_back(loadFileFromVfs(archiveExpertPath + missionName + "\\" + files.at(i)));
				}

				std::string feedback = "";
				if (!experts_xml.empty()) {
					log("CProgAndPlay : expert compressed traces found => compute feedbacks");
					// load learner xml solution
					const std::string learner_xml = loadFile(springTracesPath + missionName + "_compressed.xml");
					// compute feedbacks
					feedback = ta.constructFeedback(learner_xml, experts_xml, -1, -1);
					// Write into file
					std::ofstream jsonFile;
					jsonFile.open(springLastFeedbacksPath.c_str());
					if (jsonFile.good()) {
						jsonFile << feedback;
						jsonFile.close();
					}
				}
				else{
					log("CProgAndPlay : no expert compressed traces found => analysis aborted");
					// nothing more to do, we want to send an empty feedback
				}
				// Send feedback to Lua to display it on UI
				sendFeedback(feedback);

				// we get compressed trace that produce these feedbacks and send it to Lua to write it in logs
				std::string learner_compressed_txt = loadFile(springTracesPath + missionName + "_compressed.txt");
				// prefix message
				learner_compressed_txt.insert(0,"CompressedTraces_");
				std::vector<boost::uint8_t> data(learner_compressed_txt.size());
				std::copy(learner_compressed_txt.begin(), learner_compressed_txt.end(), data.begin());
				CLuaHandle::HandleLuaMsg(gu->myPlayerNum, LUA_HANDLE_ORDER_UI, 0, data); // processed by pp_meta_traces_manager.lua
			} else {
				log("testmap mode: no analysis required, only compression");
				// Send empty feedback to Lua to display it on UI
				sendFeedback("");
				if (missionEnded) {
					// generating an expert solution for a mission
					// move traces and compressed traces files to directory 'traces\data\expert\missionName'
					bool dirExists = FileSystemHandler::mkdir(springDataPath);
					log("Try to create: " + springExpertPath);
					dirExists = FileSystemHandler::mkdir(springExpertPath);
					if (dirExists) {
						std::string path = springExpertPath + missionName;
						log("Try to create: " + path);
						dirExists = FileSystemHandler::mkdir(path);
						if (dirExists) {
							// find the greater number unused in this folder
							int num = 1;
							DIR *pdir;
							struct dirent *pent;
							pdir = opendir(path.c_str());
							if (pdir) {
								while ((pent = readdir(pdir))) {
									std::string name = pent->d_name;
									if (name.find(".xml") != std::string::npos) {
										name.replace(name.find(".xml"), 4, "");
										int file_num = strtol(name.c_str(),NULL,10);
										if (file_num > 0)
											num = file_num + 1;
									}
								}
							}
							closedir(pdir);

							std::string oldName = springTracesPath + missionName + ".log";
							std::string newName = path + "\\" + boost::lexical_cast<std::string>(num) + ".log";
							if (rename(oldName.c_str(), newName.c_str()) == 0)
								log("raw traces successfully renamed");
							else
								log("raw traces rename operation failed");

							oldName = springTracesPath + missionName + "_compressed.xml";
							newName = path + "\\" + boost::lexical_cast<std::string>(num) + ".xml";
							if (rename(oldName.c_str(), newName.c_str()) == 0)
								log("compressed traces successfully renamed");
							else
								log("compressed traces rename operation failed");
						}
					}
				}
			}
		}
	} else {
		// No on going compression means no execution detected and so...
		// ...if player asks help we send him a feedback to ask him to execute a program first
		if (askHelp){
			log("CProgAndPlay : no on going compression but player ask help => send feedback to advise launching P&P program");
			// build a feedback formated te be interpreted by widget
			std::string feedback = "{\"feedbacks\": [\"Please execute a Prog&Play program before using help.\"]}";
			const std::map<std::string,std::string>& modOpts = gameSetup->modOptions;
			if (modOpts.find("language") != modOpts.end() && modOpts.at("language").compare("fr") == 0)
				feedback = "{\"feedbacks\": [\"Veuillez lancer un programme Prog&Play avant d'utiliser l'aide.\"]}";
			sendFeedback(feedback);
		}
		// ...if mission end exceeds the time limit we send and empty feedback to refresh UI. This occurs for example
		// when a player end a mission by hand (without P&P program) in this case the Widget waiting feedback and we
		// send it an empty one
		if (missionEndedReach){
			log("CProgAndPlay : no on going compression but mission end => send an empty feedback");
			sendFeedback("");
		}
	}

	// check if the player has click on the publish tab. It can happen only if the mission is ended.
	if (configHandler->GetString("publish", "false", true).compare("true") == 0) {
		configHandler->SetString("publish", "false", true);
		publishOnFacebook();
	}

	// Execute pending commands
	int nbCmd = execPendingCommands();
	if (nbCmd == -1){
		std::string tmp(PP_GetError());
		log(tmp.c_str());
	}
	// Limit update if commands was executed or every 4 frames
	if (updatePP() == -1){
		std::string tmp(PP_GetError());
		log(tmp.c_str());
	}

	//log("ProgAndPLay::Update end");
}
Esempio n. 6
0
		~logger()
		{
			mutex::scoped_lock l(file_mutex);
			log_file.close();
			open_filename.clear();
		}
//======================================================================
// Main:
//======================================================================
int main(int argc, char *argv[])
{
    //-------------------------------------------------------------------------------------
    // Load contact data set:
    //-------------------------------------------------------------------------------------
    // Check if correct number of parameters was passed to program:
    // Check if correct number of parameters was passed to program:
    if(argc<3){ std::cout << "Error! Data file not defined.\n"; return 0; }
    else
    {
        if(argc<5){ std::cout << "Error! Epidemic parameters not defined.\n"; return 0; }
        else
        {
            if(argc<6){ std::cout << "Error! Simulation time not specified.\n"; return 0; }
            else
            {
                if(argc<7){ std::cout << "Error! Ensemble size not specified.\n"; return 0; }
                else
                {
                    if(argc<8){ std::cout << "Error! Output time-resolution not specified.\n"; return 0;}
                }
            }
        }
    }
    // Set parameter values as specified:
    char *datafile=argv[1]; //dataset file name
    dt=atoi(argv[2]); //dataset time resolution (integer)
    char *beta_str = argv[3]; // base infection rate
    double beta = atof(beta_str);
    char *mu_str = argv[4]; // base recovery rate
    double mu = atof(mu_str);
    COUNTER betaprec=strlen(beta_str)-2;
    COUNTER muprec=strlen(mu_str)-2;
    COUNTER T_simulation = atoi(argv[5]); //simulation time
    COUNTER ensembleSize = atoi(argv[6]); //ensemble size (number of realizations)
    COUNTER outputTimeResolution = atoi(argv[7]); //output time-resolution

    // Open input file and load contact_lists:
    sprintf(inputname,"%s",datafile);
    const CONTACTS_LIST contactListList_original=loadContactListList(inputname);
    // Check if length of contacts_list > 0 and end program if it is not:
    if(contactListList_original.size()==0){ std::cout << "Error! Dataset empty.\n"; return 0; }

    //-------------------------------------------------------------------------------------
    // Define variables:
    //-------------------------------------------------------------------------------------
    NODES infected; //list of infected nodes
    double Mu; //cumulative recovery rate
    BOOLS isSusceptible, isInfected; //list which nodes are susceptible/infected, respectively
    COUNTER I,R; //number of infected and recovered nodes
    COUNTER SI; //number of susceptible nodes in contact with infectious nodes
    NODES si_s; //list of susceptible nodes in contact with infected nodes
    double Beta; //cumulative infection rate
    double Lambda; //cumulative transition rate
    double xi; //
    COUNTER t; //time counter
    COUNTER t_infectionStart; //starting time of infection
    NODE root; //root node of infection
    NODE i,j;
    double tau; //renormalized waiting time until next event
    CONTACTS_LIST contactListList(contactListList_original.size());
    CONTACTS_LIST::iterator contactList_iterator; //iterator over list of contacts
    CONTACTS::iterator contact_iterator; //iterator over contacts
    double r_transitionType; //random variable for choosing which type of transition happens
    COUNTER m; //transition process number
    COUNTER n; //time-counter
    NODES::iterator node_iterator; //iterator over list of nodes
    NODES::reverse_iterator node_reverseIterator; //reverse iterator over list of nodes
    NODES::iterator last; //iterator for use when generating unique list of new infected nodes
    NODES numbersToRemove;
    // Containers for output data:
    NODES sumI_t(T_simulation/outputTimeResolution); //list of number of infected nodes in each recorded frame
    NODES sumR_t(T_simulation/outputTimeResolution); //list of number of recovered nodes in each recorded frame
    NODES hist_R(N+1); //histogram of R values after I=0
    // Random number generators:
    boost::variate_generator<ENG,DIST_INT> randint(eng,dist_int); //random integer
    boost::variate_generator<ENG,DIST_REAL> rand(eng,dist_rand); //random float on [0,1[
    boost::variate_generator<ENG,DIST_EXP> randexp(eng,dist_exp); //random exponentially distributed float

    //-------------------------------------------------------------------------------------
    // Simulate:
    //-------------------------------------------------------------------------------------
    std::clock_t clockStart = std::clock();     //timer
    COUNTER stopped=0; //counter of number of simulations that stopped (I=0) during T_simulation
    for(COUNTER q=0; q<ensembleSize; q++)
    {
        std::cout << q << "/" << ensembleSize << std::endl; //print realization # to screen
        // Copy list of contacts:
        contactListList=contactListList_original;
        // Choose at random infectious root node:
        root=randint(N);
        // Initialize lists of infected nodes and infected node IDs:
        R=0;
        infected.clear();
        infected.push_back(root);
        I=1;
        Mu=mu;
        isInfected.assign(N,false);
        isInfected[root]=true;
        isSusceptible.assign(N,true);
        isSusceptible[root]=false;
        // First waiting "time":
        tau=randexp(1);
        // Random starting time of infection:
        t_infectionStart=randint(T_data);
        // Reset simulation time to zero:
        t=0;

        // Loop until either I=0 or t>=T_simulation
        while(I>0 && t<T_simulation)
        {
            // Loop over list of contact lists:
            for(contactList_iterator=contactListList.begin()+t_infectionStart; contactList_iterator!=contactListList.end(); contactList_iterator++)
            {
                // Create list of susceptible nodes in contact with infected nodes:
                si_s.clear();
                numbersToRemove.clear();
                n=0;
                for(contact_iterator=(*contactList_iterator).begin(); contact_iterator!=(*contactList_iterator).end(); contact_iterator++, n++)
                {
                    i=(*contact_iterator).i;
                    j=(*contact_iterator).j;
                    if(isSusceptible[i])
                    {
                        if(isInfected[j]){ si_s.push_back(i); }
                        else
                        {
                            if(!isSusceptible[j]){ numbersToRemove.push_back(n); }
                        }
                    }
                    else
                    {
                        if(isSusceptible[j])
                        {
                            if(isInfected[i]){ si_s.push_back(j); }
                            else{ numbersToRemove.push_back(n); }
                        }
                        else{ numbersToRemove.push_back(n); }
                    }
                }
                // Remove obsolete contacts:
                for(node_reverseIterator=numbersToRemove.rbegin(); node_reverseIterator!=numbersToRemove.rend(); node_reverseIterator++)
                {
//                    std::cout << *node_reverseIterator << " ";
                    (*contactList_iterator)[*node_reverseIterator]=(*contactList_iterator).back();
                    (*contactList_iterator).pop_back();
                }
                SI=si_s.size(); //number of possible S->I transitions
                Beta=(double)SI*beta; //cumulative infection rate
                Lambda=Beta+Mu; //cumulative transition rate:

                // Check if transition takes place during time-step:
                if(tau>=Lambda) //no transition takes place
                {
                    tau-=Lambda;
                }
                else //at least one transition takes place
                {
                    xi=1.; //fraction of time-step left before transition
                    // Sampling step:
                    while(tau<xi*Lambda) //repeat if next tau is smaller than ~ Lambda-tau
                    {
                        xi-=tau/Lambda; //fraction of time-step left after transition
                        r_transitionType=Lambda*rand(); //random variable for weighted sampling of transitions
                        if(r_transitionType<Beta) //S->I
                        {
                            m=randint(SI); //transition m
                            isInfected[si_s[m]]=true;
                            isSusceptible[si_s[m]]=false;
                            // Add infected node to list:
                            infected.push_back(si_s[m]);
                            I++;
                            Mu+=mu;
                        }
                        else //I->R
                        {
                            m=randint(I); //transition m
                            isInfected[infected[m]]=false;
                            // Remove drawn element from infected:
                            infected[m]=infected.back();
                            infected.pop_back();
                            I--;
                            R++;
                            Mu-=mu;
                        }
                        // Redo list of S-I contacts:
                        si_s.clear();
                        for(contact_iterator=(*contactList_iterator).begin(); contact_iterator!=(*contactList_iterator).end(); contact_iterator++)
                        {
                           i=(*contact_iterator).i;
                           j=(*contact_iterator).j;
                           if(isInfected[i])
                           {
                                if(isSusceptible[j])
                                {
                                    si_s.push_back(j);
                                }
                            }
                            else
                            {
                                if(isInfected[j])
                                {
                                    if(isSusceptible[i])
                                    {
                                        si_s.push_back(i);
                                    }
                                }
                            }
                        }
                        SI=si_s.size();
                        Beta=beta*(double)SI;
                        Lambda=Beta+Mu; //new cumulative transition rate
                        // Draw new renormalized waiting time:
                        tau=randexp(1);
                    }
                    tau-=xi*Lambda;
                }
                // Stop if I=0:
                if(I==0)
                {
                    stopped++;
                    hist_R[R]++;
                    for(n=t; n<T_simulation; n++)
                    {
                        if(n % outputTimeResolution ==0){ sumR_t[n/outputTimeResolution]+=R; }
                    }
                   break;
                }
                // Read out I and R if t is divisible by outputTimeResolution
                if(t % outputTimeResolution ==0)
                {
                    if(t>=T_simulation) //stop if max simulation time-steps has been reached
                    {
                        break;
                    }
                    else
                    {
                        sumI_t[t/outputTimeResolution]+=I;
                        sumR_t[t/outputTimeResolution]+=R;
                    }
                }
                t++;
            }
            t_infectionStart=0;
        }
    }
    double t_simu = ( std::clock() - clockStart ) / (double) CLOCKS_PER_SEC;

    //-------------------------------------------------------------------------------------
    // Save epidemic data to disk:
    //-------------------------------------------------------------------------------------
    clockStart=std::clock();
    // Open output file:
    sprintf(outputname,"avg(I_t)-%s,N=%u,dt=%u,T=%u,beta=%.*f,mu=%.*f,Q=%u,res=%u.txt",datafile,N,dt,T_simulation,betaprec,beta,muprec,mu,ensembleSize,outputTimeResolution);
    output.open(outputname);
    // Write I_t to file:
    for(node_iterator=sumI_t.begin(); node_iterator!=sumI_t.end(); node_iterator++)
    {
        output << (double)*node_iterator/(double)ensembleSize << "\t";
    }
    output.close();

    // Open output file:
    sprintf(outputname,"avg(R_t)-%s,N=%u,dt=%u,T=%u,beta=%.*f,mu=%.*f,Q=%u,res=%u.txt",datafile,N,dt,T_simulation,betaprec,beta,muprec,mu,ensembleSize,outputTimeResolution);
    output.open(outputname);
    // Write R_t to file:
    for(node_iterator=sumR_t.begin(); node_iterator!=sumR_t.end(); node_iterator++)
    {
        output << (double)*node_iterator/(double)ensembleSize << "\t";
    }
    output << "\n";
    output.close();
    // Open output file:
    sprintf(outputname,"p(R)-%s,N=%u,dt=%u,T=%u,beta=%.*f,mu=%.*f,Q=%u,res=%u.txt",datafile,N,dt,T_simulation,betaprec,beta,muprec,mu,ensembleSize,outputTimeResolution);
    output.open(outputname);
    // Write histrogram of R, h(R) to file:
    for(node_iterator=hist_R.begin(); node_iterator!=hist_R.end(); node_iterator++)
    {
        output << (double)*node_iterator/(double)ensembleSize << "\t";
    }
    output.close();
    double t_write = ( std::clock() - clockStart ) / (double) CLOCKS_PER_SEC;

    std::cout << std::endl << "temporal Gillespie---homogeneous & Poissonian SIR w/ contact removal: N=" << N
              << ", T=" << T_data << ", beta=" << beta << ", mu=" << mu;
    std::cout << ", output time-resolution = " << outputTimeResolution << std::endl;
    std::cout << "Simulation time: " << t_simu << "s, Stopped simulations: " << stopped << "/" << ensembleSize << std::endl;
    std::cout << "Writing to file: " << t_write << "s" << std::endl;

    return 0;
}
Esempio n. 8
0
GLUTMinimalCFR::~GLUTMinimalCFR()
{
  setManipulator( nullptr );
  file << "stop " << m_globalTimer.getTime() << "\n";
  file.close();
}
Esempio n. 9
0
My3DEngine::~My3DEngine(void)
{
	delete renderer;
	logs.close();
}
Esempio n. 10
0
int main()
{
        if(getuid())
        {
                cerr << "Please run as root! exit..." << endl;
                exit(1);
        }

        if(to_daemon() == -1)
        {
                cerr << "Can't turn into daemon, exit..." << endl;
                exit(1);
        }

        logs.open(LOG_PATH, logs.out | logs.app);
        if(!logs.good())
        {
                cerr << "Can't open log, exit..." << endl;
                exit(1);
        }

        logs << std::unitbuf;
        logs << "++++++++  program started! ++++++++" << endl;

        if(add_group() == -1)
        {
                logs << "Can't add group, exit..." << endl;
                logs.close();
                exit(1);
        }

        if(drop_in() == -1)
        {
                logs << "Can't enbale `drop in` support, exit..."
                        << endl;
                logs.close();
                exit(1);
        }

        std::string msg;

        if(record_pid(msg) == -1)
        {
                logs << msg << endl;
                logs.close();
                exit(1);
        }

        if(install_handler(SIGHUP, hup_handler) == -1 || 
                install_handler(SIGTERM, term_handler) == -1)
        {
                logs << "Can't install signal handlers: " << strerror(errno)
                        << " exit..." << endl;
                logs.close();
                exit(1);
        }
        
        std::string qualified_dev;
        
        while(!exit_flag)
        {
                if(log_truncate() == -1)
                        break;
                while(!is_qualified_device(qualified_dev) && !exit_flag)
                        device_helper();

                if(!exit_flag)
                {
                        privilege(true);
                        logs << qualified_dev << " granted privilege!\n";
                }

                while(is_qualified_device(qualified_dev) && !exit_flag)
                        device_helper();

                privilege(false);

                logs << "Dropped privilege!\n";
        }

        time_t tm = time(NULL);
        logs << "Program exited: " << ctime(&tm) << endl;
        logs.close();

        unlink(PID_PATH);

        return 0;
}
Esempio n. 11
0
VOID Fini(INT32 code, VOID *v)
{
    outFile.close();
}
Esempio n. 12
0
/** Closes an output file */
void RbFileManager::closeFile(std::ofstream& strm)
{
    
	strm.close();
}
Esempio n. 13
0
File: MF.cpp Progetto: mitll/MatchIT
void do_it(JIT *jit) {

    init_globals();

    Fields *filter_fields = new Fields();
    filter_fields->add(filter_filepath);

    Fields *read_audio_fields = new Fields();
    read_audio_fields->add(audio);
    read_audio_fields->add(audio_length);

    Fields *segment_fields = new Fields();
    segment_fields->add(segment_offset);

    Fields *fft_fields = new Fields();
    fft_fields->add(fft);

    Fields *ifft_fields = new Fields();
    ifft_fields->add(clipped);

    FilterStageIR *filt = new FilterStageIR(filter, "filter", filter_fields);
    TransformStageIR *reader = new TransformStageIR(read_audio, "read_audio", filter_fields, read_audio_fields);
    PresegmentationStageIR *preseg = new PresegmentationStageIR(compute_num_segments, "compute_num_segments",
                                                                read_audio_fields);
    SegmentationStageIR *seg = new SegmentationStageIR(segment, compute_num_segments, "segment",
                                                       "compute_num_segments", read_audio_fields, segment_fields);
    TransformStageIR *fft_xform = new TransformStageIR(compute_fft, "compute_fft", segment_fields, fft_fields);
    BucketStageIR *bucketer = new BucketStageIR(bucket_fns, "bucket_fns", fft_fields, OUTER);
    ComparisonStageIR *ifft_xform = new ComparisonStageIR(compute_ifft, "compute_ifft", fft_fields, ifft_fields);

//    filt->merge_in(reader);
//    reader->merge_in(preseg);
//    seg->merge_in(fft_xform);
//    fft_xform->merge_in(bucketer);
//
// can't do filter parallel and tracking
//    filt->set_parallelizable(true);
    filt->parallelize();
    filt->set_compact(true); // don't do atomic update
    reader->set_parallelizable(true);
    reader->parallelize();
    bucketer->set_parallelizable(true);
    bucketer->parallelize();
    preseg->set_parallelizable(true);
    preseg->parallelize();
    preseg->set_compact(true);
    seg->set_parallelizable(true);
    seg->parallelize();
    fft_xform->set_parallelizable(true);
    fft_xform->parallelize();
    ifft_xform->set_parallelizable(true);
    ifft_xform->parallelize();
//    ifft_xform->set_track_progress(true);
//    ifft_xform->set_num_tracking_splits(3);
//    ifft_xform->set_time_loop(true);

    ifft_xform->set_tileable(true);
    ifft_xform->tile();

    PipelineIR *pipeline_full_data = new PipelineIR();
    pipeline_full_data->register_stage(filt);
    pipeline_full_data->register_stage(reader);
    pipeline_full_data->register_stage(preseg);
    pipeline_full_data->register_stage(seg);
    pipeline_full_data->register_stage(fft_xform);
    pipeline_full_data->register_stage(bucketer);

    PipelineIR *pipeline_exemplars = pipeline_full_data->duplicate();

    // full data has the comparison in it, so the left input becomes the exemplars output
    pipeline_full_data->register_stage(ifft_xform);
//    ifft_xform->force_commutative();
//    ifft_xform->set_left_input(pipeline_exemplars->get_stages().back());

//    pipeline_exemplars->merge(pipeline_full_data); // exemplars will run, then the data, then the comparison
    pipeline_full_data->build_pipeline();
//    pipeline_exemplars->build_pipeline();
    pipeline_full_data->dump();

    LLVM::LLVMCodeGenerator codegen(jit);
    codegen.visit(pipeline_full_data->get_pipeline());
//    codegen.visit(pipeline_exemplars->get_pipeline());
    jit->dump();

#ifdef AOT_COMPILE
    AOT::aot_compile(jit->get_module().get(), "MF.o");
#else
    jit->add_module();
    std::vector<Element *> elements = init_filepaths();
    std::chrono::time_point<std::chrono::system_clock> start = utils_get_time();
    IR::cleanup();
    MType::cleanup();
    run1(jit, elements, filter_filepath, audio, audio_length, segment_offset, fft, clipped);
//    run2(jit, elements, elements, filter_filepath, audio, audio_length, segment_offset, fft, clipped);
    std::chrono::time_point<std::chrono::system_clock> end = utils_get_time();
    utils_print_time_duration(start, end);
#endif
    fftwf_destroy_plan(*fft_plan);
    fftwf_destroy_plan(*ifft_plan);
    fftwf_free(fft_plan);
    fftwf_free(ifft_plan);
    output_file.close();
    delete(filter_filepath);
    delete(audio);
    delete(audio_length);
    delete(segment_offset);
    delete(fft);
    delete(clipped);
}
	void close_store() {
		if (owl_file.is_open()) {
			owl_file << "\n)\n";
		}
		owl_file.close();
	}
Esempio n. 15
0
VOID Fini(INT32 code, VOID *v)
{
    TraceFile << "# eof" << endl;
    
    TraceFile.close();
}
Esempio n. 16
0
 void close() {
     strm.close();
 }
Esempio n. 17
0
void end_table(std::ofstream &ostr,  bool for_instructor, const std::vector<Student*> &students, int rank) {


  bool print_moss_message = false;
  if (rank != -1 && students[rank]->getMossPenalty() < -0.01) {
    print_moss_message = true;
  }

  if (print_moss_message) {
    ostr << "* = final grade with Academic Integrity Violation penalty<p>&nbsp;<p>\n";
  }

  if (DISPLAY_FINAL_GRADE && students.size() > 50) {

  int total_A = grade_counts[Grade("A")] + grade_counts[Grade("A-")];
  int total_B = grade_counts[Grade("B+")] + grade_counts[Grade("B")] + grade_counts[Grade("B-")]; 
  int total_C = grade_counts[Grade("C+")] + grade_counts[Grade("C")] + grade_counts[Grade("C-")];
  int total_D = grade_counts[Grade("D+")] + grade_counts[Grade("D")];
  int total_passed = total_A + total_B + total_C + total_D;
  int total_F = grade_counts[Grade("F")];
  int total_blank = grade_counts[Grade("")];
  int total = total_passed + total_F + auditors + total_blank;

  ostr << "<p>\n";



  ostr << "<table border=2 cellpadding=5 cellspacing=0>\n";
  ostr << "<tr>\n";
  ostr << "<td width=150>FINAL GRADE</td>";
  ostr << "<td align=center bgcolor="<<GradeColor("A")<<" width=40>A</td><td align=center bgcolor="<<GradeColor("A-")<<" width=40>A-</td>";
  ostr << "<td align=center bgcolor="<<GradeColor("B+")<<" width=40>B+</td><td align=center bgcolor="<<GradeColor("B")<<" width=40>B</td><td align=center bgcolor="<<GradeColor("B-")<<" width=40>B-</td>";
  ostr << "<td align=center bgcolor="<<GradeColor("C+")<<" width=40>C+</td><td align=center bgcolor="<<GradeColor("C")<<" width=40>C</td><td align=center bgcolor="<<GradeColor("C-")<<" width=40>C-</td>";
  ostr << "<td align=center bgcolor="<<GradeColor("D+")<<" width=40>D+</td><td align=center bgcolor="<<GradeColor("D")<<" width=40>D</td>\n";
  if (for_instructor) {
    ostr << "<td align=center bgcolor="<<GradeColor("F")<<"width=40>F</td><td align=center width=40>dropped</td>\n";
    ostr << "<td align=center width=40>audit</td>\n";
    ostr << "<td align=center align=center width=40>took final</td>\n";
    ostr << "<td align=center align=center width=40>total passed</td>\n";
    ostr << "<td align=center align=center width=40>total</td>\n";
  }
  ostr << "</tr>\n";
  
  ostr << "<tr>\n";
  ostr << "<td width=150># of students</td>";
  ostr << "<td align=center width=40>"<<grade_counts[Grade("A")]<<"</td><td align=center width=40>"<<grade_counts[Grade("A-")]<<"</td>";
  ostr << "<td align=center width=40>"<<grade_counts[Grade("B+")]<<"</td><td align=center width=40>"<<grade_counts[Grade("B")]<<"</td><td align=center width=40>"<<grade_counts[Grade("B-")]<<"</td>";
  ostr << "<td align=center width=40>"<<grade_counts[Grade("C+")]<<"</td><td align=center width=40>"<<grade_counts[Grade("C")]<<"</td><td align=center width=40>"<<grade_counts[Grade("C-")]<<"</td>";
  ostr << "<td align=center width=40>"<<grade_counts[Grade("D+")]<<"</td><td align=center width=40>"<<grade_counts[Grade("D")]<<"</td>\n";
  
  if (for_instructor) {
    ostr << "<td align=center width=40>"<<grade_counts[Grade("F")]<<"</td><td align=center width=40>"<<grade_counts[Grade("")]<<"</td>\n";
    ostr << "<td align=center width=40>"<<auditors<<"</td>\n";
    ostr << "<td align=center width=40>"<<took_final<<"</td>\n";
    ostr << "<td align=center width=40>"<<total_passed<<"</td>\n";
    ostr << "<td align=center width=40>"<<total<<"</td>\n";
  }
  ostr << "</tr>\n";
  
  
  
  ostr << "<tr>\n";
  ostr << "<td width=150>average OVERALL<br>of students with<br>this FINAL GRADE</td>";
  ostr << "<td align=center width=40>"<<grade_avg[Grade("A")]<<"</td><td align=center width=40>"<<grade_avg[Grade("A-")]<<"</td>";
  ostr << "<td align=center width=40>"<<grade_avg[Grade("B+")]<<"</td><td align=center width=40>"<<grade_avg[Grade("B")]<<"</td><td align=center width=40>"<<grade_avg[Grade("B-")]<<"</td>";
  ostr << "<td align=center width=40>"<<grade_avg[Grade("C+")]<<"</td><td align=center width=40>"<<grade_avg[Grade("C")]<<"</td><td align=center width=40>"<<grade_avg[Grade("C-")]<<"</td>";

  if (for_instructor) {
    ostr << "<td align=center width=40>"<<grade_avg[Grade("D+")]<<"</td><td align=center width=40>"<<grade_avg[Grade("D")]<<"</td>\n";
  } else {
    ostr << "<td align=center width=40> &nbsp; </td><td align=center width=40> &nbsp; </td>\n";
  }

  if (for_instructor) {
    ostr << "<td align=center width=40>"<<grade_avg[Grade("F")]<<"</td><td align=center width=40>"<<grade_avg[Grade("")]<<"</td>\n";
    ostr << "<td align=center width=40>&nbsp;</td>\n";
    ostr << "<td align=center width=40>&nbsp;</td>\n";
    ostr << "<td align=center width=40>&nbsp;</td>\n";
    ostr << "<td align=center width=40>&nbsp;</td>\n";
  }
  ostr << "</tr>\n";
  
  
  
  ostr << "</table><p>\n";

  }

  ostr.close();
}
Esempio n. 18
0
 ~basic_text_output() {
     strm.close();
 }
Esempio n. 19
0
VOID Fini(INT32 code, VOID *v)
{
    Out << "(eof)" << std::endl;
    Out.close();
}
Esempio n. 20
0
			void inactivate(){
				if(is_active()){
					ofs << FILE_COMMENTOUT_CHARS << "EOF" << std::endl;
					ofs.close();
				}
			}
Esempio n. 21
0
int main(int argc, char *argv[]) {
	if (argc < 2 || argc > 3) {
		std::cerr << "ERROR: Incorrect number of arguments" << std::endl;
		std::cerr << "The first argument should indicate the location of the configuration file and the second (optional) argument should indicate the file to log to." << std::endl;
		return -1;
	}

	// Set up logging
	std::string log_file = argc < 3 ? "log" : argv[2];
	log.open((log_file + ".log").c_str());
	compactLog.open((log_file + ".csv").c_str());

	// Print header to compactLog
	compactLog << "cycle, observation, reward, action, explored, explore_rate, total reward, average reward" << std::endl;


	// Load configuration options
	options_t options;

	// Default configuration values
	options["ct-depth"] = "3";
	options["agent-horizon"] = "16";
	options["exploration"] = "0";     // do not explore
	options["explore-decay"] = "1.0"; // exploration rate does not decay

	// Read configuration options
	std::ifstream conf(argv[1]);
	if (!conf.is_open()) {
		std::cerr << "ERROR: Could not open file '" << argv[1] << "' now exiting" << std::endl;
		return -1;
	}
	processOptions(conf, options);
	conf.close();

	// Set up the environment
	Environment *env;

	// TODO: instantiate the environment based on the "environment-name"
	// option. For any environment you do not implement you may delete the
	// corresponding if statement.
	// NOTE: you may modify the options map in order to set quantities such as
	// the reward-bits for each particular environment. See the coin-flip
	// experiment for an example.
	std::string environment_name = options["environment"];
	if (environment_name == "coin-flip") {
		env = new CoinFlip(options);
		options["agent-actions"] = "2";
		options["observation-bits"] = "1";
		options["reward-bits"] = "1";
	}
	else if (environment_name == "1d-maze") {
		// TODO: instantiate "env" (if appropriate)
	}
	else if (environment_name == "cheese-maze") {
		// TODO: instantiate "env" (if appropriate)
	}
	else if (environment_name == "tiger") {
		// TODO: instantiate "env" (if appropriate)
	}
	else if (environment_name == "extended-tiger") {
		// TODO: instantiate "env" (if appropriate)
	}
	else if (environment_name == "4x4-grid") {
		// TODO: instantiate "env" (if appropriate)
	}
	else if (environment_name == "tictactoe") {
		// TODO: instantiate "env" (if appropriate)
	}
	else if (environment_name == "biased-rock-paper-scissor") {
		// TODO: instantiate "env" (if appropriate)
	}
	else if (environment_name == "kuhn-poker") {
		// TODO: instantiate "env" (if appropriate)
	}
	else if (environment_name == "pacman") {
		// TODO: instantiate "env" (if appropriate)
	}
	else {
		std::cerr << "ERROR: unknown environment '" << environment_name << "'" << std::endl;
		return -1;
	}

	// Set up the agent
	Agent ai(options);

	// Run the main agent/environment interaction loop
	mainLoop(ai, *env, options);

	log.close();
	compactLog.close();

	return 0;
}
Esempio n. 22
0
/**
 * Close the file once all write operations done.
 */
void closeFile() {
	myFile.close();
}
Esempio n. 23
0
VOID Fini(int, VOID * v)
{   
    out << "# eof" <<  endl;
    out.close();
}
Esempio n. 24
0
/** Entry point of the program. Sets up logging, default configuration values,
 * environment and agent before starting the agent/environment interaction cycle
 * by calling mainLoop(). In the case of invalid command line arguments, it
 * prints help information to the standard output and exits.
 */
int main(int argc, char *argv[]) {
	// Check valid command line arguments.
	if (argc < 2 || argc > 3) {
		std::cerr << "ERROR: Incorrect number of arguments" << std::endl
		    << "The first argument should indicate the location of the "
		    << "configuration file and the second (optional) argument should "
		    << "indicate the file to log to." << std::endl;
		return EXIT_FAILURE;
	}

	// Set up logging, print header
	logger.open(argv[2]);
	logger << "cycle, observation, reward, action, explored, "
	    << "explore_rate, total reward, average reward, time, model size"
	    << std::endl;


	// Stores configuration options
	options_t options;

	// Default configuration values
	options["ct-depth"] = "30";
	options["agent-horizon"] = "5";
	options["exploration"] = "0.0";     // do not explore
	options["explore-decay"] = "1.0"; // exploration rate does not decay
	options["mc-simulations"] = "300";

	// Read configuration options
	std::ifstream conf(argv[1]);
	if (!conf.is_open()) {
		std::cerr << "ERROR: Could not open file '" << argv[1]
		    << "' now exiting" << std::endl;
		return EXIT_FAILURE;
	}
	processOptions(conf, options);
	conf.close();

	// Set up the environment.
	Environment *env;
	std::string environment_name;
	getRequiredOption(options, "environment", environment_name);
	if (environment_name == "coin-flip") {
		env = new CoinFlip(options);
	} else if (environment_name == "extended-tiger") {
		env = new ExtendedTiger(options);
	} else if (environment_name == "kuhn-poker") {
		env = new KuhnPoker(options);
	} else if (environment_name == "maze") {
		env = new Maze(options);
	} else if (environment_name == "pacman") {
		env = new PacMan(options);
	} else if (environment_name == "rock-paper-scissors") {
		env = new RockPaperScissors(options);
	} else if (environment_name == "tictactoe") {
		env = new TicTacToe(options);
	} else if (environment_name == "tiger") {
 		env = new Tiger(options);
	} else if (environment_name == "external-environment") {
		env = new ExternalEnvironment(options);
 	} else {
		std::cerr << "ERROR: unknown environment '" << environment_name << "'"
		    << std::endl;
		return EXIT_FAILURE;
	}

	// Copy environment-related configuration options to options map
	options["action-bits"] = toString(env->actionBits());
	options["observation-bits"] = toString(env->observationBits());
	options["percept-bits"] = toString(env->perceptBits());
	options["reward-bits"] = toString(env->rewardBits());
	options["max-action"] = toString(env->maxAction());
	options["max-observation"] = toString(env->maxObservation());
	options["max-reward"] = toString(env->maxReward());

	// Print options
	options_t::iterator it = options.begin();
	for( ; it != options.end(); it++) {
		std::cout << "OPTION: '" << it->first << "' = '" << it->second
		          << "'" << std::endl;
	}

	// Set up the agent
	Agent ai(options, *env);

	// Run the main agent/environment interaction loop
	mainLoop(ai, *env, options);

	logger.close();

	return EXIT_SUCCESS;
}
void signalHandler(int s)
{
  imu_file_.close();
}
Esempio n. 26
0
	void Chunk::saveToFile(std::ofstream &outfile){
		for (int x = 0; x < CHUNK_SIZE; x++)
			for (int y = 0; y < CHUNK_HEIGHT; y++)
					outfile.write((char *)m_pBlocks[x][y], CHUNK_SIZE);
		outfile.close();
	}
Esempio n. 27
0
int main(int argc, char *argv[]) {
	if (argc < 2) {
		std::cerr << "USAGE: ./aixi agent.conf [--option1=value1 --option2=value2 ...] " << std::endl;
		std::cerr << "The first argument should indicate the location of the configuration file. Further arguments can either be specified in the config file or passed as command line option. Command line options are used over options specified in the file." << std::endl;
		return -1;
	}
    // Initialize random seed
    srand(time(NULL));

	// Load configuration options
	options_t options;

	// Default configuration values
	options["ct-depth"] = "16";
	options["agent-horizon"] = "3";
	options["exploration"] = "0";     // do not explore
	options["explore-decay"] = "1.0"; // exploration rate does not decay
    options["mc-timelimit"] = "500"; //number of mc simulations per search
    options["terminate-age"] = "10000";
    options["log"]  = "log";
    options["load-ct"] = "";
    options["write-ct"] = "";
    options["intermediate-ct"] = "1";

	// Read configuration options
	std::ifstream conf(argv[1]);
	if (!conf.is_open()) {
		std::cerr << "ERROR: Could not open file '" << argv[1] << "' now exiting" << std::endl;
		return -1;
	}
	processOptions(conf, options);
	conf.close();

    //parse command line options (overwrites values of config files)
    parseCmdOptions(argc, argv, options);

	// Set up logging
	std::string log_file = options["log"];
	verboseLog.open((log_file + ".log").c_str());
	compactLog.open((log_file + ".csv").c_str());

	// Print header to compactLog
	compactLog << "cycle, observation, reward, action, explored, explore_rate, total reward, average reward" << std::endl;

	// Set up the environment
	Environment *env;
	std::string environment_name = options["environment"];
	if (environment_name == "coin-flip") {
		env = new CoinFlip(options);
		options["agent-actions"] = "2";
		options["observation-bits"] = "1";
		options["reward-bits"] = "1";
	}
	else if (environment_name == "tiger") {
		env = new Tiger(options);
		options["agent-actions"] = "3";
		options["observation-bits"] = "2";
		options["reward-bits"] = "7";
	}
	else if (environment_name == "biased-rock-paper-scissor") {
		env = new BiasedRockPaperScissor(options);
		options["agent-actions"] = "3";
		options["observation-bits"] = "2";
		options["reward-bits"] = "2";
	}
	else if (environment_name == "kuhn-poker") {
		env = new KuhnPoker(options);
		options["agent-actions"] = "2";
		options["observation-bits"] = "4";
		options["reward-bits"] = "3";
	}
	else if (environment_name == "pacman") {
        env = new Pacman(options);
		options["agent-actions"] = "4";
		options["observation-bits"] = "16";
		options["reward-bits"] = "8";
	}
	else {
		std::cerr << "ERROR: unknown environment '" << environment_name << "'" << std::endl;
		return -1;
	}

    printOptions(options);

	// Set up the agent
	Agent ai(options);

	// If specified, load a pretrained context tree.
    if(options["load-ct"] != ""){
        std::ifstream ct(options["load-ct"].c_str());

        if(ct.is_open()){
            ai.loadCT(ct);
        }
        else{
            std::cerr << "WARNING: specified context tree file could not be loaded.\n";
        }
        ct.close();
    }  

	// Run the main agent/environment interaction loop
	mainLoop(ai, *env, options);

	verboseLog.close();
	compactLog.close();

	return 0;
}
Esempio n. 28
0
VOID Fini(INT32 code, VOID *v)
{
    TraceFile.close();
}
 void sotDebugTrace::closeFile( const char * /*filename*/ )
 {
   if( debugfile.good()&&debugfile.is_open() ) { debugfile.close(); }
   debugfile.setstate( std::ios::failbit ) ;
 }
Esempio n. 30
0
int main(int argv, char* argc[]) {

    //handler to be called when Ctr+C
    // Register signals
    signal(SIGINT, exit_signal);


#if DEBUGIP
   ifaddrs * linkedlist_;
   if(getifaddrs(&linkedlist_) != 0){
       std::cerr << "f**k" << std::endl;
   }
    while(linkedlist_ != NULL){

        char tempIP[INET6_ADDRSTRLEN];
        sockaddr* temp = linkedlist_->ifa_addr;

        std::cout << inet_ntop(AF_INET, get_in_addr((struct sockaddr *)temp), tempIP, sizeof tempIP) << std::endl;
        linkedlist_ = linkedlist_->ifa_next;
    }
#endif


    if(argv < 6){
        std::cerr << "usage: server –u –p portno –l logfile"<< std::endl;
        return 1;
    }

    //declaring variables
    //local parsing data
        std::string logfileName;
        std::string imagePath;//this could be a single image or a collection of images
        std::ifstream imageFILE;
        //declaring flags
        bool TCP, UDP, DFLAG, IFLAG;
        TCP = UDP = DFLAG = IFLAG = false;

    //local network related data (local)
    addrinfo hints, *allInfo;
    std::string port;
    int localSocket;
    const char* localIP;
    int backlog = 0;

    //client data (remote)
    addrinfo clientAddr;//when receiving, this address is going to be filled up;
    char clientBuf[250];
    ssize_t clientBufSize;//when data is received from recvfrom, this int will have the size of the buffer void*
    socklen_t clientSockLen;
    char clientIP[INET_ADDRSTRLEN];
    std::string clientIPString;
    int clientSocket;//used for new connections

#if DEBUG
    for(int i = 0; i < argv; ++i){
        std::cout << *(argc+i) << " " << std::endl;
    }
#endif

    //parsing
    parseInput(TCP, UDP, DFLAG, IFLAG, port, imagePath, logfileName, argv, argc);
    if(DFLAG){
        backlog = 1;
    }else{
        backlog = 100;
    }
#if DEBUG
    std::cout << "info after parsing: " <<std::endl;
    std::cout << "TCP: " << TCP << std::endl;
    std::cout << "UDP: " << UDP << std::endl;
    std::cout << "DFLAG: " << DFLAG << std::endl;
    std::cout << "IFLAG: " << IFLAG << std::endl;
    std::cout << "port: " << port << std::endl;
    std::cout << "imagePath: " << imagePath << std::endl;
    std::cout << "logfileName: " << logfileName << std::endl;
#endif
    logfile.open(logfileName);

    //initializing hints (ipv4)
    memset(&hints, 0, (sizeof hints));
    hints.ai_family = AF_INET;
    if(UDP){
        hints.ai_socktype = SOCK_DGRAM;
    }
    if(TCP){
        hints.ai_socktype = SOCK_STREAM;
    }
    hints.ai_flags = 0;


    //getting my ipv4 address
    ifaddrs * linkedlist;
    if(getifaddrs(&linkedlist) != 0){
        std::cerr << "" << std::endl;
    }
    while(linkedlist != NULL){

        char tempIP[INET6_ADDRSTRLEN];
        sockaddr* temp = linkedlist->ifa_addr;
        if(temp->sa_family == AF_INET){
            localIP = inet_ntop(AF_INET, get_in_addr((struct sockaddr *)temp), tempIP, sizeof tempIP);
            char tempip[INET_ADDRSTRLEN];
            strcpy(tempip,localIP);
            tempip[6] = '\0';
            if((strcmp(localIP+2, "0.0.0.0") != 0) && (strcmp(tempip, "127.0.") != 0)){
                break;
            }
        }
        linkedlist = linkedlist->ifa_next;
    }

    //getting the info from the hints, completing it's struct and putting it into allInfo.
    //allInfo might also have an ipv6 from localhost
    if(getaddrinfo(localIP, port.c_str(), &hints, &allInfo) < 0){
        std::cerr << "Problem getting local address info:" << std::endl << strerror(errno) << std::endl;
        logfile.close();
        return 1;
    }

    //getting the local socket file descriptor
    while(allInfo != NULL){
        if ((localSocket = socket(allInfo->ai_family, allInfo->ai_socktype, allInfo->ai_protocol)) == -1) {
            close(localSocket);
            perror("server: socket");
            allInfo = allInfo->ai_next;
            continue;
        }

        if (bind(localSocket, allInfo->ai_addr, allInfo->ai_addrlen) == -1) {
            close(localSocket);
            perror("server: bind");
            allInfo = allInfo->ai_next;
            continue;
        }
        break;
    }


    //server started or UDP
    if(TCP){
        if(listen(localSocket, backlog) == -1){
            std::cerr << "Problem listening:" << std::endl << strerror(errno) << std::endl;
            logfile.close();
            return 1;
        }
        logfile << "server started on " << localIP << " at port " << port << std::endl;
        std::cout << "server started on " << localIP << " at port " << port << std::endl;



        int IDSeter = 1;
        while(1) {  // main accept() loop
            clientSocket = accept(localSocket, (struct sockaddr *)&clientAddr, &clientAddr.ai_addrlen);
            if (clientSocket == -1) {
                perror("accept");
                continue;
            }
            int clientID = IDSeter++;
            inet_ntop(AF_INET,
                      get_in_addr((struct sockaddr *)&clientAddr),
                      clientIP, clientAddr.ai_addrlen);
	    //getting client ip
            //getting uscid
	    int bytesRcv = 0;
            if((bytesRcv = recv(clientSocket, clientIP, 30,0)) < 0){
   	         std::cerr << "Problem receiving TCP message:" << std::endl << strerror(errno) << std::endl;
                 logfile.close();
                 return 1;
            }
	    clientIP[bytesRcv] = '\0';

            if(DFLAG){//If it's part three of the assignment
                logfile << "received client connection " << clientID << " from hostname " << clientIP << " port " << port << std::endl;
                std::cout<< "received client connection " << clientID << " from hostname " << clientIP << " port " << port << std::endl;
                if (!fork()) { // this is the child process
                    close(localSocket); // child doesn't need the listener

                    int realNumberBytes = 0;
                    char buf[1024];

                    //Telling the client it's part three
                    std::stringstream ss1;
                    std::string acceptBuf;
                    ss1 << clientID;
                    ss1 >> acceptBuf;
                    acceptBuf = "y" + acceptBuf;
                    if(send(clientSocket, acceptBuf.c_str(), acceptBuf.length(), 0) < 0) {
                        std::cerr << "Problem sending TCP message:" << std::endl << strerror(errno) << std::endl;
                        logfile.close();
                        return 1;
                    }

                    //getting uscid
                    if((realNumberBytes = recv(clientSocket, buf, 1024,0)) < 0){
                        std::cerr << "Problem receiving TCP message:" << std::endl << strerror(errno) << std::endl;
                        logfile.close();
                        return 1;
                    }
                    buf[realNumberBytes] = '\0';
                    logfile << clientID << " received " << buf << std::endl;
                    std::cout << clientID << " received " << buf << std::endl;

                    //getting name
                    if((realNumberBytes = recv(clientSocket, buf, 1024,0)) < 0){
                        std::cerr << "Problem receiving TCP message:" << std::endl << strerror(errno) << std::endl;
                        logfile.close();
                        return 1;
                    }
                    buf[realNumberBytes] = '\0';
                    logfile << clientID << " received " << buf << std::endl;
                    std::cout << clientID << " received " << buf << std::endl;

                    //waiting just for a little bit
                    //taken from http://www.cplusplus.com/reference/thread/this_thread/sleep_for/
                    std::this_thread::sleep_for (std::chrono::seconds(1));
                    //


                    //reading image
                    imageFILE.open(imagePath, std::ifstream::binary | std::ifstream::in);
                    std::streampos begin, end;
                    begin = imageFILE.tellg();
                    imageFILE.seekg (0, imageFILE.end);
                    end = imageFILE.tellg();

                    long long int imgSize = end - begin;
                    char imgBuf[400000];
                    imageFILE.seekg (0, imageFILE.beg);
                    for(int i= 0; i < 400000; ++i){
                        imgBuf[i] = 'i';
                    }
                    int i = 0;
                    while(imageFILE.get(imgBuf[i++]));
                    imageFILE.close();
                    logfile << clientID <<" sending image file " << imagePath << std::endl;
                    std::cout << clientID <<" sending image file " << imagePath << std::endl;

                    //first send the image size
                    std::stringstream ss;
                    std::string temp;
                    ss << imgSize;
                    ss >> temp;
                    if(send(clientSocket, temp.c_str(), temp.length(), 0) < 0) {
                        std::cerr << "Problem sending TCP message:" << std::endl << strerror(errno) << std::endl;
                        logfile.close();
                        return 1;
                    }

                    while(true){
                        if(send(clientSocket, imgBuf, imgSize, 0) < 0) {
                            std::cerr << "Problem sending TCP message:" << std::endl << strerror(errno) << std::endl;
                            logfile.close();
                            return 1;
                        }

                        if((realNumberBytes = recv(clientSocket, buf, 1024,0)) < 0){
                            std::cerr << "Problem receiving TCP message:" << std::endl << strerror(errno) << std::endl;
                            logfile.close();
                            return 1;
                        }
                        buf[realNumberBytes] = '\0';

                        if(strcmp("yes", buf) == 0){
                            break;
                        }
                    }
                    logfile << clientID << " terminating client connection..." << std::endl;
                    std::cout << clientID << " terminating client connection..." << std::endl;
                    close(clientSocket);
                    return 0;
                }
            }
            else{//If it's part two of the assignment
                logfile << "received client connection from hostname " << clientIP << " port " << port << std::endl;
                std::cout<< "received client connection from hostname " << clientIP << " port " << port << std::endl;

                int realNumberBytes = 0;
                char buf[1024];

                //telling client it's part 2
                if(send(clientSocket, "n", 1, 0) < 0) {
                    std::cerr << "Problem sending TCP message:" << std::endl << strerror(errno) << std::endl;
                    logfile.close();
                    return 1;
                }


                //getting uscid
                if((realNumberBytes = recv(clientSocket, buf, 1024,0)) < 0){
                    std::cerr << "Problem receiving TCP message:" << std::endl << strerror(errno) << std::endl;
                    logfile.close();
                    return 1;
                }
                buf[realNumberBytes] = '\0';
                logfile << "received " << buf << std::endl;
                std::cout << "received " << buf << std::endl;

                //getting name
                if((realNumberBytes = recv(clientSocket, buf, 1024,0)) < 0){
                    std::cerr << "Problem receiving TCP message:" << std::endl << strerror(errno) << std::endl;
                    logfile.close();
                    return 1;
                }
                buf[realNumberBytes] = '\0';
                logfile << "received " << buf << std::endl;
                std::cout << "received " << buf << std::endl;

                //waiting just for a little bit
                //taken from http://www.cplusplus.com/reference/thread/this_thread/sleep_for/
                std::this_thread::sleep_for (std::chrono::seconds(1));
                //


                //reading image
                imageFILE.open(imagePath, std::ifstream::binary | std::ifstream::in);
                std::streampos begin, end;
                begin = imageFILE.tellg();
                imageFILE.seekg (0, imageFILE.end);
                end = imageFILE.tellg();

                long long int imgSize = end - begin;
                char imgBuf[400000];
                imageFILE.seekg (0, imageFILE.beg);
                for(int i= 0; i < 400000; ++i){
                    imgBuf[i] = 'i';
                }
                int i = 0;
                while(imageFILE.get(imgBuf[i++]));
                imageFILE.close();
                logfile <<"sending image file " << imagePath << std::endl;
                std::cout <<"sending image file " << imagePath << std::endl;

                //first send the image size
                std::stringstream ss;
                std::string temp;
                ss << imgSize;
                ss >> temp;
                if(send(clientSocket, temp.c_str(), temp.length(), 0) < 0) {
                    std::cerr << "Problem sending TCP message:" << std::endl << strerror(errno) << std::endl;
                    logfile.close();
                    return 1;
                }

                while(true){
                    if(send(clientSocket, imgBuf, imgSize, 0) < 0) {
                        std::cerr << "Problem sending TCP message:" << std::endl << strerror(errno) << std::endl;
                        logfile.close();
                        return 1;
                    }

                    if((realNumberBytes = recv(clientSocket, buf, 1024,0)) < 0){
                        std::cerr << "Problem receiving TCP message:" << std::endl << strerror(errno) << std::endl;
                        logfile.close();
                        return 1;
                    }
                    buf[realNumberBytes] = '\0';

                    if(strcmp("yes", buf) == 0){
                        break;
                    }
                }
                logfile << "terminating server..." << std::endl;
			    std::cout << "terminating server..." << std::endl;
			    logfile.close();

			    //closing sockets
	            close(clientSocket);
	            close(localSocket);
	            return 0;
            }
        }