<commit_before>#include <opencv2/opencv.hpp>
#include <vector>
#include <iostream>

using namespace std;
using namespace cv;

static void help()
{
    cout << "\n This program demonstrates how to use BLOB and MSER to detect region \n"
        "Usage: \n"
        "  ./BLOB_MSER <image1(../data/forme2.jpg as default)>\n"
        "Press a key when image window is active to change descriptor";
}

struct MSERParams
    {
    MSERParams(int _delta = 5, int _min_area = 60, int _max_area = 14400,
    double _max_variation = 0.25, double _min_diversity = .2,
    int _max_evolution = 200, double _area_threshold = 1.01,
    double _min_margin = 0.003, int _edge_blur_size = 5)
        {
        delta = _delta;
        minArea = _min_area;
        maxArea = _max_area;
        maxVariation = _max_variation;
        minDiversity = _min_diversity;
        maxEvolution = _max_evolution;
        areaThreshold = _area_threshold;
        minMargin = _min_margin;
        edgeBlurSize = _edge_blur_size;
        pass2Only = false;
        }

    int delta;
    int minArea;
    int maxArea;
    double maxVariation;
    double minDiversity;
    bool pass2Only;

    int maxEvolution;
    double areaThreshold;
    double minMargin;
    int edgeBlurSize;
    };

String Legende(SimpleBlobDetector::Params &pAct)
{
    String s="";
    if (pAct.filterByArea)
        {
        String inf = static_cast<ostringstream*>(&(ostringstream() << pAct.minArea))->str();
        String sup = static_cast<ostringstream*>(&(ostringstream() << pAct.maxArea))->str();
        s = " Area range [" + inf + " to  " + sup + "]";
        }
    if (pAct.filterByCircularity)
        {
        String inf = static_cast<ostringstream*>(&(ostringstream() << pAct.minCircularity))->str();
        String sup = static_cast<ostringstream*>(&(ostringstream() << pAct.maxCircularity))->str();
        if (s.length()==0)
            s = " Circularity range [" + inf + " to  " + sup + "]";
        else
            s += " AND Circularity range [" + inf + " to  " + sup + "]";
        }
    if (pAct.filterByColor)
        {
        String inf = static_cast<ostringstream*>(&(ostringstream() << pAct.blobColor))->str();
        if (s.length() == 0)
            s = " Blob color " + inf;
        else
            s += " AND Blob color " + inf;
        }
    if (pAct.filterByConvexity)
        {
        String inf = static_cast<ostringstream*>(&(ostringstream() << pAct.minConvexity))->str();
        String sup = static_cast<ostringstream*>(&(ostringstream() << pAct.maxConvexity))->str();
        if (s.length() == 0)
            s = " Convexity range[" + inf + " to  " + sup + "]";
        else
            s += " AND  Convexity range[" + inf + " to  " + sup + "]";
        }
    if (pAct.filterByInertia)
        {
        String inf = static_cast<ostringstream*>(&(ostringstream() << pAct.minInertiaRatio))->str();
        String sup = static_cast<ostringstream*>(&(ostringstream() << pAct.maxInertiaRatio))->str();
        if (s.length() == 0)
            s = " Inertia ratio range [" + inf + " to  " + sup + "]";
        else
            s += " AND  Inertia ratio range [" + inf + " to  " + sup + "]";
        }
    return s;
}

int main(int argc, char *argv[])
{
    vector<String> fileName;
    if (argc == 1)
        {
        fileName.push_back("../data/BLOB_MSER.bmp");
        }
    else if (argc == 2)
        {
        fileName.push_back(argv[1]);
        }
    else
        {
        help();
        return(0);
        }
    Mat img = imread(fileName[0], IMREAD_GRAYSCALE);
    if (img.rows*img.cols <= 0)
        {
        cout << "Image " << fileName[0] << " is empty or cannot be found\n";
        return(0);
        }

    SimpleBlobDetector::Params pDefaultBLOB;
    MSERParams pDefaultMSER;
    // This is default parameters for SimpleBlobDetector
    pDefaultBLOB.thresholdStep = 10;
    pDefaultBLOB.minThreshold = 10;
    pDefaultBLOB.maxThreshold = 220;
    pDefaultBLOB.minRepeatability = 2;
    pDefaultBLOB.minDistBetweenBlobs = 10;
    pDefaultBLOB.filterByColor = false;
    pDefaultBLOB.blobColor = 0;
    pDefaultBLOB.filterByArea = false;
    pDefaultBLOB.minArea = 25;
    pDefaultBLOB.maxArea = 5000;
    pDefaultBLOB.filterByCircularity = false;
    pDefaultBLOB.minCircularity = 0.9f;
    pDefaultBLOB.maxCircularity = std::numeric_limits<float>::max();
    pDefaultBLOB.filterByInertia = false;
    pDefaultBLOB.minInertiaRatio = 0.1f;
    pDefaultBLOB.maxInertiaRatio = std::numeric_limits<float>::max();
    pDefaultBLOB.filterByConvexity = false;
    pDefaultBLOB.minConvexity = 0.95f;
    pDefaultBLOB.maxConvexity = std::numeric_limits<float>::max();
    // Descriptor array (BLOB or MSER)
    vector<String> typeDesc;
    // Param array for BLOB
    vector<SimpleBlobDetector::Params> pBLOB;
    vector<SimpleBlobDetector::Params>::iterator itBLOB;
    // Param array for MSER
    vector<MSERParams> pMSER;
    vector<MSERParams>::iterator itMSER;

    // Color palette
    vector<Vec3b>  palette;
    for (int i=0;i<65536;i++)
        palette.push_back(Vec3b(rand(),rand(),rand()));
    help();

    typeDesc.push_back("MSER");
    pMSER.push_back(pDefaultMSER);
    pMSER.back().delta=0;
    pMSER.back().minArea = 25;
    pMSER.back().maxArea = 80000;
    pMSER.back().maxVariation= 0.5;
    pMSER.back().minDiversity=0.8; // variation de taille entre deux seuillages ?
    pMSER.back().areaThreshold= 200;
    pMSER.back().maxEvolution = 1.01;
    pMSER.back().minMargin=0.003;
    pMSER.back().edgeBlurSize= 5;
    typeDesc.push_back("BLOB");
    pBLOB.push_back(pDefaultBLOB);
    pBLOB.back().filterByColor = true;
    pBLOB.back().blobColor = 0;

    // This descriptor are going to be detect and compute 4 BLOBS with 4 differents params
    // Param for first BLOB detector we want all
    typeDesc.push_back("BLOB");    // see http://docs.opencv.org/trunk/d0/d7a/classcv_1_1SimpleBlobDetector.html
    pBLOB.push_back(pDefaultBLOB);
    pBLOB.back().filterByArea = true;
    pBLOB.back().minArea = 1;
    pBLOB.back().maxArea = img.rows*img.cols;
    // Param for second BLOB detector we want area between 500 and 2900 pixels
    typeDesc.push_back("BLOB");
    pBLOB.push_back(pDefaultBLOB);
    pBLOB.back().filterByArea = true;
    pBLOB.back().minArea = 500;
    pBLOB.back().maxArea = 2900;
    // Param for third BLOB detector we want only circular object
    typeDesc.push_back("BLOB");
    pBLOB.push_back(pDefaultBLOB);
    pBLOB.back().filterByCircularity = true;
    // Param for Fourth BLOB detector we want ratio inertia
    typeDesc.push_back("BLOB");
    pBLOB.push_back(pDefaultBLOB);
    pBLOB.back().filterByInertia = true;
    pBLOB.back().minInertiaRatio = 0;
    pBLOB.back().maxInertiaRatio = 0.2;
    // Param for Fourth BLOB detector we want ratio inertia
    typeDesc.push_back("BLOB");
    pBLOB.push_back(pDefaultBLOB);
    pBLOB.back().filterByConvexity = true;
    pBLOB.back().minConvexity = 0.;
    pBLOB.back().maxConvexity = 0.9;

    itBLOB = pBLOB.begin();
    itMSER = pMSER.begin();
    vector<double> desMethCmp;
    Ptr<Feature2D> b;
    String label;
    // Descriptor loop
    vector<String>::iterator itDesc;
    for (itDesc = typeDesc.begin(); itDesc != typeDesc.end(); itDesc++)
    {
        vector<KeyPoint> keyImg1;
        if (*itDesc == "BLOB"){
            b = SimpleBlobDetector::create(*itBLOB);
            label=Legende(*itBLOB);

            itBLOB++;
        }
        if (*itDesc == "MSER"){
            b = MSER::create(itMSER->delta, itMSER->minArea, itMSER->maxArea, itMSER->maxVariation, itMSER->minDiversity, itMSER->maxEvolution,
                             itMSER->areaThreshold, itMSER->minMargin, itMSER->edgeBlurSize);
            b.dynamicCast<MSER>()->setPass2Only(true);
            //b = MSER::create();
            }
        try {
            // We can detect keypoint with detect method
            vector<KeyPoint>  keyImg;
            vector<Rect>  zone;
            vector<vector <Point>>  region;
            Mat     desc, result(img.rows,img.cols,CV_8UC3);
            int nb = img.channels();

            if (b.dynamicCast<SimpleBlobDetector>() != NULL)
            {
                Ptr<SimpleBlobDetector> sbd = b.dynamicCast<SimpleBlobDetector>();
                sbd->detect(img, keyImg, Mat());
                drawKeypoints(img,keyImg,result);
                int i=0;
                for (vector<KeyPoint>::iterator k=keyImg.begin();k!=keyImg.end();k++,i++)
                    circle(result,k->pt,k->size,palette[i%65536]);
            }
            if (b.dynamicCast<MSER>() != NULL)
            {
                Ptr<MSER> sbd = b.dynamicCast<MSER>();
                sbd->detectRegions(img, region, zone);
                int i = 0;

                for (vector<Rect>::iterator r = zone.begin(); r != zone.end();r++,i++)
                {
                    // we draw a white rectangle which include all region pixels
                    rectangle(result, *r, Vec3b(255, 255, 255), 2);
                }
                i=0;
                for (vector<vector <Point>>::iterator itr = region.begin(); itr != region.end(); itr++, i++)
                {
                    for (vector <Point>::iterator itp = region[i].begin(); itp != region[i].end(); itp++)
                    {
                        // all pixels belonging to region are red
                        result.at<Vec3b>(itp->y, itp->x) = Vec3b(0,0,128);
                    }
                }
            }
            namedWindow(*itDesc+label , WINDOW_AUTOSIZE);
            imshow(*itDesc + label, result);
            imshow("Original", img);
            FileStorage fs(*itDesc + "_" + fileName[0] + ".xml", FileStorage::WRITE);
            fs<<*itDesc<<keyImg;
                waitKey();
        }
        catch (Exception& e)
        {
            cout << "Feature : " << *itDesc << "\n";
            cout<<e.msg<<endl;
        }
    }
    return 0;
}
<commit_msg>Etude de MSER<commit_after>#include <opencv2/opencv.hpp>
#include <vector>
#include <map>
#include <iostream>

using namespace std;
using namespace cv;

void Example_MSER(vector<String> &fileName);

static void help()
{
    cout << "\n This program demonstrates how to use BLOB and MSER to detect region \n"
        "Usage: \n"
        "  ./BLOB_MSER <image1(../data/forme2.jpg as default)>\n"
        "Press a key when image window is active to change descriptor";
}

struct MSERParams
    {
    MSERParams(int _delta = 5, int _min_area = 60, int _max_area = 14400,
    double _max_variation = 0.25, double _min_diversity = .2,
    int _max_evolution = 200, double _area_threshold = 1.01,
    double _min_margin = 0.003, int _edge_blur_size = 5)
        {
        delta = _delta;
        minArea = _min_area;
        maxArea = _max_area;
        maxVariation = _max_variation;
        minDiversity = _min_diversity;
        maxEvolution = _max_evolution;
        areaThreshold = _area_threshold;
        minMargin = _min_margin;
        edgeBlurSize = _edge_blur_size;
        pass2Only = false;
        }

    int delta;
    int minArea;
    int maxArea;
    double maxVariation;
    double minDiversity;
    bool pass2Only;

    int maxEvolution;
    double areaThreshold;
    double minMargin;
    int edgeBlurSize;
    };

String Legende(SimpleBlobDetector::Params &pAct)
{
    String s="";
    if (pAct.filterByArea)
        {
        String inf = static_cast<ostringstream*>(&(ostringstream() << pAct.minArea))->str();
        String sup = static_cast<ostringstream*>(&(ostringstream() << pAct.maxArea))->str();
        s = " Area range [" + inf + " to  " + sup + "]";
        }
    if (pAct.filterByCircularity)
        {
        String inf = static_cast<ostringstream*>(&(ostringstream() << pAct.minCircularity))->str();
        String sup = static_cast<ostringstream*>(&(ostringstream() << pAct.maxCircularity))->str();
        if (s.length()==0)
            s = " Circularity range [" + inf + " to  " + sup + "]";
        else
            s += " AND Circularity range [" + inf + " to  " + sup + "]";
        }
    if (pAct.filterByColor)
        {
        String inf = static_cast<ostringstream*>(&(ostringstream() << (int)pAct.blobColor))->str();
        if (s.length() == 0)
            s = " Blob color " + inf;
        else
            s += " AND Blob color " + inf;
        }
    if (pAct.filterByConvexity)
        {
        String inf = static_cast<ostringstream*>(&(ostringstream() << pAct.minConvexity))->str();
        String sup = static_cast<ostringstream*>(&(ostringstream() << pAct.maxConvexity))->str();
        if (s.length() == 0)
            s = " Convexity range[" + inf + " to  " + sup + "]";
        else
            s += " AND  Convexity range[" + inf + " to  " + sup + "]";
        }
    if (pAct.filterByInertia)
        {
        String inf = static_cast<ostringstream*>(&(ostringstream() << pAct.minInertiaRatio))->str();
        String sup = static_cast<ostringstream*>(&(ostringstream() << pAct.maxInertiaRatio))->str();
        if (s.length() == 0)
            s = " Inertia ratio range [" + inf + " to  " + sup + "]";
        else
            s += " AND  Inertia ratio range [" + inf + " to  " + sup + "]";
        }
    return s;
}

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

    vector<String> fileName;
    Example_MSER(fileName);
    Mat img(600,800,CV_8UC1);
    if (argc == 1)
    {
        fileName.push_back("../data/BLOB_MSER.bmp");
    }
    else if (argc == 2)
        {
        fileName.push_back(argv[1]);
        }
    else
        {
        help();
        return(0);
        }
    img = imread(fileName[0], IMREAD_UNCHANGED);
    if (img.rows*img.cols <= 0)
        {
        cout << "Image " << fileName[0] << " is empty or cannot be found\n";
        return(0);
        }

    SimpleBlobDetector::Params pDefaultBLOB;
    MSERParams pDefaultMSER;
    // This is default parameters for SimpleBlobDetector
    pDefaultBLOB.thresholdStep = 10;
    pDefaultBLOB.minThreshold = 10;
    pDefaultBLOB.maxThreshold = 220;
    pDefaultBLOB.minRepeatability = 2;
    pDefaultBLOB.minDistBetweenBlobs = 10;
    pDefaultBLOB.filterByColor = false;
    pDefaultBLOB.blobColor = 0;
    pDefaultBLOB.filterByArea = false;
    pDefaultBLOB.minArea = 25;
    pDefaultBLOB.maxArea = 5000;
    pDefaultBLOB.filterByCircularity = false;
    pDefaultBLOB.minCircularity = 0.9f;
    pDefaultBLOB.maxCircularity = std::numeric_limits<float>::max();
    pDefaultBLOB.filterByInertia = false;
    pDefaultBLOB.minInertiaRatio = 0.1f;
    pDefaultBLOB.maxInertiaRatio = std::numeric_limits<float>::max();
    pDefaultBLOB.filterByConvexity = false;
    pDefaultBLOB.minConvexity = 0.95f;
    pDefaultBLOB.maxConvexity = std::numeric_limits<float>::max();
    // Descriptor array (BLOB or MSER)
    vector<String> typeDesc;
    // Param array for BLOB
    vector<SimpleBlobDetector::Params> pBLOB;
    vector<SimpleBlobDetector::Params>::iterator itBLOB;
    // Param array for MSER
    vector<MSERParams> pMSER;
    vector<MSERParams>::iterator itMSER;

    // Color palette
    vector<Vec3b>  palette;
    for (int i=0;i<65536;i++)
        palette.push_back(Vec3b((uchar)rand(), (uchar)rand(), (uchar)rand()));
    help();

/*    typeDesc.push_back("MSER");
    pMSER.push_back(pDefaultMSER);
    pMSER.back().delta = 1;
    pMSER.back().minArea = 1;
    pMSER.back().maxArea = 180000;
    pMSER.back().maxVariation= 500;
    pMSER.back().minDiversity = 0;
    pMSER.back().pass2Only = false;*/
    typeDesc.push_back("BLOB");
    pBLOB.push_back(pDefaultBLOB);
    pBLOB.back().filterByColor = true;
    pBLOB.back().blobColor = 0;

    // This descriptor are going to be detect and compute 4 BLOBS with 4 differents params
    // Param for first BLOB detector we want all
    typeDesc.push_back("BLOB");    // see http://docs.opencv.org/trunk/d0/d7a/classcv_1_1SimpleBlobDetector.html
    pBLOB.push_back(pDefaultBLOB);
    pBLOB.back().filterByArea = true;
    pBLOB.back().minArea = 1;
    pBLOB.back().maxArea = int(img.rows*img.cols);
    // Param for second BLOB detector we want area between 500 and 2900 pixels
    typeDesc.push_back("BLOB");
    pBLOB.push_back(pDefaultBLOB);
    pBLOB.back().filterByArea = true;
    pBLOB.back().minArea = 500;
    pBLOB.back().maxArea = 2900;
    // Param for third BLOB detector we want only circular object
    typeDesc.push_back("BLOB");
    pBLOB.push_back(pDefaultBLOB);
    pBLOB.back().filterByCircularity = true;
    // Param for Fourth BLOB detector we want ratio inertia
    typeDesc.push_back("BLOB");
    pBLOB.push_back(pDefaultBLOB);
    pBLOB.back().filterByInertia = true;
    pBLOB.back().minInertiaRatio = 0;
    pBLOB.back().maxInertiaRatio = (float)0.2;
    // Param for Fourth BLOB detector we want ratio inertia
    typeDesc.push_back("BLOB");
    pBLOB.push_back(pDefaultBLOB);
    pBLOB.back().filterByConvexity = true;
    pBLOB.back().minConvexity = 0.;
    pBLOB.back().maxConvexity = (float)0.9;

    itBLOB = pBLOB.begin();
    itMSER = pMSER.begin();
    vector<double> desMethCmp;
    Ptr<Feature2D> b;
    String label;
    // Descriptor loop
    vector<String>::iterator itDesc;
    for (itDesc = typeDesc.begin(); itDesc != typeDesc.end(); itDesc++)
    {
        vector<KeyPoint> keyImg1;
        if (*itDesc == "BLOB"){
            b = SimpleBlobDetector::create(*itBLOB);
            label=Legende(*itBLOB);

            itBLOB++;
        }
        if (*itDesc == "MSER"){
            if(img.type()==CV_8UC3)
            {
                b = MSER::create(itMSER->delta, itMSER->minArea, itMSER->maxArea, itMSER->maxVariation, itMSER->minDiversity, itMSER->maxEvolution,
                                itMSER->areaThreshold, itMSER->minMargin, itMSER->edgeBlurSize);
                b.dynamicCast<MSER>()->setPass2Only(itMSER->pass2Only);
            }
            else
            {
                b = MSER::create(itMSER->delta, itMSER->minArea, itMSER->maxArea, itMSER->maxVariation, itMSER->minDiversity);
            }
            //b = MSER::create();
            //b = MSER::create();
            }
        try {
            // We can detect keypoint with detect method
            vector<KeyPoint>  keyImg;
            vector<Rect>  zone;
            vector<vector <Point>>  region;
            Mat     desc, result(img.rows,img.cols,CV_8UC3);

            if (b.dynamicCast<SimpleBlobDetector>() != NULL)
            {
                Ptr<SimpleBlobDetector> sbd = b.dynamicCast<SimpleBlobDetector>();
                sbd->detect(img, keyImg, Mat());
                drawKeypoints(img,keyImg,result);
                int i=0;
                for (vector<KeyPoint>::iterator k=keyImg.begin();k!=keyImg.end();k++,i++)
                    circle(result,k->pt,k->size,palette[i%65536]);
            }
            if (b.dynamicCast<MSER>() != NULL)
            {
                Ptr<MSER> sbd = b.dynamicCast<MSER>();
                sbd->detectRegions(img, region, zone);
                int i = 0;
                result=Scalar(0,0,0);
                for (vector<Rect>::iterator r = zone.begin(); r != zone.end();r++,i++)
                {
                    // we draw a white rectangle which include all region pixels
                    rectangle(result, *r, Vec3b(255, 0, 0), 2);
                }
                i=0;
                for (vector<vector <Point>>::iterator itr = region.begin(); itr != region.end(); itr++, i++)
                {
                    for (vector <Point>::iterator itp = region[i].begin(); itp != region[i].end(); itp++)
                    {
                        // all pixels belonging to region are red
                        result.at<Vec3b>(itp->y, itp->x) = Vec3b(0,0,128);
                    }
                }
            }
            namedWindow(*itDesc+label , WINDOW_AUTOSIZE);
            imshow(*itDesc + label, result);
            imshow("Original", img);
            FileStorage fs(*itDesc + "_" + fileName[0] + ".xml", FileStorage::WRITE);
            fs<<*itDesc<<keyImg;
                waitKey();
        }
        catch (Exception& e)
        {
            cout << "Feature : " << *itDesc << "\n";
            cout<<e.msg<<endl;
        }
    }
    return 0;
}

void Example_MSER(vector<String> &fileName)
{
    Mat img(600, 800, CV_8UC1);
    fileName.push_back("SyntheticImage.bmp");
    map<int, char> val;
    int fond = 255;
    img = Scalar(fond);
    val[fond] = 1;
    Point p[] = { Point(img.cols / 4, img.rows / 4), Point(3 * img.cols / 4, img.rows / 4) };
    for (int j = 0; j<1; j++)
        {
        for (int i = 1; i<min(img.cols / 4, img.rows / 4); i += 2)
            {
            int v = 200 - (i / 40);
            Rect r(p[j] - Point(i / 2, i / 2), Size(i, i));
            rectangle(img, r, Scalar(v), 1);
            if (val.find(v) == val.end())
                val[v] = 1;
            //circle(img, p[j], i, Scalar(255 - (j + 1)*(i / 30)),2);
            }
        }
    for (int j = 1; j<2; j++)
        {
        for (int i = 1; i<min(img.cols / 4, img.rows / 4); i += 2)
            {
            int v = i / 40+30;
            Rect r(p[j] - Point(i / 2, i / 2), Size(i, i));

            rectangle(img, r, Scalar(v), 1);
            if (val.find(v) == val.end())
                val[v] = 1;
            //circle(img, p[j], i, Scalar(255 - (j + 1)*(i / 30)),2);
            }
        }
    int channel = 1;
    int histSize =  256 ;
    float range[] = { 0, 256 };
    const float* histRange[] = { range };
    Mat hist;
    // we compute the histogram from the 0-th and 1-st channels

    calcHist(&img, 1, 0, Mat(), hist, 1, &histSize, histRange, true, false);
    Mat cumHist(hist.size(), hist.type());
    cumHist.at<float>(0, 0) = hist.at<float>(0, 0);
    for (int i = 1; i < hist.rows; i++)
        cumHist.at<float>(i, 0) = cumHist.at<float>(i - 1, 0) + hist.at<float>(i, 0);
    imwrite(fileName[0], img);
    cout << "****************Maximal region************************\n";
    for (map<int, char>::iterator it = val.begin(); it != val.end(); it++)
        {
        cout << "h" << it->first << "=\t" << hist.at<float>(it->first, 0) << "\t" << cumHist.at<float>(it->first, 0) << "\t\t";
        if (it->first <= 254 && it->first >= 1)
            {
            cout << (cumHist.at<float>(it->first + 1, 0) - cumHist.at<float>(it->first - 1, 0)) / cumHist.at<float>(it->first, 0);
            }
        cout << endl;
        }
    cout << "****************Minimal region************************\n";
    cumHist.at<float>(255, 0) = hist.at<float>(255, 0);
    for (int i = 254; i >= 0; i--)
        cumHist.at<float>(i, 0) = cumHist.at<float>(i + 1, 0) + hist.at<float>(i, 0);
    map<int, char>::iterator it = val.end();
    for (it--; it != val.begin(); it--)
        {
        cout << "h" << it->first << "=\t" << hist.at<float>(it->first, 0) << "\t" << cumHist.at<float>(it->first, 0) << "\t\t";
        if (it->first <= 254 && it->first >= 1)
            {
            cout << (cumHist.at<float>(it->first - 1, 0) - cumHist.at<float>(it->first + 1, 0)) / cumHist.at<float>(it->first, 0);
            }
        cout << endl;
        }
    // img = imread("C:/Users/laurent_2/Pictures/basketball1.png", IMREAD_GRAYSCALE);

    MSERParams pDefaultMSER;
    // Descriptor array (BLOB or MSER)
    vector<String> typeDesc;
    // Param array for BLOB
    // Param array for MSER
    vector<MSERParams> pMSER;
    vector<MSERParams>::iterator itMSER;

    // Color palette
    vector<Vec3b>  palette;
    for (int i = 0; i<65536; i++)
        palette.push_back(Vec3b((uchar)rand(), (uchar)rand(), (uchar)rand()));
    help();

    typeDesc.push_back("MSER");
    pMSER.push_back(pDefaultMSER);
    pMSER.back().delta = 1;
    pMSER.back().minArea = 1;
    pMSER.back().maxArea = 180000;
    pMSER.back().maxVariation = 500;
    pMSER.back().minDiversity = 0;
    pMSER.back().pass2Only = true;
    itMSER = pMSER.begin();
    vector<double> desMethCmp;
    Ptr<Feature2D> b;
    String label;
    // Descriptor loop
    vector<String>::iterator itDesc;
    for (itDesc = typeDesc.begin(); itDesc != typeDesc.end(); itDesc++)
        {
        vector<KeyPoint> keyImg1;
        if (*itDesc == "MSER"){
            if (img.type() == CV_8UC3)
                {
                b = MSER::create(itMSER->delta, itMSER->minArea, itMSER->maxArea, itMSER->maxVariation, itMSER->minDiversity, itMSER->maxEvolution,
                                 itMSER->areaThreshold, itMSER->minMargin, itMSER->edgeBlurSize);
                b.dynamicCast<MSER>()->setPass2Only(itMSER->pass2Only);
                }
            else
                {
                b = MSER::create(itMSER->delta, itMSER->minArea, itMSER->maxArea, itMSER->maxVariation, itMSER->minDiversity);
                }
            }
        try {
            // We can detect keypoint with detect method
            vector<KeyPoint>  keyImg;
            vector<Rect>  zone;
            vector<vector <Point>>  region;
            Mat     desc, result(img.rows, img.cols, CV_8UC3);
            int nb = img.channels();

            if (b.dynamicCast<MSER>() != NULL)
                {
                Ptr<MSER> sbd = b.dynamicCast<MSER>();
                sbd->detectRegions(img, region, zone);
                int i = 0;
                result = Scalar(0, 0, 0);
                for (vector<Rect>::iterator r = zone.begin(); r != zone.end(); r++, i++)
                    {
                    // we draw a white rectangle which include all region pixels
                    rectangle(result, *r, Vec3b(255, 0, 0), 2);
                    }
                i = 0;
                for (vector<vector <Point>>::iterator itr = region.begin(); itr != region.end(); itr++, i++)
                    {
                    for (vector <Point>::iterator itp = region[i].begin(); itp != region[i].end(); itp++)
                        {
                        // all pixels belonging to region are red
                        result.at<Vec3b>(itp->y, itp->x) = Vec3b(0, 0, 128);
                        }
                    }
                }
            namedWindow(*itDesc + label, WINDOW_AUTOSIZE);
            imshow(*itDesc + label, result);
            imshow("Original", img);
            FileStorage fs(*itDesc + "_" + fileName[0] + ".xml", FileStorage::WRITE);
            fs << *itDesc << keyImg;
            waitKey();
            }
        catch (Exception& e)
            {
            cout << "Feature : " << *itDesc << "\n";
            cout << e.msg << endl;
            }
        }
    return;
    }
<|endoftext|>


<commit_before>/*******************************************************************************
 *    ALMA - Atacama Large Millimiter Array
 *    (c) European Southern Observatory, 2002
 *    Copyright by ESO (in the framework of the ALMA collaboration)
 *    and Cosylab 2002, All rights reserved
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation; either
 *    version 2.1 of the License, or (at your option) any later version.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 *
 * "@(#) $Id: loggingLog4cpp.cpp,v 1.6 2011/04/08 14:33:38 javarias Exp $"
 */

#include "loggingLog4cpp.h"
#include "loggingStdoutlayout.h"
#include "loggingXmlLayout.h"
#include "loggingACSRemoteAppender.h"

#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/SyslogAppender.hh>

#define DEFAULT_LOG_LEVEL_STDOUT 4
#define DEFUALT_LOG_LEVEL_REMOTE 3
#define DEFAULT_LOG_LEVEL_SYSLOG 3

#define STDOUT_APPENDER_NAME "STDOUT_appender"
#define SYSLOG_APPENDER_NAME "SYSLOG_appender"
#define REMOTE_APPENDER_NAME "ACS_REMOTE_appender"

using namespace logging;

Logger::Logger() :
		remoteAppenderEnabled(false),
		syslogAppenderEnabled(false),
		localLogLevel(DEFAULT_LOG_LEVEL_STDOUT),
		remoteLogLevel(DEFUALT_LOG_LEVEL_REMOTE),
		syslogLogLevel(DEFAULT_LOG_LEVEL_SYSLOG),
		loggingService(NULL){

	char* local_log_level = getenv("ACS_LOG_STDOUT");
	char* remote_log_level = getenv("ACS_LOG_REMOTE");
	char* syslog_log_level = getenv("ACS_LOG_SYSLOG");

	if (local_log_level != NULL)
		localLogLevel = atoi(local_log_level);
	if (remote_log_level != NULL)
		remoteLogLevel = atoi(remote_log_level);
	if (syslog_log_level != NULL)
		syslogLogLevel = atoi(syslog_log_level);

	getGlobalLogger();
	getStaticLogger();
}

Logger::~Logger() {
	static RemoteLoggerBuffer* buffer;
	if (buffer != NULL) {
		delete buffer;
		buffer = NULL;
	}
	//Clean the Categories?
}

void Logger::enableRemoteAppender(unsigned long cacheSize,
		unsigned int autoFlushTimeoutSec,
		Logging::AcsLogService_ptr loggingService,
		CosNaming::NamingContext_ptr namingService,
		int maxLogsPerSecond) {
	initMutex.acquire();
	if(!remoteAppenderEnabled) {
		remoteAppenderEnabled = true;
		this->cacheSize = cacheSize;
		this->autoFlushTimeoutSec = autoFlushTimeoutSec;
		if (!CORBA::is_nil(loggingService))
			this->loggingService = Logging::AcsLogService::_duplicate(loggingService);
		if(!CORBA::is_nil(namingService))
			this->namingService = CosNaming::NamingContext::_duplicate(namingService);
		this->maxLogsPerSecond = maxLogsPerSecond;

		std::vector<log4cpp::Category*>* loggers =
						ACSHierarchyMaintainer::getDefaultMaintainer().getCurrentCategories();
		std::vector<log4cpp::Category*>::iterator it;
		for (it = loggers->begin(); it < loggers->end(); it++) {
			if ((*it)->getAppender(REMOTE_APPENDER_NAME) != NULL)
				continue;
			::log4cpp::Appender* remoteAppender =
					new logging::ACSRemoteAppender(REMOTE_APPENDER_NAME,
					this->cacheSize, this->autoFlushTimeoutSec,
					this->loggingService,
					this->maxLogsPerSecond);
			//TODO: use the naming service
			remoteAppender->setLayout(new logging::ACSXmlLayout());
			remoteAppender->setThreshold(convertPriority(remoteLogLevel));
			(*it)->addAppender(remoteAppender);
		}

                delete loggers;
		loggers = NULL;
	}
	initMutex.release();
}

void Logger::enableSyslogAppender() {
	initMutex.acquire();
	if (!syslogAppenderEnabled) {
		syslogAppenderEnabled = true;
		std::vector<log4cpp::Category*>* loggers =
				ACSHierarchyMaintainer::getDefaultMaintainer().getCurrentCategories();
		std::vector<log4cpp::Category*>::iterator it;
		for (it = loggers->begin(); it < loggers->end(); it++) {
			if ((*it)->getAppender(SYSLOG_APPENDER_NAME) != NULL)
				continue;
			::log4cpp::Appender * syslogAppender =
					new ::log4cpp::SyslogAppender(SYSLOG_APPENDER_NAME, "ACS");
			syslogAppender->setLayout(new logging::ACSstdoutLayout());
			syslogAppender->setThreshold(convertPriority(syslogLogLevel));
			(*it)->addAppender(syslogAppender);
		}
	}
	initMutex.release();
}

void Logger::setLogLevels(const std::string& loggerName, log4cpp::Priority::PriorityLevel remote,
		log4cpp::Priority::PriorityLevel local) {
	ACSCategory* logger = ACSCategory::exist(loggerName);
	if (logger == NULL)
		return;
	if (logger->getAppender(REMOTE_APPENDER_NAME))
		logger->getAppender(REMOTE_APPENDER_NAME)->setThreshold(remote);
	if (logger->getAppender(STDOUT_APPENDER_NAME))
		logger->getAppender(STDOUT_APPENDER_NAME)->setThreshold(local);
	if (logger->getAppender(SYSLOG_APPENDER_NAME))
		logger->getAppender(SYSLOG_APPENDER_NAME)->setThreshold(local);
}

ACSCategory* Logger::getGlobalLogger() {
	return getLogger("GlobalLogger");
}

ACSCategory* Logger::getStaticLogger() {
	return getLogger("StaticMethodLogger");
}

ACSCategory* Logger::getLogger(const std::string& loggerName) {
	ACSCategory* logger = ACSCategory::exist(loggerName);
	if (logger == NULL)
		logger = initLogger(loggerName);
	return logger;
}

ACSCategory* Logger::initLogger(const std::string& loggerName) {
	::log4cpp::Appender* localAppender = new ::log4cpp::OstreamAppender(STDOUT_APPENDER_NAME, &::std::cout);
	localAppender->setLayout(new logging::ACSstdoutLayout());
	localAppender->setThreshold(convertPriority(localLogLevel));
	ACSCategory &logger = ACSCategory::getInstance(loggerName);
	logger.addAppender(localAppender);

	initMutex.acquire();
	if (syslogAppenderEnabled && logger.getAppender(SYSLOG_APPENDER_NAME) == NULL) {
		::log4cpp::Appender* syslogAppender = new ::log4cpp::SyslogAppender(SYSLOG_APPENDER_NAME, "ACS");
		syslogAppender->setLayout(new logging::ACSstdoutLayout());
		syslogAppender->setThreshold(convertPriority(syslogLogLevel));
		logger.addAppender(syslogAppender);
	}
	initMutex.release();

	initMutex.acquire();
	if (remoteAppenderEnabled && logger.getAppender(REMOTE_APPENDER_NAME) == NULL) {
		::log4cpp::Appender* remoteAppender = new logging::ACSRemoteAppender(REMOTE_APPENDER_NAME,
				this->cacheSize, this->autoFlushTimeoutSec,
				this->loggingService,
				this->maxLogsPerSecond);
		remoteAppender->setLayout(new logging::ACSXmlLayout());
		remoteAppender->setThreshold(convertPriority(remoteLogLevel));
		logger.addAppender(remoteAppender);
	}
	initMutex.release();

	return ACSCategory::exist(loggerName);
}

BasicLogInfo Logger::formatLog(log4cpp::Priority::PriorityLevel priority, const char *fmt, ...) {
	BasicLogInfo retVal;
	retVal.priority = priority;
	va_list argp;
	va_start(argp, fmt);
	char tmp_msg[1024];
	vsnprintf(tmp_msg, sizeof(char) * 1024, fmt, argp);
	va_end(argp);
	retVal.message = tmp_msg;
	return retVal;
}

BasicLogInfo Logger::formatLog(ACE_Log_Priority priority, const char *fmt, ...) {
	BasicLogInfo retVal;
	retVal.priority = convertPriority(priority);
	va_list argp;
	va_start(argp, fmt);
	char tmp_msg[1024];
	vsnprintf(tmp_msg, sizeof(char) * 1024, fmt, argp);
	va_end(argp);
	retVal.message = tmp_msg;
	return retVal;
}

BasicLogInfo Logger::formatLog(unsigned int priority, const char *fmt, ...) {
	BasicLogInfo retVal;
	retVal.priority = convertPriority(priority);
	va_list argp;
	va_start(argp, fmt);
	char tmp_msg[1024];
	vsnprintf(tmp_msg, sizeof(char) * 1024, fmt, argp);
	va_end(argp);
	retVal.message = tmp_msg;
	return retVal;
}

LogTrace::LogTrace(ACSCategory* logger, const std::string &method,
		const std::string &file, const unsigned long line) :
		logger(logger), method(method), file(file), line(line) {
	if(logger != NULL)
		logger->log("Entering", log4cpp::Priority::TRACE, method, file, line);
	else {
		std::cerr << "SEVERE LOGGING ERROR IN LogTrace/AUTO_TRACE - logger/getLogger() is NULL: routine=";
		std::cerr << method << " file: " << file << " line: " << line << std::endl;
	}
}

LogTrace::LogTrace (ACSCategory* logger, const std::string &method) :
	logger(logger), method(method), file("Unavailable"), line(0UL) {
	if(logger != NULL)
		logger->log("Entering...", log4cpp::Priority::TRACE, method, file, line);
	else {
		std::cerr << "SEVERE LOGGING ERROR IN LogTrace/AUTO_TRACE - logger/getLogger() is NULL: routine=";
		std::cerr << method << " file: " << file << " line: " << line << std::endl;
	}
}

LogTrace::~LogTrace() {
	if(logger != NULL)
		logger->log("Exiting...", log4cpp::Priority::TRACE, method, file, line);
}

log4cpp::Priority::PriorityLevel logging::convertPriority (unsigned int logLevel) {
	switch (logLevel) {
	case 1:
		return log4cpp::Priority::TRACE;
	case 2:
		return log4cpp::Priority::DELOUSE;
	//Old LM_DELOUSE value = 010000
	case LM_DELOUSE:
		return log4cpp::Priority::DELOUSE;
	case 3:
		return log4cpp::Priority::DEBUG;
	case 4:
		return log4cpp::Priority::INFO;
	case 5:
		return log4cpp::Priority::NOTICE;
	case 6:
		return log4cpp::Priority::WARNING;
	case 8:
		return log4cpp::Priority::ERROR;
	case 9:
		return log4cpp::Priority::CRITICAL;
	case 10:
		return log4cpp::Priority::ALERT;
	case 11:
		return log4cpp::Priority::EMERGENCY;
	default:
		return log4cpp::Priority::NOTSET;
	}
}

log4cpp::Priority::PriorityLevel logging::convertPriority (Logging::BaseLog::Priority logLevel) {
	switch (logLevel) {
	case Logging::BaseLog::LM_TRACE:
		return log4cpp::Priority::TRACE;
	case 03:
		return log4cpp::Priority::DELOUSE;
	case Logging::BaseLog::LM_DEBUG:
		return log4cpp::Priority::DEBUG;
	case Logging::BaseLog::LM_INFO:
		return log4cpp::Priority::INFO;
	case Logging::BaseLog::LM_NOTICE:
		return log4cpp::Priority::NOTICE;
	case Logging::BaseLog::LM_WARNING:
		return log4cpp::Priority::WARNING;
	case Logging::BaseLog::LM_ERROR:
		return log4cpp::Priority::ERROR;
	case Logging::BaseLog::LM_CRITICAL:
		return log4cpp::Priority::CRITICAL;
	case Logging::BaseLog::LM_ALERT:
		return log4cpp::Priority::ALERT;
	case Logging::BaseLog::LM_EMERGENCY:
		return log4cpp::Priority::EMERGENCY;
	default:
		return log4cpp::Priority::NOTSET;
	}
}

log4cpp::Priority::PriorityLevel logging::convertPriority(ACE_Log_Priority logLevel) {
	switch (logLevel) {
	case LM_TRACE:
		return log4cpp::Priority::TRACE;
	case LM_DEBUG:
		return log4cpp::Priority::DEBUG;
	case LM_INFO:
		return log4cpp::Priority::INFO;
	case LM_NOTICE:
		return log4cpp::Priority::NOTICE;
	case LM_WARNING:
		return log4cpp::Priority::WARNING;
	case LM_ERROR:
		return log4cpp::Priority::ERROR;
	case LM_CRITICAL:
		return log4cpp::Priority::CRITICAL;
	case LM_ALERT:
		return log4cpp::Priority::ALERT;
	case LM_EMERGENCY:
		return log4cpp::Priority::EMERGENCY;
	default:
		return log4cpp::Priority::NOTSET;
	}
}

log4cpp::Priority::PriorityLevel logging::convertPriority (AcsLogLevels::logLevelValue logLevel) {
	switch (logLevel) {
	case AcsLogLevels::TRACE_VAL:
		return log4cpp::Priority::TRACE;
	case AcsLogLevels::DELOUSE_VAL:
		return log4cpp::Priority::DELOUSE;
	case AcsLogLevels::DEBUG_VAL:
		return log4cpp::Priority::DEBUG;
	case AcsLogLevels::INFO_VAL:
		return log4cpp::Priority::INFO;
	case AcsLogLevels::NOTICE_VAL:
		return log4cpp::Priority::NOTICE;
	case AcsLogLevels::WARNING_VAL:
		return log4cpp::Priority::WARNING;
	case AcsLogLevels::ERROR_VAL:
		return log4cpp::Priority::ERROR;
	case AcsLogLevels::CRITICAL_VAL:
		return log4cpp::Priority::CRITICAL;
	case AcsLogLevels::ALERT_VAL:
		return log4cpp::Priority::ALERT;
	case AcsLogLevels::EMERGENCY_VAL:
		return log4cpp::Priority::EMERGENCY;
	default:
		return log4cpp::Priority::NOTSET;
	}
}

<commit_msg>ICTJ:ICT-4926: Fixed memory leak when calling getCurrentCategories in C++<commit_after>/*******************************************************************************
 *    ALMA - Atacama Large Millimiter Array
 *    (c) European Southern Observatory, 2002
 *    Copyright by ESO (in the framework of the ALMA collaboration)
 *    and Cosylab 2002, All rights reserved
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation; either
 *    version 2.1 of the License, or (at your option) any later version.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 *
 * "@(#) $Id: loggingLog4cpp.cpp,v 1.6 2011/04/08 14:33:38 javarias Exp $"
 */

#include "loggingLog4cpp.h"
#include "loggingStdoutlayout.h"
#include "loggingXmlLayout.h"
#include "loggingACSRemoteAppender.h"

#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/SyslogAppender.hh>

#define DEFAULT_LOG_LEVEL_STDOUT 4
#define DEFUALT_LOG_LEVEL_REMOTE 3
#define DEFAULT_LOG_LEVEL_SYSLOG 3

#define STDOUT_APPENDER_NAME "STDOUT_appender"
#define SYSLOG_APPENDER_NAME "SYSLOG_appender"
#define REMOTE_APPENDER_NAME "ACS_REMOTE_appender"

using namespace logging;

Logger::Logger() :
		remoteAppenderEnabled(false),
		syslogAppenderEnabled(false),
		localLogLevel(DEFAULT_LOG_LEVEL_STDOUT),
		remoteLogLevel(DEFUALT_LOG_LEVEL_REMOTE),
		syslogLogLevel(DEFAULT_LOG_LEVEL_SYSLOG),
		loggingService(NULL){

	char* local_log_level = getenv("ACS_LOG_STDOUT");
	char* remote_log_level = getenv("ACS_LOG_REMOTE");
	char* syslog_log_level = getenv("ACS_LOG_SYSLOG");

	if (local_log_level != NULL)
		localLogLevel = atoi(local_log_level);
	if (remote_log_level != NULL)
		remoteLogLevel = atoi(remote_log_level);
	if (syslog_log_level != NULL)
		syslogLogLevel = atoi(syslog_log_level);

	getGlobalLogger();
	getStaticLogger();
}

Logger::~Logger() {
	static RemoteLoggerBuffer* buffer;
	if (buffer != NULL) {
		delete buffer;
		buffer = NULL;
	}
	//Clean the Categories?
}

void Logger::enableRemoteAppender(unsigned long cacheSize,
		unsigned int autoFlushTimeoutSec,
		Logging::AcsLogService_ptr loggingService,
		CosNaming::NamingContext_ptr namingService,
		int maxLogsPerSecond) {
	initMutex.acquire();
	if(!remoteAppenderEnabled) {
		remoteAppenderEnabled = true;
		this->cacheSize = cacheSize;
		this->autoFlushTimeoutSec = autoFlushTimeoutSec;
		if (!CORBA::is_nil(loggingService))
			this->loggingService = Logging::AcsLogService::_duplicate(loggingService);
		if(!CORBA::is_nil(namingService))
			this->namingService = CosNaming::NamingContext::_duplicate(namingService);
		this->maxLogsPerSecond = maxLogsPerSecond;

		std::vector<log4cpp::Category*>* loggers =
						ACSHierarchyMaintainer::getDefaultMaintainer().getCurrentCategories();
		std::vector<log4cpp::Category*>::iterator it;
		for (it = loggers->begin(); it < loggers->end(); it++) {
			if ((*it)->getAppender(REMOTE_APPENDER_NAME) != NULL)
				continue;
			::log4cpp::Appender* remoteAppender =
					new logging::ACSRemoteAppender(REMOTE_APPENDER_NAME,
					this->cacheSize, this->autoFlushTimeoutSec,
					this->loggingService,
					this->maxLogsPerSecond);
			//TODO: use the naming service
			remoteAppender->setLayout(new logging::ACSXmlLayout());
			remoteAppender->setThreshold(convertPriority(remoteLogLevel));
			(*it)->addAppender(remoteAppender);
		}

                delete loggers;
		loggers = NULL;
	}
	initMutex.release();
}

void Logger::enableSyslogAppender() {
	initMutex.acquire();
	if (!syslogAppenderEnabled) {
		syslogAppenderEnabled = true;
		std::vector<log4cpp::Category*>* loggers =
				ACSHierarchyMaintainer::getDefaultMaintainer().getCurrentCategories();
		std::vector<log4cpp::Category*>::iterator it;
		for (it = loggers->begin(); it < loggers->end(); it++) {
			if ((*it)->getAppender(SYSLOG_APPENDER_NAME) != NULL)
				continue;
			::log4cpp::Appender * syslogAppender =
					new ::log4cpp::SyslogAppender(SYSLOG_APPENDER_NAME, "ACS");
			syslogAppender->setLayout(new logging::ACSstdoutLayout());
			syslogAppender->setThreshold(convertPriority(syslogLogLevel));
			(*it)->addAppender(syslogAppender);
		}

                delete loggers;
		loggers = NULL;
	}
	initMutex.release();
}

void Logger::setLogLevels(const std::string& loggerName, log4cpp::Priority::PriorityLevel remote,
		log4cpp::Priority::PriorityLevel local) {
	ACSCategory* logger = ACSCategory::exist(loggerName);
	if (logger == NULL)
		return;
	if (logger->getAppender(REMOTE_APPENDER_NAME))
		logger->getAppender(REMOTE_APPENDER_NAME)->setThreshold(remote);
	if (logger->getAppender(STDOUT_APPENDER_NAME))
		logger->getAppender(STDOUT_APPENDER_NAME)->setThreshold(local);
	if (logger->getAppender(SYSLOG_APPENDER_NAME))
		logger->getAppender(SYSLOG_APPENDER_NAME)->setThreshold(local);
}

ACSCategory* Logger::getGlobalLogger() {
	return getLogger("GlobalLogger");
}

ACSCategory* Logger::getStaticLogger() {
	return getLogger("StaticMethodLogger");
}

ACSCategory* Logger::getLogger(const std::string& loggerName) {
	ACSCategory* logger = ACSCategory::exist(loggerName);
	if (logger == NULL)
		logger = initLogger(loggerName);
	return logger;
}

ACSCategory* Logger::initLogger(const std::string& loggerName) {
	::log4cpp::Appender* localAppender = new ::log4cpp::OstreamAppender(STDOUT_APPENDER_NAME, &::std::cout);
	localAppender->setLayout(new logging::ACSstdoutLayout());
	localAppender->setThreshold(convertPriority(localLogLevel));
	ACSCategory &logger = ACSCategory::getInstance(loggerName);
	logger.addAppender(localAppender);

	initMutex.acquire();
	if (syslogAppenderEnabled && logger.getAppender(SYSLOG_APPENDER_NAME) == NULL) {
		::log4cpp::Appender* syslogAppender = new ::log4cpp::SyslogAppender(SYSLOG_APPENDER_NAME, "ACS");
		syslogAppender->setLayout(new logging::ACSstdoutLayout());
		syslogAppender->setThreshold(convertPriority(syslogLogLevel));
		logger.addAppender(syslogAppender);
	}
	initMutex.release();

	initMutex.acquire();
	if (remoteAppenderEnabled && logger.getAppender(REMOTE_APPENDER_NAME) == NULL) {
		::log4cpp::Appender* remoteAppender = new logging::ACSRemoteAppender(REMOTE_APPENDER_NAME,
				this->cacheSize, this->autoFlushTimeoutSec,
				this->loggingService,
				this->maxLogsPerSecond);
		remoteAppender->setLayout(new logging::ACSXmlLayout());
		remoteAppender->setThreshold(convertPriority(remoteLogLevel));
		logger.addAppender(remoteAppender);
	}
	initMutex.release();

	return ACSCategory::exist(loggerName);
}

BasicLogInfo Logger::formatLog(log4cpp::Priority::PriorityLevel priority, const char *fmt, ...) {
	BasicLogInfo retVal;
	retVal.priority = priority;
	va_list argp;
	va_start(argp, fmt);
	char tmp_msg[1024];
	vsnprintf(tmp_msg, sizeof(char) * 1024, fmt, argp);
	va_end(argp);
	retVal.message = tmp_msg;
	return retVal;
}

BasicLogInfo Logger::formatLog(ACE_Log_Priority priority, const char *fmt, ...) {
	BasicLogInfo retVal;
	retVal.priority = convertPriority(priority);
	va_list argp;
	va_start(argp, fmt);
	char tmp_msg[1024];
	vsnprintf(tmp_msg, sizeof(char) * 1024, fmt, argp);
	va_end(argp);
	retVal.message = tmp_msg;
	return retVal;
}

BasicLogInfo Logger::formatLog(unsigned int priority, const char *fmt, ...) {
	BasicLogInfo retVal;
	retVal.priority = convertPriority(priority);
	va_list argp;
	va_start(argp, fmt);
	char tmp_msg[1024];
	vsnprintf(tmp_msg, sizeof(char) * 1024, fmt, argp);
	va_end(argp);
	retVal.message = tmp_msg;
	return retVal;
}

LogTrace::LogTrace(ACSCategory* logger, const std::string &method,
		const std::string &file, const unsigned long line) :
		logger(logger), method(method), file(file), line(line) {
	if(logger != NULL)
		logger->log("Entering", log4cpp::Priority::TRACE, method, file, line);
	else {
		std::cerr << "SEVERE LOGGING ERROR IN LogTrace/AUTO_TRACE - logger/getLogger() is NULL: routine=";
		std::cerr << method << " file: " << file << " line: " << line << std::endl;
	}
}

LogTrace::LogTrace (ACSCategory* logger, const std::string &method) :
	logger(logger), method(method), file("Unavailable"), line(0UL) {
	if(logger != NULL)
		logger->log("Entering...", log4cpp::Priority::TRACE, method, file, line);
	else {
		std::cerr << "SEVERE LOGGING ERROR IN LogTrace/AUTO_TRACE - logger/getLogger() is NULL: routine=";
		std::cerr << method << " file: " << file << " line: " << line << std::endl;
	}
}

LogTrace::~LogTrace() {
	if(logger != NULL)
		logger->log("Exiting...", log4cpp::Priority::TRACE, method, file, line);
}

log4cpp::Priority::PriorityLevel logging::convertPriority (unsigned int logLevel) {
	switch (logLevel) {
	case 1:
		return log4cpp::Priority::TRACE;
	case 2:
		return log4cpp::Priority::DELOUSE;
	//Old LM_DELOUSE value = 010000
	case LM_DELOUSE:
		return log4cpp::Priority::DELOUSE;
	case 3:
		return log4cpp::Priority::DEBUG;
	case 4:
		return log4cpp::Priority::INFO;
	case 5:
		return log4cpp::Priority::NOTICE;
	case 6:
		return log4cpp::Priority::WARNING;
	case 8:
		return log4cpp::Priority::ERROR;
	case 9:
		return log4cpp::Priority::CRITICAL;
	case 10:
		return log4cpp::Priority::ALERT;
	case 11:
		return log4cpp::Priority::EMERGENCY;
	default:
		return log4cpp::Priority::NOTSET;
	}
}

log4cpp::Priority::PriorityLevel logging::convertPriority (Logging::BaseLog::Priority logLevel) {
	switch (logLevel) {
	case Logging::BaseLog::LM_TRACE:
		return log4cpp::Priority::TRACE;
	case 03:
		return log4cpp::Priority::DELOUSE;
	case Logging::BaseLog::LM_DEBUG:
		return log4cpp::Priority::DEBUG;
	case Logging::BaseLog::LM_INFO:
		return log4cpp::Priority::INFO;
	case Logging::BaseLog::LM_NOTICE:
		return log4cpp::Priority::NOTICE;
	case Logging::BaseLog::LM_WARNING:
		return log4cpp::Priority::WARNING;
	case Logging::BaseLog::LM_ERROR:
		return log4cpp::Priority::ERROR;
	case Logging::BaseLog::LM_CRITICAL:
		return log4cpp::Priority::CRITICAL;
	case Logging::BaseLog::LM_ALERT:
		return log4cpp::Priority::ALERT;
	case Logging::BaseLog::LM_EMERGENCY:
		return log4cpp::Priority::EMERGENCY;
	default:
		return log4cpp::Priority::NOTSET;
	}
}

log4cpp::Priority::PriorityLevel logging::convertPriority(ACE_Log_Priority logLevel) {
	switch (logLevel) {
	case LM_TRACE:
		return log4cpp::Priority::TRACE;
	case LM_DEBUG:
		return log4cpp::Priority::DEBUG;
	case LM_INFO:
		return log4cpp::Priority::INFO;
	case LM_NOTICE:
		return log4cpp::Priority::NOTICE;
	case LM_WARNING:
		return log4cpp::Priority::WARNING;
	case LM_ERROR:
		return log4cpp::Priority::ERROR;
	case LM_CRITICAL:
		return log4cpp::Priority::CRITICAL;
	case LM_ALERT:
		return log4cpp::Priority::ALERT;
	case LM_EMERGENCY:
		return log4cpp::Priority::EMERGENCY;
	default:
		return log4cpp::Priority::NOTSET;
	}
}

log4cpp::Priority::PriorityLevel logging::convertPriority (AcsLogLevels::logLevelValue logLevel) {
	switch (logLevel) {
	case AcsLogLevels::TRACE_VAL:
		return log4cpp::Priority::TRACE;
	case AcsLogLevels::DELOUSE_VAL:
		return log4cpp::Priority::DELOUSE;
	case AcsLogLevels::DEBUG_VAL:
		return log4cpp::Priority::DEBUG;
	case AcsLogLevels::INFO_VAL:
		return log4cpp::Priority::INFO;
	case AcsLogLevels::NOTICE_VAL:
		return log4cpp::Priority::NOTICE;
	case AcsLogLevels::WARNING_VAL:
		return log4cpp::Priority::WARNING;
	case AcsLogLevels::ERROR_VAL:
		return log4cpp::Priority::ERROR;
	case AcsLogLevels::CRITICAL_VAL:
		return log4cpp::Priority::CRITICAL;
	case AcsLogLevels::ALERT_VAL:
		return log4cpp::Priority::ALERT;
	case AcsLogLevels::EMERGENCY_VAL:
		return log4cpp::Priority::EMERGENCY;
	default:
		return log4cpp::Priority::NOTSET;
	}
}

<|endoftext|>


<commit_before>#include <ros/ros.h>
// actionlib
#include <actionlib/client/simple_action_client.h>
#include <actionlib/client/terminal_state.h>
// messages
#include <move_base_msgs/MoveBaseAction.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/OccupancyGrid.h>
// tf
#include <tf/transform_listener.h>
#include <tf/transform_datatypes.h>

nav_msgs::OccupancyGrid costmap_;
bool received_costmap_ = false;

// stops youbot
// publishes 10 msgs over a 1s period
void stopYoubot(ros::Publisher pub) {
  // stop msg Twist
  geometry_msgs::Twist stop_msg;
  stop_msg.linear.x = 0.0;
  stop_msg.linear.y = 0.0;
  stop_msg.linear.z = 0.0;
  stop_msg.angular.x = 0.0;
  stop_msg.angular.y = 0.0;
  stop_msg.angular.z = 0.0;

  ros::Rate r(10);

  for (int i = 0; i < 10; i++) {
    pub.publish(stop_msg);
    ros::spinOnce();
    r.sleep();
  }
}

// processes costmap to find area(s) of interest
// identifies maxima that have surrounding free space
void processMap() {
  size_t size = costmap_.data.size();

  ROS_INFO("Cell count of costmap: %lu", size);
  ROS_INFO("Width %d", costmap_.info.width);
  ROS_INFO("Height %d", costmap_.info.height);

  int count = 0;
  int width = costmap_.info.width;
  int height = costmap_.info.height;
  double resolution = costmap_.info.resolution;
  // geometry_msgs::Pose map_pose = costmap_.info.origin;

  int index = 0;
  int offset = 20;
  int thresh = 0; // costmap value
  bool local_max = false;
  count = 0;

  // last accepted Area of Interest
  int last_i = -1;
  int last_j = -1;
  double sameAoiThresh = 10.0; // cells
  bool sameAoi = false;
  // best area of interest
  int best_i = -1;
  int best_j = -1;
  double best_dist = 1000.0;

  // finding local maxima points
  for (int i = offset; i < (width - offset); i++) {
    for (int j = offset; j < (height - offset); j++) {
      index = width * i + j;

      if (costmap_.data[index] == 100) {
        local_max = costmap_.data[width * (i + offset) + j] == thresh && costmap_.data[width * (i - offset) + j] == thresh
                    && costmap_.data[width * i + j + offset] == thresh && costmap_.data[width * i + j - offset] == thresh;
        sameAoi = sqrt(pow(i - last_i, 2) + pow(j - last_j, 2)) < sameAoiThresh;
        if (local_max && !sameAoi) {
          ROS_INFO("Found AOI at (%d,%d)", i, j);
          last_i = i;
          last_j = j;
          count++;
          ROS_INFO("AOI info:");
          ROS_INFO("X offset: %f", (j - width / 2)*resolution);
          ROS_INFO("Y offset: %f", (i - width / 2)*resolution);
          if (sqrt(pow(i - width / 2, 2) + pow(j - width / 2, 2)) < best_dist) {
            best_i = i;
            best_j = j;
            best_dist = sqrt(pow(i - width / 2, 2) + pow(j - width / 2, 2));
          }
        }
      }
    }
  }
  ROS_INFO("costmap local max count: %d", count);

  // find transformation to manipulating youbot
  if (count > 0) {
    try {
      tf::StampedTransform stransform;
      tf::TransformListener listener;
      geometry_msgs::PoseStamped pin;
      pin.header.frame_id = "/youbot_4/base_footprint";
      pin.header.stamp = ros::Time(0);
      geometry_msgs::Quaternion orientation;
      orientation.x = 0.0;
      orientation.y = 0.0;
      orientation.z = 0.0;
      orientation.w = 1.0;
      pin.pose.orientation = orientation;
      pin.pose.position.x = (best_j - width / 2) * resolution;
      pin.pose.position.y = (best_i - width / 2) * resolution;
      geometry_msgs::PoseStamped pout;

      listener.waitForTransform("/youbot_3/base_footprint", pin.header.frame_id.c_str(), ros::Time(0), ros::Duration(13.0) );
      listener.transformPose("/youbot_3/base_footprint", pin, pout);
      ROS_INFO("AOI in frame of Youbot 3, Point (x,y,z): (%f,%f,%f)", pout.pose.position.x, pout.pose.position.y, pout.pose.position.z);

    } catch (tf::TransformException ex) {
      ROS_ERROR("%s", ex.what());
      ros::Duration(1.0).sleep();
    }
  }

}

// stores a copy of the costmap
void costmapCB(const nav_msgs::OccupancyGrid::ConstPtr& msg) {
  ROS_INFO("Costmap msg received");
  costmap_ = (*msg);
  ROS_INFO("Captured origin: (%f,%f)", costmap_.info.origin.position.x, costmap_.info.origin.position.y);
  ROS_INFO("Captured orientation: (%f,%f,%f,%f)", costmap_.info.origin.orientation.x, costmap_.info.origin.orientation.y, costmap_.info.origin.orientation.z, costmap_.info.origin.orientation.w);

  received_costmap_ = true;
}

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

  if (argc != 2)
    return 0;
  bool going = true;
  bool success = false;
  // moving state
  bool moving = false;

  // states:
  // 0 move forward
  // 1 move left
  // 2 move back
  // 3 move right
  // 4 end
  int state = 0;
  int endstate = 4;
  if (atoi(argv[1]) == 0)
    state = 4;

  // action lib client
  actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> move_ac("youbot_4/move_base", true);
  // publisher to stop youbot
  ros::Publisher nav_pub_ = n.advertise<geometry_msgs::Twist>("youbot_4/cmd_vel", 1000);
  ros::Subscriber costm_sub_ = n.subscribe("/youbot_4/move_base_node/local_costmap/costmap", 1, &costmapCB);

  ROS_INFO("Waiting for action server to start.");
  // wait for the action server to start
  move_ac.waitForServer(); //will wait for infinite time
  ROS_INFO("Running.");

  // move base goal
  move_base_msgs::MoveBaseGoal mov_goal;
  geometry_msgs::Quaternion base_orientation;
  base_orientation.x = 0.0;
  base_orientation.y = 0.0;
  base_orientation.z = 0.0;
  base_orientation.w = 1.0;

  double movement_size = 1.5; //meters

  ros::Rate r(10);

  // START
  while (ros::ok() && going) {

    // NAVIGATION
    if (moving) {
      if (move_ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) {
        stopYoubot(nav_pub_);
        state++;
        received_costmap_ = false;
        moving = false;
      } else if (move_ac.getState() == actionlib::SimpleClientGoalState::ABORTED) {
        stopYoubot(nav_pub_);
        going = false;
        moving = false;
      }

    } else if (state == 0) {
      // go forward 1m
      geometry_msgs::PoseStamped pose;
      pose.header.frame_id = "youbot_4/base_footprint";
      pose.pose.position.x = movement_size;
      pose.pose.position.y = 0.0;
      pose.pose.position.z = 0.0;
      pose.pose.orientation = base_orientation;
      mov_goal.target_pose = pose;
      move_ac.sendGoal(mov_goal);
      moving = true;

    } else if (state == 1) {
      // move left 1m
      geometry_msgs::PoseStamped pose;
      pose.header.frame_id = "youbot_4/base_footprint";
      pose.pose.position.x = 0.0;
      pose.pose.position.y = movement_size;
      pose.pose.position.z = 0.0;
      pose.pose.orientation = base_orientation;
      mov_goal.target_pose = pose;
      move_ac.sendGoal(mov_goal);
      moving = true;

    } else if (state == 2) {
      // move back 1m
      geometry_msgs::PoseStamped pose;
      pose.header.frame_id = "youbot_4/base_footprint";
      pose.pose.position.x = -movement_size;
      pose.pose.position.y = 0.0;
      pose.pose.position.z = 0.0;
      pose.pose.orientation = base_orientation;
      mov_goal.target_pose = pose;
      move_ac.sendGoal(mov_goal);
      moving = true;

    } else if (state == 3) {
      // move back 1m
      geometry_msgs::PoseStamped pose;
      pose.header.frame_id = "youbot_4/base_footprint";
      pose.pose.position.x = 0.0;
      pose.pose.position.y = -movement_size;
      pose.pose.position.z = 0.0;
      pose.pose.orientation = base_orientation;
      mov_goal.target_pose = pose;
      move_ac.sendGoal(mov_goal);
      moving = true;

    } else if (state == endstate) {
      if (received_costmap_) {
        success = true;
        going = false;
      }
    }
    r.sleep();
    ros::spinOnce();
  }// end while going
  stopYoubot(nav_pub_);

  // processing costmap
  processMap();
  // TODO from AOI found, publish to areas of interest topic

  if (success) {
    ROS_INFO("Task successful!");
  } else {
    ROS_INFO("Task failed! At state: %d", state);
  }

  // just precaution
  stopYoubot(nav_pub_);
  //exit
  return 0;
}
<commit_msg>introduced 'human in loop' to select area of interest<commit_after>#include <ros/ros.h>
// actionlib
#include <actionlib/client/simple_action_client.h>
#include <actionlib/client/terminal_state.h>
// messages
#include <move_base_msgs/MoveBaseAction.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/OccupancyGrid.h>
// tf
#include <tf/transform_listener.h>
#include <tf/transform_datatypes.h>

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

nav_msgs::OccupancyGrid costmap_;
bool received_costmap_ = false;

// stops youbot
// publishes 10 msgs over a 1s period
void stopYoubot(ros::Publisher pub) {
  // stop msg Twist
  geometry_msgs::Twist stop_msg;
  stop_msg.linear.x = 0.0;
  stop_msg.linear.y = 0.0;
  stop_msg.linear.z = 0.0;
  stop_msg.angular.x = 0.0;
  stop_msg.angular.y = 0.0;
  stop_msg.angular.z = 0.0;

  ros::Rate r(10);

  for (int i = 0; i < 10; i++) {
    pub.publish(stop_msg);
    ros::spinOnce();
    r.sleep();
  }
}

// processes costmap to find area(s) of interest
// identifies maxima that have surrounding free space
std::vector<geometry_msgs::Point> processMap() {
  std::vector<geometry_msgs::Point> AOIs;
  size_t size = costmap_.data.size();

  ROS_INFO("Cell count of costmap: %lu", size);
  ROS_INFO("Width %d", costmap_.info.width);
  ROS_INFO("Height %d", costmap_.info.height);

  int width = costmap_.info.width;
  int height = costmap_.info.height;
  double resolution = costmap_.info.resolution;
  // geometry_msgs::Pose map_pose = costmap_.info.origin;

  int index = 0;
  int offset = 20;
  int thresh = 0; // costmap value
  bool local_max = false;

  // last accepted Area of Interest
  int last_i = -1;
  int last_j = -1;
  double sameAoiThresh = 10.0; // cells
  bool sameAoi = false;

  // finding local maxima points
  for (int i = offset; i < (width - offset); i++) {
    for (int j = offset; j < (height - offset); j++) {
      index = width * i + j;

      if (costmap_.data[index] == 100) {
        local_max = costmap_.data[width * (i + offset) + j] == thresh && costmap_.data[width * (i - offset) + j] == thresh
                    && costmap_.data[width * i + j + offset] == thresh && costmap_.data[width * i + j - offset] == thresh;
        sameAoi = sqrt(pow(i - last_i, 2) + pow(j - last_j, 2)) < sameAoiThresh;
        if (local_max && !sameAoi) {
          ROS_INFO("Found AOI at (%d,%d)", i, j);
          last_i = i;
          last_j = j;
          geometry_msgs::Point aoi;
          aoi.x = (j - width / 2) * resolution;
          aoi.y = (i - width / 2) * resolution;
          aoi.z = 0.0;
          AOIs.push_back(aoi);
          ROS_INFO("AOI info:");
          ROS_INFO("X offset: %f", (j - width / 2)*resolution);
          ROS_INFO("Y offset: %f", (i - width / 2)*resolution);
        }
      }
    }
  }
  ROS_INFO("costmap local has %lu AOIs", AOIs.size());

  for (size_t i = 0; i < AOIs.size(); i++) {
    // find transformation to manipulating youbot for each AOI
    try {
      tf::StampedTransform stransform;
      tf::TransformListener listener;
      geometry_msgs::PoseStamped pin;
      pin.header.frame_id = "/youbot_4/base_footprint";
      pin.header.stamp = ros::Time(0);
      geometry_msgs::Quaternion orientation;
      orientation.x = 0.0;
      orientation.y = 0.0;
      orientation.z = 0.0;
      orientation.w = 1.0;
      pin.pose.orientation = orientation;
      pin.pose.position.x = AOIs[i].x;
      pin.pose.position.y = AOIs[i].y;
      geometry_msgs::PoseStamped pout;

      listener.waitForTransform("/youbot_3/base_footprint", pin.header.frame_id.c_str(), ros::Time(0), ros::Duration(13.0) );
      listener.transformPose("/youbot_3/base_footprint", pin, pout);
      // ROS_INFO("AOI in frame of Youbot 3, Point (x,y,z): (%f,%f,%f)", pout.pose.position.x, pout.pose.position.y, pout.pose.position.z);
      AOIs[i].x = pout.pose.position.x;
      AOIs[i].y = pout.pose.position.y;

    } catch (tf::TransformException ex) {
      ROS_ERROR("%s", ex.what());
      ros::Duration(1.0).sleep();
    }
  }
  return AOIs;
}

// stores a copy of the costmap
void costmapCB(const nav_msgs::OccupancyGrid::ConstPtr& msg) {
  ROS_INFO("Costmap msg received");
  costmap_ = (*msg);
  received_costmap_ = true;
}

size_t promptUser(  std::vector<geometry_msgs::Point> aois) {

  for (size_t i = 0; i < aois.size(); i++) {
    ROS_INFO("AOI %lu: (%f,%f,0.0)", i, aois[i].x, aois[i].y);
  }
  ROS_INFO("Which area would you like to explore?");

  string input = "";
  size_t myNumber = 0;
  while (true) {
    cout << "Please enter a valid AOI index: ";
    getline(cin, input);

    // This code converts from string to number safely.
    stringstream myStream(input);
    if (myStream >> myNumber && myNumber < aois.size() && myNumber >= 0)
      break;
    cout << "Invalid AOI, please try again" << endl;
  }
  return myNumber;
}

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

  if (argc != 2)
    return 0;
  bool going = true;
  bool success = false;
  // moving state
  bool moving = false;

  // states:
  // 0 move forward
  // 1 move left
  // 2 move back
  // 3 move right
  // 4 end
  int state = 0;
  int endstate = 4;
  if (atoi(argv[1]) == 0)
    state = 4;

  // action lib client
  actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> move_ac("youbot_4/move_base", true);
  // publisher to stop youbot
  ros::Publisher nav_pub_ = n.advertise<geometry_msgs::Twist>("youbot_4/cmd_vel", 1000);
  ros::Subscriber costm_sub_ = n.subscribe("/youbot_4/move_base_node/local_costmap/costmap", 1, &costmapCB);
  ros::Publisher aoi_pub = n.advertise<geometry_msgs::Point>("areas_of_interest", 10);

  ROS_INFO("Waiting for action server to start.");
  // wait for the action server to start
  move_ac.waitForServer(); //will wait for infinite time
  ROS_INFO("Running.");

  // move base goal
  move_base_msgs::MoveBaseGoal mov_goal;
  geometry_msgs::Quaternion base_orientation;
  base_orientation.x = 0.0;
  base_orientation.y = 0.0;
  base_orientation.z = 0.0;
  base_orientation.w = 1.0;

  double movement_size = 1.5; //meters

  ros::Rate r(10);

  // START
  while (ros::ok() && going) {

    // NAVIGATION
    if (moving) {
      if (move_ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) {
        stopYoubot(nav_pub_);
        state++;
        received_costmap_ = false;
        moving = false;
      } else if (move_ac.getState() == actionlib::SimpleClientGoalState::ABORTED) {
        stopYoubot(nav_pub_);
        going = false;
        moving = false;
      }

    } else if (state == 0) {
      // go forward 1m
      geometry_msgs::PoseStamped pose;
      pose.header.frame_id = "youbot_4/base_footprint";
      pose.pose.position.x = movement_size;
      pose.pose.position.y = 0.0;
      pose.pose.position.z = 0.0;
      pose.pose.orientation = base_orientation;
      mov_goal.target_pose = pose;
      move_ac.sendGoal(mov_goal);
      moving = true;

    } else if (state == 1) {
      // move left 1m
      geometry_msgs::PoseStamped pose;
      pose.header.frame_id = "youbot_4/base_footprint";
      pose.pose.position.x = 0.0;
      pose.pose.position.y = movement_size;
      pose.pose.position.z = 0.0;
      pose.pose.orientation = base_orientation;
      mov_goal.target_pose = pose;
      move_ac.sendGoal(mov_goal);
      moving = true;

    } else if (state == 2) {
      // move back 1m
      geometry_msgs::PoseStamped pose;
      pose.header.frame_id = "youbot_4/base_footprint";
      pose.pose.position.x = -movement_size;
      pose.pose.position.y = 0.0;
      pose.pose.position.z = 0.0;
      pose.pose.orientation = base_orientation;
      mov_goal.target_pose = pose;
      move_ac.sendGoal(mov_goal);
      moving = true;

    } else if (state == 3) {
      // move back 1m
      geometry_msgs::PoseStamped pose;
      pose.header.frame_id = "youbot_4/base_footprint";
      pose.pose.position.x = 0.0;
      pose.pose.position.y = -movement_size;
      pose.pose.position.z = 0.0;
      pose.pose.orientation = base_orientation;
      mov_goal.target_pose = pose;
      move_ac.sendGoal(mov_goal);
      moving = true;

    } else if (state == endstate) {
      if (received_costmap_) {
        success = true;
        going = false;
      }
    }
    r.sleep();
    ros::spinOnce();
  }// end while going
  stopYoubot(nav_pub_);

  // processing costmap
  std::vector<geometry_msgs::Point> AOIs = processMap();

  if (AOIs.size() > 0) {
    // TODO prompt use which AOI to choose from
    size_t aoi_index = promptUser(AOIs);

    // TODO publish AOI
    ROS_INFO("AOI %lu chosen", aoi_index);
    aoi_pub.publish(AOIs[aoi_index]);
  }

  if (success) {
    ROS_INFO("Task successful!");
  } else {
    ROS_INFO("Task failed! At state: %d", state);
  }

  // just precaution
  stopYoubot(nav_pub_);
  //exit
  return 0;
}
<|endoftext|>


<commit_before>// RUN: rm -rf %T/coverage-basic
// RUN: mkdir %T/coverage-basic && cd %T/coverage-basic
// RUN: %clangxx_asan -fsanitize-coverage=func %s -o test.exe
// RUN: %env_asan_opts=coverage=1 %run ./test.exe
//
// RUN: %sancov print *.sancov | FileCheck %s
#include <stdio.h>

void foo() { fputs("FOO", stderr); }
void bar() { fputs("BAR", stderr); }

int main(int argc, char **argv) {
  if (argc == 2) {
    foo();
    bar();
  } else {
    bar();
    foo();
  }
}

// CHECK: 0x{{[0-9a-f]*}}
// CHECK: 0x{{[0-9a-f]*}}
// CHECK: 0x{{[0-9a-f]*}}
// CHECK-NOT: 0x{{[0-9a-f]*}}
<commit_msg>Speculative fix for WinASan after r301994<commit_after>// RUN: rm -rf %T/coverage-basic
// RUN: mkdir %T/coverage-basic && cd %T/coverage-basic
// RUN: %clangxx_asan -fsanitize-coverage=func,trace-pc %s -o test.exe
// RUN: %env_asan_opts=coverage=1 %run ./test.exe
//
// RUN: %sancov print *.sancov | FileCheck %s
#include <stdio.h>

void foo() { fputs("FOO", stderr); }
void bar() { fputs("BAR", stderr); }

int main(int argc, char **argv) {
  if (argc == 2) {
    foo();
    bar();
  } else {
    bar();
    foo();
  }
}

// CHECK: 0x{{[0-9a-f]*}}
// CHECK: 0x{{[0-9a-f]*}}
// CHECK: 0x{{[0-9a-f]*}}
// CHECK-NOT: 0x{{[0-9a-f]*}}
<|endoftext|>


<commit_before>  ///////////////////////////////////////////////////////////////////////////
  ///\file AddTaskEMCALPhotonIsolation.C
  ///\brief Configuration of AliAnalysisTaskEMCALPhotonIsolation
  ///
  /// Version to be used in lego train for testing on pp@7TeV
  ///
  /// \author Lucile Ronflette <lucile.ronflette@cern.ch>, SUBATECH, Nantes
  /// \author Davide Francesco Lodato <davide.francesco.lodato@cern.ch>, Utrecht University
  /// \author Marco Marquard <marco.marquard@cern.ch>, University Frankfurt am Main
  ///////////////////////////////////////////////////////////////////////////

AliAnalysisTaskEMCALPhotonIsolation* AddTaskEMCALPhotonIsolation(
                                                                 const char*            periodstr                 = "LHC11c",
                                                                 const char*            ntracks                   = "EmcalTracks",
                                                                 const char*            nclusters                 = "EmcalClusters",
                                                                 const UInt_t           pSel                      = AliVEvent::kEMC7,
                                                                 const TString          dType                     = "ESD",
                                                                 const Bool_t		        bHisto  		              = kTRUE,
                                                                 const Int_t	      	  iOutput	  	              = 0,
                                                                 const Bool_t	          bIsMC  	                  = kFALSE,
                                                                 const Bool_t           bMCNormalization          = kFALSE,
                                                                 const Bool_t           bNLMCut                   = kFALSE,
                                                                 const Int_t            NLMCut                    = 0,
                                                                 const Double_t         minPtCutCluster           = 0.3,
                                                                 const Double_t         EtIso                     = 2.,
                                                                 const Int_t            iIsoMethod                = 1,
                                                                 const Int_t            iEtIsoMethod              = 0,
                                                                 const Int_t            iUEMethod                 = 1,
                                                                 const Bool_t           bUseofTPC                 = kFALSE,
                                                                 const Double_t         TMdeta                    = 0.02,
                                                                 const Double_t         TMdphi                    = 0.03,
                                                                 const Bool_t           bTMClusterRejection       = kTRUE,
                                                                 const Bool_t           bTMClusterRejectionInCone = kTRUE,
                                                                 const Float_t          iIsoConeRadius            = 0.4
                                                                 )
{

  printf("Preparing neutral cluster analysis\n");
  /*  // #### Detect the demanded trigger with its readable name
   TString triggerName(Form("Trigger_%i", trigger));
   if (trigger == AliVEvent::kAnyINT)
   triggerName = "kAnyINT";
   else if (trigger == AliVEvent::kAny)
   triggerName = "kAny";
   else if(trigger == AliVEvent::kINT7)
   triggerName = "kINT7";
   else if(trigger == AliVEvent::kMB)
   triggerName = "kMB";
   else if(trigger == AliVEvent::kEMC7)
   triggerName = "kEMC7";
   else if(trigger == AliVEvent::kEMCEJE)
   triggerName = "kEMCEJE";
   else if(trigger == AliVEvent::kEMCEGA)
   triggerName = "kEMCEGA";
   */
    // #### Define manager and data container names
  AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager();
  if (!manager) {
    ::Error("AddTaskEMCALPhotonIsolation", "No analysis manager to connect to.");
    return NULL;
  }

    //   //------------------------------- Tracks used for analysis -------------------------------------------
  const Double_t edist = 440;
  TString period(periodstr);
  TString inputTracksAna = "FilterTracksAna";
  Double_t trackeff           = 1.0;
  Bool_t doAODTrackProp=kTRUE;
    //   // tracks to be used in analysis
  if(dType == "ESD") {

    TString trackCutsAna(Form("Hybrid_%s", period.Data()));
      //   gROOT->LoadMacro("./AddTaskEmcalEsdTrackFilter.C");
    AliEmcalEsdTrackFilterTask *esdfilterAna =new AliEmcalEsdTrackFilterTask("AliEmcalEsdTrackFilterTaskAna");

      //-------------------------------------------------------
      // Init the task and do settings
      //-------------------------------------------------------

    gROOT->LoadMacro("$ALICE_PHYSICS/PWGJE/macros/CreateTrackCutsPWGJE.C");
    /* hybrid track cuts*/
    AliESDtrackCuts *cutsp2 = CreateTrackCutsPWGJE(10001008);       //1000 adds SPD any requirement
    esdfilterAna->SetTrackCuts(cutsp2);
      //    AliESDtrackCuts *hybsp = CreateTrackCutsPWGJE(10041008);       //1004 removes ITSrefit requirement from standard set
    AliESDtrackCuts *hybsp = CreateTrackCutsPWGJE(10011008);
      //   hybsp->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kOff);
    esdfilterAna->SetHybridTrackCuts(hybsp);
    esdfilterAna->SetIncludeNoITS(kFALSE);

    esdfilterAna->SetTracksName(inputTracksAna.Data());

    cout<<"track cuts for analysis " << trackCutsAna.Data()<<endl;
    esdfilterAna->SetDoPropagation(kTRUE);
    esdfilterAna->SetDist(edist);
    esdfilterAna->SelectCollisionCandidates(pSel);
    esdfilterAna->SetTrackEfficiency(trackeff);

    manager->AddTask(esdfilterAna);
    AliAnalysisDataContainer *cinput1 = manager->GetCommonInputContainer();
    manager->ConnectInput(esdfilterAna, 0, cinput1);

      ///    delete DataSet;
      //  delete CutsType;
  }
  else if (dType=="AOD"){
    TString trackCutsAna(Form("Hybrid_%s", period.Data()));

    AliEmcalAodTrackFilterTask *aodfilterAna = new AliEmcalAodTrackFilterTask("AliEmcalAodTrackFilterTask");
    aodfilterAna->SetTracksOutName(inputTracksAna.Data());
    aodfilterAna->SetTracksInName("tracks");
    aodfilterAna->SetMC(bIsMC);

    Bool_t includeNoITS  = kFALSE;
    Bool_t doProp        = kFALSE; //force propagation of all tracks to EMCal
    Bool_t doAttemptProp = kTRUE;  //only propagate the tracks which were not propagated during AOD filtering

    TString strTrackCuts(trackCutsAna);
    strTrackCuts.ToLower();

    TString runPeriod(period.Data());
    runPeriod.ToLower();

    if(strTrackCuts.Contains("hybrid")){
      if (runPeriod == "lhc10d" || runPeriod == "lhc10e" || runPeriod == "lhc10h" ||
          runPeriod == "lhc11h" || runPeriod == "lhc12a" || runPeriod == "lhc12b" ||
          runPeriod == "lhc12c" || runPeriod == "lhc12d" || runPeriod == "lhc12e" ||
          runPeriod == "lhc12f" || runPeriod == "lhc12g" || runPeriod == "lhc12h" ||
          runPeriod == "lhc12i" || runPeriod == "lhc13b" || runPeriod == "lhc13c" ||
          runPeriod == "lhc13d" || runPeriod == "lhc13e" || runPeriod == "lhc13f" ||
          runPeriod == "lhc13g"
          ) {
        aodfilterAna->SetAODfilterBits(256,512); // hybrid tracks
        if (runPeriod == "lhc10d" || runPeriod == "lhc10e" || runPeriod == "lhc10h")
          includeNoITS = kTRUE;
      } else if (runPeriod == "lhc12a15e"   || runPeriod.Contains("lhc12a17") || runPeriod == "lhc13b4" ||
                 runPeriod == "lhc13b4_fix" || runPeriod == "lhc13b4_plus"    || runPeriod.Contains("lhc14a1") || runPeriod.Contains("lhc13b2_efix") || runPeriod.Contains("lhc13e5") || runPeriod.Contains("lhc13e4") || runPeriod.Contains("lhc14k1a") || runPeriod.Contains("lhc14k1b")
                 ) {
        aodfilterAna->SetAODfilterBits(256,512); // hybrid tracks
      } else if (runPeriod == "lhc11a" || runPeriod == "lhc10hold") {
        aodfilterAna->SetAODfilterBits(256,16); // hybrid tracks
        includeNoITS = kTRUE;
      }
      else if (runPeriod.Contains("lhc12a15a") || runPeriod == "lhc12a15f" || runPeriod == "lhc12a15g") {
        aodfilterAna->SetAODfilterBits(256,16); // hybrid tracks
        includeNoITS = kTRUE;
      }
      else if (runPeriod.Contains("lhc11c") || runPeriod.Contains("lhc11d")){
        aodfilterAna->SetAODfilterBits(256,512);
        includeNoITS=kFALSE;
      }
      else {
        if (!runPeriod.IsNull())
          ::Warning("Run period %s not known. It will use IsHybridGlobalConstrainedGlobal.", runPeriod.Data());
      }
    }

    aodfilterAna->SetIncludeNoITS(includeNoITS);
    aodfilterAna->SetAttemptProp(doAttemptProp);
    if (doAODTrackProp) {
      aodfilterAna->SetDist(edist);
      aodfilterAna->SetAttemptPropMatch(kTRUE);
    }
    aodfilterAna->SetDoPropagation(kTRUE);
    aodfilterAna->SelectCollisionCandidates(pSel);
    aodfilterAna->SetTrackEfficiency(trackeff);

    manager->AddTask(aodfilterAna);

      // Create containers for input/output
    AliAnalysisDataContainer *cinput1 = manager->GetCommonInputContainer();
    manager->ConnectInput(aodfilterAna, 0,  cinput1 );
  }
  TString emctracksAna = Form("EmcalTracks_%s",inputTracksAna.Data());

  printf("Creating container names for cluster analysis\n");
  TString myContName("");
  if(bIsMC)
    myContName = Form("Analysis_Neutrals_MC");
  else
    myContName = Form("Analysis_Neutrals");

    // #### Define analysis task
  AliAnalysisTaskEMCALPhotonIsolation* task = new AliAnalysisTaskEMCALPhotonIsolation("Analysis",bHisto);

    // #### Task preferences
  task->SetOutputFormat(iOutput);
  task->SetLCAnalysis(kFALSE);
  task->SetIsoConeRadius(iIsoConeRadius);
  task->SetEtIsoThreshold(EtIso); // after should be replace by EtIso
  task->SetCTMdeltaEta(TMdeta); // after should be replaced by TMdeta
  task->SetCTMdeltaPhi(TMdphi); // after should be replaced by TMdphi
  task->SetQA(kTRUE);
  task->SetIsoMethod(iIsoMethod);
  task->SetEtIsoMethod(iEtIsoMethod);
  task->SetUEMethod(iUEMethod);
  task->SetUSEofTPC(bUseofTPC);
  task->SetMC(bIsMC);
  if(bIsMC && bMCNormalization) task->SetIsPythia(kTRUE);

  task->SetNLMCut(bNLMCut,NLMCut);

 TString name(Form("PhotonIsolation_%s_%s", ntracks, nclusters));
 cout<<"name des containers  "<<name.Data()<<endl;
    AliParticleContainer *trackCont  = task->AddParticleContainer(ntracks);
 //  AliParticleContainer *clusterCont = task->AddParticleContainer(nclusters);
  AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);
 // if (clusterCont) clusterCont->SetClusPtCut(minPtCutCluster);
    //  AliParticleContainer *hybTrackCont = task->AddParticleContainer(nhybtracks);

  printf("Task for neutral cluster analysis created and configured, pass it to AnalysisManager\n");
    // #### Add analysis task
  manager->AddTask(task);

  AliAnalysisDataContainer *contHistos = manager->CreateContainer(myContName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer,Form("%s:NeutralClusters_TM_%s_CPVe%.2lf_CPVp%.2lf_IsoMet%d_EtIsoMet%d_UEMet%d_TPCbound_%s_IsoConeR%.1f_NLMCut_%s_nNLM%d",AliAnalysisManager::GetCommonFileName(),bTMClusterRejection? "On" :"Off", TMdeta , TMdphi ,iIsoMethod,iEtIsoMethod,iUEMethod,bUseofTPC ? "Yes" : "No",iIsoConeRadius,bNLMCut ? "On": "Off",NLMCut));
  AliAnalysisDataContainer *cinput  = manager->GetCommonInputContainer();
  manager->ConnectInput(task, 0, cinput);
  manager->ConnectOutput(task, 1, contHistos);

    //if(isEMCalTrain)
    //    RequestMemory(task,200*1024);

  return task;
}
<commit_msg>Fix bug for Output Container name<commit_after>  ///////////////////////////////////////////////////////////////////////////
  ///\file AddTaskEMCALPhotonIsolation.C
  ///\brief Configuration of AliAnalysisTaskEMCALPhotonIsolation
  ///
  /// Version to be used in lego train for testing on pp@7TeV
  ///
  /// \author Lucile Ronflette <lucile.ronflette@cern.ch>, SUBATECH, Nantes
  /// \author Davide Francesco Lodato <davide.francesco.lodato@cern.ch>, Utrecht University
  /// \author Marco Marquard <marco.marquard@cern.ch>, University Frankfurt am Main
  ///////////////////////////////////////////////////////////////////////////

AliAnalysisTaskEMCALPhotonIsolation* AddTaskEMCALPhotonIsolation(
                                                                 const char*            periodstr                 = "LHC11c",
                                                                 const char*            ntracks                   = "EmcalTracks",
                                                                 const char*            nclusters                 = "EmcalClusters",
                                                                 const UInt_t           pSel                      = AliVEvent::kEMC7,
                                                                 const TString          dType                     = "ESD",
                                                                 const Bool_t		        bHisto  		              = kTRUE,
                                                                 const Int_t	      	  iOutput	  	              = 0,
                                                                 const Bool_t	          bIsMC  	                  = kFALSE,
                                                                 const Bool_t           bMCNormalization          = kFALSE,
                                                                 const Bool_t           bNLMCut                   = kFALSE,
                                                                 const Int_t            NLMCut                    = 0,
                                                                 const Double_t         minPtCutCluster           = 0.3,
                                                                 const Double_t         EtIso                     = 2.,
                                                                 const Int_t            iIsoMethod                = 1,
                                                                 const Int_t            iEtIsoMethod              = 0,
                                                                 const Int_t            iUEMethod                 = 1,
                                                                 const Bool_t           bUseofTPC                 = kFALSE,
                                                                 const Double_t         TMdeta                    = 0.02,
                                                                 const Double_t         TMdphi                    = 0.03,
                                                                 const Bool_t           bTMClusterRejection       = kTRUE,
                                                                 const Bool_t           bTMClusterRejectionInCone = kTRUE,
                                                                 const Float_t          iIsoConeRadius            = 0.4
                                                                 )
{

  printf("Preparing neutral cluster analysis\n");
  /*  // #### Detect the demanded trigger with its readable name
   TString triggerName(Form("Trigger_%i", trigger));
   if (trigger == AliVEvent::kAnyINT)
   triggerName = "kAnyINT";
   else if (trigger == AliVEvent::kAny)
   triggerName = "kAny";
   else if(trigger == AliVEvent::kINT7)
   triggerName = "kINT7";
   else if(trigger == AliVEvent::kMB)
   triggerName = "kMB";
   else if(trigger == AliVEvent::kEMC7)
   triggerName = "kEMC7";
   else if(trigger == AliVEvent::kEMCEJE)
   triggerName = "kEMCEJE";
   else if(trigger == AliVEvent::kEMCEGA)
   triggerName = "kEMCEGA";
   */
    // #### Define manager and data container names
  AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager();
  if (!manager) {
    ::Error("AddTaskEMCALPhotonIsolation", "No analysis manager to connect to.");
    return NULL;
  }

    //   //------------------------------- Tracks used for analysis -------------------------------------------
  const Double_t edist = 440;
  TString period(periodstr);
  TString inputTracksAna = "FilterTracksAna";
  Double_t trackeff           = 1.0;
  Bool_t doAODTrackProp=kTRUE;
    //   // tracks to be used in analysis
  if(dType == "ESD") {

    TString trackCutsAna(Form("Hybrid_%s", period.Data()));
      //   gROOT->LoadMacro("./AddTaskEmcalEsdTrackFilter.C");
    AliEmcalEsdTrackFilterTask *esdfilterAna =new AliEmcalEsdTrackFilterTask("AliEmcalEsdTrackFilterTaskAna");

      //-------------------------------------------------------
      // Init the task and do settings
      //-------------------------------------------------------

    gROOT->LoadMacro("$ALICE_PHYSICS/PWGJE/macros/CreateTrackCutsPWGJE.C");
    /* hybrid track cuts*/
    AliESDtrackCuts *cutsp2 = CreateTrackCutsPWGJE(10001008);       //1000 adds SPD any requirement
    esdfilterAna->SetTrackCuts(cutsp2);
      //    AliESDtrackCuts *hybsp = CreateTrackCutsPWGJE(10041008);       //1004 removes ITSrefit requirement from standard set
    AliESDtrackCuts *hybsp = CreateTrackCutsPWGJE(10011008);
      //   hybsp->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kOff);
    esdfilterAna->SetHybridTrackCuts(hybsp);
    esdfilterAna->SetIncludeNoITS(kFALSE);

    esdfilterAna->SetTracksName(inputTracksAna.Data());

    cout<<"track cuts for analysis " << trackCutsAna.Data()<<endl;
    esdfilterAna->SetDoPropagation(kTRUE);
    esdfilterAna->SetDist(edist);
    esdfilterAna->SelectCollisionCandidates(pSel);
    esdfilterAna->SetTrackEfficiency(trackeff);

    manager->AddTask(esdfilterAna);
    AliAnalysisDataContainer *cinput1 = manager->GetCommonInputContainer();
    manager->ConnectInput(esdfilterAna, 0, cinput1);

      ///    delete DataSet;
      //  delete CutsType;
  }
  else if (dType=="AOD"){
    TString trackCutsAna(Form("Hybrid_%s", period.Data()));

    AliEmcalAodTrackFilterTask *aodfilterAna = new AliEmcalAodTrackFilterTask("AliEmcalAodTrackFilterTask");
    aodfilterAna->SetTracksOutName(inputTracksAna.Data());
    aodfilterAna->SetTracksInName("tracks");
    aodfilterAna->SetMC(bIsMC);

    Bool_t includeNoITS  = kFALSE;
    Bool_t doProp        = kFALSE; //force propagation of all tracks to EMCal
    Bool_t doAttemptProp = kTRUE;  //only propagate the tracks which were not propagated during AOD filtering

    TString strTrackCuts(trackCutsAna);
    strTrackCuts.ToLower();

    TString runPeriod(period.Data());
    runPeriod.ToLower();

    if(strTrackCuts.Contains("hybrid")){
      if (runPeriod == "lhc10d" || runPeriod == "lhc10e" || runPeriod == "lhc10h" ||
          runPeriod == "lhc11h" || runPeriod == "lhc12a" || runPeriod == "lhc12b" ||
          runPeriod == "lhc12c" || runPeriod == "lhc12d" || runPeriod == "lhc12e" ||
          runPeriod == "lhc12f" || runPeriod == "lhc12g" || runPeriod == "lhc12h" ||
          runPeriod == "lhc12i" || runPeriod == "lhc13b" || runPeriod == "lhc13c" ||
          runPeriod == "lhc13d" || runPeriod == "lhc13e" || runPeriod == "lhc13f" ||
          runPeriod == "lhc13g"
          ) {
        aodfilterAna->SetAODfilterBits(256,512); // hybrid tracks
        if (runPeriod == "lhc10d" || runPeriod == "lhc10e" || runPeriod == "lhc10h")
          includeNoITS = kTRUE;
      } else if (runPeriod == "lhc12a15e"   || runPeriod.Contains("lhc12a17") || runPeriod == "lhc13b4" ||
                 runPeriod == "lhc13b4_fix" || runPeriod == "lhc13b4_plus"    || runPeriod.Contains("lhc14a1") || runPeriod.Contains("lhc13b2_efix") || runPeriod.Contains("lhc13e5") || runPeriod.Contains("lhc13e4") || runPeriod.Contains("lhc14k1a") || runPeriod.Contains("lhc14k1b")
                 ) {
        aodfilterAna->SetAODfilterBits(256,512); // hybrid tracks
      } else if (runPeriod == "lhc11a" || runPeriod == "lhc10hold") {
        aodfilterAna->SetAODfilterBits(256,16); // hybrid tracks
        includeNoITS = kTRUE;
      }
      else if (runPeriod.Contains("lhc12a15a") || runPeriod == "lhc12a15f" || runPeriod == "lhc12a15g") {
        aodfilterAna->SetAODfilterBits(256,16); // hybrid tracks
        includeNoITS = kTRUE;
      }
      else if (runPeriod.Contains("lhc11c") || runPeriod.Contains("lhc11d")){
        aodfilterAna->SetAODfilterBits(256,512);
        includeNoITS=kFALSE;
      }
      else {
        if (!runPeriod.IsNull())
          ::Warning("Run period %s not known. It will use IsHybridGlobalConstrainedGlobal.", runPeriod.Data());
      }
    }

    aodfilterAna->SetIncludeNoITS(includeNoITS);
    aodfilterAna->SetAttemptProp(doAttemptProp);
    if (doAODTrackProp) {
      aodfilterAna->SetDist(edist);
      aodfilterAna->SetAttemptPropMatch(kTRUE);
    }
    aodfilterAna->SetDoPropagation(kTRUE);
    aodfilterAna->SelectCollisionCandidates(pSel);
    aodfilterAna->SetTrackEfficiency(trackeff);

    manager->AddTask(aodfilterAna);

      // Create containers for input/output
    AliAnalysisDataContainer *cinput1 = manager->GetCommonInputContainer();
    manager->ConnectInput(aodfilterAna, 0,  cinput1 );
  }
  TString emctracksAna = Form("EmcalTracks_%s",inputTracksAna.Data());

  printf("Creating container names for cluster analysis\n");
  TString myContName("");
  if(bIsMC)
    myContName = Form("Analysis_Neutrals_MC");
  else
    myContName = Form("Analysis_Neutrals");

  myContName.Append(Form("_TM_%s_CPVe%.2lf_CPVp%.2lf_IsoMet%d_EtIsoMet%d_UEMet%d_TPCbound_%s_IsoConeR%.1f_NLMCut_%s_nNLM%d",bTMClusterRejection? "On" :"Off", TMdeta , TMdphi ,iIsoMethod,iEtIsoMethod,iUEMethod,bUseofTPC ? "Yes" : "No",iIsoConeRadius,bNLMCut ? "On": "Off",NLMCut));

    // #### Define analysis task
  AliAnalysisTaskEMCALPhotonIsolation* task = new AliAnalysisTaskEMCALPhotonIsolation("Analysis",bHisto);

    // #### Task preferences
  task->SetOutputFormat(iOutput);
  task->SetLCAnalysis(kFALSE);
  task->SetIsoConeRadius(iIsoConeRadius);
  task->SetEtIsoThreshold(EtIso); // after should be replace by EtIso
  task->SetCTMdeltaEta(TMdeta); // after should be replaced by TMdeta
  task->SetCTMdeltaPhi(TMdphi); // after should be replaced by TMdphi
  task->SetQA(kTRUE);
  task->SetIsoMethod(iIsoMethod);
  task->SetEtIsoMethod(iEtIsoMethod);
  task->SetUEMethod(iUEMethod);
  task->SetUSEofTPC(bUseofTPC);
  task->SetMC(bIsMC);
  if(bIsMC && bMCNormalization) task->SetIsPythia(kTRUE);

  task->SetNLMCut(bNLMCut,NLMCut);

 TString name(Form("PhotonIsolation_%s_%s", ntracks, nclusters));
 cout<<"name des containers  "<<name.Data()<<endl;
    AliParticleContainer *trackCont  = task->AddParticleContainer(ntracks);
 //  AliParticleContainer *clusterCont = task->AddParticleContainer(nclusters);
  AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);
 // if (clusterCont) clusterCont->SetClusPtCut(minPtCutCluster);
    //  AliParticleContainer *hybTrackCont = task->AddParticleContainer(nhybtracks);

  printf("Task for neutral cluster analysis created and configured, pass it to AnalysisManager\n");
    // #### Add analysis task
  manager->AddTask(task);

  AliAnalysisDataContainer *contHistos = manager->CreateContainer(myContName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer,Form("%s:NeutralClusters",AliAnalysisManager::GetCommonFileName()));
  AliAnalysisDataContainer *cinput  = manager->GetCommonInputContainer();
  manager->ConnectInput(task, 0, cinput);
  manager->ConnectOutput(task, 1, contHistos);

    //if(isEMCalTrain)
    //    RequestMemory(task,200*1024);

  return task;
}
<|endoftext|>


<commit_before>#include <sepia/util/progargs.h>
#include <iostream>

namespace sepia
{
namespace util
{

std::map< std::string, std::string > ProgArgs::sm_LongArgs;
std::map< std::string, std::pair< std::string, std::string> > ProgArgs::sm_defaults;

void ProgArgs::init( int argc, char** argv )
{
    std::string* last_value = NULL;
    bool last_was_argument = false;
    for( int i = 1; i < argc; i++ ) // i = 0 is the executable.
    {
        std::string str( argv[i] );

        if( ( str.length() > 2 )
         && ( str.compare( 0, 2, "--" ) == 0 ) )
        {
            str.erase( str.begin(), str.begin() + 2 );
            last_value = &sm_LongArgs[ str ];
            last_was_argument = true;
        }
        else if( last_value != NULL && last_was_argument )
        {
            *last_value = str;
            last_was_argument = false;
        }
        else
        {
            last_was_argument = false;
        }
    }
}

bool ProgArgs::contains( const std::string& a_string )
{
    std::map< std::string, std::string >::const_iterator it = sm_LongArgs.find( a_string );

    return it != sm_LongArgs.end();
}

const std::string ProgArgs::value( const std::string& a_string, bool* a_valid )
{
    std::map< std::string, std::string >::const_iterator it = sm_LongArgs.find( a_string );

    if( it != sm_LongArgs.end() )
    {
        if( a_valid )
        {
            *a_valid = true;
        }
        return it->second;
    }
    else
    {
        if( a_valid )
        {
            *a_valid = false;
        }
        return std::string();
    }
}

void ProgArgs::printHelp()
{
    for( const auto& item : sm_defaults )
    {
        std::cerr << "\t --" << item.first << ": " << item.second.second << " (default: " << item.second.first << ")" << std::endl;
    }
}

}
}
<commit_msg>added copyright notice.<commit_after>/*
Copyright (c) 2012-2016, Kai Hugo Hustoft Endresen <kai.endresen@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <sepia/util/progargs.h>
#include <iostream>

namespace sepia
{
namespace util
{

std::map< std::string, std::string > ProgArgs::sm_LongArgs;
std::map< std::string, std::pair< std::string, std::string> > ProgArgs::sm_defaults;

void ProgArgs::init( int argc, char** argv )
{
    std::string* last_value = NULL;
    bool last_was_argument = false;
    for( int i = 1; i < argc; i++ ) // i = 0 is the executable.
    {
        std::string str( argv[i] );

        if( ( str.length() > 2 )
         && ( str.compare( 0, 2, "--" ) == 0 ) )
        {
            str.erase( str.begin(), str.begin() + 2 );
            last_value = &sm_LongArgs[ str ];
            last_was_argument = true;
        }
        else if( last_value != NULL && last_was_argument )
        {
            *last_value = str;
            last_was_argument = false;
        }
        else
        {
            last_was_argument = false;
        }
    }
}

bool ProgArgs::contains( const std::string& a_string )
{
    std::map< std::string, std::string >::const_iterator it = sm_LongArgs.find( a_string );

    return it != sm_LongArgs.end();
}

const std::string ProgArgs::value( const std::string& a_string, bool* a_valid )
{
    std::map< std::string, std::string >::const_iterator it = sm_LongArgs.find( a_string );

    if( it != sm_LongArgs.end() )
    {
        if( a_valid )
        {
            *a_valid = true;
        }
        return it->second;
    }
    else
    {
        if( a_valid )
        {
            *a_valid = false;
        }
        return std::string();
    }
}

void ProgArgs::printHelp()
{
    for( const auto& item : sm_defaults )
    {
        std::cerr << "\t --" << item.first << ": " << item.second.second << " (default: " << item.second.first << ")" << std::endl;
    }
}

}
}
<|endoftext|>