<commit_before>/*
-------------------------------------------------------------------------
   This file is part of BayesOpt, an efficient C++ library for
   Bayesian optimization.

   Copyright (C) 2011-2013 Ruben Martinez-Cantin <rmcantin@unizar.es>

   BayesOpt is free software: you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   BayesOpt is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
*/

#include <valarray>
#include "bayesoptcont.hpp"

class ExampleOneD: public bayesopt::ContinuousModel
{
public:
  ExampleOneD(size_t dim, bopt_params par):
    ContinuousModel(dim,par) {}

  double evaluateSample(const vectord& xin)
  {
    if (xin.size() > 1)
      {
	std::cout << "WARNING: This only works for 1D inputs." << std::endl
		  << "WARNING: Using only first component." << std::endl;
      }

    double x = xin(0);
    return sqr(x-0.3) + sin(20*x)*0.2;
  };

  bool checkReachability(const vectord &query)
  {return true;};

  inline double sqr( double x ){ return x*x; }

  void printOptimal()
  {
    std::cout << "Optimal:" << 0.5 << std::endl;
  }

};

//#include "unistd.h"
using namespace std;
#include "matplotpp.h"

using namespace bayesopt;

int is_run=1;
size_t state_ii = 0;
BayesOptBase* GLOBAL_MODEL;
vector<double> lx,ly;

class MP :public MatPlot{
void DISPLAY(){
  size_t nruns = GLOBAL_MODEL->getParameters()->n_iterations;
    if ((is_run) && (state_ii < nruns))
    {
      ++state_ii;
      GLOBAL_MODEL->stepOptimization(state_ii);
      vectord last(1);
      double res = GLOBAL_MODEL->getSurrogateModel()->getLastSample(last);
      ly.push_back(res);
      lx.push_back(last(0));
    }

    int n=1000;
    vector<double> x,y,z,su,sl,c;
    x=linspace(0,1,n);
    y = x; z = x; su = x; sl = x; c= x;
    vectord q(1);
    for(int i=0;i<n;++i)
      {
	q(0) = x[i];
	ProbabilityDistribution* pd = GLOBAL_MODEL->getSurrogateModel()->prediction(q);
	y[i] = pd->getMean();
	su[i] = y[i] + 2*pd->getStd();
	sl[i] = y[i] - 2*pd->getStd();
	c[i] = -GLOBAL_MODEL->evaluateCriteria(q);
	z[i] = GLOBAL_MODEL->evaluateSample(q);
      }
    //plot
    subplot(2,1,1);
    title("press r to run and stop");
    plot(x,y); set(3);
    plot(lx,ly);set("k");set("*");
    plot(x,su);set("g"); set(2);
    plot(x,sl);set("g"); set(2);
    plot(x,z);set("r"); set(3);

    subplot(2,1,2);
    plot(x,c); set(3);
}
}mp;

void display(){mp.display(); }
void reshape(int w,int h){ mp.reshape(w,h); }
void idle( void )
{
  glutPostRedisplay();
}

void mouse(int button, int state, int x, int y ){ mp.mouse(button,state,x,y); }
void motion(int x, int y ){mp.motion(x,y); }
void passive(int x, int y ){mp.passivemotion(x,y); }
void keyboard(unsigned char key, int x, int y){
    mp.keyboard(key, x, y);
    if(key=='r'){ if(is_run==0){is_run=1;}else{is_run=0;}}
}

int main(int nargs, char *args[])
{
  size_t dim = 1;
  bopt_params parameters = initialize_parameters_to_default();
  parameters.n_init_samples = 10;
  parameters.n_iter_relearn = 0;
  parameters.n_iterations = 300;
  parameters.verbose_level = 2;

  // Surrogate models
  //  parameters.surr_name = "sStudentTProcessNIG";
  parameters.surr_name = "sGaussianProcessNormal";

  // Criterion model
  parameters.crit_name = "cAopt";
  parameters.n_crit_params = 0;

  parameters.crit_name = "cEI";
  parameters.crit_params[0] = 1;
  parameters.n_crit_params = 1;

  // parameters.crit_name = "cLCB";
  // parameters.crit_params[0] = 5;
  // parameters.n_crit_params = 1;

  // Kernel models
  // parameters.kernel.name = "kSum(kPoly3,kRQISO)";
  // double mean[128] = {1, 1, 1, 1};
  // double std[128] = {10, 10, 10, 10};
  // size_t nhp = 4;
  // memcpy(parameters.kernel.hp_mean, mean, nhp * sizeof(double));
  // memcpy(parameters.kernel.hp_std,std, nhp * sizeof(double));
  // parameters.kernel.n_hp = nhp;

  parameters.kernel.name = "kMaternISO3";
  parameters.kernel.hp_mean[0] = 1;
  parameters.kernel.hp_std[0] = 5;
  parameters.kernel.n_hp = 1;

  state_ii = 0;

  ExampleOneD* opt = new ExampleOneD(dim,parameters);
  vectord result(dim);
  GLOBAL_MODEL = opt;
  opt->initializeOptimization();
  vectord last(1);
  size_t n_points = GLOBAL_MODEL->getSurrogateModel()->getNSamples();
  for (size_t i = 0; i<n_points;++i)
    {
      double res = GLOBAL_MODEL->getSurrogateModel()->getSample(i,last);
      ly.push_back(res);
      lx.push_back(last(0));
    }

  glutInit(&nargs, args);
  glutCreateWindow(100,100,900,700);
  glutDisplayFunc( display );
  glutReshapeFunc( reshape );
  glutIdleFunc( idle );
  glutMotionFunc( motion );
  glutMouseFunc( mouse );
  glutPassiveMotionFunc(passive);
  glutKeyboardFunc( keyboard );
  glutMainLoop();

  delete opt;
  return 0;
}
<commit_msg>Some tweaks in bo_display.cpp<commit_after>/*
-------------------------------------------------------------------------
   This file is part of BayesOpt, an efficient C++ library for
   Bayesian optimization.

   Copyright (C) 2011-2013 Ruben Martinez-Cantin <rmcantin@unizar.es>

   BayesOpt is free software: you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   BayesOpt is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
*/

#include <valarray>
#include "bayesoptcont.hpp"

class ExampleOneD: public bayesopt::ContinuousModel
{
public:
  ExampleOneD(size_t dim, bopt_params par):
    ContinuousModel(dim,par) {}

  double evaluateSample(const vectord& xin)
  {
    if (xin.size() > 1)
      {
	std::cout << "WARNING: This only works for 1D inputs." << std::endl
		  << "WARNING: Using only first component." << std::endl;
      }

    double x = xin(0);
    return sqr(x-0.3) + sin(20*x)*0.2;
  };

  bool checkReachability(const vectord &query)
  {return true;};

  inline double sqr( double x ){ return x*x; }

  void printOptimal()
  {
    std::cout << "Optimal:" << 0.5 << std::endl;
  }

};

//#include "unistd.h"
using namespace std;
#include "matplotpp.h"

using namespace bayesopt;

int is_run=1;
int is_step=0;
size_t state_ii = 0;
BayesOptBase* GLOBAL_MODEL;
vector<double> lx,ly;

class MP :public MatPlot{
void DISPLAY(){
  size_t nruns = GLOBAL_MODEL->getParameters()->n_iterations;
    if ((is_run) && (state_ii < nruns))
    {
      ++state_ii;
      GLOBAL_MODEL->stepOptimization(state_ii);
      vectord last(1);
      double res = GLOBAL_MODEL->getSurrogateModel()->getLastSample(last);
      ly.push_back(res);
      lx.push_back(last(0));

	  if (is_step) { is_run = 0; is_step = 0; }
    }

    int n=1000;
    vector<double> x,y,z,su,sl,c;
    x=linspace(0,1,n);
    y = x; z = x; su = x; sl = x; c= x;
    vectord q(1);
    for(int i=0;i<n;++i)
      {
	q(0) = x[i];
	ProbabilityDistribution* pd = GLOBAL_MODEL->getSurrogateModel()->prediction(q);
	y[i] = pd->getMean();
	su[i] = y[i] + 2*pd->getStd();
	sl[i] = y[i] - 2*pd->getStd();
	c[i] = -GLOBAL_MODEL->evaluateCriteria(q);
	z[i] = GLOBAL_MODEL->evaluateSample(q);
      }
    //plot
    subplot(2,1,1);
    title("press r to run and stop");
    plot(x,y); set(3);
    plot(lx,ly);set("k");set("*");
    plot(x,su);set("g"); set(2);
    plot(x,sl);set("g"); set(2);
    plot(x,z);set("r"); set(3);

    subplot(2,1,2);
    plot(x,c); set(3);
}
}mp;

void display(){mp.display(); }
void reshape(int w,int h){ mp.reshape(w,h); }
void idle( void )
{
  glutPostRedisplay();
}

void mouse(int button, int state, int x, int y ){ mp.mouse(button,state,x,y); }
void motion(int x, int y ){mp.motion(x,y); }
void passive(int x, int y ){mp.passivemotion(x,y); }
void keyboard(unsigned char key, int x, int y){
    mp.keyboard(key, x, y);
    if(key=='r'){ if(is_run==0){is_run=1;}else{is_run=0;}}
	if(key=='s'){ is_run=1; is_step=1; }
}

int main(int nargs, char *args[])
{
  size_t dim = 1;
  bopt_params parameters = initialize_parameters_to_default();
  parameters.n_init_samples = 7;
  parameters.n_iter_relearn = 0;
  parameters.n_iterations = 300;
  parameters.verbose_level = 2;

  // Surrogate models
  //  parameters.surr_name = "sStudentTProcessNIG";
  parameters.surr_name = "sGaussianProcessNormal";

  // Criterion model
  // parameters.crit_name = "cAopt";
  // parameters.n_crit_params = 0;

  parameters.crit_name = "cEI";
  parameters.crit_params[0] = 1;
  parameters.n_crit_params = 1;

  // parameters.crit_name = "cLCB";
  // parameters.crit_params[0] = 5;
  // parameters.n_crit_params = 1;

  // Kernel models
  // parameters.kernel.name = "kSum(kPoly3,kRQISO)";
  // double mean[128] = {1, 1, 1, 1};
  // double std[128] = {10, 10, 10, 10};
  // size_t nhp = 4;
  // memcpy(parameters.kernel.hp_mean, mean, nhp * sizeof(double));
  // memcpy(parameters.kernel.hp_std,std, nhp * sizeof(double));
  // parameters.kernel.n_hp = nhp;

  parameters.kernel.name = "kMaternISO3";
  parameters.kernel.hp_mean[0] = 1;
  parameters.kernel.hp_std[0] = 5;
  parameters.kernel.n_hp = 1;

  state_ii = 0;

  ExampleOneD* opt = new ExampleOneD(dim,parameters);
  vectord result(dim);
  GLOBAL_MODEL = opt;
  opt->initializeOptimization();
  vectord last(1);
  size_t n_points = GLOBAL_MODEL->getSurrogateModel()->getNSamples();
  for (size_t i = 0; i<n_points;++i)
    {
      double res = GLOBAL_MODEL->getSurrogateModel()->getSample(i,last);
      ly.push_back(res);
      lx.push_back(last(0));
    }

  glutInit(&nargs, args);
  glutCreateWindow(100,100,900,700);
  glutDisplayFunc( display );
  glutReshapeFunc( reshape );
  glutIdleFunc( idle );
  glutMotionFunc( motion );
  glutMouseFunc( mouse );
  glutPassiveMotionFunc(passive);
  glutKeyboardFunc( keyboard );
  glutMainLoop();

  delete opt;
  return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <votca/csg/topologyreader.h>
#include <votca/csg/trajectoryreader.h>
#include <boost/program_options.hpp>
#include <boost/tokenizer.hpp>
#include <votca/csg/version.h>
#include <iostream>
#include <fstream>

using namespace std;
namespace po = boost::program_options;
using namespace votca::csg;
using namespace votca::tools;

/**
 *  *** Analyze particle distribution as a function of a coordinate ***
 *
 *  This program reads a topology and (set of) trajectory(ies). For every
 *  binned value of a chose coordinate, it outputs the time-averaged number of
 *  particles, listed by particle types.
 */
void help_text(void)
{
    votca::csg::HelpTextHeader("csg_part_dist");
    cout << "This program reads a topology and (set of) trajectory(ies). For every\n"
	"binned value of a chosen coordinate, it outputs the time-averaged number of\n"
	"particles, listed by particle types.\n\n";
}

void check_option(po::options_description &desc, po::variables_map &vm, const string &option)
{
    if(!vm.count(option)) {
        cout << "csg_part_dist \n\n";
        cout << desc << endl << "parameter " << option << " is not specified\n";
        exit(1);
    }
}

int main(int argc, char** argv)
{
    string top_file, trj_file, ptypes_file, out_file, grid,
	comment, string_tmp, coordinate="z";
    double min, max, step, coord, com(0.);
    vector<int> ptypes;
    ifstream fl_ptypes;
    ofstream fl_out;
    Topology top;
    TopologyReader *reader;
    TrajectoryReader *trajreader;
    int part_type, n_bins, first_frame(0), last_frame(-1),
	flag_found(0), **p_occ = NULL, n_part(0), frame_id(0),
	analyzed_frames(0);
    bool moreframes(1), not_the_last(1);

    MoleculeContainer::iterator mol;
    // Load topology+trajectory formats
    TopologyReader::RegisterPlugins();
    TrajectoryReader::RegisterPlugins();

    // read program options
    namespace po = boost::program_options;

    // Declare the supported options.
    po::options_description desc("Allowed options");

    // let cg_engine add some program options
    desc.add_options()
	("top", po::value<string>(&top_file), "topology file")
	("trj", po::value<string>(&trj_file), "trajectory file")
	("grid", po::value<string>(&grid), "output grid spacing (min:step:max)")
	("out", po::value<string>(&out_file),
	 "output particle distribution table")
	("ptypes", po::value<string>(&ptypes_file),
	 "particle types to include in the analysis\n"
	 " arg: file - particle types separated by space"
	 "\n default: all particle types")
	("first_frame", po::value<int>(&first_frame), "first frame considered for analysis")
	("last_frame", po::value<int>(&last_frame), "last frame considered for analysis")
	("coord", po::value<string>(&coordinate), "coordinate analyzed ('x', 'y', or 'z' (default))")
	("shift_com", "shift center of mass to zero")
	("comment", po::value<string>(&comment), "store a comment in the output table")
	("help", "produce this help message");

    // now read in the command line
    po::variables_map vm;
    try {
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);
    }
    catch(po::error& err) {
	cout << "error parsing command line: " << err.what() << endl;
	return -1;
    }

    // does the user want help?
    if (vm.count("help")) {
        help_text();
        cout << desc << endl;
        return 0;
    }

    check_option(desc, vm, "top");
    check_option(desc, vm, "trj");
    check_option(desc, vm, "out");
    check_option(desc, vm, "grid");

    if (coordinate.compare("x") != 0 && coordinate.compare("y") != 0 && coordinate.compare("z") != 0) {
	cout << "Bad format for coordinate: " << coordinate << endl;
	return 1;
    }

    // Parse grid
    Tokenizer tok(grid, ":");
    vector<string> toks;
    tok.ToVector(toks);
    if(toks.size()!=3) {
	cout << "Wrong range format, use min:step:max\n";
	return 1;
    }
    min = boost::lexical_cast<double>(toks[0]);
    step = boost::lexical_cast<double>(toks[1]);
    max = boost::lexical_cast<double>(toks[2]);
    // Calculate number of bins
    n_bins = (int)((max-min)/(1.*step)+1);

    try {
	// Load topology
        reader = TopReaderFactory().Create(vm["top"].as<string>());
        if(reader == NULL)
            throw std::runtime_error("input format not supported: " + vm["top"].as<string>());

        reader->ReadTopology(vm["top"].as<string>(), top);

	// Read the particle types file and save to variable ptypes
	if(vm.count("ptypes")) {
	    fl_ptypes.open(vm["ptypes"].as<string>().c_str());
	    if(!fl_ptypes.is_open())
		throw std::runtime_error("can't open " + vm["ptypes"].as<string>());
	    // build the list of particle types
	    if(fl_ptypes.eof())
		throw std::runtime_error("file " + vm["ptypes"].as<string>() + " is empty");
	    while (!fl_ptypes.eof()) {
		// Not very elegant, but makes sure we don't count the same element twice
		string_tmp = "__";
		fl_ptypes >> string_tmp;
		if (string_tmp != "" && string_tmp != "__") {
		    ptypes.push_back(atoi(string_tmp.c_str()));
		}
	    }
	    fl_ptypes.close();

	}
	else {
	    // Include all particle types
	    for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) {
		for(int i=0; i<(*mol)->BeadCount(); ++i) {
		    flag_found = 0;
        weak_ptr<BeadType> weak_type = (*mol)->getBead(i)->getType();
        if(shared_ptr<BeadType> shared_type = weak_type.lock()){
          part_type = atoi(shared_type->getName().c_str());
        }else{
          throw runtime_error("Cannot get bead type in part_dist as it is no "
              "longer accessible.");
        }
		    for (size_t j=0; j < ptypes.size(); ++j) {
			if (part_type == ptypes[j])
			    flag_found = 1;
		    }
		    if (!flag_found)
			ptypes.push_back(part_type);
		}
	    }
	}

	// Allocate array used to store particle occupancy p_occ
	p_occ = (int**) calloc(ptypes.size(),sizeof(int*));
	for (size_t i=0; i < ptypes.size(); ++i)
	    p_occ[i] = (int*) calloc(n_bins,sizeof(int));

	// If we need to shift the center of mass, calculate the number of
	// particles (only the ones that belong to the particle type index
	// ptypes)
	if (vm.count("shift_com")) {
	    for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) {
		for(int i=0; i<(*mol)->BeadCount(); ++i) {
        weak_ptr<BeadType> weak_type = (*mol)->getBead(i)->getType();
        if(shared_ptr<BeadType> shared_type = weak_type.lock()){
          part_type = atoi(shared_type->getName().c_str());
        }else{
          throw runtime_error("Cannot get bead type in part_dist as it is no "
              "longer accessible.");
        }
		    for (size_t j=0; j < ptypes.size(); ++j)
			if (part_type == ptypes[j])
			    ++n_part;
		}
	    }
	}

	// Now load trajectory
	trajreader = TrjReaderFactory().Create(vm["trj"].as<string>());
	if(trajreader == NULL)
            throw std::runtime_error("input format not supported: " + vm["trj"].as<string>());
	trajreader->Open(vm["trj"].as<string>());

	// Read the trajectory. Analyze each frame to obtain
	// particle occupancy as a function of coordinate z.
	while (moreframes) {
	    // Read frame
	    if (frame_id == 0)
		moreframes = trajreader->FirstFrame(top);
	    else
		moreframes = trajreader->NextFrame(top);

	    // Was this the last frame we read?
	    if (last_frame == -1)
		not_the_last = 1;
	    else {
		if (frame_id <= last_frame)
		    not_the_last = 1;
		else
		    not_the_last = 0;
	    }

	    // Calculate new center of mass position in the direction of 'coordinate'
	    com = 0.;
	    if (vm.count("shift_com")) {
        for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) {
          for(int i=0; i<(*mol)->BeadCount(); ++i) {
            weak_ptr<BeadType> weak_type = (*mol)->getBead(i)->getType();
            if(shared_ptr<BeadType> shared_type = weak_type.lock()){
              part_type = atoi(shared_type->getName().c_str());
            }else{
              throw runtime_error("Cannot get bead type in part_dist as it is no "
                  "longer accessible.");
            }
            for (size_t j=0; j < ptypes.size(); ++j) {
              if (part_type == ptypes[j]) {
                if (coordinate.compare("x") == 0) {
                  com += (*mol)->getBead(i)->getPos().getX();
                }
                else if (coordinate.compare("y") == 0) {
                  com += (*mol)->getBead(i)->getPos().getY();
                }
                else {
                  com += (*mol)->getBead(i)->getPos().getZ();
                }
              }
            }
          }
        }
        com /= n_part;
	    }

	    // Analyze frame
	    if (moreframes && frame_id >= first_frame && not_the_last) {
		++analyzed_frames;
		// Loop over each atom property
    for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) {
      for(int i=0; i<(*mol)->BeadCount(); ++i) {
        weak_ptr<BeadType> weak_type = (*mol)->getBead(i)->getType();
        if(shared_ptr<BeadType> shared_type = weak_type.lock()){
          part_type = atoi(shared_type->getName().c_str());
        }else{
          throw runtime_error("Cannot get bead type in part_dist as it is no "
              "longer accessible.");
        }

        for (size_t j=0; j < ptypes.size(); ++j) {
          if (part_type == ptypes[j]) {
            if (coordinate.compare("x") == 0)
              coord = (*mol)->getBead(i)->getPos().getX();
            else if (coordinate.compare("y") == 0)
              coord = (*mol)->getBead(i)->getPos().getY();
            else
              coord = (*mol)->getBead(i)->getPos().getZ();

            if (coord-com > min && coord-com < max)
              ++p_occ[j][(int)floor((coord-com-min)/step)];
          }
        }
      }
    }
      }
      ++frame_id;
  }

	trajreader->Close();

    }
    catch(std::exception &error) {
	cerr << "An error occured!" << endl << error.what() << endl;
    }

    // Output particle occupancy
    try {
	fl_out.open(vm["out"].as<string>().c_str());
	if(!fl_out.is_open())
	    throw std::runtime_error("can't open " + vm["out"].as<string>());

	fl_out << "#z\t" << flush;
	for (size_t i=0; i < ptypes.size(); ++i)
	    fl_out << "type " << ptypes[i] << "\t" << flush;
	fl_out << endl;
	for (int k=0; k < n_bins; ++k) {
	    fl_out << min+k*step << "\t" << flush;
	    for (size_t j=0; j < ptypes.size(); ++j) {
		if (p_occ[j][k] == 0)
		    fl_out << 0 << "\t" << flush;
		else
		    fl_out << p_occ[j][k]/(1.*analyzed_frames) << "\t" << flush;
	    }
	    fl_out << endl;
	}
	fl_out.close();
    }
    catch(std::exception &error) {
	cerr << "An error occured!" << endl << error.what() << endl;
    }

    for (size_t i=0; i < ptypes.size(); ++i)
	free(p_occ[i]);
    free(p_occ);

    cout << "The table was written to " << vm["out"].as<string>() << endl;

    return 0;
}

<commit_msg>replaced getting weak pointer with call to getBeadTypeName()<commit_after>/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <votca/csg/topologyreader.h>
#include <votca/csg/trajectoryreader.h>
#include <boost/program_options.hpp>
#include <boost/tokenizer.hpp>
#include <votca/csg/version.h>
#include <iostream>
#include <fstream>

using namespace std;
namespace po = boost::program_options;
using namespace votca::csg;
using namespace votca::tools;

/**
 *  *** Analyze particle distribution as a function of a coordinate ***
 *
 *  This program reads a topology and (set of) trajectory(ies). For every
 *  binned value of a chose coordinate, it outputs the time-averaged number of
 *  particles, listed by particle types.
 */
void help_text(void)
{
    votca::csg::HelpTextHeader("csg_part_dist");
    cout << "This program reads a topology and (set of) trajectory(ies). For every\n"
	"binned value of a chosen coordinate, it outputs the time-averaged number of\n"
	"particles, listed by particle types.\n\n";
}

void check_option(po::options_description &desc, po::variables_map &vm, const string &option)
{
    if(!vm.count(option)) {
        cout << "csg_part_dist \n\n";
        cout << desc << endl << "parameter " << option << " is not specified\n";
        exit(1);
    }
}

int main(int argc, char** argv)
{
    string top_file, trj_file, ptypes_file, out_file, grid,
	comment, string_tmp, coordinate="z";
    double min, max, step, coord, com(0.);
    vector<int> ptypes;
    ifstream fl_ptypes;
    ofstream fl_out;
    Topology top;
    TopologyReader *reader;
    TrajectoryReader *trajreader;
    int part_type, n_bins, first_frame(0), last_frame(-1),
	flag_found(0), **p_occ = NULL, n_part(0), frame_id(0),
	analyzed_frames(0);
    bool moreframes(1), not_the_last(1);

    MoleculeContainer::iterator mol;
    // Load topology+trajectory formats
    TopologyReader::RegisterPlugins();
    TrajectoryReader::RegisterPlugins();

    // read program options
    namespace po = boost::program_options;

    // Declare the supported options.
    po::options_description desc("Allowed options");

    // let cg_engine add some program options
    desc.add_options()
	("top", po::value<string>(&top_file), "topology file")
	("trj", po::value<string>(&trj_file), "trajectory file")
	("grid", po::value<string>(&grid), "output grid spacing (min:step:max)")
	("out", po::value<string>(&out_file),
	 "output particle distribution table")
	("ptypes", po::value<string>(&ptypes_file),
	 "particle types to include in the analysis\n"
	 " arg: file - particle types separated by space"
	 "\n default: all particle types")
	("first_frame", po::value<int>(&first_frame), "first frame considered for analysis")
	("last_frame", po::value<int>(&last_frame), "last frame considered for analysis")
	("coord", po::value<string>(&coordinate), "coordinate analyzed ('x', 'y', or 'z' (default))")
	("shift_com", "shift center of mass to zero")
	("comment", po::value<string>(&comment), "store a comment in the output table")
	("help", "produce this help message");

    // now read in the command line
    po::variables_map vm;
    try {
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);
    }
    catch(po::error& err) {
	cout << "error parsing command line: " << err.what() << endl;
	return -1;
    }

    // does the user want help?
    if (vm.count("help")) {
        help_text();
        cout << desc << endl;
        return 0;
    }

    check_option(desc, vm, "top");
    check_option(desc, vm, "trj");
    check_option(desc, vm, "out");
    check_option(desc, vm, "grid");

    if (coordinate.compare("x") != 0 && coordinate.compare("y") != 0 && coordinate.compare("z") != 0) {
	cout << "Bad format for coordinate: " << coordinate << endl;
	return 1;
    }

    // Parse grid
    Tokenizer tok(grid, ":");
    vector<string> toks;
    tok.ToVector(toks);
    if(toks.size()!=3) {
	cout << "Wrong range format, use min:step:max\n";
	return 1;
    }
    min = boost::lexical_cast<double>(toks[0]);
    step = boost::lexical_cast<double>(toks[1]);
    max = boost::lexical_cast<double>(toks[2]);
    // Calculate number of bins
    n_bins = (int)((max-min)/(1.*step)+1);

    try {
	// Load topology
        reader = TopReaderFactory().Create(vm["top"].as<string>());
        if(reader == NULL)
            throw std::runtime_error("input format not supported: " + vm["top"].as<string>());

        reader->ReadTopology(vm["top"].as<string>(), top);

	// Read the particle types file and save to variable ptypes
	if(vm.count("ptypes")) {
	    fl_ptypes.open(vm["ptypes"].as<string>().c_str());
	    if(!fl_ptypes.is_open())
		throw std::runtime_error("can't open " + vm["ptypes"].as<string>());
	    // build the list of particle types
	    if(fl_ptypes.eof())
		throw std::runtime_error("file " + vm["ptypes"].as<string>() + " is empty");
	    while (!fl_ptypes.eof()) {
		// Not very elegant, but makes sure we don't count the same element twice
		string_tmp = "__";
		fl_ptypes >> string_tmp;
		if (string_tmp != "" && string_tmp != "__") {
		    ptypes.push_back(atoi(string_tmp.c_str()));
		}
	    }
	    fl_ptypes.close();

	}
	else {
	    // Include all particle types
    for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) {
      for(int i=0; i<(*mol)->BeadCount(); ++i) {
        flag_found = 0;
        part_type = atoi((*mol)->getBead(i)->getBeadTypeName().c_str());
        for (size_t j=0; j < ptypes.size(); ++j) {
          if (part_type == ptypes[j])
            flag_found = 1;
        }
        if (!flag_found)
          ptypes.push_back(part_type);
      }
    }
	}

	// Allocate array used to store particle occupancy p_occ
	p_occ = (int**) calloc(ptypes.size(),sizeof(int*));
	for (size_t i=0; i < ptypes.size(); ++i)
	    p_occ[i] = (int*) calloc(n_bins,sizeof(int));

	// If we need to shift the center of mass, calculate the number of
	// particles (only the ones that belong to the particle type index
	// ptypes)
  if (vm.count("shift_com")) {
    for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) {
      for(int i=0; i<(*mol)->BeadCount(); ++i) {
        part_type = atoi((*mol)->getBead(i)->getBeadTypeName().c_str());
        for (size_t j=0; j < ptypes.size(); ++j)
          if (part_type == ptypes[j])
            ++n_part;
      }
    }
  }

	// Now load trajectory
	trajreader = TrjReaderFactory().Create(vm["trj"].as<string>());
	if(trajreader == NULL)
            throw std::runtime_error("input format not supported: " + vm["trj"].as<string>());
	trajreader->Open(vm["trj"].as<string>());

	// Read the trajectory. Analyze each frame to obtain
	// particle occupancy as a function of coordinate z.
	while (moreframes) {
	    // Read frame
	    if (frame_id == 0)
		moreframes = trajreader->FirstFrame(top);
	    else
		moreframes = trajreader->NextFrame(top);

	    // Was this the last frame we read?
	    if (last_frame == -1)
		not_the_last = 1;
	    else {
		if (frame_id <= last_frame)
		    not_the_last = 1;
		else
		    not_the_last = 0;
	    }

	    // Calculate new center of mass position in the direction of 'coordinate'
	    com = 0.;
	    if (vm.count("shift_com")) {
        for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) {
          for(int i=0; i<(*mol)->BeadCount(); ++i) {
            part_type = atoi((*mol)->getBead(i)->getBeadTypeName().c_str());
            for (size_t j=0; j < ptypes.size(); ++j) {
              if (part_type == ptypes[j]) {
                if (coordinate.compare("x") == 0) {
                  com += (*mol)->getBead(i)->getPos().getX();
                }
                else if (coordinate.compare("y") == 0) {
                  com += (*mol)->getBead(i)->getPos().getY();
                }
                else {
                  com += (*mol)->getBead(i)->getPos().getZ();
                }
              }
            }
          }
        }
        com /= n_part;
	    }

	    // Analyze frame
	    if (moreframes && frame_id >= first_frame && not_the_last) {
		++analyzed_frames;
		// Loop over each atom property
    for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) {
      for(int i=0; i<(*mol)->BeadCount(); ++i) {
        part_type = atoi((*mol)->getBead(i)->getBeadTypeName().c_str());
        for (size_t j=0; j < ptypes.size(); ++j) {
          if (part_type == ptypes[j]) {
            if (coordinate.compare("x") == 0)
              coord = (*mol)->getBead(i)->getPos().getX();
            else if (coordinate.compare("y") == 0)
              coord = (*mol)->getBead(i)->getPos().getY();
            else
              coord = (*mol)->getBead(i)->getPos().getZ();

            if (coord-com > min && coord-com < max)
              ++p_occ[j][(int)floor((coord-com-min)/step)];
          }
        }
      }
    }
      }
      ++frame_id;
  }

	trajreader->Close();

    }
    catch(std::exception &error) {
	cerr << "An error occured!" << endl << error.what() << endl;
    }

    // Output particle occupancy
    try {
	fl_out.open(vm["out"].as<string>().c_str());
	if(!fl_out.is_open())
	    throw std::runtime_error("can't open " + vm["out"].as<string>());

	fl_out << "#z\t" << flush;
	for (size_t i=0; i < ptypes.size(); ++i)
	    fl_out << "type " << ptypes[i] << "\t" << flush;
	fl_out << endl;
	for (int k=0; k < n_bins; ++k) {
	    fl_out << min+k*step << "\t" << flush;
	    for (size_t j=0; j < ptypes.size(); ++j) {
		if (p_occ[j][k] == 0)
		    fl_out << 0 << "\t" << flush;
		else
		    fl_out << p_occ[j][k]/(1.*analyzed_frames) << "\t" << flush;
	    }
	    fl_out << endl;
	}
	fl_out.close();
    }
    catch(std::exception &error) {
	cerr << "An error occured!" << endl << error.what() << endl;
    }

    for (size_t i=0; i < ptypes.size(); ++i)
	free(p_occ[i]);
    free(p_occ);

    cout << "The table was written to " << vm["out"].as<string>() << endl;

    return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: sddll.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: kz $ $Date: 2001-10-16 16:01:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SDDLL_HXX
#define _SDDLL_HXX

#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif
#ifndef _SFXDEFS_HXX //autogen
#include <sfx2/sfxdefs.hxx>
#endif

class SvFactory;
class SotFactory;
class SfxMedium;
class SfxFilter;

/*************************************************************************
|*
|* This class is a wrapper for a Load-On-Demand-DLL. One instance
|* per SfxApplication will be created for the runtime of
|* SfxApplication-subclass::Main().
|*
|* Remember: Do export this class! It is used by the application.
|*
\************************************************************************/

class SdDLL
{
protected:
    static void     RegisterFactorys();
    static void     RegisterInterfaces();
    static void     RegisterControllers();

public:
                    // Ctor/Dtor must be linked to the application
                    SdDLL();
                    ~SdDLL();

                    // static-init/exit-code must be linked to the application
    static void     LibInit();  // called from SfxApplication-subclass::Init()
    static void     LibExit();  // called from SfxApplication-subclass::Exit()

                    // DLL-init/exit-code must be linked to the DLL only
    static void     Init();     // called directly after loading the DLL
    static void     Exit();     // called directly befor unloading the DLL

    static ULONG    DetectFilter(SfxMedium& rMedium, const SfxFilter** pFilter,
                                 SfxFilterFlags nMust, SfxFilterFlags nDont);
};

/*************************************************************************
|*
|* This tricky class keeps pointers to the SvFactories while
|* the DLL isn`t loaded. A pointer to the one instance is available
|* through SD_MOD() (shared-lib-app-data).
|*
\************************************************************************/

class SdModuleDummy : public SfxModule
{
public:
    TYPEINFO();

                // SvFactory name convention:
                // 'p' + SfxObjectShell-subclass + 'Factory'
    SotFactory* pSdDrawDocShellFactory;
    SotFactory* pSdGraphicDocShellFactory;

               SdModuleDummy(ResMgr* pResMgr, BOOL bDummy,
                             SotFactory* pDrawObjFact, SotFactory* pGraphicObjFact)
               : SfxModule(pResMgr, bDummy,
                            // Der erste Factory-Pointer muss gueltig sein!
                           (SfxObjectFactory*) (pDrawObjFact ? pDrawObjFact    : pGraphicObjFact),
                           (SfxObjectFactory*) (pDrawObjFact ? pGraphicObjFact : pDrawObjFact),
                           0L),
                 pSdDrawDocShellFactory( pDrawObjFact ),
                 pSdGraphicDocShellFactory( pGraphicObjFact )
               {}

    virtual SfxModule*  Load();

    static SvGlobalName GetID(USHORT nFileFormat);
    static USHORT       HasID(const SvGlobalName& rName);
};

#ifndef _SD_DLL                      // Das define muss im Draw gesetzt werden
#define SD_MOD() ( *(SdModuleDummy**) GetAppData(SHL_DRAW) )
#endif

#endif                               // _SDDLL_HXX

<commit_msg>INTEGRATION: CWS fwkq1 (1.2.186); FILE MERGED 2003/07/14 17:52:00 mba 1.2.186.1: #110843#: get rid of factories<commit_after>/*************************************************************************
 *
 *  $RCSfile: sddll.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2003-09-19 08:14:30 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SDDLL_HXX
#define _SDDLL_HXX

#ifndef _SDMOD_HXX
#include "sdmod.hxx"
#endif

#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif
#ifndef _SFXDEFS_HXX //autogen
#include <sfx2/sfxdefs.hxx>
#endif

class SvFactory;
class SotFactory;
class SfxMedium;
class SfxFilter;

/*************************************************************************
|*
|* This class is a wrapper for a Load-On-Demand-DLL. One instance
|* per SfxApplication will be created for the runtime of
|* SfxApplication-subclass::Main().
|*
|* Remember: Do export this class! It is used by the application.
|*
\************************************************************************/

class SdDLL
{
protected:
    static void     RegisterFactorys();
    static void     RegisterInterfaces();
    static void     RegisterControllers();

public:
                    // Ctor/Dtor must be linked to the application
                    SdDLL();
                    ~SdDLL();

                    // static-init/exit-code must be linked to the application
    static void     LibInit();  // called from SfxApplication-subclass::Init()
    static void     LibExit();  // called from SfxApplication-subclass::Exit()

                    // DLL-init/exit-code must be linked to the DLL only
    static void     Init();     // called directly after loading the DLL
    static void     Exit();     // called directly befor unloading the DLL

    static ULONG    DetectFilter(SfxMedium& rMedium, const SfxFilter** pFilter,
                                 SfxFilterFlags nMust, SfxFilterFlags nDont);
};

/*************************************************************************
|*
|* This tricky class keeps pointers to the SvFactories while
|* the DLL isn`t loaded. A pointer to the one instance is available
|* through SD_MOD() (shared-lib-app-data).
|*
\************************************************************************/

#ifndef _SD_DLL                      // Das define muss im Draw gesetzt werden
#define SD_MOD() ( *(SdModule**) GetAppData(SHL_DRAW) )
#endif

#endif                               // _SDDLL_HXX

<|endoftext|>


<commit_before>// Change To The Name you chose when you created the project - eg. #include "ShooterGame.h"
#include "GameName.h"
#include "AmmoComponent.h"

// Sets default values for this component's properties
UAmmoComponent::UAmmoComponent()
{
	// Set this component to be initialized when the game starts, and to be ticked every frame.  You can turn these features
	// off to improve performance if you don't need them.
	//bWantsBeginPlay = false;
	PrimaryComponentTick.bCanEverTick = false;
}

// Called when the game starts - TODO: Do i need this?
void UAmmoComponent::BeginPlay()
{
	// Check Constructor If Not Working (bWantsBeginPlay)
	Super::BeginPlay();
}

bool UAmmoComponent::Fire()
{
	bool bSuccess = true; // Assume true by default
	if(!IsAmmoDepleted())
	{
		if(bShootingInteruptsReload && IsReloading())
		{
			CancelReload();
		}
		else
		{
			TakeAmmo(BulletsPerShot);
			bSuccess = true;
		}
	}
	else
	{
		if(FiringWithNoBulletsStartsReload && CanReload())
		{
			Reload();
		}
		bSuccess = false;
	}
	return bSuccess; // return if shot should be fired or not
}

void UAmmoComponent::Reload()
{
	if(NeedsAndCanReload())
	{
		StartReloading();
	}
}

bool UAmmoComponent::IsReloading()
{
	return (bIsReloading && GetWorld()->GetTimerManager().IsTimerActive(ReloadingHandle));
}

void UAmmoComponent::CancelReload()
{
	if(IsReloading())
	{
		bIsReloading = false;
		GetWorld()->GetTimerManager().ClearTimer(ReloadingHandle);
	}
}

int32 UAmmoComponent::TakeAmmo(int32 Amount)
{
	return SetAmmo(Ammo-Amount);
}

int32 UAmmoComponent::GiveAmmo(int32 Amount)
{
	return SetAmmo(Ammo+Amount);
}

int32 UAmmoComponent::TakeReserveAmmo()
{
	return SetReserveAmmo(ReserveAmmo-1);
}

int32 UAmmoComponent::GiveReserveAmmo(int32 Amount)
{
	return SetReserveAmmo(ReserveAmmo+Amount);
}

int32 UAmmoComponent::SetAmmo(int32 NewAmmo)
{
	Ammo = FMath::Clamp(NewAmmo, 0, MaxAmmo);

	if(Ammo <= 0)
	{
		OnAmmoDepleted.Broadcast();
	}

	return Ammo;
}

int32 UAmmoComponent::SetReserveAmmo(int32 NewReserveAmmo)
{
	ReserveAmmo = FMath::Clamp(NewReserveAmmo, 0, MaxReserveAmmo);

	if(ReserveAmmo <= 0)
	{
		OnReserveDepleted.Broadcast();
	}

	return ReserveAmmo;
}

int32 UAmmoComponent::SetMaxAmmo(int32 NewMaxAmmo)
{
	MaxAmmo = NewMaxAmmo;
	return MaxAmmo;
}

int32 UAmmoComponent::SetMaxReserveAmmo(int32 NewMaxReserveAmmo)
{
	MaxReserveAmmo = NewMaxReserveAmmo;
	return MaxReserveAmmo;
}

float UAmmoComponent::GetReloadTimeLeftPercent()
{
	return GetRemainingReloadTime()/ReloadDuration;
}

bool UAmmoComponent::IsAmmoDepleted()
{
	return Ammo <= 0;
}

bool UAmmoComponent::IsReserveAmmoDepleted()
{
	return ReserveAmmo <= 0;
}

float UAmmoComponent::GetAmmoPercent()
{
	return Ammo/MaxAmmo;
}

float UAmmoComponent::GetRemainingReloadTime()
{
	if(IsReloading() && GetWorld()->GetTimerManager().IsTimerActive(ReloadingHandle))
	{
		return GetWorld()->GetTimerManager().GetTimerRemaining(ReloadingHandle);
	}
	else
	{
		return 0.f;
	}
}

bool UAmmoComponent::NeedsAndCanReload()
{
	return NeedsToReload() && CanReload();
}

FString UAmmoComponent::GetDebugInfo()
{
	return "" + FString::FromInt(Ammo) + " / " + FString::FromInt(ReserveAmmo) + ", Reloading: " + (bIsReloading ? "true" : "false");
}

void UAmmoComponent::ResetAmmo()
{
	SetAmmo(MaxAmmo);
	SetReserveAmmo(MaxReserveAmmo);
}

float UAmmoComponent::SetReloadDuration(float NewReloadDuration)
{
	ReloadDuration = NewReloadDuration;
	return ReloadDuration;
}

bool UAmmoComponent::NeedsToReload()
{
	return Ammo < MaxAmmo;
}

bool UAmmoComponent::CanReload()
{
	return (ReserveAmmo > 0 && !IsReloading());
}

void UAmmoComponent::StartReloading()
{
	if(!IsReloading())
	{
		bIsReloading = true;
		GetWorld()->GetTimerManager().SetTimer(ReloadingHandle, this, &UAmmoComponent::FinishReloading, ReloadDuration);
		OnReloadStart.Broadcast();
	}
}

void UAmmoComponent::FinishReloading()
{
	//if(IsReloading())
	if(bIsReloading)
	{
		if(ReserveAmmo >= (MaxAmmo - Ammo))
		{
			SetReserveAmmo(ReserveAmmo-(MaxAmmo-Ammo));
			SetAmmo(MaxAmmo);
		}
		else
		{
			SetAmmo(ReserveAmmo);
			SetReserveAmmo(0);
		}
		bIsReloading = false;
		OnReloadComplete.Broadcast();
	}
	else
	{
		UE_LOG(LogTemp, Error, TEXT("Called without bIsReloading being true"))
	}
}<commit_msg>Modified Conditions in Fire()<commit_after>// Change To The Name you chose when you created the project - eg. #include "ShooterGame.h"
#include "GunCPP.h"
#include "AmmoComponent.h"

// Sets default values for this component's properties
UAmmoComponent::UAmmoComponent()
{
	// Set this component to be initialized when the game starts, and to be ticked every frame.  You can turn these features
	// off to improve performance if you don't need them.
	//bWantsBeginPlay = false;
	PrimaryComponentTick.bCanEverTick = false;
}

// Called when the game starts - TODO: Do i need this?
void UAmmoComponent::BeginPlay()
{
	// Check Constructor If Not Working (bWantsBeginPlay)
	Super::BeginPlay();
}

bool UAmmoComponent::Fire()
{
	bool bSuccess = true; // Assume true by default
	if(!IsAmmoDepleted())
	{
		if(IsReloading())
		{
			if (bShootingInteruptsReload)
			{
				CancelReload();
			}
			else
			{
				bSuccess = false;
			}
		}
		else
		{
			TakeAmmo(BulletsPerShot);
			bSuccess = true;
		}
	}
	else
	{
		if(FiringWithNoBulletsStartsReload && CanReload())
		{
			Reload();
		}
		bSuccess = false;
	}
	return bSuccess; // return if shot should be fired or not
}

void UAmmoComponent::Reload()
{
	if(NeedsAndCanReload())
	{
		StartReloading();
	}
}

bool UAmmoComponent::IsReloading()
{
	return (bIsReloading && GetWorld()->GetTimerManager().IsTimerActive(ReloadingHandle));
}

void UAmmoComponent::CancelReload()
{
	if(IsReloading())
	{
		bIsReloading = false;
		GetWorld()->GetTimerManager().ClearTimer(ReloadingHandle);
	}
}

int32 UAmmoComponent::TakeAmmo(int32 Amount)
{
	return SetAmmo(Ammo-Amount);
}

int32 UAmmoComponent::GiveAmmo(int32 Amount)
{
	return SetAmmo(Ammo+Amount);
}

int32 UAmmoComponent::TakeReserveAmmo()
{
	return SetReserveAmmo(ReserveAmmo-1);
}

int32 UAmmoComponent::GiveReserveAmmo(int32 Amount)
{
	return SetReserveAmmo(ReserveAmmo+Amount);
}

int32 UAmmoComponent::SetAmmo(int32 NewAmmo)
{
	Ammo = FMath::Clamp(NewAmmo, 0, MaxAmmo);

	if(Ammo <= 0)
	{
		OnAmmoDepleted.Broadcast();
	}

	return Ammo;
}

int32 UAmmoComponent::SetReserveAmmo(int32 NewReserveAmmo)
{
	ReserveAmmo = FMath::Clamp(NewReserveAmmo, 0, MaxReserveAmmo);

	if(ReserveAmmo <= 0)
	{
		OnReserveDepleted.Broadcast();
	}

	return ReserveAmmo;
}

int32 UAmmoComponent::SetMaxAmmo(int32 NewMaxAmmo)
{
	MaxAmmo = NewMaxAmmo;
	return MaxAmmo;
}

int32 UAmmoComponent::SetMaxReserveAmmo(int32 NewMaxReserveAmmo)
{
	MaxReserveAmmo = NewMaxReserveAmmo;
	return MaxReserveAmmo;
}

float UAmmoComponent::GetReloadTimeLeftPercent()
{
	return GetRemainingReloadTime()/ReloadDuration;
}

bool UAmmoComponent::IsAmmoDepleted()
{
	return Ammo <= 0;
}

bool UAmmoComponent::IsReserveAmmoDepleted()
{
	return ReserveAmmo <= 0;
}

float UAmmoComponent::GetAmmoPercent()
{
	return Ammo/MaxAmmo;
}

float UAmmoComponent::GetRemainingReloadTime()
{
	if(IsReloading() && GetWorld()->GetTimerManager().IsTimerActive(ReloadingHandle))
	{
		return GetWorld()->GetTimerManager().GetTimerRemaining(ReloadingHandle);
	}
	else
	{
		return 0.f;
	}
}

bool UAmmoComponent::NeedsAndCanReload()
{
	return NeedsToReload() && CanReload();
}

FString UAmmoComponent::GetDebugInfo()
{
	return "" + FString::FromInt(Ammo) + " / " + FString::FromInt(ReserveAmmo) + ", Reloading: " + (bIsReloading ? "true" : "false");
}

void UAmmoComponent::ResetAmmo()
{
	SetAmmo(MaxAmmo);
	SetReserveAmmo(MaxReserveAmmo);
}

float UAmmoComponent::SetReloadDuration(float NewReloadDuration)
{
	ReloadDuration = NewReloadDuration;
	return ReloadDuration;
}

bool UAmmoComponent::NeedsToReload()
{
	return Ammo < MaxAmmo;
}

bool UAmmoComponent::CanReload()
{
	return (ReserveAmmo > 0 && !IsReloading());
}

void UAmmoComponent::StartReloading()
{
	if(!IsReloading())
	{
		bIsReloading = true;
		GetWorld()->GetTimerManager().SetTimer(ReloadingHandle, this, &UAmmoComponent::FinishReloading, ReloadDuration);
		OnReloadStart.Broadcast();
	}
}

void UAmmoComponent::FinishReloading()
{
	//if(IsReloading())
	if(bIsReloading)
	{
		if(ReserveAmmo >= (MaxAmmo - Ammo))
		{
			SetReserveAmmo(ReserveAmmo-(MaxAmmo-Ammo));
			SetAmmo(MaxAmmo);
		}
		else
		{
			SetAmmo(ReserveAmmo);
			SetReserveAmmo(0);
		}
		bIsReloading = false;
		OnReloadComplete.Broadcast();
	}
	else
	{
		UE_LOG(LogTemp, Error, TEXT("Called without bIsReloading being true"))
	}
}<|endoftext|>


<commit_before>#ifndef BFC_OPTIMIZER_HPP
#define BFC_OPTIMIZER_HPP

#include <vector>
#include "ast.hpp"
#include "opts.hpp"

namespace bfc {

class optimizer {

    public:

        optimizer(bool clean, bool quick) : clean(clean), quick(quick)  {}

        ast_node optimize(const ast_node &program) {
            // create list of optimizers
            std::vector<opt_seq_base_visitor> opts;
            combine_inc_visitor inc;
       //     opts.push_back(inc);

            /*
            if (clean) {
                // add additional optimizers
                dead_loops_visitor deadloop;
                opts.push_back(deadloop);
            }
            */

            opt_program_visitor opt_prog(std::move(opts));
            // run optimizations
            program.accept(opt_prog);

            if (!quick) {
                if (!program.equals(opt_prog.result())) {
                    // re-run optimizations until AST is stable
                    ast_node result;
                    do {
                        result = opt_prog.result();
                        result.accept(opt_prog);
                    } while (result != opt_prog.result());
                }
            }

            return opt_prog.result();
        }

    private:
        // indicates if redundant code should be cleaned up during optimization
        bool clean;

        // indicates if one-pass or full optimization is performed
        bool quick;

};

}
#endif /* !BFC_OPTIMIZER_HPP */
<commit_msg>Comment out upcoming feature for testing<commit_after>#ifndef BFC_OPTIMIZER_HPP
#define BFC_OPTIMIZER_HPP

#include <vector>
#include "ast.hpp"
#include "opts.hpp"

namespace bfc {

class optimizer {

    public:

        optimizer(bool clean, bool quick) : clean(clean), quick(quick)  {}

        ast_node optimize(const ast_node &program) {
            // create list of optimizers
            std::vector<opt_seq_base_visitor> opts;
            combine_inc_visitor inc;
       //     opts.push_back(inc);

            /*
            if (clean) {
                // add additional optimizers
                dead_loops_visitor deadloop;
                opts.push_back(deadloop);
            }
            */

            opt_program_visitor opt_prog(std::move(opts));
            // run optimizations
            program.accept(opt_prog);

            /*
            if (!quick) {
                if (!program.equals(opt_prog.result())) {
                    // re-run optimizations until AST is stable
                    ast_node result;
                    do {
                        result = opt_prog.result();
                        result.accept(opt_prog);
                    } while (result != opt_prog.result());
                }
            }
            */

            return opt_prog.result();
        }

    private:
        // indicates if redundant code should be cleaned up during optimization
        bool clean;

        // indicates if one-pass or full optimization is performed
        bool quick;

};

}
#endif /* !BFC_OPTIMIZER_HPP */
<|endoftext|>


<commit_before>/*=========================================================================

  Program: Visomics

  Copyright (c) Kitware, Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=========================================================================*/

// Qt includes
#include <QDebug>

// QtPropertyBrowser includes
#include <QtVariantPropertyManager>
#include <QInputDialog>
#include <QMainWindow>
#include <QRegExp>

// Visomics includes
#include "voTreeDropTip.h"
#include "voApplication.h"
#include "voTableDataObject.h"
#include "voOutputDataObject.h"
#include "voIOManager.h"
#include "voUtils.h"

// VTK includes
#include <vtkArrayData.h>
#include <vtkIdTypeArray.h>
#include <vtkDoubleArray.h>
#include <vtkNew.h>
#include <vtkSmartPointer.h>
#include <vtkStringArray.h>
#include <vtkTable.h>
#include <vtkExtendedTable.h>
#include <vtkExtractSelectedTree.h>
#include <vtkSelection.h>
#include <vtkSelectionNode.h>
#include <vtkDataSetAttributes.h>
#include <vtkInformation.h>
#include <vtkAdjacentVertexIterator.h>
// --------------------------------------------------------------------------
// voTreeDropTipPrivate methods

// --------------------------------------------------------------------------
class voTreeDropTipPrivate
{
};

// --------------------------------------------------------------------------
bool voTreeDropTip::removeInternalBranch(vtkTree * tree, vtkIdTypeArray * selArray, vtkIdType currentId)
{// remove the internal branch of the selected tips
 //  by adding internal verticies/nodes to the selection
  if (tree->IsLeaf(currentId))
    {//do nothing
    return true;
    }

  vtkSmartPointer <vtkAdjacentVertexIterator> it  =
            vtkSmartPointer<vtkAdjacentVertexIterator>::New();
  tree->GetChildren(currentId,it);
  int numberOfSelectedChildren = 0;
  while (it->HasNext())
   {
   vtkIdType childId = it->Next();
   this->removeInternalBranch(tree, selArray,childId);
   //count the number of selected children
   for ( vtkIdType i = 0; i < selArray->GetNumberOfTuples(); i++)
     {
     if (selArray->GetValue(i) == childId)
       {
       numberOfSelectedChildren++;
       break;
       }
     }
   }

   if (numberOfSelectedChildren == tree->GetNumberOfChildren(currentId))
     {// add the current internal node to the selection list as well
     selArray->InsertNextValue(currentId);
     }

  return true;
}

// --------------------------------------------------------------------------
bool voTreeDropTip::getTipSelection(vtkTree * tree, vtkTable * inputDataTable, vtkSelection * sel, QStringList tipNameList)
{
  QStringList removalTipNameList;
  vtkStringArray * nodeNames = vtkStringArray::SafeDownCast(tree->GetVertexData()->GetAbstractArray("node name"));
  QString InvertSelection = this->enumParameter("invert_selection");
  if (InvertSelection == "No" )
    {
    removalTipNameList = tipNameList;
    }
  else
    {// input list is the keep list
    for ( vtkIdType i = 0; i< nodeNames->GetNumberOfValues() ; i++)
      {
      QString curTip = QString(nodeNames->GetValue(i).c_str());
      if  (!tipNameList.contains(curTip))
        {
        removalTipNameList.append(curTip);
        }
      }
    }

  vtkSmartPointer<vtkSelectionNode> selNode = vtkSmartPointer <vtkSelectionNode>::New() ;
  vtkSmartPointer<vtkIdTypeArray> selArr = vtkSmartPointer<vtkIdTypeArray>::New();
  // extract subtree using vtkExtractSelectedTree class
  // remove rows from the table
  vtkStringArray *tableNames = vtkStringArray::SafeDownCast(inputDataTable->GetColumn(0));
  for (int i =0; i < removalTipNameList.size(); i++)
    {
    vtkIdType vertexId = nodeNames->LookupValue(removalTipNameList[i].toStdString().c_str());
    if (vertexId >= 0)
      {
      selArr->InsertNextValue(vertexId);
      }
    else
      {
      qWarning()<< QObject::tr("Could not find the tip names in the tree:") << removalTipNameList[i];
      return false;
      }

    vtkIdType rowId = tableNames->LookupValue(removalTipNameList[i].toStdString().c_str());
    if (rowId >= 0)
      {
      inputDataTable->RemoveRow(rowId);
      }
    else
      {
      qWarning()<< QObject::tr("Could not find the tip names in the table:") << removalTipNameList[i];
      return false;
      }

    }

  //remove vertices whoes children are in the selection list recursively
  this->removeInternalBranch(tree,selArr,tree->GetRoot());

  selNode->SetContentType(vtkSelectionNode::INDICES);
  selNode->SetFieldType(vtkSelectionNode::VERTEX);
  selNode->SetSelectionList(selArr.GetPointer());

  selNode->GetProperties()->Set(vtkSelectionNode::INVERSE(), 1);
  sel->AddNode(selNode.GetPointer());

  return true;
}

// --------------------------------------------------------------------------
bool voTreeDropTip::getSelectionByTipNames(vtkTree * tree, vtkTable * inputDataTable, vtkSelection * sel)
{
  QString scratchString = this->stringParameter("input_string");
  QStringList tipNameList;
  QStringList removalTipNameList;
  if (!scratchString.isEmpty())
    {
    tipNameList = scratchString.split(",");
    }

  if(tipNameList.empty())
    {
    qWarning() << QObject::tr("Invalid paramater, could not parse input tip name list");
    return false;
    }

  return (this->getTipSelection(tree, inputDataTable, sel, tipNameList));
}

// --------------------------------------------------------------------------
bool voTreeDropTip::getSelectionByDataFiltering(vtkTree *tree, vtkTable * inputDataTable, vtkSelection * sel)
{
  QStringList tipNameList;
  QString scratchString = this->stringParameter("input_string");
  QStringList conditionList;
  if ( !scratchString.isEmpty())
    {
    conditionList = scratchString.split(",");
    }

  if(conditionList.empty())
    {
    qWarning() << QObject::tr("Invalid paramater, could not parse input condition list");
    return false;
    }

  vtkStringArray *tableNames = vtkStringArray::SafeDownCast(inputDataTable->GetColumn(0));
  double epsilon = 1e-5;

  for (vtkIdType row = 0; row < inputDataTable->GetNumberOfRows(); row++)
    {// for each tip
    int numberOfConditionSatisfied = 0;
    for (int i = 0; i < conditionList.size(); i++)
      { //parse each condition
      QString condition = conditionList[i];
      bool conditionSatisfied = false;
      QRegExp rx("\\b(<|>|=)");
      int pos = rx.indexIn(condition, 0);
      std::string colName = condition.left(pos).toStdString();

      bool STRING_CONDITION = false;
      if (condition.count("\"") == 2)
        {
        STRING_CONDITION = true;
        }

      if (STRING_CONDITION)
        {// string comparison
        if (condition.at(pos) == QChar('='))
          {
          QString v = QString ((inputDataTable->GetValueByName(row,colName.c_str()).ToString()).c_str());
          QString  refString = condition.section('=',1,1);
          refString.chop(1);
          refString = refString.right(refString.size()-1);
          if ( v == refString )
            {
            conditionSatisfied = true;
            }
          }
        else
          {
          qCritical()<<"String filtering can only use \"=\"";
          return false;
          }
        }
      else
        {// number comparison
        double v = inputDataTable->GetValueByName(row,colName.c_str()).ToDouble();
        double threshold;
        if (condition.at(pos) == QChar('<'))
          {
          if (condition.at(pos+1) == QChar('='))
            { // <=
            threshold = condition.right(condition.size()-pos).toDouble();
            if (v <= threshold)
              {
              conditionSatisfied = true;
              }
            }
          else
            {// <
            threshold = condition.right(condition.size()-pos-1).toDouble();
            if (v < threshold)
              {
              conditionSatisfied = true;
              }
            }
          }
        else if (condition.at(pos) == QChar('>'))
          {
          if(condition.at(pos+1) == QChar('='))
            {// >=
            threshold = condition.right(condition.size()-pos-2).toDouble();
            if (v >= threshold)
              {
              conditionSatisfied = true;
              }
            }
          else
            {//>
            threshold = condition.right(condition.size()-pos-1).toDouble();
            if (v > threshold)
              {
              conditionSatisfied = true;
              }
            }
          }
        else if (condition.at(pos) == QChar('='))
          { //=
          threshold = condition.right(condition.size()-pos-1).toDouble();
          if ( fabs(v- threshold) < epsilon)
            {
            conditionSatisfied = true;
            }
          }
        else
          {
          qCritical()<<"Error parsing the conditions; please check your syntax.";
          return false;
          }
        }// end of numeric condition

      if (!conditionSatisfied)
        {
        break;
        }
      else
        {
        numberOfConditionSatisfied ++;
        }
      } //end of "for each condition"

    if (numberOfConditionSatisfied == conditionList.size())
      { // this tip meets all conditions
      // qDebug()<<"tip name:"<<QString(tableNames->GetValue(row).c_str());
      tipNameList.append(QString(tableNames->GetValue(row).c_str()));
      }
    } // end of "for each tip"
  // qDebug()<<"tipNameList"<<tipNameList;
  return (getTipSelection(tree,inputDataTable,sel,tipNameList));
}

// --------------------------------------------------------------------------
// voTreeDropTip methods

// --------------------------------------------------------------------------
voTreeDropTip::voTreeDropTip():
  Superclass(), d_ptr(new voTreeDropTipPrivate)
{
}

// --------------------------------------------------------------------------
voTreeDropTip::~voTreeDropTip()
{
}

// --------------------------------------------------------------------------
void voTreeDropTip::setOutputInformation()
{
  this->addOutputType("treeAfterDropTip", "vtkTree" ,
    "","",
    "voTreeHeatmapView", "Subtree output");
  this->addOutputType("tableAfterDropTip", "vtkExtendedTable" ,
    "","",
    "voExtendedTableView", "Subtable output");
}

// --------------------------------------------------------------------------
void voTreeDropTip::setParameterInformation()
{
  QList<QtProperty*> DropTip_parameters;

  DropTip_parameters << this->addEnumParameter("selection_method", tr("Select tips to be removed by"), (QStringList()<<"Tip Names"<<"Data Filter"), "Tip Names");
  DropTip_parameters << this->addStringParameter("input_string", tr("Line editor"), "[tipName1, tipName2] or [awesomeness<2,island=\"Cuba\"]");
  DropTip_parameters << this->addEnumParameter("invert_selection", tr("Invert selection"), (QStringList()<<"No"<<"Yes"), "No");

  this->addParameterGroup("DropTip parameters", DropTip_parameters);
}

// --------------------------------------------------------------------------
QString voTreeDropTip::parameterDescription()const
{
  return QString("
"
    "
Select tips to be removed by: :
"
    "
Choose the method for the tip selection."
    " \"Tip Names\" requires you to list the tip "
    "names in the line editor below;\"Data Filter\" requires"
    " you to list the thresholding criteria in the line editor below.
"
    "
 Line editor :
"
    "
 Input the tips names or the data filtering criteria.
"
    "
Invert selection :
"
    "
 Invert the tip selection. If \"Yes\", The selected tips are to be kept.
"
    "
");
}

// --------------------------------------------------------------------------
bool voTreeDropTip::execute()
{
  Q_D(voTreeDropTip);
  // Import tree and assiciated traits table
  vtkTree* tree =  vtkTree::SafeDownCast(this->input(0)->dataAsVTKDataObject());
  if (!tree)
    {
    qCritical() << "Input tree is Null";
    return false;
    }

  vtkExtendedTable* extendedTable = vtkExtendedTable::SafeDownCast(
    this->input(1)->dataAsVTKDataObject());

  vtkNew<vtkTable> table;
  if (extendedTable)
    {
    table->DeepCopy(extendedTable->GetInputData());
    }
  else
    {
    qCritical()<<"Input Table is Null";
    }

  // obtain selected tips into a vtkSelection object
  QString selection_method = this->enumParameter("selection_method");

  vtkNew<vtkSelection> selectedTips;
  bool SUCCESS = false;
  if (selection_method == "Tip Names")
    {
    SUCCESS = this->getSelectionByTipNames(tree, table.GetPointer(), selectedTips.GetPointer());
    }
  else if (selection_method == "Data Filter")
    {
    SUCCESS = this->getSelectionByDataFiltering(tree, table.GetPointer(), selectedTips.GetPointer());
    }

  if (SUCCESS)
    {
    vtkNew<vtkExtractSelectedTree> extractSelectedTreeFilter;

    extractSelectedTreeFilter->SetInputData(0, tree);
    extractSelectedTreeFilter->SetInputData(1, selectedTips.GetPointer());
    extractSelectedTreeFilter->Update();

    vtkTree * outTree = vtkTree::SafeDownCast(extractSelectedTreeFilter->GetOutput());

    if(!outTree)
      {
      qCritical() << QObject::tr("extracted tree is not valid");
      return false;
      }

    this->setOutput("treeAfterDropTip", new voOutputDataObject("treeAfterDropTip", outTree));
    vtkNew<vtkExtendedTable> outputTable;
    voIOManager::convertTableToExtended(table.GetPointer(), outputTable.GetPointer());
    this->setOutput("tableAfterDropTip", new voTableDataObject("tableAfterDropTip", outputTable.GetPointer()));

    return true;
    }
  else
    {
    qCritical() << QObject::tr("selected tips are not valid");
    return false;
    }

}
<commit_msg>BUG: Invert selection does not work properly.<commit_after>/*=========================================================================

  Program: Visomics

  Copyright (c) Kitware, Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=========================================================================*/

// Qt includes
#include <QDebug>

// QtPropertyBrowser includes
#include <QtVariantPropertyManager>
#include <QInputDialog>
#include <QMainWindow>
#include <QRegExp>

// Visomics includes
#include "voTreeDropTip.h"
#include "voApplication.h"
#include "voTableDataObject.h"
#include "voOutputDataObject.h"
#include "voIOManager.h"
#include "voUtils.h"

// VTK includes
#include <vtkArrayData.h>
#include <vtkIdTypeArray.h>
#include <vtkDoubleArray.h>
#include <vtkNew.h>
#include <vtkSmartPointer.h>
#include <vtkStringArray.h>
#include <vtkTable.h>
#include <vtkExtendedTable.h>
#include <vtkExtractSelectedTree.h>
#include <vtkSelection.h>
#include <vtkSelectionNode.h>
#include <vtkDataSetAttributes.h>
#include <vtkInformation.h>
#include <vtkAdjacentVertexIterator.h>
// --------------------------------------------------------------------------
// voTreeDropTipPrivate methods

// --------------------------------------------------------------------------
class voTreeDropTipPrivate
{
};

// --------------------------------------------------------------------------
bool voTreeDropTip::removeInternalBranch(vtkTree * tree, vtkIdTypeArray * selArray, vtkIdType currentId)
{// remove the internal branch of the selected tips
 //  by adding internal verticies/nodes to the selection
  if (tree->IsLeaf(currentId))
    {//do nothing
    return true;
    }

  vtkSmartPointer <vtkAdjacentVertexIterator> it  =
            vtkSmartPointer<vtkAdjacentVertexIterator>::New();
  tree->GetChildren(currentId,it);
  int numberOfSelectedChildren = 0;
  while (it->HasNext())
   {
   vtkIdType childId = it->Next();
   this->removeInternalBranch(tree, selArray,childId);
   //count the number of selected children
   for ( vtkIdType i = 0; i < selArray->GetNumberOfTuples(); i++)
     {
     if (selArray->GetValue(i) == childId)
       {
       numberOfSelectedChildren++;
       break;
       }
     }
   }

   if (numberOfSelectedChildren == tree->GetNumberOfChildren(currentId))
     {// add the current internal node to the selection list as well
     selArray->InsertNextValue(currentId);
     }

  return true;
}

// --------------------------------------------------------------------------
bool voTreeDropTip::getTipSelection(vtkTree * tree, vtkTable * inputDataTable, vtkSelection * sel, QStringList tipNameList)
{
  QStringList removalTipNameList;
  vtkStringArray * nodeNames = vtkStringArray::SafeDownCast(tree->GetVertexData()->GetAbstractArray("node name"));
  QString InvertSelection = this->enumParameter("invert_selection");
  if (InvertSelection == "No" )
    {
    removalTipNameList = tipNameList;
    }
  else
    {// input list is the keep list
    for ( vtkIdType i = 0; i< nodeNames->GetNumberOfValues() ; i++)
      {
      QString curTip = QString(nodeNames->GetValue(i).c_str());
      if  ( !curTip.isEmpty() && !tipNameList.contains(curTip))
        {
        removalTipNameList.append(curTip);
        }
      }
    }

  vtkSmartPointer<vtkSelectionNode> selNode = vtkSmartPointer <vtkSelectionNode>::New() ;
  vtkSmartPointer<vtkIdTypeArray> selArr = vtkSmartPointer<vtkIdTypeArray>::New();
  // extract subtree using vtkExtractSelectedTree class
  // remove rows from the table
  vtkStringArray *tableNames = vtkStringArray::SafeDownCast(inputDataTable->GetColumn(0));
  for (int i =0; i < removalTipNameList.size(); i++)
    {
    vtkIdType vertexId = nodeNames->LookupValue(removalTipNameList[i].toStdString().c_str());
    if (vertexId >= 0)
      {
      selArr->InsertNextValue(vertexId);
      }
    else
      {
      qWarning()<< QObject::tr("Could not find the tip names in the tree:") << removalTipNameList[i];
      return false;
      }

    vtkIdType rowId = tableNames->LookupValue(removalTipNameList[i].toStdString().c_str());
    if (rowId >= 0)
      {
      inputDataTable->RemoveRow(rowId);
      }
    else
      {
      qWarning()<< QObject::tr("Could not find the tip names in the table:") << removalTipNameList[i];
      return false;
      }

    }

  //remove vertices whoes children are in the selection list recursively
  this->removeInternalBranch(tree,selArr,tree->GetRoot());

  selNode->SetContentType(vtkSelectionNode::INDICES);
  selNode->SetFieldType(vtkSelectionNode::VERTEX);
  selNode->SetSelectionList(selArr.GetPointer());

  selNode->GetProperties()->Set(vtkSelectionNode::INVERSE(), 1);
  sel->AddNode(selNode.GetPointer());

  return true;
}

// --------------------------------------------------------------------------
bool voTreeDropTip::getSelectionByTipNames(vtkTree * tree, vtkTable * inputDataTable, vtkSelection * sel)
{
  QString scratchString = this->stringParameter("input_string");
  QStringList tipNameList;
  QStringList removalTipNameList;
  if (!scratchString.isEmpty())
    {
    tipNameList = scratchString.split(",");
    }

  if(tipNameList.empty())
    {
    qWarning() << QObject::tr("Invalid paramater, could not parse input tip name list");
    return false;
    }

  return (this->getTipSelection(tree, inputDataTable, sel, tipNameList));
}

// --------------------------------------------------------------------------
bool voTreeDropTip::getSelectionByDataFiltering(vtkTree *tree, vtkTable * inputDataTable, vtkSelection * sel)
{
  QStringList tipNameList;
  QString scratchString = this->stringParameter("input_string");
  QStringList conditionList;
  if ( !scratchString.isEmpty())
    {
    conditionList = scratchString.split(",");
    }

  if(conditionList.empty())
    {
    qWarning() << QObject::tr("Invalid paramater, could not parse input condition list");
    return false;
    }

  vtkStringArray *tableNames = vtkStringArray::SafeDownCast(inputDataTable->GetColumn(0));
  double epsilon = 1e-5;

  for (vtkIdType row = 0; row < inputDataTable->GetNumberOfRows(); row++)
    {// for each tip
    int numberOfConditionSatisfied = 0;
    for (int i = 0; i < conditionList.size(); i++)
      { //parse each condition
      QString condition = conditionList[i];
      bool conditionSatisfied = false;
      QRegExp rx("\\b(<|>|=)");
      int pos = rx.indexIn(condition, 0);
      std::string colName = condition.left(pos).toStdString();

      bool STRING_CONDITION = false;
      if (condition.count("\"") == 2)
        {
        STRING_CONDITION = true;
        }

      if (STRING_CONDITION)
        {// string comparison
        if (condition.at(pos) == QChar('='))
          {
          QString v = QString ((inputDataTable->GetValueByName(row,colName.c_str()).ToString()).c_str());
          QString  refString = condition.section('=',1,1);
          refString.chop(1);
          refString = refString.right(refString.size()-1);
          if ( v == refString )
            {
            conditionSatisfied = true;
            }
          }
        else
          {
          qCritical()<<"String filtering can only use \"=\"";
          return false;
          }
        }
      else
        {// number comparison
        double v = inputDataTable->GetValueByName(row,colName.c_str()).ToDouble();
        double threshold;
        if (condition.at(pos) == QChar('<'))
          {
          if (condition.at(pos+1) == QChar('='))
            { // <=
            threshold = condition.right(condition.size()-pos).toDouble();
            if (v <= threshold)
              {
              conditionSatisfied = true;
              }
            }
          else
            {// <
            threshold = condition.right(condition.size()-pos-1).toDouble();
            if (v < threshold)
              {
              conditionSatisfied = true;
              }
            }
          }
        else if (condition.at(pos) == QChar('>'))
          {
          if(condition.at(pos+1) == QChar('='))
            {// >=
            threshold = condition.right(condition.size()-pos-2).toDouble();
            if (v >= threshold)
              {
              conditionSatisfied = true;
              }
            }
          else
            {//>
            threshold = condition.right(condition.size()-pos-1).toDouble();
            if (v > threshold)
              {
              conditionSatisfied = true;
              }
            }
          }
        else if (condition.at(pos) == QChar('='))
          { //=
          threshold = condition.right(condition.size()-pos-1).toDouble();
          if ( fabs(v- threshold) < epsilon)
            {
            conditionSatisfied = true;
            }
          }
        else
          {
          qCritical()<<"Error parsing the conditions; please check your syntax.";
          return false;
          }
        }// end of numeric condition

      if (!conditionSatisfied)
        {
        break;
        }
      else
        {
        numberOfConditionSatisfied ++;
        }
      } //end of "for each condition"

    if (numberOfConditionSatisfied == conditionList.size())
      { // this tip meets all conditions
      // qDebug()<<"tip name:"<<QString(tableNames->GetValue(row).c_str());
      tipNameList.append(QString(tableNames->GetValue(row).c_str()));
      }
    } // end of "for each tip"
  // qDebug()<<"tipNameList"<<tipNameList;
  return (getTipSelection(tree,inputDataTable,sel,tipNameList));
}

// --------------------------------------------------------------------------
// voTreeDropTip methods

// --------------------------------------------------------------------------
voTreeDropTip::voTreeDropTip():
  Superclass(), d_ptr(new voTreeDropTipPrivate)
{
}

// --------------------------------------------------------------------------
voTreeDropTip::~voTreeDropTip()
{
}

// --------------------------------------------------------------------------
void voTreeDropTip::setOutputInformation()
{
  this->addOutputType("treeAfterDropTip", "vtkTree" ,
    "","",
    "voTreeHeatmapView", "Subtree output");
  this->addOutputType("tableAfterDropTip", "vtkExtendedTable" ,
    "","",
    "voExtendedTableView", "Subtable output");
}

// --------------------------------------------------------------------------
void voTreeDropTip::setParameterInformation()
{
  QList<QtProperty*> DropTip_parameters;

  DropTip_parameters << this->addEnumParameter("selection_method", tr("Select tips to be removed by"), (QStringList()<<"Tip Names"<<"Data Filter"), "Tip Names");
  DropTip_parameters << this->addStringParameter("input_string", tr("Line editor"), "[tipName1, tipName2] or [awesomeness<2,island=\"Cuba\"]");
  DropTip_parameters << this->addEnumParameter("invert_selection", tr("Invert selection"), (QStringList()<<"No"<<"Yes"), "No");

  this->addParameterGroup("DropTip parameters", DropTip_parameters);
}

// --------------------------------------------------------------------------
QString voTreeDropTip::parameterDescription()const
{
  return QString("
"
    "
Select tips to be removed by: :
"
    "
Choose the method for the tip selection."
    " \"Tip Names\" requires you to list the tip "
    "names in the line editor below;\"Data Filter\" requires"
    " you to list the thresholding criteria in the line editor below.
"
    "
 Line editor :
"
    "
 Input the tips names or the data filtering criteria.
"
    "
Invert selection :
"
    "
 Invert the tip selection. If \"Yes\", The selected tips are to be kept.
"
    "
");
}

// --------------------------------------------------------------------------
bool voTreeDropTip::execute()
{
  Q_D(voTreeDropTip);
  // Import tree and assiciated traits table
  vtkTree* tree =  vtkTree::SafeDownCast(this->input(0)->dataAsVTKDataObject());
  if (!tree)
    {
    qCritical() << "Input tree is Null";
    return false;
    }

  vtkExtendedTable* extendedTable = vtkExtendedTable::SafeDownCast(
    this->input(1)->dataAsVTKDataObject());

  vtkNew<vtkTable> table;
  if (extendedTable)
    {
    table->DeepCopy(extendedTable->GetInputData());
    }
  else
    {
    qCritical()<<"Input Table is Null";
    }

  // obtain selected tips into a vtkSelection object
  QString selection_method = this->enumParameter("selection_method");

  vtkNew<vtkSelection> selectedTips;
  bool SUCCESS = false;
  if (selection_method == "Tip Names")
    {
    SUCCESS = this->getSelectionByTipNames(tree, table.GetPointer(), selectedTips.GetPointer());
    }
  else if (selection_method == "Data Filter")
    {
    SUCCESS = this->getSelectionByDataFiltering(tree, table.GetPointer(), selectedTips.GetPointer());
    }

  if (SUCCESS)
    {
    vtkNew<vtkExtractSelectedTree> extractSelectedTreeFilter;

    extractSelectedTreeFilter->SetInputData(0, tree);
    extractSelectedTreeFilter->SetInputData(1, selectedTips.GetPointer());
    extractSelectedTreeFilter->Update();

    vtkTree * outTree = vtkTree::SafeDownCast(extractSelectedTreeFilter->GetOutput());

    if(!outTree)
      {
      qCritical() << QObject::tr("extracted tree is not valid");
      return false;
      }

    this->setOutput("treeAfterDropTip", new voOutputDataObject("treeAfterDropTip", outTree));
    vtkNew<vtkExtendedTable> outputTable;
    voIOManager::convertTableToExtended(table.GetPointer(), outputTable.GetPointer());
    this->setOutput("tableAfterDropTip", new voTableDataObject("tableAfterDropTip", outputTable.GetPointer()));

    return true;
    }
  else
    {
    qCritical() << QObject::tr("selected tips are not valid");
    return false;
    }

}
<|endoftext|>


<commit_before>// Time:  O(n)
// Space: O(h)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int countUnivalSubtrees(TreeNode* root) {
        int count = 0;
        isUnivalSubtrees(root, &count);
        return count;
    }

    bool isUnivalSubtrees(TreeNode* root, int *count) {
        if (root == nullptr) {
            return true;
        }
        bool left = isUnivalSubtrees(root->left, count);
        bool right = isUnivalSubtrees(root->right, count);
        if (isSame(root, root->left, left) &&
            isSame(root, root->right, right)) {
                ++(*count);
                return true;
            }
        return false;
    }

    bool isSame(TreeNode* root, TreeNode* child, bool isUni) {
        return child == nullptr || (isUni && root->val == child->val);
    }
};
<commit_msg>Update count-univalue-subtrees.cpp<commit_after>// Time:  O(n)
// Space: O(h)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int countUnivalSubtrees(TreeNode* root) {
        int count = 0;
        isUnivalSubtrees(root, &count);
        return count;
    }

    bool isUnivalSubtrees(TreeNode* root, int *count) {
        if (root == nullptr) {
            return true;
        }
        bool left = isUnivalSubtrees(root->left, count);
        bool right = isUnivalSubtrees(root->right, count);
        if (isSame(root, root->left, left) &&
            isSame(root, root->right, right)) {
                ++(*count);
                return true;
            }
        return false;
    }

    bool isSame(TreeNode* root, TreeNode* child, bool is_uni) {
        return child == nullptr || (is_uni && root->val == child->val);
    }
};
<|endoftext|>


<commit_before>/*
* Copyright 2011, 2012 Range Networks, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

// KEEP THIS FILE CLEAN FOR GPL PUBLIC RELEASE.

#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

#define DEFAULT_CMD_PATH "/var/run/OpenBTS/command"

int main(int argc, char *argv[])
{
	const char* cmdPath = DEFAULT_CMD_PATH;
	if (argc!=1) {
		cmdPath = argv[1];
	}

	char rspPath[200];
	sprintf(rspPath,"/tmp/OpenBTS.do.%d",getpid());

	// the socket
	int sock = socket(AF_UNIX,SOCK_DGRAM,0);
	if (sock<0) {
		perror("opening datagram socket");
		exit(1);
	}

	// destination address
	struct sockaddr_un cmdSockName;
	cmdSockName.sun_family = AF_UNIX;
	strcpy(cmdSockName.sun_path,cmdPath);

	// locally bound address
	struct sockaddr_un rspSockName;
	rspSockName.sun_family = AF_UNIX;
	char rmcmd[strlen(rspPath)+10];
	sprintf(rmcmd,"rm -f %s",rspPath);
	system(rmcmd);
	strcpy(rspSockName.sun_path,rspPath);
	if (bind(sock, (struct sockaddr *) &rspSockName, sizeof(struct sockaddr_un))) {
		perror("binding name to datagram socket");
		exit(1);
	}

	char *inbuf = (char*)malloc(200);
	char *cmd = fgets(inbuf,199,stdin);
	if (!cmd) exit(0);
	cmd[strlen(cmd)-1] = '\0';

	if (sendto(sock,cmd,strlen(cmd)+1,0,(struct sockaddr*)&cmdSockName,sizeof(cmdSockName))<0) {
		perror("sending datagram");
		exit(1);
	}

	// buffer to be sized as necessary to accomodate config data length
	const int bufsz = 8500;
	char resbuf[bufsz];
	int nread = recv(sock,resbuf,bufsz-1,0);
	if (nread<0) {
		perror("receiving response");
		exit(1);
	}
	resbuf[nread] = '\0';
	printf("%s\n",resbuf);

	close(sock);

	// Delete the path to limit clutter in /tmp.
	sprintf(rmcmd,"rm -f %s",rspPath);
	system(rmcmd);
}
<commit_msg>Missed this path change<commit_after>/*
* Copyright 2011, 2012 Range Networks, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

// KEEP THIS FILE CLEAN FOR GPL PUBLIC RELEASE.

#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

#define DEFAULT_CMD_PATH "/var/run/command"

int main(int argc, char *argv[])
{
	const char* cmdPath = DEFAULT_CMD_PATH;
	if (argc!=1) {
		cmdPath = argv[1];
	}

	char rspPath[200];
	sprintf(rspPath,"/tmp/OpenBTS.do.%d",getpid());

	// the socket
	int sock = socket(AF_UNIX,SOCK_DGRAM,0);
	if (sock<0) {
		perror("opening datagram socket");
		exit(1);
	}

	// destination address
	struct sockaddr_un cmdSockName;
	cmdSockName.sun_family = AF_UNIX;
	strcpy(cmdSockName.sun_path,cmdPath);

	// locally bound address
	struct sockaddr_un rspSockName;
	rspSockName.sun_family = AF_UNIX;
	char rmcmd[strlen(rspPath)+10];
	sprintf(rmcmd,"rm -f %s",rspPath);
	system(rmcmd);
	strcpy(rspSockName.sun_path,rspPath);
	if (bind(sock, (struct sockaddr *) &rspSockName, sizeof(struct sockaddr_un))) {
		perror("binding name to datagram socket");
		exit(1);
	}

	char *inbuf = (char*)malloc(200);
	char *cmd = fgets(inbuf,199,stdin);
	if (!cmd) exit(0);
	cmd[strlen(cmd)-1] = '\0';

	if (sendto(sock,cmd,strlen(cmd)+1,0,(struct sockaddr*)&cmdSockName,sizeof(cmdSockName))<0) {
		perror("sending datagram");
		exit(1);
	}

	// buffer to be sized as necessary to accomodate config data length
	const int bufsz = 8500;
	char resbuf[bufsz];
	int nread = recv(sock,resbuf,bufsz-1,0);
	if (nread<0) {
		perror("receiving response");
		exit(1);
	}
	resbuf[nread] = '\0';
	printf("%s\n",resbuf);

	close(sock);

	// Delete the path to limit clutter in /tmp.
	sprintf(rmcmd,"rm -f %s",rspPath);
	system(rmcmd);
}
<|endoftext|>


<commit_before>/* The MIT License (MIT)
 *
 * Copyright (c) 2016 Ștefan-Gabriel Mirea, Adrian Dobrică
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#ifndef ELF_FILE_HPP_
#define ELF_FILE_HPP_

#include "elfio/elfio.hpp"
#include "file_unit.hpp"
#include <string>

namespace elf
{
/**
 * The FileUnit responsible for interpreting ELF executable files. Its is based on the ELFIO
 * library.
 */
class ELFFile : public FileUnit
{
public:
    ELFFile(const std::string &filename);
    bool getOpenStatus();
    bool save(std::string &filename);
    void modifyHex(size_t offset, std::string &newContent);
    virtual ~ELFFile();

private:
    ELFIO::elfio *file;
    bool open;
};
}

#endif // ELF_FILE_HPP_
<commit_msg>Fix typo in elf_file comment<commit_after>/* The MIT License (MIT)
 *
 * Copyright (c) 2016 Ștefan-Gabriel Mirea, Adrian Dobrică
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#ifndef ELF_FILE_HPP_
#define ELF_FILE_HPP_

#include "elfio/elfio.hpp"
#include "file_unit.hpp"
#include <string>

namespace elf
{
/**
 * The FileUnit responsible for interpreting ELF executable files. It is based on the ELFIO
 * library.
 */
class ELFFile : public FileUnit
{
public:
    ELFFile(const std::string &filename);
    bool getOpenStatus();
    bool save(std::string &filename);
    void modifyHex(size_t offset, std::string &newContent);
    virtual ~ELFFile();

private:
    ELFIO::elfio *file;
    bool open;
};
}

#endif // ELF_FILE_HPP_
<|endoftext|>


<commit_before><commit_msg>call ExternalForceField::initialize<commit_after><|endoftext|>