<commit_before>#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <boost/program_options.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid_io.hpp>

#include "csv_back.h"
#include "cyclus.h"
#include "hdf5_back.h"
#include "sqlite_back.h"
#include "xml_file_loader.h"

namespace po = boost::program_options;
namespace fs = boost::filesystem;

using namespace cyclus;

//-----------------------------------------------------------------------
// Main entry point for the test application...
//-----------------------------------------------------------------------
int main(int argc, char* argv[]) {

  // verbosity help msg
  std::string vmessage = "output log verbosity. Can be text:\n\n";
  vmessage += "   LEV_ERROR (least verbose, default), LEV_WARN, \n   LEV_INFO1 (through 5), and LEV_DEBUG1 (through 5).\n\n";
  vmessage += "Or an integer:\n\n   0 (LEV_ERROR equiv) through 11 (LEV_DEBUG5 equiv)\n";

  // parse command line options
  po::options_description desc("Allowed options");
  desc.add_options()
    ("help,h", "produce help message")
    ("include", "print the cyclus include directory")
    ("version", "print cyclus core and dependency versions and quit")
    ("schema", "dump the cyclus master schema including all installed module schemas")
    ("module-schema", po::value<std::string>(), "dump the schema for the named module")
    ("no-model", "only print log entries from cyclus core code")
    ("no-mem", "exclude memory log statement from logger output")
    ("verb,v", po::value<std::string>(), vmessage.c_str())
    ("output-path,o", po::value<std::string>(), "output path")
    ("input-file", po::value<std::string>(), "input file")
    ;

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  po::positional_options_description p;
  p.add("input-file", 1);

  //po::variables_map vm;
  po::store(po::command_line_parser(argc, argv).
            options(desc).positional(p).run(), vm);
  po::notify(vm);

  // setup context
  EventManager em;
  Timer ti;
  Context ctx(&ti, &em);

  // respond to command line args that don't run a simulation
  if (vm.count("help")) {
    std::string err_msg = "Cyclus usage requires an input file.\n";
    err_msg += "Usage:   cyclus [path/to/input/filename]\n";
    std::cout << err_msg << std::endl;
    std::cout << desc << "\n";
    return 0;
  } else if (vm.count("version")) {
    std::cout << "Cyclus Core " << version::core()
              << " (" << version::describe() << ")"
              << "\n\nDependencies:\n";
    std::cout << "   Boost    " << version::boost() << "\n";
    std::cout << "   Coin-Cbc " << version::coincbc() << "\n";
    std::cout << "   Hdf5     " << version::hdf5() << "\n";
    std::cout << "   Sqlite3  " << version::sqlite3() << "\n";
    std::cout << "   xml2     " << version::xml2() << "\n";
    return 0;
  } else if (vm.count("include")) {
    std::cout << Env::GetInstallPath() << "/include/cyclus/\n";
    return 0;
  } else if (vm.count("schema")) {
    try {
      std::cout << "\n" << BuildMasterSchema() << "\n";
    } catch (cyclus::IOError err) {
      std::cout << err.what() << "\n";
    }
    return 0;
  } else if (vm.count("module-schema")) {
    std::string name(vm["module-schema"].as<std::string>());
    try {
      DynamicModule dyn(name);
      Model* m = dyn.ConstructInstance(&ctx);
      std::cout << "<element name=\"" << name << "\">\n";
      std::cout << m->schema();
      std::cout << "</element>\n";
      delete m;
      dyn.CloseLibrary();
    } catch (cyclus::IOError err) {
      std::cout << err.what() << "\n";
    }
    return 0;
  }

  // announce yourself
  std::cout << std::endl;
  std::cout << "|--------------------------------------------|" << std::endl;
  std::cout << "|                  Cyclus                    |" << std::endl;
  std::cout << "|       a nuclear fuel cycle simulator       |" << std::endl;
  std::cout << "|  from the University of Wisconsin-Madison  |" << std::endl;
  std::cout << "|--------------------------------------------|" << std::endl;
  std::cout << std::endl;

  bool success = true;

  if (vm.count("no-model")) {
    Logger::NoModel() = true;
  }

  if (vm.count("no-mem")) {
    Logger::NoMem() = true;
  }

  if (! vm.count("input-file")) {
    std::string err_msg = "Cyclus usage requires an input file.\n";
    err_msg += "Usage:   cyclus [path/to/input/filename]\n";
    std::cout << err_msg << std::endl;
    std::cout << desc << "\n";
    return 0;
  }

  if (vm.count("verb")) {
    std::string v_level = vm["verb"].as<std::string>();
    if (v_level.length() < 3) {
      Logger::ReportLevel() = (LogLevel)strtol(v_level.c_str(), NULL, 10);
    } else {
      Logger::ReportLevel() = Logger::ToLogLevel(v_level);
    }
  }

  // tell ENV the path between the cwd and the cyclus executable
  std::string path = Env::PathBase(argv[0]);
  Env::SetCyclusRelPath(path);

  // read input file and setup simulation
  std::string inputFile = vm["input-file"].as<std::string>();
  XMLFileLoader* loader;
  try {
    loader = new XMLFileLoader(&ctx, inputFile);
    loader->LoadSim();
  } catch (Error e) {
    CLOG(LEV_ERROR) << e.what();
    return 1;
  }

  // Create the output file
  std::string output_path = "cyclus.sqlite";
  try {
    if (vm.count("output-path")){
      output_path = vm["output-path"].as<std::string>();
    }
  } catch (Error ge) {
    CLOG(LEV_ERROR) << ge.what();
    return 1;
  }

  std::string ext = fs::path(output_path).extension().generic_string();
  EventBackend* back;
  if (ext == ".h5") {
    back = new Hdf5Back(output_path.c_str());
  } else if (ext == ".csv") {
    back = new CsvBack(output_path.c_str());
  } else {
    back = new SqliteBack(output_path);
  }
  em.RegisterBackend(back);

  // print the model list
  Model::PrintModelList();

  // Run the simulation
  //try {
    ti.RunSim();
  //} catch (Error err) {
  //  success = false;
  //  CLOG(LEV_ERROR) << err.what();
  //}

  em.close();
  delete back;
  delete loader;

  if (!success) {
    std::cout << std::endl;
    std::cout << "|--------------------------------------------|" << std::endl;
    std::cout << "|                  Cyclus                    |" << std::endl;
    std::cout << "|           run *not* successful             |" << std::endl;
    std::cout << "|--------------------------------------------|" << std::endl;
    std::cout << std::endl;
    return 1;
  }

  std::cout << std::endl;
  std::cout << "|--------------------------------------------|" << std::endl;
  std::cout << "|                  Cyclus                    |" << std::endl;
  std::cout << "|              run successful                |" << std::endl;
  std::cout << "|--------------------------------------------|" << std::endl;
  std::cout << "Output location: " << output_path << std::endl;
  std::cout << "Simulation ID: " << boost::lexical_cast<std::string>(ctx.sim_id()) << std::endl;
  std::cout << std::endl;
  return 0;
}
<commit_msg>fix commented out catch line<commit_after>#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <boost/program_options.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid_io.hpp>

#include "csv_back.h"
#include "cyclus.h"
#include "hdf5_back.h"
#include "sqlite_back.h"
#include "xml_file_loader.h"

namespace po = boost::program_options;
namespace fs = boost::filesystem;

using namespace cyclus;

//-----------------------------------------------------------------------
// Main entry point for the test application...
//-----------------------------------------------------------------------
int main(int argc, char* argv[]) {

  // verbosity help msg
  std::string vmessage = "output log verbosity. Can be text:\n\n";
  vmessage += "   LEV_ERROR (least verbose, default), LEV_WARN, \n   LEV_INFO1 (through 5), and LEV_DEBUG1 (through 5).\n\n";
  vmessage += "Or an integer:\n\n   0 (LEV_ERROR equiv) through 11 (LEV_DEBUG5 equiv)\n";

  // parse command line options
  po::options_description desc("Allowed options");
  desc.add_options()
    ("help,h", "produce help message")
    ("include", "print the cyclus include directory")
    ("version", "print cyclus core and dependency versions and quit")
    ("schema", "dump the cyclus master schema including all installed module schemas")
    ("module-schema", po::value<std::string>(), "dump the schema for the named module")
    ("no-model", "only print log entries from cyclus core code")
    ("no-mem", "exclude memory log statement from logger output")
    ("verb,v", po::value<std::string>(), vmessage.c_str())
    ("output-path,o", po::value<std::string>(), "output path")
    ("input-file", po::value<std::string>(), "input file")
    ;

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  po::positional_options_description p;
  p.add("input-file", 1);

  //po::variables_map vm;
  po::store(po::command_line_parser(argc, argv).
            options(desc).positional(p).run(), vm);
  po::notify(vm);

  // setup context
  EventManager em;
  Timer ti;
  Context ctx(&ti, &em);

  // respond to command line args that don't run a simulation
  if (vm.count("help")) {
    std::string err_msg = "Cyclus usage requires an input file.\n";
    err_msg += "Usage:   cyclus [path/to/input/filename]\n";
    std::cout << err_msg << std::endl;
    std::cout << desc << "\n";
    return 0;
  } else if (vm.count("version")) {
    std::cout << "Cyclus Core " << version::core()
              << " (" << version::describe() << ")"
              << "\n\nDependencies:\n";
    std::cout << "   Boost    " << version::boost() << "\n";
    std::cout << "   Coin-Cbc " << version::coincbc() << "\n";
    std::cout << "   Hdf5     " << version::hdf5() << "\n";
    std::cout << "   Sqlite3  " << version::sqlite3() << "\n";
    std::cout << "   xml2     " << version::xml2() << "\n";
    return 0;
  } else if (vm.count("include")) {
    std::cout << Env::GetInstallPath() << "/include/cyclus/\n";
    return 0;
  } else if (vm.count("schema")) {
    try {
      std::cout << "\n" << BuildMasterSchema() << "\n";
    } catch (cyclus::IOError err) {
      std::cout << err.what() << "\n";
    }
    return 0;
  } else if (vm.count("module-schema")) {
    std::string name(vm["module-schema"].as<std::string>());
    try {
      DynamicModule dyn(name);
      Model* m = dyn.ConstructInstance(&ctx);
      std::cout << "<element name=\"" << name << "\">\n";
      std::cout << m->schema();
      std::cout << "</element>\n";
      delete m;
      dyn.CloseLibrary();
    } catch (cyclus::IOError err) {
      std::cout << err.what() << "\n";
    }
    return 0;
  }

  // announce yourself
  std::cout << std::endl;
  std::cout << "|--------------------------------------------|" << std::endl;
  std::cout << "|                  Cyclus                    |" << std::endl;
  std::cout << "|       a nuclear fuel cycle simulator       |" << std::endl;
  std::cout << "|  from the University of Wisconsin-Madison  |" << std::endl;
  std::cout << "|--------------------------------------------|" << std::endl;
  std::cout << std::endl;

  bool success = true;

  if (vm.count("no-model")) {
    Logger::NoModel() = true;
  }

  if (vm.count("no-mem")) {
    Logger::NoMem() = true;
  }

  if (! vm.count("input-file")) {
    std::string err_msg = "Cyclus usage requires an input file.\n";
    err_msg += "Usage:   cyclus [path/to/input/filename]\n";
    std::cout << err_msg << std::endl;
    std::cout << desc << "\n";
    return 0;
  }

  if (vm.count("verb")) {
    std::string v_level = vm["verb"].as<std::string>();
    if (v_level.length() < 3) {
      Logger::ReportLevel() = (LogLevel)strtol(v_level.c_str(), NULL, 10);
    } else {
      Logger::ReportLevel() = Logger::ToLogLevel(v_level);
    }
  }

  // tell ENV the path between the cwd and the cyclus executable
  std::string path = Env::PathBase(argv[0]);
  Env::SetCyclusRelPath(path);

  // read input file and setup simulation
  std::string inputFile = vm["input-file"].as<std::string>();
  XMLFileLoader* loader;
  try {
    loader = new XMLFileLoader(&ctx, inputFile);
    loader->LoadSim();
  } catch (Error e) {
    CLOG(LEV_ERROR) << e.what();
    return 1;
  }

  // Create the output file
  std::string output_path = "cyclus.sqlite";
  try {
    if (vm.count("output-path")){
      output_path = vm["output-path"].as<std::string>();
    }
  } catch (Error ge) {
    CLOG(LEV_ERROR) << ge.what();
    return 1;
  }

  std::string ext = fs::path(output_path).extension().generic_string();
  EventBackend* back;
  if (ext == ".h5") {
    back = new Hdf5Back(output_path.c_str());
  } else if (ext == ".csv") {
    back = new CsvBack(output_path.c_str());
  } else {
    back = new SqliteBack(output_path);
  }
  em.RegisterBackend(back);

  // print the model list
  Model::PrintModelList();

  // Run the simulation
  try {
    ti.RunSim();
  } catch (Error err) {
    success = false;
    CLOG(LEV_ERROR) << err.what();
  }

  em.close();
  delete back;
  delete loader;

  if (!success) {
    std::cout << std::endl;
    std::cout << "|--------------------------------------------|" << std::endl;
    std::cout << "|                  Cyclus                    |" << std::endl;
    std::cout << "|           run *not* successful             |" << std::endl;
    std::cout << "|--------------------------------------------|" << std::endl;
    std::cout << std::endl;
    return 1;
  }

  std::cout << std::endl;
  std::cout << "|--------------------------------------------|" << std::endl;
  std::cout << "|                  Cyclus                    |" << std::endl;
  std::cout << "|              run successful                |" << std::endl;
  std::cout << "|--------------------------------------------|" << std::endl;
  std::cout << "Output location: " << output_path << std::endl;
  std::cout << "Simulation ID: " << boost::lexical_cast<std::string>(ctx.sim_id()) << std::endl;
  std::cout << std::endl;
  return 0;
}
<|endoftext|>


<commit_before>#include "TKDPDF.h"
#include "TKDNodeInfo.h"

#include "TClonesArray.h"
#include "TTree.h"
#include "TH2.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TBox.h"
#include "TGraph.h"
#include "TMarker.h"

ClassImp(TKDPDF)

//_________________________________________________________________
TKDPDF::TKDPDF() :
  TKDTreeIF()
  ,TKDInterpolatorBase()
{
// Default constructor. To be used with care since in this case building
// of data structure is completly left to the user responsability.
}

//_________________________________________________________________
TKDPDF::TKDPDF(Int_t npoints, Int_t ndim, UInt_t bsize, Float_t **data) :
  TKDTreeIF(npoints, ndim, bsize, data)
  ,TKDInterpolatorBase(ndim)
{
// Wrapper constructor for the TKDTree.

  Build();
}

//_________________________________________________________________
TKDPDF::TKDPDF(TTree *t, const Char_t *var, const Char_t *cut, UInt_t bsize, Long64_t nentries, Long64_t firstentry) :
  TKDTreeIF()
  ,TKDInterpolatorBase()
{
// Alocate data from a tree. The variables which have to be analysed are
// defined in the "var" parameter as a colon separated list. The format should
// be identical to that used by TTree::Draw().
//
//

  TObjArray *vars = TString(var).Tokenize(":");
  fNDim = vars->GetEntriesFast(); fNDimm = 2*fNDim;
  fNSize = fNDim;
  if(fNDim > 6/*kDimMax*/) Warning("TKDPDF(TTree*, const Char_t, const Char_t, UInt_t)", Form("Variable number exceed maximum dimension %d. Results are unpredictable.", 6/*kDimMax*/));
  fBucketSize = bsize;

  Int_t np;
  Double_t *v;
  for(int idim=0; idim<fNDim; idim++){
    if(!(np = t->Draw(((TObjString*)(*vars)[idim])->GetName(), cut, "goff", nentries, firstentry))){
      Warning("TKDPDF(TTree*, const Char_t, const Char_t, UInt_t)", Form("Can not access data for keys %s. Key defined on tree :", ((TObjString*)(*vars)[idim])->GetName() ));
      TIterator *it = (t->GetListOfLeaves())->MakeIterator();
      TObject *o;
      while((o = (*it)())) printf("\t%s\n", o->GetName());
      continue;
    }
    if(!fNPoints){
      fNPoints = np;
      //Info("TKDPDF(TTree*, const Char_t, const Char_t, UInt_t)", Form("Allocating %d data points in %d dimensions.", fNpoints, fNDim));
      fData = new Float_t*[fNDim];
      for(int idim=0; idim<fNDim; idim++) fData[idim] = new Float_t[fNPoints];
      fDataOwner = kTRUE;
    }
    v = t->GetV1();
    for(int ip=0; ip<fNPoints; ip++) fData[idim][ip] = (Float_t)v[ip];
  }
  TKDTreeIF::Build();
  Build();
}

//_________________________________________________________________
TKDPDF::~TKDPDF()
{
}

//_________________________________________________________________
void TKDPDF::Build(Int_t)
{
// Fill interpolator's data array i.e.
//  - estimation points
//  - corresponding PDF values

  fNTNodes = fNPoints/fBucketSize + ((fNPoints%fBucketSize)?1:0);/*TKDTreeIF::GetNTNodes();*/
  if(!fBoundaries) MakeBoundaries();
  fLambda = 1 + fNDim + (fNDim*(fNDim+1)>>1);
  //printf("after MakeBoundaries() %d\n", memory());

  // allocate interpolation nodes
  TKDInterpolatorBase::Build(fNTNodes);

  TKDNodeInfo *node = 0x0;
  Float_t *bounds = 0x0;
  Int_t *indexPoints;
  for(int inode=0, tnode = fNNodes; inode<fNTNodes-1; inode++, tnode++){
    node = (TKDNodeInfo*)(*fTNodes)[inode];
    node->Val()[0] =  Float_t(fBucketSize)/fNPoints;
    bounds = GetBoundary(tnode);
    for(int idim=0; idim<fNDim; idim++) node->Val()[0] /= (bounds[2*idim+1] - bounds[2*idim]);
    node->Val()[1] =  node->Val()[0]/TMath::Sqrt(float(fBucketSize));

    indexPoints = GetPointsIndexes(tnode);
    // loop points in this terminal node
    for(int idim=0; idim<fNDim; idim++){
      node->Data()[idim] = 0.;
      for(int ip = 0; ip<fBucketSize; ip++) node->Data()[idim] += fData[idim][indexPoints[ip]];
      node->Data()[idim] /= fBucketSize;
    }
    memcpy(&(node->Data()[fNDim]), bounds, fNDimm*sizeof(Float_t));
  }

  // analyze last (incomplete) terminal node
  Int_t counts = fNPoints%fBucketSize;
  counts = counts ? counts : fBucketSize;
  Int_t inode = fNTNodes - 1, tnode = inode + fNNodes;
  node = (TKDNodeInfo*)(*fTNodes)[inode];
  node->Val()[0] =  Float_t(counts)/fNPoints;
  bounds = GetBoundary(tnode);
  for(int idim=0; idim<fNDim; idim++) node->Val()[0] /= (bounds[2*idim+1] - bounds[2*idim]);
  node->Val()[1] =  node->Val()[0]/TMath::Sqrt(float(counts));

  // loop points in this terminal node
  indexPoints = GetPointsIndexes(tnode);
  for(int idim=0; idim<fNDim; idim++){
    node->Data()[idim] = 0.;
    for(int ip = 0; ip<counts; ip++) node->Data()[idim] += fData[idim][indexPoints[ip]];
    node->Data()[idim] /= counts;
  }
  memcpy(&(node->Data()[fNDim]), bounds, fNDimm*sizeof(Float_t));

  delete [] fBoundaries;
  fBoundaries = 0x0;
}

//_________________________________________________________________
void TKDPDF::DrawNode(Int_t tnode, UInt_t ax1, UInt_t ax2)
{
// Draw node "node" and the data points within.
//
// Observation:
// This function creates some graphical objects
// but don't delete it. Abusing this function may cause memory leaks !

  if(tnode < 0 || tnode >= fNTNodes){
    Warning("DrawNode()", Form("Terminal node %d outside defined range.", tnode));
    return;
  }

  Int_t inode = tnode;
  tnode += fNNodes;
  // select zone of interest in the indexes array
  Int_t *index = GetPointsIndexes(tnode);
  Int_t nPoints = (tnode == 2*fNNodes) ? fNPoints%fBucketSize : fBucketSize;

  // draw data points
  TGraph *g = new TGraph(nPoints);
  g->SetMarkerStyle(7);
  for(int ip = 0; ip<nPoints; ip++) g->SetPoint(ip, fData[ax1][index[ip]], fData[ax2][index[ip]]);

  // draw estimation point
  TKDNodeInfo *node = (TKDNodeInfo*)(*fTNodes)[inode];
  TMarker *m=new TMarker(node->Data()[ax1], node->Data()[ax2], 20);
  m->SetMarkerColor(2);
  m->SetMarkerSize(1.7);

  // draw node contour
  Float_t *bounds = GetBoundary(tnode);
  TBox *n = new TBox(bounds[2*ax1], bounds[2*ax2], bounds[2*ax1+1], bounds[2*ax2+1]);
  n->SetFillStyle(0);

  g->Draw("ap");
  m->Draw();
  n->Draw();

  return;
}

<commit_msg>fix warning (thanks Federico)<commit_after>#include "TKDPDF.h"
#include "TKDNodeInfo.h"

#include "TClonesArray.h"
#include "TTree.h"
#include "TH2.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TBox.h"
#include "TGraph.h"
#include "TMarker.h"

ClassImp(TKDPDF)

//_________________________________________________________________
TKDPDF::TKDPDF() :
  TKDTreeIF()
  ,TKDInterpolatorBase()
{
// Default constructor. To be used with care since in this case building
// of data structure is completly left to the user responsability.
}

//_________________________________________________________________
TKDPDF::TKDPDF(Int_t npoints, Int_t ndim, UInt_t bsize, Float_t **data) :
  TKDTreeIF(npoints, ndim, bsize, data)
  ,TKDInterpolatorBase(ndim)
{
// Wrapper constructor for the TKDTree.

  Build();
}

//_________________________________________________________________
TKDPDF::TKDPDF(TTree *t, const Char_t *var, const Char_t *cut, UInt_t bsize, Long64_t nentries, Long64_t firstentry) :
  TKDTreeIF()
  ,TKDInterpolatorBase()
{
// Alocate data from a tree. The variables which have to be analysed are
// defined in the "var" parameter as a colon separated list. The format should
// be identical to that used by TTree::Draw().
//
//

  TObjArray *vars = TString(var).Tokenize(":");
  fNDim = vars->GetEntriesFast(); fNDimm = 2*fNDim;
  fNSize = fNDim;
  if(fNDim > 6/*kDimMax*/) Warning("TKDPDF(TTree*, const Char_t, const Char_t, UInt_t)", Form("Variable number exceed maximum dimension %d. Results are unpredictable.", 6/*kDimMax*/));
  fBucketSize = bsize;

  Int_t np;
  Double_t *v;
  for(int idim=0; idim<fNDim; idim++){
    if(!(np = t->Draw(((TObjString*)(*vars)[idim])->GetName(), cut, "goff", nentries, firstentry))){
      Warning("TKDPDF(TTree*, const Char_t, const Char_t, UInt_t)", Form("Can not access data for keys %s. Key defined on tree :", ((TObjString*)(*vars)[idim])->GetName() ));
      TIterator *it = (t->GetListOfLeaves())->MakeIterator();
      TObject *o;
      while((o = (*it)())) printf("\t%s\n", o->GetName());
      continue;
    }
    if(!fNPoints){
      fNPoints = np;
      //Info("TKDPDF(TTree*, const Char_t, const Char_t, UInt_t)", Form("Allocating %d data points in %d dimensions.", fNpoints, fNDim));
      fData = new Float_t*[fNDim];
      for(int jdim=fNDim; jdim--;) fData[jdim] = new Float_t[fNPoints];
      fDataOwner = kTRUE;
    }
    v = t->GetV1();
    for(int ip=0; ip<fNPoints; ip++) fData[idim][ip] = (Float_t)v[ip];
  }
  TKDTreeIF::Build();
  Build();
}

//_________________________________________________________________
TKDPDF::~TKDPDF()
{
}

//_________________________________________________________________
void TKDPDF::Build(Int_t)
{
// Fill interpolator's data array i.e.
//  - estimation points
//  - corresponding PDF values

  fNTNodes = fNPoints/fBucketSize + ((fNPoints%fBucketSize)?1:0);/*TKDTreeIF::GetNTNodes();*/
  if(!fBoundaries) MakeBoundaries();
  fLambda = 1 + fNDim + (fNDim*(fNDim+1)>>1);
  //printf("after MakeBoundaries() %d\n", memory());

  // allocate interpolation nodes
  TKDInterpolatorBase::Build(fNTNodes);

  TKDNodeInfo *node = 0x0;
  Float_t *bounds = 0x0;
  Int_t *indexPoints;
  for(int inode=0, tnode = fNNodes; inode<fNTNodes-1; inode++, tnode++){
    node = (TKDNodeInfo*)(*fTNodes)[inode];
    node->Val()[0] =  Float_t(fBucketSize)/fNPoints;
    bounds = GetBoundary(tnode);
    for(int idim=0; idim<fNDim; idim++) node->Val()[0] /= (bounds[2*idim+1] - bounds[2*idim]);
    node->Val()[1] =  node->Val()[0]/TMath::Sqrt(float(fBucketSize));

    indexPoints = GetPointsIndexes(tnode);
    // loop points in this terminal node
    for(int idim=0; idim<fNDim; idim++){
      node->Data()[idim] = 0.;
      for(int ip = 0; ip<fBucketSize; ip++) node->Data()[idim] += fData[idim][indexPoints[ip]];
      node->Data()[idim] /= fBucketSize;
    }
    memcpy(&(node->Data()[fNDim]), bounds, fNDimm*sizeof(Float_t));
  }

  // analyze last (incomplete) terminal node
  Int_t counts = fNPoints%fBucketSize;
  counts = counts ? counts : fBucketSize;
  Int_t inode = fNTNodes - 1, tnode = inode + fNNodes;
  node = (TKDNodeInfo*)(*fTNodes)[inode];
  node->Val()[0] =  Float_t(counts)/fNPoints;
  bounds = GetBoundary(tnode);
  for(int idim=0; idim<fNDim; idim++) node->Val()[0] /= (bounds[2*idim+1] - bounds[2*idim]);
  node->Val()[1] =  node->Val()[0]/TMath::Sqrt(float(counts));

  // loop points in this terminal node
  indexPoints = GetPointsIndexes(tnode);
  for(int idim=0; idim<fNDim; idim++){
    node->Data()[idim] = 0.;
    for(int ip = 0; ip<counts; ip++) node->Data()[idim] += fData[idim][indexPoints[ip]];
    node->Data()[idim] /= counts;
  }
  memcpy(&(node->Data()[fNDim]), bounds, fNDimm*sizeof(Float_t));

  delete [] fBoundaries;
  fBoundaries = 0x0;
}

//_________________________________________________________________
void TKDPDF::DrawNode(Int_t tnode, UInt_t ax1, UInt_t ax2)
{
// Draw node "node" and the data points within.
//
// Observation:
// This function creates some graphical objects
// but don't delete it. Abusing this function may cause memory leaks !

  if(tnode < 0 || tnode >= fNTNodes){
    Warning("DrawNode()", Form("Terminal node %d outside defined range.", tnode));
    return;
  }

  Int_t inode = tnode;
  tnode += fNNodes;
  // select zone of interest in the indexes array
  Int_t *index = GetPointsIndexes(tnode);
  Int_t nPoints = (tnode == 2*fNNodes) ? fNPoints%fBucketSize : fBucketSize;

  // draw data points
  TGraph *g = new TGraph(nPoints);
  g->SetMarkerStyle(7);
  for(int ip = 0; ip<nPoints; ip++) g->SetPoint(ip, fData[ax1][index[ip]], fData[ax2][index[ip]]);

  // draw estimation point
  TKDNodeInfo *node = (TKDNodeInfo*)(*fTNodes)[inode];
  TMarker *m=new TMarker(node->Data()[ax1], node->Data()[ax2], 20);
  m->SetMarkerColor(2);
  m->SetMarkerSize(1.7);

  // draw node contour
  Float_t *bounds = GetBoundary(tnode);
  TBox *n = new TBox(bounds[2*ax1], bounds[2*ax2], bounds[2*ax1+1], bounds[2*ax2+1]);
  n->SetFillStyle(0);

  g->Draw("ap");
  m->Draw();
  n->Draw();

  return;
}

<|endoftext|>


<commit_before>#include <iostream>
#include "sockets/SocketW.h"
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include "buffer.h"
#include "user.h"
#include "string.h"

#define BUFLEN 1000000

int get_empty( user ** list, int amount ) {
  for (int i = 0; i < amount; i++ ){
    if (!list[i]->is_connected){return i;}
  }
  return -1;
}

int main( int argc, char * argv[] ) {
  if (argc < 4) {
    std::cout << "usage: " << argv[0] << " buffers_count total_buffersize max_clients" << std::endl;
    return 1;
  }
  int buffers = atoi(argv[1]);
  int total_buffersize = atoi(argv[2]);
  int connections = atoi(argv[3]);
  int size_per_buffer = total_buffersize/buffers;
  std::cout << "Size per buffer: " << size_per_buffer << std::endl;
  buffer ** ringbuf = (buffer**) calloc (buffers,sizeof(buffer*));
  for (int i = 0; i < buffers; i ++ ) {
    ringbuf[i] = new buffer;
    ringbuf[i]->data = (char*) malloc(size_per_buffer);
  }
  std::cout << "Successfully allocated " << total_buffersize << " bytes total buffer." << std::endl;
  user ** connectionList = (user**) calloc (connections,sizeof(user*));
  for (int i = 0; i < connections; i++) { connectionList[i] = new user; }
  char header[13];//FLV header is always 13 bytes
  int ret = 0;
  int frame_bodylength = 0;
  int current_buffer = 0;
  int open_connection = -1;
  int lastproper = 0;//last properly finished buffer number
  unsigned int loopcount = 0;
  SWUnixSocket listener;
  SWBaseSocket * incoming = 0;
  SWBaseSocket::SWBaseError BError;
  //read FLV header - 13 bytes
  ret = fread(&header,1,13,stdin);
  //TODO: check ret?

  listener.bind("/tmp/socketfile");
  listener.listen();
  listener.set_timeout(0,50000);

  //TODO: not while true, but while running - set running to false when kill signal is received!
  while(true) {
    loopcount ++;
    //invalidate the current buffer
    ringbuf[current_buffer]->size = 0;
    ringbuf[current_buffer]->number = -1;
    if (std::cin.peek() == 'F') {
      //new FLV file, read the file head again.
      ret = fread(&header,1,13,stdin);
    } else {
      //read FLV frame header - 11 bytes
      ret = fread(ringbuf[current_buffer]->data,1,11,stdin);
      //TODO: Check ret?
      //if video frame? (id 9) check for incoming connections
      if (ringbuf[current_buffer]->data[0] == 9) {
        incoming = listener.accept(&BError);
        if (incoming){
          open_connection = get_empty(connectionList,connections);
          if (open_connection != -1) {
            connectionList[open_connection]->connect(incoming);
            //send the FLV header
            std::cout << "Client " << open_connection << " connected." << std::endl;
            connectionList[open_connection]->MyBuffer = lastproper;
            connectionList[open_connection]->MyBuffer_num = ringbuf[lastproper]->number;
            //TODO: Do this more nicely?
            if (connectionList[open_connection]->Conn->send(&header[0],13,NULL) != 13){
              connectionList[open_connection]->disconnect();
              std::cout << "Client " << open_connection << " failed to receive the header!" << std::endl;
            }
            std::cout << "Client " << open_connection << " received header!" << std::endl;
          }else{
            std::cout << "New client not connected: no more connections!" << std::endl;
          }
        }
      }
      //calculate body length of frame
      frame_bodylength = 4;
      frame_bodylength += ringbuf[current_buffer]->data[3];
      frame_bodylength += (ringbuf[current_buffer]->data[2] << 8);
      frame_bodylength += (ringbuf[current_buffer]->data[1] << 16);
      //read the rest of the frame
      ret = fread(&ringbuf[current_buffer]->data[11],1,frame_bodylength,stdin);
      //TODO: Check ret?
      ringbuf[current_buffer]->size = frame_bodylength + 11;
      ringbuf[current_buffer]->number = loopcount;
      //send all connections what they need, if and when they need it
      for (int i = 0; i < connections; i++) {connectionList[i]->Send(ringbuf, buffers);}
      //keep track of buffers
      lastproper = current_buffer;
      current_buffer++;
      current_buffer %= buffers;
    }
  }

  // disconnect listener
  listener.disconnect();
  //TODO: cleanup
  return 0;
}
<commit_msg>Filtering metadata<commit_after>#include <iostream>
#include "sockets/SocketW.h"
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include "buffer.h"
#include "user.h"
#include "string.h"

#define BUFLEN 1000000

int get_empty( user ** list, int amount ) {
  for (int i = 0; i < amount; i++ ){
    if (!list[i]->is_connected){return i;}
  }
  return -1;
}

int main( int argc, char * argv[] ) {
  if (argc < 4) {
    std::cout << "usage: " << argv[0] << " buffers_count total_buffersize max_clients" << std::endl;
    return 1;
  }
  int buffers = atoi(argv[1]);
  int total_buffersize = atoi(argv[2]);
  int connections = atoi(argv[3]);
  int size_per_buffer = total_buffersize/buffers;
  std::cout << "Size per buffer: " << size_per_buffer << std::endl;
  buffer ** ringbuf = (buffer**) calloc (buffers,sizeof(buffer*));
  for (int i = 0; i < buffers; i ++ ) {
    ringbuf[i] = new buffer;
    ringbuf[i]->data = (char*) malloc(size_per_buffer);
  }
  std::cout << "Successfully allocated " << total_buffersize << " bytes total buffer." << std::endl;
  user ** connectionList = (user**) calloc (connections,sizeof(user*));
  for (int i = 0; i < connections; i++) { connectionList[i] = new user; }
  char header[13];//FLV header is always 13 bytes
  char metadata[BUFLEN];
  int ret = 0;
  int frame_bodylength = 0;
  int current_buffer = 0;
  int open_connection = -1;
  int lastproper = 0;//last properly finished buffer number
  unsigned int loopcount = 0;
  SWUnixSocket listener;
  SWBaseSocket * incoming = 0;
  SWBaseSocket::SWBaseError BError;
  //read FLV header - 13 bytes
  ret = fread(&header,1,13,stdin);
  //TODO: check ret?

  listener.bind("/tmp/socketfile");
  listener.listen();
  listener.set_timeout(0,50000);

  //TODO: not while true, but while running - set running to false when kill signal is received!
  while(true) {
    loopcount ++;
    //invalidate the current buffer
    ringbuf[current_buffer]->size = 0;
    ringbuf[current_buffer]->number = -1;
    if (std::cin.peek() == 'F') {
      //new FLV file, read the file header again.
      ret = fread(&header,1,13,stdin);
    } else if( (int)std::cin.peek() == 12) {
      //metadata encountered, let's filter it
      ret = fread(&metadata,1,11,stdin);
      frame_bodylength = 4;
      frame_bodylength += metadata[3];
      frame_bodylength += (metadata[2] << 8);
      frame_bodylength += (metadata[1] << 16);
      ret = fread(&metadata,1,frame_bodylength,stdin);
    } else {
      //read FLV frame header - 11 bytes
      ret = fread(ringbuf[current_buffer]->data,1,11,stdin);
      //TODO: Check ret?
      //if video frame? (id 9) check for incoming connections
      if (ringbuf[current_buffer]->data[0] == 9) {
        incoming = listener.accept(&BError);
        if (incoming){
          open_connection = get_empty(connectionList,connections);
          if (open_connection != -1) {
            connectionList[open_connection]->connect(incoming);
            //send the FLV header
            std::cout << "Client " << open_connection << " connected." << std::endl;
            connectionList[open_connection]->MyBuffer = lastproper;
            connectionList[open_connection]->MyBuffer_num = ringbuf[lastproper]->number;
            //TODO: Do this more nicely?
            if (connectionList[open_connection]->Conn->send(&header[0],13,NULL) != 13){
              connectionList[open_connection]->disconnect();
              std::cout << "Client " << open_connection << " failed to receive the header!" << std::endl;
            }
            std::cout << "Client " << open_connection << " received header!" << std::endl;
          }else{
            std::cout << "New client not connected: no more connections!" << std::endl;
          }
        }
      }
      //calculate body length of frame
      frame_bodylength = 4;
      frame_bodylength += ringbuf[current_buffer]->data[3];
      frame_bodylength += (ringbuf[current_buffer]->data[2] << 8);
      frame_bodylength += (ringbuf[current_buffer]->data[1] << 16);
      //read the rest of the frame
      ret = fread(&ringbuf[current_buffer]->data[11],1,frame_bodylength,stdin);
      //TODO: Check ret?
      ringbuf[current_buffer]->size = frame_bodylength + 11;
      ringbuf[current_buffer]->number = loopcount;
      //send all connections what they need, if and when they need it
      for (int i = 0; i < connections; i++) {connectionList[i]->Send(ringbuf, buffers);}
      //keep track of buffers
      lastproper = current_buffer;
      current_buffer++;
      current_buffer %= buffers;
    }
  }

  // disconnect listener
  listener.disconnect();
  //TODO: cleanup
  return 0;
}
<|endoftext|>


<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 Module:       FGKinemat.cpp
 Author:       Tony Peden, for flight control system authored by Jon S. Berndt
 Date started: 12/02/01

 ------------- Copyright (C) 2000 Anthony K. Peden -------------

 This program 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 2 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 General Public License for more
 details.

 You should have received a copy of the GNU General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------

HISTORY
--------------------------------------------------------------------------------

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES,  and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include "FGKinemat.h"

static const char *IdSrc = "$Id: FGKinemat.cpp,v 1.1 2001/12/02 16:02:09 apeden Exp $";
static const char *IdHdr = ID_FLAPS;

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

FGKinemat::FGKinemat(FGFCS* fcs, FGConfigFile* AC_cfg) : FGFCSComponent(fcs),
AC_cfg(AC_cfg) {
  string token;
  double tmpDetent;
  double tmpTime;

  Detents.clear();
  TransitionTimes.clear();

  Type = AC_cfg->GetValue("TYPE");
  Name = AC_cfg->GetValue("NAME");
  AC_cfg->GetNextConfigLine();

  while ((token = AC_cfg->GetValue()) != string("/COMPONENT")) {
    *AC_cfg >> token;
    if (token == "ID") {
      *AC_cfg >> ID;
    } else if (token == "INPUT") {
      token = AC_cfg->GetValue("INPUT");
      if (token.find("FG_") != token.npos) {
        *AC_cfg >> token;
        InputIdx = fcs->GetState()->GetParameterIndex(token);
        InputType = itPilotAC;
      }
    } else if ( token == "DETENTS" ) {
      *AC_cfg >> NumDetents;
      for(int i=0;i<NumDetents;i++) {
        *AC_cfg >> tmpDetent;
        *AC_cfg >> tmpTime;
        Detents.push_back(tmpDetent);
        TransitionTimes.push_back(tmpTime);
      }
    } else if (token == "OUTPUT") {

      IsOutput = true;
      *AC_cfg >> sOutputIdx;
      OutputIdx = fcs->GetState()->GetParameterIndex(sOutputIdx);
    }
  }

  if (debug_lvl > 1) {
    cout << "      ID: " << ID << endl;
    cout << "      INPUT: " << InputIdx << endl;
    cout << "      DETENTS: " << NumDetents << endl;
    for(int i=0;i<NumDetents;i++) {
      cout << "        " << Detents[i] << " " << TransitionTimes[i] << endl;
    }
    if (IsOutput) cout << "      OUTPUT: " <<sOutputIdx << endl;
  }

  if (debug_lvl & 2) cout << "Instantiated: FGKinemat" << endl;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGKinemat::~FGKinemat()
{
  if (debug_lvl & 2) cout << "Destroyed:    FGKinemat" << endl;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGKinemat::Run(void ) {
  double dt=fcs->GetState()->Getdt();
  double output_transit_rate=0;

  FGFCSComponent::Run(); // call the base class for initialization of Input
  InputCmd = Input*Detents[NumDetents-1];
  OutputPos = fcs->GetState()->GetParameter(OutputIdx);

  if(InputCmd < Detents[0]) {
    fi=0;
    InputCmd=Detents[0];
    lastInputCmd=InputCmd;
    OutputPos=Detents[0];
    Output=OutputPos;
  } else if(InputCmd > Detents[NumDetents-1]) {
    fi=NumDetents-1;
    InputCmd=Detents[fi];
    lastInputCmd=InputCmd;
    OutputPos=Detents[fi];
    Output=OutputPos;
  } else {
    //cout << "FGKinemat::Run Handle: " << InputCmd << " Position: " << OutputPos << endl;
    if(dt <= 0)
      OutputPos=InputCmd;
    else {
      if(InputCmd != lastInputCmd) {

        InTransit=1;
      }
      if(InTransit) {

        //fprintf(stderr,"InputCmd: %g, OutputPos: %g\n",InputCmd,OutputPos);
        fi=0;
        while(Detents[fi] < InputCmd) {
          fi++;
        }
        if(OutputPos < InputCmd) {
          if(TransitionTimes[fi] > 0)
            output_transit_rate=(Detents[fi] - Detents[fi-1])/TransitionTimes[fi];
          else
            output_transit_rate=(Detents[fi] - Detents[fi-1])/5;
        } else {
          if(TransitionTimes[fi+1] > 0)
            output_transit_rate=(Detents[fi] - Detents[fi+1])/TransitionTimes[fi+1];
          else
            output_transit_rate=(Detents[fi] - Detents[fi+1])/5;
        }
        if(fabs(OutputPos - InputCmd) > dt*output_transit_rate)
          OutputPos+=output_transit_rate*dt;
        else {
          InTransit=0;
          OutputPos=InputCmd;
        }
      }
    }
    lastInputCmd=InputCmd;
    Output=OutputPos;
  }
  //cout << "FGKinemat::Run Handle: " << InputCmd << " Position: " << OutputPos << " Output: " << Output << endl;
  if (IsOutput) {
    //cout << "Calling SetOutput()" << endl;
    SetOutput();
  }
  //cout << "Out FGKinemat::Run" << endl;
  return true;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGKinemat::Debug(void)
{
    //TODO: Add your source code here
}

<commit_msg>Small fix in class FGKinemat to output component parameters like the rest of the classes<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 Module:       FGKinemat.cpp
 Author:       Tony Peden, for flight control system authored by Jon S. Berndt
 Date started: 12/02/01

 ------------- Copyright (C) 2000 Anthony K. Peden -------------

 This program 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 2 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 General Public License for more
 details.

 You should have received a copy of the GNU General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------

HISTORY
--------------------------------------------------------------------------------

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES,  and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include "FGKinemat.h"

static const char *IdSrc = "$Id: FGKinemat.cpp,v 1.2 2001/12/09 15:26:50 jberndt Exp $";
static const char *IdHdr = ID_FLAPS;

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

FGKinemat::FGKinemat(FGFCS* fcs, FGConfigFile* AC_cfg) : FGFCSComponent(fcs),
AC_cfg(AC_cfg) {
  string token;
  double tmpDetent;
  double tmpTime;

  Detents.clear();
  TransitionTimes.clear();

  Type = AC_cfg->GetValue("TYPE");
  Name = AC_cfg->GetValue("NAME");
  AC_cfg->GetNextConfigLine();

  while ((token = AC_cfg->GetValue()) != string("/COMPONENT")) {
    *AC_cfg >> token;
    if (token == "ID") {
      *AC_cfg >> ID;
    } else if (token == "INPUT") {
      token = AC_cfg->GetValue("INPUT");
      if (token.find("FG_") != token.npos) {
        *AC_cfg >> token;
        InputIdx = fcs->GetState()->GetParameterIndex(token);
        InputType = itPilotAC;
      }
    } else if ( token == "DETENTS" ) {
      *AC_cfg >> NumDetents;
      for(int i=0;i<NumDetents;i++) {
        *AC_cfg >> tmpDetent;
        *AC_cfg >> tmpTime;
        Detents.push_back(tmpDetent);
        TransitionTimes.push_back(tmpTime);
      }
    } else if (token == "OUTPUT") {

      IsOutput = true;
      *AC_cfg >> sOutputIdx;
      OutputIdx = fcs->GetState()->GetParameterIndex(sOutputIdx);
    }
  }

  if (debug_lvl > 0) {
    cout << "      ID: " << ID << endl;
    cout << "      INPUT: " << InputIdx << endl;
    cout << "      DETENTS: " << NumDetents << endl;
    for(int i=0;i<NumDetents;i++) {
      cout << "        " << Detents[i] << " " << TransitionTimes[i] << endl;
    }
    if (IsOutput) cout << "      OUTPUT: " <<sOutputIdx << endl;
  }

  if (debug_lvl & 2) cout << "Instantiated: FGKinemat" << endl;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGKinemat::~FGKinemat()
{
  if (debug_lvl & 2) cout << "Destroyed:    FGKinemat" << endl;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGKinemat::Run(void ) {
  double dt=fcs->GetState()->Getdt();
  double output_transit_rate=0;

  FGFCSComponent::Run(); // call the base class for initialization of Input
  InputCmd = Input*Detents[NumDetents-1];
  OutputPos = fcs->GetState()->GetParameter(OutputIdx);

  if(InputCmd < Detents[0]) {
    fi=0;
    InputCmd=Detents[0];
    lastInputCmd=InputCmd;
    OutputPos=Detents[0];
    Output=OutputPos;
  } else if(InputCmd > Detents[NumDetents-1]) {
    fi=NumDetents-1;
    InputCmd=Detents[fi];
    lastInputCmd=InputCmd;
    OutputPos=Detents[fi];
    Output=OutputPos;
  } else {
    //cout << "FGKinemat::Run Handle: " << InputCmd << " Position: " << OutputPos << endl;
    if(dt <= 0)
      OutputPos=InputCmd;
    else {
      if(InputCmd != lastInputCmd) {

        InTransit=1;
      }
      if(InTransit) {

        //fprintf(stderr,"InputCmd: %g, OutputPos: %g\n",InputCmd,OutputPos);
        fi=0;
        while(Detents[fi] < InputCmd) {
          fi++;
        }
        if(OutputPos < InputCmd) {
          if(TransitionTimes[fi] > 0)
            output_transit_rate=(Detents[fi] - Detents[fi-1])/TransitionTimes[fi];
          else
            output_transit_rate=(Detents[fi] - Detents[fi-1])/5;
        } else {
          if(TransitionTimes[fi+1] > 0)
            output_transit_rate=(Detents[fi] - Detents[fi+1])/TransitionTimes[fi+1];
          else
            output_transit_rate=(Detents[fi] - Detents[fi+1])/5;
        }
        if(fabs(OutputPos - InputCmd) > dt*output_transit_rate)
          OutputPos+=output_transit_rate*dt;
        else {
          InTransit=0;
          OutputPos=InputCmd;
        }
      }
    }
    lastInputCmd=InputCmd;
    Output=OutputPos;
  }
  //cout << "FGKinemat::Run Handle: " << InputCmd << " Position: " << OutputPos << " Output: " << Output << endl;
  if (IsOutput) {
    //cout << "Calling SetOutput()" << endl;
    SetOutput();
  }
  //cout << "Out FGKinemat::Run" << endl;
  return true;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGKinemat::Debug(void)
{
    //TODO: Add your source code here
}

<|endoftext|>


<commit_before>/*

|-------SS---EGG---CATCHER---GAME---C++---BY---SREYAS------------------|
|                                                                      |
|                Author:Console-Gamers(Sreyas and Anandu)              |
|                Use A and D to move                                   |
|   		           10 Score for each egg                                 |
|                                                                      |
|----------------------------------------------------------------------|

*/
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<dos.h>

int gameover = 0,x,y,width,height,bx,by,score=0;
enum DIRECTION
{
LEFT,RIGHT
}dir;

void setup()
{
 int i,j;

 clrscr();
 cout<<"\t\t||||SCORE|||||: " <<score<<endl<<"Hint:Press x to close the game"<<endl;
 for(i=0;i<=height;i++)
 {

  for(j=0;j<=width;j++)
  {
    if(i==y&&j==width-2)
    cout<<"#";

    else if(i==0||i==height||j==0||j==width)
    {

     if(i==y&&j==width)
     continue;

     else
      cout<<"#";

    }

    else
    if(i==y&&j==x)
    {
      cout<<"|_|";
    }

    else
    if(i==by&&j==bx)
    {
     cout<<"O";
    }

    else
    {
     cout<<" ";
    }

  }
 cout<<endl;
 }

}

//createblock()

void createblock()
{
 bx=random(width-1)+5;
 by=0;//random(y-3);
 //if(bx<x+5||bx>x+5) createblock();
}

void moveblockdown()
{

 by++;

 if(by==y&&(x==bx||x==bx+1||x==bx-1||x==bx-2||x==bx+2))
 {
 score+=10;
 createblock();

 }

 if(x<=0)
 {
  x = width - 3;
 }

 else if(x>=width-2)
 {
  x = 1;
 }

}

void getkey()
{
 if(kbhit())
 {

  switch(getch())
  {
   case 'd':
   x+=2;//dir  = RIGHT;
   break;
   case 'a':
   x-=2;//dir  = LEFT;
   break;
   case 'x':
   gameover  = 1;
   break;
  }

 }

}

void mover()
{

 switch(dir)
 {
  case LEFT:
  x--;
  break;
  case RIGHT:
  x++;
  break;
 }

}

void main()
{

 clrscr();
 width = 45;
 height = 20;

 y = height-2;//height/2;
 x = width/2;

 setup();

 while(!gameover)
 {
  delay(150);
  setup();
  //mover();
  getkey();
  createblock();

  while(by!=20&&!gameover)
  {
   delay(200);//random(101)+50);
   moveblockdown();
   setup();
  // mover();
   getkey();
  }

 }

 getch();

}
<commit_msg>Updating game with database system.<commit_after>/*

|-------SS---EGG---CATCHER---GAME---C++---BY---SREYAS------------------|
|                                                                      |
|                Author:Sreyas                                         |
|                Use A and D to move                                   |
|   		 10 Score for each egg                                 |
|                                                                      |
|----------------------------------------------------------------------|

*/
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<dos.h>

#include "register.cpp"

int gameover = 0,x,y,width,height,bx,by,score=0;
enum DIRECTION
{
LEFT,RIGHT
}dir;

void setup()
{
 int i,j;

 clrscr();
 cout<<"\t\t||||SCORE|||||: " <<score<<endl<<"Hint:Press x to close the game"<<endl;
 for(i=0;i<=height;i++)
 {

  for(j=0;j<=width;j++)
  {
    if(i==y&&j==width-2)
    cout<<"#";

    else if(i==0||i==height||j==0||j==width)
    {

     if(i==y&&j==width)
     continue;

     else
      cout<<"#";

    }

    else
    if(i==y&&j==x)
    {
      cout<<"|_|";
    }

    else
    if(i==by&&j==bx)
    {
     cout<<"O";
    }

    else
    {
     cout<<" ";
    }

  }
 cout<<endl;
 }

}

//createblock()

void createblock()
{
 bx=random(width-1)+5;
 by=0;

}

void moveblockdown()
{

 by++;

 if(by==y&&(x==bx||x==bx+1||x==bx-1||x==bx-2||x==bx+2))
 {
 score+=10;
 createblock();

 }

 if(x<=0)
 {
  x = width - 3;
 }

 else if(x>=width-2)
 {
  x = 1;
 }

}

void getkey()
{
 if(kbhit())
 {

  switch(getch())
  {
   case 'd':
   x+=2;
   break;
   case 'a':
   x-=2;
   break;
   case 'x':
   gameover  = 1;
   break;
  }

 }

}

void menu()
{
 int res;
 cout<<"1.Login\n\
	2.Register\n\
	3.Highscores\n\
	4.Help\n\
	5.About\n";

 switch(res)
 {

  case 1:
   login();

  break;

  case 2:
    Register();

  break;

  case 3:
    //need to work on
  break;

  case 4:
   //need to work on
  break;

  case 5:
   //need to work on
  break;

 }

}

void main()
{

 clrscr();
 width = 45;
 height = 20;

 y = height-2;
 x = width/2;

 setup();

 while(!gameover)
 {
  delay(150);
  setup();
  getkey();
  createblock();

  while(by!=20&&!gameover)
  {
   delay(200);
   moveblockdown();
   setup();
   getkey();
  }

 }

 getch();

}
<|endoftext|>


<commit_before>#include "Photon_Bot.h"

PhotonBot::PhotonBot(){
    init();
}

void PhotonBot::init() {
    init(6.0, 6.0);
}

void PhotonBot::init(float batteryVoltage, float motorVoltage) {
    pwmFactor = motorVoltage / batteryVoltage;
    if (pwmFactor > 1.0) {
        pwmFactor = 1.0;
    }
    pinMode(standby, OUTPUT);
    pinMode(M1[0], OUTPUT);
    pinMode(M2[0], OUTPUT);
    for (int i = 0; i < 3; i++) {
        pinMode(M3[i], OUTPUT);
        pinMode(M4[i], OUTPUT);
    }
    setStandby(false);
}

int PhotonBot::control(String command) {
    // "F-100" - forward B, L, R
    String action = command.substring(0, 1);
    String speedStr = command.substring(2);
    float speed = 0;
    if (! action.equalsIgnoreCase("S")) {
        speed = speedStr.toInt() / 100.0;
    }
    if (action.equalsIgnoreCase("F")) {
        setMotor(M3, FORWARD, speed);
        setMotor(M4, FORWARD, speed);
    }
    else if (action.equalsIgnoreCase("B")) {
        setMotor(M3, BACK, speed);
        setMotor(M4, BACK, speed);
    }
    else if (action.equalsIgnoreCase("L")) {
        setMotor(M3, FORWARD, speed);
        setMotor(M4, BACK, speed);
    }
    else if (action.equalsIgnoreCase("R")) {
        setMotor(M3, BACK, speed);
        setMotor(M4, FORWARD, speed);
    }
    else if (action.equalsIgnoreCase("S")) {
        setMotor(M3, STOP);
        setMotor(M4, STOP);
    }
    return 1;
}

int PhotonBot::setMotors(String command) {
    // "M3-F-100" use fixed positioning for first 2 params
    String motorName = command.substring(0, 2);
    String directionStr = command.substring(3, 4);
    String speedStr = command.substring(5);
    int direction = FORWARD;
    if (directionStr.equalsIgnoreCase("B")) {
        direction = BACK;
    }
    float speed = speedStr.toInt() / 100.0;
    if (motorName.equalsIgnoreCase("M3")) {
        setMotor(M3, direction, speed);
    }
    else if (motorName.equalsIgnoreCase("M4")) {
        setMotor(M4, direction, speed);
    }
    else if (motorName.equalsIgnoreCase("M1")) {
        setMotor(M1, FORWARD, speed);
    }
    else if (motorName.equalsIgnoreCase("M2")) {
        setMotor(M2, FORWARD, speed);
    }
    return 1;
}

void PhotonBot::setMotor(int motor[], int direction) {
    setMotor(motor, direction, 1.0);
}

void PhotonBot::setMotor(int motor[], int direction, float duty) {
    int pwm = int((duty * pwmFactor) * 256.0);
    if (pwm > 255) {
        pwm = 255;
    }
    SoftPWMSet(motor[0], pwm);
    if (motor == M3 || motor == M4) {
        if (direction == STOP) {
            digitalWrite(motor[1], LOW);
            digitalWrite(motor[2], LOW);
        }
        else if (direction == FORWARD) {
            digitalWrite(motor[1], LOW);
            digitalWrite(motor[2], HIGH);
        }
        else if (direction == BACK) {
            digitalWrite(motor[1], HIGH);
            digitalWrite(motor[2], LOW);
        }
    }
}

float PhotonBot::batteryVolts() {
    int raw = analogRead(battery);
    float vout = raw * 3.3 / 4096.0;
    float k = 11.0; // ratio of R1 to R1+R2
    return vout * k + 0.33; // 0.3V forward voltage of D1
}

void PhotonBot::setStandby(boolean state) {
    digitalWrite(standby, !state);
}
<commit_msg>Update Photon_Bot.cpp<commit_after>#include "Photon_Bot.h"

PhotonBot::PhotonBot(){
    init();
}

void PhotonBot::init() {
    init(6.0, 6.0);
}

void PhotonBot::init(float batteryVoltage, float motorVoltage) {
    pwmFactor = motorVoltage / batteryVoltage;
    if (pwmFactor > 1.0) {
        pwmFactor = 1.0;
    }
    pinMode(standby, OUTPUT);
    pinMode(M1[0], OUTPUT);
    pinMode(M2[0], OUTPUT);
    for (int i = 0; i < 3; i++) {
        pinMode(M3[i], OUTPUT);
        pinMode(M4[i], OUTPUT);
    }
    setStandby(false);
    SoftPWMBegin();
}

int PhotonBot::control(String command) {
    // "F-100" - forward B, L, R
    String action = command.substring(0, 1);
    String speedStr = command.substring(2);
    float speed = 0;
    if (! action.equalsIgnoreCase("S")) {
        speed = speedStr.toInt() / 100.0;
    }
    if (action.equalsIgnoreCase("F")) {
        setMotor(M3, FORWARD, speed);
        setMotor(M4, FORWARD, speed);
    }
    else if (action.equalsIgnoreCase("B")) {
        setMotor(M3, BACK, speed);
        setMotor(M4, BACK, speed);
    }
    else if (action.equalsIgnoreCase("L")) {
        setMotor(M3, FORWARD, speed);
        setMotor(M4, BACK, speed);
    }
    else if (action.equalsIgnoreCase("R")) {
        setMotor(M3, BACK, speed);
        setMotor(M4, FORWARD, speed);
    }
    else if (action.equalsIgnoreCase("S")) {
        setMotor(M3, STOP);
        setMotor(M4, STOP);
    }
    return 1;
}

int PhotonBot::setMotors(String command) {
    // "M3-F-100" use fixed positioning for first 2 params
    String motorName = command.substring(0, 2);
    String directionStr = command.substring(3, 4);
    String speedStr = command.substring(5);
    int direction = FORWARD;
    if (directionStr.equalsIgnoreCase("B")) {
        direction = BACK;
    }
    float speed = speedStr.toInt() / 100.0;
    if (motorName.equalsIgnoreCase("M3")) {
        setMotor(M3, direction, speed);
    }
    else if (motorName.equalsIgnoreCase("M4")) {
        setMotor(M4, direction, speed);
    }
    else if (motorName.equalsIgnoreCase("M1")) {
        setMotor(M1, FORWARD, speed);
    }
    else if (motorName.equalsIgnoreCase("M2")) {
        setMotor(M2, FORWARD, speed);
    }
    return 1;
}

void PhotonBot::setMotor(int motor[], int direction) {
    setMotor(motor, direction, 1.0);
}

void PhotonBot::setMotor(int motor[], int direction, float duty) {
    int pwm = int((duty * pwmFactor) * 256.0);
    if (pwm > 255) {
        pwm = 255;
    }
    SoftPWMSet(motor[0], pwm);
    if (motor == M3 || motor == M4) {
        if (direction == STOP) {
            digitalWrite(motor[1], LOW);
            digitalWrite(motor[2], LOW);
        }
        else if (direction == FORWARD) {
            digitalWrite(motor[1], LOW);
            digitalWrite(motor[2], HIGH);
        }
        else if (direction == BACK) {
            digitalWrite(motor[1], HIGH);
            digitalWrite(motor[2], LOW);
        }
    }
}

float PhotonBot::batteryVolts() {
    int raw = analogRead(battery);
    float vout = raw * 3.3 / 4096.0;
    float k = 11.0; // ratio of R1 to R1+R2
    return vout * k + 0.33; // 0.3V forward voltage of D1
}

void PhotonBot::setStandby(boolean state) {
    digitalWrite(standby, !state);
}
<|endoftext|>


<commit_before>#include "cnn/dglstm.h"

#include <string>
#include <cassert>
#include <vector>
#include <iostream>

#include "cnn/nodes.h"

using namespace std;
using namespace cnn::expr;

namespace cnn {

    enum { X2I, H2I, C2I, BI, X2O, H2O, C2O, BO, X2C, H2C, BC, X2K, C2K, Q2K, BK, STAB, X2K0};

DGLSTMBuilder::DGLSTMBuilder(unsigned layers,
                         unsigned input_dim,
                         unsigned hidden_dim,
                         Model* model) : layers(layers)
{
  Parameters * p_x2k, *p_c2k, *p_q2k, *p_bk, *p_x2k0;
  long layer_input_dim = input_dim;
  input_dims = vector<int>(layers, layer_input_dim);
  p_x2k0 = model->add_parameters({ long(hidden_dim), long(layer_input_dim) });
  for (unsigned i = 0; i < layers; ++i) {
      input_dims[i] = layer_input_dim;
    // i
    Parameters* p_x2i = model->add_parameters({long(hidden_dim), layer_input_dim});
    Parameters* p_h2i = model->add_parameters({long(hidden_dim), long(hidden_dim)});
    Parameters* p_c2i = model->add_parameters({long(hidden_dim), long(hidden_dim)});
    Parameters* p_bi = model->add_parameters({long(hidden_dim)});

    // o
    Parameters* p_x2o = model->add_parameters({long(hidden_dim), layer_input_dim});
    Parameters* p_h2o = model->add_parameters({long(hidden_dim), long(hidden_dim)});
    Parameters* p_c2o = model->add_parameters({long(hidden_dim), long(hidden_dim)});
    Parameters* p_bo = model->add_parameters({long(hidden_dim)});

    // c
    Parameters* p_x2c = model->add_parameters({long(hidden_dim), layer_input_dim});
    Parameters* p_h2c = model->add_parameters({long(hidden_dim), long(hidden_dim)});
    Parameters* p_bc = model->add_parameters({long(hidden_dim)});

    p_x2k = model->add_parameters({ long(hidden_dim), long(layer_input_dim) });
    p_c2k = model->add_parameters({ long(hidden_dim) });
    p_bk = model->add_parameters({ long(hidden_dim) });
    p_q2k = model->add_parameters({ long(hidden_dim)});

    layer_input_dim = hidden_dim;  // output (hidden) from 1st layer is input to next

    Parameters * p_stab = model->add_parameters({ 1 });
    p_stab->reset_to_zero();

    vector<Parameters*> ps;
    if (i==0)
        ps = { p_x2i, p_h2i, p_c2i, p_bi, p_x2o, p_h2o, p_c2o, p_bo, p_x2c, p_h2c, p_bc, p_x2k, p_c2k, p_q2k, p_bk, p_stab, p_x2k0};
    else
        ps = { p_x2i, p_h2i, p_c2i, p_bi, p_x2o, p_h2o, p_c2o, p_bo, p_x2c, p_h2c, p_bc, p_x2k, p_c2k, p_q2k, p_bk, p_stab};

    params.push_back(ps);
  }  // layers
}

void DGLSTMBuilder::new_graph_impl(ComputationGraph& cg){
  param_vars.clear();

  for (unsigned i = 0; i < layers; ++i){
    auto& p = params[i];

    //i
    Expression i_x2i = parameter(cg,p[X2I]);
    Expression i_h2i = parameter(cg,p[H2I]);
    Expression i_c2i = parameter(cg,p[C2I]);
    Expression i_bi = parameter(cg,p[BI]);
    //o
    Expression i_x2o = parameter(cg,p[X2O]);
    Expression i_h2o = parameter(cg,p[H2O]);
    Expression i_c2o = parameter(cg,p[C2O]);
    Expression i_bo = parameter(cg,p[BO]);
    //c
    Expression i_x2c = parameter(cg,p[X2C]);
    Expression i_h2c = parameter(cg,p[H2C]);
    Expression i_bc = parameter(cg,p[BC]);

    vector<Expression> vars;

    //k
    Expression i_x2k = parameter(cg, p[X2K]);
    Expression i_q2k = parameter(cg, p[Q2K]);
    Expression i_c2k = parameter(cg, p[C2K]);
    Expression i_bk = parameter(cg, p[BK]);

    Expression i_stab = parameter(cg, p[STAB]);

    if (i == 0)
    {
        Expression i_x2k0 = parameter(cg, p[X2K0]);
        vars = { i_x2i, i_h2i, i_c2i, i_bi, i_x2o, i_h2o, i_c2o, i_bo, i_x2c, i_h2c, i_bc, i_x2k, i_c2k, i_q2k, i_bk, i_stab, i_x2k0};
    }
    else
        vars = { i_x2i, i_h2i, i_c2i, i_bi, i_x2o, i_h2o, i_c2o, i_bo, i_x2c, i_h2c, i_bc, i_x2k, i_c2k, i_q2k, i_bk, i_stab };

    param_vars.push_back(vars);

  }
}

// layout: 0..layers = c
//         layers+1..2*layers = h
void DGLSTMBuilder::start_new_sequence_impl(const vector<Expression>& hinit) {
  h.clear();
  c.clear();

  if (hinit.size() > 0) {
    assert(layers*2 == hinit.size());
    h0.resize(layers);
    c0.resize(layers);
    for (unsigned i = 0; i < layers; ++i) {
      c0[i] = hinit[i];
      h0[i] = hinit[i + layers];
    }
    has_initial_state = true;
  } else {
    has_initial_state = false;
  }

  set_data_in_parallel(data_in_parallel());
}

void DGLSTMBuilder::set_data_in_parallel(int n)
{
    RNNBuilder::set_data_in_parallel(n);

    biases.clear();
    for (unsigned i = 0; i < layers; ++i) {
        const vector<Expression>& vars = param_vars[i];
        Expression bimb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BI]));
        Expression bcmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BC]));
        Expression bomb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BO]));
        Expression bkmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BK]));
        Expression mc2kmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[C2K]));
        vector<Expression> b = { bimb, bcmb, bomb, bkmb, mc2kmb};
        biases.push_back(b);
    }
}

Expression DGLSTMBuilder::add_input_impl(int prev, const Expression& x) {
  h.push_back(vector<Expression>(layers));
  c.push_back(vector<Expression>(layers));
  vector<Expression>& ht = h.back();
  vector<Expression>& ct = c.back();

  Expression lower_layer_c = x;  /// at layer 0, no lower memory but observation
  Expression in = x;
  Expression in_stb;

  int nutt = data_in_parallel();

  for (unsigned i = 0; i < layers; ++i) {
    const vector<Expression>& vars = param_vars[i];
    Expression i_stabilizer = exp(vars[STAB]);
    vector<Expression> v_stab = vector<Expression>(input_dims[i], i_stabilizer);
    Expression i_v_stab = concatenate_cols(vector<Expression>(nutt, concatenate(v_stab)));
    in_stb = cwise_multiply(i_v_stab, in);
    Expression i_h_tm1, i_c_tm1;

    bool has_prev_state = (prev >= 0 || has_initial_state);
    if (prev < 0) {
      if (has_initial_state) {
        // intial value for h and c at timestep 0 in layer i
        // defaults to zero matrix input if not set in add_parameter_edges
        i_h_tm1 = h0[i];
        i_c_tm1 = c0[i];
      }
    } else {  // t > 0
      i_h_tm1 = h[prev][i];
      i_c_tm1 = c[prev][i];
    }
    // input
    Expression i_ait;
    Expression bimb = biases[i][0];
    if (has_prev_state)
        i_ait = affine_transform({ bimb, vars[X2I], in_stb, vars[H2I], i_h_tm1, vars[C2I], i_c_tm1 });
    else
        i_ait = affine_transform({ bimb, vars[X2I], in_stb });
    Expression i_it = logistic(i_ait);

    // forget
    Expression i_ft = 1.f - i_it;
    // write memory cell
    Expression bcmb = biases[i][1];
    Expression i_awt;
    if (has_prev_state)
        i_awt = affine_transform({ bcmb, vars[X2C], in_stb, vars[H2C], i_h_tm1 });
    else
        i_awt = affine_transform({ bcmb, vars[X2C], in_stb });
    Expression i_wt = tanh(i_awt);

    // output
    Expression i_before_add_with_lower_linearly;
    if (has_prev_state) {
      Expression i_nwt = cwise_multiply(i_it,i_wt);
      Expression i_crt = cwise_multiply(i_ft,i_c_tm1);
      i_before_add_with_lower_linearly = i_crt + i_nwt;
    } else {
      i_before_add_with_lower_linearly = cwise_multiply(i_it, i_wt);
    }

    /// add lower layer memory cell
    Expression i_k_t;
    Expression bkmb = biases[i][3];
    Expression i_k_lowerc = bkmb;
    if (i > 0)
    {
        Expression mc2kmb = biases[i][4];
        i_k_lowerc = i_k_lowerc + cwise_multiply(mc2kmb, lower_layer_c);
    }

    if (has_prev_state)
        i_k_t = logistic(i_k_lowerc +vars[X2K] * in_stb + cwise_multiply(concatenate_cols(vector<Expression>(nutt, vars[Q2K])), i_c_tm1));
    else
        i_k_t = logistic(i_k_lowerc + vars[X2K] * in_stb);
    ct[i] = i_before_add_with_lower_linearly + cwise_multiply(i_k_t, (i == 0) ? vars[X2K0] * lower_layer_c : lower_layer_c);

    Expression i_aot;
    Expression bomb = biases[i][2];
    if (has_prev_state)
        i_aot = affine_transform({bomb, vars[X2O], in_stb, vars[H2O], i_h_tm1, vars[C2O], ct[i]});
    else
        i_aot = affine_transform({ bomb, vars[X2O], in_stb });
    Expression i_ot = logistic(i_aot);
    Expression ph_t = tanh(ct[i]);
    in = ht[i] = cwise_multiply(i_ot,ph_t);
    lower_layer_c = ct[i];
  }
  return ht.back();
}

void DGLSTMBuilder::copy(const RNNBuilder & rnn) {
  const DGLSTMBuilder & rnn_lstm = (const DGLSTMBuilder&)rnn;
  assert(params.size() == rnn_lstm.params.size());
  for(size_t i = 0; i < params.size(); ++i)
      for(size_t j = 0; j < params[i].size(); ++j)
        params[i][j]->copy(*rnn_lstm.params[i][j]);
}

} // namespace cnn
<commit_msg>prearrange bias to multiple sentence to avoid duplications<commit_after>#include "cnn/dglstm.h"

#include <string>
#include <cassert>
#include <vector>
#include <iostream>

#include "cnn/nodes.h"

using namespace std;
using namespace cnn::expr;

namespace cnn {

    enum { X2I, H2I, C2I, BI, X2O, H2O, C2O, BO, X2C, H2C, BC, X2K, C2K, Q2K, BK, STAB, X2K0};

DGLSTMBuilder::DGLSTMBuilder(unsigned layers,
                         unsigned input_dim,
                         unsigned hidden_dim,
                         Model* model) : layers(layers)
{
  Parameters * p_x2k, *p_c2k, *p_q2k, *p_bk, *p_x2k0;
  long layer_input_dim = input_dim;
  input_dims = vector<int>(layers, layer_input_dim);
  p_x2k0 = model->add_parameters({ long(hidden_dim), long(layer_input_dim) });
  for (unsigned i = 0; i < layers; ++i) {
      input_dims[i] = layer_input_dim;
    // i
    Parameters* p_x2i = model->add_parameters({long(hidden_dim), layer_input_dim});
    Parameters* p_h2i = model->add_parameters({long(hidden_dim), long(hidden_dim)});
    Parameters* p_c2i = model->add_parameters({long(hidden_dim), long(hidden_dim)});
    Parameters* p_bi = model->add_parameters({long(hidden_dim)});

    // o
    Parameters* p_x2o = model->add_parameters({long(hidden_dim), layer_input_dim});
    Parameters* p_h2o = model->add_parameters({long(hidden_dim), long(hidden_dim)});
    Parameters* p_c2o = model->add_parameters({long(hidden_dim), long(hidden_dim)});
    Parameters* p_bo = model->add_parameters({long(hidden_dim)});

    // c
    Parameters* p_x2c = model->add_parameters({long(hidden_dim), layer_input_dim});
    Parameters* p_h2c = model->add_parameters({long(hidden_dim), long(hidden_dim)});
    Parameters* p_bc = model->add_parameters({long(hidden_dim)});

    p_x2k = model->add_parameters({ long(hidden_dim), long(layer_input_dim) });
    p_c2k = model->add_parameters({ long(hidden_dim) });
    p_bk = model->add_parameters({ long(hidden_dim) });
    p_q2k = model->add_parameters({ long(hidden_dim)});

    layer_input_dim = hidden_dim;  // output (hidden) from 1st layer is input to next

    Parameters * p_stab = model->add_parameters({ 1 });
    p_stab->reset_to_zero();

    vector<Parameters*> ps;
    if (i==0)
        ps = { p_x2i, p_h2i, p_c2i, p_bi, p_x2o, p_h2o, p_c2o, p_bo, p_x2c, p_h2c, p_bc, p_x2k, p_c2k, p_q2k, p_bk, p_stab, p_x2k0};
    else
        ps = { p_x2i, p_h2i, p_c2i, p_bi, p_x2o, p_h2o, p_c2o, p_bo, p_x2c, p_h2c, p_bc, p_x2k, p_c2k, p_q2k, p_bk, p_stab};

    params.push_back(ps);
  }  // layers
}

void DGLSTMBuilder::new_graph_impl(ComputationGraph& cg){
  param_vars.clear();

  for (unsigned i = 0; i < layers; ++i){
    auto& p = params[i];

    //i
    Expression i_x2i = parameter(cg,p[X2I]);
    Expression i_h2i = parameter(cg,p[H2I]);
    Expression i_c2i = parameter(cg,p[C2I]);
    Expression i_bi = parameter(cg,p[BI]);
    //o
    Expression i_x2o = parameter(cg,p[X2O]);
    Expression i_h2o = parameter(cg,p[H2O]);
    Expression i_c2o = parameter(cg,p[C2O]);
    Expression i_bo = parameter(cg,p[BO]);
    //c
    Expression i_x2c = parameter(cg,p[X2C]);
    Expression i_h2c = parameter(cg,p[H2C]);
    Expression i_bc = parameter(cg,p[BC]);

    vector<Expression> vars;

    //k
    Expression i_x2k = parameter(cg, p[X2K]);
    Expression i_q2k = parameter(cg, p[Q2K]);
    Expression i_c2k = parameter(cg, p[C2K]);
    Expression i_bk = parameter(cg, p[BK]);

    Expression i_stab = parameter(cg, p[STAB]);

    if (i == 0)
    {
        Expression i_x2k0 = parameter(cg, p[X2K0]);
        vars = { i_x2i, i_h2i, i_c2i, i_bi, i_x2o, i_h2o, i_c2o, i_bo, i_x2c, i_h2c, i_bc, i_x2k, i_c2k, i_q2k, i_bk, i_stab, i_x2k0};
    }
    else
        vars = { i_x2i, i_h2i, i_c2i, i_bi, i_x2o, i_h2o, i_c2o, i_bo, i_x2c, i_h2c, i_bc, i_x2k, i_c2k, i_q2k, i_bk, i_stab };

    param_vars.push_back(vars);

  }
}

// layout: 0..layers = c
//         layers+1..2*layers = h
void DGLSTMBuilder::start_new_sequence_impl(const vector<Expression>& hinit) {
  h.clear();
  c.clear();

  if (hinit.size() > 0) {
    assert(layers*2 == hinit.size());
    h0.resize(layers);
    c0.resize(layers);
    for (unsigned i = 0; i < layers; ++i) {
      c0[i] = hinit[i];
      h0[i] = hinit[i + layers];
    }
    has_initial_state = true;
  } else {
    has_initial_state = false;
  }

  set_data_in_parallel(data_in_parallel());
}

void DGLSTMBuilder::set_data_in_parallel(int n)
{
    RNNBuilder::set_data_in_parallel(n);

    biases.clear();
    for (unsigned i = 0; i < layers; ++i) {
        const vector<Expression>& vars = param_vars[i];
        Expression bimb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BI]));
        Expression bcmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BC]));
        Expression bomb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BO]));
        Expression bkmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BK]));
        Expression mc2kmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[C2K]));
        Expression mq2kmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[Q2K]));
        vector<Expression> b = { bimb, bcmb, bomb, bkmb, mc2kmb, mq2kmb};
        biases.push_back(b);
    }
}

Expression DGLSTMBuilder::add_input_impl(int prev, const Expression& x) {
  h.push_back(vector<Expression>(layers));
  c.push_back(vector<Expression>(layers));
  vector<Expression>& ht = h.back();
  vector<Expression>& ct = c.back();

  Expression lower_layer_c = x;  /// at layer 0, no lower memory but observation
  Expression in = x;
  Expression in_stb;

  int nutt = data_in_parallel();

  for (unsigned i = 0; i < layers; ++i) {
    const vector<Expression>& vars = param_vars[i];
    Expression i_stabilizer = exp(vars[STAB]);
    vector<Expression> v_stab = vector<Expression>(input_dims[i], i_stabilizer);
    Expression i_v_stab = concatenate_cols(vector<Expression>(nutt, concatenate(v_stab)));
    in_stb = cwise_multiply(i_v_stab, in);
    Expression i_h_tm1, i_c_tm1;

    bool has_prev_state = (prev >= 0 || has_initial_state);
    if (prev < 0) {
      if (has_initial_state) {
        // intial value for h and c at timestep 0 in layer i
        // defaults to zero matrix input if not set in add_parameter_edges
        i_h_tm1 = h0[i];
        i_c_tm1 = c0[i];
      }
    } else {  // t > 0
      i_h_tm1 = h[prev][i];
      i_c_tm1 = c[prev][i];
    }
    // input
    Expression i_ait;
    Expression bimb = biases[i][0];
    if (has_prev_state)
        i_ait = affine_transform({ bimb, vars[X2I], in_stb, vars[H2I], i_h_tm1, vars[C2I], i_c_tm1 });
    else
        i_ait = affine_transform({ bimb, vars[X2I], in_stb });
    Expression i_it = logistic(i_ait);

    // forget
    Expression i_ft = 1.f - i_it;
    // write memory cell
    Expression bcmb = biases[i][1];
    Expression i_awt;
    if (has_prev_state)
        i_awt = affine_transform({ bcmb, vars[X2C], in_stb, vars[H2C], i_h_tm1 });
    else
        i_awt = affine_transform({ bcmb, vars[X2C], in_stb });
    Expression i_wt = tanh(i_awt);

    // output
    Expression i_before_add_with_lower_linearly;
    if (has_prev_state) {
      Expression i_nwt = cwise_multiply(i_it,i_wt);
      Expression i_crt = cwise_multiply(i_ft,i_c_tm1);
      i_before_add_with_lower_linearly = i_crt + i_nwt;
    } else {
      i_before_add_with_lower_linearly = cwise_multiply(i_it, i_wt);
    }

    /// add lower layer memory cell
    Expression i_k_t;
    Expression bkmb = biases[i][3];
    Expression i_k_lowerc = bkmb;
    if (i > 0)
    {
        Expression mc2kmb = biases[i][4];
        i_k_lowerc = i_k_lowerc + cwise_multiply(mc2kmb, lower_layer_c);
    }

    if (has_prev_state)
    {
        Expression q2kmb = biases[i][5];
        i_k_t = logistic(i_k_lowerc + vars[X2K] * in_stb + cwise_multiply(q2kmb, i_c_tm1));
    }
    else
        i_k_t = logistic(i_k_lowerc + vars[X2K] * in_stb);
    ct[i] = i_before_add_with_lower_linearly + cwise_multiply(i_k_t, (i == 0) ? vars[X2K0] * lower_layer_c : lower_layer_c);

    Expression i_aot;
    Expression bomb = biases[i][2];
    if (has_prev_state)
        i_aot = affine_transform({bomb, vars[X2O], in_stb, vars[H2O], i_h_tm1, vars[C2O], ct[i]});
    else
        i_aot = affine_transform({ bomb, vars[X2O], in_stb });
    Expression i_ot = logistic(i_aot);
    Expression ph_t = tanh(ct[i]);
    in = ht[i] = cwise_multiply(i_ot,ph_t);
    lower_layer_c = ct[i];
  }
  return ht.back();
}

void DGLSTMBuilder::copy(const RNNBuilder & rnn) {
  const DGLSTMBuilder & rnn_lstm = (const DGLSTMBuilder&)rnn;
  assert(params.size() == rnn_lstm.params.size());
  for(size_t i = 0; i < params.size(); ++i)
      for(size_t j = 0; j < params[i].size(); ++j)
        params[i][j]->copy(*rnn_lstm.params[i][j]);
}

} // namespace cnn
<|endoftext|>


<commit_before>/*
    This file is part of the KDE alarm daemon.
    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

    This program 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 2 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

// $Id$

#include <qlabel.h>
#include <qlayout.h>
#include <qcheckbox.h>
#include <qspinbox.h>
#include <qwhatsthis.h>

#include <kdebug.h>
#include <kglobal.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kconfig.h>
#include <kdialog.h>

#include "alarmdaemoniface_stub.h"
#include "alarmdaemonctrl.moc"

extern "C" {
  KCModule *create_alarmdaemonctrl(QWidget *parent, const char *name) {
    KGlobal::locale()->insertCatalogue("alarmdaemonctrl");
    return new AlarmDaemonCtrl(parent, name);
  }
}

AlarmDaemonCtrl::AlarmDaemonCtrl(QWidget *parent, const char *name) :
  KCModule(parent, name)
{
  QBoxLayout *topLayout = new QVBoxLayout( this );
  topLayout->setMargin( KDialog::marginHint() );

  mAutoStartCheck = new QCheckBox(
      i18n("Start alarm daemon automatically at login"), this );
  connect( mAutoStartCheck, SIGNAL( clicked() ), SLOT( changed() ) );
  QWhatsThis::add( mAutoStartCheck,
      i18n("Check to start the alarm daemon whenever you start a KDE session."));
  topLayout->addWidget( mAutoStartCheck );

  QBoxLayout *intervalLayout = new QHBoxLayout( topLayout );

  QLabel *intervalLabel = new QLabel( i18n("Check interval [minutes]"), this );
  intervalLayout->addWidget( intervalLabel );

  mIntervalSpin = new QSpinBox( this );
  mIntervalSpin->setMinValue( 1 );
  connect( mIntervalSpin, SIGNAL( valueChanged( int ) ), SLOT( changed() ) );
  QWhatsThis::add( mIntervalSpin,
      i18n("How often (in minutes) the alarm daemon should check for alarms becoming due."));
  intervalLayout->addWidget( mIntervalSpin );

  topLayout->addStretch();

  load();
}

AlarmDaemonCtrl::~AlarmDaemonCtrl()
{
}

void AlarmDaemonCtrl::defaults()
{
  mAutoStartCheck->setChecked( true );
  mIntervalSpin->setValue( 1 );

  emit changed(true);
}

QString AlarmDaemonCtrl::quickHelp() const
{
  return i18n( "
Alarm Daemon
 This module allows you to configure"
               " the KDE alarm daemon.");
}

void AlarmDaemonCtrl::load()
{
  kdDebug() << "AlarmDaemonCtrl::load()" << endl;

  KConfig config( locate( "config", "kalarmdrc" ) );
  config.setGroup("General");
  mAutoStartCheck->setChecked( config.readBoolEntry( "Autostart", true ) );
  mIntervalSpin->setValue( config.readNumEntry( "CheckInterval", 1 ) );

  emit changed(false);
}

void AlarmDaemonCtrl::save()
{
  kdDebug() << "AlarmDaemonCtrl::save()" << endl;

  KConfig config( locate( "config", "kalarmdrc" ) );
  config.setGroup("General");
  config.writeEntry( "Autostart", mAutoStartCheck->isChecked() );
  config.writeEntry( "CheckInterval", mIntervalSpin->value() );
  config.sync();

  // Notify the alarm daemon that the settings have changed
  AlarmDaemonIface_stub s("kalarmd", "ad");
  s.readConfig();

  emit changed(false);
}

int AlarmDaemonCtrl::buttons()
{
  return KCModule::Help | KCModule::Default | KCModule::Apply;
}

void AlarmDaemonCtrl::changed()
{
  emit changed( true );
}
<commit_msg>Approved by Coolo.  Fixes failed Q_ASSERT() in KInstance.<commit_after>/*
    This file is part of the KDE alarm daemon.
    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

    This program 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 2 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

// $Id$

#include <qlabel.h>
#include <qlayout.h>
#include <qcheckbox.h>
#include <qspinbox.h>
#include <qwhatsthis.h>

#include <kdebug.h>
#include <kglobal.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kconfig.h>
#include <kdialog.h>

#include "alarmdaemoniface_stub.h"
#include "alarmdaemonctrl.moc"

extern "C" {
  KCModule *create_alarmdaemonctrl(QWidget *parent, const char *name) {
    return new AlarmDaemonCtrl(parent, "alarmdaemonctrl");
  }
}

AlarmDaemonCtrl::AlarmDaemonCtrl(QWidget *parent, const char *name) :
  KCModule(parent, name)
{
  QBoxLayout *topLayout = new QVBoxLayout( this );
  topLayout->setMargin( KDialog::marginHint() );

  mAutoStartCheck = new QCheckBox(
      i18n("Start alarm daemon automatically at login"), this );
  connect( mAutoStartCheck, SIGNAL( clicked() ), SLOT( changed() ) );
  QWhatsThis::add( mAutoStartCheck,
      i18n("Check to start the alarm daemon whenever you start a KDE session."));
  topLayout->addWidget( mAutoStartCheck );

  QBoxLayout *intervalLayout = new QHBoxLayout( topLayout );

  QLabel *intervalLabel = new QLabel( i18n("Check interval [minutes]"), this );
  intervalLayout->addWidget( intervalLabel );

  mIntervalSpin = new QSpinBox( this );
  mIntervalSpin->setMinValue( 1 );
  connect( mIntervalSpin, SIGNAL( valueChanged( int ) ), SLOT( changed() ) );
  QWhatsThis::add( mIntervalSpin,
      i18n("How often (in minutes) the alarm daemon should check for alarms becoming due."));
  intervalLayout->addWidget( mIntervalSpin );

  topLayout->addStretch();

  load();
}

AlarmDaemonCtrl::~AlarmDaemonCtrl()
{
}

void AlarmDaemonCtrl::defaults()
{
  mAutoStartCheck->setChecked( true );
  mIntervalSpin->setValue( 1 );

  emit changed(true);
}

QString AlarmDaemonCtrl::quickHelp() const
{
  return i18n( "
Alarm Daemon
 This module allows you to configure"
               " the KDE alarm daemon.");
}

void AlarmDaemonCtrl::load()
{
  kdDebug() << "AlarmDaemonCtrl::load()" << endl;

  KConfig config( locate( "config", "kalarmdrc" ) );
  config.setGroup("General");
  mAutoStartCheck->setChecked( config.readBoolEntry( "Autostart", true ) );
  mIntervalSpin->setValue( config.readNumEntry( "CheckInterval", 1 ) );

  emit changed(false);
}

void AlarmDaemonCtrl::save()
{
  kdDebug() << "AlarmDaemonCtrl::save()" << endl;

  KConfig config( locate( "config", "kalarmdrc" ) );
  config.setGroup("General");
  config.writeEntry( "Autostart", mAutoStartCheck->isChecked() );
  config.writeEntry( "CheckInterval", mIntervalSpin->value() );
  config.sync();

  // Notify the alarm daemon that the settings have changed
  AlarmDaemonIface_stub s("kalarmd", "ad");
  s.readConfig();

  emit changed(false);
}

int AlarmDaemonCtrl::buttons()
{
  return KCModule::Help | KCModule::Default | KCModule::Apply;
}

void AlarmDaemonCtrl::changed()
{
  emit changed( true );
}
<|endoftext|>