text:
#include <Eigen/Core>
#include "mex.h"

using namespace Eigen;
using namespace std;

// TODO openmp version
// TODO roll counting in with second message passing
// TODO scaling instead of logs?

// NOTE: mxSetProperty and possibly mxGetProperty make copies, even with
// classdef < handle! lame! I believe mxGetField does NOT make a copy, though I
// haven't tested it recently

void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{

    /* SETUP */
    if (nrhs != 5) { mexErrMsgTxt("wrong number of arguments\n"); }

    //// pull out inputs

    // data
    if (!mxGetField(prhs[0],0,"data")) { mexErrMsgTxt("data missing 'data' field\n"); }
    double *alldata = mxGetPr(mxGetField(prhs[0],0,"data"));
    int bigT = mxGetN(mxGetField(prhs[0],0,"data")); // total length of the data
    int num_subparts = mxGetM(mxGetField(prhs[0],0,"data")); // number of sub-parts

    if (!mxGetField(prhs[0],0,"resources")) { mexErrMsgTxt("data missing 'resources' field\n"); }
    double *allresources = mxGetPr(mxGetField(prhs[0],0,"resources"));

    if (!mxGetField(prhs[0],0,"starts")) { mexErrMsgTxt("data missing 'starts' field\n"); }
    double *starts = mxGetPr(mxGetField(prhs[0],0,"starts"));
    int num_sequences = max(mxGetM(mxGetField(prhs[0],0,"starts")),
            mxGetM(mxGetField(prhs[0],0,"starts")));

    if (!mxGetField(prhs[0],0,"lengths")) { mexErrMsgTxt("data missing 'lengths' field\n"); }
    double *lengths = mxGetPr(mxGetField(prhs[0],0,"lengths"));

    // parameters struct
    if (!mxGetField(prhs[1],0,"learns")) { mexErrMsgTxt("model missing 'learns' field\n"); }
    double *learns = mxGetPr(mxGetField(prhs[1],0,"learns"));
    int num_resources = max(mxGetM(mxGetField(prhs[1],0,"learns")),
            mxGetN(mxGetField(prhs[1],0,"learns")));

    if (!mxGetField(prhs[1],0,"forgets")) { mexErrMsgTxt("model missing 'forgets' field\n"); }
    double *forgets = mxGetPr(mxGetField(prhs[1],0,"forgets"));

    if (!mxGetField(prhs[1],0,"guesses")) { mexErrMsgTxt("model missing 'guesses' field\n"); }
    double *guess = mxGetPr(mxGetField(prhs[1],0,"guesses"));

    if (!mxGetField(prhs[1],0,"slips")) { mexErrMsgTxt("model missing 'slips' field\n"); }
    double *slip = mxGetPr(mxGetField(prhs[1],0,"slips"));

    if (!mxGetField(prhs[1],0,"prior")) { mexErrMsgTxt("model missing 'prior' field\n"); }
    double prior = mxGetScalar(mxGetField(prhs[1],0,"prior"));

    Array2d initial_distn;
    initial_distn << 1-prior, prior;

    MatrixXd As(2,2*num_resources);
    for (int n=0; n<num_resources; n++) {
        As.col(2*n) << 1-learns[n], learns[n];
        As.col(2*n+1) << forgets[n], 1-forgets[n];
    }
    ArrayXXd Als(2,2*num_resources);
    Als = As.array().log();

    Array2Xd Bn(2,2*num_subparts);
    for (int n=0; n<num_subparts; n++) {
        Bn.col(2*n) << log(1-guess[n]), log(slip[n]); // incorrect
        Bn.col(2*n+1) << log(guess[n]), log(1-slip[n]); // correct
    }

    //// outputs

    // rhs outputs
    Map<ArrayXXd,Aligned> all_trans_softcounts(mxGetPr(prhs[2]),2,2*num_resources);
    all_trans_softcounts.setZero();
    Map<Array2Xd,Aligned> all_emission_softcounts(mxGetPr(prhs[3]),2,2*num_subparts);
    all_emission_softcounts.setZero();
    Map<Array2d,Aligned> all_initial_softcounts(mxGetPr(prhs[4]));
    all_initial_softcounts.setZero();

    // lhs outputs
    Map<Array2Xd,Aligned> alphal_out(NULL,2,bigT);
    Map<Array2Xd,Aligned> betal_out(NULL,2,bigT);
    double *total_loglike = NULL;
    switch (nlhs) {
        case 3:
            plhs[2] = mxCreateDoubleMatrix(2,bigT,mxREAL);
            new (&betal_out) Map<Array2Xd,Aligned>(mxGetPr(plhs[2]),2,bigT);
        case 2:
            plhs[1] = mxCreateDoubleMatrix(2,bigT,mxREAL);
            new (&alphal_out) Map<Array2Xd,Aligned>(mxGetPr(plhs[1]),2,bigT);
        case 1:
            plhs[0] = mxCreateDoubleScalar(0.);
            total_loglike = mxGetPr(plhs[0]);
    }

    /* COMPUTATION */

    for (int sequence_index=0; sequence_index < num_sequences; sequence_index++) {
        // NOTE: -1 because Matlab indexing starts at 1
        int sequence_start = ((int) starts[sequence_index]) - 1;
        int T = (int) lengths[sequence_index];

        Map<ArrayXXd> data(alldata + num_subparts*sequence_start,num_subparts,T);
        double *resources = allresources + sequence_start;

        //// likelihoods
        Array2Xd likelihoods(2,T);
        likelihoods.setZero();
        for (int t=0; t<T; t++) {
            for (int n=0; n<num_subparts; n++) {
                if (data(n,t) != 0) {
                    likelihoods.col(t) += Bn.col(2*n + (data(n,t) == 2));
                }
            }
        }

        //// forward messages
        Array2Xd alphal(2,T);
        alphal.col(0) = initial_distn.log() + likelihoods.col(0);
        for (int t=0; t<T-1; t++) {
            double cmax = alphal.col(t).maxCoeff();
            alphal.col(t+1) = (As.block(0,2*(resources[t]-1),2,2) // NOTE matlab indexing
                    * (alphal.col(t) - cmax).exp().matrix()).array().log()
                    + cmax + likelihoods.col(t+1);
        }

        //// backward messages
        Array2Xd betal(2,T);
        betal.col(T-1).setZero();
        for (int t=T-2; t>=0; t--) {
            Array2d thesum = likelihoods.col(t+1) + betal.col(t+1);
            double cmax = thesum.maxCoeff();
            betal.col(t) = (As.block(0,2*(resources[t]-1),2,2).transpose() // NOTE matlab indexing
                    * (thesum - cmax).exp().matrix()).array().log() + cmax;
        }

        //// statistic counting
        // TODO could roll this into second message sweep
        Array2d temp = alphal.col(0) + betal.col(0);
        double cmax = temp.maxCoeff();
        double loglike = log((temp - cmax).exp().sum()) + cmax;

        ArrayXXd trans_softcounts(2,2*num_resources);
        trans_softcounts.setZero();
        Array2Xd emission_softcounts(2,2*num_subparts);
        emission_softcounts.setZero();

        for (int t=0; t<T-1; t++) {
            Array22d pair; // cols = t, rows=t+1
            pair.rowwise() = alphal.col(t).transpose();
            pair.colwise() += (betal.col(t+1) + likelihoods.col(t+1));
            pair += Als.block(0,2*(resources[t]-1),2,2); // NOTE matlab indexing
            pair -= loglike;
            pair = pair.exp();

            trans_softcounts.block(0,2*(resources[t]-1),2,2) += pair; // NOTE matlab indexing

            Array2d single = pair.colwise().sum();
            for (int n=0; n<num_subparts; n++) {
                if (data(n,t) != 0) {
                    emission_softcounts.col(2*n + (data(n,t) == 2)) += single;
                }
            }
        }
        // NOTE: last iteration needed for emission softcounts
        int t=T-1;
        Array2d single = alphal.col(t);
        single -= loglike;
        single = single.exp();
        for (int n=0; n<num_subparts; n++) {
            if (data(n,t) != 0) { emission_softcounts.col(2*n + (data(n,t) == 2)) += single;
            }
        }

        Array2d initial_softcounts = betal.col(0) + alphal.col(0);
        initial_softcounts -= loglike;
        initial_softcounts = initial_softcounts.exp();

        // NOTE: these will need to change to base types for openmp
        all_trans_softcounts += trans_softcounts;
        all_emission_softcounts += emission_softcounts;
        all_initial_softcounts += initial_softcounts;

        switch (nlhs) {
            case 3:
                betal_out.block(0,sequence_start,2,T) = betal;
            case 2:
                alphal_out.block(0,sequence_start,2,T) = alphal;
            case 1:
                *total_loglike += loglike;
        }

    }
}

max_stars_repo_name: CAHLR/xBKT

max_issues_repo_name: CAHLR/xBKT

max_forks_repo_name: CAHLR/xBKT


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

#include <stdlib.h>

#include <cstring>
#include <iostream>
#include <boost/property_tree/json_parser.hpp>

#include "../../mxbase/FunctionTimer.h"
#include "../../mxbase/MxCenterNetPostProcessor.h"
#include "../../mxbase/MxImage.h"
#include "../../mxbase/MxUtil.h"
#include "CommandFlagParser.h"
#include "MxBase/Log/Log.h"
#include "MxBase/ModelPostProcessors/ModelPostProcessorBase/ObjectPostProcessorBase.h"
#include "MxStream/StreamManager/MxStreamManager.h"
#include "MxTools/Proto/MxpiDataType.pb.h"
#include "MxTools/Proto/MxpiDataTypeDeleter.h"
#include "cpprest/json.h"

namespace json = web::json;

FunctionStats g_infer_stats("inference",
                            "ms");  // use microseconds as time unit
FunctionStats g_total_stats("total Process",
                            "ms");  // use milliseconds as time unit
uint32_t g_original_width;
uint32_t g_original_height;

namespace {
const char STREAM_NAME[] = "im_centernet";
}  // namespace

DEFINE_string(images, "../../data/images/val2017/", "test image file or path.");
DEFINE_string(image_name_path, "../../data/config/test.txt",
              "json file for getting image info");
DEFINE_string(pipeline, "../../data/config/centernet_ms.pipeline",
              "config file for this model.");
DEFINE_uint32(width, 512, "om file accept width");
DEFINE_uint32(height, 512, "om file accept height");
DEFINE_bool(show, false,
            "whether show result as bbox on top of original picture");
DEFINE_string(color, "bgr", "input color space need for model.");
DEFINE_string(config, "../../data/models/centernet.cfg",
              "config file for this model.");

struct ImgInfo {
    std::string imgPath;
    uint64_t imageId;
};

APP_ERROR DrawRectangle(const std::string& imagePath,
                        const std::vector<MxBase::ObjectInfo>& objInfos) {
    std::string m_strOutputJpg = "mark_images/";
    std::string m_strInputFileName = basename(imagePath.c_str());
    m_strOutputJpg.append(m_strInputFileName);
    m_strOutputJpg.replace(m_strOutputJpg.rfind('.'), -1, "_out.jpg");

    if (!MkdirRecursive(ResolvePathName(m_strOutputJpg))) return false;

    CVImage img;
    if (FLAGS_show) img.Load(imagePath);
    for (auto& pos : objInfos) {
        if (FLAGS_show)
            img.DrawBox(pos.x0, pos.y0, pos.x1, pos.y1, pos.confidence);
    }
    if (FLAGS_show) img.Save(m_strOutputJpg.c_str());

    return APP_ERR_OK;
}

void GetTensors(
    const std::shared_ptr<MxTools::MxpiTensorPackageList>& tensorPackageList,
    std::vector<MxBase::TensorBase>& tensors) {
    for (int i = 0; i < tensorPackageList->tensorpackagevec_size(); ++i) {
        for (int j = 0;
             j < tensorPackageList->tensorpackagevec(i).tensorvec_size(); j++) {
            MxBase::MemoryData memoryData = {};
            memoryData.deviceId =
                tensorPackageList->tensorpackagevec(i).tensorvec(j).deviceid();
            memoryData.type = (MxBase::MemoryData::MemoryType)tensorPackageList
                                  ->tensorpackagevec(i)
                                  .tensorvec(j)
                                  .memtype();
            memoryData.size = (uint32_t)tensorPackageList->tensorpackagevec(i)
                                  .tensorvec(j)
                                  .tensordatasize();
            memoryData.ptrData =
                reinterpret_cast<void*>(tensorPackageList->tensorpackagevec(i)
                                            .tensorvec(j)
                                            .tensordataptr());
            if (memoryData.type == MxBase::MemoryData::MEMORY_HOST ||
                memoryData.type == MxBase::MemoryData::MEMORY_HOST_MALLOC ||
                memoryData.type == MxBase::MemoryData::MEMORY_HOST_NEW) {
                memoryData.deviceId = -1;
            }
            std::vector<uint32_t> outputShape = {};
            for (int k = 0; k < tensorPackageList->tensorpackagevec(i)
                                    .tensorvec(j)
                                    .tensorshape_size();
                 ++k) {
                outputShape.push_back(
                    (uint32_t)tensorPackageList->tensorpackagevec(i)
                        .tensorvec(j)
                        .tensorshape(k));
            }
            MxBase::TensorBase tmpTensor(
                memoryData, true, outputShape,
                (MxBase::TensorDataType)tensorPackageList->tensorpackagevec(0)
                    .tensorvec(j)
                    .tensordatatype());
            tensors.push_back(tmpTensor);
        }
    }
}

bool PreprocessedImage(const std::string& file, uint32_t wdith, uint32_t height,
                       CVImage& dstImg) {
    CVImage img;
    if (img.Load(file) != APP_ERR_OK) {
        LogError << "load image :" << file << " as CVImage error !!!";
        return false;
    }

    // char buf[100];
    // snprintf(buf,sizeof(buf),"%u",img.Width());
    // setenv("ORG_WIDTH",buf,1);
    // snprintf(buf,sizeof(buf),"%u",img.Height());
    // setenv("ORG_HEIGHT",buf,1);
    g_original_width = img.Width();
    g_original_height = img.Height();

    static cv::Scalar __means = {0.408, 0.447, 0.470};
    static cv::Scalar __stds = {0.289, 0.274, 0.278};

    dstImg = img.WarpAffinePreprocess(wdith, height, FLAGS_color);
    dstImg = dstImg.ConvertToDeviceFormat(ACL_FLOAT, ACL_FORMAT_NCHW, &__means,
                                          &__stds);
    return true;
}

// This function is only for reading sample txt.
APP_ERROR SendEachProtobuf(MxStream::MxStreamManager& mxStreamManager,
                           int inPluginId, const std::string& streamName,
                           MxBase::MemoryData& inputMem,
                           MxBase::TensorDataType dType) {
    MxBase::MemoryData memoryDst(inputMem.size,
                                 MxBase::MemoryData::MEMORY_HOST_NEW);
    APP_ERROR ret =
        MxBase::MemoryHelper::MxbsMallocAndCopy(memoryDst, inputMem);
    if (ret != APP_ERR_OK) {
        LogError << "Fail to malloc and copy host memory.";
        return ret;
    }
    auto tensorPackageList = std::shared_ptr<MxTools::MxpiTensorPackageList>(
        new MxTools::MxpiTensorPackageList,
        MxTools::g_deleteFuncMxpiTensorPackageList);
    auto tensorPackage = tensorPackageList->add_tensorpackagevec();
    auto tensorVec = tensorPackage->add_tensorvec();
    tensorVec->set_tensordataptr((uint64_t)memoryDst.ptrData);
    tensorVec->set_tensordatasize(memoryDst.size);
    tensorVec->set_tensordatatype(dType);
    tensorVec->set_memtype(MxTools::MXPI_MEMORY_HOST_NEW);
    tensorVec->set_deviceid(0);
    // nchw
    tensorVec->add_tensorshape(1);
    tensorVec->add_tensorshape(3);
    tensorVec->add_tensorshape(FLAGS_height);
    tensorVec->add_tensorshape(FLAGS_width);

    MxStream::MxstProtobufIn dataBuffer;
    std::ostringstream dataSource;
    dataSource << "appsrc" << inPluginId;
    dataBuffer.key = dataSource.str();
    dataBuffer.messagePtr =
        std::static_pointer_cast<google::protobuf::Message>(tensorPackageList);
    std::vector<MxStream::MxstProtobufIn> dataBufferVec;
    dataBufferVec.push_back(dataBuffer);

    ret = mxStreamManager.SendProtobuf(streamName, inPluginId, dataBufferVec);
    return ret;
}

static bool g_loop_stop = false;

void softINT(int signo) {
    printf("user ctr-c quit loop!\n");
    g_loop_stop = true;
}

bool FetchImageNameAndId(const std::string& imageFolderPath,
                         std::string& fileNamePath,
                         std::vector<ImgInfo>& files) {
    std::ifstream inFile(fileNamePath);
    std::string imageName;
    while (std::getline(inFile, imageName)) {
        std::string imagePath = imageFolderPath + imageName;
        char absPath[PATH_MAX];
        if (realpath(imagePath.c_str(), absPath) == nullptr) {
            LOG_SYS_ERROR("get the absolute file path: " << absPath);
            return false;
        }

        struct stat buffer;
        if (stat(absPath, &buffer) != 0) {
            LOG_SYS_ERROR("stat file path:" << absPath);
            return false;
        }

        std::string imageId = imageName.substr(0, imageName.size() - 4);
        int idx = 0;
        while (imageId[idx] == '0') ++idx;
        imageId = imageId.substr(idx);

        if (S_ISREG(buffer.st_mode)) {
            files.push_back({absPath, std::stoul(imageId)});
        } else {
            LogFatal << "not a regular file";
            return false;
        }
    }

    return true;
}

// write object information to JSON
bool writeImageObjectList(std::vector<json::value>& jsonObjs,
                          const std::vector<MxBase::ObjectInfo>& objs,
                          const uint64_t imgId) {
    for (auto& obj : objs) {
        json::value jsonObj;
        jsonObj["image_id"] = json::value::number(imgId);
        jsonObj["category_id"] = json::value::number(1);
        jsonObj["score"] = json::value::number(obj.confidence);
        jsonObj["bbox"][0] = json::value::number(obj.x0);
        jsonObj["bbox"][1] = json::value::number(obj.y0);
        jsonObj["bbox"][2] = json::value::number(obj.x1 - obj.x0);
        jsonObj["bbox"][3] = json::value::number(obj.y1 - obj.y0);

        std::vector<json::value> keyPoints;
        for (auto& point : obj.mask) {
            keyPoints.push_back(
                json::value::number(static_cast<float>(point[0]) / 1000));
            keyPoints.push_back(
                json::value::number(static_cast<float>(point[1]) / 1000));
            keyPoints.push_back(json::value::number(static_cast<float>(1.0)));
        }
        jsonObj["keypoints"] = json::value::array(keyPoints);

        jsonObjs.push_back(jsonObj);
    }

    return true;
}

int main(int argc, char* argv[]) {
    FLAGS_logtostderr = 1;
    std::cout << "Usage: --images " << FLAGS_images << " --pipeline "
              << FLAGS_pipeline << " --show" << std::endl;
    OptionManager::getInstance()->parseCommandLineFlags(argc, argv);

    std::vector<ImgInfo> files;
    if (!FetchImageNameAndId(FLAGS_images, FLAGS_image_name_path, files))
        return -1;

    // Init stream manager
    MxStream::MxStreamManager mxStreamManager;
    LogError << "begin to Init stream manager...";
    APP_ERROR ret = mxStreamManager.InitManager();
    if (ret != APP_ERR_OK) {
        LogError << "Failed to Init Stream manager, ret = " << ret << ".";
        return ret;
    }
    // FLAGS_minloglevel=google::GLOG_ERROR;
    // create stream by pipeline config file
    ret = mxStreamManager.CreateMultipleStreamsFromFile(FLAGS_pipeline);
    if (ret != APP_ERR_OK) {
        LogError << "Failed to create Stream, ret = " << ret << ".";
        return ret;
    }

    std::vector<std::string> keyVec = {"mxpi_tensorinfer0"};
    CVImage destImage;
    FunctionTimer timer;
    std::vector<json::value> jsonResults;

    signal(SIGINT, softINT);
    FLAGS_minloglevel = google::GLOG_ERROR;

    for (auto& file : files) {
        if (g_loop_stop) break;

        timer.start_timer();

        if (!PreprocessedImage(file.imgPath, FLAGS_width, FLAGS_height,
                               destImage)) {
            LogError << "Preprocess image file error:" << file.imgPath;
        } else {
            // read image file and build stream input
            MxBase::MemoryData dataBuffer(destImage.FetchImageBuf(),
                                          destImage.FetchImageBytes());
            // send protobuf data into stream
            ret = SendEachProtobuf(mxStreamManager, 0, STREAM_NAME, dataBuffer,
                                   MxBase::TENSOR_DTYPE_FLOAT32);

            if (APP_ERR_OK != ret) {
                LogError << "Failed to send data to stream, ret = " << ret
                         << ".";
                return ret;
            }
            std::vector<MxStream::MxstProtobufOut> output =
                mxStreamManager.GetProtobuf(STREAM_NAME, 0, keyVec);
            if (output.size() < 1) {
                LogError << "output size less then 1 !!!";
                return APP_ERR_ACL_FAILURE;
            }
            if (output[0].errorCode != APP_ERR_OK) {
                LogError << "GetProtobuf error. errorCode="
                         << output[0].errorCode;
                return output[0].errorCode;
            }
            std::shared_ptr<MxTools::MxpiTensorPackageList> objectList =
                std::dynamic_pointer_cast<MxTools::MxpiTensorPackageList>(
                    output[0].messagePtr);

            std::vector<MxBase::TensorBase> tensors = {};
            GetTensors(objectList, tensors);

            // post process
            MxCenterNetPostProcessor postProcessor;
            std::vector<std::vector<MxBase::ObjectInfo>> objectInfos;

            if (APP_ERR_OK != postProcessor.Init(FLAGS_config, "")) {
                LogError << "Failed to init post processor!";
            }
            std::vector<MxBase::ResizedImageInfo> imgInfos;
            imgInfos.emplace_back(MxBase::ResizedImageInfo{
                FLAGS_width, FLAGS_height, g_original_width, g_original_height,
                MxBase::RESIZER_RESCALE, 0.0});
            if (APP_ERR_OK !=
                postProcessor.Process(tensors, objectInfos, imgInfos)) {
                LogError << "Failed in post process!";
            }

            writeImageObjectList(jsonResults, objectInfos[0], file.imageId);
            DrawRectangle(file.imgPath, objectInfos[0]);

            timer.calculate_time();
            g_total_stats.update_time(timer.get_elapsed_time_in_milliseconds());
        }
    }
    // destroy streams
    mxStreamManager.DestroyAllStreams();

    // write inference result to the json file
    std::string m_strOutputTxt = "infer_results/sdk_infer_result.json";
    if (!MkdirRecursive(ResolvePathName(m_strOutputTxt))) return false;

    std::ofstream result_file;
    result_file.open(m_strOutputTxt);
    result_file << json::value::array(jsonResults);

    g_total_stats.print_stats();
}

ext: cpp

max_stars_repo_name: mindspore-ai/models

max_issues_repo_name: mindspore-ai/models

max_forks_repo_name: mindspore-ai/models


text:
#include <algorithm>
#include <numeric>
#include <limits>
#include <unordered_set>

#include <boost/lambda/lambda.hpp>

#include "Conditioning.h"
#include "LogSumExp.h"
#include "FactorGraphPartialObservation.h"
#include "VAcyclicDecomposition.h"
#include "FactorGraphStructurizer.h"
#include "StructuredMeanFieldInference.h"

using namespace boost::lambda;

namespace Grante {

StructuredMeanFieldInference::StructuredMeanFieldInference(
	const FactorGraph* fg, FactorConditioningTable* fcond_tab,
	DecompositionType decomp_type)
	: InferenceMethod(fg), fcond_tab(fcond_tab),
		log_z(std::numeric_limits<double>::signaling_NaN()),
		verbose(true), conv_tol(1.0e-6), max_iter(50) {
	// 1. Compute a v-acyclic decomposition of the factor graph
	VAcyclicDecomposition vac(fg);
	std::vector<double> factor_weight(fg->Factors().size(), 1.0);

	// Total correlation based weights
	if (decomp_type == TotalCorrelationWeights) {
		const std::vector<Factor*>& factors = fg->Factors();
		for (unsigned int fi = 0; fi < factors.size(); ++fi) {
			double tcorr = factors[fi]->TotalCorrelation();
			assert(tcorr >= -1.0e-10);
			// Add an epsilon so it is always better to add factors than to
			// leave them out.
			factor_weight[fi] = std::min(1.0e-3, tcorr);
		}
	}
	std::vector<bool> factor_is_removed;
	vac.ComputeDecompositionSP(factor_weight, factor_is_removed);

	InitializeVAC(factor_is_removed);
}

StructuredMeanFieldInference::StructuredMeanFieldInference(
	const FactorGraph* fg, FactorConditioningTable* fcond_tab,
	const std::vector<bool>& factor_is_removed)
	: InferenceMethod(fg), fcond_tab(fcond_tab),
		log_z(std::numeric_limits<double>::signaling_NaN()),
		verbose(true), conv_tol(1.0e-6), max_iter(50) {
	// TODO: assert this yields a v-acyclic decomposition
	assert(factor_is_removed.size() == fg->Factors().size());
	InitializeVAC(factor_is_removed);
}

StructuredMeanFieldInference::~StructuredMeanFieldInference() {
	// Delete component factor graphs (created in InitializeVAC)
	assert(mf_comp.size() == mf_comp_inf.size());
	for (unsigned int ci = 0; ci < mf_comp.size(); ++ci) {
		delete (mf_comp[ci]);
		delete (mf_comp_inf[ci]);
	}
}

void StructuredMeanFieldInference::InitializeVAC(
	const std::vector<bool>& factor_is_removed) {
	// Create simple factor to fi lookup table
	const std::vector<Factor*>& factors = fg->Factors();
	for (unsigned int fi = 0; fi < factors.size(); ++fi)
		fac_to_fi.insert(std::pair<Factor*, unsigned int>(factors[fi], fi));

	// Decompose factor graph into components
	std::vector<unsigned int> cc_var_label;
	unsigned int cc_count = FactorGraphStructurizer::ConnectedComponents(
		fg, factor_is_removed, cc_var_label);

	// Instantiate a conditioned factor graph for each connected component
	mf_comp.resize(cc_count);
	mf_comp_inf.resize(cc_count);
	for (unsigned int ci = 0; ci < cc_count; ++ci) {
		// Collect all variables in this component
		std::vector<unsigned int> cond_var_set;
		std::unordered_set<unsigned int> cond_var;
		for (unsigned int vi = 0; vi < cc_var_label.size(); ++vi) {
			// Variable in this component -> do not condition
			if (cc_var_label[vi] == ci)
				continue;

			// Condition on all variables not in this component
			cond_var_set.push_back(vi);
			cond_var.insert(vi);
		}

		// Collect all factors in which both conditioned and unconditioned
		// variables appear and initialize the expectation to uniform.
		std::vector<unsigned int> cond_fac_subset;
		std::vector<std::vector<double> > cond_expect;
		for (unsigned int fi = 0; fi < factors.size(); ++fi) {
			bool has_cond = false;	// Factor has conditioned-on variables
			bool has_uncond = false;	// Factor has unconditioned variables
			const std::vector<unsigned int>& fac_vars =
				factors[fi]->Variables();
			const std::vector<unsigned int>& fac_card =
				factors[fi]->Cardinalities();
			unsigned int cond_prod_card = 1;
			for (unsigned int fvi = 0; fvi < fac_vars.size(); ++fvi) {
				if (cond_var.count(fac_vars[fvi]) == 0) {
					has_uncond = true;
				} else {
					has_cond = true;
					cond_prod_card *= fac_card[fvi];
				}
			}
			// Fully conditioned and fully unconditioned factors -> skip
			if (has_cond == false || has_uncond == false)
				continue;

			// We have a mixed factor, produce a uniform expectation
			// observation
			std::vector<double> cur_cond_marg(cond_prod_card,
				1.0/static_cast<double>(cond_prod_card));

			// Add this factor as to be conditioned
			cond_fac_subset.push_back(fi);
			cond_expect.push_back(cur_cond_marg);
		}

		// Build a partial observation from all the conditioned factors
		FactorGraphPartialObservation pobs(cond_var_set, cond_fac_subset,
			cond_expect);

		// Condition and add
		std::vector<unsigned int> var_new_to_orig;
		FactorGraph* fg_cond = Conditioning::ConditionFactorGraph(fcond_tab,
			fg, &pobs, var_new_to_orig);

		// Store conditioned factor graph and create an inference object.
		// The conditioned factor graph is always tree structured.
		mf_comp[ci] = fg_cond;
		mf_comp_inf[ci] = new TreeInference(fg_cond);

		// Collect all mean-field factors
		std::unordered_set<unsigned int>
			cond_fac_subset_hs(cond_fac_subset.begin(), cond_fac_subset.end());
		const std::vector<Factor*>& comp_factors = fg_cond->Factors();
		for (unsigned int comp_fi = 0; comp_fi < comp_factors.size();
			++comp_fi) {
			Factor* comp_fac = comp_factors[comp_fi];
			// Is conditioned?  No -> skip
			if (cond_fac_subset_hs.count(
				fac_to_fi[fcond_tab->OriginalFactor(comp_fac)]) == 0)
				continue;

			meanfield_factor_set.insert(comp_fac);
			cfac_to_mfi[comp_fac] = ci;
			cfac_to_cfi[comp_fac] = comp_fi;
		}
	}

	// Create lookup tables needed during inference
	for (unsigned int mfi = 0; mfi < mf_comp.size(); ++mfi) {
		const std::vector<Factor*>& mfi_factors = mf_comp[mfi]->Factors();
		for (unsigned int comp_fi = 0; comp_fi < mfi_factors.size();
			++comp_fi) {
			Factor* new_factor = mfi_factors[comp_fi];
			bool is_conditioned = meanfield_factor_set.count(new_factor) != 0;
			if (is_conditioned == false)
				continue;

			unsigned int orig_fi =
				fac_to_fi[fcond_tab->OriginalFactor(new_factor)];
			fi_to_condfac[orig_fi].insert(new_factor);
		}
	}
}

InferenceMethod* StructuredMeanFieldInference::Produce(
	const FactorGraph* fg) const {
	StructuredMeanFieldInference* smf =
		new StructuredMeanFieldInference(fg, fcond_tab);
	smf->SetParameters(verbose, conv_tol, max_iter);

	return (smf);
}

void StructuredMeanFieldInference::SetParameters(bool verbose,
	double conv_tol, unsigned int max_iter) {
	this->verbose = verbose;
	assert(conv_tol >= 0.0);
	this->conv_tol = conv_tol;
	this->max_iter = max_iter;
}

void StructuredMeanFieldInference::PerformInference() {
	// 1. Compute initial log partition function
	log_z = 0.0;
	for (unsigned int mfi = 0; mfi < mf_comp.size(); ++mfi) {
		mf_comp[mfi]->ForwardMap();
		mf_comp_inf[mfi]->PerformInference();
	}

	ProduceMarginals();
	log_z = ComputeLogPartitionFunction();

	// 2. Iterate mean field on components
	double conv_measure = std::numeric_limits<double>::infinity();
	for (unsigned int iter = 1; (max_iter == 0 || iter <= max_iter) &&
		conv_measure >= conv_tol; ++iter)
	{
		if (verbose) {
			std::cout << "iter " << iter << ", logZ " << log_z
				<< ", conv " << conv_measure << std::endl;
		}

		// For each component,
		for (unsigned int mfi = 0; mfi < mf_comp.size(); ++mfi) {
			// i) update all conditioning expectation information
			UpdateComponentEnergies(mfi);
			mf_comp[mfi]->ForwardMap();

			// ii) Perform inference
			mf_comp_inf[mfi]->PerformInference();
		}
		// Produce all marginals, either as copy or product
		ProduceMarginals();

		// Compute bound to the log-partition function
		double log_z_prev = log_z;
		log_z = ComputeLogPartitionFunction();
		assert(log_z >= (log_z_prev - 1.0e-11));
		conv_measure = std::max(0.0, log_z - log_z_prev);
	}
	if (verbose)
		std::cout << "Converged with tol " << conv_measure << "." << std::endl;

	// 3. Delete component inference results
	for (unsigned int mfi = 0; mfi < mf_comp.size(); ++mfi)
		mf_comp_inf[mfi]->ClearInferenceResult();
}

// This method has the responsibility to update all information related to
// component 'mfi'.  In particular, the factors that are part of mfi but
// conditioned on other component inference results need to be processed.  The
// result of this processing are new expectations applied to the conditioning
// factors, producing new energies.
void StructuredMeanFieldInference::UpdateComponentEnergies(unsigned int mfi) {
	FactorGraph* comp = mf_comp[mfi];
	const std::vector<Factor*>& mfi_factors = comp->Factors();

	// For each factor in mfi
	for (unsigned int comp_fi = 0; comp_fi < mfi_factors.size();
		++comp_fi) {
		Factor* new_factor = mfi_factors[comp_fi];
		bool is_conditioned = meanfield_factor_set.count(new_factor) != 0;
		if (is_conditioned == false)
			continue;	// Skip unconditioned factors

		// It is a conditioned factor
		Factor* orig_factor = fcond_tab->OriginalFactor(new_factor);
		assert(orig_factor != 0);
		assert(fac_to_fi.count(orig_factor) > 0);
		unsigned int orig_fi = fac_to_fi[orig_factor];
		assert(fi_to_condfac.count(orig_fi) > 0);
		// Set of all factors derived by conditioning this original factor
		const std::unordered_set<Factor*>& cond_facs =
			fi_to_condfac[orig_fi];

		// Schematic
		//
		//       (0) ---[F]--- (1)     // original factor
		//       (0) ---[G]            // conditioned factor 1
		//              [H]--- (1)     // conditioned factor 2
		//
		// new_factor is G, orig_factor is F, cond_facs is {G,H}.
		//
		// We now build new expectations used to update factor G.  We build
		// these from the marginals of cond_facs \ {new_factor}, hence from H.
		std::vector<double> ext_marginals(
			orig_factor->Type()->ProdCardinalities(), 1.0);
		size_t cond_expect_prodcard = 1;
		for (std::unordered_set<Factor*>::const_iterator
			cfi = cond_facs.begin(); cfi != cond_facs.end(); ++cfi) {
			// Ignore own marginals
			if (*cfi == new_factor)
				continue;

			// Obtain the conditional marginals
			assert(cfac_to_mfi.find(new_factor) != cfac_to_mfi.end());
			assert(cfac_to_cfi.find(new_factor) != cfac_to_cfi.end());
			const std::vector<double>& cfi_marg =
				mf_comp_inf[cfac_to_mfi[*cfi]]->Marginal(cfac_to_cfi[*cfi]);

			// Extend and multiply
			std::vector<double> cfi_ext_marginals(
				orig_factor->Type()->ProdCardinalities(), 0.0);
			fcond_tab->ExtendMarginals(*cfi, cfi_marg,
				cfi_ext_marginals, true);
			std::transform(cfi_ext_marginals.begin(), cfi_ext_marginals.end(),
				ext_marginals.begin(), ext_marginals.begin(), _1 * _2);
			cond_expect_prodcard *= (*cfi)->Type()->ProdCardinalities();
		}

		// Project to conditioned-on expectations
		assert(cond_expect_prodcard ==
			(orig_factor->Type()->ProdCardinalities() /
			new_factor->Type()->ProdCardinalities()));
		std::vector<double> cond_var_expect(cond_expect_prodcard);
		fcond_tab->ProjectExtendedMarginalsCond(new_factor, ext_marginals,
			cond_var_expect);

		// Update conditioned factor with new expectations
		fcond_tab->UpdateConditioningInformation(new_factor, cond_var_expect);
	}
}

void StructuredMeanFieldInference::ProduceMarginals() {
	// Initialize all marginals to 1.0 because unconditioned factors will
	// overwrite the marginals and conditioned factors multiply the values
	// (factorial meanfield assumption).
	const std::vector<Factor*>& factors = fg->Factors();
	marginals.resize(factors.size());
	std::unordered_map<Factor*, unsigned int> fac_to_fi;
	for (unsigned int fi = 0; fi < factors.size(); ++fi) {
		marginals[fi].resize(factors[fi]->Type()->ProdCardinalities());
		std::fill(marginals[fi].begin(), marginals[fi].end(), 1.0);
		fac_to_fi.insert(std::pair<Factor*, unsigned int>(factors[fi], fi));
	}
	for (unsigned int mfi = 0; mfi < mf_comp.size(); ++mfi) {
		const std::vector<Factor*>& mfi_factors = mf_comp[mfi]->Factors();
		for (unsigned int comp_fi = 0; comp_fi < mfi_factors.size();
			++comp_fi) {
			Factor* new_factor = mfi_factors[comp_fi];
			// Original factor index
			unsigned int orig_fi =
				fac_to_fi[fcond_tab->OriginalFactor(new_factor)];
			// Marginal from the component (possibly conditioned)
			const std::vector<double>& comp_marg =
				mf_comp_inf[mfi]->Marginal(comp_fi);

			bool is_conditioned = meanfield_factor_set.count(new_factor) != 0;
			if (is_conditioned == false) {
				// Unconditioned factor: copy marginals
				assert(comp_marg.size() == marginals[orig_fi].size());
				std::copy(comp_marg.begin(), comp_marg.end(),
					marginals[orig_fi].begin());
				continue;
			}

			// Conditioned factor: extend to full marginals and multiply
			std::vector<double> ext_marginals(marginals[orig_fi].size(), 0.0);
			fcond_tab->ExtendMarginals(new_factor, comp_marg,
				ext_marginals, true);
			std::transform(ext_marginals.begin(), ext_marginals.end(),
				marginals[orig_fi].begin(), marginals[orig_fi].begin(),
				_1 * _2);
		}
	}
}

double StructuredMeanFieldInference::ComputeLogPartitionFunction() {
	const std::vector<Factor*>& factors = fg->Factors();
	double mu_theta = 0.0;
	for (unsigned int fi = 0; fi < factors.size(); ++fi) {
		// <\theta,\mu>, where \theta=-E in our notation.
		mu_theta -= std::inner_product(marginals[fi].begin(),
			marginals[fi].end(), factors[fi]->Energies().begin(), 0.0);
	}
	// + \sum_m H_m(\mu)
	double H_sum = 0.0;
	for (unsigned int mfi = 0; mfi < mf_comp.size(); ++mfi)
		H_sum += mf_comp_inf[mfi]->Entropy();
#if 0
	std::cout << "mu_theta = " << mu_theta << std::endl;
	std::cout << "H_sum = " << H_sum << std::endl;
	std::cout << "log Z >= " << (mu_theta + H_sum) << std::endl;
#endif

	return (mu_theta + H_sum);
}

void StructuredMeanFieldInference::ClearInferenceResult() {
	marginals.clear();
}

const std::vector<double>& StructuredMeanFieldInference::Marginal(
	unsigned int factor_id) const {
	assert(factor_id < marginals.size());
	return (marginals[factor_id]);
}

const std::vector<std::vector<double> >&
StructuredMeanFieldInference::Marginals() const {
	return (marginals);
}

double StructuredMeanFieldInference::LogPartitionFunction() const {
	return (log_z);
}

void StructuredMeanFieldInference::Sample(
	std::vector<std::vector<unsigned int> >& states,
	unsigned int sample_count) {
	// NOT IMPLEMENTED
	assert(0);
}

double StructuredMeanFieldInference::MinimizeEnergy(
	std::vector<unsigned int>& state) {
	// NOT IMPLEMENTED
	assert(0);
	return (std::numeric_limits<double>::signaling_NaN());
}

}

max_stars_repo_name: pantonante/grante-bazel

max_issues_repo_name: pantonante/grante-bazel

max_forks_repo_name: pantonante/grante-bazel


text:
#include <iostream>
#include <iomanip>   // setpercision
#include <armadillo>
#include <vector>
#include <sys/stat.h>	//mkdir
#include <sys/types.h>	//mkdir
#include <string>

#include "Sto_IHT.h"
#include "Functions.h"
#include "Bayes_Sto_IHT.h"
#include "Parallel_AMP.h"

using namespace std;
using namespace arma;

// ---------------------------------------------------
// ---------------------------------------------------
// ----------- function: calculate metrics -----------
// ---------------------------------------------------
performance_metrics calculate_metrics(const vector<trial_info> MC_runs, const unsigned int max_iter){
	performance_metrics metrics;
	if (MC_runs.size() ==0 ){
		return metrics;
	}

	// calculate means
	metrics.time_avg = 0;
	metrics.iter_avg = 0;
	metrics.time_per_iter_avg = 0;
	metrics.success_avg = 0;
	for (unsigned int mc = 0; mc < MC_runs.size(); mc++){
		if (MC_runs[mc].time == -1){
			continue;
		}
		if (MC_runs[mc].iterations < max_iter){
			metrics.time_avg += MC_runs[mc].time;
			metrics.iter_avg += MC_runs[mc].iterations;
			metrics.time_per_iter_avg += MC_runs[mc].time/MC_runs[mc].iterations;
		}
		metrics.success_avg += double(MC_runs[mc].iterations < max_iter);
	}
	metrics.time_avg    = metrics.time_avg/MC_runs.size();
	metrics.iter_avg    = metrics.iter_avg/MC_runs.size();
	metrics.success_avg = metrics.success_avg/MC_runs.size();
	metrics.time_per_iter_avg    = metrics.time_per_iter_avg/MC_runs.size();

	// calculate standard deviations
	metrics.time_std = 0;
	metrics.iter_std = 0;
	metrics.success_std = 0;
	metrics.time_per_iter_std = 0;
	for (unsigned int mc = 0; mc < MC_runs.size(); mc++){
		if (MC_runs[mc].time == -1){
			continue;
		}
		if (MC_runs[mc].iterations < max_iter){
			metrics.time_std += pow(MC_runs[mc].time,2);
			metrics.iter_std += pow(MC_runs[mc].iterations,2) ;
			metrics.time_per_iter_std += pow(MC_runs[mc].time/MC_runs[mc].iterations,2) ;
		}
		metrics.success_std += pow(double(MC_runs[mc].iterations < max_iter),2);
	}
	metrics.time_std    = metrics.time_std/MC_runs.size();
	metrics.iter_std    = metrics.iter_std/MC_runs.size();
	metrics.success_std = metrics.success_std/MC_runs.size();
	metrics.time_per_iter_std    = metrics.time_per_iter_std/MC_runs.size();

	metrics.time_std    -= pow(metrics.time_avg,2);
	metrics.iter_std    -= pow(metrics.iter_avg,2);
	metrics.success_std -= pow(metrics.success_avg,2);
	metrics.time_per_iter_std    -= pow(metrics.time_per_iter_avg,2);

	metrics.time_std = sqrt(metrics.time_std);
	metrics.iter_std = sqrt(metrics.iter_std);
	metrics.time_per_iter_std = sqrt(metrics.time_per_iter_std);
	metrics.success_std = sqrt(metrics.success_std);
	return metrics;
}

// ---------------------------------------------------
// ---------------------------------------------------
// ----------- function: run_mc_trials ---------------
// ---------------------------------------------------
vector<performance_metrics> run_mc_trials(const vector <string> alg_names, const unsigned int sig_dim, const unsigned int sparsity, const unsigned int meas_num, const unsigned int max_iter, const double gamma, const double tol , const vec prob_vec, simulation_parameters simulation_params, const int num_mc_runs, const int SEED){

	vector<performance_metrics> MC_metrics;

	simulation_parameters simulation_params_non_parallel = simulation_params;
	simulation_params_non_parallel.num_cores = 1;

	// performance metrics for different methods in MC trials
    vector <vector<trial_info>> alg_infos(alg_names.size());

	for (int mc = 0; mc < num_mc_runs; mc++){
		if (SEED == -1){
			arma_rng::set_seed_random();
			srand(time(NULL));
		}else{
			arma_rng::set_seed(SEED);
			srand(SEED);
		}

		// Generate sparse signal
		vec support(sig_dim,fill::zeros);
		support(span(0,sparsity-1)).ones();
		random_shuffle(support.begin(),support.end());

		const vec x = support;				// Bernoulli signal

		// Generate Measurement matrix
		const mat A =normalise( randn(meas_num,sig_dim) );

		// compute measurements
		const vec y = A*x;

		double time;
		unsigned int num_iters;

        for (unsigned int alg = 0; alg < alg_names.size(); alg++) {
            if(alg_names[alg].compare("Bayesian Sto_IHT") == 0){
                // Solve in Parallel with Bayesian update rules
                time = omp_get_wtime();
                const vec x_hat_bayesian = bayesian_Sto_IHT(A, y, sparsity, prob_vec, max_iter, gamma, tol, num_iters, simulation_params);
                alg_infos[alg].push_back(trial_info(omp_get_wtime() - time,num_iters ));
            }
            else if(alg_names[alg].compare("Sto_IHT") == 0){
                // solve with non-parallel StoIHT
                time = omp_get_wtime();
                const vec x_hat = parallel_Sto_IHT(A, y, sparsity, prob_vec, max_iter, gamma, tol, num_iters, simulation_params_non_parallel);
                alg_infos[alg].push_back(trial_info(omp_get_wtime() - time,num_iters ));
            }
            else if(alg_names[alg].compare("Parallel Sto_IHT") == 0){
                // Solve with Parallel StoIHT
                time = omp_get_wtime();
                const vec x_hat_parallel = parallel_Sto_IHT(A, y, sparsity, prob_vec, max_iter, gamma, tol, num_iters, simulation_params);
                alg_infos[alg].push_back(trial_info(omp_get_wtime() - time,num_iters ));
            }
            else if(alg_names[alg].compare("Tally Sto_IHT") == 0){
                // Solve in Parallel with tally score
                time = omp_get_wtime();
                const vec x_hat_tally = tally_Sto_IHT(A, y, sparsity, prob_vec, max_iter, gamma, tol, num_iters, simulation_params);
                alg_infos[alg].push_back(trial_info(omp_get_wtime() - time,num_iters ));
            }
            else if(alg_names[alg].compare("AMP") == 0){
                // Solve with AMP
                time = omp_get_wtime();
                const vec x_hat_AMP = AMP(A, y, sparsity, max_iter, tol, num_iters,simulation_params);
                alg_infos[alg].push_back(trial_info(omp_get_wtime() - time,num_iters ));
            }
            else if(alg_names[alg].compare("Parallel AMP") == 0){
                // Solve with R_MP_AMP
                time = omp_get_wtime();
                const vec x_hat_R_MP_AMP = R_MP_AMP(A, y, sparsity, max_iter, tol, num_iters,simulation_params);
                alg_infos[alg].push_back(trial_info(omp_get_wtime() - time,num_iters ));
            }
            else{
                cout << "Unknown Algorithm name: " << alg_names[alg] << endl << endl;
                throw;
            }

        }
	}

    for (unsigned int alg = 0; alg < alg_names.size(); alg++) {
        MC_metrics.push_back(calculate_metrics(alg_infos[alg],max_iter));
    }
	return MC_metrics;
}

// ---------------------------------------------------
// ---------------------------------------------------
// ----------- function: set_slow_cores ---------
// ---------------------------------------------------
// NOTE: Thread #0 is never selected to be slow
// Because it is already performing extra calculation to check the convergence criteria
// This way it is easier to interpret the results
void set_slow_cores(uvec &slow_cores, const simulation_parameters simulation_params){
	vec cores(simulation_params.num_cores-1,fill::zeros);
	// generate slow core indices
	slow_cores.reset();
	if (simulation_params.num_slow_cores > 0){
		cores.zeros();
		cores(span(0,simulation_params.num_slow_cores-1)).ones();
		random_shuffle(cores.begin(),cores.end());
		slow_cores = find(cores!=0) + 1;
	}
	return;
}

// ---------------------------------------------------
// ---------------------------------------------------
// ----------- function: save_results ----------------
// ---------------------------------------------------
void save_results(const vector<string> alg_names, const vector <vector<performance_metrics>> sweep_metrics,
	const string parameter_to_sweep, const vec parameter_to_sweep_values,
	const unsigned int sig_dim, const unsigned int sparsity, const unsigned int meas_num,
	const unsigned int max_iter, simulation_parameters simulation_params, const int num_mc_runs){
	// create directory
	string dir = "../results";
	mkdir(dir.c_str(),0777);

	ofstream ofs;
	ofs.open (dir + "/simulation_env.txt", std::ofstream::out);
	ofs << "# of Processors Available: \t" << omp_get_num_procs() << endl << endl;
	ofs << "# of MC trials: \t" << num_mc_runs << endl << endl;
	ofs << "Signal Dimension: \t" << sig_dim << endl<<endl;
	ofs << "Sparsity: \t\t" << sparsity << endl<<endl;
	ofs << "# of measurements: \t" << meas_num << endl<<endl;
	ofs << "Max. # of Iters: \t" << max_iter << endl<<endl;
	ofs << "Percentage of Slow Cores: \t" << simulation_params.slow_cores_ratio * 100;
	ofs << " (each sleeping for " << simulation_params.sleep_slow_cores/1000 << " ms )" << endl<<endl;
	ofs << "Parameter to Sweep: " << parameter_to_sweep << ':' << endl;
	ofs << parameter_to_sweep_values.t() << endl;

	ofs.close();

	char delimiter = '\t';
	for (unsigned int i = 0; i < alg_names.size(); i++){
		if (sweep_metrics[0][i].time_avg < 0){
			continue;
		}
		ofs.open (dir + "/" + alg_names[i] + ".txt", std::ofstream::out);
		ofs << parameter_to_sweep << "\t time_avg\ttime_std\tsuccess_avg\tsuccess_std\ttime_per_iter_avg\ttime_per_iter_std\titer_avg\titer_std" << endl;
		for (unsigned int param = 0; param <parameter_to_sweep_values.n_elem; param++ ){
			ofs << parameter_to_sweep_values[param]         << delimiter
                << 1000* sweep_metrics[param][i].time_avg 	<< delimiter
				<< 1000* sweep_metrics[param][i].time_std 	<< delimiter
				<< sweep_metrics[param][i].success_avg 		<< delimiter
				<< sweep_metrics[param][i].success_std 		<< delimiter
				<< 1000* sweep_metrics[param][i].time_per_iter_avg  << delimiter
				<< 1000* sweep_metrics[param][i].time_per_iter_std  << delimiter
				<< sweep_metrics[param][i].iter_avg  		<< delimiter
				<< sweep_metrics[param][i].iter_std 		<< delimiter
				<< endl ;

		}
		ofs.close();

	}
}

// ---------------------------------------------------
// ---------------------------------------------------
// ----------- function: print_results----------------
// ---------------------------------------------------
void print_results(const vector<string> alg_names, const vector <vector<performance_metrics>> sweep_metrics,
	const string parameter_to_sweep, const vec parameter_to_sweep_values,
	const unsigned int sig_dim, const unsigned int sparsity, const unsigned int meas_num,
	const unsigned int max_iter, simulation_parameters simulation_params, const int num_mc_runs){
	cout << setprecision(5);
	string delimiter = "\t\t";
	cout << endl;
    cout << parameter_to_sweep << delimiter << "time_avg" << delimiter << "success_avg"
        << delimiter << "time/iter_avg"  << delimiter<< "iter_avg" << endl;
	for (unsigned int i = 0; i < alg_names.size(); i++){
		if (sweep_metrics[0][i].time_avg < 0){
			continue;
		}
		cout << alg_names[i] << ":" << endl;
		for (unsigned int param = 0; param <parameter_to_sweep_values.n_elem; param++ ){
			cout<< parameter_to_sweep_values[param]         << delimiter
                << 1000* sweep_metrics[param][i].time_avg 	<< delimiter
				<< sweep_metrics[param][i].success_avg 		<< delimiter
				<< 1000* sweep_metrics[param][i].time_per_iter_avg  << delimiter
				<< sweep_metrics[param][i].iter_avg  		<< delimiter
				<< endl ;

		}
		cout << endl;

	}
	cout << endl;
	cout << "NOTE: Zero (if any) means the success rate of the corresponding algorithm is zero." << endl;
	cout << "(increase maxIter, decrease sparsity, increase MC trials, ....)" << endl;
}

// ---------------------------------------------------
// ---------------------------------------------------
// ----------- function: run_experiments--------------
// ---------------------------------------------------
void run_experiments(const vector <string> alg_names, unsigned int sig_dim, unsigned int sparsity, unsigned int meas_num, const unsigned int max_iter, const double gamma, const double tol , const vec prob_vec, simulation_parameters simulation_params,
	 const int num_mc_runs, const int SEED){
	cout << setprecision(3);
    string parameter_to_sweep = "Cores";
    cout << " Parameter to Sweep: " << parameter_to_sweep << ':' << endl;

    vec parameter_to_sweep_values = floor(linspace(1,10,5));

    vector <vector<performance_metrics>> sweep_metrics(parameter_to_sweep_values.n_elem);

    for (unsigned int param = 0; param <parameter_to_sweep_values.n_elem; param++ ){
        simulation_params.num_cores = int(parameter_to_sweep_values[param]);
        simulation_params.num_slow_cores = int(simulation_params.slow_cores_ratio * simulation_params.num_cores);
        cout << simulation_params.num_cores << '\t' << flush;
        sweep_metrics[param] =  run_mc_trials(alg_names, sig_dim, sparsity, meas_num, max_iter, gamma, tol , prob_vec, simulation_params,  num_mc_runs,  SEED);
    }
    cout << endl;
    // Print/Save
    print_results(alg_names, sweep_metrics, parameter_to_sweep, parameter_to_sweep_values, sig_dim, sparsity,  meas_num, max_iter, simulation_params, num_mc_runs);
    save_results(alg_names, sweep_metrics, parameter_to_sweep, parameter_to_sweep_values, sig_dim, sparsity,  meas_num, max_iter, simulation_params, num_mc_runs);

	return;
}

max_stars_repo_name: LCWN-Lab/Parallel-Sparse-Recovery

max_issues_repo_name: LCWN-Lab/Parallel-Sparse-Recovery

max_forks_repo_name: LCWN-Lab/Parallel-Sparse-Recovery


text:
//
// Copyright (C) 2014, 2015 Ableton AG, Berlin. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//

/*!
 * @file
 */

#pragma once

#include <atria/meta/pack.hpp>
#include <atria/xform/any_state.hpp>
#include <atria/xform/with_state.hpp>
#include <atria/xform/state_wrapper.hpp>
#include <atria/xform/transducer_impl.hpp>
#include <atria/prelude/comp.hpp>

#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>

#include <functional>
#include <cassert>

namespace atria {
namespace xform {

namespace detail {

template <typename CompleteT,
          typename ReduceT>
struct transducer_tag
{
  using complete_t = CompleteT;
  using reduce_t   = ReduceT;
};

template <typename StateT,
          typename ReducingFnT,
          typename XformT,
          typename... OutputTs>
struct transducer_state
{
  template <typename WrappedT>
  struct make_state_wrapper
  {
    using xformed_t  = typename XformT::result_type;
    using reduce_t   = estd::decay_t<
      estd::result_of_t<ReducingFnT(StateT, OutputTs...)> >;
    using complete_t = estd::decay_t<
      decltype(state_complete(std::declval<reduce_t>()))>;
    using tag_t      = transducer_tag<complete_t, reduce_t >;
    using type       = state_wrapper<tag_t, WrappedT, xformed_t>;
  };

  using type = typename boost::mpl::eval_if<
      is_state_wrapper<StateT>,
      meta::identity<estd::decay_t<StateT> >,
      make_state_wrapper<any_state>
    >::type;
};

template <typename StateT,
          typename ReducingFnT,
          typename XformT,
          typename... OutputTs>
using transducer_state_t = typename transducer_state<
  StateT, ReducingFnT, XformT, OutputTs...>::type;

template <typename... OutputTs>
struct transducer_rf_gen
{
  template <typename TagT>
  struct from_any_state_rf_gen
  {
    template <typename ReducingFnT>
    struct apply
    {
      ReducingFnT step;

      template <typename ...InputTs>
      any_state operator() (any_state s, InputTs&& ...is)
      {
        using reduce_t   = typename TagT::reduce_t;
        using complete_t = typename TagT::complete_t;

        if (s.has<reduce_t>()) {
          auto next = step(std::move(s).as<reduce_t>(),
                           std::forward<InputTs>(is)...);
          s = std::move(next);
        } else if (s.has<complete_t>()) {
          auto next = step(std::move(s).as<complete_t>(),
                           std::forward<InputTs>(is)...);
          s = std::move(next);
        } else {
          assert(!"oops!");
        }
        return s;
      }
    };
  };

  template <typename TagT>
  using from_any_state = transducer_impl<from_any_state_rf_gen<TagT> >;

  template <typename ReducingFnT,
            typename XformT>
  struct apply
  {
    ReducingFnT step;
    XformT xform;

    template <typename StateT, typename... InputTs>
    auto operator() (StateT st, InputTs&& ...ins)
      -> transducer_state_t<StateT, ReducingFnT, XformT, OutputTs...>
    {
      using wrapped_t = transducer_state_t<
        StateT, ReducingFnT, XformT, OutputTs...>;
      using tag_t = typename wrapped_t::tag;

      return with_state(
        std::move(st),
        [&](StateT&& sst) {
          auto xformed = comp(xform, from_any_state<tag_t>{})(step);
          auto next = xformed(std::move(sst), std::forward<InputTs>(ins)...);
          return wrap_state<tag_t> (
            std::move(next),
            std::move(xformed));
        },
        [&](wrapped_t&& sst) {
          auto next = state_wrapper_data(sst)(
            std::move(state_unwrap(sst)),
            std::forward<InputTs>(ins)...);
          state_unwrap(sst) = std::move(next);
          return std::move(sst);
        });
    }
  };
};

template <typename C, typename R, typename T>
auto state_wrapper_complete(transducer_tag<C, R>, T&& wrapper) -> C
{
  return state_complete(state_unwrap(std::forward<T>(wrapper)))
    .template as<C>();
}

template <typename C, typename R, typename T>
auto state_wrapper_unwrap_all(transducer_tag<C, R>, T&& wrapper) -> C
{
  return state_unwrap_all(state_unwrap(std::forward<T>(wrapper)))
    .template as<C>();
}

template <typename C, typename R, typename T, typename U>
auto state_wrapper_rewrap(transducer_tag<C, R>, T&& s, U&& x)
  -> estd::decay_t<T>
{
  static_assert(std::is_same<estd::decay_t<U>, C>{} ||
                std::is_same<estd::decay_t<U>, any_state>{},
                "Yo! you are rewrapping with the wrong thing!");
  return wrap_state<transducer_tag<C, R> >(
    state_rewrap(state_unwrap(std::forward<T>(s)), std::forward<U>(x)),
    state_wrapper_data(std::forward<T>(s)));
}

template <typename... ArgTs>
struct reducing_function
{
  using type = std::function<any_state(any_state, ArgTs...)>;
};

template <typename InputT, typename OutputT>
using transducer_function_t = std::function<
  meta::unpack_t<reducing_function, InputT> (
    meta::unpack_t<reducing_function, OutputT>)>;

} // namespace detail

/*!
 * Type erased transducer.
 *
 * This allows to store transducers in places where the full type can
 * not be known at compile time.  The `InputT` template argument is
 * the type of the input over which you may apply the transducer.
 * For example:
 *
 * @code{.cpp}
 * transducer<int> filter_odd = filter([] (int x) {
 *     return x % 2;
 * });
 * @endcode
 *
 * A second template argument can be passed to indicate the type of
 * data after running through the transducer.  By default, it's the
 * same as the input.
 *
 * @code{.cpp}
 * transducer<int, std::string> serialize = map([] (int x) {
 *     return std::to_string(x);
 * });
 * @endcode
 *
 * Both the first or second template arguments can take a
 * `meta::pack<>` when it can take or pass more than one input type.
 *
 * @code{.cpp}
 * transducer<pack<int, int>, float> serialize = map([] (int a, int b) {
 *     return float(a) / float(b);
 * });
 * @endcode
 *
 * @note Type erased transducers have a performance cost.  Not only is
 *       it slower to pass them around, they are significantly slower
 *       when processing the sequence.  For such, use them when really
 *       needed, and otherwise use `auto` and templates to avoid
 *       erasing the types of the transducers.
 *
 * @note A type erased transducer actually defers applying the held
 *       transducer until it first runs through a sequence, as
 *       ilustrated by this example:
 *
 *       @code{.cpp}
 *       transducer<int> filter_odd = [](auto step) {
 *           std::cout << "Building step" << std::endl;
 *           return [](auto st, int x) {
 *               return x % 2 ? step(st, x) : st;
 *           };
 *       };
 *
 *       // Doesn't print anything
 *       auto step = filter_odd(std::plus<>{});
 *
 *       // Now it prints
 *       auto sum = reduce(step, 0, {1, 2, 3})
 *       @endcode
 */
template <typename InputT=meta::pack<>, typename OutputT=InputT>
using transducer = transducer_impl<
  meta::unpack<detail::transducer_rf_gen, OutputT>,
  detail::transducer_function_t<InputT, OutputT> >;

} // namespace xform
} // namespace atria

ext: hpp

max_issues_repo_name: Ableton/atria


text:
// @COPYRIGHT@
// Licensed under MIT license (LICENSE.txt)

// clxx/app/options/option_value.hpp

/** // doc: clxx/app/options/option_value.hpp {{{
 * \file clxx/app/options/option_value.hpp
 * \brief Defines the \ref clxx::app::options::option_value class
 */ // }}}
#ifndef CLXX_APP_OPTIONS_OPTION_VALUE_HPP_INCLUDED
#define CLXX_APP_OPTIONS_OPTION_VALUE_HPP_INCLUDED

#include <boost/program_options/value_semantic.hpp>

/** // doc: BOOST_PROGRAM_OPTIONS_NEED_VALUE_NAME_FIX {{{
 * \brief Whether to use a workaround for missing
 *    boost::program_options::typed_value<T,CharT>::value_name()
 *
 * Older versions of Boost.Program_Options were missing the
 * boost::program_options::typed_value<T,CharT>::name() and
 * boost::program_options::typed_value<T,CharT>::value_name() methods.
 * For those versions, we provide special workaround, that is we implement
 * these methods in our subclass clxx::app::options::option_value.
 *
 * This constant decides, whether this workaround should be enabled or not.
 */ // }}}
#define BOOST_PROGRAM_OPTIONS_NEED_VALUE_NAME_FIX 1
// FIXME: I'm not sure, in which version of Boost.ProgramOptions the member
// function boost::program_options::typed_value<T,charT>::value_name()'
// will be implemented (it's already in svn, but ...). When it will be clear,
// just uncomment following lines (replacing 2 with correct version number):
/* #include <boost/program_options/version.hpp>
 * #define BOOST_PROGRAM_OPTIONS_NEED_VALUE_NAME_FIX \
 *   (BOOST_PROGRAM_OPTIONS_VERSION <= 2) */

/** \cond SHOW_IGNORED_COMPOUNDS */
#if BOOST_PROGRAM_OPTIONS_NEED_VALUE_NAME_FIX
namespace boost { namespace program_options {
extern BOOST_PROGRAM_OPTIONS_DECL std::string arg;
}}
#endif
/** \endcond */

namespace clxx { namespace app { namespace options {

/** // doc: class option_value {{{
 * \brief Single option value
 *
 * The option_value object encapsuates the actual value and also has a name.
 */ // }}}
template <class T, class charT = char>
class option_value
  : public boost::program_options::typed_value<T, charT>
{
public:
  /** // doc: ~option_value() {{{
   * \brief Destructor
   */ // }}}
  virtual ~option_value()
  {
  }

  /** // doc: option_value(...) {{{
   * \brief Constructor
   */ // }}}
  option_value(T* store_to)
    : boost::program_options::typed_value<T,charT>(store_to)
  {
  }

#if BOOST_PROGRAM_OPTIONS_NEED_VALUE_NAME_FIX
  /** // doc: foo() {{{
   * \brief Returns option value's name
   */ // }}}
  std::string name( ) const;

  /** // doc: value_name(n) {{{
   * \brief Sets option value's name
   *
   * \param n The new name
   * \returns Pointer to this object
   */ // }}}
  option_value* value_name(std::string const& n)
  {
    this->_value_name = n;
    return this;
  }
#endif

private:
#if BOOST_PROGRAM_OPTIONS_NEED_VALUE_NAME_FIX
  std::string _value_name;
#endif
};

/** // doc: value(v) {{{
 * \brief Generate \ref option_value wrapper for value of type T
 * \tparam T Type of the underlying value
 * \param v Pointer to the variable being wrapped with the option_value object.
 * \returns A pointer to newly allocated \ref option_value object. The returned
 *    value is allocated with the \c new operator.
 */ // }}}
template<class T>
option_value<T>*
value(T* v)
{
  option_value<T> *r = new option_value<T>(v);
  return r;
}

/** // doc: value() {{{
 * \brief Generate \ref option_value object wrapping \c nullptr.
 * \tparam T Type of the underlying value
 * \returns A pointer to new \ref option_value object.
 */ // }}}
template<class T>
option_value<T>*
value()
{
  return clxx::app::options::value<T>(nullptr);
}

/** // doc: wvalue(v) {{{
 * \brief Generate \ref option_value wrapper for value of type T
 * \tparam T Type of the underlying value
 *
 * The returned option_value object uses \c wchar_t string to represent its
 * name.
 *
 * \param v Pointer to the variable being wrapped with the option_value object.
 * \returns A pointer to newly allocated \ref option_value object. The returned
 *    value is allocated with the \c new operator.
 */ // }}}
template<class T>
option_value<T, wchar_t>*
wvalue(T* v)
{
  option_value<T,wchar_t>* r = new option_value<T,wchar_t>(v);
  return r;
}

/** // doc: wvalue() {{{
 * \brief Generate \ref option_value object wrapping \c nullptr.
 *
 * The returned option_value object uses \c wchar_t string to represent its
 * name.
 *
 * \tparam T Type of the underlying value
 * \returns A pointer to new \ref option_value object.
 */ // }}}
template<class T>
option_value<T, wchar_t>*
wvalue()
{
  return clxx::app::options::wvalue<T>(0);
}

/** // doc: bool_switch(v) {{{
 * \brief Generate \ref option_value object wrapping a boolean value
 * \param v Pointer to the variable being wrapped with the new \ref
 *    option_value object.
 * \returns A pointer newly created option_value object. The object is
 *    allocated with the operator \c new.
 */ // }}}
BOOST_PROGRAM_OPTIONS_DECL inline option_value<bool>*
bool_switch(bool* v)
{
  option_value<bool>* r = new option_value<bool>(v);
  r->default_value(0);
  r->zero_tokens();

  return r;
}

/** // doc: bool_switch() {{{
 * \brief Generate \ref option_value object wrapping \c nullptr.
 * \tparam T Type of the underlying value
 * \returns A pointer to new \ref option_value object.
 */ // }}}
BOOST_PROGRAM_OPTIONS_DECL inline option_value<bool>*
bool_switch()
{
  return bool_switch(0);
}

#if BOOST_PROGRAM_OPTIONS_NEED_VALUE_NAME_FIX
template<class T, class charT>
std::string option_value<T, charT>::
name() const
{
  using std::string;
  string my_name(boost::program_options::typed_value<T,charT>::name());
  if(!this->_value_name.empty())
    {
      // Ugly fix. I hope, that BOOST > 1.49 will implement "value_name" on its
      // own. The code is based on reverse engineering of name() implementation
      // found in boost/program_options/detail/value_semantic.hpp (ver. 1.49).
      size_t pos;
      using boost::program_options::arg;
      string pattern("[=arg(=");
      pos = my_name.find(pattern);
      if(pos != string::npos)
        {
          string replacement(string("[=") + this->_value_name + string("(="));
          my_name.replace(pos,pattern.length(),replacement);
        }
      pos = my_name.find(arg);
      if(pos != string::npos)
        {
          my_name.replace(pos,arg.length(),this->_value_name);
        }
    }
  return my_name;
}
#endif
} } } // end namespace clxx::app::options
#endif /* CLXX_APP_OPTIONS_OPTION_VALUE_HPP_INCLUDED */
// vim: set expandtab tabstop=2 shiftwidth=2:
// vim: set foldmethod=marker foldcolumn=4:

max_stars_repo_name: ptomulik/clxx

max_issues_repo_name: ptomulik/clxx

max_forks_repo_name: ptomulik/clxx


text:
// Copyright (c) 2014-2017 Jae-jun Kang
// See the file LICENSE for details.

#ifndef X2BOOST_XPILER_PROGRAM_HPP_
#define X2BOOST_XPILER_PROGRAM_HPP_

#ifndef X2BOOST_XPILER_PRE_HPP_
#include "pre.hpp"
#endif

#include <map>

#include <boost/filesystem.hpp>

#include "formatter.hpp"
#include "handler.hpp"
#include "options.hpp"

namespace xpiler
{
    class program
    {
    public:
        typedef std::map<std::string, handler*> handler_map_type;
        typedef std::map<std::string, formatter*> formatter_map_type;

        program();

        void process(const std::string& path);

        static const formatter_map_type& formatters() { return formatters_; }

        static options opts;

        bool error;

    private:
        void process_dir(const boost::filesystem::path& path);
        void process_file(const boost::filesystem::path& path);

        static handler_map_type handlers_;
        static formatter_map_type formatters_;

        struct static_initializer
        {
            static_initializer();
            ~static_initializer();
        };
        static static_initializer static_init_;

        formatter* formatter_;
        std::vector<std::string> sub_dirs_;
    };
}

#endif  // X2BOOST_XPILER_PROGRAM_HPP_


text:
// __COPYRIGHT_START__
// Package Name : efscape
// File Name : RunServer.cpp
// Copyright (C) 2006-2019 Jon C. Cline
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
// RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
// CONTRACT, NEGLIGENCE OR// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
// __COPYRIGHT_END__

#include "RunServer.hpp"

#include <Ice/Ice.h>  // need Ice definitions

// ModelHome servant definition
#include "ModelHomeI.hpp"

// definitions for accessing the model factory
#include <efscape/impl/ModelHomeI.hpp>
#include <efscape/impl/ModelHomeSingleton.hpp>

// definitions for access the local file system
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/operations.hpp>

namespace fs = boost::filesystem;

namespace efscape {

namespace server {

// class variables
const char* RunServer::mScp_program_name = "efserver";
const char* RunServer::mScp_program_version = "version 2.0.0 (2019/08/18)";

/** default constructor */
RunServer::RunServer() {}

/** destructor */
RunServer::~RunServer() {}

/**
 * Returns the program name
 *
 * @returns the program name
 */
const char* RunServer::program_name() { return RunServer::mScp_program_name; }

/**
 * Returns the program name (class version)
 *
 * @returns the program name
 */
const char* RunServer::ProgramName() { return RunServer::mScp_program_name; }

/**
 * Returns the program version.
 *
 * @returns the program version
 */
const char* RunServer::program_version() {
  return RunServer::mScp_program_version;
}

/**
 * Executes the RunServer command
 *
 * @returns exit state
 */
int RunServer::execute() {
  int status = EXIT_SUCCESS;

  //----------------------------------------------
  // create a root model from the model repository
  //----------------------------------------------
  try {
    if (debug_on()) {
      // note (2008.06.05):
      // The default debug setting is not working.
      impl::ModelHomeI::getLogger()->setLevel(log4cxx::Level::getDebug());
    } else {
      impl::ModelHomeI::getLogger()->setLevel(log4cxx::Level::getError());
    }

    LOG4CXX_DEBUG(impl::ModelHomeI::getLogger(), "Loading libraries");
    impl::Singleton<impl::ModelHomeI>::Instance().LoadLibraries();

    //----------------------
    // launch the ICE server
    //----------------------
    // attempt to retrieve the root directory of efscape ICE configuration
    std::string lC_EfscapeIcePath = ".";  // default location
    char* lcp_env_variable =              // get EFSCAPE_HOME
        getenv("EFSCAPE_HOME");

    if (lcp_env_variable != 0) lC_EfscapeIcePath = lcp_env_variable;

    fs::path lC_iceConfigPath =
        fs::path(lC_EfscapeIcePath) / fs::path("config.server");

    LOG4CXX_DEBUG(
        efscape::impl::ModelHomeI::getLogger(),
        "efscape ICE server config=<" << lC_iceConfigPath.string() << ">");

    // provide command-line arguments
    int argc = 1;
    char** argv = new char*[argc * sizeof(char*)];
    argv[0] = new char[std::string(program_name()).size() + 1];
    strcpy(argv[0], program_name());

    //
    // CtrlCHandler must be created before the communicator or any other
    // threads are started
    //
    Ice::CtrlCHandler ctrlCHandler;

    //
    // CommunicatorHolder's ctor initializes an Ice communicator,
    // and its dtor destroys this communicator.
    //
    Ice::CommunicatorHolder ich(argc, argv, "config.server");
    auto communicator = ich.communicator();

    ctrlCHandler.setCallback([communicator](int) { communicator->shutdown(); });

    auto adapter = communicator->createObjectAdapter("ModelHome");
    adapter->add(std::make_shared<ModelHomeI>(),
                 Ice::stringToIdentity("ModelHome"));
    adapter->activate();

    communicator->waitForShutdown();

    // this->main(argc, argv, lC_iceConfigPath.string().c_str());

    // delete argv (no longer needed)
    for (int i = 0; i < argc; i++) {
      delete[] argv[i];
    }
    delete[] argv;

  } catch (const std::logic_error& lC_excp) {
    LOG4CXX_ERROR(impl::ModelHomeI::getLogger(), lC_excp.what());
    return EXIT_FAILURE;
  } catch (const std::exception& lC_excp) {
    LOG4CXX_ERROR(impl::ModelHomeI::getLogger(), lC_excp.what());
    return EXIT_FAILURE;
  } catch (...) {
    LOG4CXX_ERROR(impl::ModelHomeI::getLogger(),
                  "Error occurred parsing argument <" << (*this)[0] << ">");
  }
  return EXIT_SUCCESS;

}  // RunServer::execute()

/**
 * Parses the command line arguements and initializes the command
 * configuration.
 *
 * @param argc number of command line arguments
 * @param argv vector of command line arguments
 * @returns exit status
 */
int RunServer::parse_options(int argc, char* argv[]) {
  int li_status = CommandOpt::parse_options(argc, argv);  // parent method
  if (li_status != 0) return li_status;

  if (files() > 1) {
    usage();
    return 1;
  }

  return li_status;
}

/**
 * Prints out usage message for this command/program
 *
 * @args  exit_value exit value
 */
void RunServer::usage(int exit_value) {
  std::cerr << "usage:\n"
            << program_name() << " "
            << "[-d] [-h] [-v] \n\t"
            << "[[-i] input_files]\n\t"
            << "[-o output_file]\n\t"
            << "[class_name] param_name\n\n"
            << "where [] indicates optional option:\n\n"
            << mC_description << "examples:\n\t\t" << program_name() << "\n\t\t"
            << program_name() << " -d -o logfile_name\n\n";

  exit(exit_value);
}

//================================
// end of RunServer implementation
//================================

const bool registered = impl::Singleton<impl::ModelHomeI>::Instance()
                            .getCommandFactory()
                            .registerType<RunServer>(RunServer::ProgramName());

}  // namespace server

}  // namespace efscape

max_stars_repo_name: clinejc/efscape

max_issues_repo_name: clinejc/efscape

max_forks_repo_name: clinejc/efscape


text:
#include "nano_socket.h"

#include <nn.h>
#include <pubsub.h>

#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/zlib.hpp>

#include <iostream>

namespace ios = boost::iostreams;

namespace kluster
{
  namespace transport
  {

    NanoSocket::NanoSocket(int socketType) throw()
    {
      m_socket = nn_socket(AF_SP, socketType);
      if (m_socket < 0)
       throw NanoException{};

      std::cout << "Created socket " << m_socket << ", type " << socketType << std::endl;
    }

    NanoSocket::~NanoSocket()
    {
      nn_shutdown(m_socket, 0);
    }

    void NanoSocket::Bind(const std::string& address) throw()
    {
      if (nn_bind(m_socket, address.c_str()) < 0)
        throw NanoException{};
    }

    void NanoSocket::Connect(const std::string& address) throw()
    {
      if (nn_connect(m_socket, address.c_str()) < 0)
        throw NanoException{};
    }

    void NanoSocket::Send(const NanoMessage& message) throw()
    {
      std::stringstream data;
      data << NanoMessage::SaveMessage(message);

      ios::filtering_streambuf<ios::input> compressor;
      compressor.push(ios::zlib_compressor());
      compressor.push(data);

      std::stringstream compressed;
      ios::copy(compressor, compressed);

      const std::string compressedData = compressed.str();

      std::cout << "Socket " << m_socket << ": "
       << "Sending message type " << message.header.type << ", size " << compressedData.size() << std::endl;
      if (nn_send(m_socket, compressedData.data(), compressedData.size(), 0) < 0)
        throw NanoException{};
    }

    NanoMessage NanoSocket::Recv() throw()
    {
      char *buf = NULL;
      int size = nn_recv (m_socket, &buf, NN_MSG, 0);
      if (size < 0)
      {
        throw NanoException{};
      }

      std::stringstream compressed;
      compressed.write(buf, size);
      nn_freemsg (buf);

      ios::filtering_streambuf<ios::input> decompressor;
      decompressor.push(ios::zlib_decompressor());
      decompressor.push(compressed);

      std::stringstream decompressed;
      ios::copy(decompressor, decompressed);

      NanoMessage nm = NanoMessage::LoadMessage(decompressed.str());
      std::cout << "Socket " << m_socket << ": "
        << "got message type " << nm.header.type << std::endl;
      return nm;
    }

    void NanoSocket::SetSubscription(const std::string& sub) throw()
    {
      if (nn_setsockopt (m_socket, NN_SUB, NN_SUB_SUBSCRIBE, sub.c_str(), 0) < 0)
      {
        throw NanoException{};
      }
    }

    std::pair<int, boost::optional<NanoMessage>> NanoSocket::Poll(NanoSocket **sockets, size_t len, std::chrono::milliseconds timeout) throw()
    {
      std::vector<nn_pollfd> pfds;

      std::stringstream trace;
      trace << "Polling [ ";
      for (size_t i=0; i<len; ++i)
      {
        nn_pollfd pfd;
        pfd.fd = sockets[i]->m_socket;
        pfd.events = NN_POLLIN;
        pfds.push_back(pfd);
        trace << pfd.fd << " ";
      }

      std::cout << trace.str() << "]" << std::endl;

      boost::optional<NanoMessage> message;
      int rc = nn_poll(&pfds[0], len, -1);

      if (rc == -1) {
          throw NanoException();
      }

      int socketIndex = -1;
      if (rc > 0)
      {
        for (size_t i=0; i<len; ++i)
        {
          if (pfds[i].revents & NN_POLLIN)
          {
            socketIndex = i;
            break;
          }
        }
      }

      if (socketIndex >= 0)
      {
        message = sockets[socketIndex]->Recv();
      }

      return std::make_pair(socketIndex, message);
    }
  }
}

max_stars_repo_name: variar/kluster

max_issues_repo_name: variar/kluster

max_forks_repo_name: variar/kluster


text:
#include "IfSearch.h"

#include <QDir>
#include <QFileSystemWatcher>
#include <QStringList>
#include <QTimer>

#include <EigenFace.h>
#include <EigenFaceGenerator.h>
#include <EigenFaceFace.h>
#include <EigenFaceTemplate.h>
#include <EigenFaceSearchResultList.h>
#include <FaceBase.h>
#include <FileWriteProfile.h>
#include <ImageCache.h>
#include <InfoMacros.h>
#include <InputHotdir.h>
#include <Return.h>
#include <Settings.h>

void IfSearch::doAuthenticate(void)
{
    if (ffdBusy)
    {
        INFO("[SEARCH] ffdBusy");
        if (--searchTimeout)
            return searchError("Timeout");
        QTimer::singleShot(100, this, SLOT(doAuthenticate()));
        return;
    }
    searchResults.clear();
    authConfidence = -1;
    authUpdate = 0;
    appSettings->setValue("Search/Results", searchResults);
    appSettings->setValue("Search/Reason", QString());
    appSettings->setValue("Search/Confidence", authConfidence = 0);
    searchPersonKey = appSettings->value("Search/PersonKey", 0).toInt();
    searchPersonId = appSettings->value("Search/PersonId", QString()).toString();
    PROGRESS("[SEARCH] Started for Authenticate: %1 #%2", searchPersonId, searchPersonKey);

    searchTemplate.clear();
    appSettings->setValue("Search/Status", "Checking FaceBase");
    if ( ! faceBase)
        return searchError("No FaceBase");

    if (searchPersonKey)
    {
        searchPersonId = faceBase->personId(searchPersonKey);
        if (searchPersonId.isEmpty())
            return searchError(tr("PersonKey %1 does not exist").arg(searchPersonKey));
    }
    else
    {
        if (searchPersonId.isEmpty())
            return searchError(tr("PersonId or PersonKey must be specified for Authenticate"));
        searchPersonKey = faceBase->personKey(searchPersonId);
        if ( ! searchPersonKey)
            return searchError(tr("PersonId %1 does not exist").arg(searchPersonId));
    }

    NULLPTR(appSettings); NULLPTR(writer);
    QStringList qsl;

    appSettings->setValue("Search/Status", "Scanning Directory");
    QString dirName = appSettings->value("Search/InputDir", "../Search").toString();
    if (dirName.isEmpty())
        return searchError("Search/InputDir is empty");

    searchDir = writer->baseDir();
    if ( ! searchDir.cd(dirName))
        return searchError(tr("Can't cd to %1").arg(dirName));
    searchPending = searchDir.entryList(QDir::Files);
    authWatcher = new QFileSystemWatcher(QStringList() << searchDir.absolutePath(), this);
    connect(authWatcher, SIGNAL(directoryChanged(QString)),
            this, SLOT(authDirChange(QString)));

    searchResults = tr("Authenticating %1:%2").arg(searchPersonKey).arg(searchPersonId);
    appSettings->setValue("Search/Status", "Collecting");

    int toMsec = appSettings->value("Search/AuthTimeout", 5000).toInt();
    QTimer::singleShot(toMsec, this, SLOT(authFinished()));
    QTimer::singleShot(10, this, SLOT(tryAuthenticate()));
} // doAuthenticate()

void IfSearch::authDirChange(QString path)
{
    searchPending = searchDir.entryList(QDir::Files);
    if ( ! searchTemplate.isEmpty() && searchPending.isEmpty())
    {
        searchResults += resultsDelimiter + "Cancelled";
        authFinished();
    }
    else
        QTimer::singleShot(10, this, SLOT(tryAuthenticate()));
}

void IfSearch::tryAuthenticate(void)
{
    foreach (QString id, searchTemplate.idList())
    {
        if (searchPending.contains(id))
            searchPending.removeAll(id);
        else
        {
            searchTemplate.removeById(id);
            searchResults += resultsDelimiter + tr("%1 Removed").arg(id);
        }
    }

    foreach (QString fileName, searchPending)
    {
        EigenFaceTemplate tpl;
        Return rtn = tpl.read(searchDir.absoluteFilePath(fileName));
        if (rtn.isError()) return searchError(rtn.toString());
        tpl.setVectorId(fileName);
        searchTemplate.add(tpl);
        searchResults += resultsDelimiter + tr("%1 Active").arg(fileName);
    }

    int minFaces = appSettings->value("Search/AuthMinFaces", 3).toInt();
    int maxFaces = appSettings->value("Search/AuthMaxFaces", 10).toInt();
    int passConfidence = appSettings->value("Search/AuthPassConfidence", 850).toInt();
    if (searchTemplate.size() >= minFaces)
    {
        QList<int> faceKeys = faceBase->personFaceKeys(searchPersonKey);
        EigenFaceSearchResultList resList
                = eigenMatcher->search(EigenFaceSearchSettings::Authenticate,
                                       searchTemplate,
                                       &searchSettings,
                                       faceKeys);
        authConfidence = resList.bestConfidence();
        searchResults += resultsDelimiter + tr("Confidence=%1").arg(authConfidence);
        appSettings->setValue("Search/Confidence", authConfidence);
        appSettings->setValue("Search/Status", tr("Update %1").arg(++authUpdate));
        if (authConfidence >= passConfidence)
        {
            searchResults += resultsDelimiter + "Pass";
            authFinished();
        }
        if (searchTemplate.size() >= maxFaces)
        {
            searchResults += resultsDelimiter + "MaxFaces";
            authFinished();
        }
    }
}

void IfSearch::authFinished(void)
{
    delete authWatcher;
    authWatcher = 0;
    int failConfidence = appSettings->value("Search/AuthFailConfidence", 600).toInt();
    int passConfidence = appSettings->value("Search/AuthPassConfidence", 850).toInt();
    if (authConfidence < failConfidence)
        appSettings->setValue("Search/Authenticate", "Fail");
    else if (authConfidence >= passConfidence)
        appSettings->setValue("Search/Authenticate", "Pass");
    else
        appSettings->setValue("Search/Authenticate", "Maybe");
    return searchFinish();
}


text:
#ifndef CANARD_NET_OFP_DATA_TYPE_HPP
#define CANARD_NET_OFP_DATA_TYPE_HPP

#include <cstdint>
#include <algorithm>
#include <iterator>
#include <limits>
#include <stdexcept>
#include <boost/container/container_fwd.hpp>
#include <boost/container/vector.hpp>

namespace canard {
namespace net {
namespace ofp {

  using data_type = boost::container::vector<std::uint8_t>;

  namespace data_type_detail {

    template <class Iterator>
    auto decode_data(Iterator& first, std::size_t const data_length)
      -> data_type
    {
      auto data = data_type{data_length, boost::container::default_init};
      auto const last = std::next(first, data_length);
      std::copy(first, last, data.data());
      first = last;
      return data;
    }

  } // namespace data_type_detail

  using data_type_detail::decode_data;

  inline auto calc_ofp_length(
      data_type const& data, std::uint16_t const base_length)
    -> std::uint16_t
  {
    auto const max_length
      = std::uint16_t(std::numeric_limits<std::uint16_t>::max() - base_length);
    if (data.size() > max_length) {
      throw std::runtime_error{"too large data length"};
    }
    return base_length + data.size();
  }

} // namespace ofp
} // namespace net
} // namespace canard

#endif // CANARD_NET_OFP_DATA_TYPE_HPP


text:
#include <iostream>
#include "conditional_moment_ineq.h"
#include <Eigen/Dense>
using namespace std;
using namespace conditional_moment_inequality;

using Mat = Eigen::Matrix<FLOAT, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>;
using Vec = Eigen::Matrix<FLOAT, Eigen::Dynamic, 1>;

template<typename T>
void
apply(Mat& M, T& f)
{
    FLOAT* M_ptr = M.data();
    UInt   n_M   = M.size();

    for (UInt i = 0; i < n_M; ++i)
    {
        M_ptr[i] = f(M_ptr[i]);
    }
}

// randn
inline void
randn(Mat& M, std::mt19937& rng)
{
    std::normal_distribution<double> normal_dist(0, 1);

    auto f = [&rng, &normal_dist](FLOAT x) { return normal_dist(rng); };
    apply(M, f);
}

int main()
{
    mt19937 rng(1000);
    if (sizeof(FLOAT) == 4)
    {
        cout << "runing with 32-bit float" << endl;
    }
    if (sizeof(FLOAT) == 8) cout << "runing with 64-bit FLOAT" << endl;

    int sample_size = 1000;
    Mat M(sample_size, 4);
    randn(M, rng);

    vector<FLOAT *> X(3);
    for (auto & x : X)
    {
        x = new FLOAT[sample_size];
        std::normal_distribution<double> normal_dist(0, 1);
        for (UInt i = 0; i < sample_size; ++i) x[i] = normal_dist(rng);
    }

    // Test true parameter
    cout << "Test true parameter: " << endl;
    Conditional_Moment_Ineq ineq(sample_size, 0.05, Conditional_Moment_Ineq::KS_S1);
    vector<int> sign(M.cols(), 0);
    ineq.set_cond_M(M.data(), M.cols(), sign.data());
    ineq.set_instruments(X, M.cols());

    bool test_result = ineq.inference();
    if (test_result)
    {
        cout << "the moment model is accepted." << endl;
    }
    else
    {
        cout << "the moment model is rejected." << endl;
    }

    // Test wrong parameter
    cout << "Test wrong parameter: " << endl;
    Mat M_wrong = M;
    M_wrong.col(0).array() -= 0.2;
    sign[0] = 1;
    ineq.set_cond_M(M_wrong.data(), M_wrong.cols(), sign.data());
    test_result = ineq.inference();
    if (test_result)
    {
        cout << "the moment model is accepted." << endl;
    }
    else
    {
        cout << "the moment model is rejected." << endl;
    }

    for (auto & x : X)
    {
        delete [] x;
    }
    return 0;
}

max_stars_repo_name: lixiong-li/GPU-CMI

max_issues_repo_name: lixiong-li/GPU-CMI

max_forks_repo_name: lixiong-li/GPU-CMI


text:
#include "web_client_ssl.h"

#include <iostream>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/stream.hpp>

WebClientSsl::WebClientSsl(boost::asio::io_context& ioc, boost::asio::ssl::context& ctx) :
    resolver_(ioc),
    stream_(ioc, ctx),
    logger_(Logger::get(("WebClientSsl.") + std::to_string(reinterpret_cast<uint64_t>(this))))
{
    logger_->trace("WebClientSsl()");
}

WebClientSsl::~WebClientSsl()
{
    logger_->trace("~WebClientSsl()");
}

void WebClientSsl::fail(boost::system::error_code ec, char const* what)
{
    if (errorCb_)
        errorCb_(ec, what);
}

void WebClientSsl::run(const std::string& host, const std::string& port, const std::string& target, boost::beast::http::verb method,
         const std::string& accept,
         const std::string& contentType,
         const std::string& body,
         WebClient::ResponseCb responseCb, WebClient::ErrorCb errorCb)
{
    logger_->debug("run: host:{} port:{} target:{} method:{} accept:{} contentType:{} body.size:{}",
                   host, port, target, boost::beast::http::to_string(method), accept, contentType, body.size());

    // clear info from previous run
    req_ = WebClient::Request();
    res_ = WebClient::Response();

    responseCb_ = responseCb;
    errorCb_ = errorCb;
    const int version = 11; // HTTP "1.1"

    // Set SNI Hostname (many hosts need this to handshake successfully)
    if(!SSL_set_tlsext_host_name(stream_.native_handle(), host.c_str()))
    {
        boost::system::error_code ec { static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category() };
        logger_->error("run: SSL_set_tlsext_host_name failed: {}", ec.message());
        return;
    }

    req_.version(version);
    req_.method(method);
    req_.target(target);
    req_.set(boost::beast::http::field::accept, accept);
    if (!body.empty())
    {
        req_.body() = body;
        req_.set(boost::beast::http::field::content_type, contentType);
        req_.set(boost::beast::http::field::content_length, body.size());
    }
    req_.set(boost::beast::http::field::host, host);
    req_.set(boost::beast::http::field::user_agent, BOOST_BEAST_VERSION_STRING);

    // Look up the domain name
    resolver_.async_resolve(host, port,
                std::bind(
                    &WebClientSsl::on_resolve,
                    shared_from_this(),
                    std::placeholders::_1,
                    std::placeholders::_2));
}

void WebClientSsl::run(const std::string& host, const std::string& port, const std::string& target, boost::beast::http::verb method,
         const std::string& acceptType,
         WebClient::ResponseCb responseCb, WebClient::ErrorCb errorCb)
{
    return run(host, port, target, method, acceptType, "", "", responseCb, errorCb);
}

void WebClientSsl::stop()
{
    logger_->debug("stop()");
    boost::system::error_code ec;
#warning "TODO ; SSL Client stop()"
#if 0
    socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
    socket_.close(ec);
#endif
}

void WebClientSsl::on_resolve(boost::system::error_code ec, boost::asio::ip::tcp::resolver::results_type results)
{
    logger_->trace("on_resolve: {}", ec.message());

    if (ec)
    {
        logger_->error("on_resolve: {}", ec.message());
        return fail(ec, "resolve");
    }

    // Make the connection on the IP address we get from a lookup
    boost::asio::async_connect(
                stream_.next_layer(),
                results.begin(),
                results.end(),
                std::bind(
                    &WebClientSsl::on_connect,
                    shared_from_this(),
                    std::placeholders::_1));
}

void WebClientSsl::on_connect(boost::system::error_code ec)
{
    logger_->trace("on_connect: {}", ec.message());

    if (ec)
    {
        logger_->error("on_connect: {}", ec.message());
        return fail(ec, "connect");
    }

    // Perform the SSL handshake
    stream_.async_handshake(
                boost::asio::ssl::stream_base::client,
                std::bind(
                    &WebClientSsl::on_handshake,
                    shared_from_this(),
                    std::placeholders::_1));
}

void WebClientSsl::on_handshake(boost::system::error_code ec)
{
    logger_->trace("on_handshake: {}", ec.message());

    if (ec)
    {
        logger_->error("on_handshake: {}", ec.message());
        return fail(ec, "handshake");
    }

    // Send the HTTP request to the remote host
    boost::beast::http::async_write(stream_, req_,
                      std::bind(
                          &WebClientSsl::on_write,
                          shared_from_this(),
                          std::placeholders::_1,
                          std::placeholders::_2));
}

void WebClientSsl::on_write(boost::system::error_code ec, std::size_t bytes_transferred)
{
    logger_->trace("on_write: ec:{} bytes:{}", ec.message(), bytes_transferred);

    if (ec)
    {
        logger_->error("on_write: {}", ec.message());
        return fail(ec, "write");
    }

    // Receive the HTTP response
    boost::beast::http::async_read(stream_, buffer_, res_,
                                   std::bind(
                                       &WebClientSsl::on_read,
                                       shared_from_this(),
                                       std::placeholders::_1,
                                       std::placeholders::_2));
}

void WebClientSsl::on_read(boost::system::error_code ec, std::size_t bytes_transferred)
{
    logger_->trace("on_read: ec:{} bytes:{}", ec.message(), bytes_transferred);

    if (ec)
    {
        logger_->error("on_read: {}", ec.message());
        return fail(ec, "read");
    }

#if 1
    /// \todo Keep open if 1.1 ?
    // Gracefully close the stream
    stream_.async_shutdown(
                std::bind(
                    &WebClientSsl::on_shutdown,
                    shared_from_this(),
                    std::placeholders::_1));
#endif
    if (responseCb_)
        responseCb_(res_);
}

void WebClientSsl::on_shutdown(boost::system::error_code ec)
{
    logger_->trace("on_shutdown: {}", ec.message());
#if 0
    if (ec == boost::asio::error::eof)
    {
        // Rationale:
        // http://stackoverflow.com/questions/25587403/boost-asio-ssl-async-shutdown-always-finishes-with-an-error
        ec.assign(0, ec.category());
    }
#endif

    boost::system::error_code ignoredEc;
    stream_.lowest_layer().cancel(ignoredEc);
    stream_.lowest_layer().close(ignoredEc);

    if (ec && ec != boost::asio::error::eof)
    {
        logger_->error("on_shutdown: {}", ec.message());
        return fail(ec, "shutdown");
    }

    // If we get here then the connection is closed gracefully
}

max_stars_repo_name: pykel/stalk

max_issues_repo_name: pykel/stalk

max_forks_repo_name: pykel/stalk


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2004-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)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#include <boost/interprocess/sync/named_mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include "mutex_test_template.hpp"
#include "named_creation_template.hpp"
#include <boost/interprocess/detail/interprocess_tester.hpp>
#include <exception>

#if defined(BOOST_INTERPROCESS_WINDOWS)
#include <boost/interprocess/sync/windows/named_mutex.hpp>
#endif

using namespace boost::interprocess;

template<class NamedMutex>
int test_named_mutex()
{
   int ret = 0;
   BOOST_TRY{
      NamedMutex::remove(test::get_process_id_name());
      test::test_named_creation< test::named_sync_creation_test_wrapper<NamedMutex> >();
      #if defined(BOOST_INTERPROCESS_WCHAR_NAMED_RESOURCES)
      test::test_named_creation< test::named_sync_creation_test_wrapper_w<NamedMutex> >();
      #endif   //defined(BOOST_INTERPROCESS_WCHAR_NAMED_RESOURCES)
      test::test_all_lock< test::named_sync_wrapper<NamedMutex> >();
      test::test_all_mutex<test::named_sync_wrapper<NamedMutex> >();
   }
   BOOST_CATCH(std::exception &ex){
      std::cout << ex.what() << std::endl;
      ret = 1;
   } BOOST_CATCH_END
   NamedMutex::remove(test::get_process_id_name());
   return ret;
}

int main()
{
   int ret;
   #if defined(BOOST_INTERPROCESS_WINDOWS)
   ret = test_named_mutex<ipcdetail::winapi_named_mutex>();
   if (ret)
      return ret;
   #endif
   ret = test_named_mutex<named_mutex>();

   return ret;
}


text:
//  (C) Copyright Steve Cleary & John Maddock 2000.
//  Use, modification and distribution are subject to 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)

//  See http://www.boost.org for most recent version including documentation.

#include <boost/config.hpp>
#include <boost/static_assert.hpp>

//
// all these tests should fail:
//

struct Bob
{
  public:

  // Member function scope: provides access to member variables
  char x[4];
  char c;
  int f()
  {
#if !defined(BOOST_MSVC) || BOOST_MSVC > 1200 // broken sizeof in VC6
    BOOST_STATIC_ASSERT(sizeof(x) == 4);
    BOOST_STATIC_ASSERT(sizeof(c) == 1);
    BOOST_STATIC_ASSERT((sizeof(x) == sizeof(c))); // should not compile
#endif
    return x;
  }
};


text:
//////////////////////////////////////////////////////////////////////////////
// data::field::survival::functional::elapsed_time.hpp         				//
//                                                                          //
//                                                                          //
//  (C) Copyright 2010 Erwann Rogard                                        //
//  Use, modification and distribution are subject to 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_STATISTICS_DETAIL_DATA_FIELD_SURVIVAL_FUNCTIONAL_ELAPSED_TIME_HPP_ER_2010
#define BOOST_STATISTICS_DETAIL_DATA_FIELD_SURVIVAL_FUNCTIONAL_ELAPSED_TIME_HPP_ER_2010
#include <boost/statistics/detail/data/field/framework/float_valued.hpp>
#include <boost/statistics/detail/data/field/survival/fields/entry_time.hpp>

namespace boost{
namespace statistics{
namespace detail{
namespace data{
namespace field{
namespace functional{

	template<typename T>
 	struct elapsed_time{
    	typedef typename field::meta::entry_time<T>::type f_;

		typedef T result_type;

		elapsed_time(const T& t):t_(t){}

        T operator()(const f_& t)const{
        	return field::elapsed_time(f,this->t_);
        }

		private:
		T t_;

    };

}// functional
}// field
}// data
}// detail
}// statistics
}// boost

#endif


text:
//
// Copyright (c) 2021 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/CPPAlliance/http_proto
//

#ifndef BOOST_HTTP_PROTO_RFC_IMPL_REQUEST_LINE_RULE_IPP
#define BOOST_HTTP_PROTO_RFC_IMPL_REQUEST_LINE_RULE_IPP

#include <boost/http_proto/rfc/request_line_rule.hpp>
#include <boost/http_proto/rfc/charsets.hpp>
#include <boost/http_proto/rfc/crlf_rule.hpp>
#include <boost/http_proto/rfc/version_rule.hpp>
#include <boost/http_proto/bnf/ctype.hpp>
#include <boost/url/grammar/parse.hpp>

namespace boost {
namespace http_proto {

/*
    request-line   = method SP request-target SP HTTP-version CRLF
*/
void
request_line_rule::
parse(
    char const*& it,
    char const* const end,
    error_code& ec,
    request_line_rule& t) noexcept
{
    method_rule t0;
    request_target_rule t1;
    version_rule t2;

    if(! grammar::parse(
        it, end, ec,
        t0, ' ',
        t1, ' ',
        t2, crlf_rule{}))
        return;
    t.m = t0.m;
    t.ms = t0.s;
    t.t = t1.s;
    t.v = t2.v;
}

} // http_proto
} // boost

#endif

ext: ipp