text:
//---------------------------------Spheral++----------------------------------//
// GeomSymmetricTensor -- the symmetric tensor class
//----------------------------------------------------------------------------//
#include <cmath>
#include <limits>
#include <float.h>
#include <vector>

#include "GeomSymmetricTensor.hh"
#include "EigenStruct.hh"
#include "buildEigenVector.hh"
#include "findEigenValues3.hh"
#include "Utilities/SpheralFunctions.hh"
#include "Utilities/rotationMatrix.hh"

#include "Jacobi2.hh"

#include <Eigen/Dense>

#include <cmath>
using std::min;
using std::max;
using std::abs;

namespace Spheral {

using std::abs;

//------------------------------------------------------------------------------
// Return the eigen values and eigen vectors of a symmetric tensor
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// 3-D.
template<>
EigenStruct<3>
GeomSymmetricTensor<3>::eigenVectors() const {

  // Some useful typedefs.
  typedef GeomVector<3> Vector;
  typedef GeomTensor<3> Tensor;
  typedef GeomSymmetricTensor<3> SymTensor;

  // Tolerances for fuzzy math.
  const double degenerate = 1.0e-20;
  const double tolerance = 5.0e-5;

  // Prepare the result.
  EigenStruct<3> result;

  // Create a scaled version of this tensor, with all elements in the range [-1,1].
  const double fscale = max(10.0*std::numeric_limits<double>::epsilon(), this->maxAbsElement());
  CHECK(fscale > 0.0);
  const double fscalei = 1.0/fscale;
  SymTensor A = (*this)*fscalei;

  // Check for any degenerate elements, and just zero 'em out.
  A.xx(abs(A.xx()) < degenerate ? 0.0 : A.xx());
  A.xy(abs(A.xy()) < degenerate ? 0.0 : A.xy());
  A.xz(abs(A.xz()) < degenerate ? 0.0 : A.xz());
  A.yy(abs(A.yy()) < degenerate ? 0.0 : A.yy());
  A.yz(abs(A.yz()) < degenerate ? 0.0 : A.yz());
  A.zz(abs(A.zz()) < degenerate ? 0.0 : A.zz());

// #ifdef USEJACOBI

//   // Use the Jacobi iterative diagonalization method to determine
//   // the eigen values/vectors.
//   const int nrot = jacobiDiagonalize<Dim<3> >(A,
//                                               result.eigenVectors,
//                                               result.eigenValues);
//   result.eigenValues *= fscale;

// #elif USEEIGEN

  // Use the Eigen library to determine the eigen values/vectors.
  {
    Eigen::Matrix3d B;
    B <<
      A.xx(), A.xy(), A.xz(),
      A.yx(), A.yy(), A.yz(),
      A.zx(), A.zy(), A.zz();
    const Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigensolver(B);
    const Eigen::Vector3d& Bvals = eigensolver.eigenvalues();
    const Eigen::Matrix3d& Bvecs = eigensolver.eigenvectors();
    result.eigenValues = Vector(Bvals(0), Bvals(1), Bvals(2)) * fscale;
    const double x1 = 1.0/std::sqrt(Bvecs(0,0)*Bvecs(0,0) + Bvecs(1,0)*Bvecs(1,0) + Bvecs(2,0)*Bvecs(2,0));
    const double x2 = 1.0/std::sqrt(Bvecs(0,1)*Bvecs(0,1) + Bvecs(1,1)*Bvecs(1,1) + Bvecs(2,1)*Bvecs(2,1));
    const double x3 = 1.0/std::sqrt(Bvecs(0,2)*Bvecs(0,2) + Bvecs(1,2)*Bvecs(1,2) + Bvecs(2,2)*Bvecs(2,2));
    result.eigenVectors = Tensor(Bvecs(0,0)*x1, Bvecs(0,1)*x2, Bvecs(0,2)*x3,
                                 Bvecs(1,0)*x1, Bvecs(1,1)*x2, Bvecs(1,2)*x3,
                                 Bvecs(2,0)*x1, Bvecs(2,1)*x2, Bvecs(2,2)*x3);
  }

// #else

//   // Compute the scaled eigen-values, and sort them.
//   Vector lambdaVec = A.eigenValues();
//   sort(lambdaVec.begin(), lambdaVec.end());
//   CHECK(lambdaVec.x() <= lambdaVec.y() and
//         lambdaVec.y() <= lambdaVec.z());

//   // Assign the true eigen-values in the result.
//   result.eigenValues = fscale*lambdaVec;
//   result.eigenVectors = SymTensor::one;

//   // If any of the eigen-values result in a tensor that is not positive-rank
//   // (all zero elements), we assume the eigen-values are equal and punt
//   // with the identity tensor for the eigen-vectors.
//   // We simultaneously compute the row containing the maximum absolute value
//   // element for each eigen-value.
//   bool punt = false;
//   double maxEVelement = -1.0;
//   Vector maxEVrow;
//   int iFirst = -1;
//   for (int ivalue = 0; ivalue != 3; ++ivalue) {
//     const SymTensor M = A - lambdaVec(ivalue)*SymTensor::one;
//     if (M.maxAbsElement() < degenerate) punt = true;
//     for (int irow = 0; irow != 3; ++irow) {
//       const Vector Mvec = M.getRow(irow);
//       const double thpt = Mvec.maxAbsElement();
//       if (thpt > maxEVelement) {
//         maxEVelement = thpt;
//         maxEVrow = Mvec;
//         iFirst = ivalue;
//       }
//     }
//   }

//   // If we found an all zero M (= A - lambda*I) matrix, we punt and accept the identity
//   // tensor as our eigen-vectors.  Otherwise, continue the compuation.
//   if (!punt) {
//     CHECK(iFirst >= 0 and iFirst < 3);

//     // Select the ordering we'll go through the eigen-values in, starting
//     // with the row with the largest absolute value element.
//     const int iSecond = (iFirst + 1) % 3;
//     const int iThird = (iSecond + 1) % 3;
//     CHECK(iFirst + iSecond + iThird == 3);

//     // We need two orthogonal unit vectors in the plane perpendicular to
//     // the maximum row selected previously.  We can do this by finding the
//     // rotational transformation wherein x' axis is aligned with this row, and
//     // taking our two vectors as the other two rows of this transform.
//     const Vector R = maxEVrow.unitVector();
//     const Tensor Tr = rotationMatrix(R);
//     const Vector U0 = Tr.getRow(1);
//     const Vector U1 = Tr.getRow(2);

//     // Now we can compute the eigen-vector corresponding the first eigen-value
//     // selected previously.
//     const Vector V0 = buildUniqueEigenVector(A,
//                                              lambdaVec(iFirst),
//                                              U0,
//                                              U1);
//     result.eigenVectors.setColumn(iFirst, V0);

//     // Now we know the remaining eigen-vectors are in the plane perpendicular to
//     // V0.  We know R is in that plane, and so is R x V0.  With that knowledge
//     // we can basically repeat the same procedure for the next eigen-vector.
//     Vector S = R.cross(V0);
//     CHECK(fuzzyEqual(S.magnitude2(), 1.0, tolerance));
//     const Vector V1 = buildUniqueEigenVector(A,
//                                              lambdaVec(iSecond),
//                                              R,
//                                              S);
//     result.eigenVectors.setColumn(iSecond, V1);

//     // The last eigen-vector is orthogonal to the first two, so we can find it
//     // simply by taking the cross-product of the previous eigen-vectors.
//     const Vector V2 = V0.cross(V1);
//     CHECK(fuzzyEqual(V2.magnitude2(), 1.0, tolerance));
//     CHECK(fuzzyEqual(((A - lambdaVec(iThird)*SymTensor::one)*V2).maxAbsElement(), 0.0, tolerance));
//     result.eigenVectors.setColumn(iThird, V2);
//   }

// #endif

  BEGIN_CONTRACT_SCOPE
  // Check the result.
  const double lambda1 = result.eigenValues.x();
  const double lambda2 = result.eigenValues.y();
  const double lambda3 = result.eigenValues.z();
  const Vector v1 = result.eigenVectors.getColumn(0);
  const Vector v2 = result.eigenVectors.getColumn(1);
  const Vector v3 = result.eigenVectors.getColumn(2);
  ENSURE2(fuzzyEqual(v1.dot(v2), 0.0, tolerance) and
          fuzzyEqual(v1.dot(v3), 0.0, tolerance) and
          fuzzyEqual(v2.dot(v3), 0.0, tolerance),
          v1 << " " << v2 << " " << v3 << " : " << *this);
  ENSURE2(fuzzyEqual(v1.magnitude2(), 1.0, tolerance) and
          fuzzyEqual(v2.magnitude2(), 1.0, tolerance) and
          fuzzyEqual(v3.magnitude2(), 1.0, tolerance),
          v1 << " " << v2 << " " << v3);
  const double tol = tolerance*max(1.0, this->maxAbsElement());
  ENSURE2(fuzzyEqual((SymTensor(xx() - lambda1, xy(), xz(),
                                yx(), yy() - lambda1, yz(),
                                zx(), zy(), zz() - lambda1)*v1).maxAbsElement(), 0.0, tol),
          *this << " " << A << " " << lambda1 << " " << v1 << " " << tol << " "
          << SymTensor(xx() - lambda1, xy(), xz(),
                       yx(), yy() - lambda1, yz(),
                       zx(), zy(), zz() - lambda1)*v1);
  ENSURE(fuzzyEqual((SymTensor(xx() - lambda2, xy(), xz(),
                               yx(), yy() - lambda2, yz(),
                               zx(), zy(), zz() - lambda2)*v2).maxAbsElement(), 0.0, tol));
  ENSURE(fuzzyEqual((SymTensor(xx() - lambda3, xy(), xz(),
                               yx(), yy() - lambda3, yz(),
                               zx(), zy(), zz() - lambda3)*v3).maxAbsElement(), 0.0, tol));
  ENSURE(fuzzyEqual(abs(result.eigenVectors.Determinant()), 1.0, tolerance));
  END_CONTRACT_SCOPE

  return result;
}

//------------------------------------------------------------------------------
// Explicit instantiation.
//------------------------------------------------------------------------------
template class GeomSymmetricTensor<1>;
template class GeomSymmetricTensor<2>;
template class GeomSymmetricTensor<3>;

//------------------------------------------------------------------------------
// Set the static variables.
//------------------------------------------------------------------------------
template<> const unsigned GeomSymmetricTensor<1>::nDimensions = 1;
template<> const unsigned GeomSymmetricTensor<1>::numElements = 1;
template<> const GeomSymmetricTensor<1> GeomSymmetricTensor<1>::zero = GeomSymmetricTensor<1>(0.0);
template<> const GeomSymmetricTensor<1> GeomSymmetricTensor<1>::one = GeomSymmetricTensor<1>(1.0);

template<> const unsigned GeomSymmetricTensor<2>::nDimensions = 2;
template<> const unsigned GeomSymmetricTensor<2>::numElements = 3;
template<> const GeomSymmetricTensor<2> GeomSymmetricTensor<2>::zero = GeomSymmetricTensor<2>(0.0, 0.0,
                                                                                0.0, 0.0);
template<> const GeomSymmetricTensor<2> GeomSymmetricTensor<2>::one = GeomSymmetricTensor<2>(1.0, 0.0,
                                                                                0.0, 1.0);

template<> const unsigned GeomSymmetricTensor<3>::nDimensions = 3;
template<> const unsigned GeomSymmetricTensor<3>::numElements = 6;
template<> const GeomSymmetricTensor<3> GeomSymmetricTensor<3>::zero = GeomSymmetricTensor<3>(0.0, 0.0, 0.0,
                                                                                0.0, 0.0, 0.0,
                                                                                0.0, 0.0, 0.0);
template<> const GeomSymmetricTensor<3> GeomSymmetricTensor<3>::one = GeomSymmetricTensor<3>(1.0, 0.0, 0.0,
                                                                                0.0, 1.0, 0.0,
                                                                                0.0, 0.0, 1.0);

template<> const double GeomSymmetricTensor<1>::onethird = 1.0/3.0;
template<> const double GeomSymmetricTensor<2>::onethird = 1.0/3.0;
template<> const double GeomSymmetricTensor<3>::onethird = 1.0/3.0;

template<> const double GeomSymmetricTensor<1>::sqrt3 = std::sqrt(3.0);
template<> const double GeomSymmetricTensor<2>::sqrt3 = std::sqrt(3.0);
template<> const double GeomSymmetricTensor<3>::sqrt3 = std::sqrt(3.0);

}

max_stars_repo_name: markguozhiming/spheral

max_stars_repo_licenses: BSD-Source-Code BSD-3-Clause-LBNL FSFAP

max_issues_repo_name: markguozhiming/spheral

max_issues_repo_licenses: BSD-Source-Code BSD-3-Clause-LBNL FSFAP

max_forks_repo_name: markguozhiming/spheral

max_forks_repo_licenses: BSD-Source-Code BSD-3-Clause-LBNL FSFAP


text:
#pragma once
#include "EnvironmentWatcher.hpp"
#include "PreviewData.hpp"
#include <memory>
#include <map>
#include <string>
#include <boost/filesystem.hpp>

using std::string;

namespace fs = boost::filesystem;

namespace RC2 {
	typedef std::map<long, std::shared_ptr<EnvironmentWatcher>> EnvironmentMap;
	typedef std::map<int, std::unique_ptr<PreviewData>> PreviewMap;

	enum PdfStatus { successPdfStatus, killedPdfStatus, otherPdfStatus };

	struct ExecCompleteArgs {
		RSession *session;
		JsonCommand command;
		FileInfo finfo;
		int queryId;
		//object ptr points to does not have to exist past this call. just to allow null value
		ExecCompleteArgs(RSession *inSession, JsonCommand inCommand, int inQueryId, FileInfo *info)
		: session(inSession), command(inCommand), finfo(info), queryId(inQueryId)
		{}
	};

	struct DelayCommandArgs {
		RSession *session;
		string json;
		DelayCommandArgs(RC2::RSession *inSession, string inJson)
		: session(inSession), json(inJson)
		{}
	};

	struct BoolResetter {
		BoolResetter(bool *ptr, bool valueToSet) { _ptr = ptr; _valToSet = valueToSet; *_ptr = valueToSet; }
		~BoolResetter() { *_ptr = !_valToSet; }
	private:
		bool *_ptr;
		bool _valToSet;
	};

	struct SweavePdfData {
		JsonCommand command;
		RSession *session;
		pid_t pid;
		fs::path srcPath;
		fs::path scratchPath;
		string baseName;
		int queryId;
		PdfStatus pstatus = successPdfStatus;
		SweavePdfData (JsonCommand cmd, RSession *s, pid_t p, fs::path spath, fs::path tpath, string name, int qid = 0)
		: command(cmd), session(s), pid(p), srcPath(spath), scratchPath(tpath), baseName(name), queryId(qid)
		{};
	};

} // namespace

inline bool stringHasPrefix(string str, const char* prefix) {
	return strncmp(str.c_str(), prefix, strlen(prefix)) == 0;
}

inline double currentFractionalSeconds() {
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return tv.tv_sec + (round(tv.tv_usec/1000.0)/1000.0);
}

enum KnitExceptionCode { none, forkError=100, execvError, pathError, pdfError, errorInLogFile, unknownError };

inline int clientErrorForKnitExceptionCode(KnitExceptionCode code) {
	switch (code) {
		case forkError:
		case execvError:
		case pathError:
		case pdfError:
			return kError_SweaveError;
		case errorInLogFile:
			return kError_SweaveErrorInLogFile;
		case unknownError:
		default:
			return kError_Unknown;
	}
}

ext: hpp


text:
#include <boost/algorithm/string.hpp>

#include "cPackEngine.h"

struct item_build_instructions
{
    string id;
    vector<string> size_v;
    string dimension_units;
    int constraints;
    float weight;
};

int   cPackEngine::Build(
    const char* bin_input_description,
    const char* item_input_description )
{
    Clear();
    vector<string> bin_v;
    boost::split(bin_v, bin_input_description, boost::is_any_of(","));
    vector<string> item_v;
    boost::split(item_v, item_input_description, boost::is_any_of(","));

    int error = BuildBins( bin_v );
    if ( error )
    {
        return error;
    }

    return BuildItems( item_v );
}

void cPackEngine::Clear()
{
    Bins.clear();
    Items.clear();
    myUnpackedItems.clear();
    Dimension = 0;
}

void cPackEngine::Pack()
{
    if( Dimension == 2 )
    {
        BoxPacker2D packer;
        packer.packThem( Bins, Items );
    }

    else if( Dimension == 3 )
    {
        /*
        Save the bins
        in case we need to try again with the original list
        */
        BinsOriginal = Bins;

        bool fOneBin_saved = myfOneBin;
        bool packOK = false;

        if( ! myfOneBin )
        {
            // the one bin option was not selected
            // but lets try packing just one bin anyway
            myfOneBin = true;
        }
        /*
            if one bin is requested
            there is no need to look at bins that are too small to hold every item
        */
        RemoveBinsTooSmallForAllItems();

        /*
          need not look at bins that are not strong enough
          to hold the weight of all the items
        */
        RemoveBinsTooLightForAllItems();

        /*
          check that requested one bin pack is feasible
        */
        if( ( ! Bins.size() ) && fOneBin_saved )
        {
            myError = "No bin capable of holding all items";

            // Do the best we can
            // by packing as much as possible into the largest bin
            Bins = BinsOriginal;
            RemoveAllButLargestBin();
        }

        if( Bins.size() )
        {

            // sort bins into increasing size
            sort( Bins.begin(), Bins.end(),
                  []( bin_t a, bin_t b )
            {
                return a->volume() < b->volume();
            });

            bin_v_t Bins_saved( Bins );

            if( myfOneBin )
            {
                // try smallest
                bin_t smallest_bin = Bins[0];
                Bins.clear();
                Bins.push_back( smallest_bin );
            }
            else
            {
                bin_t smallest_bin = SmallestBinForAllItems();
                Bins.clear();
                Bins.push_back( smallest_bin );
            }

            /*
                Pack
            */
            BoxPacker3D packer;
            packer.packThem( Bins, Items );

            while ( myUnpackedItems.size() )
            {
                // there were some unpacked items

                if( Bins_saved.size() <= 1 )
                    break;

                /*
                    try again with saved bins
                    without the smallest
                */
                myUnpackedItems.clear();
                Bins = Bins_saved;

                // reset items to unpacked status
                for( auto i : Items )
                    i->setBin( -1 );

                RemoveSmallestBin();
                Bins_saved = Bins;
                bin_t smallest_bin = Bins[0];
                Bins.clear();
                Bins.push_back( smallest_bin );

                packer.packThem( Bins, Items );

            }
            Bins[0]->Ground();
            Bins[0]->Support();

            if( ! myUnpackedItems.size() )
                packOK = true;
        }

        if( ( ! packOK ) && ( ! fOneBin_saved ) )
        {

            // one bin packing failed
            // but it was not explicitly requested
            // so try packing into multiple bins
            //cout << "Trying multiple bins\n";
            myfOneBin = false;
            Bins = BinsOriginal;
            myUnpackedItems.clear();
            // reset items to unpacked status
            for( auto i : Items )
                i->setBin( -1 );

            BoxPacker3D packer;
            packer.packThem( Bins, Items );

            // Slide unsupported bins downwards
            for( auto b : Bins )
                b->Ground();
        }
    }

    // delete unused  bins

    Bins.erase(
        remove_if(
            Bins.begin(),
            Bins.end(),
            [ ] ( bin_t b )
    {
        return b->itemsInBinCount() == 0 ;
    } ),
    Bins.end() );
}

string cPackEngine::getJson()
{
    stringstream jsonStr;
    if( myError.length() )
    {
        jsonStr << "{\"error\":\"" << myError << "\",\n";
    }
    else
    {
        jsonStr << "{";
    }
    jsonStr << "\"packed\":[";
    for( unsigned i=0; i < Bins.size(); ++i )
    {
        Bins[i]->encodeAsJSON(jsonStr, false);
        if ( i != Bins.size() - 1)
            jsonStr << ",";
    }

    jsonStr << "],\n";

    jsonStr << "\"unpacked\":[\n";
    bool first = true;
    for( auto unpacked_item : myUnpackedItems )
    {
        if( ! first )
            jsonStr << ",";
        first = false;
        unpacked_item->encodeAsJSON( jsonStr );
    }
    jsonStr << "]}";

    string json = jsonStr.str();

    char *s_buffer =  new char[json.size()+1];
    copy(json.begin(), json.end(), s_buffer);
    s_buffer[json.size()] = '\0';

//    for( auto i : Items )
//    {
//        i->Print();
//    }

    return string( s_buffer );
}

string cPackEngine::getCutList()
{
    string sl;
    for( auto b : Bins )
    {
        cCutList L;
        b->AddToCutList( L );
        L.set( b );
        sl += L.get();
    }

    return sl;
}

string cPackEngine::DrawList()
{
    stringstream ss;
    for( auto b : Bins )
    {
        b->DrawList( ss );
    }
    return ss.str();
}

string cPackEngine::Unpacked()
{
    string s;
    for( auto i : myUnpackedItems )
        s += i->id() + ",";
    return s;
}

string cPackEngine::getCSV()
{
    stringstream ss;

    for( auto& b : Bins )
    {
        ss << b->getCSV();
    }
    return ss.str();
}

void cPackEngine::getSTL()
{
    if( myfRandom )
        return;

    string s;
    int offset = 0;
    for( auto& b : Bins )
    {
        s += b->getSTL( offset );
        offset += b->side_1()->size() * 1.5;
    }

    ofstream filestl("packit4me2.stl");
    filestl << s;
    filestl.close();
}

int cPackEngine::BuildBins( vector<string>& bin_v )
{

    for(unsigned i= 0; i < bin_v.size(); i++)
    {
        string bin_str = bin_v[i];
        vector<string> id_bin;
        boost::split(id_bin, bin_str, boost::is_any_of(":"));

        const int expected_field_count = 5;

        if( id_bin.size() != expected_field_count )
        {
            throw std::runtime_error("Unexpected bin field count");
        }
        Bin::bin_build_instructions instructions;
        instructions.bin_id = id_bin[0];
        instructions.dimension_units = id_bin[1];
        int quantity = (int) atof( id_bin[2].c_str() );
        if( quantity == -1 )
            instructions.can_copy = true;
        else
            instructions.can_copy = false;
        string bin_size = id_bin[3];
        instructions.maxWeight = atof( id_bin[4].c_str() );

        id_bin.clear();

        vector<string> bin_size_v;
        boost::split(bin_size_v, bin_size, boost::is_any_of("x"));

        if ( isDimError( (int)bin_size_v.size() ) == true )
        {
            return 2;
        }

        instructions.size_v = bin_size_v;

        // Build the bin and store it
        if( quantity <= 0 )
            quantity = 1;

        for( int k = 0; k < quantity; k++ )
        {
            Bins.push_back( bin_t( Bin::Build ( instructions ) ) );
        }

    }
    return 0;
}
int cPackEngine::BuildItems( vector<string>& item_v )
{
    //cout << "Building " << item_v.size() << " items" << "\n";

    for(unsigned i= 0; i < item_v.size(); i++)
    {
        item_build_instructions instructions;
        string item_str = item_v[i];
        vector<string> id_item;
        boost::split(id_item, item_str, boost::is_any_of(":"));

        const int expected_field_count = 6;

        if( id_item.size() < expected_field_count || id_item.size() > expected_field_count )
        {
            throw std::runtime_error("Unexpected item field count "+item_str);
        }

        //string item_id = id_item[0];
        instructions.id = id_item[0];
        instructions.dimension_units = id_item[1];
        instructions.constraints = (int) atof( id_item[2].c_str() );
        int quantity = (int) atof( id_item[3].c_str() );
        string item_size = id_item[4];
        instructions.weight = atof( id_item[5].c_str() );

        id_item.clear();

        vector<string> item_size_v;
        boost::split(item_size_v, item_size, boost::is_any_of("x"));

        if ( isDimError( (int)item_size_v.size() ) == true )
        {
            return 2;
        }

        instructions.size_v =  item_size_v;

        for( int k = 0; k < quantity; k++ )
        {
            Items.push_back( item_t( Item::Build( instructions  ) ) );
        }
    }
    return 0;
}
bool cPackEngine::isDimError( int dim )
{
    if ( dim < 2 || dim > 3 )
        return true;

    if( Dimension == 0)
    {
        Dimension = dim;
        return false;
    }
    else
    {
        if ( Dimension != dim )
            return true;
        else
            return false;
    }
}

/**
cPackEngine
  Scale according to input dimension units into inches

	param[in] unit_string  The dimensional unit string input e.g. ft, in

	@return Scale required, 1.0 if not recognized

*/
float cPackEngine::DimensionUnitScale( const string& unit_string )
{
    if ( unit_string == "ft" )
    {
        return 12.0f;
    }
    else if ( unit_string == "mm" )
    {
        return  0.0393701f;
    }
    else if ( unit_string == "cm" )
    {
        return 0.393701f;
    }
    else if ( unit_string == "m" )
    {
        return 39.3701f;
    }
    return 1.0f;
}

void cPackEngine::RemoveBinsTooSmallForAllItems()
{
    // check that this is wanted
    if( ! myfOneBin )
        return;

    // calculate total volume of all items
    double totalVolumeAllItems = 0;
    for( auto& i : Items )
    {
        totalVolumeAllItems += i->volume();
    }

    // remove bins that are too small
    Bins.erase(
        remove_if(
            Bins.begin(),
            Bins.end(),
            [ totalVolumeAllItems ] ( bin_t b )
    {
        return b->volume() < totalVolumeAllItems;
    } ),
    Bins.end() );

}

bin_t cPackEngine::SmallestBinForAllItems()
{
    // calculate total volume of all items
    double totalVolumeAllItems = 0;
    double totalWeightAllItems = 0;
    for( auto& i : Items )
    {
        totalVolumeAllItems += i->volume();
        totalWeightAllItems += i->Weight();
    }
    for( auto b : Bins )
    {
        if( b->volume() >= totalVolumeAllItems &&
                b->MaxWeight() >= totalWeightAllItems )
            return b;
    }
    return Bins.back();
}

void cPackEngine::RemoveBinsTooLightForAllItems()
{
    // check that this is wanted
    if( ! myfOneBin )
        return;

    // calculate total weight of all items
    double totalWeightAllItems = 0;
    for( auto& i : Items )
    {
        totalWeightAllItems += i->Weight();
    }

    // remove bins that cannot carry the total weight
    Bins.erase(
        remove_if(
            Bins.begin(),
            Bins.end(),
            [ totalWeightAllItems ] ( bin_t b )
    {
        return b->MaxWeight() < totalWeightAllItems;
    } ),
    Bins.end() );

}

void cPackEngine::RemoveSmallestBin()
{
    if( Bins.size() <= 1 )
    {
        throw std::runtime_error("No bins big enough to contain all items");
    }

    sort(Bins.begin(), Bins.end(), Utils::compareAscShape);

    Bins.erase( Bins.begin() );
}

void cPackEngine::RemoveAllButLargestBin()
{
    if( Bins.size() <= 1 )
        return;
    sort( Bins.begin(), Bins.end(), Utils::compareAscShape);
    auto iter_last_but_one = Bins.end();
    iter_last_but_one--;
    iter_last_but_one--;
    Bins.erase( Bins.begin(), iter_last_but_one );
}

int cPackEngine::CountBinsUsed()
{
    int count = 0;
    for( auto b : Bins )
    {
        if( b->itemsInBinCount() )
            count++;
    }
    return count;
}

void cPackEngine::PrintAllBins()
{
    if( ! Bins.size() )
    {
        cout << "the world has zero bins!\n";
        return;
    }
    cout << "All " << Bins.size() << " Bins\n";
    for( auto b : Bins )
    {
        cout << "Bin " << b->id() <<" contains " << b->itemsInBinCount() << "\n";
    }
    cout << "===All Bins\n";
}

Bin* Bin::Build(  bin_build_instructions& instructions )
{
    Bin *bin;
    switch( instructions.size_v.size() )
    {
    case 1:
        bin = new Bin1D();
        bin->set_id( instructions.bin_id );
        bin->set_side_1( new Side(atof(instructions.size_v[0].c_str()), 'w') );
        bin->set_side_2( new Side(atof(instructions.size_v[1].c_str()), 'h') );

        break;

    case 2:
        bin = new Bin2D();
        bin->set_id( instructions.bin_id );
        bin->set_side_1( new Side(atof(instructions.size_v[0].c_str()), 'w') );
        bin->set_side_2( new Side(atof(instructions.size_v[1].c_str()), 'h') );

        break;

    case 3:
        bin = new Bin3D();
        bin->set_id( instructions.bin_id );
        bin->set_side_1( new Side(atof(instructions.size_v[0].c_str()), 'w') );
        bin->set_side_2( new Side(atof(instructions.size_v[1].c_str()), 'h') );
        bin->set_side_3( new Side(atof(instructions.size_v[2].c_str()), 'l') );

        break;

    default:
        break;

    }

    // Convert from input dimensional units
    // to internal units, assumed to be inches ( the default )

    bin->ScaleSize( cPackEngine::DimensionUnitScale( instructions.dimension_units ) );

    bin->setCanCopy( instructions.can_copy );

    bin->MaxWeight( instructions.maxWeight );

    return bin;

}

Item* Item::Build(  item_build_instructions& instructions )
{
    Item* item;

    switch( instructions.size_v.size() )
    {
    case 1:
        item = new Item2D();

        item->set_id( instructions.id );
        item->set_side_1( new Side( atof(instructions.size_v[0].c_str()), 'w' ) );
        item->set_side_2( new Side( atof(instructions.size_v[1].c_str()), 'h' ) );
        break;

    case 2:
        item = new Item2D();
        item->set_id( instructions.id );
        item->set_side_1( new Side( atof(instructions.size_v[0].c_str()), 'w' ) );
        item->set_side_2( new Side( atof(instructions.size_v[1].c_str()), 'h' ) );
        break;

    case 3:
        item = new Item3D();
        item->set_id( instructions.id );
        item->set_side_1( new Side( atof(instructions.size_v[0].c_str()), 'w' ));
        item->set_side_2( new Side( atof(instructions.size_v[1].c_str()), 'h'  ) );
        item->set_side_3( new Side( atof(instructions.size_v[2].c_str()), 'l'  ) );
        break;

    default:
        break;

    }

    item->set_constraints( instructions.constraints );

    item->ScaleSize( cPackEngine::DimensionUnitScale( instructions.dimension_units ) );

    item->Weight( instructions.weight );

    return item;
}

namespace pack {
void RemoveUnusedBins( cPackEngine& packer )
{
    bin_v_t& bins = packer.bins();
    bins.erase(
        remove_if(
            bins.begin(),
            bins.end(),
            [ ] ( bin_t b )
    {
        if( (int)b->id().find("_cpy") != -1 )
        {
            // generated duplicate bin
            if( ! b->itemsInBinCount() )
                // contains no items
                return true;
        }
        return false;
    } ),
    bins.end() );
}
}

ext: cpp

max_stars_repo_name: JamesBremner/Pack

max_issues_repo_name: JamesBremner/Pack

max_forks_repo_name: JamesBremner/Pack


text:
/**
 * @file BoostFilesystem.hpp
 *
 * @copyright Copyright (c) 2020 Innovatrics s.r.o. All rights reserved.
 *
 * @maintainer Tomas Krupa <tomas.krupa@innovatrics.com>
 * @created 10.08.2020
 *
 */

#pragma once

#include "BoostMMFile.hpp"

#include <boost/filesystem.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
#include <memory>

#include "Directory.hpp"
#include "File.hpp"
#include "Filesystem.hpp"

#ifdef _WIN32
#undef createDirectory
#endif

/**
 * @brief BoostFilesystem
 *
 * Defines basic BoostFilesystem operations.
 */
template<class TDirectory, class TDerivedFile>
class BoostFilesystem final
  : public File<BoostFilesystem<TDirectory, TDerivedFile>>
{
public:
  std::unique_ptr<TDerivedFile> createInputFile(const std::string& path) const
  {
    namespace io = boost::iostreams;

    return std::make_unique<TDerivedFile>(
      path, (int)io::mapped_file_base::mapmode::readonly);
  }

  std::unique_ptr<TDerivedFile> createOutputFile(const std::string& path,
                                                 filesystem::WriteMode mode) const
  {
    std::ios_base::openmode openMode(std::ios::out | std::ios::binary);

    auto addWriteMode = [](bool flag,
                           int positive,
                           int negative) { // no jump condition by alexandrescu
      return static_cast<std::ios::openmode>(
        (flag & static_cast<unsigned>(positive)) |
        (flag & static_cast<unsigned>(negative)));
    };

    openMode |= addWriteMode(
      mode == filesystem::WriteMode::Truncate, std::ios::trunc, std::ios::app);

    namespace io = boost::iostreams;

    return std::make_unique<TDerivedFile>(
      path, (int)io::mapped_file_base::mapmode::readwrite);
  }

  std::unique_ptr<TDirectory> createDirectory(const std::string& path) const
  {
    namespace fs = boost::filesystem;
    if (fs::create_directory(path)) {
      return std::make_unique<TDirectory>(path);
    }
    return nullptr;
  }

  bool exists(const std::string& path) const
  {
    return boost::filesystem::exists(path);
  }

  BoostFilesystem() = default;

  ~BoostFilesystem() = default;

  BoostFilesystem(const BoostFilesystem&) = delete;

  BoostFilesystem(BoostFilesystem&&) = delete;

  BoostFilesystem& operator=(const BoostFilesystem&) = delete;

  BoostFilesystem& operator=(BoostFilesystem&&) = delete;

private:
};


text:
//          Copyright Gavin Band 2008 - 2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#include <string>
#include <boost/signals2/signal.hpp>
#include <boost/function.hpp>
#include <boost/tuple/tuple.hpp>

#include "genfile/SNPDataSourceProcessor.hpp"
#include "genfile/VariantIdentifyingData.hpp"
#include "genfile/VariantEntry.hpp"
#include "genfile/Error.hpp"
#include "genfile/SNPDataSink.hpp"
#include "genfile/get_set_eigen.hpp"
#include "genfile/vcf/get_set_eigen.hpp"

#include "statfile/BuiltInTypeStatSink.hpp"

#include "db/Connection.hpp"
#include "db/SQLStatement.hpp"
#include "qcdb/FlatFileOutputter.hpp"

#include "components/SNPSummaryComponent/PairwiseCallComparer.hpp"
#include "components/SNPSummaryComponent/PairwiseCallComparerManager.hpp"
#include "components/SNPSummaryComponent/CallComparerComponent.hpp"
#include "components/SNPSummaryComponent/FrequentistTestCallMerger.hpp"
#include "components/SNPSummaryComponent/LeastMissingConsensusCaller.hpp"

CallComparerProcessor::UniquePtr CallComparerProcessor::create( PairwiseCallComparerManager::UniquePtr comparer, std::vector< std::string > const& call_fields ) {
	UniquePtr result(
		new CallComparerProcessor( comparer, call_fields )
	) ;
	return result ;
}

CallComparerProcessor::CallComparerProcessor( PairwiseCallComparerManager::UniquePtr call_comparer, std::vector< std::string > const& call_fields  ):
	m_call_comparer( call_comparer ),
	m_call_fields( call_fields ),
	m_begun( false )
{}

void CallComparerProcessor::operator()(
	VariantIdentifyingData const& snp,
	Genotypes const& genotypes,
	Ploidy const&,
	genfile::VariantDataReader& data_reader,
	ResultCallback callback
) {
	if( !m_begun ) {
		m_call_comparer->begin_processing_snps( genotypes.rows() ) ;
		m_begun = true ;
	}

	// Add all the calls to the call comparer.
	m_call_comparer->begin_processing_snp( snp ) ;
	for( std::size_t i = 0; i < m_call_fields.size(); ++i ) {
		genfile::vcf::GenotypeSetter< Eigen::MatrixBase< Eigen::MatrixXd > > setter( m_calls ) ;
		data_reader.get( m_call_fields[i], setter ) ;
		m_call_comparer->add_calls( m_call_fields[i], m_calls ) ;
	}
	m_call_comparer->end_processing_snp() ;
}

std::string CallComparerProcessor::get_summary( std::string const& prefix, std::size_t column_width ) const {
	return prefix + "CallComparerProcessor" ;
}

void CallComparerComponent::declare_options( appcontext::OptionProcessor& options ) {
	options.declare_group( "Call comparison options" ) ;
	options[ "-compare-calls" ]
		.set_description( "Compare genotype calls from the given fields of a VCF or other file. "
		 	"The value should be a comma-separated list of genotype call fields in the data.")
		.set_takes_values_until_next_option() ;
	options[ "-tabulate-call-comparison" ]
		.set_description( "Specify that a table of counts should be output for each pair of callsets at each SNP" ) ;
	options[ "-consensus-call" ]
		.set_description( "Combine calls from several different genotypers into a single consensus callset. "
			"The calls to use are specified using the -compare-calls option. "
			"A consensus call at each SNP is made when no significant difference is found "
			"between N-1 of the N callsets." )
		.set_takes_single_value()
		.set_default_value( "call-comparisons.vcf" ) ;

	options[ "-comparison-model" ]
		.set_description( "Set the model used for call comparison.  Currently this must be \"GenotypeFrequencyTest\". or \"AcceptAll\"." )
		.set_takes_single_value()
		.set_default_value( "GenotypeFrequencyTest" ) ;

	options[ "-consensus-model" ]
		.set_description( "Model used to combine calls in the consensus set of calls. "
		 	"Currently this can be \"LeastMissing\" or \"QuangStyle\"." )
		.set_takes_single_value()
		.set_default_value( "LeastMissing" ) ;
	options[ "-consensus-call-pvalue-threshold" ]
		.set_description( "Treat calls in call comparison treated as distinct if the p-value of an association test between them "
			"is less than or equal to this value." )
		.set_takes_single_value()
		.set_default_value( 0.001 ) ;

	options.option_implies_option( "-consensus-call", "-s" ) ;
	options.option_implies_option( "-compare-calls", "-s" ) ;
	options.option_implies_option( "-tabulate-call-comparison", "-compare-calls" ) ;
	options.option_implies_option( "-consensus-call", "-compare-calls" ) ;
	options.option_implies_option( "-consensus-call-pvalue-threshold", "-compare-calls" ) ;
}

CallComparerComponent::UniquePtr CallComparerComponent::create(
	genfile::CohortIndividualSource const& samples,
	appcontext::OptionProcessor const& options,
	appcontext::UIContext& ui_context
) {
	CallComparerComponent::UniquePtr result(
		new CallComparerComponent( samples, options, ui_context )
	) ;
	return result ;
}

CallComparerComponent::CallComparerComponent(
	genfile::CohortIndividualSource const& samples,
	appcontext::OptionProcessor const& options,
	appcontext::UIContext&
):
	m_samples( samples ),
	m_options( options )
{}

namespace {
	genfile::VariantEntry get_sample_entry( genfile::CohortIndividualSource const& samples, std::string const& name, std::size_t i ) {
		return samples.get_entry( i, name ) ;
	}

	void send_results_to_sink(
		genfile::SNPDataSink::SharedPtr sink,
		genfile::VariantIdentifyingData const& snp,
		Eigen::MatrixXd const& genotypes,
		std::map< std::string, std::vector< genfile::VariantEntry > > const& info
	) {
		sink->write_snp(
			genotypes.rows(),
			snp,
			genfile::GenotypeGetter< Eigen::MatrixXd >( genotypes, 0ul ),
			genfile::GenotypeGetter< Eigen::MatrixXd >( genotypes, 1ul ),
			genfile::GenotypeGetter< Eigen::MatrixXd >( genotypes, 2ul ),
			info
		) ;
	}
}

namespace {
	// Adapter to adapt SNPSummaryComponent outputters to be used here.
	struct SNPSummaryOutputter: public PairwiseCallComparerManager::ComparisonClient {
	public:
		static UniquePtr create( qcdb::Storage::SharedPtr outputter ) {
			return UniquePtr( new SNPSummaryOutputter( outputter ) ) ;
		}

		static SharedPtr create_shared( qcdb::Storage::SharedPtr outputter ) {
			return SharedPtr( new SNPSummaryOutputter( outputter ) ) ;
		}

	public:
		SNPSummaryOutputter( qcdb::Storage::SharedPtr outputter ):
			m_outputter( outputter )
		{}

		void begin_comparisons( genfile::VariantIdentifyingData const& snp ) {
			m_snp = snp ;
		} ;

		void end_comparisons() {}

		void set_result(
			std::string const& first_callset,
			std::string const& second_callset,
			std::string const& comparison,
			std::string const& variable,
			genfile::VariantEntry const& value
		) {
			m_outputter->store_per_variant_data(
				m_snp,
				comparison + ":" + first_callset + "/" + second_callset + ":" + variable,
				value
			) ;
		}

	private:
		qcdb::Storage::SharedPtr m_outputter ;
		genfile::VariantIdentifyingData m_snp ;
	} ;
}

void CallComparerComponent::setup( SNPSummaryComputationManager& snp_summary_component_manager, qcdb::Storage::SharedPtr storage ) const {
	PairwiseCallComparerManager::UniquePtr manager( PairwiseCallComparerManager::create().release() ) ;

	SNPSummaryOutputter::SharedPtr snp_outputter = SNPSummaryOutputter::create_shared(
		storage
	) ;

	manager->send_comparisons_to( snp_outputter ) ;

	std::string const comparison_model = m_options.get< std::string >( "-comparison-model" ) ;
	if( comparison_model != "AcceptAll" ) {
		manager->add_comparer( comparison_model, PairwiseCallComparer::create( comparison_model ) ) ;
	}
	if( m_options.check( "-tabulate-call-comparison" )) {
		manager->add_comparer( "GenotypeTabulatingCallComparer", PairwiseCallComparer::create( "GenotypeTabulatingCallComparer" ) ) ;
	}

	manager->set_merger( PairwiseCallComparerManager::Merger::create( comparison_model, m_options ) ) ;

	if( m_options.check( "-consensus-call" )) {
		ConsensusCaller::SharedPtr consensus_caller ;
		{
			genfile::SNPDataSink::SharedPtr sink(
				genfile::SNPDataSink::create(
					m_options.get< std::string >( "-consensus-call" )
				).release()
			) ;
			sink->set_sample_names(
				m_samples.get_number_of_individuals(),
				boost::bind( get_sample_entry, boost::ref( m_samples ), "ID_1", _1 )
			) ;
			consensus_caller = ConsensusCaller::create_shared( m_options.get< std::string >( "-consensus-model" ) ) ;
			consensus_caller->send_results_to(
				boost::bind(
					&send_results_to_sink,
					sink,
					_1,
					_2,
					_3
				)
			) ;
		}
		manager->send_merge_to( consensus_caller ) ;
	}

	CallComparerProcessor::UniquePtr ccc = CallComparerProcessor::create(
		manager,
		m_options.get_values< std::string >( "-compare-calls" )
	) ;

	snp_summary_component_manager.add_computation(
		"call_comparison",
		SNPSummaryComputation::UniquePtr( ccc.release() )
	) ;
}

max_stars_repo_name: CreRecombinase/qctool

max_issues_repo_name: CreRecombinase/qctool

max_forks_repo_name: CreRecombinase/qctool


text:
#ifndef MATRIX2D_TPP
#define MATRIX2D_TPP

#include "matrix2d/matrix2d.hpp"

#include <boost/iterator/iterator_facade.hpp>

#include <range/v3/action/join.hpp>
#include <range/v3/algorithm/max.hpp>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/all.hpp>
#include <range/v3/view/cache1.hpp>
#include <range/v3/view/intersperse.hpp>
#include <range/v3/view/join.hpp>
#include <range/v3/view/transform.hpp>

#include <fmt/format.h>
#include <fmt/ostream.h>
#include <fmt/ranges.h>

#include <algorithm>
#include <cstddef>
#include <iterator>
#include <ostream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

// https://github.com/fmtlib/fmt/issues/751
// https://github.com/fmtlib/fmt/pull/759
namespace fmt {
template <class T, class Char>
struct is_range<matrix2d::Matrix2d<T>, Char> : std::false_type {};
} // namespace fmt

namespace matrix2d {

// NOTE: Do NOT follow the boost docs and use
// boost::random_access_traversal_tag as the iterator category tag for row
// iterators. If you do this, then call say, std::distance, std::distance will
// check to see if there iterator_traits::iterator_category is
// std::random_access_iterator_tag, which it isn't as it's
// boost::random_access_traversal_tag.
// This means that std::distance will assume the row_iterator is an input
// iterator, and will keep calling ++row_iterator until you hit the end. If
// you called std::distance(x, y) where y is before x, then you're screwed (x
// will be inced till it hits end_, or without end_ into UB past end_).
// Whereas with the correct iterator_category distance_to will be called as
// expected.
// This was annoying to find to say the least.

// https://www.boost.org/doc/libs/1_72_0/libs/iterator/doc/iterator_facade.html
// "Should" be the size_type of the underlying ContiguousContainer
// using size_type = std::size_t;
// using difference_type = std::ptrdiff_t;
// typename std::iterator_traits<Iterator>::difference_type;

template <class V>
template <class I, class VT>
template <class I1, class VT1, class>
Matrix2d<V>::row_iter<I, VT>::row_iter(const row_iter<I1, VT1>& other)
    : row_(other.row_), end_(other.end_), size_(other.size_) {}

template <class V>
template <class I, class VT>
Matrix2d<V>::row_iter<I, VT>::row_iter(const Iterator row, const size_type size,
                                       const Iterator end)
    : row_(row), end_(end), size_(size) {}

template <class V>
template <class I, class VT>
void Matrix2d<V>::row_iter<I, VT>::advance(const difference_type n) {
  if (n > 0) {
    assert(row_ < end_ && "row_ iterator advanced past end_");
  }
  std::advance(row_, static_cast<difference_type>(size_) * n);
}

template <class V>
template <class I, class VT>
void Matrix2d<V>::row_iter<I, VT>::increment() {
  this->advance(1);
}

template <class V>
template <class I, class VT>
void Matrix2d<V>::row_iter<I, VT>::decrement() {
  this->advance(-1);
}

template <class V>
template <class I, class VT>
template <class I1, class VT1>
typename Matrix2d<V>::difference_type //
Matrix2d<V>::row_iter<I, VT>::distance_to(
    const row_iter<I1, VT1>& other) const {
  assert(size_ == other.size_);
  if (size_ == 0) {
    // Must be a zero sized matrix
    assert(row_ == other.row_);
    return 0;
  }
  static_assert(
      std::is_signed_v<decltype((other.row_ - row_) /
                                static_cast<difference_type>(size_))>);
  return (other.row_ - row_) / static_cast<difference_type>(size_);
}

template <class V>
template <class I, class VT>
template <class I1, class VT1>
bool Matrix2d<V>::row_iter<I, VT>::equal(const row_iter<I1, VT1>& other) const {
  assert(size_ == other.size_);
  return this->row_ == other.row_;
}

// dereference should return a reference type, we're using a span so the
// valuetype is a view onto the data
template <class V>
template <class I, class VT>
VT Matrix2d<V>::row_iter<I, VT>::dereference() const {
  assert(row_ < end_);
  // assert(row_ + size_ <= end_); // Could push iterator/pointer past end_
  assert(end_ - row_ >= static_cast<difference_type>(size_));
  static_assert(std::is_lvalue_reference_v<decltype(*row_)>);
  return {&*row_, size_};
}

// NOTE: can't (easily anyway) use ranges::subrange in place of this class.
// It stores two iterators (well iterator+sentinel) (call them first, last),
// not an iterator+size_ pair like this. This means for a loop like
// for (auto it = v.begin(); it != v.end(); ++it)
// on the last iteration, first == v.end(), but last == first + size_ ie. we
// will increment past the end iterator which is UB
// Whereas this will have row_ == v.end() and size_ is just a number.

template <class V>
std::string Matrix2d<V>::to_string(const std::string_view elem_delim,
                                       const std::string_view row_delim,
                                       const std::size_t pad) const {
  if (this->empty()) {
    return "";
  }

  const auto width =
      pad + ranges::max(ranges::views::all(*this) |
                        ranges::views::transform([](const auto& elem) {
                          return fmt::formatted_size("{}", elem);
                        }));

  // Must call the below range pipeline to produce a string on an lvalue. Since
  // we end the pipeline with to_string everything is evaluated here, so no
  // lifetime issue.
  auto rows = this->rows_iter();

  // See dynamic width https://fmt.dev/7.1.3/syntax.html#format-examples
  return rows | ranges::views::transform([elem_delim, width](const auto& row) {
           // https://old.reddit.com/r/cpp/comments/opuu92/whats_up_with_c_ranges/h68o4ey/
           return fmt::format("{:>{}}", fmt::join(row, elem_delim), width);
         }) |
         ranges::views::cache1 | ranges::views::join(row_delim) |
         ranges::to<std::string>();
}

template <class V>
std::ostream& operator<<(std::ostream& os, const Matrix2d<V>& m) {
  return os << m.to_string();
}

template <class V>
inline Matrix2d<V>::Matrix2d(const size_type rows, const size_type cols)
    : rows_(rows), cols_(cols), data_(rows * cols) {
  // std::fill(data_.begin(), data_.end(), value_type{});
}

template <class V>
inline typename Matrix2d<V>::value_type
Matrix2d<V>::operator()(const size_type row, const size_type col) const {
#ifndef NDEBUG
  if (row >= rows_ || col >= cols_)
    throw std::out_of_range("const Matrix2d subscript out of bounds");
#endif
  return data_[cols_ * row + col];
}

template <class V>
inline typename Matrix2d<V>::reference
Matrix2d<V>::operator()(const size_type row, const size_type col) {
#ifndef NDEBUG
  if (row >= rows_ || col >= cols_)
    throw std::out_of_range("const Matrix2d subscript out of bounds");
#endif
  return data_[cols_ * row + col];
}

template <class V>
inline typename Matrix2d<V>::value_type
Matrix2d<V>::operator()(const Index& index) const {
  return this->operator()(index.y, index.x);
}

template <class V>
inline typename Matrix2d<V>::reference
Matrix2d<V>::operator()(const Index& index) {
  return this->operator()(index.y, index.x);
}

} // namespace matrix2d

#endif // MATRIX2D_TPP

ext: tpp


text:
/**
 * \file
 * \author stvdedal@gmail.com
 *
 * \brief
 * Program for testing gspan algorithm
 */

#include "gspan.hpp"

#include <boost/graph/adjacency_list.hpp>

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <list>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <functional>

#include <cctype>
#include <cstdlib>

using namespace boost;

void
print_usage(std::ostream& s)
{
    // line width 80
    // --------------------------------------------------------------------------------
    s <<
      "Usage: gspan [options]\n"
      "Graph-based substructure pattern mining.\n"
      "Depending on the graph count in input, there are two modes:\n"
      "  1. input contains one graph. Mined patterns belong to this one;\n"
      "       in this case only --mincount=NUM option is used\n"
      "  2. input contains many graphs. Mined patterns belong to some graph in input;\n"
      "       in this case --minsupp=NUM option is used, as more useful.\n"
      "Options:\n"
      "  -i, --input FILE        file to read, default stdin\n"
      "  -o, --output FILE       file to write, default stdout\n"
      "  -c, --mincount NUM      minimal count, integer value, default 1\n"
      "  -s, --minsupp NUM       minimal support, 0..1\n"
      "  -l, --legacy            use tgf format for input and output (slower!)\n"
      "  -e, --embeddings [opts] none, autgrp, all. default is none\n"
      "  -h, --help              this help"
      << std::endl;
}

void error_usage()
{
    print_usage(std::cerr);
    exit(1);
}

std::ifstream input_fstream;
std::ofstream output_fstream;
std::istream* input_stream = &std::cin;
std::ostream* output_stream = &std::cout;
bool no_output = false;
bool use_legacy = false;
enum OutputMappings {
    OUTPUT_MAPPING_NONE,
    OUTPUT_MAPPING_ONE_AUTOMORPH,
    OUTPUT_MAPPING_ALL
} output_mappings = OUTPUT_MAPPING_NONE;

static std::size_t pattern_no = 0;

/**
 * Vertex and edge properties are used by algorithm.
 * To optimize comparison, they are integers (not strings)
 *
 * vertex values are addressed by boost::vertex_name
 * edge values   are addressed by boost::edge_name
 */
std::vector<std::string> v_values;
std::vector<std::string> e_values;

std::size_t
map_string_to_integer(std::vector<std::string>& values,
                      const std::string& value)
{
    auto valit = std::find(values.begin(), values.end(), value);
    if (valit == values.end()) {
        valit = values.insert(values.end(), value);
    }
    return valit - values.begin();
}

using VP = property<vertex_name_t, std::size_t>;
using EP =
    property<edge_index_t, std::size_t, property<edge_name_t, std::size_t> >;

using InputGraph = adjacency_list<vecS, vecS, undirectedS, VP, EP, std::size_t>;
using InputGraphVertex = graph_traits<InputGraph>::vertex_descriptor;
using InputGraphEdge = graph_traits<InputGraph>::edge_descriptor;
using GspanTraits = gspan_traits<InputGraph, vertex_name_t, edge_name_t>;

template <typename MG, typename SBG>
void
print_mapping(const MG& mg,
              const SBG& s,
              std::size_t map_no,
              std::size_t autmorph_no)
{
    std::ostream& os = *output_stream;

    //os << std::endl;
    const InputGraph& ig = *s.input_graph();
    os << "m " << map_no << " #automorh " << autmorph_no << " "<<ig[graph_bundle]<< std::endl;
    for (auto v_mg : vertices(mg)) {
        auto v_ig = get_v_ig(s, v_mg);
        os << "v " << v_index(mg, v_mg) << " ";
        //os << ig[graph_bundle] << " ";
        os << get(get(vertex_index, ig), v_ig) << std::endl;
    }
    for (auto e_mg : edges(mg)) {
        auto e_ig = get_e_ig(s, e_mg);
        os << "e " << e_index(mg, e_mg) << " ";
        //os << ig[graph_bundle] << " ";
        os << get(get(edge_index, ig), e_ig) << std::endl;
    }
}

void
write_egf(const GspanTraits::MG& mg, const GspanTraits::SG& sg, int support)
{
    ++pattern_no;

    if (no_output)
        return;

    std::ostream& os = *output_stream;

    //os << std::endl;
    os << "p " << pattern_no << " # occurence " << support << std::endl;
    for (auto v : vertices(mg))
        os << "v " << v_index(mg, v) << " " << v_values[v_bundle(mg, v)]
           << std::endl;
    for (auto e : edges(mg))
        os << "e " << e_index(mg, e) << " " << source_index(mg, e) << " "
           << target_index(mg, e) << " " << e_values[e_bundle(mg, e)] << std::endl;

    if (output_mappings != OUTPUT_MAPPING_NONE) {
        std::size_t map_no = 0;
        for (const auto& g_sbgs : sg) {
            for (const auto& grp : g_sbgs.second.aut_list) {
                std::size_t autmorph_no = 0;
                for (const auto& s : grp) {
                    print_mapping(mg, *s, ++map_no, ++autmorph_no);
                    if (output_mappings == OUTPUT_MAPPING_ONE_AUTOMORPH)
                        break;
                }
            }
        }
    }
}

void
write_tgf(const GspanTraits::MG& mg, const GspanTraits::SG& sg, int support)
{
    ++pattern_no;

    if (no_output)
        return;
    std::ostream& os = *output_stream;

    using MGE = GspanTraits::MG::edge_descriptor;
    std::vector<MGE> mg_edges; // to reverse (for matching with gbolt)

    mg_edges.reserve(num_edges(mg));
    for (auto e : edges(mg))
        mg_edges.push_back(e);

    os << "t # " << pattern_no - 1 << " * " << support << std::endl;
    for (auto v : vertices(mg))
        os << "v " << v_index(mg, v) << " " << v_bundle(mg, v) << std::endl;

    using RevIt = std::vector<MGE>::const_reverse_iterator;
    for (RevIt ei = mg_edges.rbegin(); ei != mg_edges.rend(); ++ei) {
        MGE e = *ei;
        os << "e " << source_index(mg, e) << " " << target_index(mg, e)
           << " " << e_bundle(mg, e) << std::endl;
    }

    std::set<std::size_t> graph_ids;
    for (const auto& g_sbgs : sg) {
        const InputGraph& ig = *g_sbgs.first;
        graph_ids.insert(ig[graph_bundle]);
    }

    os << "x ";
    for (std::size_t graph_id : graph_ids) {
        os << graph_id << " ";
    }

    os << std::endl << std::endl;
}

inline
std::string&
remove_comment(std::string& s)
{
    s.erase(std::find(s.begin(), s.end(), '#'), s.end());
    return s;
}

inline
std::string&
remove_whitespaces_left(std::string& s)
{
    using namespace std;
    s.erase(s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun(&::isblank))));
    return s;
}

inline
std::string&
remove_whitespaces_right(std::string& s)
{
    using namespace std;
    auto rit = find_if(s.rbegin(), s.rend(), not1(ptr_fun(&::isblank)));
    s.erase(rit.base(), s.end());
    return s;
}

bool read_egf(std::list<InputGraph>& container, std::istream& is)
{
    std::map<std::size_t, InputGraphVertex> vmap;
    std::size_t line_no = 0;
    std::string line;

    while (getline(is, line)) {
        ++line_no;
        remove_comment(line);
        remove_whitespaces_left(line);
        remove_whitespaces_right(line);
        if (line.empty())
            continue;
        char tag = 0;
        std::stringstream ss(line);
        ss >> tag;
        switch (tag) {
        case 't': {
            vmap.clear();
            container.push_back(InputGraph());
            std::size_t graph_id = 0;
            ss >> graph_id;
            if (!ss) {
                std::cerr << "invalid or missed <graph_id>, at line " << line_no
                          << std::endl;
                return false;
            }
            container.back()[graph_bundle] = graph_id;
        }
        break;
        case 'v': {
            if (container.empty()) {
                std::cerr << "invalid format: 't' tag missed" << std::endl;
                return false;
            }
            InputGraph& g = container.back();
            InputGraphVertex v = add_vertex(g);
            std::size_t vertex_id = 0;
            ss >> vertex_id;
            if (!ss) {
                std::cerr << "invalid or missed <vertex_id>, at line " << line_no
                          << std::endl;
                return false;
            }

            std::string value;
            getline(ss, value);
            remove_whitespaces_left(value);
            put(get(vertex_name, g), v, map_string_to_integer(v_values, value));
            vmap[vertex_id] = v;
        }
        break;
        case 'e': {
            if (container.empty()) {
                std::cerr << "invalid format: 't' tag missed" << std::endl;
                return false;
            }
            InputGraph& g = container.back();
            std::size_t edge_id = 0;
            if (!(ss >> edge_id)) {
                std::cerr << "invalid or missed <edge_id>, at line " << line_no
                          << std::endl;
                return false;
            }
            std::size_t src_id;
            if (!(ss >> src_id) || vmap.find(src_id) == vmap.end()) {
                std::cerr << "invalid or missed <vertex_id_1>, at line " << line_no
                          << std::endl;
                return false;
            }
            std::size_t dst_id;
            if (!(ss >> dst_id) || vmap.find(dst_id) == vmap.end()) {
                std::cerr << "invalid or missed <vertex_id_2>, at line " << line_no
                          << std::endl;
                return false;
            }

            InputGraphVertex u = vmap[src_id];
            InputGraphVertex v = vmap[dst_id];
            InputGraphEdge e = add_edge(u, v, g).first;
            put(get(edge_index, g), e, edge_id);

            std::string value;
            getline(ss, value);
            remove_whitespaces_left(value);
            put(get(edge_name, g), e, map_string_to_integer(e_values, value));
        }
        break;
        default:
            std::cerr << "invalid or missed <tag>, at line " << line_no << std::endl;
            return false;
        }
    }

    return true;
}

bool read_tgf(std::list<InputGraph>& container, std::istream& is)
{
    std::map<std::size_t, InputGraphVertex> vmap;
    std::size_t line_no = 0;
    std::string line;

    while (getline(is, line)) {
        ++line_no;
        if (line.empty())
            continue;
        char tag = 0;
        std::stringstream ss(line);
        ss >> tag;
        switch (tag) {
        case 't': {
            vmap.clear();
            container.push_back(InputGraph());
            char nsign = 0;
            std::size_t graph_id = 0;
            ss >> nsign >> graph_id;
            if (!ss || nsign != '#') {
                std::cerr << "invalid or missed <graph_id>, at line " << line_no
                          << std::endl;
                return false;
            }
            container.back()[graph_bundle] = graph_id;
        }
        break;
        case 'v': {
            if (container.empty()) {
                std::cerr << "invalid format: 't' tag missed" << std::endl;
                return false;
            }
            InputGraph& g = container.back();
            InputGraphVertex v = add_vertex(g);
            std::size_t vertex_id = 0;
            ss >> vertex_id;
            if (!ss || vertex_id >= num_vertices(g)) {
                std::cerr << "invalid or missed <vertex_id>, at line " << line_no
                          << std::endl;
                return false;
            }

            std::size_t ival;
            if (!(ss >> ival)) {
                std::cerr << "invalid or missed vertex value (integer), at line " << line_no
                          << std::endl;
                return false;
            }
            put(get(vertex_name, g), v, ival);
            vmap[vertex_id] = v;
        }
        break;
        case 'e': {
            if (container.empty()) {
                std::cerr << "invalid format: 't' tag missed" << std::endl;
                return false;
            }
            InputGraph& g = container.back();
            std::size_t src_id;
            if (!(ss >> src_id) || vmap.find(src_id) == vmap.end()) {
                std::cerr << "invalid or missed <vertex_id_1>, at line " << line_no
                          << std::endl;
                return false;
            }
            std::size_t dst_id;
            if (!(ss >> dst_id) || vmap.find(dst_id) == vmap.end()) {
                std::cerr << "invalid or missed <vertex_id_2>, at line " << line_no
                          << std::endl;
                return false;
            }

            InputGraphVertex u = vmap[src_id];
            InputGraphVertex v = vmap[dst_id];
            InputGraphEdge e = add_edge(u, v, g).first;
            put(get(edge_index, g), e, num_edges(g) - 1);

            std::size_t ival;
            if (!(ss >> ival)) {
                std::cerr << "invalid or missed edge value (integer), at line " << line_no
                          << std::endl;
                return false;
            }
            put(get(edge_name, g), e, ival);
        }
        break;
        default:
            std::cerr << "invalid or missed <tag>, at line " << line_no << std::endl;
            return false;
        }
    }

    return true;
}

struct input_statistics {
    std::size_t graph_count;
    struct {
        std::size_t avg;
        std::size_t min;
        std::size_t max;
    } v, e;
};

void calculate_statistics(const std::list<InputGraph>& container,
                          input_statistics* stat)
{
    stat->graph_count = 0;
    stat->v.avg = 0;
    stat->v.min = 0;
    stat->v.max = 0;
    stat->e.avg = 0;
    stat->e.min = 0;
    stat->e.max = 0;
    if (container.empty()) {
        return;
    }
    stat->v.max = stat->v.min = num_vertices(container.front());
    stat->e.max = stat->e.min = num_edges(container.front());
    for (const InputGraph& g : container) {
        ++stat->graph_count;
        std::size_t vn = num_vertices(g);
        std::size_t en = num_edges(g);
        stat->v.avg += vn;
        stat->e.avg += en;
        if (stat->v.min > vn) {
            stat->v.min = vn;
        }
        if (stat->v.max < vn) {
            stat->v.max = vn;
        }
        if (stat->e.min > en) {
            stat->e.min = en;
        }
        if (stat->e.max < en) {
            stat->e.max = en;
        }
    }
    stat->v.avg /= stat->graph_count;
    stat->e.avg /= stat->graph_count;
}

int
main(int argc, char** argv)
{
    std::size_t mincount = 0;
    bool minsupp_exist = true;
    double minsupp = 1.0;

    for (int i = 1; i < argc; ++i) {
        std::string opt(argv[i]);
        if (opt == "--help" || opt == "-h") {
            print_usage(std::cout);
            return 0;
        }
        else if (opt == "--input" || opt == "-i") {
            if (++i >= argc || input_fstream.is_open())
                error_usage();
            input_fstream.open(argv[i]);
            input_stream = &input_fstream;
            continue;
        }
        else if (opt == "--output" || opt == "-o") {
            if (++i >= argc || output_fstream.is_open())
                error_usage();
            std::string file(argv[i]);
            if (file != "/dev/null") {
                output_fstream.open(file);
                output_stream = &output_fstream;
            }
            else {
                no_output = true;
            }
            continue;
        }
        else if (opt == "--mincount" || opt == "-c") {
            if (++i >= argc)
                error_usage();
            if (! (std::stringstream(argv[i]) >> mincount)) {
                error_usage();
            }
            continue;
        }
        else if (opt == "--minsupp" || opt == "-s") {
            if (++i >= argc)
                error_usage();
            if (! (std::stringstream(argv[i]) >> minsupp)) {
                error_usage();
            }
            minsupp_exist = true;
            continue;
        }
        else if (opt == "--legacy" || opt == "-l") {
            use_legacy = true;
        }
        else if (opt == "--embeddings" || opt == "-e") {
            if (++i >= argc)
                error_usage();
            std::string param(argv[i]);
            if (param == "all")
                output_mappings = OUTPUT_MAPPING_ALL;
            else if (param == "autgrp")
                output_mappings = OUTPUT_MAPPING_ONE_AUTOMORPH;
            else if (param == "none")
                output_mappings = OUTPUT_MAPPING_NONE;
            else
                error_usage();
            continue;
        }
        else {
            error_usage();
        }
    }

    std::list<InputGraph> input_graphs;

    if (!(use_legacy ? read_tgf : read_egf)(input_graphs, *input_stream))
        return 1;

    input_statistics stat;
    calculate_statistics(input_graphs, &stat);

    if (minsupp_exist) {
        mincount = stat.graph_count * minsupp;
    }

    std::cerr << std::endl;
    std::cerr << "# input data statistics:\n"
              << "# graph count          = " << stat.graph_count << std::endl
              << "# vertices avg,min,max = "
              << stat.v.avg << ", " << stat.v.min << ", " << stat.v.max << std::endl
              << "# edges avg,min,max    = "
              << stat.e.avg << ", " << stat.e.min << ", " << stat.e.max << std::endl
              << "# min_count            = " << mincount << std::endl << std::endl;

    if (input_graphs.size() == 1)
        gspan_one_graph(input_graphs.back(),
                        mincount,
                        use_legacy ? write_tgf : write_egf,
                        vertex_name,
                        edge_name);
    else
        gspan_many_graphs(input_graphs.begin(),
                          input_graphs.end(),
                          mincount,
                          use_legacy ? write_tgf : write_egf,
                          vertex_name,
                          edge_name);

    std::cerr << std::endl;
    std::cerr << "# mined " << pattern_no << " patterns" << std::endl;
}

max_stars_repo_name: dtchuink/DFG-Pattern-Generator

max_issues_repo_name: dtchuink/DFG-Pattern-Generator

max_forks_repo_name: dtchuink/DFG-Pattern-Generator


text:
#include <ast.h>
#include <grammar.h>

#include <boost/program_options.hpp>

#include <iostream>
#include <string>
#include <type_traits>

const std::string testsSuccess[] = {
    "42",
    "-12",
    "3*4",
    "10 mod 2",
    "-1*(4123%(1 + 4))",
    "!(4/2)",
    "-(3*(2/2))",
    "4*2-3",
    "(2+3)*4",
    "2+2+2",
    "3==4",
    "5 ne 6",
    "3+4>22",
    "5*(3+2) le 1",
    "(2+4) between [-1, 10]",
    "10 in {4}",
    "!(2 in {3, 4, 5})",
    "(6 > 4) and (1 == 1)",
    "(3 mod 2 == 0) or 3 in {1, 2, 3}",
    "3.25 < 4-0.5",
    "'a' > '\\t'",
    "\"hello\"==\"world\\n\"",
    "$x.y[123].z",
    "q[xy_2==(1+2)]",
    "exists foo",
    "!exists bar_2[100]",
    "#2017-09-16#",
    "#T12:34:56.89#",
    "#2017-09-16 T12:34:56.89#",
    "this.id=3+4",
    "$xyz=#2017-09-16#",
    "3*4 /* totally \n valid /* and nested! */ \n comment */",
    "42 // ignore"};

const std::string testsFailure[] = {
    "4*", "/2",
    /* "1*+2", */ // interesting case - double_ parses this...so is it really
                  // wrong?
    "1+*2", "3+", "!between [2,10]",
    /* "exists 3*4" */ // shouldn't parse, something is wrong with the skipper
    "exists (3*4)", "#2017#", "T12:3", "=3+4", "$i=", "this.id=3+4=5-6"};

std::pair<bool, score::ast::Statement> doParse(const std::string &stmt) {
  score::ast::Statement ast;
  bool parsed = score::parse(ast, stmt);
  return {parsed, ast};
}

void runTests() {
  auto testFn = [](auto &tests, bool shouldParse) {
    for (const auto &t : tests) {
      std::cout << "attempting parse for: " << t << std::endl;

      bool parsed = doParse(t).first;

      if ((shouldParse && parsed) || (!shouldParse && !parsed)) {
        std::cout << "\tOK" << std::endl;
      } else {
        std::cout << "\tERROR "
                  << "(should" << (shouldParse ? " " : " not ")
                  << "have parsed)" << std::endl;
      }
    }
  };
  testFn(testsSuccess, true);
  testFn(testsFailure, false);
}

int main(int argc, char *argv[]) {
  namespace po = boost::program_options;

  try {
    po::options_description scoreDesc("score dsl command-line tool");
    scoreDesc.add_options()("help,h", "this help message")(
        "runTests", "run built-in test suite")("expression",
                                               "score expression to evaluate");

    po::positional_options_description posOptions;
    posOptions.add("expression", 1);

    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv)
                  .options(scoreDesc)
                  .positional(posOptions)
                  .run(),
              vm);
    po::notify(vm);

    if (vm.count("help")) {
      std::cout << scoreDesc << std::endl;
      return EXIT_SUCCESS;
    }

    const auto &rtCount = vm.count("runTests");
    const auto &eCount = vm.count("expression");
    if (rtCount && eCount) {
      std::cerr << "either specify the 'runTests' flag or an 'expression', but "
                   "not both."
                << std::endl;
      return EXIT_FAILURE;
    }

    if (rtCount) {
      runTests();
      return EXIT_SUCCESS;
    }

    if (eCount) {
      const auto &eArg = vm["expression"].as<std::string>();

      const auto &parsePair = doParse(eArg);
      if (!parsePair.first) {
        std::cout << "parse failed" << std::endl;
      } else {
        std::cout << "parse succeeded" << std::endl;
      }
      return EXIT_SUCCESS;
    }

    std::cout << scoreDesc << std::endl;
    return EXIT_SUCCESS;
  } catch (std::exception &e) {
    std::cerr << "exception encountered: " << e.what() << std::endl;
    return EXIT_FAILURE;
  } catch (...) {
    std::cerr << "unknown failure" << std::endl;
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}

max_stars_repo_name: FIXTradingCommunity/fix-orchestra-cpp

max_issues_repo_name: FIXTradingCommunity/fix-orchestra-cpp

max_forks_repo_name: FIXTradingCommunity/fix-orchestra-cpp


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2012 - 2014 MetaScale SAS
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_BOOLEAN_FUNCTIONS_SIMD_COMMON_IFNOTSUB_HPP_INCLUDED
#define BOOST_SIMD_BOOLEAN_FUNCTIONS_SIMD_COMMON_IFNOTSUB_HPP_INCLUDED

#include <boost/simd/boolean/functions/ifnotsub.hpp>
#include <boost/simd/include/functions/simd/if_zero_else.hpp>
#include <boost/simd/include/functions/simd/minus.hpp>
#include <boost/simd/sdk/meta/cardinal_of.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/dispatch/attributes.hpp>

namespace boost { namespace simd { namespace ext
{
  BOOST_DISPATCH_IMPLEMENT_IF          ( ifnotsub_, tag::cpu_
                                       , (A0)(A1)(X)
                                       , (boost::mpl::equal_to < boost::simd::meta::cardinal_of<A0>
                                                               , boost::simd::meta::cardinal_of<A1>
                                                               >
                                         )
                                       , ((simd_<unspecified_<A0>,X>))
                                         ((simd_<unspecified_<A1>,X>))
                                         ((simd_<unspecified_<A1>,X>))
                                       )
  {
    typedef A1 result_type;

    BOOST_FORCEINLINE
    result_type operator()(A0 const& a0, A1 const& a1, A1 const& a2) const
    {
      return a1-if_zero_else(a0, a2);
    }
  };
} } }

#endif


text:
#include "../python_extension.hpp"
#include "lue/object/phenomena.hpp"
#include "../core/collection.hpp"
#include "lue/py/conversion.hpp"
#include <pybind11/pybind11.h>
#include <boost/algorithm/string/join.hpp>

namespace py = pybind11;
using namespace pybind11::literals;

namespace lue {
namespace data_model {
namespace {

static std::string formal_string_representation(
    Phenomenon const& phenomenon)
{
    return fmt::format(
        "Phenomenon(pathname='{}')",
        phenomenon.id().pathname());
}

static std::string informal_string_representation(
    Phenomenon const& phenomenon)
{
    return fmt::format(
        "{}\n"
        "    collection-property-sets: [{}]\n"
        "    property-sets: [{}]",
        formal_string_representation(phenomenon),
        boost::algorithm::join(
            phenomenon.collection_property_sets().names(), ", "),
        boost::algorithm::join(phenomenon.property_sets().names(), ", "));
}

PropertySet& add_property_set(
    PropertySets& property_sets,
    std::string const& name)
{
    return property_sets.add(name);
}

PropertySet& add_property_set(
    PropertySets& property_sets,
    std::string const& name,
    SpaceConfiguration const& space_configuration,
    py::dtype const& space_coordinate_dtype,
    Rank const rank)
{
    auto const datatype =
        numpy_type_to_memory_datatype(space_coordinate_dtype);

    return property_sets.add(
        name,
        space_configuration, datatype, rank);
}

PropertySet& add_property_set(
    PropertySets& property_sets,
    std::string const& name,
    TimeConfiguration const& time_configuration,
    Clock const& clock)
{
    return property_sets.add(
        name,
        time_configuration, clock);
}

PropertySet& add_property_set(
    PropertySets& property_sets,
    std::string const& name,
    TimeConfiguration const& time_configuration,
    Clock const& clock,
    SpaceConfiguration const& space_configuration,
    py::dtype const& space_coordinate_dtype,
    Rank const rank)
{
    auto const datatype =
        numpy_type_to_memory_datatype(space_coordinate_dtype);

    return property_sets.add(
        name,
        time_configuration, clock,
        space_configuration, datatype, rank);
}

PropertySet& add_property_set(
    PropertySets& property_sets,
    std::string const& name,
    TimeDomain& time_domain)
{
    return property_sets.add(name, time_domain);
}

PropertySet& add_property_set(
    PropertySets& property_sets,
    std::string const& name,
    TimeDomain& time_domain,
    ObjectTracker& object_tracker)
{
    return property_sets.add(name, time_domain, object_tracker);
}

PropertySet& add_property_set(
    PropertySets& property_sets,
    std::string const& name,
    TimeDomain& time_domain,
    SpaceConfiguration const& space_configuration,
    py::dtype const& space_coordinate_dtype,
    Rank const rank)
{
    auto const datatype =
        numpy_type_to_memory_datatype(space_coordinate_dtype);

    return property_sets.add(
        name,
        time_domain,
        space_configuration, datatype, rank);
}

PropertySet& add_property_set(
    PropertySets& property_sets,
    std::string const& name,
    TimeDomain& time_domain,
    ObjectTracker& object_tracker,
    SpaceConfiguration const& space_configuration,
    py::dtype const& space_coordinate_dtype,
    Rank const rank)
{
    auto const datatype =
        numpy_type_to_memory_datatype(space_coordinate_dtype);

    return property_sets.add(
        name,
        time_domain, object_tracker,
        space_configuration, datatype, rank);
}

}  // Anonymous namespace

void init_phenomenon(
    py::module& module)
{

    BASE_COLLECTION(Phenomena, Phenomenon)

    py::class_<Phenomena, PhenomenonCollection>(
        module,
        "Phenomena",
        R"(
    Collection of phenomena

    Phenomenon collections can be obtained from :class:`Dataset` and
    :class:`Universe` instances.
)")

        ;

    py::class_<Phenomenon, hdf5::Group>(
        module,
        "Phenomenon",
        R"(
    Class for representing information about a collection of objects

    A phenomenon contains two :class:`property set collections
    <PropertySets>`. The :meth:`first <Phenomenon.property_sets>`
    contains information about each object in a collection of objects. The
    :meth:`second <Phenomenon.collection_property_sets>` second contains
    information that is representable for the collection of objects as
    a whole.

    Phenomena are used to organize information about different collections
    of objects. For example, information about cows, parcels and farmers
    can be stored using three phenomena.
)")

        .def(
            "__repr__",
            [](Phenomenon const& phenomenon) {
                return formal_string_representation(phenomenon);
            }
        )

        .def(
            "__str__",
            [](Phenomenon const& phenomenon) {
                return informal_string_representation(phenomenon);
            }
        )

        .def_property_readonly(
            "object_id",
            py::overload_cast<>(&Phenomenon::object_id),
            R"(
    object_id docstring...
)")

        .def_property_readonly(
            "property_sets",
            py::overload_cast<>(&Phenomenon::property_sets),
            R"(
    Return property sets collection containing information about each
    object in the collection of objects

    :rtype: PropertySets
)",
            py::return_value_policy::reference_internal)

        .def_property_readonly(
            "collection_property_sets",
            py::overload_cast<>(&Phenomenon::collection_property_sets),
            R"(
    Return property sets collection containing information about the
    collection of objects

    :rtype: PropertySets
)",
            py::return_value_policy::reference_internal)

        .def(
            "__getattr__",
            [](
                Phenomenon& phenomenon,
                std::string const& property_set_name)
            {
                auto const property_set_found =
                    phenomenon.property_sets().contains(property_set_name);
                auto const collection_property_set_found =
                    phenomenon.collection_property_sets().contains(
                        property_set_name);

                if(!property_set_found && !collection_property_set_found) {
                    // TODO We are throwing a KeyError here. Should be
                    // an AttributeError, but pybind11 does not seem to
                    // support that yet.
                    //
                    // Python message:
                    // AttributeError: 'x' object has no attribute 'y'
                    // Ours is a little bit different:
                    throw pybind11::key_error(fmt::format(
                        "Phenomenon does not contain (collection) "
                        "property-set '{}'",
                        property_set_name));
                }

                assert(property_set_found || collection_property_set_found);

                auto& property_sets = property_set_found
                    ? phenomenon.property_sets()
                    : phenomenon.collection_property_sets()
                    ;

                return py::cast(&property_sets[property_set_name]);
            },
            py::return_value_policy::reference_internal)

        .def(
            "add_property_set",
            [](
                Phenomenon& phenomenon,
                std::string const& name) -> PropertySet&
            {
                return add_property_set(phenomenon.property_sets(), name);
            },
            "name"_a,
            R"(
    Add new property-set to collection

    :param str name: Name of property-set to create
    :return: Property-set created
    :rtype: PropertySet
    :raises RuntimeError: In case the property-set cannot be created

    The property-set will have no time domain and no space
    domain. Information stored in this property-set will be omnipresent
    through time and space.
)",
            py::return_value_policy::reference_internal)

        .def(
            "add_collection_property_set",
            [](
                Phenomenon& phenomenon,
                std::string const& name) -> PropertySet&
            {
                return add_property_set(
                    phenomenon.collection_property_sets(), name);
            },
            "name"_a,
            R"(
    Add new property-set to collection

    :param str name: Name of property-set to create
    :return: Property-set created
    :rtype: PropertySet
    :raises RuntimeError: In case the property-set cannot be created

    The property-set will have no time domain and no space
    domain. Information stored in this property-set will be omnipresent
    through time and space.
)",
            py::return_value_policy::reference_internal)

        .def(
            "add_property_set",
            [](
                Phenomenon& phenomenon,
                std::string const& name,
                SpaceConfiguration const& space_configuration,
                py::dtype const& space_coordinate_dtype,
                Rank const rank) -> PropertySet&
            {
                return add_property_set(
                    phenomenon.property_sets(), name,
                    space_configuration, space_coordinate_dtype, rank);
            },
            "name"_a,
            "space_configuration"_a,
            "space_coordinate_dtype"_a,
            "rank"_a,
            R"(
    Add new property-set to collection

    :param str name: Name of property-set to create
    :param SpaceConfiguration space_configuration: Configuration of
        space domain
    :param numpy.dtype space_coordinate_dtype: Datatype of the spatial
        coordinates
    :param int rank: Number of spatial dimensions
    :return: Property-set created
    :rtype: PropertySet
    :raises RuntimeError: In case the property-set cannot be created

    The property-set returned will have no time domain. Information
    stored in this property-set will be omnipresent through time.
)",
            py::return_value_policy::reference_internal)

        .def(
            "add_property_set",
            [](
                Phenomenon& phenomenon,
                std::string const& name,
                TimeConfiguration const& time_configuration,
                Clock const& clock) -> PropertySet&
            {
                return add_property_set(
                    phenomenon.property_sets(), name,
                    time_configuration, clock);
            },
            "name"_a,
            "time_configuration"_a,
            "clock"_a,
            R"(
    Add new property-set to collection

    :param str name: Name of property-set to create
    :param TimeConfiguration time_configuration: Configuration of
        time domain
    :param lue.Clock clock: Clock for locations in time
    :return: Property-set created
    :rtype: PropertySet
    :raises RuntimeError: In case the property-set cannot be created
)",
            py::return_value_policy::reference_internal)

        .def(
            "add_property_set",
            [](
                Phenomenon& phenomenon,
                std::string const& name,
                TimeConfiguration const& time_configuration,
                Clock const& clock,
                SpaceConfiguration const& space_configuration,
                py::dtype const& space_coordinate_dtype,
                Rank const rank) -> PropertySet&
            {
                return add_property_set(
                    phenomenon.property_sets(), name,
                    time_configuration, clock,
                    space_configuration, space_coordinate_dtype, rank);
            },
            "name"_a,
            "time_configuration"_a,
            "clock"_a,
            "space_configuration"_a,
            "space_coordinate_dtype"_a,
            "rank"_a,
            R"(
    Add new property-set to collection

    :param str name: Name of property-set to create
    :param TimeConfiguration time_configuration: Configuration of
        time domain
    :param lue.Clock clock: Clock for locations in time
    :param SpaceConfiguration space_configuration: Configuration of
        space domain
    :param numpy.dtype space_coordinate_dtype: Datatype of the spatial
        coordinates
    :param int rank: Number of spatial dimensions
    :return: Property-set created
    :rtype: PropertySet
    :raises RuntimeError: In case the property-set cannot be created
)",
            py::return_value_policy::reference_internal)

        .def(
            "add_property_set",
            [](
                Phenomenon& phenomenon,
                std::string const& name,
                TimeDomain& time_domain) -> PropertySet&
            {
                return add_property_set(
                    phenomenon.property_sets(), name,
                    time_domain);
            },
            "name"_a,
            "time_domain"_a,
            R"(
    Add new property-set to collection

    :param str name: Name of property-set to create
    :param TimeDomain time_domain: Another property-set's time domain
        to use. Sharing time domains makes sense when the locations in
        time are the same. This saves space in the dataset.
    :return: Property-set created
    :rtype: PropertySet
    :raises RuntimeError: In case the property-set cannot be created

    The property-set will have no space domain. Information stored in
    this property-set will be omnipresent through space.
)",
            py::return_value_policy::reference_internal)

        .def(
            "add_collection_property_set",
            [](
                Phenomenon& phenomenon,
                std::string const& name,
                TimeDomain& time_domain) -> PropertySet&
            {
                return add_property_set(
                    phenomenon.collection_property_sets(), name,
                    time_domain);
            },
            "name"_a,
            "time_domain"_a,
            R"(
    Add new property-set to collection

    :param str name: Name of property-set to create
    :param TimeDomain time_domain: Another property-set's time domain
        to use. Sharing time domains makes sense when the locations in
        time are the same. This saves space in the dataset.
    :return: Property-set created
    :rtype: PropertySet
    :raises RuntimeError: In case the property-set cannot be created

    The property-set will have no space domain. Information stored in
    this property-set will be omnipresent through space.
)",
            py::return_value_policy::reference_internal)

        .def(
            "add_property_set",
            [](
                Phenomenon& phenomenon,
                std::string const& name,
                TimeDomain& time_domain,
                ObjectTracker& object_tracker) -> PropertySet&
            {
                return add_property_set(
                    phenomenon.property_sets(), name,
                    time_domain, object_tracker);
            },
            "name"_a,
            "time_domain"_a,
            "object_tracker"_a,
            R"(
    Add new property-set to collection

    :param str name: Name of property-set to create
    :param TimeDomain time_domain: Another property-set's time domain
        to use. Sharing time domains makes sense when the locations in
        time are the same. This saves space in the dataset.
    :param ObjectTracker object_tracker: Another property-set's object
        tracker to use. Sharing object trackers makes sense when the
        active set in different property-sets are the same.
    :return: Property-set created
    :rtype: PropertySet
    :raises RuntimeError: In case the property-set cannot be created

    The property-set will have no space domain. Information stored in
    this property-set will be omnipresent through space.
)",
            py::return_value_policy::reference_internal)

        .def(
            "add_property_set",
            [](
                Phenomenon& phenomenon,
                std::string const& name,
                TimeDomain& time_domain,
                SpaceConfiguration const& space_configuration,
                py::dtype const& space_coordinate_dtype,
                Rank const rank) -> PropertySet&
            {
                return add_property_set(
                    phenomenon.property_sets(), name,
                    time_domain,
                    space_configuration, space_coordinate_dtype, rank);
            },
            "name"_a,
            "time_domain"_a,
            "space_configuration"_a,
            "space_coordinate_dtype"_a,
            "rank"_a,
            R"(
    Add new property-set to collection

    :param str name: Name of property-set to create
    :param TimeDomain time_domain: Another property-set's time domain
        to use. Sharing time domains makes sense when the locations in
        time are the same. This saves space in the dataset.
    :param SpaceConfiguration space_configuration: Configuration of
        space domain
    :param numpy.dtype space_coordinate_dtype: Datatype of the spatial
        coordinates
    :param int rank: Number of spatial dimensions
    :return: Property-set created
    :rtype: PropertySet
    :raises RuntimeError: In case the property-set cannot be created
)",
            py::return_value_policy::reference_internal)

        .def(
            "add_property_set",
            [](
                Phenomenon& phenomenon,
                std::string const& name,
                TimeDomain& time_domain,
                ObjectTracker& object_tracker,
                SpaceConfiguration const& space_configuration,
                py::dtype const& space_coordinate_dtype,
                Rank const rank) -> PropertySet&
            {
                return add_property_set(
                    phenomenon.property_sets(), name,
                    time_domain, object_tracker,
                    space_configuration, space_coordinate_dtype, rank);
            },
            "name"_a,
            "time_domain"_a,
            "object_tracker"_a,
            "space_configuration"_a,
            "space_coordinate_dtype"_a,
            "rank"_a,
            R"(
    Add new property-set to collection

    :param str name: Name of property-set to create
    :param TimeDomain time_domain: Another property-set's time domain
        to use. Sharing time domains makes sense when the locations in
        time are the same. This saves space in the dataset.
    :param ObjectTracker object_tracker: Another property-set's object
        tracker to use. Sharing object trackers makes sense when the
        active set in different property-sets are the same.
    :param SpaceConfiguration space_configuration: Configuration of
        space domain
    :param numpy.dtype space_coordinate_dtype: Datatype of the spatial
        coordinates
    :param int rank: Number of spatial dimensions
    :return: Property-set created
    :rtype: PropertySet
    :raises RuntimeError: In case the property-set cannot be created
)",
            py::return_value_policy::reference_internal)

        ;

}

}  // namespace data_model
}  // namespace lue

max_stars_repo_name: OliverSchmitz/lue

max_issues_repo_name: OliverSchmitz/lue

max_forks_repo_name: OliverSchmitz/lue


text:
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman

Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef BOOST_SPIRIT_QI_DETAIL_EXPECTATION_FAILURE_HPP
#define BOOST_SPIRIT_QI_DETAIL_EXPECTATION_FAILURE_HPP

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/spirit/home/support/info.hpp>

#include <boost/config.hpp> // for BOOST_SYMBOL_VISIBLE
#include <stdexcept>

namespace boost { namespace spirit { namespace qi {
    template <typename Iterator>
    struct BOOST_SYMBOL_VISIBLE expectation_failure : std::runtime_error
    {
        expectation_failure(Iterator first_, Iterator last_, info const& what)
            : std::runtime_error("boost::spirit::qi::expectation_failure")
            , first(first_), last(last_), what_(what)
        {}
        ~expectation_failure() BOOST_NOEXCEPT_OR_NOTHROW {}

        Iterator first;
        Iterator last;
        info what_;
    };
}}}

#endif

max_issues_repo_name: qingkouwei/mediaones

max_forks_repo_name: qingkouwei/mediaones


text:
#pragma once

#include <bunsan/curl/options/traits.hpp>

#include <curl/curl.h>

#include <boost/optional.hpp>

namespace bunsan::curl::options::wrapper {

template <typename Wrapper,
          decltype(static_cast<Wrapper *>(nullptr)->data()) Default>
class wrapped_option_default {
 public:
  using retention_policy = typename Wrapper::retention_policy;

 public:
  wrapped_option_default() = default;

  template <typename Arg, typename... Args>
  explicit wrapped_option_default(Arg &&arg, Args &&... args)
      : m_wrapper(std::forward<Arg>(arg), std::forward<Args>(args)...) {}

  auto data() const {
    if (m_wrapper) {
      return m_wrapper->data();
    } else {
      return Default;
    }
  }

 private:
  boost::optional<Wrapper> m_wrapper;
};

}  // namespace bunsan::curl::options::wrapper

#define BUNSAN_CURL_OPTION_DEFAULT_WRAPPED(NAME, CODE, ...)           \
  using NAME = ::bunsan::curl::options::wrapper::wrapped_option<      \
      CODE, ::bunsan::curl::options::wrapper::wrapped_option_default< \
                ::bunsan::curl::options::wrapper::__VA_ARGS__> >;

max_stars_repo_name: bacsorg/bacs

max_issues_repo_name: bacsorg/bacs

max_forks_repo_name: bacsorg/bacs