<commit_before>//===--- LLVMOpt.cpp ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// This is a simple reimplementation of opt that includes support for Swift-
/// specific LLVM passes. It is meant to make it easier to handle issues related
/// to transitioning to the new LLVM pass manager (which lacks the dynamism of
/// the old pass manager) and also problems during the code base transition to
/// that pass manager. Additionally it will enable a user to exactly simulate
/// Swift's LLVM pass pipeline by using the same pass pipeline building
/// machinery in IRGen, something not possible with opt.
///
//===----------------------------------------------------------------------===//

#include "swift/Subsystems.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Basic/LLVMContext.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/LLVMPasses/PassesFwd.h"
#include "swift/LLVMPasses/Passes.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/CallGraphSCCPass.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/RegionPass.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Bitcode/BitcodeWriterPass.h"
#include "llvm/CodeGen/CommandFlags.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/IRPrintingPasses.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/LegacyPassNameParser.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/InitializePasses.h"
#include "llvm/LinkAllIR.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"

using namespace swift;

//===----------------------------------------------------------------------===//
//                            Option Declarations
//===----------------------------------------------------------------------===//

// The OptimizationList is automatically populated with registered passes by the
// PassNameParser.
//
static llvm::cl::list<const llvm::PassInfo *, bool, llvm::PassNameParser>
    PassList(llvm::cl::desc("Optimizations available:"));

static llvm::cl::opt<bool>
    Optimized("O", llvm::cl::desc("Optimization level O. Similar to swift -O"));

// TODO: I wanted to call this 'verify', but some other pass is using this
// option.
static llvm::cl::opt<bool> VerifyEach(
    "verify-each",
    llvm::cl::desc("Should we spend time verifying that the IR is well "
                   "formed"));

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

static llvm::cl::opt<bool>
    PrintStats("print-stats",
               llvm::cl::desc("Should LLVM Statistics be printed"));

static cl::opt<std::string> InputFilename(cl::Positional,
                                          cl::desc("<input file>"),
                                          cl::init("-"),
                                          cl::value_desc("filename"));

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

static cl::opt<std::string> DefaultDataLayout(
    "default-data-layout",
    cl::desc("data layout string to use if not specified by module"),
    cl::value_desc("layout-string"), cl::init(""));

//===----------------------------------------------------------------------===//
//                               Helper Methods
//===----------------------------------------------------------------------===//

static llvm::CodeGenOpt::Level GetCodeGenOptLevel() {
  // TODO: Is this the right thing to do here?
  if (Optimized)
    return CodeGenOpt::Default;
  return CodeGenOpt::None;
}

// Returns the TargetMachine instance or zero if no triple is provided.
static llvm::TargetMachine *
getTargetMachine(llvm::Triple TheTriple, StringRef CPUStr,
                 StringRef FeaturesStr, const llvm::TargetOptions &Options) {
  std::string Error;
  const auto *TheTarget =
      llvm::TargetRegistry::lookupTarget(MArch, TheTriple, Error);
  // Some modules don't specify a triple, and this is okay.
  if (!TheTarget) {
    return nullptr;
  }

  return TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr,
                                        FeaturesStr, Options, RelocModel,
                                        CMModel, GetCodeGenOptLevel());
}

static void dumpOutput(llvm::Module &M, llvm::raw_ostream &os) {
  // For now just always dump assembly.
  legacy::PassManager EmitPasses;
  EmitPasses.add(createPrintModulePass(os));
  EmitPasses.run(M);
}

// This function isn't referenced outside its translation unit, but it
// can't use the "static" keyword because its address is used for
// getMainExecutable (since some platforms don't support taking the
// address of main, and some platforms can't implement getMainExecutable
// without being given the address of a function in the main executable).
void anchorForGetMainExecutable() {}

static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
  // Add the pass to the pass manager...
  PM.add(P);
  if (P->getPassID() == &SwiftAAWrapperPass::ID) {
    PM.add(createExternalAAWrapperPass([](Pass &P, Function &, AAResults &AAR) {
      if (auto *WrapperPass = P.getAnalysisIfAvailable<SwiftAAWrapperPass>())
        AAR.addAAResult(WrapperPass->getResult());
    }));
  }

  // If we are verifying all of the intermediate steps, add the verifier...
  if (VerifyEach)
    PM.add(createVerifierPass());
}

static void runSpecificPasses(StringRef Binary, llvm::Module *M,
                              llvm::TargetMachine *TM,
                              llvm::Triple &ModuleTriple) {
  llvm::legacy::PassManager Passes;
  llvm::TargetLibraryInfoImpl TLII(ModuleTriple);
  Passes.add(new TargetLibraryInfoWrapperPass(TLII));

  const llvm::DataLayout &DL = M->getDataLayout();
  if (DL.isDefault() && !DefaultDataLayout.empty()) {
    M->setDataLayout(DefaultDataLayout);
  }

  // Add internal analysis passes from the target machine.
  Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
                                                     : TargetIRAnalysis()));

  for (const llvm::PassInfo *PassInfo : PassList) {
    llvm::Pass *P = nullptr;
    if (PassInfo->getTargetMachineCtor())
      P = PassInfo->getTargetMachineCtor()(TM);
    else if (PassInfo->getNormalCtor())
      P = PassInfo->getNormalCtor()();
    else
      errs() << Binary << ": cannot create pass: " << PassInfo->getPassName()
             << "\n";
    if (P) {
      addPass(Passes, P);
    }
  }

  // Do it.
  Passes.run(*M);
}

//===----------------------------------------------------------------------===//
//                            Main Implementation
//===----------------------------------------------------------------------===//

int main(int argc, char **argv) {
  INITIALIZE_LLVM(argc, argv);

  // Initialize passes
  PassRegistry &Registry = *PassRegistry::getPassRegistry();
  initializeCore(Registry);
  initializeScalarOpts(Registry);
  initializeObjCARCOpts(Registry);
  initializeVectorization(Registry);
  initializeIPO(Registry);
  initializeAnalysis(Registry);
  initializeTransformUtils(Registry);
  initializeInstCombine(Registry);
  initializeInstrumentation(Registry);
  initializeTarget(Registry);
  // For codegen passes, only passes that do IR to IR transformation are
  // supported.
  initializeCodeGenPreparePass(Registry);
  initializeAtomicExpandPass(Registry);
  initializeRewriteSymbolsPass(Registry);
  initializeWinEHPreparePass(Registry);
  initializeDwarfEHPreparePass(Registry);
  initializeSjLjEHPreparePass(Registry);

  // Register Swift Only Passes.
  initializeSwiftAAWrapperPassPass(Registry);
  initializeSwiftRCIdentityPass(Registry);
  initializeSwiftARCOptPass(Registry);
  initializeSwiftARCContractPass(Registry);
  initializeSwiftStackPromotionPass(Registry);
  initializeInlineTreePrinterPass(Registry);
  initializeSwiftMergeFunctionsPass(Registry);

  llvm::cl::ParseCommandLineOptions(argc, argv, "Swift LLVM optimizer\n");

  if (PrintStats)
    llvm::EnableStatistics();

  llvm::SMDiagnostic Err;

  // Load the input module...
  std::unique_ptr<Module> M =
      parseIRFile(InputFilename, Err, getGlobalLLVMContext());

  if (!M) {
    Err.print(argv[0], errs());
    return 1;
  }

  if (verifyModule(*M, &errs())) {
    errs() << argv[0] << ": " << InputFilename
           << ": error: input module is broken!\n";
    return 1;
  }

  // If we are supposed to override the target triple, do so now.
  if (!TargetTriple.empty())
    M->setTargetTriple(llvm::Triple::normalize(TargetTriple));

  // Figure out what stream we are supposed to write to...
  std::unique_ptr<llvm::tool_output_file> Out;
  // Default to standard output.
  if (OutputFilename.empty())
    OutputFilename = "-";

  std::error_code EC;
  Out.reset(
      new llvm::tool_output_file(OutputFilename, EC, llvm::sys::fs::F_None));
  if (EC) {
    errs() << EC.message() << '\n';
    return 1;
  }

  llvm::Triple ModuleTriple(M->getTargetTriple());
  std::string CPUStr, FeaturesStr;
  llvm::TargetMachine *Machine = nullptr;
  const llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();

  if (ModuleTriple.getArch()) {
    CPUStr = getCPUStr();
    FeaturesStr = getFeaturesStr();
    Machine = getTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
  }

  std::unique_ptr<llvm::TargetMachine> TM(Machine);

  // Override function attributes based on CPUStr, FeaturesStr, and command line
  // flags.
  setFunctionAttributes(CPUStr, FeaturesStr, *M);

  if (Optimized) {
    IRGenOptions Opts;
    Opts.Optimize = true;

    // Then perform the optimizations.
    performLLVMOptimizations(Opts, M.get(), TM.get());
  } else {
    runSpecificPasses(argv[0], M.get(), TM.get(), ModuleTriple);
  }

  // Finally dump the output.
  dumpOutput(*M, Out->os());

  return 0;
}
<commit_msg>[stable-merge] [swift-llvm-opt] Pass RelocModel as an Optional<commit_after>//===--- LLVMOpt.cpp ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// This is a simple reimplementation of opt that includes support for Swift-
/// specific LLVM passes. It is meant to make it easier to handle issues related
/// to transitioning to the new LLVM pass manager (which lacks the dynamism of
/// the old pass manager) and also problems during the code base transition to
/// that pass manager. Additionally it will enable a user to exactly simulate
/// Swift's LLVM pass pipeline by using the same pass pipeline building
/// machinery in IRGen, something not possible with opt.
///
//===----------------------------------------------------------------------===//

#include "swift/Subsystems.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Basic/LLVMContext.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/LLVMPasses/PassesFwd.h"
#include "swift/LLVMPasses/Passes.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/CallGraphSCCPass.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/RegionPass.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Bitcode/BitcodeWriterPass.h"
#include "llvm/CodeGen/CommandFlags.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/IRPrintingPasses.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/LegacyPassNameParser.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/InitializePasses.h"
#include "llvm/LinkAllIR.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"

using namespace swift;

//===----------------------------------------------------------------------===//
//                            Option Declarations
//===----------------------------------------------------------------------===//

// The OptimizationList is automatically populated with registered passes by the
// PassNameParser.
//
static llvm::cl::list<const llvm::PassInfo *, bool, llvm::PassNameParser>
    PassList(llvm::cl::desc("Optimizations available:"));

static llvm::cl::opt<bool>
    Optimized("O", llvm::cl::desc("Optimization level O. Similar to swift -O"));

// TODO: I wanted to call this 'verify', but some other pass is using this
// option.
static llvm::cl::opt<bool> VerifyEach(
    "verify-each",
    llvm::cl::desc("Should we spend time verifying that the IR is well "
                   "formed"));

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

static llvm::cl::opt<bool>
    PrintStats("print-stats",
               llvm::cl::desc("Should LLVM Statistics be printed"));

static cl::opt<std::string> InputFilename(cl::Positional,
                                          cl::desc("<input file>"),
                                          cl::init("-"),
                                          cl::value_desc("filename"));

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

static cl::opt<std::string> DefaultDataLayout(
    "default-data-layout",
    cl::desc("data layout string to use if not specified by module"),
    cl::value_desc("layout-string"), cl::init(""));

//===----------------------------------------------------------------------===//
//                               Helper Methods
//===----------------------------------------------------------------------===//

static llvm::CodeGenOpt::Level GetCodeGenOptLevel() {
  // TODO: Is this the right thing to do here?
  if (Optimized)
    return CodeGenOpt::Default;
  return CodeGenOpt::None;
}

// Returns the TargetMachine instance or zero if no triple is provided.
static llvm::TargetMachine *
getTargetMachine(llvm::Triple TheTriple, StringRef CPUStr,
                 StringRef FeaturesStr, const llvm::TargetOptions &Options) {
  std::string Error;
  const auto *TheTarget =
      llvm::TargetRegistry::lookupTarget(MArch, TheTriple, Error);
  // Some modules don't specify a triple, and this is okay.
  if (!TheTarget) {
    return nullptr;
  }

  return TheTarget->createTargetMachine(
      TheTriple.getTriple(), CPUStr, FeaturesStr, Options,
      Optional<Reloc::Model>(RelocModel), CMModel, GetCodeGenOptLevel());
}

static void dumpOutput(llvm::Module &M, llvm::raw_ostream &os) {
  // For now just always dump assembly.
  legacy::PassManager EmitPasses;
  EmitPasses.add(createPrintModulePass(os));
  EmitPasses.run(M);
}

// This function isn't referenced outside its translation unit, but it
// can't use the "static" keyword because its address is used for
// getMainExecutable (since some platforms don't support taking the
// address of main, and some platforms can't implement getMainExecutable
// without being given the address of a function in the main executable).
void anchorForGetMainExecutable() {}

static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
  // Add the pass to the pass manager...
  PM.add(P);
  if (P->getPassID() == &SwiftAAWrapperPass::ID) {
    PM.add(createExternalAAWrapperPass([](Pass &P, Function &, AAResults &AAR) {
      if (auto *WrapperPass = P.getAnalysisIfAvailable<SwiftAAWrapperPass>())
        AAR.addAAResult(WrapperPass->getResult());
    }));
  }

  // If we are verifying all of the intermediate steps, add the verifier...
  if (VerifyEach)
    PM.add(createVerifierPass());
}

static void runSpecificPasses(StringRef Binary, llvm::Module *M,
                              llvm::TargetMachine *TM,
                              llvm::Triple &ModuleTriple) {
  llvm::legacy::PassManager Passes;
  llvm::TargetLibraryInfoImpl TLII(ModuleTriple);
  Passes.add(new TargetLibraryInfoWrapperPass(TLII));

  const llvm::DataLayout &DL = M->getDataLayout();
  if (DL.isDefault() && !DefaultDataLayout.empty()) {
    M->setDataLayout(DefaultDataLayout);
  }

  // Add internal analysis passes from the target machine.
  Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
                                                     : TargetIRAnalysis()));

  for (const llvm::PassInfo *PassInfo : PassList) {
    llvm::Pass *P = nullptr;
    if (PassInfo->getTargetMachineCtor())
      P = PassInfo->getTargetMachineCtor()(TM);
    else if (PassInfo->getNormalCtor())
      P = PassInfo->getNormalCtor()();
    else
      errs() << Binary << ": cannot create pass: " << PassInfo->getPassName()
             << "\n";
    if (P) {
      addPass(Passes, P);
    }
  }

  // Do it.
  Passes.run(*M);
}

//===----------------------------------------------------------------------===//
//                            Main Implementation
//===----------------------------------------------------------------------===//

int main(int argc, char **argv) {
  INITIALIZE_LLVM(argc, argv);

  // Initialize passes
  PassRegistry &Registry = *PassRegistry::getPassRegistry();
  initializeCore(Registry);
  initializeScalarOpts(Registry);
  initializeObjCARCOpts(Registry);
  initializeVectorization(Registry);
  initializeIPO(Registry);
  initializeAnalysis(Registry);
  initializeTransformUtils(Registry);
  initializeInstCombine(Registry);
  initializeInstrumentation(Registry);
  initializeTarget(Registry);
  // For codegen passes, only passes that do IR to IR transformation are
  // supported.
  initializeCodeGenPreparePass(Registry);
  initializeAtomicExpandPass(Registry);
  initializeRewriteSymbolsPass(Registry);
  initializeWinEHPreparePass(Registry);
  initializeDwarfEHPreparePass(Registry);
  initializeSjLjEHPreparePass(Registry);

  // Register Swift Only Passes.
  initializeSwiftAAWrapperPassPass(Registry);
  initializeSwiftRCIdentityPass(Registry);
  initializeSwiftARCOptPass(Registry);
  initializeSwiftARCContractPass(Registry);
  initializeSwiftStackPromotionPass(Registry);
  initializeInlineTreePrinterPass(Registry);
  initializeSwiftMergeFunctionsPass(Registry);

  llvm::cl::ParseCommandLineOptions(argc, argv, "Swift LLVM optimizer\n");

  if (PrintStats)
    llvm::EnableStatistics();

  llvm::SMDiagnostic Err;

  // Load the input module...
  std::unique_ptr<Module> M =
      parseIRFile(InputFilename, Err, getGlobalLLVMContext());

  if (!M) {
    Err.print(argv[0], errs());
    return 1;
  }

  if (verifyModule(*M, &errs())) {
    errs() << argv[0] << ": " << InputFilename
           << ": error: input module is broken!\n";
    return 1;
  }

  // If we are supposed to override the target triple, do so now.
  if (!TargetTriple.empty())
    M->setTargetTriple(llvm::Triple::normalize(TargetTriple));

  // Figure out what stream we are supposed to write to...
  std::unique_ptr<llvm::tool_output_file> Out;
  // Default to standard output.
  if (OutputFilename.empty())
    OutputFilename = "-";

  std::error_code EC;
  Out.reset(
      new llvm::tool_output_file(OutputFilename, EC, llvm::sys::fs::F_None));
  if (EC) {
    errs() << EC.message() << '\n';
    return 1;
  }

  llvm::Triple ModuleTriple(M->getTargetTriple());
  std::string CPUStr, FeaturesStr;
  llvm::TargetMachine *Machine = nullptr;
  const llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();

  if (ModuleTriple.getArch()) {
    CPUStr = getCPUStr();
    FeaturesStr = getFeaturesStr();
    Machine = getTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
  }

  std::unique_ptr<llvm::TargetMachine> TM(Machine);

  // Override function attributes based on CPUStr, FeaturesStr, and command line
  // flags.
  setFunctionAttributes(CPUStr, FeaturesStr, *M);

  if (Optimized) {
    IRGenOptions Opts;
    Opts.Optimize = true;

    // Then perform the optimizations.
    performLLVMOptimizations(Opts, M.get(), TM.get());
  } else {
    runSpecificPasses(argv[0], M.get(), TM.get(), ModuleTriple);
  }

  // Finally dump the output.
  dumpOutput(*M, Out->os());

  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include "PlanGenerator.h"
#include "PX4API.h"
#include "WorkspaceParser.h"
using namespace std;

#define SIMULATOR_PORT 14550

WS_Coord shiftBy = WS_Coord(25, 25, 0);

WS_Coord PlannerToGazebo(WS_Coord coord) {
    return WS_Coord(coord.x - shiftBy.x, coord.y - shiftBy.y, coord.z - shiftBy.z);
}

WS_Coord GazeboToPlanner(WS_Coord coord) {
    return WS_Coord(coord.x + shiftBy.x, coord.y + shiftBy.y, coord.z + shiftBy.z);
}

int main(int argc, char const *argv[])
{
    PX4API *px4 = new PX4API(SIMULATOR_PORT);
    char filename[] = "traj.csv";
    PX4Logger *px4logger = new PX4Logger(10, filename, true, vector<bool>{true, true, true});
    double eps = 1;

    usleep(2500000);
    px4->Arm();
    usleep(2500000);
    px4->StartAutopilot(0,0,-3); //takeoff
    usleep(5000000);

    WorkspaceInfo* WSInfo = ParseWorkspaceConfig(argv[1]);	//char* pathToWorkspace = "../../Src/Workspaces/Exp2";
	int count;
    int* output_seq_of_locations = (int*)malloc(100 * sizeof(int));
	int output_size = 0;
    int* gotos = (int*)malloc(100 * sizeof(int));
    int gotosSize = 0;
	// Testcase: Only static obstacles.
    vector<vector<WS_Coord>> avoidsArr;

    //Goto (1, 1, 2)
    WS_Coord destination = WS_Coord(1, 1, 2);
    WS_Coord currentLocation = GazeboToPlanner(WS_Coord(0, 0, 3));

    GenerateMotionPlanFor(0, WSInfo, WSInfo->ConvertCoordToGridLocation(currentLocation), WSInfo->ConvertCoordToGridLocation(destination), WSInfo->GetObstaclesLocations(), avoidsArr, output_seq_of_locations, &output_size);

    cout << "Trajectory Length = " << output_size << endl;
    cout << "Trajectory: " << endl;
    for (count = 0; count < output_size; count++)
    {
        cout << output_seq_of_locations[count] << endl;
    }

    ConvertToGotos(output_seq_of_locations, output_size, gotos, &gotosSize);
    cout << "Gotos: " << endl;
    for (count = 0; count < gotosSize; count++)
    {
        cout << gotos[count] << endl;
    }

    for (count = 0; count < gotosSize; count++)
    {
        WS_Coord go = PlannerToGazebo(WSInfo->ConvertGridLocationToCoord(gotos[count]));
        px4->GoTo(go.x,go.y,-go.z,0.5);
    }

	return 0;
}
<commit_msg>updated<commit_after>#include <iostream>
#include "PlanGenerator.h"
#include "PX4API.h"
#include "WorkspaceParser.h"
using namespace std;

#define SIMULATOR_PORT 14550

WS_Coord shiftBy = WS_Coord(25, 25, 0);

WS_Coord PlannerToGazebo(WS_Coord coord) {
    return WS_Coord(coord.x - shiftBy.x, coord.y - shiftBy.y, coord.z - shiftBy.z);
}

WS_Coord GazeboToPlanner(WS_Coord coord) {
    return WS_Coord(coord.x + shiftBy.x, coord.y + shiftBy.y, coord.z + shiftBy.z);
}

int main(int argc, char const *argv[])
{
    PX4API *px4 = new PX4API(SIMULATOR_PORT);
    char filename[] = "traj.csv";
    PX4Logger *px4logger = new PX4Logger(10, filename, true, vector<bool>{true, true, true});
    double eps = 1;

    usleep(2500000);
    px4->Arm();
    usleep(2500000);
    px4->StartAutopilot(0,0,-3); //takeoff
    usleep(5000000);

    WorkspaceInfo* WSInfo = ParseWorkspaceConfig(argv[1]);	//char* pathToWorkspace = "../../Src/Workspaces/Exp2";
	int count;
    int* output_seq_of_locations = (int*)malloc(100 * sizeof(int));
	int output_size = 0;
    int* gotos = (int*)malloc(100 * sizeof(int));
    int gotosSize = 0;
	// Testcase: Only static obstacles.
    vector<vector<WS_Coord>> avoidsArr;

    //Goto (1, 1, 2)
    vector<WS_Coord> destinations = { WS_Coord(1, 1, 2), WS_Coord(1, 40, 2), WS_Coord(43, 43, 2), WS_Coord(41, 1, 3)};

    WS_Coord currentLocation = GazeboToPlanner(WS_Coord(0, 0, 3));

    for(int locs = 0; locs < destinations.size(); locs++)
    {
        GenerateMotionPlanFor(0, WSInfo, WSInfo->ConvertCoordToGridLocation(currentLocation), WSInfo->ConvertCoordToGridLocation(destinations[locs]), WSInfo->GetObstaclesLocations(), avoidsArr, output_seq_of_locations, &output_size);

        cout << "Trajectory Length = " << output_size << endl;
        cout << "Trajectory: " << endl;
        for (count = 0; count < output_size; count++)
        {
            cout << output_seq_of_locations[count] << endl;
        }

        ConvertToGotos(output_seq_of_locations, output_size, gotos, &gotosSize);
        cout << "Gotos: " << endl;
        for (count = 0; count < gotosSize; count++)
        {
            cout << gotos[count] << endl;
        }

        for (count = 0; count < gotosSize; count++)
        {
            WS_Coord go = PlannerToGazebo(WSInfo->ConvertGridLocationToCoord(gotos[count]));
            px4->GoTo(go.x,go.y,-go.z, 1);
        }
        currentLocation = destinations[locs];
    }

	return 0;
}
<|endoftext|>


<commit_before>#include <mbed.h>
#include <cmsis_os.h>
#include <USBHID.h>
#include <memory>

#include "SharedSPI.hpp"
#include "CC1201Radio.hpp"
#include "logger.hpp"
#include "pins.hpp"
#include "usb-interface.hpp"
#include "watchdog.hpp"

#define RJ_WATCHDOG_TIMER_VALUE 2  // seconds

using namespace std;

USBHID usbLink(64, 64, RJ_VENDOR_ID, RJ_PRODUCT_ID, RJ_RELEASE);

shared_ptr<RtosTimer> rx_led_ticker;
shared_ptr<RtosTimer> tx_led_ticker;

bool initRadio() {
    /// A shared spi bus used for the fpga and cc1201 radio
    shared_ptr<SharedSPI> sharedSPI =
        make_shared<SharedSPI>(RJ_SPI_MOSI, RJ_SPI_MISO, RJ_SPI_SCK);
    sharedSPI->format(8, 0);  // 8 bits per transfer

    // RX/TX leds
    auto rxTimeoutLED =
        make_shared<FlashingTimeoutLED>(DigitalOut(LED1, OpenDrain));
    auto txTimeoutLED =
        make_shared<FlashingTimeoutLED>(DigitalOut(LED2, OpenDrain));

    // Startup the CommModule interface
    CommModule::Instance = make_shared<CommModule>(rxTimeoutLED, txTimeoutLED);
    shared_ptr<CommModule> commModule = CommModule::Instance;

    // Create a new physical hardware communication link
    global_radio =
        new CC1201(sharedSPI, RJ_RADIO_nCS, RJ_RADIO_INT, preferredSettings,
                   sizeof(preferredSettings) / sizeof(registerSetting_t));

    return global_radio->isConnected();
}

void radioRxHandler(rtp::packet* pkt) {
    // TODO: copy data
    HID_REPORT data;
    bool success = usbLink.sendNB(&data);
    if (!success) {
        LOG(WARN, "Failed to transfer received packet over usb");
    }
}

int main() {
    // set baud rate to higher value than the default for faster terminal
    Serial s(RJ_SERIAL_RXTX);
    s.baud(57600);

    // Set the default logging configurations
    isLogging = RJ_LOGGING_EN;
    rjLogLevel = INIT;

    LOG(INIT, "Base station starting...");

    if (initRadio()) {
        LOG(INIT, "Radio interface ready on %3.2fMHz!", global_radio->freq());

        CommModule::Instance->setRxHandler(&radioRxHandler, rtp::port::CONTROL);
        CommModule::Instance->setTxHandler(
            (CommLink*)global_radio, &CommLink::sendPacket, rtp::port::CONTROL);
    } else {
        LOG(FATAL, "No radio interface found!\r\n");
    }

    DigitalOut radioStatusLed(LED4, global_radio->isConnected());

    // Set the watdog timer's initial config
    Watchdog::Set(RJ_WATCHDOG_TIMER_VALUE);

    while (true) {
        // make sure we can always reach back to main by
        // renewing the watchdog timer periodically
        Watchdog::Renew();

        HID_REPORT data;
        usbLink.readNB(&data);
        rtp::packet pkt;  // TODO: fill data
        CommModule::Instance->send(pkt);
    }
}
<commit_msg>commented out HID stuff - program runs now<commit_after>#include <mbed.h>
#include <cmsis_os.h>
#include <USBHID.h>
#include <memory>

#include "SharedSPI.hpp"
#include "CC1201Radio.hpp"
#include "logger.hpp"
#include "pins.hpp"
#include "usb-interface.hpp"
#include "watchdog.hpp"

#define RJ_WATCHDOG_TIMER_VALUE 2  // seconds

using namespace std;

// USBHID usbLink(64, 64, RJ_VENDOR_ID, RJ_PRODUCT_ID, RJ_RELEASE);

shared_ptr<RtosTimer> rx_led_ticker;
shared_ptr<RtosTimer> tx_led_ticker;

bool initRadio() {
    /// A shared spi bus used for the fpga and cc1201 radio
    shared_ptr<SharedSPI> sharedSPI =
        make_shared<SharedSPI>(RJ_SPI_MOSI, RJ_SPI_MISO, RJ_SPI_SCK);
    sharedSPI->format(8, 0);  // 8 bits per transfer

    // RX/TX leds
    auto rxTimeoutLED =
        make_shared<FlashingTimeoutLED>(DigitalOut(LED1, OpenDrain));
    auto txTimeoutLED =
        make_shared<FlashingTimeoutLED>(DigitalOut(LED2, OpenDrain));

    // Startup the CommModule interface
    CommModule::Instance = make_shared<CommModule>(rxTimeoutLED, txTimeoutLED);
    shared_ptr<CommModule> commModule = CommModule::Instance;

    // Create a new physical hardware communication link
    global_radio =
        new CC1201(sharedSPI, RJ_RADIO_nCS, RJ_RADIO_INT, preferredSettings,
                   sizeof(preferredSettings) / sizeof(registerSetting_t));

    return global_radio->isConnected();
}

void radioRxHandler(rtp::packet* pkt) {
    // TODO: copy data
    HID_REPORT data;
    bool success = false;  // usbLink.sendNB(&data);

    if (!success) {
        LOG(WARN, "Failed to transfer received packet over usb");
    }
}

int main() {
    // set baud rate to higher value than the default for faster terminal
    Serial s(RJ_SERIAL_RXTX);
    s.baud(57600);

    // Set the default logging configurations
    isLogging = RJ_LOGGING_EN;
    rjLogLevel = INIT;

    LOG(INIT, "Base station starting...");

    if (initRadio()) {
        LOG(INIT, "Radio interface ready on %3.2fMHz!", global_radio->freq());

        CommModule::Instance->setRxHandler(&radioRxHandler, rtp::port::CONTROL);
        CommModule::Instance->setTxHandler(
            (CommLink*)global_radio, &CommLink::sendPacket, rtp::port::CONTROL);
    } else {
        LOG(FATAL, "No radio interface found!\r\n");
    }

    DigitalOut radioStatusLed(LED4, global_radio->isConnected());

    // Set the watdog timer's initial config
    Watchdog::Set(RJ_WATCHDOG_TIMER_VALUE);

    while (true) {
        // make sure we can always reach back to main by
        // renewing the watchdog timer periodically
        Watchdog::Renew();

        HID_REPORT data;
        // usbLink.readNB(&data);
        if (false) {
            rtp::packet pkt;  // TODO: fill data
            CommModule::Instance->send(pkt);
        }
    }
}
<|endoftext|>


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

// test for Realm's serializing code

#include "realm/serialize.h"

#include <sys/resource.h>
#include <string.h>

#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <map>
#include <list>

static bool verbose = false;
static int error_count = 0;

static void parse_args(int argc, const char *argv[])
{
  for(int i = 1; i < argc; i++) {
    if(!strcmp(argv[i], "-v")) {
      verbose = true;
      continue;
    }
  }
}

// helper functions to print out containers
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v)
{
  os << '[' << v.size() << ']';
  for(typename std::vector<T>::const_iterator it = v.begin();
      it != v.end();
      it++)
    os << ' ' << *it;
  return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::list<T>& l)
{
  os << '[' << l.size() << ']';
  for(typename std::list<T>::const_iterator it = l.begin();
      it != l.end();
      it++)
    os << ' ' << *it;
  return os;
}

template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& os, const std::map<T1, T2>& m)
{
  os << '[' << m.size() << ']';
  for(typename std::map<T1, T2>::const_iterator it = m.begin();
      it != m.end();
      it++)
    os << ' ' << it->first << '=' << it->second;
  return os;
}

template <typename T>
void test_dynamic(const char *name, const T& input, size_t exp_size = 0)
{
  // first serialize and check size
  Realm::Serialization::DynamicBufferSerializer dbs(0);

  bool ok1 = dbs << input;
  if(!ok1) {
    std::cout << "ERROR: " << name << "dynamic serialization failed!" << std::endl;
    error_count++;
  }

  size_t act_size = dbs.bytes_used();

  if(exp_size > 0) {
    if(act_size != exp_size) {
      std::cout << "ERROR: " << name << "dynamic size = " << act_size << " (should be " << exp_size << ")" << std::endl;
      error_count++;
    } else {
      if(verbose)
	printf("OK: %s dynamic size = %zd\n", name, act_size);
    }
  }

  void *buffer = dbs.detach_buffer();

  // now deserialize into a new object and test for equality
  Realm::Serialization::FixedBufferDeserializer fbd(buffer, act_size);
  T output;

  bool ok2 = fbd >> output;
  if(!ok2) {
    printf("ERROR: %s dynamic deserialization failed!\n", name);
    error_count++;
  }

  ptrdiff_t leftover = fbd.bytes_left();
  if(leftover != 0) {
    printf("ERROR: %s dynamic leftover = %zd\n", name, leftover);
    error_count++;
  }

  bool ok3 = (input == output);
  if(ok3) {
    if(verbose)
      printf("OK: %s dynamic output matches\n", name);
  } else {
    printf("ERROR: %s dynamic output mismatch:\n", name);
    std::cout << "Input:  " << input << std::endl;
    std::cout << "Buffer: [" << act_size << "]";
    std::cout << std::hex;
    for(size_t i = 0; i < act_size; i++)
      std::cout << ' ' << std::setfill('0') << std::setw(2) << (int)((unsigned char *)buffer)[i];
    std::cout << std::dec << std::endl;
    std::cout << "Output: " << output << std::endl;
    error_count++;
  }

  free(buffer);
}

template <typename T>
void do_test(const char *name, const T& input, size_t exp_size = 0)
{
  test_dynamic(name, input, exp_size);
}

template <typename T1, typename T2>
struct Pair {
  T1 x;
  T2 y;

  Pair(void) : x(), y() {}
  Pair(T1 _x, T2 _y) : x(_x), y(_y) {}

  bool operator==(const Pair<T1,T2>& rhs) const
  {
    return (x == rhs.x) && (y == rhs.y);
  }

  friend std::ostream& operator<<(std::ostream& os, const Pair<T1, T2>& p)
  {
    return os << '<' << p.x << ',' << p.y << '>';
  }
};

#if 0
template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& os, const Pair<T1, T2>& p)
{
  return os << '<' << p.x << ',' << p.y << '>';
}
#endif

typedef Pair<double, int> PODStruct;
TYPE_IS_SERIALIZABLE(PODStruct);

typedef Pair<double, float> PODPacked;
template <typename S>
bool operator<<(S& s, const PODPacked& p) { return (s << p.x) && (s << p.y); }
template <typename S>
bool operator>>(S& s, PODPacked& p) { return (s >> p.x) && (s >> p.y); }

typedef Pair<double, char> PODPacked2;
template <typename S>
bool operator&(S& s, const PODPacked& p) { return (s & p.x) && (s & p.y); }

int main(int argc, const char *argv[])
{
  parse_args(argc, argv);

  {
    // a common failure mode for the serialization logic is infinite recursion,
    //  so set very tight bounds on our stack size and run time
    struct rlimit rl;
    int ret;
    rl.rlim_cur = rl.rlim_max = 16384;  // 16KB
    ret = setrlimit(RLIMIT_STACK, &rl);
    assert(ret == 0);
    rl.rlim_cur = rl.rlim_max = 5;  // 5 seconds
    ret = setrlimit(RLIMIT_CPU, &rl);
    assert(ret == 0);
  }

  int x = 5;
  do_test("int", x, sizeof(int));

  do_test("double", double(4.5), sizeof(double));

  //void *f = &x;
  //do_test("void*", f, sizeof(void *));

  do_test("pod struct", PODStruct(6.5, 7), sizeof(PODStruct));

  do_test("pod packed", PODPacked(8.5, 9.1), 12 /* not sizeof(PODPacked)*/);

  //do_test("pod packed2", PODPacked2(10.5, 'z'), 9 /* not sizeof(PODPacked2)*/);

  std::vector<int> a(3);
  a[0] = 1;
  a[1] = 2;
  a[2] = 3;
  do_test("vector<int>", a, sizeof(size_t) + a.size() * sizeof(int));

  std::list<int> b;
  b.push_back(4);
  b.push_back(5);
  b.push_back(6);
  b.push_back(7);
  do_test("list<int>", b, sizeof(size_t) + b.size() * sizeof(int));

  std::map<int, double> c;
  c[8] = 1.1;
  c[9] = 2.2;
  c[10] = 3.3;
  do_test("map<int,double>", c, sizeof(size_t) + c.size() * 16 /*alignment*/);
}
<commit_msg>more test cases<commit_after>// Copyright 2015 Stanford University
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

// test for Realm's serializing code

#include "realm/serialize.h"

#include <sys/resource.h>
#include <string.h>

#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <map>
#include <list>

static bool verbose = false;
static int error_count = 0;

static void parse_args(int argc, const char *argv[])
{
  for(int i = 1; i < argc; i++) {
    if(!strcmp(argv[i], "-v")) {
      verbose = true;
      continue;
    }
  }
}

// helper functions to print out containers
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v)
{
  os << '[' << v.size() << ']';
  for(typename std::vector<T>::const_iterator it = v.begin();
      it != v.end();
      it++)
    os << ' ' << *it;
  return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::list<T>& l)
{
  os << '[' << l.size() << ']';
  for(typename std::list<T>::const_iterator it = l.begin();
      it != l.end();
      it++)
    os << ' ' << *it;
  return os;
}

template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& os, const std::map<T1, T2>& m)
{
  os << '[' << m.size() << ']';
  for(typename std::map<T1, T2>::const_iterator it = m.begin();
      it != m.end();
      it++)
    os << ' ' << it->first << '=' << it->second;
  return os;
}

template <typename T>
size_t test_dynamic(const char *name, const T& input, size_t exp_size = 0)
{
  // first serialize and check size
  Realm::Serialization::DynamicBufferSerializer dbs(0);

  bool ok1 = dbs << input;
  if(!ok1) {
    std::cout << "ERROR: " << name << "dynamic serialization failed!" << std::endl;
    error_count++;
  }

  size_t act_size = dbs.bytes_used();

  if(exp_size > 0) {
    if(act_size != exp_size) {
      std::cout << "ERROR: " << name << "dynamic size = " << act_size << " (should be " << exp_size << ")" << std::endl;
      error_count++;
    } else {
      if(verbose)
	printf("OK: %s dynamic size = %zd\n", name, act_size);
    }
  }

  void *buffer = dbs.detach_buffer();

  // now deserialize into a new object and test for equality
  Realm::Serialization::FixedBufferDeserializer fbd(buffer, act_size);
  T output;

  bool ok2 = fbd >> output;
  if(!ok2) {
    printf("ERROR: %s dynamic deserialization failed!\n", name);
    error_count++;
  }

  ptrdiff_t leftover = fbd.bytes_left();
  if(leftover != 0) {
    printf("ERROR: %s dynamic leftover = %zd\n", name, leftover);
    error_count++;
  }

  bool ok3 = (input == output);
  if(ok3) {
    if(verbose)
      printf("OK: %s dynamic output matches\n", name);
  } else {
    printf("ERROR: %s dynamic output mismatch:\n", name);
    std::cout << "Input:  " << input << std::endl;
    std::cout << "Buffer: [" << act_size << "]";
    std::cout << std::hex;
    for(size_t i = 0; i < act_size; i++)
      std::cout << ' ' << std::setfill('0') << std::setw(2) << (int)((unsigned char *)buffer)[i];
    std::cout << std::dec << std::endl;
    std::cout << "Output: " << output << std::endl;
    error_count++;
  }

  free(buffer);

  return act_size;
}

template <typename T>
void test_size(const char *name, const T& input, size_t exp_size)
{
  Realm::Serialization::ByteCountSerializer bcs;

  bool ok = bcs << input;
  if(!ok) {
    std::cout << "ERROR: " << name << "byetcount serialization failed!" << std::endl;
    error_count++;
  }

  size_t act_size = bcs.bytes_used();
  if(act_size != exp_size) {
    std::cout << "ERROR: " << name << "bytecount size = " << act_size << " (should be " << exp_size << ")" << std::endl;
    error_count++;
  } else {
    if(verbose)
      printf("OK: %s bytecount size = %zd\n", name, act_size);
  }
}

template <typename T>
void test_fixed(const char *name, const T& input, size_t exp_size)
{
  // first serialize and check size
  void *buffer = malloc(exp_size);
  Realm::Serialization::FixedBufferSerializer fbs(buffer, exp_size);

  bool ok1 = fbs << input;
  if(!ok1) {
    std::cout << "ERROR: " << name << "fixed serialization failed!" << std::endl;
    error_count++;
  }

  ptrdiff_t leftover = fbs.bytes_left();

  if(leftover != 0) {
    std::cout << "ERROR: " << name << "fixed leftover = " << leftover << std::endl;
    error_count++;
  } else {
    if(verbose)
      printf("OK: %s fixed leftover = %zd\n", name, leftover);
  }

  // now deserialize into a new object and test for equality
  Realm::Serialization::FixedBufferDeserializer fbd(buffer, exp_size);
  T output;

  bool ok2 = fbd >> output;
  if(!ok2) {
    printf("ERROR: %s fixed deserialization failed!\n", name);
    error_count++;
  }

  leftover = fbd.bytes_left();
  if(leftover != 0) {
    printf("ERROR: %s fixed leftover = %zd\n", name, leftover);
    error_count++;
  }

  bool ok3 = (input == output);
  if(ok3) {
    if(verbose)
      printf("OK: %s fixed output matches\n", name);
  } else {
    printf("ERROR: %s fixed output mismatch:\n", name);
    std::cout << "Input:  " << input << std::endl;
    std::cout << "Buffer: [" << exp_size << "]";
    std::cout << std::hex;
    for(size_t i = 0; i < exp_size; i++)
      std::cout << ' ' << std::setfill('0') << std::setw(2) << (int)((unsigned char *)buffer)[i];
    std::cout << std::dec << std::endl;
    std::cout << "Output: " << output << std::endl;
    error_count++;
  }

  free(buffer);
}

template <typename T>
void do_test(const char *name, const T& input, size_t exp_size = 0)
{
  exp_size = test_dynamic(name, input, exp_size);
  test_size(name, input, exp_size);
  test_fixed(name, input, exp_size);
}

template <typename T1, typename T2>
struct Pair {
  T1 x;
  T2 y;

  Pair(void) : x(), y() {}
  Pair(T1 _x, T2 _y) : x(_x), y(_y) {}

  bool operator==(const Pair<T1,T2>& rhs) const
  {
    return (x == rhs.x) && (y == rhs.y);
  }

  friend std::ostream& operator<<(std::ostream& os, const Pair<T1, T2>& p)
  {
    return os << '<' << p.x << ',' << p.y << '>';
  }
};

#if 0
template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& os, const Pair<T1, T2>& p)
{
  return os << '<' << p.x << ',' << p.y << '>';
}
#endif

typedef Pair<double, int> PODStruct;
TYPE_IS_SERIALIZABLE(PODStruct);

typedef Pair<double, float> PODPacked;
template <typename S>
bool operator<<(S& s, const PODPacked& p) { return (s << p.x) && (s << p.y); }
template <typename S>
bool operator>>(S& s, PODPacked& p) { return (s >> p.x) && (s >> p.y); }

typedef Pair<double, char> PODPacked2;
template <typename S>
bool operator&(S& s, const PODPacked2& p) { return (s & p.x) && (s & p.y); }

typedef Pair<PODPacked, int> PP2;
template <typename S>
bool operator&(S& s, const PP2& p) { return (s & p.x) && (s & p.y); }

int main(int argc, const char *argv[])
{
  parse_args(argc, argv);

  {
    // a common failure mode for the serialization logic is infinite recursion,
    //  so set very tight bounds on our stack size and run time
    struct rlimit rl;
    int ret;
    rl.rlim_cur = rl.rlim_max = 16384;  // 16KB
    ret = setrlimit(RLIMIT_STACK, &rl);
    assert(ret == 0);
    rl.rlim_cur = rl.rlim_max = 5;  // 5 seconds
    ret = setrlimit(RLIMIT_CPU, &rl);
    assert(ret == 0);
  }

  int x = 5;
  do_test("int", x, sizeof(int));

  do_test("double", double(4.5), sizeof(double));

  //void *f = &x;
  //do_test("void*", f, sizeof(void *));

  do_test("pod struct", PODStruct(6.5, 7), sizeof(PODStruct));

  do_test("pod packed", PODPacked(8.5, 9.1), 12 /* not sizeof(PODPacked)*/);

  do_test("pod packed2", PODPacked2(10.5, 'z'), 9 /* not sizeof(PODPacked2)*/);

  do_test("pp2", PP2(PODPacked(44.3, 1), 9), 16 /* not sizeof(PP2) */);

  std::vector<int> a(3);
  a[0] = 1;
  a[1] = 2;
  a[2] = 3;
  do_test("vector<int>", a, sizeof(size_t) + a.size() * sizeof(int));

  std::vector<PODStruct> a2(1);
  a2[0] = PODStruct(3, 4);
  do_test("vector<PODStruct>", a2, sizeof(size_t) + a2.size() * sizeof(PODStruct));

  std::vector<PODPacked> a3(1);
  a3[0] = PODPacked(3, 4);
  do_test("vector<PODPacked>", a3, sizeof(size_t) + 12 /* not sizeof(PODPacked)*/);

  std::vector<PODPacked2> a4(1);
  a4[0] = PODPacked2(3, 4);
  do_test("vector<PODPacked2>", a4, sizeof(size_t) + 9 /* not sizeof(PODPacked2)*/);

  std::list<int> b;
  b.push_back(4);
  b.push_back(5);
  b.push_back(6);
  b.push_back(7);
  do_test("list<int>", b, sizeof(size_t) + b.size() * sizeof(int));

  std::map<int, double> c;
  c[8] = 1.1;
  c[9] = 2.2;
  c[10] = 3.3;
  do_test("map<int,double>", c, sizeof(size_t) + c.size() * 16 /*alignment*/);

  std::vector<std::string> ss;
  ss.push_back("Hello");
  ss.push_back("World");
  do_test("vector<string>", ss, sizeof(size_t) + 12 + 9);

  if(error_count > 0) {
    std::cout << "ERRORS FOUND" << std::endl;
    exit(1);
  } else {
    std::cout << "all tests passed" << std::endl;
    exit(0);
  }
}
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

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

	cpp-ethereum 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 cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file EthashCPUMiner.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 *
 * Determines the PoW algorithm.
 */

#include "EthashCPUMiner.h"
#include <thread>
#include <chrono>
#include <boost/algorithm/string.hpp>
#if ETH_CPUID || !ETH_TRUE
#define HAVE_STDINT_H
#include <libcpuid/libcpuid.h>
#endif
using namespace std;
using namespace dev;
using namespace eth;

unsigned EthashCPUMiner::s_numInstances = 0;

static string jsonEncode(map<string, string> const& _m)
{
	string ret = "{";

	for (auto const& i: _m)
	{
		string k = boost::replace_all_copy(boost::replace_all_copy(i.first, "\\", "\\\\"), "'", "\\'");
		string v = boost::replace_all_copy(boost::replace_all_copy(i.second, "\\", "\\\\"), "'", "\\'");
		if (ret.size() > 1)
			ret += ", ";
		ret += "\"" + k + "\":\"" + v + "\"";
	}

	return ret + "}";
}

void EthashCPUMiner::workLoop()
{
	auto tid = std::this_thread::get_id();
	static std::mt19937_64 s_eng((time(0) + std::hash<decltype(tid)>()(tid)));

	uint64_t tryNonce = (uint64_t)(u64)Nonce::random(s_eng);
	ethash_return_value ethashReturn;

	WorkPackage w = work();

	EthashAux::FullType dag;
	while (!shouldStop() && !dag)
	{
		while (!shouldStop() && EthashAux::computeFull(w.seedHash, true) != 100)
			this_thread::sleep_for(chrono::milliseconds(500));
		dag = EthashAux::full(w.seedHash, false);
	}

	h256 boundary = w.boundary;
	unsigned hashCount = 1;
	for (; !shouldStop(); tryNonce++, hashCount++)
	{
		ethashReturn = ethash_full_compute(dag->full, *(ethash_h256_t*)w.headerHash.data(), tryNonce);
		h256 value = h256((uint8_t*)&ethashReturn.result, h256::ConstructFromPointer);
		if (value <= boundary && submitProof(EthashProofOfWork::Solution{(h64)(u64)tryNonce, h256((uint8_t*)&ethashReturn.mix_hash, h256::ConstructFromPointer)}))
			break;
		if (!(hashCount % 100))
			accumulateHashes(100);
	}
}

std::string EthashCPUMiner::platformInfo()
{
	string baseline = toString(std::thread::hardware_concurrency()) + "-thread CPU";
#if ETH_CPUID || !ETH_TRUE
	if (!cpuid_present())
		return baseline;
	struct cpu_raw_data_t raw;
	struct cpu_id_t data;
	if (cpuid_get_raw_data(&raw) < 0)
		return baseline;
	if (cpu_identify(&raw, &data) < 0)
		return baseline;
	map<string, string> m;
	m["vendor"] = data.vendor_str;
	m["codename"] = data.cpu_codename;
	m["brand"] = data.brand_str;
	m["L1 cache"] = toString(data.l1_data_cache);
	m["L2 cache"] = toString(data.l2_cache);
	m["L3 cache"] = toString(data.l3_cache);
	m["cores"] = toString(data.num_cores);
	m["threads"] = toString(data.num_logical_cpus);
	m["clocknominal"] = toString(cpu_clock_by_os());
	m["clocktested"] = toString(cpu_clock_measure(200, 0));
	/*
	printf("  MMX         : %s\n", data.flags[CPU_FEATURE_MMX] ? "present" : "absent");
	printf("  MMX-extended: %s\n", data.flags[CPU_FEATURE_MMXEXT] ? "present" : "absent");
	printf("  SSE         : %s\n", data.flags[CPU_FEATURE_SSE] ? "present" : "absent");
	printf("  SSE2        : %s\n", data.flags[CPU_FEATURE_SSE2] ? "present" : "absent");
	printf("  3DNow!      : %s\n", data.flags[CPU_FEATURE_3DNOW] ? "present" : "absent");
	*/
	return jsonEncode(m);
#else
	return baseline;
#endif
}
<commit_msg>fixed build wo libcpuid<commit_after>/*
	This file is part of cpp-ethereum.

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

	cpp-ethereum 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 cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file EthashCPUMiner.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 *
 * Determines the PoW algorithm.
 */

#include "EthashCPUMiner.h"
#include <thread>
#include <chrono>
#include <boost/algorithm/string.hpp>
#if ETH_CPUID || !ETH_TRUE
#define HAVE_STDINT_H
#include <libcpuid/libcpuid.h>
#endif
using namespace std;
using namespace dev;
using namespace eth;

unsigned EthashCPUMiner::s_numInstances = 0;

#if ETH_CPUID || !ETH_TRUE
static string jsonEncode(map<string, string> const& _m)
{
	string ret = "{";

	for (auto const& i: _m)
	{
		string k = boost::replace_all_copy(boost::replace_all_copy(i.first, "\\", "\\\\"), "'", "\\'");
		string v = boost::replace_all_copy(boost::replace_all_copy(i.second, "\\", "\\\\"), "'", "\\'");
		if (ret.size() > 1)
			ret += ", ";
		ret += "\"" + k + "\":\"" + v + "\"";
	}

	return ret + "}";
}
#endif

void EthashCPUMiner::workLoop()
{
	auto tid = std::this_thread::get_id();
	static std::mt19937_64 s_eng((time(0) + std::hash<decltype(tid)>()(tid)));

	uint64_t tryNonce = (uint64_t)(u64)Nonce::random(s_eng);
	ethash_return_value ethashReturn;

	WorkPackage w = work();

	EthashAux::FullType dag;
	while (!shouldStop() && !dag)
	{
		while (!shouldStop() && EthashAux::computeFull(w.seedHash, true) != 100)
			this_thread::sleep_for(chrono::milliseconds(500));
		dag = EthashAux::full(w.seedHash, false);
	}

	h256 boundary = w.boundary;
	unsigned hashCount = 1;
	for (; !shouldStop(); tryNonce++, hashCount++)
	{
		ethashReturn = ethash_full_compute(dag->full, *(ethash_h256_t*)w.headerHash.data(), tryNonce);
		h256 value = h256((uint8_t*)&ethashReturn.result, h256::ConstructFromPointer);
		if (value <= boundary && submitProof(EthashProofOfWork::Solution{(h64)(u64)tryNonce, h256((uint8_t*)&ethashReturn.mix_hash, h256::ConstructFromPointer)}))
			break;
		if (!(hashCount % 100))
			accumulateHashes(100);
	}
}

std::string EthashCPUMiner::platformInfo()
{
	string baseline = toString(std::thread::hardware_concurrency()) + "-thread CPU";
#if ETH_CPUID || !ETH_TRUE
	if (!cpuid_present())
		return baseline;
	struct cpu_raw_data_t raw;
	struct cpu_id_t data;
	if (cpuid_get_raw_data(&raw) < 0)
		return baseline;
	if (cpu_identify(&raw, &data) < 0)
		return baseline;
	map<string, string> m;
	m["vendor"] = data.vendor_str;
	m["codename"] = data.cpu_codename;
	m["brand"] = data.brand_str;
	m["L1 cache"] = toString(data.l1_data_cache);
	m["L2 cache"] = toString(data.l2_cache);
	m["L3 cache"] = toString(data.l3_cache);
	m["cores"] = toString(data.num_cores);
	m["threads"] = toString(data.num_logical_cpus);
	m["clocknominal"] = toString(cpu_clock_by_os());
	m["clocktested"] = toString(cpu_clock_measure(200, 0));
	/*
	printf("  MMX         : %s\n", data.flags[CPU_FEATURE_MMX] ? "present" : "absent");
	printf("  MMX-extended: %s\n", data.flags[CPU_FEATURE_MMXEXT] ? "present" : "absent");
	printf("  SSE         : %s\n", data.flags[CPU_FEATURE_SSE] ? "present" : "absent");
	printf("  SSE2        : %s\n", data.flags[CPU_FEATURE_SSE2] ? "present" : "absent");
	printf("  3DNow!      : %s\n", data.flags[CPU_FEATURE_3DNOW] ? "present" : "absent");
	*/
	return jsonEncode(m);
#else
	return baseline;
#endif
}
<|endoftext|>


<commit_before>#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <math.h>
#include <sstream>
#include <string>
#include <vector>

#include <zlib.h>
#include <stdio.h>
#include <getopt.h>

#include "include/readfq/kseq.h"

#include "include/rapidjson/document.h"
#include "include/rapidjson/writer.h"
#include "include/rapidjson/stringbuffer.h"
#include "include/rapidjson/prettywriter.h"
#include "include/rapidjson/filereadstream.h"
#include "include/rapidjson/filewritestream.h"

KSEQ_INIT(gzFile, gzread)

#define VERSION "2.0"
#define SUBPROGRAM "calculate"
#define read seq_segs

using namespace std;
using namespace rapidjson;

typedef PrettyWriter<StringBuffer> JSONWriter;

namespace opt
{
    static unsigned int verbose;
    static string reads_file;
    static string paf_file;
    static string gfa_file;
    static string type;
    static string sample_name;
}

// TODO: move to own header file...
class read
{
    public:
        string read_id;
        unsigned int read_len;
        unsigned long total_len_overlaps;
        int total_num_overlaps;
    void set(string i, int l, int lol)
    {
        read_id = i;
        read_len = l;
        total_len_overlaps = lol;
        total_num_overlaps = 1;
    }
    void updateOverlap(int new_ol_len)
    {
        total_len_overlaps += new_ol_len;
        total_num_overlaps += 1;
    }
};

void calculate_est_cov_and_est_genome_size( map<string, read> paf, JSONWriter* writer );
void calculate_read_length( map<string, read> paf, JSONWriter* writer);
void calculate_GC_content( string readsFile, JSONWriter* writer);
void calculate_tot_bases( map<string, read> paf, JSONWriter* writer);

int getopt( int argc, char *const arv[], const char *optstring);
enum { OPT_VERSION };
void parse_args( int argc, char *argv[]);
map<string, read> parse_paf();

int main( int argc, char *argv[])
{
    // parse the input arguments, if successful it will save all the arguments
    // in the global struct opts
    parse_args(argc, argv);

    // parse the input PAF file and return a map with key = read id,
    // and value = read object with all needed read info
    map<string, read> paf_records = parse_paf();

    // start the JSON object
    StringBuffer s;
    JSONWriter writer(s);
    writer.StartObject();

    // add input arguments
    writer.String("sample_name");
    writer.String(opt::sample_name.c_str());

    // start calculations
    calculate_read_length( paf_records, &writer);
    calculate_est_cov_and_est_genome_size( paf_records, &writer);
    calculate_GC_content( opt::reads_file, &writer);
    calculate_tot_bases( paf_records, &writer);

    // convert JSON document to string and print
    writer.EndObject();
    cout << s.GetString() << endl;

}

void parse_args ( int argc, char *argv[])
{
    // getopt
    extern char *optarg;
    extern int optind, opterr, optopt;
    const char* const short_opts = "hvr:t:n:p:g:";
    const option long_opts[] = {
        {"verbose",         no_argument,        NULL,   'v'},
        {"version",         no_argument,        NULL,   OPT_VERSION},
        {"reads",           required_argument,  NULL,   'r'},
        {"type",            required_argument,  NULL,   't'},
        {"sample_name", required_argument,  NULL,   'n'},
        {"paf",         required_argument,  NULL,   'p'},
        {"gfa",         optional_argument,  NULL,   'g'},
        {"help",            no_argument,    NULL,   'h'},
        { NULL,         0,  NULL,   0}
    };

    static const char* PREQCLR_CALCULATE_VERSION_MESSAGE =
    "preqclr-" SUBPROGRAM " version " VERSION "\n"
    "Written by Joanna Pineda.\n"
    "\n"
    "Copyright 2017 Ontario Institute for Cancer Research\n";

    static const char* PREQCLR_CALCULATE_USAGE_MESSAGE =
    "Usage: preqclr version " VERSION " " SUBPROGRAM " [OPTIONS] --reads reads.fa --type {ont|pb} --paf overlaps.paf --gfa layout.gfa \n"
    "Calculate information for preqclr report\n"
    "\n"
    "-v, --verbose              display verbose output\n"
    "        --version              display version\n"
    "-r, --reads                Fasta, fastq, fasta.gz, or fastq.gz files containing reads\n"
    "-t, --type             Type of long read sequencer. Either pacbio (pb) or oxford nanopore technology data (ont)\n"
    "-n, --sample_name          Sample name; you can use the name of species for example. This will be used as output prefix\n"
    "-p, --paf              Minimap2 pairwise alignment file (PAF). This is produced using \'minimap2 -x ava-ont sample.fastq sample.fasta"
    "\n"
    "-g, --gfa              Miniasm graph gragment assembly (GFA) file. This is produced using \'miniasm -f reads.fasta overlaps.paf\'\n"
    "\n";

    int rflag=0, tflag=0, nflag=0, pflag=0, gflag=0, verboseflag=0, versionflag=0;
    int c;
    while ( (c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1 ) {
    // getopt will loop through arguments, returns -1 when end of options, and store current arg in optarg
    // if optarg is not null, keep as optarg else ""
    std::istringstream arg(optarg != NULL ? optarg : "");
    switch(c) {
        case 'v':
            opt::verbose = 1; // set verbose flag
            break;
        case OPT_VERSION:
            cout << PREQCLR_CALCULATE_VERSION_MESSAGE << endl;
            exit(0);
        case 'r':
            rflag = 1;
            arg >> opt::reads_file;
            break;
        case 't':
            tflag = 1;
            if (( arg.str().compare("ont")    != 0 ) && ( arg.str().compare("pb") != 0 )) {
                fprintf(stderr, "preqclr %s: option -t,--type is missing a valid argument {ont,pb}. \n\n", SUBPROGRAM);
                fprintf(stderr, PREQCLR_CALCULATE_USAGE_MESSAGE, argv[0]);
                exit(1);
            }
            arg >> opt::type;
            break;
        case 'n':
            nflag = 1;
            arg >> opt::sample_name;
            break;
        case 'p':
            pflag = 1;
            arg >> opt::paf_file;
            break;
        case 'g':
            gflag = 1;
            arg >> opt::gfa_file;
            break;
        case 'h':
            cout << PREQCLR_CALCULATE_USAGE_MESSAGE << endl;
            exit(0);
        case ':':
            fprintf(stderr, "preqclr %s: option `-%c' is missing a required argument\n", SUBPROGRAM, optopt);
            fprintf(stderr, PREQCLR_CALCULATE_USAGE_MESSAGE, argv[0]);
            exit(1);
        case '?':
            // invalid option: getopt_long already printed an error message
            fprintf(stderr, "preqclr %s: option `-%c' is invalid: ignored\n", SUBPROGRAM, optopt);
            fprintf(stderr, PREQCLR_CALCULATE_USAGE_MESSAGE, argv[0]);
            break;
        }
    }
    if( argc < 4 ) {
        cerr << PREQCLR_CALCULATE_USAGE_MESSAGE << endl;
        exit(1);
    }

    // print any remaining command line argumentes
    if (optind < argc) {
        for (; optind < argc; optind++)
            cerr << "preqclr " << SUBPROGRAM << ": too many arguments:"
                 << " argv[optind]" << endl;
    }

    // check mandatory variables and assign defaults
    if ( rflag == 0 ) {
        fprintf(stderr, "preqclr %s: missing -r,--reads option\n\n", SUBPROGRAM);
        fprintf(stderr, PREQCLR_CALCULATE_USAGE_MESSAGE, argv[0]);
        exit(1);
    }
    if ( nflag == 0 ) {
        fprintf(stderr, "preqclr %s: missing -n,--sample_name option\n\n", SUBPROGRAM);
        fprintf(stderr, PREQCLR_CALCULATE_USAGE_MESSAGE);
        exit(1);
    }
    if ( pflag == 0 ) {
        fprintf(stderr, "preqclr %s: missing -p,--paf option\n\n", SUBPROGRAM);
        fprintf(stderr, PREQCLR_CALCULATE_USAGE_MESSAGE);
        exit(1);
    }
    if ( tflag == 0 ) {
        fprintf(stderr, "preqclr %s: missing -t,--type option\n\n", SUBPROGRAM);
        fprintf(stderr, PREQCLR_CALCULATE_USAGE_MESSAGE);
        exit(1);
    }

    // check if an option is used more than once
    // check if files exist and are readable ...

};

map<string, read> parse_paf()
{
    // read each line in paf file passed on by user
    string line;
    ifstream infile(opt::paf_file);
    map<string, read> paf_records;
    while( getline(infile, line) ) {

        // read each line/overlap and save each column into variable
        string qname;
        unsigned int qlen, qstart, qend;
        char strand;
        string tname;
        unsigned int tlen, tstart, tend;
        stringstream ss(line);
        ss >> qname >> qlen >> qstart >> qend >> strand >> tname >> tlen >> tstart >> tend;

        if ( qname.compare(tname) != 0 ) {
            unsigned int qprefix_len = qstart;
            unsigned int qsuffix_len = qlen - qend;
            unsigned int tprefix_len = tstart;
            unsigned int tsuffix_len = tlen - tend;

            // calculate overlap length, we need to take into account minimap2's softclipping
            int left_clip = 0, right_clip = 0;
            if ( ( qstart != 0 ) && ( tstart != 0 ) ){
                if ( strand == '+' ) {
                    left_clip += min(qprefix_len, tprefix_len);
                } else {
                    left_clip += min(qprefix_len, tsuffix_len);
                }
            }
            if ( ( qend != 0 ) && ( tend != 0 ) ){
                if ( strand == '+' ) {
                    right_clip += min(qsuffix_len, tsuffix_len);
                } else {
                    right_clip += min(qsuffix_len, tprefix_len);
                }
            }

            unsigned long overlap_len = (qend - qstart) + left_clip + right_clip;

            // add this information to paf_records dictionary
            auto i = paf_records.find(qname);
            if ( i == paf_records.end() ) {
                // if read not found initialize in paf_records
                read qr;
                qr.set(qname, qlen, overlap_len);
                paf_records.insert(pair<string,read>(qname, qr));
            } else {
                // if read found, update the overlap info
                i->second.updateOverlap(overlap_len);
            }
            auto j = paf_records.find(tname);
            if ( j == paf_records.end() ) {
                // if target read not found initialize in paf_records
                read tr;
                tr.set(tname, tlen, overlap_len);
                paf_records.insert(pair<string,read>(tname, tr));
            } else {
                // if target read found, update the overlap info
                j->second.updateOverlap(overlap_len);
            }
        }
    }

    // let's check the records...
    for ( auto const& r : paf_records ) {
        // Accessing KEY from element pointed by it
        string read_id = r.first;
        read temp = r.second;
    }

   return paf_records;
}

void calculate_tot_bases( map<string, read> paf, JSONWriter* writer)
{
    /*
    ========================================================
    Calculating total number of bases as a function of
    min read length
    --------------------------------------------------------
    Shows the total number of bases with varying minimum
    read length cut offs.
    Input:      Dictionary of reads with read length info in value
    Output:     Dictionary:
                key   = read length cut off
                value = total number of bases
    ========================================================
    */

    // bin the reads by read length
    map < unsigned long, unsigned long, greater<unsigned long>> read_lengths;
    for( auto it = paf.begin(); it != paf.end(); it++) {
        string id = it->first;
        int r_len = it->second.read_len;

        // add as new read length if read length not in map yet
        auto j = read_lengths.find(r_len);
        if ( j == read_lengths.end() ) {
            // if read length not found
            read_lengths.insert( pair<int,int>(r_len, 1) );
        } else {
            // if read length found
            j->second+=1;
        }
    }

    // sort read lengths
    // display items in sorted order of keys
    writer->Key("total_num_bases_vs_min_read_length");
    writer->StartObject();
    unsigned long curr_longest;
    unsigned long tot_num_bases = 0;
    for (const auto& p : read_lengths) {
        curr_longest = p.first;
        tot_num_bases += ( p.second * p.first);
        string key = to_string( curr_longest );
        writer->Key(key.c_str());
        writer->Int(tot_num_bases);
    }
    writer->EndObject();
}

void calculate_GC_content( string file, JSONWriter* writer )
{
    /*
    ========================================================
    Calculating GC-content per read
    --------------------------------------------------------
    Parses through read file and counts the Cs and Gs,
    then divides by the read length.
    Input:     Path to reads FILE
    Output:    List of GC content of all reads
    ========================================================
    */

    vector < double > GC_content;
    gzFile fp;
    kseq_t *seq;
    const char *c = file.c_str();
    fp = gzopen(c, "r");
    seq = kseq_init(fp);
    writer->Key("read_counts_per_GC_content");
    writer->StartArray();
    while (kseq_read(seq) >= 0) {
         string id = seq->name.s;
         string sequence = seq->seq.s;
         size_t C_count = count(sequence.begin(), sequence.end(), 'C');
         size_t G_count = count(sequence.begin(), sequence.end(), 'G');
         double r_len = sequence.length();
         double gc_cont = (double( C_count + G_count ) / r_len) *100.0;
         writer->Double(gc_cont);
    }
    writer->EndArray();
    kseq_destroy(seq);
    gzclose(fp);
}

void calculate_est_cov_and_est_genome_size( map<string, read> paf, JSONWriter* writer )
{
    /*
    ========================================================
    Calculating est cov per read and est genome size
    --------------------------------------------------------
    For each read uses length and sum of lengths of all
    overlaps.
    Input:    PAF records dictionary
    Output:   Dictionary: (each entry is a read)
              key = est coverage
              value = read length
    ========================================================
    */

    vector< pair < int, int > > covs;
    double r_len, r_tot_len_ol, r_tot_num_ol, r_cov;

    // make an object that will hold pair of coverage and read length
    writer->Key("per_read_est_cov_and_read_length");
    writer->StartObject();
    for( auto it = paf.begin(); it != paf.end(); it++)
    {
        string id = it->first;
        read r = it->second;
        float r_len = float(r.read_len);
        unsigned long r_tot_len_ol = r.total_len_overlaps;
        float r_cov = r_tot_len_ol / r_len;
        string key = to_string(r_cov);
        writer->Key(key.c_str());
        writer->Int(r_len);
        covs.push_back(make_pair(r_cov,r_len));
    }
    writer->EndObject();

    // filter the coverage: remove if outside 1.5*interquartile_range
    // calculate IQR
    // sort the estimated coverages
    sort(covs.begin(), covs.end());

    // get the index of the 25th and 75th percentile item
    int i25 = ceil(covs.size() * 0.25);
    int i75 = ceil(covs.size() * 0.75);

    // find IQR
    int IQR = covs[i75].first - covs[i25].first;
    double bd = IQR*1.5;
    int lowerbound = double(covs[i25].first) - bd;
    int upperbound = double(covs[i75].first) + bd;

    // create a new set after applying this filter
    // stores info of set of reads after filtering:
    unsigned long sum_len = 0;
    unsigned long sum_cov = 0;
    float tot_reads = 0;
    for( auto it = covs.begin(); it != covs.end(); ++it) {
        if (( it->first > lowerbound ) && ( it->first < upperbound )) {
            unsigned long co = it->first;
            unsigned long le = it->second;
            sum_len += le;
            sum_cov += co;
            tot_reads += 1;
        }
    }

    // calculate estimated genome size
    float mean_read_len = sum_len / tot_reads;
    float mean_cov = sum_cov / tot_reads;
    float est_genome_size = ( tot_reads * mean_read_len ) / mean_cov;

    // now store in JSON object
    writer->Key("est_cov_post_filter_info");
    writer->StartArray();
    writer->Double(lowerbound);
    writer->Double(upperbound);
    writer->Int(tot_reads);
    writer->Double(IQR);
    writer->EndArray();
    writer->Key("est_genome_size");
    writer->Double(est_genome_size);
}

void calculate_read_length( map<string, read> paf, JSONWriter* writer)
{
    /*
    ========================================================
    Calculating read lengths
    --------------------------------------------------------
    For each read add read lengths to JSON object
    Input:        PAF records dictionary
    Output:     List of all read lengths
    ========================================================
    */

    writer->Key("per_read_read_length");
    writer->StartArray();

    // loop through the map of reads and get read lengths
    for(auto it = paf.begin(); it != paf.end(); it++) {
        read r = it->second;
        int r_len = r.read_len;
        writer->Int(r_len);
    }
    writer->EndArray();
}
<commit_msg>restructured the program: moved definition of read into own file, removed from main program. Moved main program to main directory.<commit_after><|endoftext|>


<commit_before>/** ==========================================================================
* 2010 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes
* with no warranties. This code is yours to share, use and modify with no
* strings attached and no restrictions or obligations.
 *
 * For more information see g3log/LICENSE or refer refer to http://unlicense.org
* ============================================================================
*
* Example of a normal std::queue protected by a mutex for operations,
* making it safe for thread communication, using std::mutex from C++0x with
* the help from the std::thread library from JustSoftwareSolutions
* ref: http://www.stdthread.co.uk/doc/headers/mutex.html
*
* This exampel  was totally inspired by Anthony Williams lock-based data structures in
* Ref: "C++ Concurrency In Action" http://www.manning.com/williams */

#pragma once

#include <queue>
#include <mutex>
#include <exception>
#include <condition_variable>

/** Multiple producer, multiple consumer thread safe queue
* Since 'return by reference' is used this queue won't throw */
template<typename T>
class shared_queue
{
   std::queue<T> queue_;
   mutable std::mutex m_;
   std::condition_variable data_cond_;

   shared_queue &operator=(const shared_queue &) = delete;
   shared_queue(const shared_queue &other) = delete;

public:
   shared_queue() {}

   void push(T item) {
      {
         std::lock_guard<std::mutex> lock(m_);
         queue_.push(std::move(item));
      }
      data_cond_.notify_one();
   }

   /// \return immediately, with true if successful retrieval
   bool try_and_pop(T &popped_item) {
      std::lock_guard<std::mutex> lock(m_);
      if (queue_.empty()) {
         return false;
      }
      popped_item = std::move(queue_.front());
      queue_.pop();
      return true;
   }

   /// Try to retrieve, if no items, wait till an item is available and try again
   void wait_and_pop(T &popped_item) {
      std::unique_lock<std::mutex> lock(m_);
      while (queue_.empty())
      {
         data_cond_.wait(lock);
         //  This 'while' loop is equal to
         //  data_cond_.wait(lock, [](bool result){return !queue_.empty();});
      }
      popped_item = std::move(queue_.front());
      queue_.pop();
   }

   bool empty() const {
      std::lock_guard<std::mutex> lock(m_);
      return queue_.empty();
   }

   unsigned size() const {
      std::lock_guard<std::mutex> lock(m_);
      return queue_.size();
   }
};
<commit_msg>fix typo in shared_queue.hpp exampel -> example (#363)<commit_after>/** ==========================================================================
* 2010 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes
* with no warranties. This code is yours to share, use and modify with no
* strings attached and no restrictions or obligations.
 *
 * For more information see g3log/LICENSE or refer refer to http://unlicense.org
* ============================================================================
*
* Example of a normal std::queue protected by a mutex for operations,
* making it safe for thread communication, using std::mutex from C++0x with
* the help from the std::thread library from JustSoftwareSolutions
* ref: http://www.stdthread.co.uk/doc/headers/mutex.html
*
* This example  was totally inspired by Anthony Williams lock-based data structures in
* Ref: "C++ Concurrency In Action" http://www.manning.com/williams */

#pragma once

#include <queue>
#include <mutex>
#include <exception>
#include <condition_variable>

/** Multiple producer, multiple consumer thread safe queue
* Since 'return by reference' is used this queue won't throw */
template<typename T>
class shared_queue
{
   std::queue<T> queue_;
   mutable std::mutex m_;
   std::condition_variable data_cond_;

   shared_queue &operator=(const shared_queue &) = delete;
   shared_queue(const shared_queue &other) = delete;

public:
   shared_queue() {}

   void push(T item) {
      {
         std::lock_guard<std::mutex> lock(m_);
         queue_.push(std::move(item));
      }
      data_cond_.notify_one();
   }

   /// \return immediately, with true if successful retrieval
   bool try_and_pop(T &popped_item) {
      std::lock_guard<std::mutex> lock(m_);
      if (queue_.empty()) {
         return false;
      }
      popped_item = std::move(queue_.front());
      queue_.pop();
      return true;
   }

   /// Try to retrieve, if no items, wait till an item is available and try again
   void wait_and_pop(T &popped_item) {
      std::unique_lock<std::mutex> lock(m_);
      while (queue_.empty())
      {
         data_cond_.wait(lock);
         //  This 'while' loop is equal to
         //  data_cond_.wait(lock, [](bool result){return !queue_.empty();});
      }
      popped_item = std::move(queue_.front());
      queue_.pop();
   }

   bool empty() const {
      std::lock_guard<std::mutex> lock(m_);
      return queue_.empty();
   }

   unsigned size() const {
      std::lock_guard<std::mutex> lock(m_);
      return queue_.size();
   }
};
<|endoftext|>


<commit_before>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <fnord-msg/MessageObject.h>
#include <fnord-base/exception.h>

namespace fnord {
namespace msg {

MessageObject::MessageObject(
    uint32_t _id /* = 0 */) :
    id(_id),
    type(FieldType::OBJECT) {
  new (&data_) Vector<MessageObject>();
}

MessageObject::MessageObject(
    uint32_t _id,
    uint32_t value) :
    id(_id),
    type(FieldType::UINT32) {
  new (&data_) uint32_t(value);
}

MessageObject::MessageObject(
    uint32_t _id,
    const String& value) : id(_id),
    type(FieldType::STRING) {
  new (&data_) String(value);
}

MessageObject::MessageObject(
    uint32_t _id,
    TrueType t) :
    id(_id),
    type(FieldType::BOOLEAN) {
  new (&data_) uint8_t(1);
}

MessageObject::MessageObject(
    uint32_t _id,
    FalseType f) :
    id(_id),
    type(FieldType::BOOLEAN) {
  new (&data_) uint8_t(0);
}

MessageObject::MessageObject(
    const MessageObject& other) :
    id(other.id),
    type(other.type) {
  switch (type) {

    case FieldType::OBJECT:
      new (&data_) Vector<MessageObject>(other.asObject());
      break;

    case FieldType::STRING:
      new (&data_) String(other.asString());
      break;

    case FieldType::UINT32:
      new (&data_) uint32_t(other.asUInt32());
      break;

    case FieldType::BOOLEAN:
      new (&data_) uint8_t(other.asBool() ? 1 : 0);
      break;

  }
}

//MessageObject& MessageObject::operator=(const MessageObject& other) {
//  free old.., copy type, id
//  switch (other.type) {
//
//    case FieldType::OBJECT:
//      new (&data_) Vector<MessageObject>(other.asObject());
//      break;
//
//    case FieldType::STRING:
//      new (&data_) String(other.asString());
//      break;
//
//    case FieldType::UINT32:
//      new (&data_) uint32_t(other.asUInt32());
//      break;
//
//    case FieldType::BOOLEAN:
//      new (&data_) uint8_t(other.asBool() ? 1 : 0);
//      break;
//
//  }
//
//  return *this;
//}

MessageObject::~MessageObject() {
  switch (type) {

    case FieldType::OBJECT:
      ((Vector<MessageObject>*) &data_)->~vector();
      break;

    case FieldType::STRING:
      ((String*) &data_)->~String();
      break;

    case FieldType::UINT32:
    case FieldType::BOOLEAN:
      break;

  }
}

Vector<MessageObject>& MessageObject::asObject() const {
#ifndef FNORD_NODEBUG
  if (type != FieldType::OBJECT) {
    RAISE(kTypeError);
  }
#endif

  return *((Vector<MessageObject>*) &data_);
}

const String& MessageObject::asString() const {
#ifndef FNORD_NODEBUG
  if (type != FieldType::STRING) {
    RAISE(kTypeError);
  }
#endif

  return *((String*) &data_);
}

uint32_t MessageObject::asUInt32() const {
#ifndef FNORD_NODEBUG
  if (type != FieldType::UINT32) {
    RAISE(kTypeError);
  }
#endif

  return *((uint32_t*) &data_);
}

bool MessageObject::asBool() const {
#ifndef FNORD_NODEBUG
  if (type != FieldType::BOOLEAN) {
    RAISE(kTypeError);
  }
#endif

  uint8_t val = *((uint8_t*) &data_);
  return val > 0;
}

//MessageObject::MessageObject(uint32_t id, uint32_t value);
//MessageObject::MessageObject(uint32_t id, String value);
//MessageObject::MessageObject(uint32_t id, bool value);

} // namespace msg
} // namespace fnord
<commit_msg>workaround<commit_after>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <fnord-msg/MessageObject.h>
#include <fnord-base/exception.h>

namespace fnord {
namespace msg {

MessageObject::MessageObject(
    uint32_t _id /* = 0 */) :
    id(_id),
    type(FieldType::OBJECT) {
  new (&data_) Vector<MessageObject>();
}

MessageObject::MessageObject(
    uint32_t _id,
    uint32_t value) :
    id(_id),
    type(FieldType::UINT32) {
  new (&data_) uint32_t(value);
}

MessageObject::MessageObject(
    uint32_t _id,
    const String& value) : id(_id),
    type(FieldType::STRING) {
  new (&data_) String(value);
}

MessageObject::MessageObject(
    uint32_t _id,
    TrueType t) :
    id(_id),
    type(FieldType::BOOLEAN) {
  new (&data_) uint8_t(1);
}

MessageObject::MessageObject(
    uint32_t _id,
    FalseType f) :
    id(_id),
    type(FieldType::BOOLEAN) {
  new (&data_) uint8_t(0);
}

MessageObject::MessageObject(
    const MessageObject& other) :
    id(other.id),
    type(other.type) {
  switch (type) {

    case FieldType::OBJECT:
      new (&data_) Vector<MessageObject>(other.asObject());
      break;

    case FieldType::STRING:
      new (&data_) String(other.asString());
      break;

    case FieldType::UINT32:
      new (&data_) uint32_t(other.asUInt32());
      break;

    case FieldType::BOOLEAN:
      new (&data_) uint8_t(other.asBool() ? 1 : 0);
      break;

  }
}

//MessageObject& MessageObject::operator=(const MessageObject& other) {
//  free old.., copy type, id
//  switch (other.type) {
//
//    case FieldType::OBJECT:
//      new (&data_) Vector<MessageObject>(other.asObject());
//      break;
//
//    case FieldType::STRING:
//      new (&data_) String(other.asString());
//      break;
//
//    case FieldType::UINT32:
//      new (&data_) uint32_t(other.asUInt32());
//      break;
//
//    case FieldType::BOOLEAN:
//      new (&data_) uint8_t(other.asBool() ? 1 : 0);
//      break;
//
//  }
//
//  return *this;
//}

MessageObject::~MessageObject() {
  switch (type) {

    case FieldType::OBJECT:
      ((Vector<MessageObject>*) &data_)->~vector();
      break;

    case FieldType::STRING:
      ((String*) &data_)->~String();
      break;

    case FieldType::UINT32:
    case FieldType::BOOLEAN:
      break;

  }
}

Vector<MessageObject>& MessageObject::asObject() const {
#ifndef FNORD_NODEBUG
  if (type != FieldType::OBJECT) {
    RAISE(kTypeError);
  }
#endif

  return *((Vector<MessageObject>*) &data_);
}

const String& MessageObject::asString() const {
#ifndef FNORD_NODEBUG
  if (type != FieldType::STRING) {
    RAISE(kTypeError);
  }
#endif

  return *((String*) &data_);
}

uint32_t MessageObject::asUInt32() const {
#ifndef FNORD_NODEBUG
  if (type != FieldType::UINT32) {
    RAISE(kTypeError);
  }
#endif

  return *((uint32_t*) &data_);
}

bool MessageObject::asBool() const {
  if (type == FieldType::UINT32) {
    uint32_t val = *((uint32_t*) &data_);
    return val > 0;
  }

#ifndef FNORD_NODEBUG
  if (type != FieldType::BOOLEAN) {
    RAISE(kTypeError);
  }
#endif

  uint8_t val = *((uint8_t*) &data_);
  return val > 0;
}

//MessageObject::MessageObject(uint32_t id, uint32_t value);
//MessageObject::MessageObject(uint32_t id, String value);
//MessageObject::MessageObject(uint32_t id, bool value);

} // namespace msg
} // namespace fnord
<|endoftext|>