<commit_before>//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the llc code generator driver. It provides a convenient
// command-line interface for generating native assembly-language code
// or C code, given LLVM bitcode.
//
//===----------------------------------------------------------------------===//

#include "llvm/LLVMContext.h"
#include "llvm/DataLayout.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Support/IRReader.h"
#include "llvm/CodeGen/CommandFlags.h"
#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
#include "llvm/CodeGen/LinkAllCodegenComponents.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetLibraryInfo.h"
#include "llvm/Target/TargetMachine.h"
#include <memory>
using namespace llvm;

// General options for llc.  Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));

static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));

// Determine optimization level.
static cl::opt<char>
OptLevel("O",
         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
                  "(default = '-O2')"),
         cl::Prefix,
         cl::ZeroOrMore,
         cl::init(' '));

static cl::opt<std::string>
TargetTriple("mtriple", cl::desc("Override target triple for module"));

cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
                       cl::desc("Do not verify input module"));

cl::opt<bool>
DisableSimplifyLibCalls("disable-simplify-libcalls",
                        cl::desc("Disable simplify-libcalls"),
                        cl::init(false));

// GetFileNameRoot - Helper function to get the basename of a filename.
static inline std::string
GetFileNameRoot(const std::string &InputFilename) {
  std::string IFN = InputFilename;
  std::string outputFilename;
  int Len = IFN.length();
  if ((Len > 2) &&
      IFN[Len-3] == '.' &&
      ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
       (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
    outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
  } else {
    outputFilename = IFN;
  }
  return outputFilename;
}

static tool_output_file *GetOutputStream(const char *TargetName,
                                         Triple::OSType OS,
                                         const char *ProgName) {
  // If we don't yet have an output filename, make one.
  if (OutputFilename.empty()) {
    if (InputFilename == "-")
      OutputFilename = "-";
    else {
      OutputFilename = GetFileNameRoot(InputFilename);

      switch (FileType) {
      case TargetMachine::CGFT_AssemblyFile:
        if (TargetName[0] == 'c') {
          if (TargetName[1] == 0)
            OutputFilename += ".cbe.c";
          else if (TargetName[1] == 'p' && TargetName[2] == 'p')
            OutputFilename += ".cpp";
          else
            OutputFilename += ".s";
        } else
          OutputFilename += ".s";
        break;
      case TargetMachine::CGFT_ObjectFile:
        if (OS == Triple::Win32)
          OutputFilename += ".obj";
        else
          OutputFilename += ".o";
        break;
      case TargetMachine::CGFT_Null:
        OutputFilename += ".null";
        break;
      }
    }
  }

  // Decide if we need "binary" output.
  bool Binary = false;
  switch (FileType) {
  case TargetMachine::CGFT_AssemblyFile:
    break;
  case TargetMachine::CGFT_ObjectFile:
  case TargetMachine::CGFT_Null:
    Binary = true;
    break;
  }

  // Open the file.
  std::string error;
  unsigned OpenFlags = 0;
  if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
  tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
                                                 OpenFlags);
  if (!error.empty()) {
    errs() << error << '\n';
    delete FDOut;
    return 0;
  }

  return FDOut;
}

// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);

  // Enable debug stream buffering.
  EnableDebugBuffering = true;

  LLVMContext &Context = getGlobalContext();
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.

  // Initialize targets first, so that --version shows registered targets.
  InitializeAllTargets();
  InitializeAllTargetMCs();
  InitializeAllAsmPrinters();
  InitializeAllAsmParsers();

  // Initialize codegen and IR passes used by llc so that the -print-after,
  // -print-before, and -stop-after options work.
  PassRegistry *Registry = PassRegistry::getPassRegistry();
  initializeCore(*Registry);
  initializeCodeGen(*Registry);
  initializeLoopStrengthReducePass(*Registry);
  initializeLowerIntrinsicsPass(*Registry);
  initializeUnreachableBlockElimPass(*Registry);

  // Register the target printer for --version.
  cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);

  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");

  // Load the module to be compiled...
  SMDiagnostic Err;
  std::auto_ptr<Module> M;
  Module *mod = 0;
  Triple TheTriple;

  bool SkipModule = MCPU == "help" ||
                    (!MAttrs.empty() && MAttrs.front() == "help");

  // If user just wants to list available options, skip module loading
  if (!SkipModule) {
    M.reset(ParseIRFile(InputFilename, Err, Context));
    mod = M.get();
    if (mod == 0) {
      Err.print(argv[0], errs());
      return 1;
    }

    // If we are supposed to override the target triple, do so now.
    if (!TargetTriple.empty())
      mod->setTargetTriple(Triple::normalize(TargetTriple));
    TheTriple = Triple(mod->getTargetTriple());
  } else {
    TheTriple = Triple(Triple::normalize(TargetTriple));
  }

  if (TheTriple.getTriple().empty())
    TheTriple.setTriple(sys::getDefaultTargetTriple());

  // Get the target specific parser.
  std::string Error;
  const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
                                                         Error);
  if (!TheTarget) {
    errs() << argv[0] << ": " << Error;
    return 1;
  }

  // Package up features to be passed to target/subtarget
  std::string FeaturesStr;
  if (MAttrs.size()) {
    SubtargetFeatures Features;
    for (unsigned i = 0; i != MAttrs.size(); ++i)
      Features.AddFeature(MAttrs[i]);
    FeaturesStr = Features.getString();
  }

  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  switch (OptLevel) {
  default:
    errs() << argv[0] << ": invalid optimization level.\n";
    return 1;
  case ' ': break;
  case '0': OLvl = CodeGenOpt::None; break;
  case '1': OLvl = CodeGenOpt::Less; break;
  case '2': OLvl = CodeGenOpt::Default; break;
  case '3': OLvl = CodeGenOpt::Aggressive; break;
  }

  TargetOptions Options;
  Options.LessPreciseFPMADOption = EnableFPMAD;
  Options.NoFramePointerElim = DisableFPElim;
  Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
  Options.AllowFPOpFusion = FuseFPOps;
  Options.UnsafeFPMath = EnableUnsafeFPMath;
  Options.NoInfsFPMath = EnableNoInfsFPMath;
  Options.NoNaNsFPMath = EnableNoNaNsFPMath;
  Options.HonorSignDependentRoundingFPMathOption =
      EnableHonorSignDependentRoundingFPMath;
  Options.UseSoftFloat = GenerateSoftFloatCalls;
  if (FloatABIForCalls != FloatABI::Default)
    Options.FloatABIType = FloatABIForCalls;
  Options.NoZerosInBSS = DontPlaceZerosInBSS;
  Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
  Options.DisableTailCalls = DisableTailCalls;
  Options.StackAlignmentOverride = OverrideStackAlignment;
  Options.RealignStack = EnableRealignStack;
  Options.TrapFuncName = TrapFuncName;
  Options.PositionIndependentExecutable = EnablePIE;
  Options.EnableSegmentedStacks = SegmentedStacks;
  Options.UseInitArray = UseInitArray;
  Options.SSPBufferSize = SSPBufferSize;

  std::auto_ptr<TargetMachine>
    target(TheTarget->createTargetMachine(TheTriple.getTriple(),
                                          MCPU, FeaturesStr, Options,
                                          RelocModel, CMModel, OLvl));
  assert(target.get() && "Could not allocate target machine!");
  assert(mod && "Should have exited after outputting help!");
  TargetMachine &Target = *target.get();

  if (DisableDotLoc)
    Target.setMCUseLoc(false);

  if (DisableCFI)
    Target.setMCUseCFI(false);

  if (EnableDwarfDirectory)
    Target.setMCUseDwarfDirectory(true);

  if (GenerateSoftFloatCalls)
    FloatABIForCalls = FloatABI::Soft;

  // Disable .loc support for older OS X versions.
  if (TheTriple.isMacOSX() &&
      TheTriple.isMacOSXVersionLT(10, 6))
    Target.setMCUseLoc(false);

  // Figure out where we are going to send the output.
  OwningPtr<tool_output_file> Out
    (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
  if (!Out) return 1;

  // Build up all of the passes that we want to do to the module.
  PassManager PM;

  // Add an appropriate TargetLibraryInfo pass for the module's triple.
  TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
  if (DisableSimplifyLibCalls)
    TLI->disableAllFunctions();
  PM.add(TLI);

  if (target.get()) {
    PM.add(new TargetTransformInfo(target->getScalarTargetTransformInfo(),
                                   target->getVectorTargetTransformInfo()));
  }

  // Add the target data from the target machine, if it exists, or the module.
  if (const DataLayout *TD = Target.getDataLayout())
    PM.add(new DataLayout(*TD));
  else
    PM.add(new DataLayout(mod));

  // Override default to generate verbose assembly.
  Target.setAsmVerbosityDefault(true);

  if (RelaxAll) {
    if (FileType != TargetMachine::CGFT_ObjectFile)
      errs() << argv[0]
             << ": warning: ignoring -mc-relax-all because filetype != obj";
    else
      Target.setMCRelaxAll(true);
  }

  {
    formatted_raw_ostream FOS(Out->os());

    AnalysisID StartAfterID = 0;
    AnalysisID StopAfterID = 0;
    const PassRegistry *PR = PassRegistry::getPassRegistry();
    if (!StartAfter.empty()) {
      const PassInfo *PI = PR->getPassInfo(StartAfter);
      if (!PI) {
        errs() << argv[0] << ": start-after pass is not registered.\n";
        return 1;
      }
      StartAfterID = PI->getTypeInfo();
    }
    if (!StopAfter.empty()) {
      const PassInfo *PI = PR->getPassInfo(StopAfter);
      if (!PI) {
        errs() << argv[0] << ": stop-after pass is not registered.\n";
        return 1;
      }
      StopAfterID = PI->getTypeInfo();
    }

    // Ask the target to add backend passes as necessary.
    if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
                                   StartAfterID, StopAfterID)) {
      errs() << argv[0] << ": target does not support generation of this"
             << " file type!\n";
      return 1;
    }

    // Before executing passes, print the final values of the LLVM options.
    cl::PrintOptionValues();

    PM.run(*mod);
  }

  // Declare success.
  Out->keep();

  return 0;
}
<commit_msg>Add a -time-compilations=<N> option to llc.<commit_after>//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the llc code generator driver. It provides a convenient
// command-line interface for generating native assembly-language code
// or C code, given LLVM bitcode.
//
//===----------------------------------------------------------------------===//

#include "llvm/LLVMContext.h"
#include "llvm/DataLayout.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Support/IRReader.h"
#include "llvm/CodeGen/CommandFlags.h"
#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
#include "llvm/CodeGen/LinkAllCodegenComponents.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetLibraryInfo.h"
#include "llvm/Target/TargetMachine.h"
#include <memory>
using namespace llvm;

// General options for llc.  Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));

static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));

static cl::opt<unsigned>
TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
                 cl::value_desc("N"),
                 cl::desc("Repeat compilation N times for timing"));

// Determine optimization level.
static cl::opt<char>
OptLevel("O",
         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
                  "(default = '-O2')"),
         cl::Prefix,
         cl::ZeroOrMore,
         cl::init(' '));

static cl::opt<std::string>
TargetTriple("mtriple", cl::desc("Override target triple for module"));

cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
                       cl::desc("Do not verify input module"));

cl::opt<bool>
DisableSimplifyLibCalls("disable-simplify-libcalls",
                        cl::desc("Disable simplify-libcalls"),
                        cl::init(false));

static int compileModule(char**, LLVMContext&);

// GetFileNameRoot - Helper function to get the basename of a filename.
static inline std::string
GetFileNameRoot(const std::string &InputFilename) {
  std::string IFN = InputFilename;
  std::string outputFilename;
  int Len = IFN.length();
  if ((Len > 2) &&
      IFN[Len-3] == '.' &&
      ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
       (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
    outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
  } else {
    outputFilename = IFN;
  }
  return outputFilename;
}

static tool_output_file *GetOutputStream(const char *TargetName,
                                         Triple::OSType OS,
                                         const char *ProgName) {
  // If we don't yet have an output filename, make one.
  if (OutputFilename.empty()) {
    if (InputFilename == "-")
      OutputFilename = "-";
    else {
      OutputFilename = GetFileNameRoot(InputFilename);

      switch (FileType) {
      case TargetMachine::CGFT_AssemblyFile:
        if (TargetName[0] == 'c') {
          if (TargetName[1] == 0)
            OutputFilename += ".cbe.c";
          else if (TargetName[1] == 'p' && TargetName[2] == 'p')
            OutputFilename += ".cpp";
          else
            OutputFilename += ".s";
        } else
          OutputFilename += ".s";
        break;
      case TargetMachine::CGFT_ObjectFile:
        if (OS == Triple::Win32)
          OutputFilename += ".obj";
        else
          OutputFilename += ".o";
        break;
      case TargetMachine::CGFT_Null:
        OutputFilename += ".null";
        break;
      }
    }
  }

  // Decide if we need "binary" output.
  bool Binary = false;
  switch (FileType) {
  case TargetMachine::CGFT_AssemblyFile:
    break;
  case TargetMachine::CGFT_ObjectFile:
  case TargetMachine::CGFT_Null:
    Binary = true;
    break;
  }

  // Open the file.
  std::string error;
  unsigned OpenFlags = 0;
  if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
  tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
                                                 OpenFlags);
  if (!error.empty()) {
    errs() << error << '\n';
    delete FDOut;
    return 0;
  }

  return FDOut;
}

// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);

  // Enable debug stream buffering.
  EnableDebugBuffering = true;

  LLVMContext &Context = getGlobalContext();
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.

  // Initialize targets first, so that --version shows registered targets.
  InitializeAllTargets();
  InitializeAllTargetMCs();
  InitializeAllAsmPrinters();
  InitializeAllAsmParsers();

  // Initialize codegen and IR passes used by llc so that the -print-after,
  // -print-before, and -stop-after options work.
  PassRegistry *Registry = PassRegistry::getPassRegistry();
  initializeCore(*Registry);
  initializeCodeGen(*Registry);
  initializeLoopStrengthReducePass(*Registry);
  initializeLowerIntrinsicsPass(*Registry);
  initializeUnreachableBlockElimPass(*Registry);

  // Register the target printer for --version.
  cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);

  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");

  // Compile the module TimeCompilations times to give better compile time
  // metrics.
  for (unsigned I = TimeCompilations; I; --I)
    if (int RetVal = compileModule(argv, Context))
      return RetVal;
  return 0;
}

static int compileModule(char **argv, LLVMContext &Context) {
  // Load the module to be compiled...
  SMDiagnostic Err;
  std::auto_ptr<Module> M;
  Module *mod = 0;
  Triple TheTriple;

  bool SkipModule = MCPU == "help" ||
                    (!MAttrs.empty() && MAttrs.front() == "help");

  // If user just wants to list available options, skip module loading
  if (!SkipModule) {
    M.reset(ParseIRFile(InputFilename, Err, Context));
    mod = M.get();
    if (mod == 0) {
      Err.print(argv[0], errs());
      return 1;
    }

    // If we are supposed to override the target triple, do so now.
    if (!TargetTriple.empty())
      mod->setTargetTriple(Triple::normalize(TargetTriple));
    TheTriple = Triple(mod->getTargetTriple());
  } else {
    TheTriple = Triple(Triple::normalize(TargetTriple));
  }

  if (TheTriple.getTriple().empty())
    TheTriple.setTriple(sys::getDefaultTargetTriple());

  // Get the target specific parser.
  std::string Error;
  const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
                                                         Error);
  if (!TheTarget) {
    errs() << argv[0] << ": " << Error;
    return 1;
  }

  // Package up features to be passed to target/subtarget
  std::string FeaturesStr;
  if (MAttrs.size()) {
    SubtargetFeatures Features;
    for (unsigned i = 0; i != MAttrs.size(); ++i)
      Features.AddFeature(MAttrs[i]);
    FeaturesStr = Features.getString();
  }

  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  switch (OptLevel) {
  default:
    errs() << argv[0] << ": invalid optimization level.\n";
    return 1;
  case ' ': break;
  case '0': OLvl = CodeGenOpt::None; break;
  case '1': OLvl = CodeGenOpt::Less; break;
  case '2': OLvl = CodeGenOpt::Default; break;
  case '3': OLvl = CodeGenOpt::Aggressive; break;
  }

  TargetOptions Options;
  Options.LessPreciseFPMADOption = EnableFPMAD;
  Options.NoFramePointerElim = DisableFPElim;
  Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
  Options.AllowFPOpFusion = FuseFPOps;
  Options.UnsafeFPMath = EnableUnsafeFPMath;
  Options.NoInfsFPMath = EnableNoInfsFPMath;
  Options.NoNaNsFPMath = EnableNoNaNsFPMath;
  Options.HonorSignDependentRoundingFPMathOption =
      EnableHonorSignDependentRoundingFPMath;
  Options.UseSoftFloat = GenerateSoftFloatCalls;
  if (FloatABIForCalls != FloatABI::Default)
    Options.FloatABIType = FloatABIForCalls;
  Options.NoZerosInBSS = DontPlaceZerosInBSS;
  Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
  Options.DisableTailCalls = DisableTailCalls;
  Options.StackAlignmentOverride = OverrideStackAlignment;
  Options.RealignStack = EnableRealignStack;
  Options.TrapFuncName = TrapFuncName;
  Options.PositionIndependentExecutable = EnablePIE;
  Options.EnableSegmentedStacks = SegmentedStacks;
  Options.UseInitArray = UseInitArray;
  Options.SSPBufferSize = SSPBufferSize;

  std::auto_ptr<TargetMachine>
    target(TheTarget->createTargetMachine(TheTriple.getTriple(),
                                          MCPU, FeaturesStr, Options,
                                          RelocModel, CMModel, OLvl));
  assert(target.get() && "Could not allocate target machine!");
  assert(mod && "Should have exited after outputting help!");
  TargetMachine &Target = *target.get();

  if (DisableDotLoc)
    Target.setMCUseLoc(false);

  if (DisableCFI)
    Target.setMCUseCFI(false);

  if (EnableDwarfDirectory)
    Target.setMCUseDwarfDirectory(true);

  if (GenerateSoftFloatCalls)
    FloatABIForCalls = FloatABI::Soft;

  // Disable .loc support for older OS X versions.
  if (TheTriple.isMacOSX() &&
      TheTriple.isMacOSXVersionLT(10, 6))
    Target.setMCUseLoc(false);

  // Figure out where we are going to send the output.
  OwningPtr<tool_output_file> Out
    (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
  if (!Out) return 1;

  // Build up all of the passes that we want to do to the module.
  PassManager PM;

  // Add an appropriate TargetLibraryInfo pass for the module's triple.
  TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
  if (DisableSimplifyLibCalls)
    TLI->disableAllFunctions();
  PM.add(TLI);

  if (target.get()) {
    PM.add(new TargetTransformInfo(target->getScalarTargetTransformInfo(),
                                   target->getVectorTargetTransformInfo()));
  }

  // Add the target data from the target machine, if it exists, or the module.
  if (const DataLayout *TD = Target.getDataLayout())
    PM.add(new DataLayout(*TD));
  else
    PM.add(new DataLayout(mod));

  // Override default to generate verbose assembly.
  Target.setAsmVerbosityDefault(true);

  if (RelaxAll) {
    if (FileType != TargetMachine::CGFT_ObjectFile)
      errs() << argv[0]
             << ": warning: ignoring -mc-relax-all because filetype != obj";
    else
      Target.setMCRelaxAll(true);
  }

  {
    formatted_raw_ostream FOS(Out->os());

    AnalysisID StartAfterID = 0;
    AnalysisID StopAfterID = 0;
    const PassRegistry *PR = PassRegistry::getPassRegistry();
    if (!StartAfter.empty()) {
      const PassInfo *PI = PR->getPassInfo(StartAfter);
      if (!PI) {
        errs() << argv[0] << ": start-after pass is not registered.\n";
        return 1;
      }
      StartAfterID = PI->getTypeInfo();
    }
    if (!StopAfter.empty()) {
      const PassInfo *PI = PR->getPassInfo(StopAfter);
      if (!PI) {
        errs() << argv[0] << ": stop-after pass is not registered.\n";
        return 1;
      }
      StopAfterID = PI->getTypeInfo();
    }

    // Ask the target to add backend passes as necessary.
    if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
                                   StartAfterID, StopAfterID)) {
      errs() << argv[0] << ": target does not support generation of this"
             << " file type!\n";
      return 1;
    }

    // Before executing passes, print the final values of the LLVM options.
    cl::PrintOptionValues();

    PM.run(*mod);
  }

  // Declare success.
  Out->keep();

  return 0;
}
<|endoftext|>


<commit_before>//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
//
// This utility provides a way to execute LLVM bytecode without static
// compilation.  This consists of a very simple and slow (but portable)
// interpreter, along with capability for system specific dynamic compilers.  At
// runtime, the fastest (stable) execution engine is selected to run the
// program.  This means the JIT compiler for the current platform if it's
// available.
//
//===----------------------------------------------------------------------===//

#include "ExecutionEngine.h"
#include "Support/CommandLine.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Module.h"
#include "llvm/Target/TargetMachineImpls.h"

namespace {
  cl::opt<std::string>
  InputFile(cl::desc("<input bytecode>"), cl::Positional, cl::init("-"));

  cl::list<std::string>
  InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));

  cl::opt<std::string>
  MainFunction ("f", cl::desc("Function to execute"), cl::init("main"),
		cl::value_desc("function name"));

  cl::opt<bool> DebugMode("d", cl::desc("Start program in debugger"));

  cl::opt<bool> TraceMode("trace", cl::desc("Enable Tracing"));

  cl::opt<bool> ForceInterpreter("force-interpreter",
				 cl::desc("Force interpretation: disable JIT"),
				 cl::init(true));
}

//===----------------------------------------------------------------------===//
// ExecutionEngine Class Implementation
//

ExecutionEngine::~ExecutionEngine() {
  delete &CurMod;
}

//===----------------------------------------------------------------------===//
// main Driver function
//
int main(int argc, char** argv) {
  cl::ParseCommandLineOptions(argc, argv,
			      " llvm interpreter & dynamic compiler\n");

  // Load the bytecode...
  std::string ErrorMsg;
  Module *M = ParseBytecodeFile(InputFile, &ErrorMsg);
  if (M == 0) {
    std::cout << "Error parsing '" << InputFile << "': "
              << ErrorMsg << "\n";
    exit(1);
  }

#if 0
  // Link in the runtime library for LLI...
  std::string RuntimeLib = getCurrentExecutablePath();
  if (!RuntimeLib.empty()) RuntimeLib += "/";
  RuntimeLib += "RuntimeLib.bc";

  if (Module *SupportLib = ParseBytecodeFile(RuntimeLib, &ErrorMsg)) {
    if (LinkModules(M, SupportLib, &ErrorMsg))
      std::cerr << "Error Linking runtime library into current module: "
                << ErrorMsg << "\n";
  } else {
    std::cerr << "Error loading runtime library '"+RuntimeLib+"': "
              << ErrorMsg << "\n";
  }
#endif

  unsigned Config = (M->isLittleEndian()   ? TM::LittleEndian : TM::BigEndian) |
                    (M->has32BitPointers() ? TM::PtrSize32    : TM::PtrSize64);
  ExecutionEngine *EE = 0;

  // If there is nothing that is forcing us to use the interpreter, make a JIT.
  if (!ForceInterpreter && !DebugMode && !TraceMode)
    EE = ExecutionEngine::createJIT(M, Config);

  // If we can't make a JIT, make an interpreter instead.
  if (EE == 0)
    EE = ExecutionEngine::createInterpreter(M, Config, DebugMode, TraceMode);

  // Add the module name to the start of the argv vector...
  InputArgv.insert(InputArgv.begin(), InputFile);

  // Run the main function!
  int ExitCode = EE->run(MainFunction, InputArgv);

  // Now that we are done executing the program, shut down the execution engine
  delete EE;
  return ExitCode;
}
<commit_msg>The JIT is the default mode for LLI now<commit_after>//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
//
// This utility provides a way to execute LLVM bytecode without static
// compilation.  This consists of a very simple and slow (but portable)
// interpreter, along with capability for system specific dynamic compilers.  At
// runtime, the fastest (stable) execution engine is selected to run the
// program.  This means the JIT compiler for the current platform if it's
// available.
//
//===----------------------------------------------------------------------===//

#include "ExecutionEngine.h"
#include "Support/CommandLine.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Module.h"
#include "llvm/Target/TargetMachineImpls.h"

namespace {
  cl::opt<std::string>
  InputFile(cl::desc("<input bytecode>"), cl::Positional, cl::init("-"));

  cl::list<std::string>
  InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));

  cl::opt<std::string>
  MainFunction ("f", cl::desc("Function to execute"), cl::init("main"),
		cl::value_desc("function name"));

  cl::opt<bool> DebugMode("d", cl::desc("Start program in debugger"));

  cl::opt<bool> TraceMode("trace", cl::desc("Enable Tracing"));

  cl::opt<bool> ForceInterpreter("force-interpreter",
				 cl::desc("Force interpretation: disable JIT"),
				 cl::init(false));
}

//===----------------------------------------------------------------------===//
// ExecutionEngine Class Implementation
//

ExecutionEngine::~ExecutionEngine() {
  delete &CurMod;
}

//===----------------------------------------------------------------------===//
// main Driver function
//
int main(int argc, char** argv) {
  cl::ParseCommandLineOptions(argc, argv,
			      " llvm interpreter & dynamic compiler\n");

  // Load the bytecode...
  std::string ErrorMsg;
  Module *M = ParseBytecodeFile(InputFile, &ErrorMsg);
  if (M == 0) {
    std::cout << "Error parsing '" << InputFile << "': "
              << ErrorMsg << "\n";
    exit(1);
  }

#if 0
  // Link in the runtime library for LLI...
  std::string RuntimeLib = getCurrentExecutablePath();
  if (!RuntimeLib.empty()) RuntimeLib += "/";
  RuntimeLib += "RuntimeLib.bc";

  if (Module *SupportLib = ParseBytecodeFile(RuntimeLib, &ErrorMsg)) {
    if (LinkModules(M, SupportLib, &ErrorMsg))
      std::cerr << "Error Linking runtime library into current module: "
                << ErrorMsg << "\n";
  } else {
    std::cerr << "Error loading runtime library '"+RuntimeLib+"': "
              << ErrorMsg << "\n";
  }
#endif

  unsigned Config = (M->isLittleEndian()   ? TM::LittleEndian : TM::BigEndian) |
                    (M->has32BitPointers() ? TM::PtrSize32    : TM::PtrSize64);
  ExecutionEngine *EE = 0;

  // If there is nothing that is forcing us to use the interpreter, make a JIT.
  if (!ForceInterpreter && !DebugMode && !TraceMode)
    EE = ExecutionEngine::createJIT(M, Config);

  // If we can't make a JIT, make an interpreter instead.
  if (EE == 0)
    EE = ExecutionEngine::createInterpreter(M, Config, DebugMode, TraceMode);

  // Add the module name to the start of the argv vector...
  InputArgv.insert(InputArgv.begin(), InputFile);

  // Run the main function!
  int ExitCode = EE->run(MainFunction, InputArgv);

  // Now that we are done executing the program, shut down the execution engine
  delete EE;
  return ExitCode;
}
<|endoftext|>


<commit_before>#include <chord.h>
#include <location.h>
#include <locationtable.h>
#include <dhash_common.h>
#include <dhash.h>
#include <misc_utils.h>
#include "dhblock.h"
#include "download.h"

// ---------------------------------------------------------------------------
// dhash_download -- downloads a block of a specific chord node.  That node
//                   should already be in the location table.

dhash_download::dhash_download (ptr<vnode> clntnode, chord_node source,
				blockID blockID, char *data, u_int len,
				u_int totsz, int cookie, cbretrieve_t cb,
				cbtmo_t cb_tmo)
  : clntnode (clntnode),  npending (0), error (false), source (source),
				  blckID (blockID), cb (cb), cb_tmo (cb_tmo),
				  nextchunk (0), numchunks (0),
				  didrexmit (false)
{
  start = getusec ();
  // the first chunk of data may be passed in
  if (data) {
    process_first_chunk (data, len, totsz, cookie);
    check_finish ();
  } else {
    unsigned mtu = (clntnode->my_location ()->id () == source.x)
      ? 8192 : dhblock::dhash_mtu ();
    getchunk (0, mtu, 0, wrap (this, &dhash_download::first_chunk_cb));
  }
}

dhash_download::~dhash_download ()
{
  if (buffer) {
    free (buffer);
    buffer = NULL;
  }
}

void
dhash_download::getchunk (u_int start, u_int len, int cookie, gotchunkcb_t cb)
{
  ptr<s_dhash_fetch_arg> arg = New refcounted<s_dhash_fetch_arg>;
  arg->key   = blckID.ID;
  arg->ctype = blckID.ctype;
  arg->start = start;
  arg->len   = len;
  arg->cookie = cookie;

  npending++;
  ptr<dhash_fetchiter_res> res = New refcounted<dhash_fetchiter_res> ();

  long seqno = clntnode->doRPC
    (source, dhash_program_1, DHASHPROC_FETCHITER, arg, res,
     wrap (this, &dhash_download::gotchunk, cb, res, numchunks++),
     cb_tmo);

  seqnos.push_back (seqno);
}

void
dhash_download::gotchunk (gotchunkcb_t cb, ptr<dhash_fetchiter_res> res,
			  int chunknum, clnt_stat err)
{
  (*cb) (res, chunknum, err);
}

void
dhash_download::first_chunk_cb  (ptr<dhash_fetchiter_res> res, int chunknum,
				 clnt_stat err)
{
  npending--;

  if (err || (res && res->status != DHASH_COMPLETE))
    fail (dhasherr2str (res->status));
  else {
    int cookie     = res->compl_res->cookie;
    size_t totsz   = res->compl_res->attr.size;
    size_t datalen = res->compl_res->res.size ();
    char  *data    = res->compl_res->res.base ();
    process_first_chunk (data, datalen, totsz, cookie);
  }
  check_finish ();
}

void
dhash_download::process_first_chunk (char *data, size_t datalen, size_t totsz,
				     int cookie)
{
  buf_len = totsz;
  buffer = (char *)malloc (buf_len);

  nextchunk++;
  add_data (data, datalen, 0);

  //issue the RPCs to get the other chunks
  size_t nread = datalen;
  while (nread < totsz) {
    unsigned mtu = (clntnode->my_location ()->id () == source.x)
      ? 8192 : dhblock::dhash_mtu ();
    int length = MIN (mtu, totsz - nread);
    getchunk (nread, length, cookie,
	      wrap (this, &dhash_download::later_chunk_cb));
    nread += length;
  }
}

void
dhash_download::later_chunk_cb (ptr<dhash_fetchiter_res> res, int chunknum,
				clnt_stat err)
{
  npending--;

  if (err || (res && res->status != DHASH_COMPLETE))
    fail (dhasherr2str (res->status));
  else {

    if (!didrexmit && (chunknum > nextchunk)) {
      warn << "FAST retransmit: " << blckID << " chunk "
	   << nextchunk << " being retransmitted.\n";
      clntnode->resendRPC (seqnos[nextchunk]);
      didrexmit = true;  // be conservative: only fast rexmit once per block
    }

    nextchunk++;
    add_data (res->compl_res->res.base (), res->compl_res->res.size (),
	      res->compl_res->offset);
  }
  check_finish ();
}

void
dhash_download::add_data (char *data, int len, int off)
{
  if ((unsigned)(off + len) > (u_int)buf_len)
    fail (strbuf ("bad chunk: off %d, len %d, block %d",
		  off, len, buf_len));
  else
    memcpy (buffer + off, data, len);
}

void
dhash_download::check_finish ()
{
  if (npending == 0) {
    ptr<dhash_block> block = NULL;
    /* got all chunks */
    if (!error)  {
      block = New refcounted<dhash_block> (buffer, buf_len, blckID.ctype);
      block->source = source.x;
      block->hops   = 0;
      block->errors = 0;
    }
    (*cb) (block);
    delete this;
  }
}

void
dhash_download::fail (str errstr)
{
  warn << "dhash_download failed: " << blckID << ": "
       << errstr << " at " << source.x << "\n";
  error = true;
}

<commit_msg>Initialize memory.<commit_after>#include <chord.h>
#include <location.h>
#include <locationtable.h>
#include <dhash_common.h>
#include <dhash.h>
#include <misc_utils.h>
#include "dhblock.h"
#include "download.h"

// ---------------------------------------------------------------------------
// dhash_download -- downloads a block of a specific chord node.  That node
//                   should already be in the location table.

dhash_download::dhash_download (ptr<vnode> clntnode, chord_node source,
				blockID blockID, char *data, u_int len,
				u_int totsz, int cookie, cbretrieve_t cb,
				cbtmo_t cb_tmo) :
  clntnode (clntnode),
  npending (0),
  error (false),
  source (source),
  blckID (blockID),
  cb (cb),
  cb_tmo (cb_tmo),
  buffer (NULL),
  buf_len (0),
  nextchunk (0),
  numchunks (0),
  didrexmit (false),
  start (getusec ())
{
  // the first chunk of data may be passed in
  if (data) {
    process_first_chunk (data, len, totsz, cookie);
    check_finish ();
  } else {
    unsigned mtu = (clntnode->my_location ()->id () == source.x)
      ? 8192 : dhblock::dhash_mtu ();
    getchunk (0, mtu, 0, wrap (this, &dhash_download::first_chunk_cb));
  }
}

dhash_download::~dhash_download ()
{
  if (buffer) {
    free (buffer);
    buffer = NULL;
  }
}

void
dhash_download::getchunk (u_int start, u_int len, int cookie, gotchunkcb_t cb)
{
  ptr<s_dhash_fetch_arg> arg = New refcounted<s_dhash_fetch_arg>;
  arg->key   = blckID.ID;
  arg->ctype = blckID.ctype;
  arg->start = start;
  arg->len   = len;
  arg->cookie = cookie;

  npending++;
  ptr<dhash_fetchiter_res> res = New refcounted<dhash_fetchiter_res> ();

  long seqno = clntnode->doRPC
    (source, dhash_program_1, DHASHPROC_FETCHITER, arg, res,
     wrap (this, &dhash_download::gotchunk, cb, res, numchunks++),
     cb_tmo);

  seqnos.push_back (seqno);
}

void
dhash_download::gotchunk (gotchunkcb_t cb, ptr<dhash_fetchiter_res> res,
			  int chunknum, clnt_stat err)
{
  (*cb) (res, chunknum, err);
}

void
dhash_download::first_chunk_cb  (ptr<dhash_fetchiter_res> res, int chunknum,
				 clnt_stat err)
{
  npending--;

  if (err || (res && res->status != DHASH_COMPLETE))
    fail (dhasherr2str (res->status));
  else {
    int cookie     = res->compl_res->cookie;
    size_t totsz   = res->compl_res->attr.size;
    size_t datalen = res->compl_res->res.size ();
    char  *data    = res->compl_res->res.base ();
    process_first_chunk (data, datalen, totsz, cookie);
  }
  check_finish ();
}

void
dhash_download::process_first_chunk (char *data, size_t datalen, size_t totsz,
				     int cookie)
{
  buf_len = totsz;
  buffer = (char *)malloc (buf_len);

  nextchunk++;
  add_data (data, datalen, 0);

  //issue the RPCs to get the other chunks
  size_t nread = datalen;
  while (nread < totsz) {
    unsigned mtu = (clntnode->my_location ()->id () == source.x)
      ? 8192 : dhblock::dhash_mtu ();
    int length = MIN (mtu, totsz - nread);
    getchunk (nread, length, cookie,
	      wrap (this, &dhash_download::later_chunk_cb));
    nread += length;
  }
}

void
dhash_download::later_chunk_cb (ptr<dhash_fetchiter_res> res, int chunknum,
				clnt_stat err)
{
  npending--;

  if (err || (res && res->status != DHASH_COMPLETE))
    fail (dhasherr2str (res->status));
  else {

    if (!didrexmit && (chunknum > nextchunk)) {
      warn << "FAST retransmit: " << blckID << " chunk "
	   << nextchunk << " being retransmitted.\n";
      clntnode->resendRPC (seqnos[nextchunk]);
      didrexmit = true;  // be conservative: only fast rexmit once per block
    }

    nextchunk++;
    add_data (res->compl_res->res.base (), res->compl_res->res.size (),
	      res->compl_res->offset);
  }
  check_finish ();
}

void
dhash_download::add_data (char *data, int len, int off)
{
  if ((unsigned)(off + len) > (u_int)buf_len)
    fail (strbuf ("bad chunk: off %d, len %d, block %d",
		  off, len, buf_len));
  else
    memcpy (buffer + off, data, len);
}

void
dhash_download::check_finish ()
{
  if (npending == 0) {
    ptr<dhash_block> block = NULL;
    /* got all chunks */
    if (!error)  {
      block = New refcounted<dhash_block> (buffer, buf_len, blckID.ctype);
      block->source = source.x;
      block->hops   = 0;
      block->errors = 0;
    }
    (*cb) (block);
    delete this;
  }
}

void
dhash_download::fail (str errstr)
{
  warn << "dhash_download failed: " << blckID << ": "
       << errstr << " at " << source.x << "\n";
  error = true;
}

<|endoftext|>


<commit_before>

#include "RemoteReasoner.h"

#include "actasp/reasoners/Clingo.h"
#include "actasp/executors/ReplanningActionExecutor.h"
#include "actasp/ActionExecutor.h"
#include "actasp/AspFluent.h"
#include "actasp/planners/AnyPlan.h"

#include "actions/ActionFactory.h"
#include "actions/LogicalNavigation.h"

#include <ros/ros.h>
#include <ros/console.h>

#include <boost/filesystem.hpp>

#include <string>

using namespace std;
using namespace bwi_krexec;
using namespace actasp;

int main(int argc, char**argv) {
  ros::init(argc, argv, "bwi_action_execution");
  ros::NodeHandle n;

  if (ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug)) {
    ros::console::notifyLoggerLevelsChanged();
  }

//  create initial state
  LogicalNavigation setInitialState("noop");
  setInitialState.run();

  ActionFactory::setSimulation(true); //parametrize this

  AspKR *reasoner = new RemoteReasoner();
  Planner *planner = new AnyPlan(reasoner);
  ActionExecutor *executor = new ReplanningActionExecutor(reasoner,planner,ActionFactory::actions());

  vector<AspRule> goalRules;

  goalRules.push_back(AspRule() << AspFluent("not visited(l3_418,n)"));
  goalRules.push_back(AspRule() << AspFluent("not visited(l3_414a,n)"));

  executor->setGoal(goalRules);

  ros::Rate loop(10);

  while (ros::ok() && !executor->goalReached() && !executor->failed()) {

    executor->executeActionStep();

    ros::spinOnce();

    loop.sleep();
  }

  delete executor;
  delete reasoner;

  return 0;
}<commit_msg>minor changes in the action executor<commit_after>

#include "RemoteReasoner.h"

#include "actasp/reasoners/Clingo.h"
#include "actasp/executors/ReplanningActionExecutor.h"
#include "actasp/ActionExecutor.h"
#include "actasp/AspFluent.h"
#include "actasp/planners/AnyPlan.h"

#include "actions/ActionFactory.h"
#include "actions/LogicalNavigation.h"

#include <ros/ros.h>
#include <ros/console.h>

#include <boost/filesystem.hpp>

#include <string>

using namespace std;
using namespace bwi_krexec;
using namespace actasp;

int main(int argc, char**argv) {
  ros::init(argc, argv, "bwi_action_execution");
  ros::NodeHandle n;

  if (ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug)) {
    ros::console::notifyLoggerLevelsChanged();
  }

//  create initial state
  LogicalNavigation setInitialState("noop");
  setInitialState.run();

  ActionFactory::setSimulation(true); //parametrize this

  AspKR *reasoner = new RemoteReasoner();
  ActionExecutor *executor = new ReplanningActionExecutor(reasoner,reasoner,ActionFactory::actions());

  vector<AspRule> goalRules(1);

  goalRules[0].body.push_back(AspFluent("not at(l3_516,I)"));

  executor->setGoal(goalRules);

  ros::Rate loop(10);

  while (ros::ok() && !executor->goalReached() && !executor->failed()) {

    executor->executeActionStep();

    ros::spinOnce();

    loop.sleep();
  }

  if(executor->failed()) {
    ROS_INFO("Execution failed");
  }
  if(executor->goalReached()) {
    ROS_INFO("Execution succeded");
  }

  delete executor;
  delete reasoner;

  return 0;
}<|endoftext|>


<commit_before>//
//  diana_client.cpp
//  diana
//
//  Created by Raphael Bost on 20/07/2016.
//  Copyright © 2016 Raphael Bost. All rights reserved.
//

#include "diana/client_runner.hpp"
#include "utils/logger.hpp"
#include "aux/db_generator.hpp"

#include <sse/crypto/utils.hpp>

#include <list>
#include <mutex>
#include <iostream>

#include <unistd.h>
#include <stdio.h>

__thread std::list<std::pair<std::string, uint64_t>> *buffer_list__ = NULL;

int main(int argc, char** argv) {
    sse::logger::set_severity(sse::logger::INFO);
    sse::logger::set_benchmark_file("benchmark_diana_client.out");

    sse::crypto::init_crypto_lib();

    opterr = 0;
    int c;

    std::list<std::string> input_files;
    std::list<std::string> keywords;
    std::string json_file;
    std::string client_db;
    std::string output_path;
    bool print_stats = false;
    uint32_t bench_count = 0;
    uint32_t rnd_entries_count = 0;

    bool print_results = true;

    while ((c = getopt (argc, argv, "l:b:o:i:t:dpr:q")) != -1)
        switch (c)
    {
        case 'l':
            input_files.push_back(std::string(optarg));
            break;
        case 'b':
            client_db = std::string(optarg);
            break;
        case 'o':
            output_path = std::string(optarg);
            break;
        case 'i':
            json_file = std::string(optarg);
            break;
        case 't':
            bench_count = atoi(optarg);
            break;
        case 'd': // load a default file, only for debugging
//            input_files.push_back("/Volumes/Storage/WP_Inverted/inverted_index_all_sizes/inverted_index_10000.json");
            input_files.push_back("/Users/raphaelbost/Documents/inverted_index_1000.json");
            break;
        case 'p':
            print_stats = true;
            break;
        case 'q':
            print_results = false;
            break;
        case 'r':
            rnd_entries_count = (uint32_t)std::stod(std::string(optarg),nullptr);
            //atol(optarg);
            break;
        case '?':
            if (optopt == 'l' || optopt == 'b' || optopt == 'o' || optopt == 'i' || optopt == 't' || optopt == 'r')
                fprintf (stderr, "Option -%c requires an argument.\n", optopt);
            else if (isprint (optopt))
                fprintf (stderr, "Unknown option `-%c'.\n", optopt);
            else
                fprintf (stderr,
                         "Unknown option character `\\x%x'.\n",
                         optopt);
            return 1;
        default:
            exit(-1);
    }

    for (int index = optind; index < argc; index++)
    {
          keywords.push_back(std::string(argv[index]));
    }

    if (client_db.size()==0) {
        sse::logger::log(sse::logger::WARNING) << "Client database not specified" << std::endl;
        sse::logger::log(sse::logger::WARNING) << "Using \'test.dcdb\' by default" << std::endl;
        client_db = "test.dcdb";
    }else{
        sse::logger::log(sse::logger::INFO) << "Running client with database " << client_db << std::endl;
    }

    std::unique_ptr<sse::diana::DianaClientRunner> client_runner;

    if (json_file.size() > 0) {
        sse::logger::log(sse::logger::CRITICAL) << "JSON import is not supported in Diana!" << std::endl;
//        client_runner.reset( new sse::diana::DianaClientRunner("localhost:4241", client_db, json_file) );
    }else{
        size_t setup_size = 1e5;
        uint32_t n_keywords = 1e4;

        if( rnd_entries_count > 0)
        {
            setup_size = 11*rnd_entries_count;
            n_keywords = 1.4*rnd_entries_count/(10*std::thread::hardware_concurrency());
        }

        client_runner.reset( new sse::diana::DianaClientRunner("localhost:4241", client_db, setup_size, n_keywords) );
    }

    for (std::string &path : input_files) {
        sse::logger::log(sse::logger::INFO) << "Load file " << path << std::endl;
        client_runner->load_inverted_index(path);
        sse::logger::log(sse::logger::INFO) << "Done loading file " << path << std::endl;
    }

    if (rnd_entries_count > 0) {
        sse::logger::log(sse::logger::INFO) << "Randomly generating database with " << rnd_entries_count << " docs" << std::endl;

        std::mutex buffer_mtx;

        auto gen_callback = [&client_runner](const std::string &s, size_t i)
        {
            if (buffer_list__ == NULL) {
                buffer_list__ = new std::list<std::pair<std::string, uint64_t>>();
            }
            buffer_list__->push_back(std::make_pair(s, i));

            if (buffer_list__->size() >= 50) {
                client_runner->async_update(*buffer_list__);

                buffer_list__->clear();
            }
//            client_runner->async_update(s, i);
        };

        client_runner->start_update_session();
        sse::sophos::gen_db(rnd_entries_count, gen_callback);
        client_runner->end_update_session();
    }

    for (std::string &kw : keywords) {
        std::cout << "-------------- Search --------------" << std::endl;

        std::mutex logger_mtx;
        std::ostream& log_stream = sse::logger::log(sse::logger::INFO);
        bool first = true;

        auto print_callback = [&logger_mtx, &log_stream, &first, print_results](uint64_t res)
        {
            if (print_results) {
             logger_mtx.lock();

             if (!first) {
                 log_stream << ", ";
             }
             first = false;
             log_stream << res;

             logger_mtx.unlock();
            }
        };

        log_stream << "Search results: \n{";

        auto res = client_runner->search(kw, print_callback);

        log_stream << "}" << std::endl;
    }

    if (output_path.size()>0) {
        sse::logger::log(sse::logger::CRITICAL) << "JSON export is not supported in Diana!" << std::endl;

//        client_runner->output_db(output_path);
    }

    if (print_stats)
    {
        client_runner->print_stats(sse::logger::log(sse::logger::INFO));
    }

    client_runner.reset();

    sse::crypto::cleanup_crypto_lib();

    return 0;
}
<commit_msg>Removed useless CLI options for Diana's client<commit_after>//
//  diana_client.cpp
//  diana
//
//  Created by Raphael Bost on 20/07/2016.
//  Copyright © 2016 Raphael Bost. All rights reserved.
//

#include "diana/client_runner.hpp"
#include "utils/logger.hpp"
#include "aux/db_generator.hpp"

#include <sse/crypto/utils.hpp>

#include <list>
#include <mutex>
#include <iostream>

#include <unistd.h>
#include <stdio.h>

__thread std::list<std::pair<std::string, uint64_t>> *buffer_list__ = NULL;

int main(int argc, char** argv) {
    sse::logger::set_severity(sse::logger::INFO);
    sse::logger::set_benchmark_file("benchmark_diana_client.out");

    sse::crypto::init_crypto_lib();

    opterr = 0;
    int c;

    std::list<std::string> input_files;
    std::list<std::string> keywords;
    std::string client_db;
    bool print_stats = false;
    uint32_t rnd_entries_count = 0;

    bool print_results = true;

    while ((c = getopt (argc, argv, "l:b:dpr:q")) != -1)
        switch (c)
    {
        case 'l':
            input_files.push_back(std::string(optarg));
            break;
        case 'b':
            client_db = std::string(optarg);
            break;
        case 'd': // load a default file, only for debugging
//            input_files.push_back("/Volumes/Storage/WP_Inverted/inverted_index_all_sizes/inverted_index_10000.json");
            input_files.push_back("/Users/raphaelbost/Documents/inverted_index_1000.json");
            break;
        case 'p':
            print_stats = true;
            break;
        case 'q':
            print_results = false;
            break;
        case 'r':
            rnd_entries_count = (uint32_t)std::stod(std::string(optarg),nullptr);
            //atol(optarg);
            break;
        case '?':
            if (optopt == 'l' || optopt == 'b' || optopt == 'o' || optopt == 'i' || optopt == 't' || optopt == 'r')
                fprintf (stderr, "Option -%c requires an argument.\n", optopt);
            else if (isprint (optopt))
                fprintf (stderr, "Unknown option `-%c'.\n", optopt);
            else
                fprintf (stderr,
                         "Unknown option character `\\x%x'.\n",
                         optopt);
            return 1;
        default:
            exit(-1);
    }

    for (int index = optind; index < argc; index++)
    {
          keywords.push_back(std::string(argv[index]));
    }

    if (client_db.size()==0) {
        sse::logger::log(sse::logger::WARNING) << "Client database not specified" << std::endl;
        sse::logger::log(sse::logger::WARNING) << "Using \'test.dcdb\' by default" << std::endl;
        client_db = "test.dcdb";
    }else{
        sse::logger::log(sse::logger::INFO) << "Running client with database " << client_db << std::endl;
    }

    std::unique_ptr<sse::diana::DianaClientRunner> client_runner;

    size_t setup_size = 1e5;
    uint32_t n_keywords = 1e4;

    if( rnd_entries_count > 0)
    {
        setup_size = 11*rnd_entries_count;
        n_keywords = 1.4*rnd_entries_count/(10*std::thread::hardware_concurrency());
    }

    client_runner.reset( new sse::diana::DianaClientRunner("localhost:4241", client_db, setup_size, n_keywords) );

    for (std::string &path : input_files) {
        sse::logger::log(sse::logger::INFO) << "Load file " << path << std::endl;
        client_runner->load_inverted_index(path);
        sse::logger::log(sse::logger::INFO) << "Done loading file " << path << std::endl;
    }

    if (rnd_entries_count > 0) {
        sse::logger::log(sse::logger::INFO) << "Randomly generating database with " << rnd_entries_count << " docs" << std::endl;

        std::mutex buffer_mtx;

        auto gen_callback = [&client_runner](const std::string &s, size_t i)
        {
            if (buffer_list__ == NULL) {
                buffer_list__ = new std::list<std::pair<std::string, uint64_t>>();
            }
            buffer_list__->push_back(std::make_pair(s, i));

            if (buffer_list__->size() >= 50) {
                client_runner->async_update(*buffer_list__);

                buffer_list__->clear();
            }
//            client_runner->async_update(s, i);
        };

        client_runner->start_update_session();
        sse::sophos::gen_db(rnd_entries_count, gen_callback);
        client_runner->end_update_session();
    }

    for (std::string &kw : keywords) {
        std::cout << "-------------- Search --------------" << std::endl;

        std::mutex logger_mtx;
        std::ostream& log_stream = sse::logger::log(sse::logger::INFO);
        bool first = true;

        auto print_callback = [&logger_mtx, &log_stream, &first, print_results](uint64_t res)
        {
            if (print_results) {
             logger_mtx.lock();

             if (!first) {
                 log_stream << ", ";
             }
             first = false;
             log_stream << res;

             logger_mtx.unlock();
            }
        };

        log_stream << "Search results: \n{";

        auto res = client_runner->search(kw, print_callback);

        log_stream << "}" << std::endl;
    }

    if (print_stats)
    {
        client_runner->print_stats(sse::logger::log(sse::logger::INFO));
    }

    client_runner.reset();

    sse::crypto::cleanup_crypto_lib();

    return 0;
}
<|endoftext|>


<commit_before>#ifndef DISPLACEMENT_H
#define DISPLACEMENT_H

#include <fftw3.h>
#include <stdint.h>
#include "part_data.hpp"

class PowerSpec;

class DisplacementFields
{
    public:
        DisplacementFields(size_t Nmesh, int Seed, double Box, bool twolpt=true);
        lpt_data displacement_fields(const int type, part_grid& Pgrid, PowerSpec * PSpec, bool RayleighScatter=true);
        ~DisplacementFields();
    private:
        //Takes the computed Fourier displacement field and reads them into lpt_data outdata, using a grid specified in Pgrid.
        double displacement_read_out(const int order, lpt_data& outdata, part_grid& Pgrid, const int axes, const int type);
        //Size of the Fourier grid
        const size_t Nmesh;
        //Do we need a twolpt term?
        const bool twolpt;
        //Seed for the random number generator.
        //Constant for all particle types, so they are coherent.
        const int Seed;
        //Box size
        const double Box;
        //FFT variables for Zeldovich
        fftw_plan Inverse_plan;
        double *Disp;
        //This will always be a cast of Disp
        fftw_complex *Cdata;
        //Pointers for 2LPT term
        fftwf_plan Forward_plan2;
        fftwf_plan Inverse_plan_grad[3];
        float *twosrc;
        fftwf_complex *ctwosrc;
        fftwf_complex *(cdigrad[3]);
        float *(digrad[3]);
};

#endif
<commit_msg>Fix compiler warning<commit_after>#ifndef DISPLACEMENT_H
#define DISPLACEMENT_H

#include <fftw3.h>
#include <stdint.h>
#include "part_data.hpp"

class PowerSpec;

class DisplacementFields
{
    public:
        DisplacementFields(size_t Nmesh, int Seed, double Box, bool twolpt=true);
        lpt_data displacement_fields(const int type, part_grid& Pgrid, PowerSpec * PSpec, bool RayleighScatter=true);
        ~DisplacementFields();
    private:
        //Takes the computed Fourier displacement field and reads them into lpt_data outdata, using a grid specified in Pgrid.
        double displacement_read_out(const int order, lpt_data& outdata, part_grid& Pgrid, const int axes, const int type);
        //Size of the Fourier grid
        const size_t Nmesh;
        //Do we need a twolpt term?
        const bool twolpt;
        //Seed for the random number generator.
        //Constant for all particle types, so they are coherent.
        const int Seed;
        //Box size
        const double Box;
        //FFT variables for Zeldovich
        fftw_plan Inverse_plan;
        double *Disp;
        //This will always be a cast of Disp
        fftw_complex *Cdata;
        //Pointers for 2LPT term
        fftwf_plan Forward_plan2;
        fftwf_plan Inverse_plan_grad[3];
        float *twosrc;
        fftwf_complex *ctwosrc;
        fftwf_complex *cdigrad[3];
        float *digrad[3];
};

#endif
<|endoftext|>


<commit_before>/*
C++ implementation of the PCA fitter

L.Storchi, A.Modak, S.R.Chowdhury : 2016
*/
#include "../interface/PCATrackFitter.h"
#include "../interface/pcaconst.hpp"

namespace
{
  /* quick and very dirty */
  void dump_element (const pca::matrixpcaconst<double> & in, std::ostream & out)
  {
    out.precision(6);
    for (unsigned int i = 0; i<in.n_rows(); ++i)
    {
      for (unsigned int j = 0; j<in.n_cols(); ++j)
        out << std::scientific << in(i, j) << " ";
      out << std::endl;
    }
  }

  bool import_pca_const (const std::string & cfname,
      pca::matrixpcaconst<double> & cmtx_rz,
      pca::matrixpcaconst<double> & qvec_rz,
      pca::matrixpcaconst<double> & amtx_rz,
      pca::matrixpcaconst<double> & kvec_rz,
      pca::matrixpcaconst<double> & cmtx_rphi,
      pca::matrixpcaconst<double> & qvec_rphi,
      pca::matrixpcaconst<double> & amtx_rphi,
      pca::matrixpcaconst<double> & kvec_rphi,
      double eta, double pt,
      int chargesignin)
  {
    std::vector<pca::matrixpcaconst<double> > vct;
    if (pca::read_pcacosnt_from_file (vct, cfname.c_str()))
    {
      int hwmanygot = 0;
      std::vector<pca::matrixpcaconst<double> >::const_iterator it =
        vct.begin();
      for (; it != vct.end(); ++it)
      {
        double ptmin, ptmax, etamin, etamax;
        int chargesign;

        it->get_ptrange(ptmin, ptmax);
        it->get_etarange(etamin, etamax);
        chargesign = it->get_chargesign();

        if (it->get_plane_type() == pca::matrixpcaconst<double>::RZ)
        {
          if ((eta >= etamin) && (eta <= etamax))
          {
            switch(it->get_const_type())
            {
              case pca::matrixpcaconst<double>::QVEC :
                qvec_rz = *it;
                hwmanygot++;
                break;
              case pca::matrixpcaconst<double>::KVEC :
                kvec_rz = *it;
                hwmanygot++;
                break;
              case pca::matrixpcaconst<double>::CMTX :
                cmtx_rz = *it;
                hwmanygot++;
                break;
              case pca::matrixpcaconst<double>::AMTX :
                amtx_rz = *it;
                hwmanygot++;
                break;
              default:
                break;
            }
          }
        }
        else if (it->get_plane_type() == pca::matrixpcaconst<double>::RPHI)
        {
          if (chargesignin == chargesign)
          {
            if ((pt >= ptmin) && (pt <= ptmax))
            {
              switch(it->get_const_type())
              {
                case pca::matrixpcaconst<double>::QVEC :
                  qvec_rphi = *it;
                  hwmanygot++;
                  break;
                case pca::matrixpcaconst<double>::KVEC :
                  kvec_rphi = *it;
                  hwmanygot++;
                  break;
                case pca::matrixpcaconst<double>::CMTX :
                  cmtx_rphi = *it;
                  hwmanygot++;
                  break;
                case pca::matrixpcaconst<double>::AMTX :
                  amtx_rphi = *it;
                  hwmanygot++;
                  break;
                default:
                  break;
              }
            }
          }
        }
      }

      if (hwmanygot == 8)
        return true;
      else
      {
        std::cerr << "Found " << hwmanygot << " const instead of 8" << std::endl;
        return false;
      }
    }

    // TODO add consistency check for dims

    return false;
  }
}

PCATrackFitter::PCATrackFitter():TrackFitter(0)
{
}

PCATrackFitter::PCATrackFitter(int nb):TrackFitter(nb)
{
}

PCATrackFitter::~PCATrackFitter()
{
}

void PCATrackFitter::initialize()
{
}

void PCATrackFitter::mergePatterns()
{
}

// Tentative duplicate removal
// Not used for the moment

void PCATrackFitter::mergeTracks()
{
  unsigned int index = 0;
  vector<Track*>::iterator it = tracks.begin();

  while(it!=tracks.end())
  {
    Track* newTrack = *it;
    bool found = false;
    for(unsigned int i=0;i<index;i++)
    {
      Track* ref = tracks[i];
      float dpt,dphi,dz,deta;
      dpt = fabs(newTrack->getCurve()-ref->getCurve());
      dphi = fabs(newTrack->getPhi0()-ref->getPhi0());
      dz = fabs(newTrack->getZ0()-ref->getZ0());
      deta = fabs(newTrack->getEta0()-ref->getEta0());
      found = (deta<0.02) &&
	(dphi<0.005) &&
	(dpt<0.1) &&
	(dz<0.3);

      if(found)
	break;
    }

    if(found)
      tracks.erase(it);
    else
    {
      index++;
      it++;
    }
  }
}

void PCATrackFitter::setTracks(const std::vector<Track*> & intc)
{
  tracks_ = intc;
}

void PCATrackFitter::fit(vector<Hit*> hits)
{
  int tow = sector_id; // The tower ID, necessary to get the phi shift

  std::cout << "In PCA::fit tow: " << tow << std::endl;

  double sec_phi = 0;
  switch (tow%8)
  {
    case 0:
      sec_phi = 0.4;
      break;
    case 1:
      sec_phi = 1.2;
      break;
    case 3:
      sec_phi = 2.0;
      break;
    case 4:
      sec_phi = 2.7;
      break;
    case 5:
      sec_phi = -2.0;
      break;
    case 6:
      sec_phi = -1.2;
      break;
    case 7:
      sec_phi = -0.4;
      break;
  }

  double ci = cos(sec_phi);
  double si = sin(sec_phi);

  //std::cout << "tracks_.size() : " << tracks_.size() << std::endl;

  /*
  std::ofstream xyzfile;
  xyzfile.open ("PCAxyzfile.txt");

  std::ofstream rpzfile;
  rpzfile.open ("PCArphizfile.txt");
  */

  for(unsigned int tt=0; tt<tracks_.size(); ++tt)
  {
    //vector<int> stubids = tracks_[tt]->getStubs(); // TODO are they the hits idx ?

    //std::cout << "hits.size() : " << hits.size() << std::endl;

    if (hits.size() == 6)
    {
      pca::matrixpcaconst<double> zrv(1, 12), phirv(1, 12);
      unsigned int coordidx = 0;

      for(unsigned int idx = 0; idx < hits.size(); ++idx)
      {
        double xi =  hits[idx]->getX()*ci+ hits[idx]->getY()*si;
        double yi = -hits[idx]->getX()*si+ hits[idx]->getY()*ci;

        double zi = hits[idx]->getZ();
        double ri = sqrt(xi*xi+yi*yi);
        double pi = atan2(yi,xi);

        std::cout << "PCAxyz " << xi << " " << yi << " " << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;

        std::cout << "PCArpz " << xi << " " << yi << " " << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;

        /*
        xyzfile << xi << " " << yi << " " << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;

        rpzfile << ri << " " << pi << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;
        */

        zrv(0, coordidx) = zi;
        phirv(0, coordidx) = pi;

        ++coordidx;

        zrv(0, coordidx) = ri;
        phirv(0, coordidx) = ri;

        ++coordidx;
      }

      int charge;
      double pt_est, eta_est, z0_est, phi_est;
      charge = tracks_[tt]->getCharge();
      pt_est = tracks_[tt]->getCurve();
      eta_est = tracks_[tt]->getEta0();
      z0_est = tracks_[tt]->getZ0();
      phi_est = tracks_[tt]->getPhi0();

      /* TEST
      zrv(0, 0) = -16.1314; zrv(0, 1) = 23.3135;
      zrv(0, 2) = -22.7054; zrv(0, 3) = 34.8367;
      zrv(0, 4) = -32.6362; zrv(0, 5) = 51.9131;
      eta_est = -0.580448;
      z0_est = -2.65203;

      phirv(0, 0) = 2.74588; phirv(0, 1) = 23.2105;
      phirv(0, 2) = 2.76857; phirv(0, 3) = 37.0286;
      phirv(0, 4) = 2.79267; phirv(0, 5) = 51.2692;
      phirv(0, 6) = 2.82109; phirv(0, 7) = 67.7289;
      phirv(0, 8) = 2.85643; phirv(0, 9) = 87.8179;
      phirv(0, 10) = 2.89452; phirv(0, 11) = 109.012;
      pt_est = 1.0/0.315806;
      phi_est = 2.70006;
      charge = +1;
      */

      std::string cfname = "./barrel_tow18_pca_const.txt";

      pca::matrixpcaconst<double> cmtx_rz(0, 0);
      pca::matrixpcaconst<double> qvec_rz(0, 0);
      pca::matrixpcaconst<double> amtx_rz(0, 0);
      pca::matrixpcaconst<double> kvec_rz(0, 0);
      pca::matrixpcaconst<double> cmtx_rphi(0, 0);
      pca::matrixpcaconst<double> qvec_rphi(0, 0);
      pca::matrixpcaconst<double> amtx_rphi(0, 0);
      pca::matrixpcaconst<double> kvec_rphi(0, 0);

      if (import_pca_const (cfname,
                            cmtx_rz,
                            qvec_rz,
                            amtx_rz,
                            kvec_rz,
                            cmtx_rphi,
                            qvec_rphi,
                            amtx_rphi,
                            kvec_rphi,
                            eta_est,
                            pt_est,
                            charge))
      {
        /*
        std::cout << "CMTX RZ: " << std::endl;
        dump_element(cmtx_rz, std::cout);

        std::cout << "QVEC RZ: " << std::endl;
        dump_element(qvec_rz, std::cout);

        std::cout << "CMTX RPHI: " << std::endl;
        dump_element(cmtx_rphi, std::cout);

        std::cout << "QVEC RPHI: " << std::endl;
        dump_element(qvec_rphi, std::cout);
        */

        double cottheta = 0.0; // eta
        double z0 = 0.0;

        cottheta = qvec_rz(0,0);
        z0 = qvec_rz(0,1);
        for (int i=0; i<(int)cmtx_rz.n_cols(); ++i)
        {
          cottheta += cmtx_rz(0, i) * zrv(0, i);
          z0 += cmtx_rz(1, i) * zrv(0, i);
        }

        double coverpt = 0.0; // pt
        double phi = 0.0;

        coverpt = qvec_rphi(0,0);
        phi = qvec_rphi(0,1);
        for (int i=0; i<(int)cmtx_rphi.n_cols(); ++i)
        {
          coverpt += cmtx_rphi(0, i) * phirv(0, i);
          phi += cmtx_rphi(1, i) * phirv(0, i);
        }

        double pt = (double)(charge)/coverpt;

        // TODO: checkit theta to eta
        double eta = 0.0e0;
        double theta = atan(1.0e0 / cottheta);
        double tantheta2 = tan (theta/2.0e0);
        if (tantheta2 < 0.0)
          eta = 1.0e0 * log (-1.0e0 * tantheta2);
        else
          eta = -1.0e0 * log (tantheta2);

        Track* fit_track = new Track();

        std::cout.precision(8);
        std::cout << std::scientific << " pt : " << pt << " ==> " << pt_est << std::endl;
        std::cout << std::scientific << " phi: " << phi << " ==> " << phi_est << std::endl;
        std::cout << std::scientific << " eta: " << eta << " ==> " << eta_est << std::endl;
        std::cout << std::scientific << " z0 : " << z0 << " ==> " << z0_est << std::endl;

        fit_track->setCurve(pt);
        fit_track->setPhi0(phi);
        fit_track->setEta0(eta);
        fit_track->setZ0(z0);

        for(unsigned int idx = 0; idx < hits.size(); ++idx)
          fit_track->addStubIndex(idx);

        tracks.push_back(fit_track);
      }
      else
      {
        std::cerr << "error while reading PCA const" << std::endl;
        std::cout << "error while reading PCA const" << std::endl;
      }

    }
    else
    {
      // TODO non 6 layers
    }
  }

  /*
  xyzfile.close();
  rpzfile.close();

  std::cout << "Close files" << std::endl;
  */
}

void PCATrackFitter::fit()
{

  vector<Hit*> activatedHits;

  //////// Get the list of unique stubs from the tracks ///////////

  // TODO not sure will work as it is now need to deal with given
  //      tracks

  set<int> ids;
  int total=0;
  for (unsigned int i=0; i<patterns.size(); ++i)
  {
    vector<Hit*> allHits = patterns[i]->getHits();
    total+=allHits.size();
    for(unsigned int j=0; j<allHits.size(); ++j)
    {
      pair<set<int>::iterator,bool> result = ids.insert(allHits[j]->getID());
      if (result.second == true )
        activatedHits.push_back(allHits[j]);
    }
  }

  fit(activatedHits);
}

TrackFitter* PCATrackFitter::clone()
{
  PCATrackFitter* fit = new PCATrackFitter(nb_layers);

  // TODO

  return fit;
}

<commit_msg>backup<commit_after>/*
C++ implementation of the PCA fitter

L.Storchi, A.Modak, S.R.Chowdhury : 2016
*/
#include "../interface/PCATrackFitter.h"
#include "../interface/pcaconst.hpp"

namespace
{
  /* quick and very dirty */
  void dump_element (const pca::matrixpcaconst<double> & in, std::ostream & out)
  {
    out.precision(6);
    for (unsigned int i = 0; i<in.n_rows(); ++i)
    {
      for (unsigned int j = 0; j<in.n_cols(); ++j)
        out << std::scientific << in(i, j) << " ";
      out << std::endl;
    }
  }

  bool import_pca_const (const std::string & cfname,
      pca::matrixpcaconst<double> & cmtx_rz,
      pca::matrixpcaconst<double> & qvec_rz,
      pca::matrixpcaconst<double> & amtx_rz,
      pca::matrixpcaconst<double> & kvec_rz,
      pca::matrixpcaconst<double> & cmtx_rphi,
      pca::matrixpcaconst<double> & qvec_rphi,
      pca::matrixpcaconst<double> & amtx_rphi,
      pca::matrixpcaconst<double> & kvec_rphi,
      double eta, double pt,
      int chargesignin)
  {
    std::vector<pca::matrixpcaconst<double> > vct;
    if (pca::read_pcacosnt_from_file (vct, cfname.c_str()))
    {
      int hwmanygot = 0;
      std::vector<pca::matrixpcaconst<double> >::const_iterator it =
        vct.begin();
      for (; it != vct.end(); ++it)
      {
        double ptmin, ptmax, etamin, etamax;
        int chargesign;

        it->get_ptrange(ptmin, ptmax);
        it->get_etarange(etamin, etamax);
        chargesign = it->get_chargesign();

        if (it->get_plane_type() == pca::matrixpcaconst<double>::RZ)
        {
          if ((eta >= etamin) && (eta <= etamax))
          {
            switch(it->get_const_type())
            {
              case pca::matrixpcaconst<double>::QVEC :
                qvec_rz = *it;
                hwmanygot++;
                break;
              case pca::matrixpcaconst<double>::KVEC :
                kvec_rz = *it;
                hwmanygot++;
                break;
              case pca::matrixpcaconst<double>::CMTX :
                cmtx_rz = *it;
                hwmanygot++;
                break;
              case pca::matrixpcaconst<double>::AMTX :
                amtx_rz = *it;
                hwmanygot++;
                break;
              default:
                break;
            }
          }
        }
        else if (it->get_plane_type() == pca::matrixpcaconst<double>::RPHI)
        {
          if (chargesignin == chargesign)
          {
            if ((pt >= ptmin) && (pt <= ptmax))
            {
              switch(it->get_const_type())
              {
                case pca::matrixpcaconst<double>::QVEC :
                  qvec_rphi = *it;
                  hwmanygot++;
                  break;
                case pca::matrixpcaconst<double>::KVEC :
                  kvec_rphi = *it;
                  hwmanygot++;
                  break;
                case pca::matrixpcaconst<double>::CMTX :
                  cmtx_rphi = *it;
                  hwmanygot++;
                  break;
                case pca::matrixpcaconst<double>::AMTX :
                  amtx_rphi = *it;
                  hwmanygot++;
                  break;
                default:
                  break;
              }
            }
          }
        }
      }

      if (hwmanygot == 8)
        return true;
      else
      {
        std::cerr << "Found " << hwmanygot << " const instead of 8" << std::endl;
        return false;
      }
    }

    // TODO add consistency check for dims

    return false;
  }
}

PCATrackFitter::PCATrackFitter():TrackFitter(0)
{
}

PCATrackFitter::PCATrackFitter(int nb):TrackFitter(nb)
{
}

PCATrackFitter::~PCATrackFitter()
{
}

void PCATrackFitter::initialize()
{
}

void PCATrackFitter::mergePatterns()
{
}

// Tentative duplicate removal
// Not used for the moment

void PCATrackFitter::mergeTracks()
{
  unsigned int index = 0;
  vector<Track*>::iterator it = tracks.begin();

  while(it!=tracks.end())
  {
    Track* newTrack = *it;
    bool found = false;
    for(unsigned int i=0;i<index;i++)
    {
      Track* ref = tracks[i];
      float dpt,dphi,dz,deta;
      dpt = fabs(newTrack->getCurve()-ref->getCurve());
      dphi = fabs(newTrack->getPhi0()-ref->getPhi0());
      dz = fabs(newTrack->getZ0()-ref->getZ0());
      deta = fabs(newTrack->getEta0()-ref->getEta0());
      found = (deta<0.02) &&
	(dphi<0.005) &&
	(dpt<0.1) &&
	(dz<0.3);

      if(found)
	break;
    }

    if(found)
      tracks.erase(it);
    else
    {
      index++;
      it++;
    }
  }
}

void PCATrackFitter::setTracks(const std::vector<Track*> & intc)
{
  tracks_ = intc;
}

void PCATrackFitter::fit(vector<Hit*> hits)
{
  int tow = sector_id; // The tower ID, necessary to get the phi shift

  std::cout << "In PCA::fit tow: " << tow << std::endl;

  double sec_phi = 0;
  switch (tow%8)
  {
    case 0:
      sec_phi = 0.4;
      break;
    case 1:
      sec_phi = 1.2;
      break;
    case 3:
      sec_phi = 2.0;
      break;
    case 4:
      sec_phi = 2.7;
      break;
    case 5:
      sec_phi = -2.0;
      break;
    case 6:
      sec_phi = -1.2;
      break;
    case 7:
      sec_phi = -0.4;
      break;
  }

  double ci = cos(sec_phi);
  double si = sin(sec_phi);

  //std::cout << "tracks_.size() : " << tracks_.size() << std::endl;

  /*
  std::ofstream xyzfile;
  xyzfile.open ("PCAxyzfile.txt");

  std::ofstream rpzfile;
  rpzfile.open ("PCArphizfile.txt");
  */

  for(unsigned int tt=0; tt<tracks_.size(); ++tt)
  {
    //vector<int> stubids = tracks_[tt]->getStubs(); // TODO are they the hits idx ?

    //std::cout << "hits.size() : " << hits.size() << std::endl;

    if (hits.size() == 6)
    {
      pca::matrixpcaconst<double> zrv(1, 12), phirv(1, 12);
      unsigned int coordidx = 0;

      for(unsigned int idx = 0; idx < hits.size(); ++idx)
      {
        double xi =  hits[idx]->getX()*ci+ hits[idx]->getY()*si;
        double yi = -hits[idx]->getX()*si+ hits[idx]->getY()*ci;

        double zi = hits[idx]->getZ();
        double ri = sqrt(xi*xi+yi*yi);
        double pi = atan2(yi,xi);

        std::cout << "PCAxyz " << xi << " " << yi << " " << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;

        std::cout << "PCArpz " << ri << " " << pi << " " << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;

        /*
        xyzfile << xi << " " << yi << " " << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;

        rpzfile << ri << " " << pi << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;
        */

        zrv(0, coordidx) = zi;
        phirv(0, coordidx) = pi;

        ++coordidx;

        zrv(0, coordidx) = ri;
        phirv(0, coordidx) = ri;

        ++coordidx;
      }

      int charge;
      double pt_est, eta_est, z0_est, phi_est;
      charge = tracks_[tt]->getCharge();
      pt_est = tracks_[tt]->getCurve();
      eta_est = tracks_[tt]->getEta0();
      z0_est = tracks_[tt]->getZ0();
      phi_est = tracks_[tt]->getPhi0();

      /* TEST
      zrv(0, 0) = -16.1314; zrv(0, 1) = 23.3135;
      zrv(0, 2) = -22.7054; zrv(0, 3) = 34.8367;
      zrv(0, 4) = -32.6362; zrv(0, 5) = 51.9131;
      eta_est = -0.580448;
      z0_est = -2.65203;

      phirv(0, 0) = 2.74588; phirv(0, 1) = 23.2105;
      phirv(0, 2) = 2.76857; phirv(0, 3) = 37.0286;
      phirv(0, 4) = 2.79267; phirv(0, 5) = 51.2692;
      phirv(0, 6) = 2.82109; phirv(0, 7) = 67.7289;
      phirv(0, 8) = 2.85643; phirv(0, 9) = 87.8179;
      phirv(0, 10) = 2.89452; phirv(0, 11) = 109.012;
      pt_est = 1.0/0.315806;
      phi_est = 2.70006;
      charge = +1;
      */

      std::string cfname = "./barrel_tow18_pca_const.txt";

      pca::matrixpcaconst<double> cmtx_rz(0, 0);
      pca::matrixpcaconst<double> qvec_rz(0, 0);
      pca::matrixpcaconst<double> amtx_rz(0, 0);
      pca::matrixpcaconst<double> kvec_rz(0, 0);
      pca::matrixpcaconst<double> cmtx_rphi(0, 0);
      pca::matrixpcaconst<double> qvec_rphi(0, 0);
      pca::matrixpcaconst<double> amtx_rphi(0, 0);
      pca::matrixpcaconst<double> kvec_rphi(0, 0);

      if (import_pca_const (cfname,
                            cmtx_rz,
                            qvec_rz,
                            amtx_rz,
                            kvec_rz,
                            cmtx_rphi,
                            qvec_rphi,
                            amtx_rphi,
                            kvec_rphi,
                            eta_est,
                            pt_est,
                            charge))
      {
        /*
        std::cout << "CMTX RZ: " << std::endl;
        dump_element(cmtx_rz, std::cout);

        std::cout << "QVEC RZ: " << std::endl;
        dump_element(qvec_rz, std::cout);

        std::cout << "CMTX RPHI: " << std::endl;
        dump_element(cmtx_rphi, std::cout);

        std::cout << "QVEC RPHI: " << std::endl;
        dump_element(qvec_rphi, std::cout);
        */

        double cottheta = 0.0; // eta
        double z0 = 0.0;

        cottheta = qvec_rz(0,0);
        z0 = qvec_rz(0,1);
        for (int i=0; i<(int)cmtx_rz.n_cols(); ++i)
        {
          cottheta += cmtx_rz(0, i) * zrv(0, i);
          z0 += cmtx_rz(1, i) * zrv(0, i);
        }

        double coverpt = 0.0; // pt
        double phi = 0.0;

        coverpt = qvec_rphi(0,0);
        phi = qvec_rphi(0,1);
        for (int i=0; i<(int)cmtx_rphi.n_cols(); ++i)
        {
          coverpt += cmtx_rphi(0, i) * phirv(0, i);
          phi += cmtx_rphi(1, i) * phirv(0, i);
        }

        double pt = (double)(charge)/coverpt;

        // TODO: checkit theta to eta
        double eta = 0.0e0;
        double theta = atan(1.0e0 / cottheta);
        double tantheta2 = tan (theta/2.0e0);
        if (tantheta2 < 0.0)
          eta = 1.0e0 * log (-1.0e0 * tantheta2);
        else
          eta = -1.0e0 * log (tantheta2);

        Track* fit_track = new Track();

        std::cout << " pt : " << pt << " ==> " << pt_est << std::endl;
        std::cout << " phi: " << phi << " ==> " << phi_est << std::endl;
        std::cout << " eta: " << eta << " ==> " << eta_est << std::endl;
        std::cout << " z0 : " << z0 << " ==> " << z0_est << std::endl;

        fit_track->setCurve(pt);
        fit_track->setPhi0(phi);
        fit_track->setEta0(eta);
        fit_track->setZ0(z0);

        for(unsigned int idx = 0; idx < hits.size(); ++idx)
          fit_track->addStubIndex(idx);

        tracks.push_back(fit_track);
      }
      else
      {
        std::cerr << "error while reading PCA const" << std::endl;
        std::cout << "error while reading PCA const" << std::endl;
      }

    }
    else
    {
      // TODO non 6 layers
    }
  }

  /*
  xyzfile.close();
  rpzfile.close();

  std::cout << "Close files" << std::endl;
  */
}

void PCATrackFitter::fit()
{

  vector<Hit*> activatedHits;

  //////// Get the list of unique stubs from the tracks ///////////

  // TODO not sure will work as it is now need to deal with given
  //      tracks

  set<int> ids;
  int total=0;
  for (unsigned int i=0; i<patterns.size(); ++i)
  {
    vector<Hit*> allHits = patterns[i]->getHits();
    total+=allHits.size();
    for(unsigned int j=0; j<allHits.size(); ++j)
    {
      pair<set<int>::iterator,bool> result = ids.insert(allHits[j]->getID());
      if (result.second == true )
        activatedHits.push_back(allHits[j]);
    }
  }

  fit(activatedHits);
}

TrackFitter* PCATrackFitter::clone()
{
  PCATrackFitter* fit = new PCATrackFitter(nb_layers);

  // TODO

  return fit;
}

<|endoftext|>