<commit_before>/* File sections:
 * Service: constructors, destructors
 * Solution: functions directly related to the solution of a (sub)problem
 * Utility: advanced member access such as searching and counting
 * List: maintenance of lists or arrays of objects
 */

#include "Result.h"
#include "Output_def.h"

#include "Input/CoolingTime.h"
#include "Input/Mixture.h"

#include "Chains/Chain.h"
#include "Chains/Node.h"

#include "Calc/topScheduleT.h"

/****************************
 ********* Service **********
 ***************************/

int Result::nResults = 0;
FILE* Result::binDump = NULL;
const int Result::delimiter = -1;

Result::Result(int setKza, Result* nxtPtr)
{
  int resNum;

  kza = setKza;
  N = NULL;
  if (nResults>0)
    {
      N = new double[nResults];
      for (resNum=0;resNum<nResults;resNum++)
	N[resNum] = 0;
    }
  next = nxtPtr;
}

Result::Result(const Result& r)
{
  int resNum;

  kza = r.kza;
  N = NULL;
  if (nResults>0)
    {
      N = new double[nResults];
      for (resNum=0;resNum<nResults;resNum++)
	N[resNum] = r.N[resNum];
    }
  next = NULL;

}

Result::Result(int setKza,float* floatN)
{
  int resNum;

  kza = setKza;
  N = NULL;
  if (nResults>0)
    {
      N = new double[nResults];
      for (resNum=0;resNum<nResults;resNum++)
	N[resNum] = floatN[resNum];
    }
  next = NULL;
}

Result& Result::operator=(const Result& r)
{
  if (this == &r)
    return *this;

  int resNum;

  kza = r.kza;
  delete N;
  N = NULL;
  if (nResults>0)
    {
      N = new double[nResults];
      for (resNum=0;resNum<nResults;resNum++)
	N[resNum] = r.N[resNum];
    }

  return *this;
}

/*******************************
 *********** Utility ***********
 ******************************/

Result* Result::find(int srchKza)
{
  Result *oldPtr, *ptr = this;

  while (ptr->next != NULL)
    {
      oldPtr = ptr;
      ptr = ptr->next;
      if (ptr->kza == srchKza)
	return ptr;
      else if (ptr->kza > srchKza)
	{
	  oldPtr->next = new Result(srchKza,ptr);
	  return oldPtr->next;
	}
    }

  ptr->next = new Result(srchKza);

  return ptr->next;

}

/****************************
 ********** Tally ***********
 ***************************/

void Result::tallySoln(Chain *chain, topScheduleT* schedT)
{
  Result *ptr, *head = this;
  int rank, setKza;

  /* get the rank of the first node to be tallied */
  rank = chain->getSetRank();

  /* get the first kza to be set */
  setKza = chain->getKza(rank);

  /* if we are not done (finish condition: kza == 0) */
  while (setKza > 0)
    {
      /* tally result */
      double *Nlist = schedT->results(rank);

      head->find(setKza)->tally(Nlist);

      /* this is allocated in topScheduleT::results() */
      delete Nlist;

      /* get next isotope */
      setKza = chain->getKza(++rank);
    }
}

void Result::tally(double* Nlist, double scale)
{
  int resNum;

  for (resNum=0;resNum<nResults;resNum++)
    if (Nlist[resNum]<0)
      error(2000,"A negative solution has been encountered, suggesting a possible round off error.  Please notify the code author.");
    else
      N[resNum] += Nlist[resNum]*scale;

}

/*****************************
 ********* PostProc **********
 ****************************/

void Result::postProcList(Result* outputList, Mixture *mixPtr, int rootKza)
{
  Component *compPtr=NULL;
  double density;
  int compNum;

  /* get the first component number and density for this root
   * isotope */
  compPtr = mixPtr->getComp(rootKza,density,NULL);

  /* if we found the component */
  while (compPtr)
    {
      compNum = mixPtr->getCompNum(compPtr);

      /* update this component */
      postProc(outputList[compNum],density);

      /* get the next component */
      compPtr = mixPtr->getComp(rootKza,density,compPtr);
    }

  /* we are done with this data now */
  delete next;
  next = NULL;
}

void Result::postProc(Result& outputList, double density)
{
  Result *ptr = this;

  /* for each result isotope */
  while (ptr->next != NULL)
    {
      ptr = ptr->next;

      /* tally the output list */
      outputList.find(ptr->kza)->tally(ptr->N,density);

    }

}

void Result::write(int response, CoolingTime *coolList, double*& total,
		   double volume)
{
  int resNum;
  Result* ptr = this;
  double multiplier=1;
  Node dataAccess;
  char isoSym[15];

  /* initialize the total array */
  delete total;
  total = new double[nResults];
  for (resNum=0;resNum<nResults;resNum++)
    total[resNum] = 0;

  /* write a standard header for this table */
  coolList->writeHeader();

  /* for each isotope in the table */
  while (ptr->next != NULL)
    {
      ptr = ptr->next;

      /* query the data library through a dummy Node object
       * to get the nuclear data for the multiplier */
      switch(response)
	{
	case OUTFMT_ACT:
	  multiplier = dataAccess.getLambda(ptr->kza);
	  break;
	case OUTFMT_HEAT:
	  multiplier = dataAccess.getHeat(ptr->kza);
	  break;
	case OUTFMT_ALPHA:
	  multiplier = dataAccess.getAlpha(ptr->kza);
	  break;
	case OUTFMT_BETA:
	  multiplier = dataAccess.getBeta(ptr->kza);
	  break;
	case OUTFMT_GAMMA:
	  multiplier = dataAccess.getGamma(ptr->kza);
	  break;
	}

      /* if the multipier is 0 (e.g. stable isotope for activity based
	 responses) skip this isotope */
      if (multiplier == 0)
	continue;

      /* renormalize the multiplier by the volume */
      multiplier /= volume;

      /* write the formatted output for this isotope */
      cout << isoName(ptr->kza,isoSym) << "\t";

      for (resNum=0;resNum<nResults;resNum++)
	{
	  sprintf(isoSym,"%-11.4e ",ptr->N[resNum]*multiplier);
	  cout << isoSym;
	  /* increment the total */
	  total[resNum] += ptr->N[resNum]*multiplier;
	}

      cout << endl;
    }

  /* write a separator for the table */
  coolList->writeSeparator();

  /* write the formatted output for the total response */
  cout << "total\t";
  for (resNum=0;resNum<nResults;resNum++)
    {
      sprintf(isoSym,"%-11.4e ",total[resNum]);
      cout << isoSym;
    }
  cout << endl;

}

/*****************************
 ********* PostProc **********
 ****************************/

void Result::initBinDump(char* fname)
{
  binDump = fopen(fname,"wb+");
  if (!binDump)
    error(300,"Unable to open dump file %s",fname);
};

void Result::dumpHeader()
{
  fwrite(&nResults,SINT,1,binDump);
}

void Result::xCheck()
{
  if (binDump == NULL)
    {
      warning(301,"ALARA now requires a binary dump file.  Openning the default file 'alara.dmp'");
      binDump = fopen("alara.dmp","wb+");
      if (!binDump)
	error(300,"Unable to open dump file alara.dmp");
    }
}

void Result::resetBinDump()
{
  fflush(binDump);
  fseek(binDump,0L,SEEK_SET);
  fread(&nResults,SINT,1,binDump);
  verbose(1,"Reset binary dump with %d results per isotope.",nResults);
}

void Result::writeDump()
{
  Result *ptr = this;
  Result *list = next;
  static float *floatN = new float[nResults];
  int resNum;

  while (ptr->next != NULL)
    {
      ptr = ptr->next;

      fwrite(&(ptr->kza),SINT,1,binDump);
      for (resNum=0;resNum<nResults;resNum++)
	floatN[resNum] = ptr->N[resNum];
      fwrite(floatN,SFLOAT,nResults,binDump);

    }

  fwrite(&delimiter,SINT,1,binDump);

  delete list;
  next = NULL;

}

void Result::readDump()
{
  Result *ptr = this;
  int readKza,resNum;

  static float *floatN = new float[nResults];

  fread(&readKza,SINT,1,binDump);
  while (readKza != delimiter)
    {
      fread(floatN,SFLOAT,nResults,binDump);
      ptr->next = new Result(readKza,floatN);
      ptr = ptr->next;
      fread(&readKza,SINT,1,binDump);
    }
}

<commit_msg>Commented out error message used during debugging.<commit_after>/* File sections:
 * Service: constructors, destructors
 * Solution: functions directly related to the solution of a (sub)problem
 * Utility: advanced member access such as searching and counting
 * List: maintenance of lists or arrays of objects
 */

#include "Result.h"
#include "Output_def.h"

#include "Input/CoolingTime.h"
#include "Input/Mixture.h"

#include "Chains/Chain.h"
#include "Chains/Node.h"

#include "Calc/topScheduleT.h"

/****************************
 ********* Service **********
 ***************************/

int Result::nResults = 0;
FILE* Result::binDump = NULL;
const int Result::delimiter = -1;

Result::Result(int setKza, Result* nxtPtr)
{
  int resNum;

  kza = setKza;
  N = NULL;
  if (nResults>0)
    {
      N = new double[nResults];
      for (resNum=0;resNum<nResults;resNum++)
	N[resNum] = 0;
    }
  next = nxtPtr;
}

Result::Result(const Result& r)
{
  int resNum;

  kza = r.kza;
  N = NULL;
  if (nResults>0)
    {
      N = new double[nResults];
      for (resNum=0;resNum<nResults;resNum++)
	N[resNum] = r.N[resNum];
    }
  next = NULL;

}

Result::Result(int setKza,float* floatN)
{
  int resNum;

  kza = setKza;
  N = NULL;
  if (nResults>0)
    {
      N = new double[nResults];
      for (resNum=0;resNum<nResults;resNum++)
	N[resNum] = floatN[resNum];
    }
  next = NULL;
}

Result& Result::operator=(const Result& r)
{
  if (this == &r)
    return *this;

  int resNum;

  kza = r.kza;
  delete N;
  N = NULL;
  if (nResults>0)
    {
      N = new double[nResults];
      for (resNum=0;resNum<nResults;resNum++)
	N[resNum] = r.N[resNum];
    }

  return *this;
}

/*******************************
 *********** Utility ***********
 ******************************/

Result* Result::find(int srchKza)
{
  Result *oldPtr, *ptr = this;

  while (ptr->next != NULL)
    {
      oldPtr = ptr;
      ptr = ptr->next;
      if (ptr->kza == srchKza)
	return ptr;
      else if (ptr->kza > srchKza)
	{
	  oldPtr->next = new Result(srchKza,ptr);
	  return oldPtr->next;
	}
    }

  ptr->next = new Result(srchKza);

  return ptr->next;

}

/****************************
 ********** Tally ***********
 ***************************/

void Result::tallySoln(Chain *chain, topScheduleT* schedT)
{
  Result *ptr, *head = this;
  int rank, setKza;

  /* get the rank of the first node to be tallied */
  rank = chain->getSetRank();

  /* get the first kza to be set */
  setKza = chain->getKza(rank);

  /* if we are not done (finish condition: kza == 0) */
  while (setKza > 0)
    {
      /* tally result */
      double *Nlist = schedT->results(rank);

      head->find(setKza)->tally(Nlist);

      /* this is allocated in topScheduleT::results() */
      delete Nlist;

      /* get next isotope */
      setKza = chain->getKza(++rank);
    }
}

void Result::tally(double* Nlist, double scale)
{
  int resNum;

  for (resNum=0;resNum<nResults;resNum++)
    /* used during debuggin
       if ( isnan(Nlist[resNum]) )
       error(2000,"A negative solution has been encountered, suggesting a possible round off error.  Please notify the code author.");
       else
    */
    N[resNum] += Nlist[resNum]*scale;

}

/*****************************
 ********* PostProc **********
 ****************************/

void Result::postProcList(Result* outputList, Mixture *mixPtr, int rootKza)
{
  Component *compPtr=NULL;
  double density;
  int compNum;

  /* get the first component number and density for this root
   * isotope */
  compPtr = mixPtr->getComp(rootKza,density,NULL);

  /* if we found the component */
  while (compPtr)
    {
      compNum = mixPtr->getCompNum(compPtr);

      /* update this component */
      postProc(outputList[compNum],density);

      /* get the next component */
      compPtr = mixPtr->getComp(rootKza,density,compPtr);
    }

  /* we are done with this data now */
  delete next;
  next = NULL;
}

void Result::postProc(Result& outputList, double density)
{
  Result *ptr = this;

  /* for each result isotope */
  while (ptr->next != NULL)
    {
      ptr = ptr->next;

      /* tally the output list */
      outputList.find(ptr->kza)->tally(ptr->N,density);

    }

}

void Result::write(int response, CoolingTime *coolList, double*& total,
		   double volume)
{
  int resNum;
  Result* ptr = this;
  double multiplier=1;
  Node dataAccess;
  char isoSym[15];

  /* initialize the total array */
  delete total;
  total = new double[nResults];
  for (resNum=0;resNum<nResults;resNum++)
    total[resNum] = 0;

  /* write a standard header for this table */
  coolList->writeHeader();

  /* for each isotope in the table */
  while (ptr->next != NULL)
    {
      ptr = ptr->next;

      /* query the data library through a dummy Node object
       * to get the nuclear data for the multiplier */
      switch(response)
	{
	case OUTFMT_ACT:
	  multiplier = dataAccess.getLambda(ptr->kza);
	  break;
	case OUTFMT_HEAT:
	  multiplier = dataAccess.getHeat(ptr->kza);
	  break;
	case OUTFMT_ALPHA:
	  multiplier = dataAccess.getAlpha(ptr->kza);
	  break;
	case OUTFMT_BETA:
	  multiplier = dataAccess.getBeta(ptr->kza);
	  break;
	case OUTFMT_GAMMA:
	  multiplier = dataAccess.getGamma(ptr->kza);
	  break;
	}

      /* if the multipier is 0 (e.g. stable isotope for activity based
	 responses) skip this isotope */
      if (multiplier == 0)
	continue;

      /* renormalize the multiplier by the volume */
      multiplier /= volume;

      /* write the formatted output for this isotope */
      cout << isoName(ptr->kza,isoSym) << "\t";

      for (resNum=0;resNum<nResults;resNum++)
	{
	  sprintf(isoSym,"%-11.4e ",ptr->N[resNum]*multiplier);
	  cout << isoSym;
	  /* increment the total */
	  total[resNum] += ptr->N[resNum]*multiplier;
	}

      cout << endl;
    }

  /* write a separator for the table */
  coolList->writeSeparator();

  /* write the formatted output for the total response */
  cout << "total\t";
  for (resNum=0;resNum<nResults;resNum++)
    {
      sprintf(isoSym,"%-11.4e ",total[resNum]);
      cout << isoSym;
    }
  cout << endl;

}

/*****************************
 ********* PostProc **********
 ****************************/

void Result::initBinDump(char* fname)
{
  binDump = fopen(fname,"wb+");
  if (!binDump)
    error(300,"Unable to open dump file %s",fname);
};

void Result::dumpHeader()
{
  fwrite(&nResults,SINT,1,binDump);
}

void Result::xCheck()
{
  if (binDump == NULL)
    {
      warning(301,"ALARA now requires a binary dump file.  Openning the default file 'alara.dmp'");
      binDump = fopen("alara.dmp","wb+");
      if (!binDump)
	error(300,"Unable to open dump file alara.dmp");
    }
}

void Result::resetBinDump()
{
  fflush(binDump);
  fseek(binDump,0L,SEEK_SET);
  fread(&nResults,SINT,1,binDump);
  verbose(1,"Reset binary dump with %d results per isotope.",nResults);
}

void Result::writeDump()
{
  Result *ptr = this;
  Result *list = next;
  static float *floatN = new float[nResults];
  int resNum;

  while (ptr->next != NULL)
    {
      ptr = ptr->next;

      fwrite(&(ptr->kza),SINT,1,binDump);
      for (resNum=0;resNum<nResults;resNum++)
	floatN[resNum] = ptr->N[resNum];
      fwrite(floatN,SFLOAT,nResults,binDump);

    }

  fwrite(&delimiter,SINT,1,binDump);

  delete list;
  next = NULL;

}

void Result::readDump()
{
  Result *ptr = this;
  int readKza,resNum;

  static float *floatN = new float[nResults];

  fread(&readKza,SINT,1,binDump);
  while (readKza != delimiter)
    {
      fread(floatN,SFLOAT,nResults,binDump);
      ptr->next = new Result(readKza,floatN);
      ptr = ptr->next;
      fread(&readKza,SINT,1,binDump);
    }
}

<|endoftext|>


<commit_before>#ifndef COMMANDOBSERVERBASE_HPP_
#define COMMANDOBSERVERBASE_HPP_

#include "itkCommand.h"
#include "itkArray.h"
#include "itkGradientDescentOptimizer.h"
#include "itkRegularStepGradientDescentOptimizer.h"

using namespace std;

class CommandObserverBase : public itk::Command
{
public:
  typedef itk::Array< double > ParamsType;

  void Execute(itk::Object *caller, const itk::EventObject & event)
  {
	  // in this case, just calls the const version of Execute
    this->Execute( (const itk::Object *)caller, event);
  }

  // extracts info from optimiser into instance variables
  // and calls pure virtual implementation for subclass
	void Execute(const itk::Object *caller, const itk::EventObject & event)
	{
	  // Check if it is the right type of event
	  if( ! itk::IterationEvent().CheckEvent( &event ) )
    { return; }

    // extract values from optimizer
    typedef itk::GradientDescentOptimizer GD;
    typedef itk::RegularStepGradientDescentOptimizer RSGD;

    // optimizer base class does not have GetCurrentIteration method,
    // so runtime check to extract current iteration
    if(const GD* gd = dynamic_cast< const GD* >( caller ))
      extractVariablesFromOptimizer< GD >( gd );
    else if(const RSGD * rsgd = dynamic_cast< const RSGD* >( caller ))
      extractVariablesFromOptimizer< RSGD >( rsgd );
    else
    {
      cerr << "No optimizer found." << endl;
      exit(EXIT_FAILURE);
    }

    // run the derived class virtual method run()
    run();
	}

  // Virtual method to override in base classes
  // Specifics of what the derived class does
  virtual void run() = 0;

  // constructor
  CommandObserverBase() {}

	// explicitly declare virtual destructor,
  // so that base pointers to derived classes will be destroyed fully
  // Made pure virtual to make class abstract
  virtual ~CommandObserverBase()=0;

protected:
  // template method is necessary because there is no interface
  // to extract values in a common Optimizer base class in ITKv3
  // therefore must use implicit template-based interfaces
  template<typename OptimizerType>
  void extractVariablesFromOptimizer(const OptimizerType* optimizer)
  {
    m_iteration = optimizer->GetCurrentIteration();
    m_value     = optimizer->GetValue();
    m_position  = optimizer->GetCurrentPosition();
    m_scales    = optimizer->GetScales();
  }

  // extracted optimiser variables
  unsigned long m_iteration;
  double m_value;
  ParamsType m_position;
  ParamsType m_scales;

private:
  // Copy constructor and copy assignment operator Made private
  // so that no subclasses or clients can use them,
  // deliberately not implemented so not even class methods can use them
  CommandObserverBase(const CommandObserverBase&);
  CommandObserverBase& operator=(const CommandObserverBase&);

};

inline CommandObserverBase::~CommandObserverBase() {}
#endif

<commit_msg>CommandObserverBase ctr initialises members.<commit_after>#ifndef COMMANDOBSERVERBASE_HPP_
#define COMMANDOBSERVERBASE_HPP_

#include "itkCommand.h"
#include "itkArray.h"
#include "itkGradientDescentOptimizer.h"
#include "itkRegularStepGradientDescentOptimizer.h"

using namespace std;

class CommandObserverBase : public itk::Command
{
public:
  typedef itk::Array< double > ParamsType;

  void Execute(itk::Object *caller, const itk::EventObject & event)
  {
	  // in this case, just calls the const version of Execute
    this->Execute( (const itk::Object *)caller, event);
  }

  // extracts info from optimiser into instance variables
  // and calls pure virtual implementation for subclass
	void Execute(const itk::Object *caller, const itk::EventObject & event)
	{
	  // Check if it is the right type of event
	  if( ! itk::IterationEvent().CheckEvent( &event ) )
    { return; }

    // extract values from optimizer
    typedef itk::GradientDescentOptimizer GD;
    typedef itk::RegularStepGradientDescentOptimizer RSGD;

    // optimizer base class does not have GetCurrentIteration method,
    // so runtime check to extract current iteration
    if(const GD* gd = dynamic_cast< const GD* >( caller ))
      extractVariablesFromOptimizer< GD >( gd );
    else if(const RSGD * rsgd = dynamic_cast< const RSGD* >( caller ))
      extractVariablesFromOptimizer< RSGD >( rsgd );
    else
    {
      cerr << "No optimizer found." << endl;
      exit(EXIT_FAILURE);
    }

    // run the derived class virtual method run()
    run();
	}

  // Virtual method to override in base classes
  // Specifics of what the derived class does
  virtual void run() = 0;

	// explicitly declare virtual destructor,
  // so that base pointers to derived classes will be destroyed fully
  // Made pure virtual to make class abstract
  virtual ~CommandObserverBase()=0;

protected:
  // template method is necessary because there is no interface
  // to extract values in a common Optimizer base class in ITKv3
  // therefore must use implicit template-based interfaces
  template<typename OptimizerType>
  void extractVariablesFromOptimizer(const OptimizerType* optimizer)
  {
    m_iteration = optimizer->GetCurrentIteration();
    m_value     = optimizer->GetValue();
    m_position  = optimizer->GetCurrentPosition();
    m_scales    = optimizer->GetScales();
  }

  // extracted optimiser variables
  unsigned long m_iteration;
  double m_value;
  ParamsType m_position;
  ParamsType m_scales;

  // constructor
  CommandObserverBase():m_iteration(0), m_value(0.0) {}

private:
  // Copy constructor and copy assignment operator Made private
  // so that no subclasses or clients can use them,
  // deliberately not implemented so not even class methods can use them
  CommandObserverBase(const CommandObserverBase&);
  CommandObserverBase& operator=(const CommandObserverBase&);

};

inline CommandObserverBase::~CommandObserverBase() {}
#endif

<|endoftext|>


<commit_before>/*------------MD.cpp----------------------------------------------------------//
*
*             MD.cpp -- a simple event-driven MD simulation
*
* Purpose: Figure out the pressure on the interior of a box based on
*          Boltzmann's theory and stuff
*
*   Notes: This simulation will predominantly follow the logic of the link in
*          the README file
*
*          This file was written live by Leios on twitch.tv/simuleios
*          Please note that the efficiency of this code cannot be guaranteed.
*
*-----------------------------------------------------------------------------*/

#include <iostream>
#include <vector>
#include <fstream>
#include <random>
#include <algorithm>

/*----------------------------------------------------------------------------//
* STRUCTS AND FUNCTIONS
*-----------------------------------------------------------------------------*/

// Holds our data in a central struct, to be called mainly in a vector
struct Particle{
    int pid;
    double pos_x, pos_y, pos_z, vel_x, vel_y, vel_z, time;
};

// holds interaction data
struct Interaction{
    double rtime;
    int part1, part2;
};

// Makes starting data
std::vector<Particle> populate(int pnum, double box_length, double max_vel);

// Makes the list for our simulation later, required starting data
std::vector<Interaction> make_list(const std::vector<Particle> &curr_data,
                                   double box_length, double radius);

// This performs our MD simulation with a vector of interactions
// Also writes simulation to file, specified by README
void simulate(std::vector<Interaction> &interactions,
              std::vector<Particle> &curr_data,
              double radius, double mass, double box_length);

// Update list during simulate
std::vector<Interaction> update_list(const std::vector<Particle> &curr_data,
                                     double box_length, double radius,
                                     std::vector<Interaction> list);

/*----------------------------------------------------------------------------//
* MAIN
*-----------------------------------------------------------------------------*/

int main(void){

    int pnum = 10000;
    double box_length = 10, max_vel = 0.01;

    std::vector<Particle> curr_data = populate(pnum, box_length, max_vel);

    for (const auto &p : curr_data){

        std::cout << p.pos_x << std::endl;

    }

    std::vector<Interaction> list = make_list(curr_data, box_length,0.1);

    std::cout << std::endl << std::endl;

    for (const auto &it : list){
        std::cout << it.rtime << std::endl;
    }

    return 0;
}

/*----------------------------------------------------------------------------//
* SUBROUTINES
*-----------------------------------------------------------------------------*/

// Makes starting data
std::vector<Particle> populate(int pnum, double box_length, double max_vel){
    std::vector<Particle> curr_data(pnum);

    // static to create only 1 random_device
    static std::random_device rd;
    static std::mt19937 gen(rd());

    /* instead of doing % and * to get the correct distribution we directly
       specify which distribution we want */

    std::uniform_real_distribution<double>
        box_length_distribution(0, box_length);
    std::uniform_real_distribution<double>
       max_vel_distribution(0, max_vel);

    int pid_counter = 0;
    for (auto &p : curr_data){ //read: for all particles p in curr_data
        p.time = 0;
        p.pid = pid_counter++;

        for (auto &pos : { &p.pos_x, &p.pos_y, &p.pos_z }){
            *pos = box_length_distribution(gen);
        }

        for (auto &vel : { &p.vel_x, &p.vel_y, &p.vel_z }){
            *vel = max_vel_distribution(gen);
        }
    }

    return curr_data;
}

// Makes the list for our simulation later, required starting data
// Step 1: Check interactions between Particles, based on README link
// Step 2: Update list.
// Step 3: Sort list, lowest first
std::vector<Interaction> make_list(const std::vector<Particle> &curr_data,
                                   double box_length, double radius){
    /* passing curr_data as const reference to avoid the copy and accidental
    overwriting */
    std::vector<Interaction> list;
    Interaction test;
    int i = 0, j;
    double del_x, del_y, del_z, del_vx, del_vy, del_vz, r_tot, rad_d, del_vtot;

    // Step 1 -- find interactions
    for (const auto &ip : curr_data){
        j = 0;
        for (const auto &jp : curr_data){
            if (i != j){

                // simple definitions to make things easier later
                del_x = ip.pos_x - jp.pos_x;
                del_y = ip.pos_y - jp.pos_y;
                del_z = ip.pos_z - jp.pos_y;

                del_vx = ip.vel_x - jp.vel_y;
                del_vy = ip.vel_y - jp.vel_y;
                del_vz = ip.vel_z - jp.vel_z;

                r_tot = 2 * radius;

                // This is actually the sqrt(del_vtot)
                del_vtot = del_vx*del_x + del_vy*del_y + del_vz*del_z;

                // This is under the radical in quad eq., thus "rad_d"
                rad_d = (del_vtot * del_vtot
                        - 4 * (del_vx*del_vx + del_vy*del_vy + del_vz*del_vz)
                        * (del_x*del_x + del_y*del_y + del_z*del_z
                           - r_tot*r_tot));

                double taptime;
                if (del_x * del_vx >= 0 && del_y * del_vy >= 0 &&
                    del_z * del_vz >= 0){
                    taptime = 0;
                }

                // NaN error here! Sorry about that ^^, lt was gt (oops!)
                else if (rad_d < 0){
                    taptime = 0;
                }

                else {
                    taptime = (-(del_vx*del_x + del_vy*del_y + del_vz*del_z)
                            + sqrt(rad_d)) / (2 *
                            (del_vx*del_vx + del_vz*del_vz + del_vy*del_vy));
                }

                // Step 2 -- update list
                if (taptime != 0){
                    std::cout << "found one!" << std::endl;
                    test.rtime = taptime;
                    test.part1 = i;
                    test.part2 = j;
                    list.push_back(test);
                }
            }
            j++;
        }
        i++;
    }

    // Step 3 -- sort the list

    // The std::sort command wants to know 3 things:
    //     1. Where to start sorting
    //     2. Where to stop sorting
    //     3. Which element value is greater
    //
    // To check #3, we create a lambda (on-the-fly) function that reads in the
    //     two previous variables as dum1 and dum2 and checks which element is
    //     lesser. That's it.

    std::sort(std::begin(list), std::end(list),
              [](const Interaction &dum1, const Interaction &dum2)
                 {return dum1.rtime < dum2.rtime;});

    return list;
}

// This performs our MD simulation with a vector of interactions
// Also writes simulation to file, specified by README
// Note: Time-loop here
// Step 1: loop over timesteps, defined in list
// Step 2: model the interaction of particles that interact
// Step 3: update list
// Step 4: output positions to file
// UNCHECKED
void simulate(std::vector<Interaction> &interactions,
              std::vector<Particle> &curr_data,
              double radius, double mass, double box_length){

    double del_x, del_y, del_z, J_x, J_y, J_z, J_tot, rtot;
    double del_vx, del_vy, del_vz, del_vtot;

    // Note that these are all defined in the material linked in README
    // Step 1
    for (double simtime = 0; simtime < interactions.back().rtime;
         simtime += interactions[0].rtime){

        del_x = (curr_data[interactions[0].part1].pos_x
                 + curr_data[interactions[0].part1].vel_x * simtime)
                 - (curr_data[interactions[0].part2].pos_x
                 + curr_data[interactions[0].part2].vel_x * simtime);

        del_y = (curr_data[interactions[0].part1].pos_y
                 + curr_data[interactions[0].part1].vel_y * simtime)
                 - (curr_data[interactions[0].part2].pos_y
                 + curr_data[interactions[0].part2].vel_y * simtime);

        del_z = (curr_data[interactions[0].part1].pos_z
                 + curr_data[interactions[0].part1].vel_z * simtime)
                 - (curr_data[interactions[0].part2].pos_z
                 + curr_data[interactions[0].part2].vel_z * simtime);

        del_vx = (curr_data[interactions[0].part1].vel_x)
                 - (curr_data[interactions[0].part2].vel_x);

        del_vy = (curr_data[interactions[0].part1].vel_y)
                 - (curr_data[interactions[0].part2].vel_y);

        del_vz = (curr_data[interactions[0].part1].vel_z)
                 - (curr_data[interactions[0].part2].vel_z);

        rtot = sqrt(del_x * del_x + del_y * del_y + del_z * del_z);
        del_vtot = sqrt(del_vx * del_vx + del_vy * del_vy + del_vz * del_vz);

        // Step 2
        J_tot = (2 * mass * mass * del_vtot * rtot) / (2 * radius * (2 * mass));

        J_x = J_tot * del_x / (2 * radius);
        J_y = J_tot * del_y / (2 * radius);
        J_z = J_tot * del_z / (2 * radius);

        curr_data[interactions[0].part1].vel_x += J_x / mass;
        curr_data[interactions[0].part1].vel_y += J_y / mass;
        curr_data[interactions[0].part1].vel_z += J_z / mass;

        curr_data[interactions[0].part2].vel_x -= J_x / mass;
        curr_data[interactions[0].part2].vel_y -= J_y / mass;
        curr_data[interactions[0].part2].vel_z -= J_z / mass;

        // Step 3 -- update list; TODO
        // UNCHECKED
        interactions = update_list(curr_data, box_length, radius, interactions);

    }

}

// Update list during simulate
// NOT FINISHED
std::vector<Interaction> update_list(const std::vector<Particle> &curr_data,
                                     double box_length, double radius,
                                     std::vector<Interaction> list){

    Interaction test;
    int i = 0;
    double del_x, del_y, del_z, del_vx, del_vy, del_vz, r_tot, rad_d, del_vtot;

    // Copied from above in make_list
    for (const auto &ip : curr_data){
        for (int j = 0; j < 2; j++){
            if (i != 0){
                auto &jp = curr_data[list[j].part1];

                // simple definitions to make things easier later
                del_x = ip.pos_x - jp.pos_x;
                del_y = ip.pos_y - jp.pos_y;
                del_z = ip.pos_z - jp.pos_y;

                del_vx = ip.vel_x - jp.vel_y;
                del_vy = ip.vel_y - jp.vel_y;
                del_vz = ip.vel_z - jp.vel_z;

                r_tot = 2 * radius;

                // This is actually the sqrt(del_vtot)
                del_vtot = del_vx*del_x + del_vy*del_y + del_vz*del_z;

                // This is under the radical in quad eq., thus "rad_d"
                rad_d = (del_vtot * del_vtot
                        - 4 * (del_vx*del_vx + del_vy*del_vy + del_vz*del_vz)
                        * (del_x*del_x + del_y*del_y + del_z*del_z
                           - r_tot*r_tot));

                double taptime;
                if (del_x * del_vx >= 0 && del_y * del_vy >= 0 &&
                    del_z * del_vz >= 0){
                    taptime = 0;
                }

                // NaN error here! Sorry about that ^^, lt was gt (oops!)
                else if (rad_d < 0){
                    taptime = 0;
                }

                else {
                    taptime = (-(del_vx*del_x + del_vy*del_y + del_vz*del_z)
                            + sqrt(rad_d)) / (2 *
                            (del_vx*del_vx + del_vz*del_vz + del_vy*del_vy));
                }

                // Step 2 -- update list
                if (taptime != 0){
                    std::cout << "found one!" << std::endl;
                    test.rtime = taptime;
                    test.part1 = i;
                    test.part2 = j;
                    list.push_back(test);
                }
            }
        }
        i++;
    }

    std::sort(std::begin(list), std::end(list),
              [](const Interaction &dum1, const Interaction &dum2)
                 {return dum1.rtime < dum2.rtime;});

    return list;
}
<commit_msg>Checks on Generated Particle<commit_after>/*------------MD.cpp----------------------------------------------------------//
*
*             MD.cpp -- a simple event-driven MD simulation
*
* Purpose: Figure out the pressure on the interior of a box based on
*          Boltzmann's theory and stuff
*
*   Notes: This simulation will predominantly follow the logic of the link in
*          the README file
*
*          This file was written live by Leios on twitch.tv/simuleios
*          Please note that the efficiency of this code cannot be guaranteed.
*
*-----------------------------------------------------------------------------*/

#include <iostream>
#include <vector>
#include <fstream>
#include <random>
#include <algorithm>

/*----------------------------------------------------------------------------//
* STRUCTS AND FUNCTIONS
*-----------------------------------------------------------------------------*/

// Holds our data in a central struct, to be called mainly in a vector
struct Particle{
    int pid;
    double pos_x, pos_y, pos_z, vel_x, vel_y, vel_z, time;
};

// holds interaction data
struct Interaction{
    double rtime;
    int part1, part2;
};

// Makes starting data
std::vector<Particle> populate(int pnum, double box_length, double max_vel,
                                double radius);

// Makes the list for our simulation later, required starting data
std::vector<Interaction> make_list(const std::vector<Particle> &curr_data,
                                   double box_length, double radius);

// This performs our MD simulation with a vector of interactions
// Also writes simulation to file, specified by README
void simulate(std::vector<Interaction> &interactions,
              std::vector<Particle> &curr_data,
              double radius, double mass, double box_length);

// Update list during simulate
std::vector<Interaction> update_list(const std::vector<Particle> &curr_data,
                                     double box_length, double radius,
                                     std::vector<Interaction> list);

/*----------------------------------------------------------------------------//
* MAIN
*-----------------------------------------------------------------------------*/

int main(void){

    int pnum = 1000;
    double box_length = 10, max_vel = 0.01, radius = 0.1;

    std::vector<Particle> curr_data = populate(pnum, box_length, max_vel, radius);

    for (const auto &p : curr_data){

        std::cout << p.pos_x << std::endl;

    }

    std::vector<Interaction> list = make_list(curr_data, box_length, radius);

    std::cout << std::endl << std::endl;

    for (const auto &it : list){
        std::cout << it.rtime << std::endl;
    }

    return 0;
}

/*----------------------------------------------------------------------------//
* SUBROUTINES
*-----------------------------------------------------------------------------*/

// Makes starting data
std::vector<Particle> populate(int pnum, double box_length, double max_vel,
                                double radius){
    std::vector<Particle> curr_data(pnum);

    // static to create only 1 random_device
    static std::random_device rd;
    static std::mt19937 gen(rd());

    /* instead of doing % and * to get the correct distribution we directly
       specify which distribution we want */

    std::uniform_real_distribution<double>
        box_length_distribution(radius, box_length-radius);
    std::uniform_real_distribution<double>
       max_vel_distribution(0, max_vel);

    int pid_counter = 0;
    for (auto &p : curr_data){ //read: for all particles p in curr_data
        p.time = 0;
        p.pid = pid_counter++;

        bool incorrectGeneration = true;
        while (incorrectGeneration){
            incorrectGeneration = false;
            for (auto &pos : { &p.pos_x, &p.pos_y, &p.pos_z }){
                *pos = box_length_distribution(gen);
            }
            for (int i = 0; i < p.pid; i++){
				auto& other_p = curr_data[i];
				// Distance < Radius * 2 Particle
				// Distance^2 < (Radius*2)^2
				if ( ((other_p.pos_x - p.pos_x)*(other_p.pos_x - p.pos_x) +
					  (other_p.pos_y - p.pos_y)*(other_p.pos_y - p.pos_y) +
					  (other_p.pos_z - p.pos_z)*(other_p.pos_z - p.pos_z))
					  < ((2*radius)*(2*radius)) ) {
					incorrectGeneration = true;
				}
			}
        }

        for (auto &vel : { &p.vel_x, &p.vel_y, &p.vel_z }){
            *vel = max_vel_distribution(gen);
        }
    }

    return curr_data;
}

// Makes the list for our simulation later, required starting data
// Step 1: Check interactions between Particles, based on README link
// Step 2: Update list.
// Step 3: Sort list, lowest first
std::vector<Interaction> make_list(const std::vector<Particle> &curr_data,
                                   double box_length, double radius){
    /* passing curr_data as const reference to avoid the copy and accidental
    overwriting */
    std::vector<Interaction> list;
    Interaction test;
    int i = 0, j;
    double del_x, del_y, del_z, del_vx, del_vy, del_vz, r_tot, rad_d, del_vtot;

    // Step 1 -- find interactions
    for (const auto &ip : curr_data){
        j = 0;
        for (const auto &jp : curr_data){
            if (i != j){

                // simple definitions to make things easier later
                del_x = ip.pos_x - jp.pos_x;
                del_y = ip.pos_y - jp.pos_y;
                del_z = ip.pos_z - jp.pos_y;

                del_vx = ip.vel_x - jp.vel_y;
                del_vy = ip.vel_y - jp.vel_y;
                del_vz = ip.vel_z - jp.vel_z;

                r_tot = 2 * radius;

                // This is actually the sqrt(del_vtot)
                del_vtot = del_vx*del_x + del_vy*del_y + del_vz*del_z;

                // This is under the radical in quad eq., thus "rad_d"
                rad_d = (del_vtot * del_vtot
                        - 4 * (del_vx*del_vx + del_vy*del_vy + del_vz*del_vz)
                        * (del_x*del_x + del_y*del_y + del_z*del_z
                           - r_tot*r_tot));

                double taptime;
                if (del_x * del_vx >= 0 && del_y * del_vy >= 0 &&
                    del_z * del_vz >= 0){
                    taptime = 0;
                }

                // NaN error here! Sorry about that ^^, lt was gt (oops!)
                else if (rad_d < 0){
                    taptime = 0;
                }

                else {
                    taptime = (-(del_vx*del_x + del_vy*del_y + del_vz*del_z)
                            + sqrt(rad_d)) / (2 *
                            (del_vx*del_vx + del_vz*del_vz + del_vy*del_vy));
                }

                // Step 2 -- update list
                if (taptime != 0){
                    std::cout << "found one!" << std::endl;
                    test.rtime = taptime;
                    test.part1 = i;
                    test.part2 = j;
                    list.push_back(test);
                }
            }
            j++;
        }
        i++;
    }

    // Step 3 -- sort the list

    // The std::sort command wants to know 3 things:
    //     1. Where to start sorting
    //     2. Where to stop sorting
    //     3. Which element value is greater
    //
    // To check #3, we create a lambda (on-the-fly) function that reads in the
    //     two previous variables as dum1 and dum2 and checks which element is
    //     lesser. That's it.

    std::sort(std::begin(list), std::end(list),
              [](const Interaction &dum1, const Interaction &dum2)
                 {return dum1.rtime < dum2.rtime;});

    return list;
}

// This performs our MD simulation with a vector of interactions
// Also writes simulation to file, specified by README
// Note: Time-loop here
// Step 1: loop over timesteps, defined in list
// Step 2: model the interaction of particles that interact
// Step 3: update list
// Step 4: output positions to file
// UNCHECKED
void simulate(std::vector<Interaction> &interactions,
              std::vector<Particle> &curr_data,
              double radius, double mass, double box_length){

    double del_x, del_y, del_z, J_x, J_y, J_z, J_tot, rtot;
    double del_vx, del_vy, del_vz, del_vtot;

    // Note that these are all defined in the material linked in README
    // Step 1
    for (double simtime = 0; simtime < interactions.back().rtime;
         simtime += interactions[0].rtime){

        del_x = (curr_data[interactions[0].part1].pos_x
                 + curr_data[interactions[0].part1].vel_x * simtime)
                 - (curr_data[interactions[0].part2].pos_x
                 + curr_data[interactions[0].part2].vel_x * simtime);

        del_y = (curr_data[interactions[0].part1].pos_y
                 + curr_data[interactions[0].part1].vel_y * simtime)
                 - (curr_data[interactions[0].part2].pos_y
                 + curr_data[interactions[0].part2].vel_y * simtime);

        del_z = (curr_data[interactions[0].part1].pos_z
                 + curr_data[interactions[0].part1].vel_z * simtime)
                 - (curr_data[interactions[0].part2].pos_z
                 + curr_data[interactions[0].part2].vel_z * simtime);

        del_vx = (curr_data[interactions[0].part1].vel_x)
                 - (curr_data[interactions[0].part2].vel_x);

        del_vy = (curr_data[interactions[0].part1].vel_y)
                 - (curr_data[interactions[0].part2].vel_y);

        del_vz = (curr_data[interactions[0].part1].vel_z)
                 - (curr_data[interactions[0].part2].vel_z);

        rtot = sqrt(del_x * del_x + del_y * del_y + del_z * del_z);
        del_vtot = sqrt(del_vx * del_vx + del_vy * del_vy + del_vz * del_vz);

        // Step 2
        J_tot = (2 * mass * mass * del_vtot * rtot) / (2 * radius * (2 * mass));

        J_x = J_tot * del_x / (2 * radius);
        J_y = J_tot * del_y / (2 * radius);
        J_z = J_tot * del_z / (2 * radius);

        curr_data[interactions[0].part1].vel_x += J_x / mass;
        curr_data[interactions[0].part1].vel_y += J_y / mass;
        curr_data[interactions[0].part1].vel_z += J_z / mass;

        curr_data[interactions[0].part2].vel_x -= J_x / mass;
        curr_data[interactions[0].part2].vel_y -= J_y / mass;
        curr_data[interactions[0].part2].vel_z -= J_z / mass;

        // Step 3 -- update list; TODO
        // UNCHECKED
        interactions = update_list(curr_data, box_length, radius, interactions);

    }

}

// Update list during simulate
// NOT FINISHED
std::vector<Interaction> update_list(const std::vector<Particle> &curr_data,
                                     double box_length, double radius,
                                     std::vector<Interaction> list){

    Interaction test;
    int i = 0;
    double del_x, del_y, del_z, del_vx, del_vy, del_vz, r_tot, rad_d, del_vtot;

    // Copied from above in make_list
    for (const auto &ip : curr_data){
        for (int j = 0; j < 2; j++){
            if (i != 0){
                auto &jp = curr_data[list[j].part1];

                // simple definitions to make things easier later
                del_x = ip.pos_x - jp.pos_x;
                del_y = ip.pos_y - jp.pos_y;
                del_z = ip.pos_z - jp.pos_y;

                del_vx = ip.vel_x - jp.vel_y;
                del_vy = ip.vel_y - jp.vel_y;
                del_vz = ip.vel_z - jp.vel_z;

                r_tot = 2 * radius;

                // This is actually the sqrt(del_vtot)
                del_vtot = del_vx*del_x + del_vy*del_y + del_vz*del_z;

                // This is under the radical in quad eq., thus "rad_d"
                rad_d = (del_vtot * del_vtot
                        - 4 * (del_vx*del_vx + del_vy*del_vy + del_vz*del_vz)
                        * (del_x*del_x + del_y*del_y + del_z*del_z
                           - r_tot*r_tot));

                double taptime;
                if (del_x * del_vx >= 0 && del_y * del_vy >= 0 &&
                    del_z * del_vz >= 0){
                    taptime = 0;
                }

                // NaN error here! Sorry about that ^^, lt was gt (oops!)
                else if (rad_d < 0){
                    taptime = 0;
                }

                else {
                    taptime = (-(del_vx*del_x + del_vy*del_y + del_vz*del_z)
                            + sqrt(rad_d)) / (2 *
                            (del_vx*del_vx + del_vz*del_vz + del_vy*del_vy));
                }

                // Step 2 -- update list
                if (taptime != 0){
                    std::cout << "found one!" << std::endl;
                    test.rtime = taptime;
                    test.part1 = i;
                    test.part2 = j;
                    list.push_back(test);
                }
            }
        }
        i++;
    }

    std::sort(std::begin(list), std::end(list),
              [](const Interaction &dum1, const Interaction &dum2)
                 {return dum1.rtime < dum2.rtime;});

    return list;
}
<|endoftext|>


<commit_before>#include "perfmon/archive.hpp"

#include "containers/archive/stl_types.hpp"

write_message_t &operator<<(write_message_t &msg, const perfmon_result_t &x) {
    perfmon_result_t::perfmon_result_type_t type = x.get_type();
    msg << type;
    switch (type) {
    case perfmon_result_t::type_value: {
        msg << *x.get_string();
    } break;
    case perfmon_result_t::type_map: {
        int64_t size = x.get_map_size();
        msg << size;
        for (perfmon_result_t::const_iterator it = x.begin(); it != x.end(); ++it) {
            msg << it->first;
            rassert(it->second != NULL);
            msg << *it->second;
        }
    } break;
    default:
        unreachable("unknown prefmon_result_type_t value");
    }

    return msg;
}

archive_result_t deserialize(read_stream_t *s, perfmon_result_t *thing) {
    perfmon_result_t::perfmon_result_type_t type;
    archive_result_t res = deserialize(s, &type);
    if (res) {
        return res;
    }

    thing->reset_type(type);
    switch (type) {
    case perfmon_result_t::type_value: {
        res = deserialize(s, thing->get_string());
        if (res) {
            return res;
        }
    } break;
    case perfmon_result_t::type_map: {
        int64_t size;
        res = deserialize(s, &size);
        if (res) {
            return res;
        }

        for (int64_t i = 0; i < size; ++i) {
            std::string name;
            res = deserialize(s, &name);
            if (res) {
                return res;
            }
            scoped_ptr_t<perfmon_result_t> subthing(new perfmon_result_t);
            res = deserialize(s, subthing.get());
            if (res) {
                return res;
            }

            std::pair<perfmon_result_t::iterator, bool> insert_result
                = thing->insert(name, std::move(subthing));
            if (!insert_result.second) {
                return ARCHIVE_RANGE_ERROR;
            }
        }
    } break;
    default:
        unreachable("unknown prefmon_result_type_t value");
    }

    return ARCHIVE_SUCCESS;
}
<commit_msg>Made perfmon/archive.cc compile in debug mode.<commit_after>#include "perfmon/archive.hpp"

#include "containers/archive/stl_types.hpp"

write_message_t &operator<<(write_message_t &msg, const perfmon_result_t &x) {
    perfmon_result_t::perfmon_result_type_t type = x.get_type();
    msg << type;
    switch (type) {
    case perfmon_result_t::type_value: {
        msg << *x.get_string();
    } break;
    case perfmon_result_t::type_map: {
        int64_t size = x.get_map_size();
        msg << size;
        for (perfmon_result_t::const_iterator it = x.begin(); it != x.end(); ++it) {
            msg << it->first;
            rassert(it->second.has());
            msg << *it->second;
        }
    } break;
    default:
        unreachable("unknown prefmon_result_type_t value");
    }

    return msg;
}

archive_result_t deserialize(read_stream_t *s, perfmon_result_t *thing) {
    perfmon_result_t::perfmon_result_type_t type;
    archive_result_t res = deserialize(s, &type);
    if (res) {
        return res;
    }

    thing->reset_type(type);
    switch (type) {
    case perfmon_result_t::type_value: {
        res = deserialize(s, thing->get_string());
        if (res) {
            return res;
        }
    } break;
    case perfmon_result_t::type_map: {
        int64_t size;
        res = deserialize(s, &size);
        if (res) {
            return res;
        }

        for (int64_t i = 0; i < size; ++i) {
            std::string name;
            res = deserialize(s, &name);
            if (res) {
                return res;
            }
            scoped_ptr_t<perfmon_result_t> subthing(new perfmon_result_t);
            res = deserialize(s, subthing.get());
            if (res) {
                return res;
            }

            std::pair<perfmon_result_t::iterator, bool> insert_result
                = thing->insert(name, std::move(subthing));
            if (!insert_result.second) {
                return ARCHIVE_RANGE_ERROR;
            }
        }
    } break;
    default:
        unreachable("unknown prefmon_result_type_t value");
    }

    return ARCHIVE_SUCCESS;
}
<|endoftext|>


<commit_before>#include "blockinfo.h"

#if defined(__linux__) /* Linux */
#include <linux/fs.h>
#elif defined(BSD) || defined(__darwin__) /* *BSD/Darwin */
#include <sys/disklabel.h>
#include <sys/disk.h>
#endif

bool block_info(const char* device, blockinfo_t& info) noexcept
{
  posix::fd_t fd = posix::open(device, O_RDONLY);

  if(fd == posix::error_response)
    return false;
  bool rvalue = block_info(fd, info);
  return posix::close(fd) && rvalue;
}

bool block_info(posix::fd_t fd, blockinfo_t& info) noexcept
{

  // get block size (if needed)
#if defined(BLKSSZGET) // Linux
  if(posix::ioctl(fd, BLKSSZGET, &info.block_size) <= posix::error_response)
    return false;
#elif defined(DKIOCGETBLOCKCOUNT) // Darwin
  if(posix::ioctl(fd, DKIOCGETBLOCKCOUNT, &info.block_size) <= posix::error_response)
    return false;
#elif defined(DIOCGSECTORSIZE) // BSD
  if(posix::ioctl(fd, DIOCGSECTORSIZE, &info.block_size) <= posix::error_response)
    return false;
#elif defined(BLOCK_SIZE) // Linux (hardcoded)
  info.block_size = BLOCK_SIZE;
#else
  info.block_size = 512; // default size
#endif

  // try to get the raw size of the partition (might be larger than the usable size)
#if defined(DKIOCGETBLOCKCOUNT) // Darwin
  if(posix::ioctl(fd, DKIOCGETBLOCKCOUNT, &info.block_count) <= posix::error_response)
    return false;

#elif defined(DIOCGMEDIASIZE) // BSD
  if(posix::ioctl(fd, DIOCGMEDIASIZE, &info.block_count) <= posix::error_response)
    return false;
  info.block_count /= info.block_size;

#elif defined(DIOCGDINFO) // old BSD
  struct disklabel info;
  if(posix::ioctl(fd, DIOCGDINFO, &info) <= posix::error_response)
    return false;
  info.block_size = info.d_secsize;
  info.block_count = info.d_ncylinders * info.d_secpercyl;

#elif defined(BLKGETSIZE64) // Linux 2.6+
  if(posix::ioctl(fd, BLKGETSIZE64, &info.block_count) <= posix::error_response)
    return false;
  info.block_count /= info.block_size;

#elif defined(BLKGETSIZE) // old Linux
  int bc = 0;
  if(posix::ioctl(fd, BLKGETSIZE, &bc) <= posix::error_response)
    return false;
  info.block_count = uint64_t(bc) * 512; // due to previously hardcoded sector size
  info.block_count /= info.block_size;

#else
# pragma message("Falling back on lseek(fd, 0, SEEK_END) to get device size.  This is undefined behavior in POSIX.")
  info.block_count = uint64_t(::lseek(fd, 0, SEEK_END)); // behavior not defined in POSIX for devices but try as a last resort
  info.block_count /= info.block_size;
#endif
  return true;
}
<commit_msg>added code for ancient Linux but I need to figure out the calculation later<commit_after>#include "blockinfo.h"

#if defined(__linux__) /* Linux */
#include <linux/fs.h>
#include <linux/hdreg.h> // ancient Linux
#elif defined(BSD) || defined(__darwin__) /* *BSD/Darwin */
#include <sys/disklabel.h>
#include <sys/disk.h>
#endif

bool block_info(const char* device, blockinfo_t& info) noexcept
{
  posix::fd_t fd = posix::open(device, O_RDONLY);

  if(fd == posix::error_response)
    return false;
  bool rvalue = block_info(fd, info);
  return posix::close(fd) && rvalue;
}

bool block_info(posix::fd_t fd, blockinfo_t& info) noexcept
{
  // get block size (if needed)
#if defined(BLKSSZGET) // Linux
  if(posix::ioctl(fd, BLKSSZGET, &info.block_size) <= posix::error_response)
    return false;
#elif defined(DKIOCGETBLOCKCOUNT) // Darwin
  if(posix::ioctl(fd, DKIOCGETBLOCKCOUNT, &info.block_size) <= posix::error_response)
    return false;
#elif defined(DIOCGSECTORSIZE) // BSD
  if(posix::ioctl(fd, DIOCGSECTORSIZE, &info.block_size) <= posix::error_response)
    return false;
#elif defined(BLOCK_SIZE) // Linux (hardcoded)
  info.block_size = BLOCK_SIZE;
#else
  info.block_size = 512; // default size
#endif

  // try to get the raw size of the partition (might be larger than the usable size)
#if defined(DKIOCGETBLOCKCOUNT) // Darwin
  if(posix::ioctl(fd, DKIOCGETBLOCKCOUNT, &info.block_count) <= posix::error_response)
    return false;

#elif defined(DIOCGMEDIASIZE) // BSD
  if(posix::ioctl(fd, DIOCGMEDIASIZE, &info.block_count) <= posix::error_response)
    return false;
  info.block_count /= info.block_size;

#elif defined(DIOCGDINFO) // old BSD
  struct disklabel info;
  if(posix::ioctl(fd, DIOCGDINFO, &info) <= posix::error_response)
    return false;
  info.block_size = info.d_secsize;
  info.block_count = info.d_ncylinders * info.d_secpercyl;

#elif defined(BLKGETSIZE64) // Linux 2.6+
  if(posix::ioctl(fd, BLKGETSIZE64, &info.block_count) <= posix::error_response)
    return false;
  info.block_count /= info.block_size;

#elif defined(BLKGETSIZE) // old Linux
  int bc = 0;
  if(posix::ioctl(fd, BLKGETSIZE, &bc) <= posix::error_response)
    return false;
  info.block_count = uint64_t(bc) * 512; // due to previously hardcoded sector size
  info.block_count /= info.block_size;

#elif defined(HDIO_GETGEO) // ancient Linux
  struct hd_geometry geom;
  if(posix::ioctl(fd, HDIO_GETGEO, &geom) <= posix::error_response)
    return false;
# error Sorry but the HDIO_GETGEO code is non-functional. ;(
  geom.heads; // number of heads
  geom.sectors; // number of sectors/track
  geom.cylinders; // number of cylinders, mod 65536
  geom.start; // starting sector of this partition.

#else
# pragma message("Falling back on lseek(fd, 0, SEEK_END) to get device size.  This is undefined behavior in POSIX.")
  info.block_count = uint64_t(::lseek(fd, 0, SEEK_END)); // behavior not defined in POSIX for devices but try as a last resort
  info.block_count /= info.block_size;
#endif
  return true;
}
<|endoftext|>


<commit_before>#include <boost/tokenizer.hpp>
#include <iostream>
#include <unistd.h>
#include <string.h>
#include <cstdlib>
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <sstream>
#include <vector>

using namespace std;
using namespace boost;

void execvp(char **ye, int k) {
	ye[k] = NULL;
        int pid = fork();
        if(pid == -1) {
       		perror("fork");
                exit(1);
        }
        if(pid == 0) {
        	int r = execvp(ye[0], ye);
                if(r == -1) {
                       perror("execvp");
                       exit(1);
                }
        }
      	else {
        	if(-1 == waitpid(pid, &pid, 0)) {
                          perror("waitpid");
                }
        }

}

void pipe() {}

void rshell(string &x) {
	char *argv[9];
	int i = 0;
	string going;
	string saad;
	vector<string> arg_s;
	typedef tokenizer< char_separator<char> > tokenizer;
	char_separator<char> sep (" ", "#-;||&&", drop_empty_tokens);
	tokenizer tokens(x, sep);
	for(tokenizer::iterator tok_iter=tokens.begin(); tok_iter != tokens.end(); ++tok_iter) {
		 if(saad == "-") {
			going += *tok_iter;
			going += " ";
		 	saad.append(*tok_iter);
			arg_s.push_back(saad);
			argv[i] = new char[12];
			strcpy(argv[i], const_cast<char*>(saad.c_str()));
			if(*tok_iter == "exit")
				exit(0);
                        ++i;
                        continue;

		  }

                  if(*tok_iter == "-") {
                        saad = *tok_iter;
			going += *tok_iter;
			going += " ";
                        continue;
                  }

	          if(*tok_iter == "#") {
			break;
		  }

		  if(*tok_iter == ";") {
                        ++tok_iter;
                        rshell(going);
                        going.erase(0, going.find(*tok_iter, i));
                        arg_s.clear();
                        i = 0;
                        argv[i] = new char[12];
	          }

		  if(*tok_iter == "&") {
			++tok_iter;
			if(*tok_iter == "&") {
				++tok_iter;
				rshell(going);
				going.erase(0, going.find(*tok_iter, i));
				arg_s.clear();
				i = 0;
				argv[i] = new char[12];
			}
		  }

		  if(*tok_iter == "|") {
			++tok_iter;
			if(*tok_iter == "|") {
				++tok_iter;
				rshell(going);
				going.erase(0, going.find(*tok_iter, i));
				arg_s.clear();
				i = 0;
				argv[i] = new char[12];
			}

		  }

		  going += *tok_iter;
		  going += " ";

		  arg_s.push_back(*tok_iter);
		  argv[i] = new char[12];
	 	  strcpy(argv[i], const_cast<char*>(arg_s[i].c_str()));

		  if(*tok_iter == "exit")
			exit(0);

		  ++i;

	}
	execvp(argv, i);

	return;
}

int main()
{
	string args;
	while(1 != 2)
	{
		cout << "$ ";
		getline(cin, args);
		rshell(args);
	}

	return 0;
}
<commit_msg>piping started<commit_after>#include <boost/tokenizer.hpp>
#include <iostream>
#include <unistd.h>
#include <string.h>
#include <cstdlib>
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <sstream>
#include <vector>
#include <sys/stat.h>
#include <fcntl.h>

using namespace std;
using namespace boost;

void execvp(char **ye, int k) {
	ye[k] = NULL;
        int pid = fork();
        if(pid == -1) {
       		perror("fork");
                exit(1);
        }
        if(pid == 0) {
        	int r = execvp(ye[0], ye);
                if(r == -1) {
                       perror("execvp");
                       exit(1);
                }
        }
      	else {
        	if(-1 == waitpid(pid, &pid, 0)) {
                          perror("waitpid");
                }
        }

}

void rshell(string &x) {
	char *argv[9];
	int i = 0;
	string going;
	string saad;
	vector<string> arg_s;
	typedef tokenizer< char_separator<char> > tokenizer;
	char_separator<char> sep (" ", "<>>>#-;||&&", drop_empty_tokens);
	tokenizer tokens(x, sep);
	for(tokenizer::iterator tok_iter=tokens.begin(); tok_iter != tokens.end(); ++tok_iter) {
		 if(saad == "-") {
			going += *tok_iter;
			going += " ";
		 	saad.append(*tok_iter);
			arg_s.push_back(saad);
			argv[i] = new char[12];
			strcpy(argv[i], const_cast<char*>(saad.c_str()));
			if(*tok_iter == "exit")
				exit(0);
                        ++i;
                        continue;

		  }

                  if(*tok_iter == "-") {
                        saad = *tok_iter;
			going += *tok_iter;
			going += " ";
                        continue;
                  }

	          if(*tok_iter == "#") {
			break;
		  }

		  if(*tok_iter == ";") {
                        ++tok_iter;
                        rshell(going);
                        going.erase(0, going.find(*tok_iter, i));
                        arg_s.clear();
                        i = 0;
                        argv[i] = new char[12];
	          }

		  if(*tok_iter == "&") {
			++tok_iter;
			if(*tok_iter == "&") {
				++tok_iter;
				rshell(going);
				going.erase(0, going.find(*tok_iter, i));
				arg_s.clear();
				i = 0;
				argv[i] = new char[12];
			}
		  }

		  if(*tok_iter == "<") {
			++tok_iter;
			string cake = *tok_iter;
			int fd = open(cake.c_str(), O_RDWR);
			if(fd == -1) {
				perror("open");
				exit(1);
			}
			int oldstdin = dup(0);
			if(oldstdin == -1) {
				perror("dup");
				exit(1);
			}
			int kd = close(0);
			if(kd == -1) {
				perror("close");
				exit(1);
			}
			int grat = dup2(oldstdin, fd);
			if(grat == -1)
			{
				perror("dup2");
				exit(1);
			}
			int blah = close(fd);
			if(blah == -1)
			{
				perror("blah");
				exit(1);
			}
			continue;

		  }

		  if(*tok_iter == ">") {
			++tok_iter;
			if(*tok_iter == ">") {

			}
			string cake = *tok_iter;
			int fd = open(cake.c_str(), O_RDWR | O_CREAT);
			if(fd == -1) {
				perror("open");
				exit(1);
			}
			int oldstdout = dup(1);
			if(oldstdout == -1) {
				perror("dup");
				exit(1);
			}
			int kd = close(1);
			if(kd == -1) {
				perror("close");
				exit(1);
			}
			int grat = dup2(oldstdout, fd);
			if(grat == -1)
			{
				perror("grat");
				exit(1);
			}
			int blah = close(fd);
			if(blah == -1)
			{
				perror("close");
				exit(1);
			}
			continue;
		  }

		  if(*tok_iter == "|") {
			++tok_iter;

			//piping

			if(*tok_iter == "|") {
				++tok_iter;
				rshell(going);
				going.erase(0, going.find(*tok_iter, i));
				arg_s.clear();
				i = 0;
				argv[i] = new char[12];
			}

		  }

		  going += *tok_iter;
		  going += " ";

		  arg_s.push_back(*tok_iter);
		  argv[i] = new char[12];
	 	  strcpy(argv[i], const_cast<char*>(arg_s[i].c_str()));

		  if(*tok_iter == "exit")
			exit(0);

		  ++i;

	}
	execvp(argv, i);

	return;
}

int main()
{
	string args;
	while(1 != 2)
	{
		cout << "$ ";
		getline(cin, args);
		rshell(args);
	}

	return 0;
}
<|endoftext|>


<commit_before>#ifndef INCLUDE_AL_FILE_HPP
#define INCLUDE_AL_FILE_HPP

#include <unistd.h>
#include <stdio.h>
#include <string>
#include <sys/stat.h>
#include <list>

#include "system/al_Config.h"

#ifdef AL_WIN32
	#define AL_FILE_DELIMITER '\\'
#else
	#define AL_FILE_DELIMITER '/'
#endif

#define AL_PATH_MAX (4096)

namespace al{

/// Strips a qualified path to a file (src) into a path to the containing folder (dst)
void path2dir(char* dst, const char* src);

/// a pair of path (folder/directory) and filename
class FilePath {
public:
	FilePath() {};
	FilePath(std::string file, std::string path = "/") : mPath(path), mFile(file) {}

	const std::string& file() const { return mFile; }
	const std::string& path() const { return mPath; }

	std::string filepath() const { return path()+file(); }

	FilePath& file(const std::string& v) { mFile=v; return *this; }
	FilePath& path(const std::string& v) { mPath=v; return *this; }

protected:
	std::string mPath;
	std::string mFile;
};

/// A handy way to manage several possible search paths
class SearchPaths {
public:
	SearchPaths() {}
	SearchPaths(int argc, char * const argv[], bool recursive=true) { addAppPaths(argc,argv,recursive); }
	~SearchPaths() {}

	/// find a file in the searchpaths
	/// returns true if file found, and fills result with corresponding path & filename
	/// returns false if file not found
	FilePath find(const std::string& filename);

	/// add a path to search in; recursive searching is optional
	void addSearchPath(const std::string& path, bool recursive = true);

	/// adds best estimate of application launch paths (cwd etc.)
	/// can pass in argv from the main() function if desired.
	void addAppPaths(int argc, char * const argv[], bool recursive = true);
	void addAppPaths(bool recursive = true);

	const std::string& appPath() const { return mAppPath; }

	/// todo?
	//void addResourcePath();

	// strips trailing filename from a path; e.g. /usr/bin/man -> /usr/bin/
	static std::string stripFileName(const std::string& src);
	// ensure path ends with the proper delimiter
	static std::string conformPath(const std::string& src);
	// does a file at the given filepath exist?
	static bool fileExists(const std::string& name, const std::string& path);

protected:

	typedef std::pair<std::string, bool> searchpath;
	std::list<searchpath> mSearchPaths;

	std::string mAppPath;

};

/// File
class File{
public:

	/// @param[in] path		path of file
	/// @param[in] mode		i/o mode w, r, wb, rb
	File(std::string path, std::string mode="r", bool open=false);

	~File();

	void close();	///< Close file
	bool open();	///< Open file with specified i/o mode

	File& mode(std::string v){ mMode=v.data(); return *this; }
	File& path(std::string v){ mPath=v.data(); return *this; }

	/// Write memory elements to file
	int write(std::string v){ return fwrite(v.data(), 1, v.length(), mFP); }
	int write(const void * v, int size, int items=1){ return fwrite(v, size, items, mFP); }

	/// Quick and dirty write memory to file
	static int write(std::string path, const void * v, int size, int items=1);

	/// Returns character string of file contents (read mode only)
	char * readAll();

	/// Returns whether file is open
	bool opened() const { return 0 != mFP; }

	/// Returns file i/o mode string
	const char * mode() const { return mMode; }

	/// Returns path string
	const char * path() const { return mPath; }

	/// Returns size (in bytes) of file contents
	int size() const { return mSizeBytes; }

	/// Returns whether file exists
	static bool exists(std::string path);

	/// Return modification time of file (or 0 on failure)
	/// as number of seconds since 00:00:00 january 1, 1970 UTC
	al_sec modified();
	/// Return last access time of file (or 0 on failure)
	/// as number of seconds since 00:00:00 january 1, 1970 UTC
	al_sec accessed();
	/// Return creation time of file (or 0 on failure)
	/// as number of seconds since 00:00:00 january 1, 1970 UTC
	al_sec created();

	/// Return size file (or 0 on failure)
	size_t size();
	/// Return space used on disk of file (or 0 on failure)
	size_t storage();

	FILE * filePointer() { return mFP; }

protected:
	const char * mPath;
	const char * mMode;
	char * mContent;
	int mSizeBytes;
	FILE * mFP;

	class Impl; Impl * mImpl;

	void freeContent();
	void allocContent(int n);
	void getSize();
};

//// INLINE IMPLEMENTATION ////

inline std::string SearchPaths::stripFileName(const std::string& src) {
	std::string filepath(src);
	size_t pos = filepath.find_last_of(AL_FILE_DELIMITER);
	if (pos !=std::string::npos) {
		filepath.erase(pos+1);
	}
	return filepath;
}

inline std::string SearchPaths::conformPath(const std::string& src) {
	std::string path(src);
	// paths should end with a delimiter:
	if (path[path.size()-1] != AL_FILE_DELIMITER) {
		path += AL_FILE_DELIMITER;
	}
	return path;
}

inline void SearchPaths::addAppPaths(int argc, char * const argv[], bool recursive) {
	addAppPaths(recursive);
	if (argc > 0) {
		//char path[4096];
		std::string filepath = stripFileName(argv[0]);
		mAppPath = filepath;
		addSearchPath(filepath, recursive);
	}
}

inline void SearchPaths::addAppPaths(bool recursive) {
	char cwd[4096];
	getcwd(cwd, sizeof(cwd));
	addSearchPath(cwd, recursive);
}

inline void SearchPaths::addSearchPath(const std::string& src, bool recursive) {
	std::string path=conformPath(src);

	// check for duplicates
	std::list<searchpath>::iterator iter = mSearchPaths.begin();
	while (iter != mSearchPaths.end()) {
		//printf("path %s\n", iter->first.data());
		if (path == iter->first.data()) {
			return;
		}
		iter++;
	}
	printf("adding path %s\n", path.data());
	mSearchPaths.push_front(searchpath(path, recursive));
}

inline bool SearchPaths::fileExists(const std::string& path, const std::string& name) {
	struct stat stFileInfo;
	std::string filename(path+name);
	return (stat((path + name).c_str(),&stFileInfo) == 0);
}

} // al::

#endif

<commit_msg>fixed initialization order in File()<commit_after>#ifndef INCLUDE_AL_FILE_HPP
#define INCLUDE_AL_FILE_HPP

#include <unistd.h>
#include <stdio.h>
#include <string>
#include <sys/stat.h>
#include <list>

#include "system/al_Config.h"

#ifdef AL_WIN32
	#define AL_FILE_DELIMITER '\\'
#else
	#define AL_FILE_DELIMITER '/'
#endif

#define AL_PATH_MAX (4096)

namespace al{

/// Strips a qualified path to a file (src) into a path to the containing folder (dst)
void path2dir(char* dst, const char* src);

/// a pair of path (folder/directory) and filename
class FilePath {
public:
	FilePath() {};
	FilePath(std::string file, std::string path = "/") : mPath(path), mFile(file) {}

	const std::string& file() const { return mFile; }
	const std::string& path() const { return mPath; }

	std::string filepath() const { return path()+file(); }

	FilePath& file(const std::string& v) { mFile=v; return *this; }
	FilePath& path(const std::string& v) { mPath=v; return *this; }

protected:
	std::string mPath;
	std::string mFile;
};

/// A handy way to manage several possible search paths
class SearchPaths {
public:
	SearchPaths() {}
	SearchPaths(int argc, char * const argv[], bool recursive=true) { addAppPaths(argc,argv,recursive); }
	~SearchPaths() {}

	/// find a file in the searchpaths
	/// returns true if file found, and fills result with corresponding path & filename
	/// returns false if file not found
	FilePath find(const std::string& filename);

	/// add a path to search in; recursive searching is optional
	void addSearchPath(const std::string& path, bool recursive = true);

	/// adds best estimate of application launch paths (cwd etc.)
	/// can pass in argv from the main() function if desired.
	void addAppPaths(int argc, char * const argv[], bool recursive = true);
	void addAppPaths(bool recursive = true);

	const std::string& appPath() const { return mAppPath; }

	/// todo?
	//void addResourcePath();

	// strips trailing filename from a path; e.g. /usr/bin/man -> /usr/bin/
	static std::string stripFileName(const std::string& src);
	// ensure path ends with the proper delimiter
	static std::string conformPath(const std::string& src);
	// does a file at the given filepath exist?
	static bool fileExists(const std::string& name, const std::string& path);

protected:

	typedef std::pair<std::string, bool> searchpath;
	std::list<searchpath> mSearchPaths;

	std::string mAppPath;

};

/// File
class File{
public:

	/// @param[in] path		path of file
	/// @param[in] mode		i/o mode w, r, wb, rb
	File(std::string path, std::string mode="r", bool open=false);

	~File();

	void close();	///< Close file
	bool open();	///< Open file with specified i/o mode

	File& mode(std::string v){ mMode=v.data(); return *this; }
	File& path(std::string v){ mPath=v.data(); return *this; }

	/// Write memory elements to file
	int write(std::string v){ return fwrite(v.data(), 1, v.length(), mFP); }
	int write(const void * v, int size, int items=1){ return fwrite(v, size, items, mFP); }

	/// Quick and dirty write memory to file
	static int write(std::string path, const void * v, int size, int items=1);

	/// Returns character string of file contents (read mode only)
	char * readAll();

	/// Returns whether file is open
	bool opened() const { return 0 != mFP; }

	/// Returns file i/o mode string
	const char * mode() const { return mMode; }

	/// Returns path string
	const char * path() const { return mPath; }

	/// Returns size (in bytes) of file contents
	int size() const { return mSizeBytes; }

	/// Returns whether file exists
	static bool exists(std::string path);

	/// Return modification time of file (or 0 on failure)
	/// as number of seconds since 00:00:00 january 1, 1970 UTC
	al_sec modified();
	/// Return last access time of file (or 0 on failure)
	/// as number of seconds since 00:00:00 january 1, 1970 UTC
	al_sec accessed();
	/// Return creation time of file (or 0 on failure)
	/// as number of seconds since 00:00:00 january 1, 1970 UTC
	al_sec created();

	/// Return size file (or 0 on failure)
	size_t size();
	/// Return space used on disk of file (or 0 on failure)
	size_t storage();

	FILE * filePointer() { return mFP; }

protected:
	class Impl; Impl * mImpl;

	const char * mPath;
	const char * mMode;
	char * mContent;
	int mSizeBytes;
	FILE * mFP;

	void freeContent();
	void allocContent(int n);
	void getSize();
};

//// INLINE IMPLEMENTATION ////

inline std::string SearchPaths::stripFileName(const std::string& src) {
	std::string filepath(src);
	size_t pos = filepath.find_last_of(AL_FILE_DELIMITER);
	if (pos !=std::string::npos) {
		filepath.erase(pos+1);
	}
	return filepath;
}

inline std::string SearchPaths::conformPath(const std::string& src) {
	std::string path(src);
	// paths should end with a delimiter:
	if (path[path.size()-1] != AL_FILE_DELIMITER) {
		path += AL_FILE_DELIMITER;
	}
	return path;
}

inline void SearchPaths::addAppPaths(int argc, char * const argv[], bool recursive) {
	addAppPaths(recursive);
	if (argc > 0) {
		//char path[4096];
		std::string filepath = stripFileName(argv[0]);
		mAppPath = filepath;
		addSearchPath(filepath, recursive);
	}
}

inline void SearchPaths::addAppPaths(bool recursive) {
	char cwd[4096];
	getcwd(cwd, sizeof(cwd));
	addSearchPath(cwd, recursive);
}

inline void SearchPaths::addSearchPath(const std::string& src, bool recursive) {
	std::string path=conformPath(src);

	// check for duplicates
	std::list<searchpath>::iterator iter = mSearchPaths.begin();
	while (iter != mSearchPaths.end()) {
		//printf("path %s\n", iter->first.data());
		if (path == iter->first.data()) {
			return;
		}
		iter++;
	}
	printf("adding path %s\n", path.data());
	mSearchPaths.push_front(searchpath(path, recursive));
}

inline bool SearchPaths::fileExists(const std::string& path, const std::string& name) {
	struct stat stFileInfo;
	std::string filename(path+name);
	return (stat((path + name).c_str(),&stFileInfo) == 0);
}

} // al::

#endif

<|endoftext|>


<commit_before>/*
 * groundManager.cpp
 *
 *  Created on: Sep 11, 2013
 *      Author: chpark
 */
#include <itomp_cio_planner/contact/ground_manager.h>
#include <itomp_cio_planner/util/planning_parameters.h>
#include <itomp_cio_planner/util/point_to_triangle_projection.h>
#include <itomp_cio_planner/util/exponential_map.h>
#include <limits>

namespace itomp_cio_planner
{

GroundManager::GroundManager()
{
}

GroundManager::~GroundManager()
{
}

void GroundManager::initialize(
		const planning_scene::PlanningSceneConstPtr& planning_scene)
{
	planning_scene_ = planning_scene;
	initializeStaticScene();
}

void GroundManager::getNearestGroundPosition(const Eigen::Vector3d& position_in,
		const Eigen::Vector3d& orientation_in, Eigen::Vector3d& position_out,
		Eigen::Vector3d& orientation_out, Eigen::Vector3d& normal) const
{
	double min_dist = position_in(2) - (-0.227936);

	// ground
	position_out = Eigen::Vector3d(position_in(0), position_in(1), -0.227936);
	normal = Eigen::Vector3d(0, 0, 1);

	Eigen::Matrix3d orientation_in_mat =
			exponential_map::ExponentialMapToRotation(orientation_in);
	Eigen::Vector3d x_axis = orientation_in_mat.col(0);
	Eigen::Vector3d y_axis = orientation_in_mat.col(1);
	Eigen::Vector3d normal_in = orientation_in_mat.col(2);

	if (position_in(0) < -4.4)
	{

	}
	else if (position_in(0) < -4.0)
	{
		position_out(2) = 1.2;
	}
	else if (position_in(0) < -3.0)
	{
		position_out(2) = 0.5;
	}

	//getNearestMeshPosition(position_in, position_out, normal_in, normal, min_dist);

	Eigen::Vector3d proj_x_axis = x_axis - x_axis.dot(normal) * normal;
	Eigen::Vector3d proj_y_axis = y_axis - y_axis.dot(normal) * normal;
	if (proj_x_axis.norm() > proj_y_axis.norm())
	{
		proj_x_axis.normalize();
		proj_y_axis = normal.cross(proj_x_axis);
	}
	else
	{
		proj_y_axis.normalize();
		proj_x_axis = proj_y_axis.cross(normal);
	}
	Eigen::Matrix3d orientation_out_mat;
	orientation_out_mat.col(0) = proj_x_axis;
	orientation_out_mat.col(1) = proj_y_axis;
	orientation_out_mat.col(2) = normal;
	orientation_out = exponential_map::RotationToExponentialMap(
			orientation_out_mat);
}

bool GroundManager::getNearestMeshPosition(const Eigen::Vector3d& position_in,
		Eigen::Vector3d& position_out, const Eigen::Vector3d& normal_in, Eigen::Vector3d& normal,
		double current_min_distance) const
{
	bool updated = false;

	for (int i = 0; i < triangles_.size(); ++i)
	{
		const Triangle& triangle = triangles_[i];

		Eigen::Vector3d projection = ProjPoint2Triangle(triangle.points_[0], triangle.points_[1],
				triangle.points_[2], position_in);
		double distance = (position_in - projection).norm();
		if (distance < current_min_distance)
		{
			current_min_distance = distance;
			normal = triangle.normal_;
			position_out = projection;

			updated = true;
		}
	}

	return updated;
}

void GroundManager::initializeStaticScene()
{
	triangles_.clear();

	const collision_detection::WorldConstPtr& world =
			planning_scene_->getWorld();
	std::vector<std::string> object_ids = world->getObjectIds();
	for (int i = 0; i < object_ids.size(); ++i)
	{
		collision_detection::World::ObjectConstPtr obj = world->getObject(
				object_ids[i]);
		for (int j = 0; j < obj->shapes_.size(); ++j)
		{
			shapes::ShapeConstPtr shape = obj->shapes_[j];
			const shapes::Mesh* mesh =
					dynamic_cast<const shapes::Mesh*>(shape.get());
			if (mesh == NULL)
				continue;

			Eigen::Affine3d& transform = obj->shape_poses_[j];
			for (int k = 0; k < mesh->triangle_count; ++k)
			{
				int triangle_vertex1 = mesh->triangles[3 * k];
				int triangle_vertex2 = mesh->triangles[3 * k + 1];
				int triangle_vertex3 = mesh->triangles[3 * k + 2];
				Eigen::Vector3d position1(mesh->vertices[3 * triangle_vertex1],
						mesh->vertices[3 * triangle_vertex1 + 1],
						mesh->vertices[3 * triangle_vertex1 + 2]);
				Eigen::Vector3d position2(mesh->vertices[3 * triangle_vertex2],
						mesh->vertices[3 * triangle_vertex2 + 1],
						mesh->vertices[3 * triangle_vertex2 + 2]);
				Eigen::Vector3d position3(mesh->vertices[3 * triangle_vertex3],
						mesh->vertices[3 * triangle_vertex3 + 1],
						mesh->vertices[3 * triangle_vertex3 + 2]);
				position1 = transform * position1;
				position2 = transform * position2;
				position3 = transform * position3;

				Eigen::Vector3d p0 = (position2 - position1);
				Eigen::Vector3d p1 = (position3 - position1);
				p0.normalize();
				p1.normalize();
				Eigen::Vector3d normal = p0.cross(p1);
				if (normal.norm() < 1e-7)
					continue;
				normal.normalize();

				Triangle tri;
				tri.points_[0] = position1;
				tri.points_[1] = position2;
				tri.points_[2] = position3;
				tri.normal_ = normal;
				triangles_.push_back(tri);
			}
		}
	}
}

}

<commit_msg>get contact points from mesh<commit_after>/*
 * groundManager.cpp
 *
 *  Created on: Sep 11, 2013
 *      Author: chpark
 */
#include <itomp_cio_planner/contact/ground_manager.h>
#include <itomp_cio_planner/util/planning_parameters.h>
#include <itomp_cio_planner/util/point_to_triangle_projection.h>
#include <itomp_cio_planner/util/exponential_map.h>
#include <limits>

namespace itomp_cio_planner
{

GroundManager::GroundManager()
{
}

GroundManager::~GroundManager()
{
}

void GroundManager::initialize(
		const planning_scene::PlanningSceneConstPtr& planning_scene)
{
	planning_scene_ = planning_scene;
	initializeStaticScene();
}

void GroundManager::getNearestGroundPosition(const Eigen::Vector3d& position_in,
		const Eigen::Vector3d& orientation_in, Eigen::Vector3d& position_out,
		Eigen::Vector3d& orientation_out, Eigen::Vector3d& normal) const
{
	double min_dist = position_in(2) - (-0.227936);

	// ground
	position_out = Eigen::Vector3d(position_in(0), position_in(1), -0.227936);
	normal = Eigen::Vector3d(0, 0, 1);

	Eigen::Matrix3d orientation_in_mat =
			exponential_map::ExponentialMapToRotation(orientation_in);
	Eigen::Vector3d x_axis = orientation_in_mat.col(0);
	Eigen::Vector3d y_axis = orientation_in_mat.col(1);
	Eigen::Vector3d normal_in = orientation_in_mat.col(2);

	if (position_in(0) < -4.4)
	{

	}
	else if (position_in(0) < -4.0)
	{
		position_out(2) = 1.2;
	}
	else if (position_in(0) < -3.0)
	{
		position_out(2) = 0.5;
	}

	getNearestMeshPosition(position_in, position_out, normal_in, normal, min_dist);

	Eigen::Vector3d proj_x_axis = x_axis - x_axis.dot(normal) * normal;
	Eigen::Vector3d proj_y_axis = y_axis - y_axis.dot(normal) * normal;
	if (proj_x_axis.norm() > proj_y_axis.norm())
	{
		proj_x_axis.normalize();
		proj_y_axis = normal.cross(proj_x_axis);
	}
	else
	{
		proj_y_axis.normalize();
		proj_x_axis = proj_y_axis.cross(normal);
	}
	Eigen::Matrix3d orientation_out_mat;
	orientation_out_mat.col(0) = proj_x_axis;
	orientation_out_mat.col(1) = proj_y_axis;
	orientation_out_mat.col(2) = normal;
	orientation_out = exponential_map::RotationToExponentialMap(
			orientation_out_mat);
}

bool GroundManager::getNearestMeshPosition(const Eigen::Vector3d& position_in,
		Eigen::Vector3d& position_out, const Eigen::Vector3d& normal_in, Eigen::Vector3d& normal,
		double current_min_distance) const
{
	bool updated = false;

	for (int i = 0; i < triangles_.size(); ++i)
	{
		const Triangle& triangle = triangles_[i];

		if (triangle.normal_.dot(normal_in) < 0.5)
			continue;

		Eigen::Vector3d projection = ProjPoint2Triangle(triangle.points_[0], triangle.points_[1],
				triangle.points_[2], position_in);
		double distance = (position_in - projection).norm();
		if (distance < current_min_distance)
		{
			current_min_distance = distance;
			normal = triangle.normal_;
			position_out = projection;

			updated = true;
		}
	}

	return updated;
}

void GroundManager::initializeStaticScene()
{
	triangles_.clear();

	const collision_detection::WorldConstPtr& world =
			planning_scene_->getWorld();
	std::vector<std::string> object_ids = world->getObjectIds();
	for (int i = 0; i < object_ids.size(); ++i)
	{
		collision_detection::World::ObjectConstPtr obj = world->getObject(
				object_ids[i]);
		for (int j = 0; j < obj->shapes_.size(); ++j)
		{
			shapes::ShapeConstPtr shape = obj->shapes_[j];
			const shapes::Mesh* mesh =
					dynamic_cast<const shapes::Mesh*>(shape.get());
			if (mesh == NULL)
				continue;

			Eigen::Affine3d& transform = obj->shape_poses_[j];
			for (int k = 0; k < mesh->triangle_count; ++k)
			{
				int triangle_vertex1 = mesh->triangles[3 * k];
				int triangle_vertex2 = mesh->triangles[3 * k + 1];
				int triangle_vertex3 = mesh->triangles[3 * k + 2];
				Eigen::Vector3d position1(mesh->vertices[3 * triangle_vertex1],
						mesh->vertices[3 * triangle_vertex1 + 1],
						mesh->vertices[3 * triangle_vertex1 + 2]);
				Eigen::Vector3d position2(mesh->vertices[3 * triangle_vertex2],
						mesh->vertices[3 * triangle_vertex2 + 1],
						mesh->vertices[3 * triangle_vertex2 + 2]);
				Eigen::Vector3d position3(mesh->vertices[3 * triangle_vertex3],
						mesh->vertices[3 * triangle_vertex3 + 1],
						mesh->vertices[3 * triangle_vertex3 + 2]);
				position1 = transform * position1;
				position2 = transform * position2;
				position3 = transform * position3;

				Eigen::Vector3d p0 = (position2 - position1);
				Eigen::Vector3d p1 = (position3 - position1);
				p0.normalize();
				p1.normalize();
				Eigen::Vector3d normal = p0.cross(p1);
				if (normal.norm() < 1e-7)
					continue;
				normal.normalize();

				Triangle tri;
				tri.points_[0] = position1;
				tri.points_[1] = position2;
				tri.points_[2] = position3;
				tri.normal_ = normal;
				triangles_.push_back(tri);
			}
		}
	}
}

}

<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/policy/configuration_policy_store_interface.h"

namespace {

using namespace policy;

bool IsProxyPolicy(ConfigurationPolicyType policy) {
  return policy == kPolicyProxyMode ||
         policy == kPolicyProxyServerMode ||
         policy == kPolicyProxyServer ||
         policy == kPolicyProxyPacUrl ||
         policy == kPolicyProxyBypassList;
}

} // namespace

namespace policy {

void ObservingPolicyStoreInterface::Apply(ConfigurationPolicyType policy,
                                          Value* value) {
  next_->Apply(policy, value);

  if (IsProxyPolicy(policy))
      proxy_policy_applied_ = true;
}

void FilteringPolicyStoreInterface::Apply(ConfigurationPolicyType policy,
                                          Value* value) {
  // Apply() takes ownership of |value|.
  if (IsProxyPolicy(policy) && apply_proxy_policies_)
    next_->Apply(policy, value);
  else
    delete value;
}

} // namespace policy
<commit_msg>Fix missing include.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/values.h"
#include "chrome/browser/policy/configuration_policy_store_interface.h"

namespace {

using namespace policy;

bool IsProxyPolicy(ConfigurationPolicyType policy) {
  return policy == kPolicyProxyMode ||
         policy == kPolicyProxyServerMode ||
         policy == kPolicyProxyServer ||
         policy == kPolicyProxyPacUrl ||
         policy == kPolicyProxyBypassList;
}

} // namespace

namespace policy {

void ObservingPolicyStoreInterface::Apply(ConfigurationPolicyType policy,
                                          Value* value) {
  next_->Apply(policy, value);

  if (IsProxyPolicy(policy))
      proxy_policy_applied_ = true;
}

void FilteringPolicyStoreInterface::Apply(ConfigurationPolicyType policy,
                                          Value* value) {
  // Apply() takes ownership of |value|.
  if (IsProxyPolicy(policy) && apply_proxy_policies_)
    next_->Apply(policy, value);
  else
    delete value;
}

} // namespace policy
<|endoftext|>


<commit_before><commit_msg>Canbus: refactor the response_check logic for the lexus controller<commit_after><|endoftext|>


<commit_before>#include <complex>
#include <vector>
#include <math.h>

class MFCC {
private:
  const double PI = 4 * atan(1.0);

private:
  inline double hz2mel(double f) {
    return 2595 * std::log10(1 + f/700);
  }

  inline double mel2hz(double m) {
    return 700 * (std::pow(10, m/2595) - 1);
  }

public:
  // constructor
  MFCC() {

  }

  // main process
  // TODO: should be return some value
  void process() {

  }
}
<commit_msg>fft かいた<commit_after>#include <complex>
#include <vector>
#include <map>
#include <math.h>

class MFCC {
private:
  const double PI = 4 * atan(1.0);
  std::vector<std::complex<double>> Xjo, Xjo2;
  std::map<int, std::map<int, std::complex<double>>> bitTable_;
  size_t numFFT;

private:
  inline double hz2mel(double f) {
    return 2595 * std::log10(1 + f/700);
  }

  inline double mel2hz(double m) {
    return 700 * (std::pow(10, m/2595) - 1);
  }

// constructor から呼び出されるものたち
private:
  // fft で使う
  void bitTable(void) {
    const std::complex<double> j(0, 1); // 0 + j
    for(int n = 2; n <= numFFT; n *= 2) {
      for(int k = 0; k <= N/2 - 1; k+=1) {
        bitTable_[N][k] = exp(-2 * PI * k / n * j);
      }
    }
  }

private:
  // preemphasis filter をかける
  // hamming window をかける
  // fft
  // 振幅スペクトルを求める
  // log mel filter bank をかける
  // 離散コサイン変換 (dct2)
  void preEmphasisAndHamming(void) {
    std::vector<double> f(frame.size());
    f[0] = frame[0] * 0.08;
    for(int i = 1; i < frame.size(); i+=1) {
      // TODO: preEmphasis Coef
      f[i] = frame[i] - ( 0.97 * frame[i - 1]);
      // TODO: N
      f[i] = f[i] * (0.54 - 0.46 * cos( 2.0 * PI * i / (N - 1)));
    }
    frame = f;
  }

  std::vector<std::complex<double>> fft(std::vector<std::complex<double>> x) {
    int N = x.size();
    if(N==1) return x;

    std::vector<std::complex<double>> xe(N/2, 0), xo(N/2, 0);
    for(int i = 0; i < N; i += 2)
      xe[i/2] = x[i];
    for(int i = 1; i < N; i += 2)
      xo[(i-1)/2] = x[i];

    Xjo = fft(xe);
    Xjo2 = fft(xo);
    Xjo.insert(Xjo.end(), Xjo2.begin(), Xjo2.end());

    for(int i = 0; i <= N/2 - 1; i+=1) {
      std::complex<double> t = Xjo[i], tw = bitTable_[N][i];
      Xjo[i] = t + tw * Xjo[i+N/2];
      Xjo[i+N/2] = t - tw * Xjo[i+N/2];
    }

    return Xjo;
  }

  void powerSpectrum(void) {
    // std::vector<std::complex<double>> data
    // for(int i = 0; i < ; i+=1)
    // pow(abs(data[i]),2)
  }

  void logMelFilterbank(void) {
    // いろいろ
  }

  /*
   * DCT: Discrete Cosine Transform
   *
   *            N-1
   *  y[k] = 2* sum x[n]*cos(pi*k*(2n+1)/(2*N)), 0 <= k < N.
   *            n=0
   */
  void dct(void) {

  }

public:
  // constructor
  MFCC() {

    numFFT = 2048;
    bitTable();
  }

  // main process
  // TODO: should be return some value
  void process() {
    // frame = wav.getChannelData(0);
    preEmphasisAndHamming();
    fft();
    // power spectrum ( or amplitude spectrum )
    // apply log mel filter bank
    // dct
  }
}
<|endoftext|>