text:
/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 * @file GncPoseAveragingExample.cpp
 * @brief example of GNC estimating a single pose from pose priors possibly corrupted with outliers
 * You can run this example using: ./GncPoseAveragingExample nrInliers nrOutliers
 * e.g.,: ./GncPoseAveragingExample 10 5  (if the numbers are not specified, default
 * values nrInliers = 10 and nrOutliers = 10 are used)
 * @date May 8, 2021
 * @author Luca Carlone
 */

#include <gtsam/geometry/Pose3.h>
#include <gtsam/nonlinear/Values.h>
#include <gtsam/nonlinear/GncOptimizer.h>

#include <string>
#include <fstream>
#include <iostream>
#include <random>
#include <boost/lexical_cast.hpp>

using namespace std;
using namespace gtsam;

int main(int argc, char** argv){
  cout << "== Robust Pose Averaging Example === " << endl;

  // default number of inliers and outliers
  size_t nrInliers = 10;
  size_t nrOutliers = 10;

  // User can pass arbitrary number of inliers and outliers for testing
  if (argc > 1)
    nrInliers = atoi(argv[1]);
  if (argc > 2)
    nrOutliers = atoi(argv[2]);
  cout << "nrInliers " << nrInliers << " nrOutliers "<< nrOutliers << endl;

  // Seed random number generator
  random_device rd;
  mt19937 rng(rd());
  uniform_real_distribution<double> uniform(-10, 10);
  normal_distribution<double> normalInliers(0.0, 0.05);

  Values initial;
  initial.insert(0, Pose3::identity()); // identity pose as initialization

  // create ground truth pose
  Vector6 poseGtVector;
  for(size_t i = 0; i < 6; ++i){
    poseGtVector(i) = uniform(rng);
  }
  Pose3 gtPose = Pose3::Expmap(poseGtVector); // Pose3( Rot3::Ypr(3.0, 1.5, 0.8), Point3(4,1,3) );

  NonlinearFactorGraph graph;
  const noiseModel::Isotropic::shared_ptr model = noiseModel::Isotropic::Sigma(6,0.05);
  // create inliers
  for(size_t i=0; i<nrInliers; i++){
    Vector6 poseNoise;
    for(size_t i = 0; i < 6; ++i){
      poseNoise(i) = normalInliers(rng);
    }
    Pose3 poseMeasurement = gtPose.retract(poseNoise);
    graph.add(gtsam::PriorFactor<gtsam::Pose3>(0,poseMeasurement,model));
  }

  // create outliers
  for(size_t i=0; i<nrOutliers; i++){
    Vector6 poseNoise;
    for(size_t i = 0; i < 6; ++i){
      poseNoise(i) = uniform(rng);
    }
    Pose3 poseMeasurement = gtPose.retract(poseNoise);
    graph.add(gtsam::PriorFactor<gtsam::Pose3>(0,poseMeasurement,model));
  }

  GncParams<LevenbergMarquardtParams> gncParams;
  auto gnc = GncOptimizer<GncParams<LevenbergMarquardtParams>>(graph,
      initial,
      gncParams);

  Values estimate = gnc.optimize();
  Pose3 poseError = gtPose.between( estimate.at<Pose3>(0) );
  cout << "norm of translation error: " << poseError.translation().norm() <<
      " norm of rotation error: " << poseError.rotation().rpy().norm() << endl;
  // poseError.print("pose error: \n ");
  return 0;
}

max_stars_repo_name: h-rover/gtsam

max_issues_repo_name: h-rover/gtsam

max_forks_repo_name: h-rover/gtsam


text:
/**
 ** Isaac Genome Alignment Software
 ** Copyright (c) 2010-2017 Illumina, Inc.
 ** All rights reserved.
 **
 ** This software is provided under the terms and conditions of the
 ** GNU GENERAL PUBLIC LICENSE Version 3
 **
 ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3
 ** along with this program. If not, see
 ** <https://github.com/illumina/licenses/>.
 **
 ** \file testSampleSheetCsvGrammar.cpp
 **
 ** tests boost::spirit grammar for use bases mask parsing
 **
 ** \author Roman Petrovski
 **/

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

#include <boost/algorithm/string.hpp>
#include <boost/assign.hpp>
#include <boost/lexical_cast.hpp>

using namespace std;

#include "RegistryName.hh"
#include "testSampleSheetCsvGrammar.hh"

#include "SampleSheetCsvGrammar.hpp"
#include "flowcell/SequencingAdapterMetadata.hh"

CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( TestSampleSheetCsvGrammar, registryName("SampleSheetCsvGrammar"));

void TestSampleSheetCsvGrammar::setUp()
{
}

void TestSampleSheetCsvGrammar::tearDown()
{
}

using isaac::demultiplexing::SampleSheetCsvGrammar;
typedef SampleSheetCsvGrammar<std::string::const_iterator> Parser;

void TestSampleSheetCsvGrammar::testStandard()
{
    std::string test(
        // header line (first line) must be always discarded
        "FCID,Lane,SampleID,SampleRef,Index,Description,Control,Recipe,Operator,SampleProject\r"
        // commented lines must be discarded
        "#A805CKABXX,1,AR008,human,ACTTGA,Cypress,Y,\"101,7,101\",CB,Demo\r\n"
        // regular line ending with just lf
        "A805CKABXX,1,AR005,human,ACTTGA,Cypress,Y,101+7,CB,Demo\n"
        // regular line ending with crlf and containing quoted fields with quotes and comma inside
        "A805CKABXX,2,AR008,human,ACT-TGA,\"\"\"Cypress\"\"\",Y,\"101,7,101\",CB,Demo\r\n"
        // empty line
        "\r\n"
        // another empty line
        "\r"
        // yet another empty line
        "\n"
        // another regular line ending with cr only
        "A805CKABXX,3,AR008,human,ACTTGA,Cypress,Y,101+7,CB,Demo\r"
        "A805CKABXX,4,,human,unknown,Cypress,Y,101+7,CB,Demo\r"
        "A805CKABXX,5,,human,Undetermined,Cypress,Y,101+7,CB,Demo\r"
        "#A805CKABXX,6,,human,Undetermined,Cypress,Y,101+7,CB,Demo\r"
        "#A805CKABXX,7,,human,Undetermined,Cypress,Y,101+7,CB,Demo\r"
        );
    std::string::const_iterator parseIt(test.begin());
    std::string::const_iterator parseEnd(test.end());

    const isaac::flowcell::SequencingAdapterMetadata testAdapterMetadata(
        "CTGTCTCTTATACACATCT",
        false,
        strlen("CTGTCTCTTATACACATCT"));

    static const isaac::flowcell::SequencingAdapterMetadataList adapters = boost::assign::list_of(testAdapterMetadata);
    SampleSheetCsvGrammar<std::string::const_iterator> parser(adapters);
    isaac::flowcell::BarcodeMetadataList result;

    try
    {
        if (!boost::spirit::qi::parse(parseIt, parseEnd, parser, result) || parseEnd != parseIt)
        {
            CPPUNIT_FAIL("Could not parse the sample sheet csv stream text:\n" + std::string(parseIt, parseEnd));
        }
    }
    catch(boost::spirit::qi::expectation_failure<std::string::const_iterator> const &e)
    {
        const std::string::const_iterator bufferBegin(test.begin());

        const std::string message = (boost::format("Could not parse the sample sheet csv. "
            "Expected:"
            "\n==================================================================\n%s||"
            "\n==================================================================\n"
            "Got:"
            "\n==================================================================\n%s||"
            "\n==================================================================\n"
            " at offset: %d") % e.what_ % std::string(e.first, e.last) %
            std::distance(bufferBegin, e.first)).str();
        CPPUNIT_FAIL(message);
    }

    CPPUNIT_ASSERT_EQUAL(size_t(5), result.size());

    CPPUNIT_ASSERT_EQUAL(std::string("A805CKABXX"), result.at(0).getFlowcellId());
    CPPUNIT_ASSERT_EQUAL(1U, result.at(0).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("AR005"), result.at(0).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string("ACTTGA"), result.at(0).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("Cypress"), result.at(0).getDescription());
    CPPUNIT_ASSERT_EQUAL(std::string("101+7"), result.at(0).getRecipe());
    CPPUNIT_ASSERT_EQUAL(std::string("CB"), result.at(0).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("Demo"), result.at(0).getProject());
    CPPUNIT_ASSERT_EQUAL(size_t(1), result.at(0).getAdapters().size());
    CPPUNIT_ASSERT_EQUAL(testAdapterMetadata, result.at(0).getAdapters().at(0));
    CPPUNIT_ASSERT_EQUAL(false, result.at(0).isUnknown());

    CPPUNIT_ASSERT_EQUAL(std::string("A805CKABXX"), result.at(1).getFlowcellId());
    CPPUNIT_ASSERT_EQUAL(2U, result.at(1).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("AR008"), result.at(1).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string("ACT-TGA"), result.at(1).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("\"Cypress\""), result.at(1).getDescription());
    CPPUNIT_ASSERT_EQUAL(std::string("101,7,101"), result.at(1).getRecipe());
    CPPUNIT_ASSERT_EQUAL(std::string("CB"), result.at(1).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("Demo"), result.at(1).getProject());
    CPPUNIT_ASSERT_EQUAL(size_t(1), result.at(1).getAdapters().size());
    CPPUNIT_ASSERT_EQUAL(testAdapterMetadata, result.at(1).getAdapters().at(0));
    CPPUNIT_ASSERT_EQUAL(false, result.at(1).isUnknown());

    CPPUNIT_ASSERT_EQUAL(std::string("A805CKABXX"), result.at(2).getFlowcellId());
    CPPUNIT_ASSERT_EQUAL(3U, result.at(2).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("AR008"), result.at(2).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string("ACTTGA"), result.at(2).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("Cypress"), result.at(2).getDescription());
    CPPUNIT_ASSERT_EQUAL(std::string("101+7"), result.at(2).getRecipe());
    CPPUNIT_ASSERT_EQUAL(std::string("CB"), result.at(2).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("Demo"), result.at(2).getProject());
    CPPUNIT_ASSERT_EQUAL(size_t(1), result.at(2).getAdapters().size());
    CPPUNIT_ASSERT_EQUAL(testAdapterMetadata, result.at(2).getAdapters().at(0));
    CPPUNIT_ASSERT_EQUAL(false, result.at(2).isUnknown());

    CPPUNIT_ASSERT_EQUAL(std::string("A805CKABXX"), result.at(3).getFlowcellId());
    CPPUNIT_ASSERT_EQUAL(4U, result.at(3).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("unknown"), result.at(3).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string(""), result.at(3).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("Cypress"), result.at(3).getDescription());
    CPPUNIT_ASSERT_EQUAL(std::string("101+7"), result.at(3).getRecipe());
    CPPUNIT_ASSERT_EQUAL(std::string("CB"), result.at(3).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("Demo"), result.at(3).getProject());
    CPPUNIT_ASSERT_EQUAL(size_t(1), result.at(3).getAdapters().size());
    CPPUNIT_ASSERT_EQUAL(testAdapterMetadata, result.at(3).getAdapters().at(0));
    CPPUNIT_ASSERT_EQUAL(true, result.at(3).isUnknown());

    CPPUNIT_ASSERT_EQUAL(std::string("A805CKABXX"), result.at(4).getFlowcellId());
    CPPUNIT_ASSERT_EQUAL(5U, result.at(4).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("unknown"), result.at(4).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string(""), result.at(4).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("Cypress"), result.at(4).getDescription());
    CPPUNIT_ASSERT_EQUAL(std::string("101+7"), result.at(4).getRecipe());
    CPPUNIT_ASSERT_EQUAL(std::string("CB"), result.at(4).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("Demo"), result.at(4).getProject());
    CPPUNIT_ASSERT_EQUAL(size_t(1), result.at(4).getAdapters().size());
    CPPUNIT_ASSERT_EQUAL(testAdapterMetadata, result.at(4).getAdapters().at(0));
    CPPUNIT_ASSERT_EQUAL(true, result.at(4).isUnknown());
}

void TestSampleSheetCsvGrammar::testDualBarcodeMiSeq()
{
    std::string test(
        "[Header],,,,,,,,,,\r"
"IEMFileVersion,3,,,,,,,,,\n"
"Investigator Name,Isabelle,,,,,,,,,\n"
"Project Name,Zebra_validation,,,,,,,,,\n"
"Experiment Name,48plex,,,,,,,,,\n"
"Date,20/02/2012,,,,,,,,,\n"
"Workflow,Resequencing,,,,,,,,,\n"
"Assay,TruSeq,,,,,,,,,\n"
"Description,G7_H1_12pM,,,,,,,,,\n"
"Chemistry,Amplicon,,,,,,,,,\n"
"[Reads],,,,,,,,,,\n"
"151,,,,,,,,,,\n"
"151,,,,,,,,,,\n"
"[Settings],,,,,,,,,,\n"
"[Data],,,,,,,,,,\n"
"Sample_ID,Sample_Name,Sample_Plate,Sample_Well,Sample_Project,index,I7_Index_ID,index2,I5_Index_ID,Description,GenomeFolder\n"
"A1_Bcereus,Human,A1_Bcereus,H12,Zebra_validation,ATTACTCG,D701,TATAGCCT,D501,Tada,\\\\ch-isilon\\isilon\\Mondas_software\\Genomes\\B_Cereus_ATCC10987_ELAND\n"
"C2_Bcereus,Human,C2_Bcereus,H11,Zebra_validation,TCCGGAGA,D702,CCTATCCT,D503,none,\\\\ch-isilon\\isilon\\Mondas_software\\Genomes\\B_Cereus_ATCC10987_ELAND\n"
        );
    std::string::const_iterator parseIt(test.begin());
    std::string::const_iterator parseEnd(test.end());

    const isaac::flowcell::SequencingAdapterMetadataList noAdapters;
    SampleSheetCsvGrammar<std::string::const_iterator> parser(noAdapters);
    isaac::flowcell::BarcodeMetadataList result;
    try
    {
        if (!boost::spirit::qi::parse(parseIt, parseEnd, parser, result) || parseEnd != parseIt)
        {
            CPPUNIT_FAIL("Could not parse the sample sheet csv stream text:\n" + std::string(parseIt, parseEnd));
        }
    }
    catch(boost::spirit::qi::expectation_failure<std::string::const_iterator> const &e)
    {
        const std::string::const_iterator bufferBegin(test.begin());

        const std::string message = (boost::format("Could not parse the sample sheet csv. "
            "Expected:"
            "\n==================================================================\n%s||"
            "\n==================================================================\n"
            "Got:"
            "\n==================================================================\n%s||"
            "\n==================================================================\n"
            " at offset: %d") % e.what_ % std::string(e.first, e.last) %
            std::distance(bufferBegin, e.first)).str();
        CPPUNIT_FAIL(message);
    }
    CPPUNIT_ASSERT_EQUAL(size_t(2), result.size());

    CPPUNIT_ASSERT_EQUAL(1U, result.at(0).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("A1_Bcereus"), result.at(0).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string("ATTACTCG-TATAGCCT"), result.at(0).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("Tada"), result.at(0).getDescription());
    CPPUNIT_ASSERT_EQUAL(std::string("Isabelle"), result.at(0).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("Zebra_validation"), result.at(0).getProject());
    CPPUNIT_ASSERT_EQUAL(false, result.at(0).isUnknown());

    CPPUNIT_ASSERT_EQUAL(1U, result.at(1).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("C2_Bcereus"), result.at(1).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string("TCCGGAGA-CCTATCCT"), result.at(1).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("none"), result.at(1).getDescription());
    CPPUNIT_ASSERT_EQUAL(std::string("Isabelle"), result.at(1).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("Zebra_validation"), result.at(1).getProject());
    CPPUNIT_ASSERT_EQUAL(false, result.at(1).isUnknown());
}

void TestSampleSheetCsvGrammar::testAnotherDualBarcodeMiSeq()
{
    std::string test(
        "[Header],\n\r"
"IEMFileVersion,3\n\r"
"Investigator Name,Nick\n\r"
"Project Name,Tudu\n\r"
"Experiment Name,DVT_VaraiabilityHC#11_SD\n\r"
"Date,1/18/2012\n\r"
"Workflow,Resequencing\n\r"
"Assay,Nextera\n\r"
"Description,Variability\n\r"
"Chemistry,Amplicon\n\r"
"\n\r"
"[Reads],\n\r"
"151,\n\r"
"151,\n\r"
"\n\r"
"[Manifests],\n\r"
"A,Manifest,,,,,,,,,,\n\r"
"\n\r"
"[Settings],,,,,,,,,,,\n\r"
"Aligner,isaac,,,,,,,,,,\n\r"
"Adapter,CTGTCTCTTATACACATCT,,,,,,,,,,\n\r"
"\n\r"
"[Data],,,,,,,,,,,\n\r"
"Sample_ID,Sample_Name,Sample_Plate,Sample_Well,Sample_Project,index,I7_Index_ID,index2,I5_Index_ID,Description,GenomeFolder,Manifest\n\r"
"V_1,V_1,Variability,F09,Tudu,GCTACGCT,N709,ACTGCATA,N506,DaytoDayVaraiability,Homo_sapiens/UCSC/hg19/Sequence/WholeGenomeFASTA/,A\n\r"
"V_2,V_2,Variability,F10,Tudu,CGAGGCTG,N710,ACTGCATA,N506,DaytoDayVaraiability,Homo_sapiens/UCSC/hg19/Sequence/WholeGenomeFASTA/,A\n\r"
        );
    std::string::const_iterator parseIt(test.begin());
    std::string::const_iterator parseEnd(test.end());

    const isaac::flowcell::SequencingAdapterMetadataList noAdapters;
    SampleSheetCsvGrammar<std::string::const_iterator> parser(noAdapters);
    isaac::flowcell::BarcodeMetadataList result;
    try
    {
        if (!boost::spirit::qi::parse(parseIt, parseEnd, parser, result) || parseEnd != parseIt)
        {
            CPPUNIT_FAIL("Could not parse the sample sheet csv stream text:\n" + std::string(parseIt, parseEnd));
        }
    }
    catch(boost::spirit::qi::expectation_failure<std::string::const_iterator> const &e)
    {
        const std::string::const_iterator bufferBegin(test.begin());

        const std::string message = (boost::format("Could not parse the sample sheet csv. "
            "Expected:"
            "\n==================================================================\n%s||"
            "\n==================================================================\n"
            "Got:"
            "\n==================================================================\n%s||"
            "\n==================================================================\n"
            " at offset: %d") % e.what_ % std::string(e.first, e.last) %
            std::distance(bufferBegin, e.first)).str();
        CPPUNIT_FAIL(message);
    }
    CPPUNIT_ASSERT_EQUAL(size_t(2), result.size());

    CPPUNIT_ASSERT_EQUAL(1U, result.at(0).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("V_1"), result.at(0).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string("GCTACGCT-ACTGCATA"), result.at(0).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("DaytoDayVaraiability"), result.at(0).getDescription());
    CPPUNIT_ASSERT_EQUAL(std::string("Nick"), result.at(0).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("Tudu"), result.at(0).getProject());
    CPPUNIT_ASSERT_EQUAL(false, result.at(0).isUnknown());

    CPPUNIT_ASSERT_EQUAL(1U, result.at(1).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("V_2"), result.at(1).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string("CGAGGCTG-ACTGCATA"), result.at(1).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("DaytoDayVaraiability"), result.at(1).getDescription());
    CPPUNIT_ASSERT_EQUAL(std::string("Nick"), result.at(1).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("Tudu"), result.at(1).getProject());
    CPPUNIT_ASSERT_EQUAL(false, result.at(1).isUnknown());
}

void TestSampleSheetCsvGrammar::testNonMultiplexedMiSeq()
{
    std::string test(
"[Header],,,,,,,,,,,,,,,,\r\n"
"IEMFileVersion,3,,,,,,,,,,,,,,,\r\n"
"Investigator Name,TN/ZK,,,,,,,,,,,,,,,\r\n"
"Project Name,2kb,,,,,,,,,,,,,,,\r\n"
"Experiment Name,Roberto 2kb,,,,,,,,,,,,,,,\r\n"
"Date,05/01/2012,,,,,,,,,,,,,,,\r\n"
"Workflow,Resequencing,,,,,,,,,,,,,,,\r\n"
"Assay,TruSeq DNA/RNA,,,,,,,,,,,,,,,\r\n"
"Description,,,,,,,,,,,,,,,,\r\n"
"Chemistry,Arusha_Roberto,,,,,,,,,,,,,,,\r\n"
"[Reads],,,,,,,,,,,,,,,,\r\n"
"101,,,,,,,,,,,,,,,,\r\n"
"101,,,,,,,,,,,,,,,,\r\n"
"[Settings],,,,,,,,,,,,,,,,\r\n"
"[Data],,,,,,,,,,,,,,,,\r\n"
"Sample_ID,Sample_Name,GenomeFolder\r\n"
"E-coli,CT5244,\\\\ch-isilon\\isilon\\Mondas_software\\Genomes\\E_coli_ELAND"
        );
    std::string::const_iterator parseIt(test.begin());
    std::string::const_iterator parseEnd(test.end());

    const isaac::flowcell::SequencingAdapterMetadataList noAdapters;
    SampleSheetCsvGrammar<std::string::const_iterator> parser(noAdapters);
    isaac::flowcell::BarcodeMetadataList result;
    try
    {
        if (!boost::spirit::qi::parse(parseIt, parseEnd, parser, result) || parseEnd != parseIt)
        {
            CPPUNIT_FAIL("Could not parse the sample sheet csv stream text:\n" + std::string(parseIt, parseEnd));
        }
    }
    catch(boost::spirit::qi::expectation_failure<std::string::const_iterator> const &e)
    {
        const std::string::const_iterator bufferBegin(test.begin());

        const std::string message = (boost::format("Could not parse the sample sheet csv. "
            "Expected:"
            "\n==================================================================\n%s||"
            "\n==================================================================\n"
            "Got:"
            "\n==================================================================\n%s||"
            "\n==================================================================\n"
            " at offset: %d") % e.what_ % std::string(e.first, e.last) %
            std::distance(bufferBegin, e.first)).str();
        CPPUNIT_FAIL(message);
    }
    CPPUNIT_ASSERT_EQUAL(size_t(1), result.size());

    CPPUNIT_ASSERT_EQUAL(1U, result.at(0).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("E-coli"), result.at(0).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string(""), result.at(0).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("none"), result.at(0).getName());
    CPPUNIT_ASSERT_EQUAL(std::string("TN/ZK"), result.at(0).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("2kb"), result.at(0).getProject());
    CPPUNIT_ASSERT_EQUAL(false, result.at(0).isUnknown());
    CPPUNIT_ASSERT_EQUAL(true, result.at(0).isNoIndex());
    CPPUNIT_ASSERT_EQUAL(std::string("\\\\ch-isilon\\isilon\\Mondas_software\\Genomes\\E_coli_ELAND"), result.at(0).getReference());
}

void TestSampleSheetCsvGrammar::testSingleBarcodeMiSeq()
{
    std::string test(
        "[Header],,,\r\n"
        "Investigator Name,Aurelie,,\r\n"
        "Project Name,Blah,,\r\n"
        "Experiment Name,tada,,\r\n"
        "Date,02/03/2012,,\r\n"
        "Workflow,Resequencing,,\r\n"
        "Chemistry,outch,,\r\n"
        ",,,\r\n"
        "[Reads],,,\r\n"
        "251,,,\r\n"
        "251,,,\r\n"
        ",,,\r\n"
        "[Manifests],,,\r\n"
        "A,ManifestNameHere,,\r\n"
        ",,,\r\n"
        "[Settings],,,\r\n"
        "FilterPCRDuplicates,0,,\r\n"
        ",,,\r\n"
        "[Data],,,\r\n"
        "Sample_ID,Sample_Name,GenomeFolder,Index\r\n"
        "1,BCereus,\\\\ch-isilon\\iGenomes\\Bacillus_cereus_ATCC_10987\\NCBI\\2004-02-13\\Sequence\\Chromosomes,CTTGTA\r\n"
        "2,Rhodo,\\\\ch-isilon\\iGenomes\\Rhodobacter_sphaeroides_2.4.1\\NCBI\\2005-10-07\\Sequence\\Chromosomes,CAGATC\r\n"
        "3,Human,\\\\ch-isilon\\iGenomes\\Homo_sapiens\\NCBI\\build37.2\\Sequence\\Chromosomes,ATCACG\r\n"
        "4,EColi,\\\\ch-isilon\\iGenomes\\Escherichia_coli_K_12_DH10B\\NCBI\\2008-03-17\\Sequence\\Chromosomes,TGACCA\r\n"
        "5,EColi,\\\\ch-isilon\\iGenomes\\Escherichia_coli_K_12_DH10B\\NCBI\\2008-03-17\\Sequence\\Chromosomes,GCCAAT\r\n"
        "6,PHix,\\\\ch-isilon\\iGenomes\\PhiX\\Illumina\\RTA\\Sequence\\Chromosomes,CGATGT\r\n"
        );
    std::string::const_iterator parseIt(test.begin());
    std::string::const_iterator parseEnd(test.end());

    const isaac::flowcell::SequencingAdapterMetadataList noAdapters;
    SampleSheetCsvGrammar<std::string::const_iterator> parser(noAdapters);
    isaac::flowcell::BarcodeMetadataList result;
    try
    {
        if (!boost::spirit::qi::parse(parseIt, parseEnd, parser, result) || parseEnd != parseIt)
        {
            CPPUNIT_FAIL("Could not parse the sample sheet csv stream text:\n" + std::string(parseIt, parseEnd));
        }
    }
    catch(boost::spirit::qi::expectation_failure<std::string::const_iterator> const &e)
    {
        const std::string::const_iterator bufferBegin(test.begin());

        const std::string message = (boost::format("Could not parse the sample sheet csv. "
            "Expected:"
            "\n==================================================================\n%s||"
            "\n==================================================================\n"
            "Got:"
            "\n==================================================================\n%s||"
            "\n==================================================================\n"
            " at offset: %d") % e.what_ % std::string(e.first, e.last) %
            std::distance(bufferBegin, e.first)).str();
        CPPUNIT_FAIL(message);
    }
    CPPUNIT_ASSERT_EQUAL(size_t(6), result.size());

    CPPUNIT_ASSERT_EQUAL(1U, result.at(0).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("1"), result.at(0).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string("CTTGTA"), result.at(0).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("CTTGTA"), result.at(0).getName());
    CPPUNIT_ASSERT_EQUAL(std::string("Aurelie"), result.at(0).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("Blah"), result.at(0).getProject());
    CPPUNIT_ASSERT_EQUAL(false, result.at(0).isUnknown());
    CPPUNIT_ASSERT_EQUAL(false, result.at(0).isNoIndex());
    CPPUNIT_ASSERT_EQUAL(std::string("\\\\ch-isilon\\iGenomes\\Bacillus_cereus_ATCC_10987\\NCBI\\2004-02-13\\Sequence\\Chromosomes"), result.at(0).getReference());

    CPPUNIT_ASSERT_EQUAL(1U, result.at(1).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("2"), result.at(1).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string("CAGATC"), result.at(1).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("CAGATC"), result.at(1).getName());
    CPPUNIT_ASSERT_EQUAL(std::string("Aurelie"), result.at(1).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("Blah"), result.at(1).getProject());
    CPPUNIT_ASSERT_EQUAL(false, result.at(1).isUnknown());
    CPPUNIT_ASSERT_EQUAL(false, result.at(1).isNoIndex());
    CPPUNIT_ASSERT_EQUAL(std::string("\\\\ch-isilon\\iGenomes\\Rhodobacter_sphaeroides_2.4.1\\NCBI\\2005-10-07\\Sequence\\Chromosomes"), result.at(1).getReference());

    CPPUNIT_ASSERT_EQUAL(1U, result.at(2).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("3"), result.at(2).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string("ATCACG"), result.at(2).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("ATCACG"), result.at(2).getName());
    CPPUNIT_ASSERT_EQUAL(std::string("Aurelie"), result.at(2).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("Blah"), result.at(2).getProject());
    CPPUNIT_ASSERT_EQUAL(false, result.at(2).isUnknown());
    CPPUNIT_ASSERT_EQUAL(false, result.at(2).isNoIndex());
    CPPUNIT_ASSERT_EQUAL(std::string("\\\\ch-isilon\\iGenomes\\Homo_sapiens\\NCBI\\build37.2\\Sequence\\Chromosomes"), result.at(2).getReference());

    CPPUNIT_ASSERT_EQUAL(1U, result.at(3).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("4"), result.at(3).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string("TGACCA"), result.at(3).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("TGACCA"), result.at(3).getName());
    CPPUNIT_ASSERT_EQUAL(std::string("Aurelie"), result.at(3).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("Blah"), result.at(3).getProject());
    CPPUNIT_ASSERT_EQUAL(false, result.at(3).isUnknown());
    CPPUNIT_ASSERT_EQUAL(false, result.at(3).isNoIndex());
    CPPUNIT_ASSERT_EQUAL(std::string("\\\\ch-isilon\\iGenomes\\Escherichia_coli_K_12_DH10B\\NCBI\\2008-03-17\\Sequence\\Chromosomes"), result.at(3).getReference());

    CPPUNIT_ASSERT_EQUAL(1U, result.at(4).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("5"), result.at(4).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string("GCCAAT"), result.at(4).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("GCCAAT"), result.at(4).getName());
    CPPUNIT_ASSERT_EQUAL(std::string("Aurelie"), result.at(4).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("Blah"), result.at(4).getProject());
    CPPUNIT_ASSERT_EQUAL(false, result.at(4).isUnknown());
    CPPUNIT_ASSERT_EQUAL(false, result.at(4).isNoIndex());
    CPPUNIT_ASSERT_EQUAL(std::string("\\\\ch-isilon\\iGenomes\\Escherichia_coli_K_12_DH10B\\NCBI\\2008-03-17\\Sequence\\Chromosomes"), result.at(4).getReference());

    CPPUNIT_ASSERT_EQUAL(1U, result.at(5).getLane());
    CPPUNIT_ASSERT_EQUAL(std::string("6"), result.at(5).getSampleName());
    CPPUNIT_ASSERT_EQUAL(std::string("CGATGT"), result.at(5).getSequence());
    CPPUNIT_ASSERT_EQUAL(std::string("CGATGT"), result.at(5).getName());
    CPPUNIT_ASSERT_EQUAL(std::string("Aurelie"), result.at(5).getOperator());
    CPPUNIT_ASSERT_EQUAL(std::string("Blah"), result.at(5).getProject());
    CPPUNIT_ASSERT_EQUAL(false, result.at(5).isUnknown());
    CPPUNIT_ASSERT_EQUAL(false, result.at(5).isNoIndex());
    CPPUNIT_ASSERT_EQUAL(std::string("\\\\ch-isilon\\iGenomes\\PhiX\\Illumina\\RTA\\Sequence\\Chromosomes"), result.at(5).getReference());
}

ext: cpp


text:
#pragma once

/***
 * Helper header which includes boost spirit
 */

#include <boost/config/warning_disable.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/qi.hpp>

namespace wml {
namespace qi = boost::spirit::qi;
} // end namespace wml

ext: hpp

max_stars_repo_name: garbageslam/libwml

max_issues_repo_name: garbageslam/libwml

max_forks_repo_name: garbageslam/libwml


text:
#include <Corrade/Containers/Array.h>
#include <Corrade/Containers/ArrayView.h>
#include <Corrade/Utility/Arguments.h>
#include <Magnum/GL/Renderer.h>
#include <Magnum/Shaders/VertexColor.h>
#include <mtao/geometry/grid/grid.h>
#include <mtao/opengl/objects/grid.h>
#include <mtao/types.h>

#include <Eigen/Geometry>
#include <algorithm>
#include <iostream>
#include <memory>
#include <mtao/opengl/shaders/vector_field.hpp>

#include "imgui.h"
#include "mtao/geometry/bounding_box.hpp"
#include "mtao/geometry/mesh/boundary_facets.h"
#include "mtao/geometry/mesh/read_obj.hpp"
#include "mtao/opengl/Window.h"
#include "mtao/opengl/drawables.h"

using namespace mtao::opengl;

class MeshViewer : public mtao::opengl::Window3 {
   public:
    enum class Mode : int { Smoothing, LSReinitialization };
    Mode mode = Mode::LSReinitialization;

    float permeability = 100.0;
    float timestep = 1000.0;
    bool animate = false;
    using Vec = mtao::VectorX<GLfloat>;
    using Vec3 = mtao::Vec3f;
    Vec data;
    Vec data_original;
    Vec dx;
    Vec dy;
    Vec signs;
    Eigen::AlignedBox<float, 3> bbox;
    Eigen::SparseMatrix<float> L;

    std::array<int, 3> N{{20, 20, 20}};
    int& NI = N[0];
    int& NJ = N[1];
    int& NK = N[2];
    float scale = 1.0;

    Eigen::SimplicialLDLT<Eigen::SparseMatrix<float>> solver;

    MeshViewer(const Arguments& args)
        : Window3(args),
          _wireframe_shader{
              supportsGeometryShader()
                  ? Magnum::Shaders::MeshVisualizer::Flag::Wireframe
                  : Magnum::Shaders::MeshVisualizer::Flag{}} {
        bbox.min().setConstant(-1);
        bbox.max().setConstant(1);
        mv_drawable =
            new mtao::opengl::Drawable<Magnum::Shaders::MeshVisualizer>{
                grid, _wireframe_shader, drawables()};
        mv_drawable->set_visibility(false);
        ;

        edge_drawable = new mtao::opengl::Drawable<Magnum::Shaders::Flat3D>{
            grid, _flat_shader, drawables()};
        edge_drawable->activate_triangles({});
        edge_drawable->activate_edges();
        grid.setParent(&root());
        vfield_mesh.setParent(&root());
#ifdef FLATIT
        _vf_viewer = new mtao::opengl::Drawable<Magnum::Shaders::Flat3D>{
            vfield_mesh, _flat_shader, drawables()};
#else
        _vf_viewer =
            new mtao::opengl::Drawable<mtao::opengl::VectorFieldShader<3>>{
                vfield_mesh, _vf_shader, drawables()};
#endif
        update();
    }
    void update() {
        // mtao::geometry::grid::Grid3f g(std::array<int,3>{{NI,NJ,NK}});
        auto g = mtao::geometry::grid::Grid3f::from_bbox(
            bbox, std::array<int, 3>{{NI, NJ, NK}});

        grid.set(g);
        {
            vfield_mesh.setVertexBuffer(g.vertices());
            mtao::ColVecs3f V = g.vertices();
            // V.array() -= .5;
            auto x = V.row(0).eval();
            V.row(0) = -V.row(1);
            V.row(1) = x;
            V.row(2).array() -= g.bbox().center().z();
            V.row(2) = -V.row(2).array().pow(3);
            vfield_mesh.setVFieldBuffer(V);
        }

        _vf_viewer->deactivate();
        _vf_viewer->activate_points();
    }
    void do_animation() {}
    void gui() override {
        if (ImGui::InputInt3("N", &NI)) {
            update();
        }
        if (ImGui::SliderFloat3("min", bbox.min().data(), -2, 2)) {
            bbox.min() = (bbox.min().array() < bbox.max().array())
                             .select(bbox.min(), bbox.max());
            update();
        }
        if (ImGui::SliderFloat3("max", bbox.max().data(), -2, 2)) {
            bbox.max() = (bbox.min().array() > bbox.max().array())
                             .select(bbox.min(), bbox.max());
            update();
        }
        if (ImGui::SliderFloat("scale", &scale, 0, 2)) {
            _vf_shader.setScale(scale);
        }
        if (mv_drawable) {
            mv_drawable->gui();
        }
        if (edge_drawable) {
            edge_drawable->gui();
        }
        if (ImGui::Button("Step")) {
            do_animation();
        }
    }
    /*
    void draw() override {
        if(animate) {
            do_animation();
        }
        Magnum::GL::Renderer::disable(Magnum::GL::Renderer::Feature::FaceCulling);
        Window3::draw();
    }
    */
   private:
    Magnum::Shaders::MeshVisualizer _wireframe_shader;
    Magnum::Shaders::Flat3D _flat_shader;
    mtao::opengl::VectorFieldShader<3> _vf_shader;
    mtao::opengl::objects::Mesh<3> vfield_mesh;
    mtao::opengl::objects::Grid<3> grid;
    mtao::opengl::Drawable<Magnum::Shaders::MeshVisualizer>* mv_drawable =
        nullptr;
    mtao::opengl::Drawable<Magnum::Shaders::Flat3D>* edge_drawable = nullptr;
#ifdef FLATIT
    mtao::opengl::Drawable<Magnum::Shaders::Flat3D>* _vf_viewer = nullptr;
#else
    mtao::opengl::Drawable<mtao::opengl::VectorFieldShader<3>>* _vf_viewer =
        nullptr;
#endif
};

MAGNUM_APPLICATION_MAIN(MeshViewer)

max_stars_repo_name: mtao/core

max_issues_repo_name: mtao/core

max_forks_repo_name: mtao/core


text:
#pragma once

#include <nano/lib/errors.hpp>
#include <nano/lib/locks.hpp>
#include <nano/lib/timer.hpp>

#include <boost/iostreams/concepts.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/multiprecision/cpp_int.hpp>

#include <atomic>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <string>

#define GTEST_TEST_ERROR_CODE(expression, text, actual, expected, fail)                       \
	GTEST_AMBIGUOUS_ELSE_BLOCKER_                                                             \
	if (const ::testing::AssertionResult gtest_ar_ = ::testing::AssertionResult (expression)) \
		;                                                                                \
	else                                                                                \
		fail (::testing::internal::GetBoolAssertionFailureMessage (                           \
		gtest_ar_, text, actual, expected)                                                    \
		      .c_str ())

/** Extends gtest with a std::error_code assert that prints the error code message when non-zero */
#define ASSERT_NO_ERROR(condition)                                                      \
	GTEST_TEST_ERROR_CODE (!(condition), #condition, condition.message ().c_str (), "", \
	GTEST_FATAL_FAILURE_)

/** Extends gtest with a std::error_code assert that expects an error */
#define ASSERT_IS_ERROR(condition)                                                            \
	GTEST_TEST_ERROR_CODE ((condition.value () > 0), #condition, "An error was expected", "", \
	GTEST_FATAL_FAILURE_)

/** Asserts that the condition becomes true within the deadline */
#define ASSERT_TIMELY(time, condition)    \
	system.deadline_set (time);           \
	while (!(condition))                  \
	{                                     \
		ASSERT_NO_ERROR (system.poll ()); \
	}

/* Convenience globals for gtest projects */
namespace nano
{
using uint128_t = boost::multiprecision::uint128_t;
class keypair;
class public_key;
class block_hash;
class telemetry_data;
class network_params;
class system;

extern nano::keypair const & zero_key;
extern nano::keypair const & dev_genesis_key;
extern std::string const & nano_dev_genesis;
extern std::string const & genesis_block;
extern nano::block_hash const & genesis_hash;
extern nano::public_key const & nano_dev_account;
extern nano::public_key const & genesis_account;
extern nano::public_key const & burn_account;
extern nano::uint128_t const & genesis_amount;

class stringstream_mt_sink : public boost::iostreams::sink
{
public:
	stringstream_mt_sink () = default;
	stringstream_mt_sink (stringstream_mt_sink const & sink)
	{
		nano::lock_guard<std::mutex> guard (mutex);
		ss << sink.ss.str ();
	}

	std::streamsize write (const char * string_to_write, std::streamsize size)
	{
		nano::lock_guard<std::mutex> guard (mutex);
		ss << std::string (string_to_write, size);
		return size;
	}

	std::string str ()
	{
		nano::lock_guard<std::mutex> guard (mutex);
		return ss.str ();
	}

private:
	mutable std::mutex mutex;
	std::stringstream ss;
};

class boost_log_cerr_redirect
{
public:
	boost_log_cerr_redirect (std::streambuf * new_buffer) :
	old (std::cerr.rdbuf (new_buffer))
	{
		console_sink = (boost::log::add_console_log (std::cerr, boost::log::keywords::format = "%Message%"));
	}

	~boost_log_cerr_redirect ()
	{
		std::cerr.rdbuf (old);
		boost::log::core::get ()->remove_sink (console_sink);
	}

private:
	std::streambuf * old;
	boost::shared_ptr<boost::log::sinks::synchronous_sink<boost::log::sinks::text_ostream_backend>> console_sink;
};

class cout_redirect
{
public:
	cout_redirect (std::streambuf * new_buffer)
	{
		std::cout.rdbuf (new_buffer);
	}

	~cout_redirect ()
	{
		std::cout.rdbuf (old);
	}

private:
	std::streambuf * old{ std::cout.rdbuf () };
};

namespace util
{
	/**
	 * Helper to signal completion of async handlers in tests.
	 * Subclasses implement specific conditions for completion.
	 */
	class completion_signal
	{
	public:
		virtual ~completion_signal ()
		{
			notify ();
		}

		/** Explicitly notify the completion */
		void notify ()
		{
			cv.notify_all ();
		}

	protected:
		nano::condition_variable cv;
		std::mutex mutex;
	};

	/**
	 * Signals completion when a count is reached.
	 */
	class counted_completion : public completion_signal
	{
	public:
		/**
		 * Constructor
		 * @param required_count_a When increment() reaches this count within the deadline, await_count_for() will return false.
		 */
		counted_completion (unsigned required_count_a) :
		required_count (required_count_a)
		{
		}

		/**
		 * Wait for increment() to signal completion, or reaching the deadline.
		 * @param deadline_duration_a Deadline as a std::chrono duration
		 * @return true if the count is reached within the deadline
		 */
		template <typename UNIT>
		bool await_count_for (UNIT deadline_duration_a)
		{
			nano::timer<UNIT> timer (nano::timer_state::started);
			bool error = true;
			while (error && timer.before_deadline (deadline_duration_a))
			{
				error = count < required_count;
				if (error)
				{
					nano::unique_lock<std::mutex> lock (mutex);
					cv.wait_for (lock, std::chrono::milliseconds (1));
				}
			}
			return error;
		}

		/** Increments the current count. If the required count is reached, await_count_for() waiters are notified. */
		unsigned increment ()
		{
			auto val (count.fetch_add (1));
			if (val >= required_count)
			{
				notify ();
			}
			return val;
		}

		void increment_required_count ()
		{
			++required_count;
		}

	private:
		std::atomic<unsigned> count{ 0 };
		std::atomic<unsigned> required_count;
	};
}

void wait_peer_connections (nano::system &);
}

max_stars_repo_name: LenWilliamson/nano-node

max_issues_repo_name: LenWilliamson/nano-node

max_forks_repo_name: LenWilliamson/nano-node


text:
/***************************************************************************
   Copyright 2015 Ufora Inc.

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

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

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

#ifdef BSA_PLATFORM_WINDOWS
#define BOOST_TEST_DYN_LINK
#endif

#include <boost/test/unit_test.hpp>

#define BOOST_TEST_USE_CPPML_PRINTER( T )                               \
namespace boost { namespace test_tools {								\
template<>																\
struct print_log_value<T> {												\
	void operator()( std::ostream& os, T const& t )						\
		{																\
		os << prettyPrintString(t);										\
		}																\
};																		\
}}																		// End of macro.

max_stars_repo_name: ufora/ufora


text:
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <string>
#include <sstream>

#include <sensor_msgs/PointCloud2.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_cloud.h>

#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>

#include <cstdlib>
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <std_msgs/Bool.h>
#include <std_msgs/UInt16.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <time.h>
#include <sys/timeb.h>
#include "baxter_core_msgs/EndpointState.h"
#include "baxter_core_msgs/EndEffectorState.h"
#include "baxter_pykdl/joy_stick_commands.h"
#include <sensor_msgs/JointState.h>
#include <sys/stat.h>
#include <boost/filesystem.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
// using namespace cv;
// using namespace std;

// void leftCallback (const baxter_core_msgs::EndpointState& msg);

int Folder_number;
std::string frame_str;
std::stringstream convert; // stringstream used for the conversion

std::string folder1;
std::string sub_folder1;

std::stringstream folder;
std::stringstream N;
int frame = 0;
bool flag1 = 0;
bool flag2 = 0;
bool flag3 = 0;
bool flag4 = 0;
bool flag5 = 0;

struct stat info;
std::ofstream robotStream;
std::ofstream leftStream;
std::ofstream rightStream;

cv_bridge::CvImagePtr right;
cv_bridge::CvImagePtr kinect;
cv_bridge::CvImagePtr left;
baxter_core_msgs::EndpointState left_arm;
baxter_core_msgs::EndpointState right_arm;
baxter_core_msgs::EndEffectorState left_g;
baxter_core_msgs::EndEffectorState right_g;
sensor_msgs::PointCloud2ConstPtr table;
sensor_msgs::JointState robot;
baxter_pykdl::joy_stick_commands joy_commands;
std_msgs::UInt16 save_commands;

pcl::PCLPointCloud2* cloud = new pcl::PCLPointCloud2;
pcl::PCLPointCloud2ConstPtr cloudPtr(cloud);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_filtered2(new pcl::PointCloud<pcl::PointXYZRGB>);

cv::VideoCapture stream1(0);
cv::Mat cameraFrame;

void left_imageCallback(const sensor_msgs::ImageConstPtr& msg)
{
  cv::imshow("left", cv_bridge::toCvShare(msg, "bgr8")->image);
  cv::waitKey(1);
  if (!flag1)
    std::cout << "left recieved..." << std::endl;
  flag1 = 1;
  left = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
}

void right_imageCallback(const sensor_msgs::ImageConstPtr& msg)
{
  cv::imshow("right", cv_bridge::toCvShare(msg, "bgr8")->image);
  cv::waitKey(1);
  if (!flag2)
    std::cout << "right recieved..." << std::endl;
  flag2 = 1;
  right = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
}

void kinect_imageCallback(const sensor_msgs::ImageConstPtr& msg)
{
  cv::imshow("kinect", cv_bridge::toCvShare(msg, "bgr8")->image);
  kinect = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
  // rgb camera
  stream1.read(cameraFrame);
  cv::imshow("cam", cameraFrame);
  cv::waitKey(1);
  if (!flag3)
  {
    std::cout << "kinect recieved..." << std::endl;
    std::cout << "cam recieved..." << std::endl;
  }
  flag3 = 1;
}

void
cloud_table (const sensor_msgs::PointCloud2ConstPtr& cloud_msg)
{
  table = cloud_msg;
  if (!flag4)
    std::cout << "table pointcloud recieved..." << std::endl;
  flag4 = 1;
}

void
cloud_cb (const sensor_msgs::PointCloud2ConstPtr& cloud_msg)
{
  if (flag1 && flag2 && flag3 && flag4 && flag5)
  {
  frame += 1;
  std::cout << frame << " frames received..." << std::endl;
  convert.str("");
  if (frame<10)
    convert << "000" << frame;
  else if (frame<100)
    convert << "00" << frame;
  else if (frame<1000)
    convert << "0" << frame;
  else if (frame<10000)
    convert << frame;
  frame_str = convert.str();
  // saving left hand image
  sub_folder1 = folder1+"/LH_rgb/Left_"+frame_str+".png";
  cv::imwrite(sub_folder1.c_str(), left->image);
  // saving right hand image
  sub_folder1 = folder1+"/RH_rgb/Right_"+frame_str+".png";
  cv::imwrite(sub_folder1.c_str(), right->image);
  // saving kinect image
  sub_folder1 = folder1+"/kinect_rgb/Kinect_"+frame_str+".png";
  cv::imwrite(sub_folder1.c_str(), kinect->image);
  // saving cam image
  sub_folder1 = folder1+"/cam/cam_"+frame_str+".png";
  cv::imwrite(sub_folder1.c_str(), cameraFrame);
  // saving left hand data
  sub_folder1 = folder1+"/Robot_state/Robot_state_"+frame_str+".txt";
	robotStream.open(sub_folder1.c_str());
  robotStream << "time:" << robot.header.stamp << "\n\njoint_name,position,velocity,effort"
  << "\n" << robot.name[0] << "," << robot.position[0] << "," << robot.velocity[0] << "," << robot.effort[0]
  << "\n" << robot.name[1] << "," << robot.position[1] << "," << robot.velocity[1] << "," << robot.effort[1]
  << "\n" << robot.name[2] << "," << robot.position[2] << "," << robot.velocity[2] << "," << robot.effort[2]
  << "\n" << robot.name[3] << "," << robot.position[3] << "," << robot.velocity[3] << "," << robot.effort[3]
  << "\n" << robot.name[4] << "," << robot.position[4] << "," << robot.velocity[4] << "," << robot.effort[4]
  << "\n" << robot.name[5] << "," << robot.position[5] << "," << robot.velocity[5] << "," << robot.effort[5]
  << "\n" << robot.name[6] << "," << robot.position[6] << "," << robot.velocity[6] << "," << robot.effort[6]
  << "\n" << robot.name[7] << "," << robot.position[7] << "," << robot.velocity[7] << "," << robot.effort[7]
  << "\n" << robot.name[8] << "," << robot.position[8] << "," << robot.velocity[8] << "," << robot.effort[8]
  << "\n" << robot.name[9] << "," << robot.position[9] << "," << robot.velocity[9] << "," << robot.effort[9]
  << "\n" << robot.name[10] << "," << robot.position[10] << "," << robot.velocity[10] << "," << robot.effort[10]
  << "\n" << robot.name[11] << "," << robot.position[11] << "," << robot.velocity[11] << "," << robot.effort[11]
  << "\n" << robot.name[12] << "," << robot.position[12] << "," << robot.velocity[12] << "," << robot.effort[12]
  << "\n" << robot.name[13] << "," << robot.position[13] << "," << robot.velocity[13] << "," << robot.effort[13]
  << "\n" << robot.name[14] << "," << robot.position[14] << "," << robot.velocity[14] << "," << robot.effort[14]
  << "\n" << robot.name[15] << "," << robot.position[15] << "," << robot.velocity[15] << "," << robot.effort[15]
  << "\n\nLeft_Gripper"
  << "\nL_x," << left_arm.pose.position.x
  << "\nL_y," << left_arm.pose.position.y
  << "\nL_z," << left_arm.pose.position.z
  << "\nL_rot_x," << left_arm.pose.orientation.x
  << "\nL_rot_y," << left_arm.pose.orientation.y
  << "\nL_rot_z," << left_arm.pose.orientation.z
  << "\nL_rot_w," << left_arm.pose.orientation.w
  << "\nL_gripper," << left_g.position
  << "\n\nRight_Gripper"
  << "\nR_x," << right_arm.pose.position.x
  << "\nR_y," << right_arm.pose.position.y
  << "\nR_z," << right_arm.pose.position.z
  << "\nR_rot_x," << right_arm.pose.orientation.x
  << "\nR_rot_y," << right_arm.pose.orientation.y
  << "\nR_rot_z," << right_arm.pose.orientation.z
  << "\nR_rot_w," << right_arm.pose.orientation.w
  << "\nR_gripper," << right_g.position
  << "\n\nRobot_commands"
  << "\narm," << joy_commands.arm
  << "\njoystick_buttons," << joy_commands.buttons
  << "\njoystick_axes," << joy_commands.axes
  << "\ntwist," << joy_commands.twist
  << "\nq_dot," << joy_commands.q_dot;
	robotStream.close();
  // saving right hand data
  // sub_folder1 = folder1+"/RH_data/EndpointRight_"+frame_str+".csv";
	// rightStream.open(sub_folder1.c_str());
  // rightStream << "time:" << robot.header.stamp << "\nx:" << right_arm.pose.position.x << "\ny:" << right_arm.pose.position.y << "\nz:" << right_arm.pose.position.z << "\nrot_x:"
  //  << right_arm.pose.orientation.x << "\nrot_y:" << right_arm.pose.orientation.y << "\nrot_z:" << right_arm.pose.orientation.z << "\nrot_w:"
  //  << right_arm.pose.orientation.w << "\ngripper:" << right_g.position << std::endl;
	// rightStream.close();
  // Convert to PCL data type
  pcl_conversions::toPCL(*cloud_msg, *cloud);
  pcl::fromPCLPointCloud2(*cloud,*cloud_filtered2);
  sub_folder1 = folder1+"/tabletop_pc/tabletop_pc_"+frame_str+".pcd";
  pcl::io::savePCDFile (sub_folder1.c_str(), *cloud_filtered2, true);
  // Convert to PCL data type
  pcl_conversions::toPCL(*table, *cloud);
  pcl::fromPCLPointCloud2(*cloud,*cloud_filtered2);
  sub_folder1 = folder1+"/table_pc/table_pc_"+frame_str+".pcd";
  pcl::io::savePCDFile (sub_folder1.c_str(), *cloud_filtered2, true);
  // folder.str("");
  // folder << "/home/omari/Datasets/test" << N.str() << std::string("/table_") << frame_str << std::string(".pcd");
  // pcl::io::savePCDFile (folder.str(), *cloud_filtered2, true);
  }
}

void leftCallback (const baxter_core_msgs::EndpointState& msg)
{
    left_arm = msg;
}

void rightCallback (const baxter_core_msgs::EndpointState& msg)
{
    right_arm = msg;
}

void rightGripperCallback (const baxter_core_msgs::EndEffectorState& msg)
{
    right_g = msg;
}

void leftGripperCallback (const baxter_core_msgs::EndEffectorState& msg)
{
    left_g = msg;
}

void jointCallback (const sensor_msgs::JointState& msg)
{
    if (msg.name[0]=="head_nod")
      robot = msg;
}

void jointCommandsCallback (const baxter_pykdl::joy_stick_commands& msg)
{
    joy_commands = msg;
}

void saveCommandsCallback (const std_msgs::UInt16& msg)
{
    save_commands = msg;
    std::cout << save_commands.data << std::endl;

    if (save_commands.data)
    {
      // check if folder exists so we don't over write it
      folder1 = "/home/omari/Datasets/scene"+N.str();
      if( stat( folder1.c_str(), &info ) != 0 )
      {
          printf( "creating %s\n", folder1.c_str() );
          boost::filesystem::create_directories(folder1.c_str());
          sub_folder1 = folder1+ "/tracking";
          printf( "creating %s\n", sub_folder1.c_str() );
          boost::filesystem::create_directories(sub_folder1.c_str());
          sub_folder1 = folder1+ "/tabletop_pc";
          printf( "creating %s\n", sub_folder1.c_str() );
          boost::filesystem::create_directories(sub_folder1.c_str());
          sub_folder1 = folder1+ "/table_pc";
          printf( "creating %s\n", sub_folder1.c_str() );
          boost::filesystem::create_directories(sub_folder1.c_str());
          sub_folder1 = folder1+ "/cam";
          printf( "creating %s\n", sub_folder1.c_str() );
          boost::filesystem::create_directories(sub_folder1.c_str());
          sub_folder1 = folder1+ "/kinect_rgb";
          printf( "creating %s\n", sub_folder1.c_str() );
          boost::filesystem::create_directories(sub_folder1.c_str());
          sub_folder1 = folder1+ "/LH_rgb";
          printf( "creating %s\n", sub_folder1.c_str() );
          boost::filesystem::create_directories(sub_folder1.c_str());
          sub_folder1 = folder1+ "/RH_rgb";
          printf( "creating %s\n", sub_folder1.c_str() );
          boost::filesystem::create_directories(sub_folder1.c_str());
          sub_folder1 = folder1+ "/Robot_state";
          printf( "creating %s\n", sub_folder1.c_str() );
          boost::filesystem::create_directories(sub_folder1.c_str());
          sub_folder1 = folder1+ "/clusters";
          printf( "creating %s\n", sub_folder1.c_str() );
          boost::filesystem::create_directories(sub_folder1.c_str());
          frame = 0;
          flag5 = 1;
      }
      else if( info.st_mode & S_IFDIR )
      {
        printf( "%s exists\n", folder1.c_str() );
        // exit (1);
      }
      else
      {
          printf( "creating %s\n", folder1.c_str() );
          boost::filesystem::create_directories(folder1.c_str());
      }
    }
    else
    {
      flag5 = 0;
      std::cout << "stopped saving" << std::endl;
      Folder_number++;
      N.str("");
      N << Folder_number;
    }

}

int main(int argc, char **argv)
{
  // check if user entered folder number
  if (argc < 2)
  {
    PCL_WARN("Please set the folder (e.g. rosrun pcl_functions save_data 6)\n", argv[0]);
    exit (1);
  }

  // Initialize node and subscribers
  N.str("");
  N << argv[1];
  Folder_number = (uint16_t)atoi(argv[1]);
  ros::init(argc, argv, "image_listener");
  ros::NodeHandle nh;
  cv::namedWindow("left");
  cv::namedWindow("right");
  cv::namedWindow("kinect");
  cv::namedWindow("cam");
  cv::startWindowThread();
  image_transport::ImageTransport it(nh);
  image_transport::Subscriber sub1 = it.subscribe("/cameras/left_hand_camera/image", 1, left_imageCallback);
  image_transport::Subscriber sub2 = it.subscribe("/cameras/right_hand_camera/image", 1, right_imageCallback);
  image_transport::Subscriber sub3 = it.subscribe("/kinect2_1/qhd/image_color", 1, kinect_imageCallback);
  ros::Subscriber sub4 = nh.subscribe ("/table_pointcloud_1", 1, cloud_table);
  ros::Subscriber sub5 = nh.subscribe ("/tabletop_pointcloud_1", 1, cloud_cb);
	ros::Subscriber sub6 = nh.subscribe("/robot/limb/left/endpoint_state", 1, leftCallback);
	ros::Subscriber sub7 = nh.subscribe("/robot/limb/right/endpoint_state", 1, rightCallback);
	ros::Subscriber sub8 = nh.subscribe("/robot/end_effector/right_gripper/state", 1, rightGripperCallback);
	ros::Subscriber sub9 = nh.subscribe("/robot/end_effector/left_gripper/state", 1, leftGripperCallback);
	ros::Subscriber sub10 = nh.subscribe("/robot/joint_states", 1, jointCallback);
	ros::Subscriber sub11 = nh.subscribe("/joy_commands", 1, jointCommandsCallback);
	ros::Subscriber sub12 = nh.subscribe("/save_commands", 1, saveCommandsCallback);
  ros::spin();
  cv::destroyWindow("left");
  cv::destroyWindow("right");
  cv::destroyWindow("kinect");
}


text: #include <boost/spirit/home/karma/stream/ostream_iterator.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  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.
 */
/*
 * Copyright (C) 2020 ScyllaDB
 */

#pragma once

#include "fs/bitwise.hh"
#include "fs/cluster.hh"
#include "fs/inode.hh"
#include "fs/inode_info.hh"
#include "fs/metadata_disk_entries.hh"
#include "fs/metadata_to_disk_buffer.hh"
#include "fs/units.hh"
#include "fs/metadata_log.hh"
#include "seastar/core/do_with.hh"
#include "seastar/core/future-util.hh"
#include "seastar/core/future.hh"
#include "seastar/core/temporary_buffer.hh"

#include <boost/crc.hpp>
#include <cstddef>
#include <cstring>
#include <unordered_set>
#include <variant>

namespace seastar::fs {

// TODO: add a comment about what it is
class data_reader {
    const uint8_t* _data = nullptr;
    size_t _size = 0;
    size_t _pos = 0;
    size_t _last_checkpointed_pos = 0;

public:
    data_reader() = default;

    data_reader(const uint8_t* data, size_t size) : _data(data), _size(size) {}

    size_t curr_pos() const noexcept { return _pos; }

    size_t last_checkpointed_pos() const noexcept { return _last_checkpointed_pos; }

    size_t bytes_left() const noexcept { return _size - _pos; }

    void align_curr_pos(size_t alignment) noexcept { _pos = round_up_to_multiple_of_power_of_2(_pos, alignment); }

    void checkpoint_curr_pos() noexcept { _last_checkpointed_pos = _pos; }

    // Returns whether the reading was successful
    bool read(void* destination, size_t size);

    // Returns whether the reading was successful
    template<class T>
    bool read_entry(T& entry) noexcept {
        return read(&entry, sizeof(entry));
    }

    // Returns whether the reading was successful
    bool read_string(std::string& str, size_t size);

    std::optional<temporary_buffer<uint8_t>> read_tmp_buff(size_t size);

    // Returns whether the processing was successful
    bool process_crc_without_reading(boost::crc_32_type& crc, size_t size);

    std::optional<data_reader> extract(size_t size);
};

class metadata_log_bootstrap {
    metadata_log& _metadata_log;
    cluster_range _available_clusters;
    std::unordered_set<cluster_id_t> _taken_clusters;
    std::optional<cluster_id_t> _next_cluster;
    temporary_buffer<uint8_t> _curr_cluster_data;
    data_reader _curr_cluster;
    data_reader _curr_checkpoint;

    metadata_log_bootstrap(metadata_log& metadata_log, cluster_range available_clusters);

    future<> bootstrap(cluster_id_t first_metadata_cluster_id, fs_shard_id_t fs_shards_pool_size,
            fs_shard_id_t fs_shard_id);

    future<> bootstrap_cluster(cluster_id_t curr_cluster);

    static auto invalid_entry_exception() {
        return make_exception_future<>(std::runtime_error("Invalid metadata log entry"));
    }

    future<> bootstrap_read_cluster();

    // Returns whether reading and checking was successful
    bool read_and_check_checkpoint();

    future<> bootstrap_checkpointed_data();

    future<> bootstrap_next_metadata_cluster();

    bool inode_exists(inode_t inode);

    future<> bootstrap_create_inode();

    future<> bootstrap_delete_inode();

    future<> bootstrap_small_write();

    future<> bootstrap_medium_write();

    future<> bootstrap_large_write();

    future<> bootstrap_large_write_without_mtime();

    future<> bootstrap_truncate();

    future<> bootstrap_add_dir_entry();

    future<> bootstrap_create_inode_as_dir_entry();

    future<> bootstrap_delete_dir_entry();

    future<> bootstrap_delete_inode_and_dir_entry();

public:
    static future<> bootstrap(metadata_log& metadata_log, inode_t root_dir, cluster_id_t first_metadata_cluster_id,
            cluster_range available_clusters, fs_shard_id_t fs_shards_pool_size, fs_shard_id_t fs_shard_id);
};

} // namespace seastar::fs

ext: hh

max_stars_repo_name: rokinsky/seastar

max_issues_repo_name: rokinsky/seastar

max_forks_repo_name: rokinsky/seastar


text:
#ifndef LBFGS_HPP
#define LBFGS_HPP

#include <Eigen/Eigen>
#include <cmath>
#include <algorithm>

namespace lbfgs
{
    // ----------------------- Data Type Part -----------------------

    /**
     * L-BFGS optimization parameters.
     */
    struct lbfgs_parameter_t
    {
        /**
         * The number of corrections to approximate the inverse hessian matrix.
         *  The L-BFGS routine stores the computation results of previous m
         *  iterations to approximate the inverse hessian matrix of the current
         *  iteration. This parameter controls the size of the limited memories
         *  (corrections). The default value is 8. Values less than 3 are
         *  not recommended. Large values will result in excessive computing time.
         */
        int mem_size = 8;

        /**
         * Epsilon for grad convergence test. DO NOT USE IT in nonsmooth cases!
         *  Set it to 0.0 and use past-delta-based test for nonsmooth functions.
         *  This parameter determines the accuracy with which the solution is to
         *  be found. A minimization terminates when
         *      ||g(x)||_inf / max(1, ||x||_inf) < g_epsilon,
         *  where ||.||_inf is the infinity norm. The default value is 1.0e-5.
         *  This should be greater than 1.0e-6 in practice because L-BFGS does
         *  not directly reduce first-order residual. It still needs the function
         *  value which can be corrupted by machine_prec when ||g|| is small.
         */
        double g_epsilon = 1.0e-5;

        /**
         * Distance for delta-based convergence test.
         *  This parameter determines the distance, in iterations, to compute
         *  the rate of decrease of the cost function. If the value of this
         *  parameter is zero, the library does not perform the delta-based
         *  convergence test. The default value is 3.
         */
        int past = 3;

        /**
         * Delta for convergence test.
         *  This parameter determines the minimum rate of decrease of the
         *  cost function. The library stops iterations when the following
         *  condition is met:
         *      |f' - f| / max(1, |f|) < delta,
         *  where f' is the cost value of past iterations ago, and f is
         *  the cost value of the current iteration.
         *  The default value is 1.0e-6.
         */
        double delta = 1.0e-6;

        /**
         * The maximum number of iterations.
         *  The lbfgs_optimize() function terminates an minimization process with
         *  ::LBFGSERR_MAXIMUMITERATION status code when the iteration count
         *  exceedes this parameter. Setting this parameter to zero continues an
         *  minimization process until a convergence or error. The default value
         *  is 0.
         */
        int max_iterations = 0;

        /**
         * The maximum number of trials for the line search.
         *  This parameter controls the number of function and gradients evaluations
         *  per iteration for the line search routine. The default value is 64.
         */
        int max_linesearch = 64;

        /**
         * The minimum step of the line search routine.
         *  The default value is 1.0e-20. This value need not be modified unless
         *  the exponents are too large for the machine being used, or unless the
         *  problem is extremely badly scaled (in which case the exponents should
         *  be increased).
         */
        double min_step = 1.0e-20;

        /**
         * The maximum step of the line search.
         *  The default value is 1.0e+20. This value need not be modified unless
         *  the exponents are too large for the machine being used, or unless the
         *  problem is extremely badly scaled (in which case the exponents should
         *  be increased).
         */
        double max_step = 1.0e+20;

        /**
         * A parameter to control the accuracy of the line search routine.
         *  The default value is 1.0e-4. This parameter should be greater
         *  than zero and smaller than 1.0.
         */
        double f_dec_coeff = 1.0e-4;

        /**
         * A parameter to control the accuracy of the line search routine.
         *  The default value is 0.9. If the function and gradient
         *  evaluations are inexpensive with respect to the cost of the
         *  iteration (which is sometimes the case when solving very large
         *  problems) it may be advantageous to set this parameter to a small
         *  value. A typical small value is 0.1. This parameter should be
         *  greater than the f_dec_coeff parameter and smaller than 1.0.
         */
        double s_curv_coeff = 0.9;

        /**
         * A parameter to ensure the global convergence for nonconvex functions.
         *  The default value is 1.0e-6. The parameter performs the so called
         *  cautious update for L-BFGS, especially when the convergence is
         *  not sufficient. The parameter must be positive but might as well
         *  be less than 1.0e-3 in practice.
         */
        double cautious_factor = 1.0e-6;

        /**
         * The machine precision for floating-point values. The default is 1.0e-16.
         *  This parameter must be a positive value set by a client program to
         *  estimate the machine precision.
         */
        double machine_prec = 1.0e-16;
    };

    /**
     * Return values of lbfgs_optimize().
     *  Roughly speaking, a negative value indicates an error.
     */
    enum
    {
        /** L-BFGS reaches convergence. */
        LBFGS_CONVERGENCE = 0,
        /** L-BFGS satisfies stopping criteria. */
        LBFGS_STOP,
        /** The iteration has been canceled by the monitor callback. */
        LBFGS_CANCELED,

        /** Unknown error. */
        LBFGSERR_UNKNOWNERROR = -1024,
        /** Invalid number of variables specified. */
        LBFGSERR_INVALID_N,
        /** Invalid parameter lbfgs_parameter_t::mem_size specified. */
        LBFGSERR_INVALID_MEMSIZE,
        /** Invalid parameter lbfgs_parameter_t::g_epsilon specified. */
        LBFGSERR_INVALID_GEPSILON,
        /** Invalid parameter lbfgs_parameter_t::past specified. */
        LBFGSERR_INVALID_TESTPERIOD,
        /** Invalid parameter lbfgs_parameter_t::delta specified. */
        LBFGSERR_INVALID_DELTA,
        /** Invalid parameter lbfgs_parameter_t::min_step specified. */
        LBFGSERR_INVALID_MINSTEP,
        /** Invalid parameter lbfgs_parameter_t::max_step specified. */
        LBFGSERR_INVALID_MAXSTEP,
        /** Invalid parameter lbfgs_parameter_t::f_dec_coeff specified. */
        LBFGSERR_INVALID_FDECCOEFF,
        /** Invalid parameter lbfgs_parameter_t::s_curv_coeff specified. */
        LBFGSERR_INVALID_SCURVCOEFF,
        /** Invalid parameter lbfgs_parameter_t::machine_prec specified. */
        LBFGSERR_INVALID_MACHINEPREC,
        /** Invalid parameter lbfgs_parameter_t::max_linesearch specified. */
        LBFGSERR_INVALID_MAXLINESEARCH,
        /** The function value became NaN or Inf. */
        LBFGSERR_INVALID_FUNCVAL,
        /** The line-search step became smaller than lbfgs_parameter_t::min_step. */
        LBFGSERR_MINIMUMSTEP,
        /** The line-search step became larger than lbfgs_parameter_t::max_step. */
        LBFGSERR_MAXIMUMSTEP,
        /** Line search reaches the maximum, assumptions not satisfied or precision not achievable.*/
        LBFGSERR_MAXIMUMLINESEARCH,
        /** The algorithm routine reaches the maximum number of iterations. */
        LBFGSERR_MAXIMUMITERATION,
        /** Relative search interval width is at least lbfgs_parameter_t::machine_prec. */
        LBFGSERR_WIDTHTOOSMALL,
        /** A logic error (negative line-search step) occurred. */
        LBFGSERR_INVALIDPARAMETERS,
        /** The current search direction increases the cost function value. */
        LBFGSERR_INCREASEGRADIENT,
    };

    /**
     * Callback interface to provide cost function and gradient evaluations.
     *
     *  The lbfgs_optimize() function call this function to obtain the values of cost
     *  function and its gradients when needed. A client program must implement
     *  this function to evaluate the values of the cost function and its
     *  gradients, given current values of variables.
     *
     *  @param  instance    The user data sent for lbfgs_optimize() function by the client.
     *  @param  x           The current values of variables.
     *  @param  g           The gradient vector. The callback function must compute
     *                      the gradient values for the current variables.
     *  @retval double      The value of the cost function for the current variables.
     */
    typedef double (*lbfgs_evaluate_t)(void *instance,
                                       const Eigen::VectorXd &x,
                                       Eigen::VectorXd &g);

    /**
     * Callback interface to provide an upper bound at the beginning of the current line search.
     *
     *  The lbfgs_optimize() function call this function to obtain the values of the
     *  upperbound of the stepsize to search in, provided with the beginning values of
     *  variables before the line search, and the current step vector (can be descent direction).
     *  A client program can implement this function for more efficient linesearch. Any step
     *  larger than this bound should not be considered. For example, it has a very large or even
     *  inf function value. Note that the function value at the provided bound should be FINITE!
     *  If it is not used, just set it nullptr.
     *
     *  @param  instance    The user data sent for lbfgs_optimize() function by the client.
     *  @param  xp          The values of variables before current line search.
     *  @param  d           The step vector. It can be the descent direction.
     *  @retval double      The upperboud of the step in current line search routine,
     *                      such that (stpbound * d) is the maximum reasonable step.
     */
    typedef double (*lbfgs_stepbound_t)(void *instance,
                                        const Eigen::VectorXd &xp,
                                        const Eigen::VectorXd &d);

    /**
     * Callback interface to monitor the progress of the minimization process.
     *
     *  The lbfgs_optimize() function call this function for each iteration. Implementing
     *  this function, a client program can store or display the current progress
     *  of the minimization process. If it is not used, just set it nullptr.
     *
     *  @param  instance    The user data sent for lbfgs_optimize() function by the client.
     *  @param  x           The current values of variables.
     *  @param  g           The current gradient values of variables.
     *  @param  fx          The current value of the cost function.
     *  @param  step        The line-search step used for this iteration.
     *  @param  k           The iteration count.
     *  @param  ls          The number of evaluations called for this iteration.
     *  @retval int         Zero to continue the minimization process. Returning a
     *                      non-zero value will cancel the minimization process.
     */
    typedef int (*lbfgs_progress_t)(void *instance,
                                    const Eigen::VectorXd &x,
                                    const Eigen::VectorXd &g,
                                    const double fx,
                                    const double step,
                                    const int k,
                                    const int ls);

    /**
     * Callback data struct
     */
    struct callback_data_t
    {
        void *instance = nullptr;
        lbfgs_evaluate_t proc_evaluate = nullptr;
        lbfgs_stepbound_t proc_stepbound = nullptr;
        lbfgs_progress_t proc_progress = nullptr;
    };

    // ----------------------- L-BFGS Part -----------------------

    /**
     * Line search method for smooth or nonsmooth functions.
     *  This function performs line search to find a point that satisfy
     *  both the Armijo condition and the weak Wolfe condition. It is
     *  as robust as the backtracking line search but further applies
     *  to continuous and piecewise smooth functions where the strong
     *  Wolfe condition usually does not hold.
     *
     *  @see
     *      Adrian S. Lewis and Michael L. Overton. Nonsmooth optimization
     *      via quasi-Newton methods. Mathematical Programming, Vol 141,
     *      No 1, pp. 135-163, 2013.
     */
    inline int line_search_lewisoverton(Eigen::VectorXd &x,
                                        double &f,
                                        Eigen::VectorXd &g,
                                        double &stp,
                                        const Eigen::VectorXd &s,
                                        const Eigen::VectorXd &xp,
                                        const Eigen::VectorXd &gp,
                                        const double stpmin,
                                        const double stpmax,
                                        const callback_data_t &cd,
                                        const lbfgs_parameter_t &param)
    {
        int count = 0;
        bool brackt = false, touched = false;
        double finit, dginit, dgtest, dstest;
        double mu = 0.0, nu = stpmax;

        /* Check the input parameters for errors. */
        if (!(stp > 0.0))
        {
            return LBFGSERR_INVALIDPARAMETERS;
        }

        /* Compute the initial gradient in the search direction. */
        dginit = gp.dot(s);

        /* Make sure that s points to a descent direction. */
        if (0.0 < dginit)
        {
            return LBFGSERR_INCREASEGRADIENT;
        }

        /* The initial value of the cost function. */
        finit = f;
        dgtest = param.f_dec_coeff * dginit;
        dstest = param.s_curv_coeff * dginit;

        while (true)
        {
            x = xp + stp * s;

            /* Evaluate the function and gradient values. */
            f = cd.proc_evaluate(cd.instance, x, g);
            ++count;

            /* Test for errors. */
            if (std::isinf(f) || std::isnan(f))
            {
                return LBFGSERR_INVALID_FUNCVAL;
            }
            /* Check the Armijo condition. */
            if (f > finit + stp * dgtest)
            {
                nu = stp;
                brackt = true;
            }
            else
            {
                /* Check the weak Wolfe condition. */
                if (g.dot(s) < dstest)
                {
                    mu = stp;
                }
                else
                {
                    return count;
                }
            }
            if (param.max_linesearch <= count)
            {
                /* Maximum number of iteration. */
                return LBFGSERR_MAXIMUMLINESEARCH;
            }
            if (brackt && (nu - mu) < param.machine_prec * nu)
            {
                /* Relative interval width is at least machine_prec. */
                return LBFGSERR_WIDTHTOOSMALL;
            }

            if (brackt)
            {
                stp = 0.5 * (mu + nu);
            }
            else
            {
                stp *= 2.0;
            }

            if (stp < stpmin)
            {
                /* The step is the minimum value. */
                return LBFGSERR_MINIMUMSTEP;
            }
            if (stp > stpmax)
            {
                if (touched)
                {
                    /* The step is the maximum value. */
                    return LBFGSERR_MAXIMUMSTEP;
                }
                else
                {
                    /* The maximum value should be tried once. */
                    touched = true;
                    stp = stpmax;
                }
            }
        }
    }

    /**
     * Start a L-BFGS optimization.
     * Assumptions: 1. f(x) is either C2 or C0 but piecewise C2;
     *              2. f(x) is lower bounded;
     *              3. f(x) has bounded level sets;
     *              4. g(x) is either the gradient or subgradient;
     *              5. The gradient exists at the initial guess x0.
     * A user must implement a function compatible with ::lbfgs_evaluate_t (evaluation
     * callback) and pass the pointer to the callback function to lbfgs_optimize()
     * arguments. Similarly, a user can implement a function compatible with
     * ::lbfgs_stepbound_t to provide an external upper bound for stepsize, and
     * ::lbfgs_progress_t (progress callback) to obtain the current progress
     * (e.g., variables, function, and gradient, etc) and to cancel the iteration
     * process if necessary. Implementation of the stepbound and the progress callback
     * is optional: a user can pass nullptr if progress notification is not necessary.
     *
     *
     *  @param  x               The vector of decision variables.
     *                          THE INITIAL GUESS x0 SHOULD BE SET BEFORE THE CALL!
     *                          A client program can receive decision variables
     *                          through this vector, at which the cost and its
     *                          gradient are queried during minimization.
     *  @param  f               The ref to the variable that receives the final
     *                          value of the cost function for the variables.
     *  @param  proc_evaluate   The callback function to provide function f(x) and
     *                          gradient g(x) evaluations given a current values of
     *                          variables x. A client program must implement a
     *                          callback function compatible with lbfgs_evaluate_t
     *                          and pass the pointer to the callback function.
     *  @param  proc_stepbound  The callback function to provide values of the
     *                          upperbound of the stepsize to search in, provided
     *                          with the beginning values of variables before the
     *                          line search, and the current step vector (can be
     *                          negative gradient). A client program can implement
     *                          this function for more efficient linesearch. If it is
     *                          not used, just set it nullptr.
     *  @param  proc_progress   The callback function to receive the progress
     *                          (the number of iterations, the current value of
     *                          the cost function) of the minimization
     *                          process. This argument can be set to nullptr if
     *                          a progress report is unnecessary.
     *  @param  instance        A user data pointer for client programs. The callback
     *                          functions will receive the value of this argument.
     *  @param  param           The parameters for L-BFGS optimization.
     *  @retval int             The status code. This function returns a nonnegative
     *                          integer if the minimization process terminates without
     *                          an error. A negative integer indicates an error.
     */
    inline int lbfgs_optimize(Eigen::VectorXd &x,
                              double &f,
                              lbfgs_evaluate_t proc_evaluate,
                              lbfgs_stepbound_t proc_stepbound,
                              lbfgs_progress_t proc_progress,
                              void *instance,
                              const lbfgs_parameter_t &param)
    {
        int ret, i, j, k, ls, end, bound;
        double step, step_min, step_max, fx, ys, yy;
        double gnorm_inf, xnorm_inf, beta, rate, cau;

        const int n = x.size();
        const int m = param.mem_size;

        /* Check the input parameters for errors. */
        if (n <= 0)
        {
            return LBFGSERR_INVALID_N;
        }
        if (m <= 0)
        {
            return LBFGSERR_INVALID_MEMSIZE;
        }
        if (param.g_epsilon < 0.0)
        {
            return LBFGSERR_INVALID_GEPSILON;
        }
        if (param.past < 0)
        {
            return LBFGSERR_INVALID_TESTPERIOD;
        }
        if (param.delta < 0.0)
        {
            return LBFGSERR_INVALID_DELTA;
        }
        if (param.min_step < 0.0)
        {
            return LBFGSERR_INVALID_MINSTEP;
        }
        if (param.max_step < param.min_step)
        {
            return LBFGSERR_INVALID_MAXSTEP;
        }
        if (!(param.f_dec_coeff > 0.0 &&
              param.f_dec_coeff < 1.0))
        {
            return LBFGSERR_INVALID_FDECCOEFF;
        }
        if (!(param.s_curv_coeff < 1.0 &&
              param.s_curv_coeff > param.f_dec_coeff))
        {
            return LBFGSERR_INVALID_SCURVCOEFF;
        }
        if (!(param.machine_prec > 0.0))
        {
            return LBFGSERR_INVALID_MACHINEPREC;
        }
        if (param.max_linesearch <= 0)
        {
            return LBFGSERR_INVALID_MAXLINESEARCH;
        }

        /* Prepare intermediate variables. */
        Eigen::VectorXd xp(n);
        Eigen::VectorXd g(n);
        Eigen::VectorXd gp(n);
        Eigen::VectorXd d(n);
        Eigen::VectorXd pf(std::max(1, param.past));

        /* Initialize the limited memory. */
        Eigen::VectorXd lm_alpha = Eigen::VectorXd::Zero(m);
        Eigen::MatrixXd lm_s = Eigen::MatrixXd::Zero(n, m);
        Eigen::MatrixXd lm_y = Eigen::MatrixXd::Zero(n, m);
        Eigen::VectorXd lm_ys = Eigen::VectorXd::Zero(m);

        /* Construct a callback data. */
        callback_data_t cd;
        cd.instance = instance;
        cd.proc_evaluate = proc_evaluate;
        cd.proc_stepbound = proc_stepbound;
        cd.proc_progress = proc_progress;

        /* Evaluate the function value and its gradient. */
        fx = cd.proc_evaluate(cd.instance, x, g);

        /* Store the initial value of the cost function. */
        pf(0) = fx;

        /*
        Compute the direction;
        we assume the initial hessian matrix H_0 as the identity matrix.
        */
        d = -g;

        /*
        Make sure that the initial variables are not a stationary point.
        */
        gnorm_inf = g.cwiseAbs().maxCoeff();
        xnorm_inf = x.cwiseAbs().maxCoeff();

        if (gnorm_inf / std::max(1.0, xnorm_inf) < param.g_epsilon)
        {
            /* The initial guess is already a stationary point. */
            ret = LBFGS_CONVERGENCE;
        }
        else
        {
            /*
            Compute the initial step:
            */
            step = 1.0 / d.norm();

            k = 1;
            end = 0;
            bound = 0;

            while (true)
            {
                /* Store the current position and gradient vectors. */
                xp = x;
                gp = g;

                /* If the step bound can be provied dynamically, then apply it. */
                step_min = param.min_step;
                step_max = param.max_step;
                if (cd.proc_stepbound)
                {
                    step_max = cd.proc_stepbound(cd.instance, xp, d);
                    step_max = step_max < param.max_step ? step_max : param.max_step;
                    step = step < step_max ? step : 0.5 * step_max;
                }

                /* Search for an optimal step. */
                ls = line_search_lewisoverton(x, fx, g, step, d, xp, gp, step_min, step_max, cd, param);

                if (ls < 0)
                {
                    /* Revert to the previous point. */
                    x = xp;
                    g = gp;
                    ret = ls;
                    break;
                }

                /* Report the progress. */
                if (cd.proc_progress)
                {
                    if (cd.proc_progress(cd.instance, x, g, fx, step, k, ls))
                    {
                        ret = LBFGS_CANCELED;
                        break;
                    }
                }

                /*
                Convergence test.
                The criterion is given by the following formula:
                ||g(x)||_inf / max(1, ||x||_inf) < g_epsilon
                */
                gnorm_inf = g.cwiseAbs().maxCoeff();
                xnorm_inf = x.cwiseAbs().maxCoeff();
                if (gnorm_inf / std::max(1.0, xnorm_inf) < param.g_epsilon)
                {
                    /* Convergence. */
                    ret = LBFGS_CONVERGENCE;
                    break;
                }

                /*
                Test for stopping criterion.
                The criterion is given by the following formula:
                |f(past_x) - f(x)| / max(1, |f(x)|) < \delta.
                */
                if (0 < param.past)
                {
                    /* We don't test the stopping criterion while k < past. */
                    if (param.past <= k)
                    {
                        /* The stopping criterion. */
                        rate = std::fabs(pf(k % param.past) - fx) / std::max(1.0, std::fabs(fx));

                        if (rate < param.delta)
                        {
                            ret = LBFGS_STOP;
                            break;
                        }
                    }

                    /* Store the current value of the cost function. */
                    pf(k % param.past) = fx;
                }

                if (param.max_iterations != 0 && param.max_iterations <= k)
                {
                    /* Maximum number of iterations. */
                    ret = LBFGSERR_MAXIMUMITERATION;
                    break;
                }

                /* Count the iteration number. */
                ++k;

                /*
                Update vectors s and y:
                s_{k+1} = x_{k+1} - x_{k} = \step * d_{k}.
                y_{k+1} = g_{k+1} - g_{k}.
                */
                lm_s.col(end) = x - xp;
                lm_y.col(end) = g - gp;

                /*
                Compute scalars ys and yy:
                ys = y^t \cdot s = 1 / \rho.
                yy = y^t \cdot y.
                Notice that yy is used for scaling the hessian matrix H_0 (Cholesky factor).
                */
                ys = lm_y.col(end).dot(lm_s.col(end));
                yy = lm_y.col(end).squaredNorm();
                lm_ys(end) = ys;

                /* Compute the negative of gradients. */
                d = -g;

                /*
                Only cautious update is performed here as long as
                (y^t \cdot s) / ||s_{k+1}||^2 > \epsilon * ||g_{k}||^\alpha,
                where \epsilon is the cautious factor and a proposed value
                for \alpha is 1.
                This is not for enforcing the PD of the approxomated Hessian
                since ys > 0 is already ensured by the weak Wolfe condition.
                This is to ensure the global convergence as described in:
                Dong-Hui Li and Masao Fukushima. On the global convergence of
                the BFGS method for nonconvex unconstrained optimization problems.
                SIAM Journal on Optimization, Vol 11, No 4, pp. 1054-1064, 2011.
                */
                cau = lm_s.col(end).squaredNorm() * gp.norm() * param.cautious_factor;

                if (ys > cau)
                {
                    /*
                    Recursive formula to compute dir = -(H \cdot g).
                    This is described in page 779 of:
                    Jorge Nocedal.
                    Updating Quasi-Newton Matrices with Limited Storage.
                    Mathematics of Computation, Vol. 35, No. 151,
                    pp. 773--782, 1980.
                    */
                    ++bound;
                    bound = m < bound ? m : bound;
                    end = (end + 1) % m;

                    j = end;
                    for (i = 0; i < bound; ++i)
                    {
                        j = (j + m - 1) % m; /* if (--j == -1) j = m-1; */
                        /* \alpha_{j} = \rho_{j} s^{t}_{j} \cdot q_{k+1}. */
                        lm_alpha(j) = lm_s.col(j).dot(d) / lm_ys(j);
                        /* q_{i} = q_{i+1} - \alpha_{i} y_{i}. */
                        d += (-lm_alpha(j)) * lm_y.col(j);
                    }

                    d *= ys / yy;

                    for (i = 0; i < bound; ++i)
                    {
                        /* \beta_{j} = \rho_{j} y^t_{j} \cdot \gamm_{i}. */
                        beta = lm_y.col(j).dot(d) / lm_ys(j);
                        /* \gamm_{i+1} = \gamm_{i} + (\alpha_{j} - \beta_{j}) s_{j}. */
                        d += (lm_alpha(j) - beta) * lm_s.col(j);
                        j = (j + 1) % m; /* if (++j == m) j = 0; */
                    }
                }

                /* The search direction d is ready. We try step = 1 first. */
                step = 1.0;
            }
        }

        /* Return the final value of the cost function. */
        f = fx;

        return ret;
    }

    /**
     * Get string description of an lbfgs_optimize() return code.
     *
     *  @param err          A value returned by lbfgs_optimize().
     */
    inline const char *lbfgs_strerror(const int err)
    {
        switch (err)
        {
        case LBFGS_CONVERGENCE:
            return "Success: reached convergence (g_epsilon).";

        case LBFGS_STOP:
            return "Success: met stopping criteria (past f decrease less than delta).";

        case LBFGS_CANCELED:
            return "The iteration has been canceled by the monitor callback.";

        case LBFGSERR_UNKNOWNERROR:
            return "Unknown error.";

        case LBFGSERR_INVALID_N:
            return "Invalid number of variables specified.";

        case LBFGSERR_INVALID_MEMSIZE:
            return "Invalid parameter lbfgs_parameter_t::mem_size specified.";

        case LBFGSERR_INVALID_GEPSILON:
            return "Invalid parameter lbfgs_parameter_t::g_epsilon specified.";

        case LBFGSERR_INVALID_TESTPERIOD:
            return "Invalid parameter lbfgs_parameter_t::past specified.";

        case LBFGSERR_INVALID_DELTA:
            return "Invalid parameter lbfgs_parameter_t::delta specified.";

        case LBFGSERR_INVALID_MINSTEP:
            return "Invalid parameter lbfgs_parameter_t::min_step specified.";

        case LBFGSERR_INVALID_MAXSTEP:
            return "Invalid parameter lbfgs_parameter_t::max_step specified.";

        case LBFGSERR_INVALID_FDECCOEFF:
            return "Invalid parameter lbfgs_parameter_t::f_dec_coeff specified.";

        case LBFGSERR_INVALID_SCURVCOEFF:
            return "Invalid parameter lbfgs_parameter_t::s_curv_coeff specified.";

        case LBFGSERR_INVALID_MACHINEPREC:
            return "Invalid parameter lbfgs_parameter_t::machine_prec specified.";

        case LBFGSERR_INVALID_MAXLINESEARCH:
            return "Invalid parameter lbfgs_parameter_t::max_linesearch specified.";

        case LBFGSERR_INVALID_FUNCVAL:
            return "The function value became NaN or Inf.";

        case LBFGSERR_MINIMUMSTEP:
            return "The line-search step became smaller than lbfgs_parameter_t::min_step.";

        case LBFGSERR_MAXIMUMSTEP:
            return "The line-search step became larger than lbfgs_parameter_t::max_step.";

        case LBFGSERR_MAXIMUMLINESEARCH:
            return "Line search reaches the maximum try number, assumptions not satisfied or precision not achievable.";

        case LBFGSERR_MAXIMUMITERATION:
            return "The algorithm routine reaches the maximum number of iterations.";

        case LBFGSERR_WIDTHTOOSMALL:
            return "Relative search interval width is at least lbfgs_parameter_t::machine_prec.";

        case LBFGSERR_INVALIDPARAMETERS:
            return "A logic error (negative line-search step) occurred.";

        case LBFGSERR_INCREASEGRADIENT:
            return "The current search direction increases the cost function value.";

        default:
            return "(unknown)";
        }
    }

} // namespace lbfgs

#endif

max_stars_repo_name: RENyunfan/GCOPTER

max_issues_repo_name: RENyunfan/GCOPTER

max_forks_repo_name: RENyunfan/GCOPTER


text:
/*******************************************************************************
 * This file is part of KaHyPar.
 *
 * Copyright (C) 2015-2016 Sebastian Schlag <sebastian.schlag@kit.edu>
 *
 * KaHyPar 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.
 *
 * KaHyPar 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 KaHyPar.  If not, see <http://www.gnu.org/licenses/>.
 *
 ******************************************************************************/

#include <boost/program_options.hpp>

#include <iostream>
#include <string>

#include "kahypar/macros.h"
#include "tools/cnf_to_hgr_conversion.h"

namespace po = boost::program_options;

int main(int argc, char* argv[]) {
  using cnfconversion::HypergraphRepresentation;

  std::string cnf_filename;
  std::string hgr_filename;
  HypergraphRepresentation hypergraph_type;

  po::options_description options("Options");
  options.add_options()
    ("formula,f",
    po::value<std::string>(&cnf_filename)->value_name("<string>")->required(),
    "CNF formula filename")
    ("hypergraph,h",
    po::value<std::string>(&hgr_filename)->value_name("<string>"),
    "Hypergraph filename")
    ("representation,r",
    po::value<std::string>()->value_name("<string>")->required()->notifier(
      [&](const std::string& representation) {
    if (representation == "primal") {
      hypergraph_type = HypergraphRepresentation::Primal;
    } else if (representation == "dual") {
      hypergraph_type = HypergraphRepresentation::Dual;
    } else if (representation == "literal") {
      hypergraph_type = HypergraphRepresentation::Literal;
    } else {
      std::cerr << "Hypergraph representation invalid" << std::endl;
      std::exit(-1);
    }
  }),
    "Hypergraph Representation:\n"
    " - primal \n"
    " - dual \n"
    " - literal \n");

  po::variables_map cmd_vm;
  po::store(po::parse_command_line(argc, argv, options), cmd_vm);
  po::notify(cmd_vm);

  if (hgr_filename.empty()) {
    hgr_filename = cnf_filename + "." + toString(hypergraph_type) + ".hgr";
  } else {
    hgr_filename.insert(hgr_filename.find_last_of("."), "." + toString(hypergraph_type));
  }

  std::cout << "Converting SAT instance " << cnf_filename << " to HGR hypergraph format: "
            << hgr_filename << " ..." << std::endl;
  cnfconversion::convertInstance(cnf_filename, hgr_filename, hypergraph_type);
  std::cout << " ... done!" << std::endl;
  return 0;
}

ext: cc

max_stars_repo_name: sjkelly/LSOracle

max_issues_repo_name: sjkelly/LSOracle

max_forks_repo_name: sjkelly/LSOracle


text:
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

#ifndef avro_Layout_hh__
#define avro_Layout_hh__

#include <boost/noncopyable.hpp>
#include "Boost.hh"

/// \file Layout.hh
///

namespace avro {

class Layout : private boost::noncopyable {

  protected:

    Layout(size_t offset = 0) :
        offset_(offset)
    {}

  public:

    size_t offset() const {
        return offset_;
    }

    virtual ~Layout() {}

  private:

    const size_t offset_;
};

class PrimitiveLayout : public Layout {

  public:

    PrimitiveLayout(size_t offset = 0) :
        Layout(offset)
    {}
};

class CompoundLayout : public Layout {

  public:

    CompoundLayout(size_t offset = 0) :
        Layout(offset)
    {}

    void add(Layout *layout) {
        layouts_.push_back(layout);
    }

    const Layout &at (size_t idx) const {
        return layouts_.at(idx);
    }

  private:

    boost::ptr_vector<Layout> layouts_;
};

} // namespace avro

#endif

max_stars_repo_name: SpotifyUsedOpenSourceCode/avro

max_issues_repo_name: SpotifyUsedOpenSourceCode/avro

max_forks_repo_name: SpotifyUsedOpenSourceCode/avro