<commit_before>/*
 * Copyright (c) 2011, The University of Oxford
 * 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.
 * 3. Neither the name of the University of Oxford nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * 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 HOLDER 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 "utility/oskar_Device_curand_state.h"
#include "utility/oskar_device_curand_state_init.h"
#include <cstdlib>

#ifdef __cplusplus
extern "C" {
#endif

oskar_Device_curand_state::oskar_Device_curand_state(int num_states)
{
    if (cudaMalloc((void**)&state, num_states * sizeof(curandState)) != CUDA_SUCCESS)
        throw "Error allocating memory oskar_Device_state::curand_state.";
}

oskar_Device_curand_state::~oskar_Device_curand_state()
{
    if (state != NULL) cudaFree(state);
}

int oskar_Device_curand_state::init(int seed, int offset, int use_device_offset)
{
    return oskar_device_curand_state_init(state, num_states, seed, offset,
            use_device_offset);
}

#ifdef __cplusplus
}
#endif
<commit_msg>added missing header include<commit_after>/*
 * Copyright (c) 2011, The University of Oxford
 * 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.
 * 3. Neither the name of the University of Oxford nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * 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 HOLDER 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 "utility/oskar_Device_curand_state.h"
#include "utility/oskar_device_curand_state_init.h"
#include <cstdlib>
#include <cuda.h>

#ifdef __cplusplus
extern "C" {
#endif

oskar_Device_curand_state::oskar_Device_curand_state(int num_states)
{
    if (cudaMalloc((void**)&state, num_states * sizeof(curandState)) != CUDA_SUCCESS)
        throw "Error allocating memory oskar_Device_state::curand_state.";
}

oskar_Device_curand_state::~oskar_Device_curand_state()
{
    if (state != NULL) cudaFree(state);
}

int oskar_Device_curand_state::init(int seed, int offset, int use_device_offset)
{
    return oskar_device_curand_state_init(state, num_states, seed, offset,
            use_device_offset);
}

#ifdef __cplusplus
}
#endif
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

// mapnik
#include <mapnik/debug.hpp>
#include <mapnik/image_reader.hpp>
// boost
#include <boost/shared_ptr.hpp>
#include <boost/filesystem/operations.hpp>

extern "C"
{
#include <tiffio.h>
}

namespace mapnik
{

using std::min;
using std::max;

class tiff_reader : public image_reader
{
    typedef boost::shared_ptr<TIFF> tiff_ptr;
    struct tiff_closer
    {
        void operator() (TIFF * tif)
        {
            if (tif != 0)
            {
                TIFFClose(tif);
            }
        }
    };

private:
    std::string file_name_;
    int read_method_;
    unsigned width_;
    unsigned height_;
    int rows_per_strip_;
    int tile_width_;
    int tile_height_;
    tiff_ptr tif_;
    bool premultiplied_alpha_;
public:
    enum TiffType {
        generic=1,
        stripped,
        tiled
    };
    explicit tiff_reader(std::string const& file_name);
    virtual ~tiff_reader();
    unsigned width() const;
    unsigned height() const;
    bool premultiplied_alpha() const;
    void read(unsigned x,unsigned y,image_data_32& image);
private:
    tiff_reader(const tiff_reader&);
    tiff_reader& operator=(const tiff_reader&);
    void init();
    void read_generic(unsigned x,unsigned y,image_data_32& image);
    void read_stripped(unsigned x,unsigned y,image_data_32& image);
    void read_tiled(unsigned x,unsigned y,image_data_32& image);
    TIFF* load_if_exists(std::string const& filename);
    static void on_error(const char* /*module*/, const char* fmt, va_list argptr);
};

namespace
{
image_reader* create_tiff_reader(std::string const& file)
{
    return new tiff_reader(file);
}

const bool registered = register_image_reader("tiff",create_tiff_reader);
}

tiff_reader::tiff_reader(std::string const& file_name)
    : file_name_(file_name),
      read_method_(generic),
      width_(0),
      height_(0),
      rows_per_strip_(0),
      tile_width_(0),
      tile_height_(0),
      premultiplied_alpha_(false)
{
    init();
}

void tiff_reader::on_error(const char* /*module*/, const char* fmt, va_list argptr)
{
  char msg[10240];
  vsprintf(msg, fmt, argptr);
  throw image_reader_exception(msg);
}

void tiff_reader::init()
{
    // TODO: error handling
    TIFF* tif = load_if_exists(file_name_);
    if (!tif) throw image_reader_exception( std::string("Can't load tiff file: '") + file_name_ + "'");

    TIFFSetWarningHandler(0);
    TIFFSetErrorHandler(on_error);

    char msg[1024];

    if (TIFFRGBAImageOK(tif,msg))
    {
        TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width_);
        TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height_);
        if (TIFFIsTiled(tif))
        {
            TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width_);
            TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height_);
            read_method_=tiled;
        }
        else if (TIFFGetField(tif,TIFFTAG_ROWSPERSTRIP,&rows_per_strip_)!=0)
        {
            read_method_=stripped;
        }
        //TIFFTAG_EXTRASAMPLES
        uint16 extrasamples;
        uint16* sampleinfo;
        TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
                              &extrasamples, &sampleinfo);
        if (extrasamples == 1 &&
            sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA)
        {
            premultiplied_alpha_ = true;
        }
    }
    else
    {
        throw image_reader_exception(msg);
    }
}

tiff_reader::~tiff_reader()
{
}

unsigned tiff_reader::width() const
{
    return width_;
}

unsigned tiff_reader::height() const
{
    return height_;
}

bool tiff_reader::premultiplied_alpha() const
{
    return premultiplied_alpha_;
}

void tiff_reader::read(unsigned x,unsigned y,image_data_32& image)
{
    if (read_method_==stripped)
    {
        read_stripped(x,y,image);
    }
    else if (read_method_==tiled)
    {
        read_tiled(x,y,image);
    }
    else
    {
        read_generic(x,y,image);
    }
}

void tiff_reader::read_generic(unsigned /*x*/,unsigned /*y*/,image_data_32& /*image*/)
{
    TIFF* tif = load_if_exists(file_name_);
    if (tif)
    {
        MAPNIK_LOG_DEBUG(tiff_reader) << "tiff_reader: TODO - tiff is not stripped or tiled";
    }
}

void tiff_reader::read_tiled(unsigned x0,unsigned y0,image_data_32& image)
{
    TIFF* tif = load_if_exists(file_name_);
    if (tif)
    {
        uint32* buf = (uint32*)_TIFFmalloc(tile_width_*tile_height_*sizeof(uint32));
        int width=image.width();
        int height=image.height();

        int start_y=(y0/tile_height_)*tile_height_;
        int end_y=((y0+height)/tile_height_+1)*tile_height_;

        int start_x=(x0/tile_width_)*tile_width_;
        int end_x=((x0+width)/tile_width_+1)*tile_width_;
        int row,tx0,tx1,ty0,ty1;

        for (int y=start_y;y<end_y;y+=tile_height_)
        {
            ty0 = max(y0,(unsigned)y) - y;
            ty1 = min(height+y0,(unsigned)(y+tile_height_)) - y;

            int n0=tile_height_-ty1;
            int n1=tile_height_-ty0-1;

            for (int x=start_x;x<end_x;x+=tile_width_)
            {

                if (!TIFFReadRGBATile(tif,x,y,buf)) break;

                tx0=max(x0,(unsigned)x);
                tx1=min(width+x0,(unsigned)(x+tile_width_));
                row=y+ty0-y0;
                for (int n=n1;n>=n0;--n)
                {
                    image.setRow(row,tx0-x0,tx1-x0,(const unsigned*)&buf[n*tile_width_+tx0-x]);
                    ++row;
                }
            }
        }
        _TIFFfree(buf);
    }
}

void tiff_reader::read_stripped(unsigned x0,unsigned y0,image_data_32& image)
{
    TIFF* tif = load_if_exists(file_name_);
    if (tif)
    {
        uint32* buf = (uint32*)_TIFFmalloc(width_*rows_per_strip_*sizeof(uint32));

        int width=image.width();
        int height=image.height();

        unsigned start_y=(y0/rows_per_strip_)*rows_per_strip_;
        unsigned end_y=((y0+height)/rows_per_strip_+1)*rows_per_strip_;
        bool laststrip=((unsigned)end_y > height_)?true:false;
        int row,tx0,tx1,ty0,ty1;

        tx0=x0;
        tx1=min(width+x0,(unsigned)width_);

        for (unsigned y=start_y; y < end_y; y+=rows_per_strip_)
        {
            ty0 = max(y0,y)-y;
            ty1 = min(height+y0,y+rows_per_strip_)-y;

            if (!TIFFReadRGBAStrip(tif,y,buf)) break;

            row=y+ty0-y0;

            int n0=laststrip ? 0:(rows_per_strip_-ty1);
            int n1=laststrip ? (ty1-ty0-1):(rows_per_strip_-ty0-1);
            for (int n=n1;n>=n0;--n)
            {
                image.setRow(row,tx0-x0,tx1-x0,(const unsigned*)&buf[n*width_+tx0]);
                ++row;
            }
        }
        _TIFFfree(buf);
    }
}

TIFF* tiff_reader::load_if_exists(std::string const& filename)
{
    if (!tif_)
    {
        boost::filesystem::path path(file_name_);
        if (boost::filesystem::is_regular(path)) // exists and regular file
        {
            // File path is a full file path and does exist
            tif_ = tiff_ptr(TIFFOpen(filename.c_str(), "rb"), tiff_closer());
        }
    }
    return tif_.get();
}

} // namespace mapnik
<commit_msg>set TIFFSetErrorHandler to null to start to avoid tiff from printing to stderr on fail - refs #1783<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

// mapnik
#include <mapnik/debug.hpp>
#include <mapnik/image_reader.hpp>
// boost
#include <boost/shared_ptr.hpp>
#include <boost/filesystem/operations.hpp>

extern "C"
{
#include <tiffio.h>
}

namespace mapnik
{

using std::min;
using std::max;

class tiff_reader : public image_reader
{
    typedef boost::shared_ptr<TIFF> tiff_ptr;
    struct tiff_closer
    {
        void operator() (TIFF * tif)
        {
            if (tif != 0)
            {
                TIFFClose(tif);
            }
        }
    };

private:
    std::string file_name_;
    int read_method_;
    unsigned width_;
    unsigned height_;
    int rows_per_strip_;
    int tile_width_;
    int tile_height_;
    tiff_ptr tif_;
    bool premultiplied_alpha_;
public:
    enum TiffType {
        generic=1,
        stripped,
        tiled
    };
    explicit tiff_reader(std::string const& file_name);
    virtual ~tiff_reader();
    unsigned width() const;
    unsigned height() const;
    bool premultiplied_alpha() const;
    void read(unsigned x,unsigned y,image_data_32& image);
private:
    tiff_reader(const tiff_reader&);
    tiff_reader& operator=(const tiff_reader&);
    void init();
    void read_generic(unsigned x,unsigned y,image_data_32& image);
    void read_stripped(unsigned x,unsigned y,image_data_32& image);
    void read_tiled(unsigned x,unsigned y,image_data_32& image);
    TIFF* load_if_exists(std::string const& filename);
    static void on_error(const char* /*module*/, const char* fmt, va_list argptr);
};

namespace
{
image_reader* create_tiff_reader(std::string const& file)
{
    return new tiff_reader(file);
}

const bool registered = register_image_reader("tiff",create_tiff_reader);
}

tiff_reader::tiff_reader(std::string const& file_name)
    : file_name_(file_name),
      read_method_(generic),
      width_(0),
      height_(0),
      rows_per_strip_(0),
      tile_width_(0),
      tile_height_(0),
      premultiplied_alpha_(false)
{
    init();
}

void tiff_reader::on_error(const char* /*module*/, const char* fmt, va_list argptr)
{
  char msg[10240];
  vsprintf(msg, fmt, argptr);
  throw image_reader_exception(msg);
}

void tiff_reader::init()
{
    TIFFSetWarningHandler(0);
    // Note - we intentially set the error handling to null
    // when opening the image for the first time to avoid
    // leaking in TiffOpen: https://github.com/mapnik/mapnik/issues/1783
    TIFFSetErrorHandler(0);
    TIFF* tif = load_if_exists(file_name_);
    if (!tif) throw image_reader_exception( std::string("Can't load tiff file: '") + file_name_ + "'");
    TIFFSetErrorHandler(on_error);

    char msg[1024];

    if (TIFFRGBAImageOK(tif,msg))
    {
        TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width_);
        TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height_);
        if (TIFFIsTiled(tif))
        {
            TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width_);
            TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height_);
            read_method_=tiled;
        }
        else if (TIFFGetField(tif,TIFFTAG_ROWSPERSTRIP,&rows_per_strip_)!=0)
        {
            read_method_=stripped;
        }
        //TIFFTAG_EXTRASAMPLES
        uint16 extrasamples;
        uint16* sampleinfo;
        TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
                              &extrasamples, &sampleinfo);
        if (extrasamples == 1 &&
            sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA)
        {
            premultiplied_alpha_ = true;
        }
    }
    else
    {
        throw image_reader_exception(msg);
    }
}

tiff_reader::~tiff_reader()
{
}

unsigned tiff_reader::width() const
{
    return width_;
}

unsigned tiff_reader::height() const
{
    return height_;
}

bool tiff_reader::premultiplied_alpha() const
{
    return premultiplied_alpha_;
}

void tiff_reader::read(unsigned x,unsigned y,image_data_32& image)
{
    if (read_method_==stripped)
    {
        read_stripped(x,y,image);
    }
    else if (read_method_==tiled)
    {
        read_tiled(x,y,image);
    }
    else
    {
        read_generic(x,y,image);
    }
}

void tiff_reader::read_generic(unsigned /*x*/,unsigned /*y*/,image_data_32& /*image*/)
{
    TIFF* tif = load_if_exists(file_name_);
    if (tif)
    {
        MAPNIK_LOG_DEBUG(tiff_reader) << "tiff_reader: TODO - tiff is not stripped or tiled";
    }
}

void tiff_reader::read_tiled(unsigned x0,unsigned y0,image_data_32& image)
{
    TIFF* tif = load_if_exists(file_name_);
    if (tif)
    {
        uint32* buf = (uint32*)_TIFFmalloc(tile_width_*tile_height_*sizeof(uint32));
        int width=image.width();
        int height=image.height();

        int start_y=(y0/tile_height_)*tile_height_;
        int end_y=((y0+height)/tile_height_+1)*tile_height_;

        int start_x=(x0/tile_width_)*tile_width_;
        int end_x=((x0+width)/tile_width_+1)*tile_width_;
        int row,tx0,tx1,ty0,ty1;

        for (int y=start_y;y<end_y;y+=tile_height_)
        {
            ty0 = max(y0,(unsigned)y) - y;
            ty1 = min(height+y0,(unsigned)(y+tile_height_)) - y;

            int n0=tile_height_-ty1;
            int n1=tile_height_-ty0-1;

            for (int x=start_x;x<end_x;x+=tile_width_)
            {

                if (!TIFFReadRGBATile(tif,x,y,buf)) break;

                tx0=max(x0,(unsigned)x);
                tx1=min(width+x0,(unsigned)(x+tile_width_));
                row=y+ty0-y0;
                for (int n=n1;n>=n0;--n)
                {
                    image.setRow(row,tx0-x0,tx1-x0,(const unsigned*)&buf[n*tile_width_+tx0-x]);
                    ++row;
                }
            }
        }
        _TIFFfree(buf);
    }
}

void tiff_reader::read_stripped(unsigned x0,unsigned y0,image_data_32& image)
{
    TIFF* tif = load_if_exists(file_name_);
    if (tif)
    {
        uint32* buf = (uint32*)_TIFFmalloc(width_*rows_per_strip_*sizeof(uint32));

        int width=image.width();
        int height=image.height();

        unsigned start_y=(y0/rows_per_strip_)*rows_per_strip_;
        unsigned end_y=((y0+height)/rows_per_strip_+1)*rows_per_strip_;
        bool laststrip=((unsigned)end_y > height_)?true:false;
        int row,tx0,tx1,ty0,ty1;

        tx0=x0;
        tx1=min(width+x0,(unsigned)width_);

        for (unsigned y=start_y; y < end_y; y+=rows_per_strip_)
        {
            ty0 = max(y0,y)-y;
            ty1 = min(height+y0,y+rows_per_strip_)-y;

            if (!TIFFReadRGBAStrip(tif,y,buf)) break;

            row=y+ty0-y0;

            int n0=laststrip ? 0:(rows_per_strip_-ty1);
            int n1=laststrip ? (ty1-ty0-1):(rows_per_strip_-ty0-1);
            for (int n=n1;n>=n0;--n)
            {
                image.setRow(row,tx0-x0,tx1-x0,(const unsigned*)&buf[n*width_+tx0]);
                ++row;
            }
        }
        _TIFFfree(buf);
    }
}

TIFF* tiff_reader::load_if_exists(std::string const& filename)
{
    if (!tif_)
    {
        boost::filesystem::path path(file_name_);
        if (boost::filesystem::is_regular(path)) // exists and regular file
        {
            // File path is a full file path and does exist
            tif_ = tiff_ptr(TIFFOpen(filename.c_str(), "rb"), tiff_closer());
        }
    }
    return tif_.get();
}

} // namespace mapnik
<|endoftext|>


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

#include <memory>

#include "SurgSim/Input/DeviceInterface.h"
#include "SurgSim/Devices/Nimble/NimbleDevice.h"

#include "SurgSim/Testing/VisualTestCommon/ToolSquareTest.h"

using SurgSim::Input::DeviceInterface;
using SurgSim::Device::NimbleDevice;

int main(int argc, char** argv)
{
	auto leftDevice = std::make_shared<NimbleDevice>("NimbleDeviceLeft");

	auto rightDevice = std::make_shared<NimbleDevice>("NimbleDeviceRight");

	runToolSquareTest(leftDevice, rightDevice, "Move the hands to control the sphere/square.");

	std::cout << std::endl << "Exiting." << std::endl;
	// Cleanup and shutdown will happen automatically as objects go out of scope.

	return 0;
}
<commit_msg>Add PoseTransform to NimbleDevices in the Visual Test.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <memory>

#include "SurgSim/Input/DeviceInterface.h"
#include "SurgSim/Devices/DeviceFilters/PoseTransform.h"
#include "SurgSim/Devices/Nimble/NimbleDevice.h"

#include "SurgSim/Testing/VisualTestCommon/ToolSquareTest.h"

using SurgSim::Input::DeviceInterface;
using SurgSim::Device::PoseTransform;
using SurgSim::Device::NimbleDevice;

int main(int argc, char** argv)
{
	auto leftDevice = std::make_shared<NimbleDevice>("NimbleDeviceLeft");
	auto leftDeviceFilter = std::make_shared<PoseTransform>("NimbleDeviceLeftDeviceFilter");
	leftDeviceFilter->setTranslationScale(0.0001);
	leftDevice->addInputConsumer(leftDeviceFilter);
	leftDevice->setOutputProducer(leftDeviceFilter);
	leftDevice->initialize();

	auto rightDevice = std::make_shared<NimbleDevice>("NimbleDeviceRight");
	rightDevice->setupToTrackRightHand();
	auto rightDeviceFilter = std::make_shared<PoseTransform>("NimbleDeviceRightDeviceFilter");
	rightDeviceFilter->setTranslationScale(0.0001);
	rightDevice->addInputConsumer(rightDeviceFilter);
	rightDevice->setOutputProducer(rightDeviceFilter);
	rightDevice->initialize();

	runToolSquareTest(leftDeviceFilter, rightDeviceFilter, "Move the hands to control the sphere/square.");

	std::cout << std::endl << "Exiting." << std::endl;
	// Cleanup and shutdown will happen automatically as objects go out of scope.

	return 0;
}
<|endoftext|>


<commit_before>/*
 * SchemeShell.cc
 *
 * Simple scheme shell
 * Copyright (c) 2008 Linas Vepstas <linas@linas.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifdef HAVE_GUILE

#include <opencog/util/Config.h>
#include <opencog/util/Logger.h>
#include <opencog/guile/SchemeEval.h>
#include <opencog/cogserver/server/ConsoleSocket.h>
#include <opencog/cogserver/server/CogServer.h>

#include "SchemeShell.h"

using namespace opencog;

SchemeShell::SchemeShell(void)
{
	normal_prompt = "guile> ";
	if (config().get_bool("ANSI_ENABLED"))
		normal_prompt = config()["ANSI_SCM_PROMPT"];
	else
		normal_prompt = config()["SCM_PROMPT"];

	abort_prompt += normal_prompt;

	pending_prompt = "... ";

	evaluator = SchemeEval::get_evaluator();

	// Set the inital atomspace for this thread.
	SchemeEval::set_scheme_as(&cogserver().getAtomSpace());
}

SchemeShell::~SchemeShell()
{
}

/**
 * Register this shell with the console.
 */
void SchemeShell::thread_init(void)
{
	SchemeEval::set_scheme_as(&cogserver().getAtomSpace());
}

#endif
/* ===================== END OF FILE ============================ */
<commit_msg>The actual fix for bug #2328<commit_after>/*
 * SchemeShell.cc
 *
 * Simple scheme shell
 * Copyright (c) 2008 Linas Vepstas <linas@linas.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifdef HAVE_GUILE

#include <opencog/util/Config.h>
#include <opencog/util/Logger.h>
#include <opencog/guile/SchemeEval.h>
#include <opencog/cogserver/server/ConsoleSocket.h>
#include <opencog/cogserver/server/CogServer.h>

#include "SchemeShell.h"

using namespace opencog;

SchemeShell::SchemeShell(void)
{
	normal_prompt = "guile> ";
	if (config().get_bool("ANSI_ENABLED"))
		normal_prompt = config()["ANSI_SCM_PROMPT"];
	else
		normal_prompt = config()["SCM_PROMPT"];

	abort_prompt += normal_prompt;

	pending_prompt = "... ";

	evaluator = SchemeEval::get_evaluator();

	// Set the inital atomspace for this thread.
	SchemeEval::set_scheme_as(&cogserver().getAtomSpace());
}

SchemeShell::~SchemeShell()
{
	// We must stall until after the evaluator has finished
	// evaluating. Otherwise, the thread_init() method (below)
	// might never get a chance to run, leading to a NULL
	// atomspace, leading to a crash.  Bug #2328.
	while_not_done();
}

/**
 * Register this shell with the console.
 */
void SchemeShell::thread_init(void)
{
	SchemeEval::set_scheme_as(&cogserver().getAtomSpace());
}

#endif
/* ===================== END OF FILE ============================ */
<|endoftext|>


<commit_before>/*
 * UREConfigReader.cc
 *
 * Copyright (C) 2015 OpenCog Foundation
 *
 * Author: Nil Geisweiller <ngeiswei@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "UREConfigReader.h"

#include <opencog/atoms/bind/BindLink.h>
#include <opencog/atoms/bind/DefineLink.h>
#include <opencog/atoms/NumberNode.h>
#include <opencog/query/BindLink.h>

using namespace opencog;

UREConfigReader::UREConfigReader(AtomSpace& as) : _as(as)
{
	// Iterate over all rule-based systems and retrieve their rules
	// and parameters
	for (Handle rbs : fetch_rule_based_systems()) {
		// Retrieve rule names and instantiate them
		for (Handle rn : fetch_rules(rbs)) {
			// Build rule and cache it in _sys2params
			Handle rule_h = fetch_definition(rn);
			_sys2params[rbs].rules.emplace_back(rule_h);
		}

		// Fetch maximum number of iterations
		_sys2params[rbs].max_iter = fetch_num_param(max_iter_name, rbs);

		// Fetch attention allocation parameter and cache it
		_sys2params[rbs].attention_alloc =
			fetch_bool_param(attention_alloc_name, rbs);
	}
}

const std::vector<Rule>& UREConfigReader::get_rules(Handle rbs) const
{
	return _sys2params.at(rbs).rules;
}

bool UREConfigReader::get_attention_allocation(Handle rbs) const
{
	return _sys2params.at(rbs).attention_alloc;
}

int UREConfigReader::get_maximum_iterations(Handle rbs) const
{
	return _sys2params.at(rbs).max_iter;
}

HandleSeq UREConfigReader::fetch_rule_based_systems()
{
    // Retrieve all rule-based systems inheriting URE_top_rulebase
	Handle rbs_var = _as.addNode(VARIABLE_NODE, "__URE_RBS__");
	BindLink bl({rbs_var,
				_as.addLink(IMPLICATION_LINK,
				            // Clause:
				            // InheritanceLink
				            //    VariableNode "__URE_SUB_SYSTEMS__"
				            //    ConceptNode URE_top_name
				            _as.addLink(INHERITANCE_LINK,
				                        rbs_var,
				                        _as.addNode(CONCEPT_NODE,
				                                    URE_top_name)),
				            // Rewrite: (all inherited rule-based systems)
				            rbs_var)});
	Handle bl_h = bl.getHandle();
	Handle rule_based_systems = bindlink(&_as, bl_h);

	// Remove the BindLink from the AtomSpace as it is no longer useful
	_as.removeAtom(bl_h);

	return LinkCast(rule_based_systems)->getOutgoingSet();
}

HandleSeq UREConfigReader::fetch_rules(Handle rbs)
{
	// Retrieve rules
	Handle rule_var = _as.addNode(VARIABLE_NODE, "__URE_RULE__");
	BindLink bl({rule_var,
				_as.addLink(IMPLICATION_LINK,
				            // Clause:
				            // MemberLink
				            //    VariableNode "__URE_RULE__"
				            //    ConceptNode <RBS>
				            _as.addLink(MEMBER_LINK, rule_var, rbs),
				            // Rewrite: (all member rules)
				            rule_var)});
	Handle rule_names = bindlink(&_as, bl.getHandle());

	return LinkCast(rule_names)->getOutgoingSet();
}

Handle UREConfigReader::fetch_definition(Handle label)
{
	HandleSeq defines;
	label->getIncomingSetByType(back_inserter(defines), DEFINE_LINK);
	OC_ASSERT(defines.size() == 1, "There should be only one definition");
	return Handle::UNDEFINED; // DefineLinkCast(defines.front())->get_definition();
                              // commented out till get_definition is
                              // extended to any object not just
                              // functions.
}

Handle UREConfigReader::fetch_execution_output(Handle schema, Handle input)
{
	// Retrieve rules
	Handle output_var = _as.addNode(VARIABLE_NODE, "__EXECUTION_OUTPUT_VAR__");
	BindLink bl({output_var,
				_as.addLink(IMPLICATION_LINK,
				            // Clause:
				            // ExecutionLink
				            //    <schema>
				            //    <input>
				            //    output_var
				            _as.addLink(EXECUTION_LINK,
				                        schema,
				                        input,
				                        output_var),
				            // Rewrite: (all outputs)
				            output_var)});
	Handle bl_h = bl.getHandle();
	Handle outputs = bindlink(&_as, bl_h);

	// Remove the BindLink from the AtomSpace as it is no longer useful
	_as.removeAtom(bl_h);

	HandleSeq outputs_hs = LinkCast(outputs)->getOutgoingSet();
	OC_ASSERT(outputs_hs.size() == 1, "There should be only one output");

	return outputs_hs.front();
}

double UREConfigReader::fetch_num_param(const string& schema_name, Handle input)
{
	Handle param_schema = _as.addNode(SCHEMA_NODE, schema_name);
	Handle output_h = fetch_execution_output(param_schema, input);
	return NumberNodeCast(output_h)->getValue();
}

bool UREConfigReader::fetch_bool_param(const string& pred_name, Handle input)
{
	Handle pred = _as.addNode(PREDICATE_NODE, pred_name);
	TruthValuePtr tv = _as.addLink(EVALUATION_LINK, pred, input)->getTruthValue();
	return tv->getMean() > 0.5;
}
<commit_msg>Remove BindLink's ImplicationLinks in URE config reader code<commit_after>/*
 * UREConfigReader.cc
 *
 * Copyright (C) 2015 OpenCog Foundation
 *
 * Author: Nil Geisweiller <ngeiswei@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "UREConfigReader.h"

#include <opencog/atoms/bind/BindLink.h>
#include <opencog/atoms/bind/DefineLink.h>
#include <opencog/atoms/NumberNode.h>
#include <opencog/query/BindLink.h>

using namespace opencog;

UREConfigReader::UREConfigReader(AtomSpace& as) : _as(as)
{
	// Iterate over all rule-based systems and retrieve their rules
	// and parameters
	for (Handle rbs : fetch_rule_based_systems()) {
		// Retrieve rule names and instantiate them
		for (Handle rn : fetch_rules(rbs)) {
			// Build rule and cache it in _sys2params
			Handle rule_h = fetch_definition(rn);
			_sys2params[rbs].rules.emplace_back(rule_h);
		}

		// Fetch maximum number of iterations
		_sys2params[rbs].max_iter = fetch_num_param(max_iter_name, rbs);

		// Fetch attention allocation parameter and cache it
		_sys2params[rbs].attention_alloc =
			fetch_bool_param(attention_alloc_name, rbs);
	}
}

const std::vector<Rule>& UREConfigReader::get_rules(Handle rbs) const
{
	return _sys2params.at(rbs).rules;
}

bool UREConfigReader::get_attention_allocation(Handle rbs) const
{
	return _sys2params.at(rbs).attention_alloc;
}

int UREConfigReader::get_maximum_iterations(Handle rbs) const
{
	return _sys2params.at(rbs).max_iter;
}

HandleSeq UREConfigReader::fetch_rule_based_systems()
{
    // Retrieve all rule-based systems inheriting URE_top_rulebase
	Handle rbs_var = _as.addNode(VARIABLE_NODE, "__URE_RBS__");
	BindLink bl({rbs_var,
				// Clause:
				// InheritanceLink
				//    VariableNode "__URE_SUB_SYSTEMS__"
				//    ConceptNode URE_top_name
				_as.addLink(INHERITANCE_LINK,
				            rbs_var,
				            _as.addNode(CONCEPT_NODE,
				                        URE_top_name)),
				// Rewrite: (all inherited rule-based systems)
				rbs_var});
	Handle bl_h = bl.getHandle();
	Handle rule_based_systems = bindlink(&_as, bl_h);

	// Remove the BindLink from the AtomSpace as it is no longer useful
	_as.removeAtom(bl_h);

	return LinkCast(rule_based_systems)->getOutgoingSet();
}

HandleSeq UREConfigReader::fetch_rules(Handle rbs)
{
	// Retrieve rules
	Handle rule_var = _as.addNode(VARIABLE_NODE, "__URE_RULE__");
	BindLink bl({rule_var,
				// Clause:
				// MemberLink
				//    VariableNode "__URE_RULE__"
				//    ConceptNode <RBS>
				_as.addLink(MEMBER_LINK, rule_var, rbs),
				// Rewrite: (all member rules)
				rule_var});
	Handle rule_names = bindlink(&_as, bl.getHandle());

	return LinkCast(rule_names)->getOutgoingSet();
}

Handle UREConfigReader::fetch_definition(Handle label)
{
	HandleSeq defines;
	label->getIncomingSetByType(back_inserter(defines), DEFINE_LINK);
	OC_ASSERT(defines.size() == 1, "There should be only one definition");
	return Handle::UNDEFINED; // DefineLinkCast(defines.front())->get_definition();
                              // commented out till get_definition is
                              // extended to any object not just
                              // functions.
}

Handle UREConfigReader::fetch_execution_output(Handle schema, Handle input)
{
	// Retrieve rules
	Handle output_var = _as.addNode(VARIABLE_NODE, "__EXECUTION_OUTPUT_VAR__");
	BindLink bl({output_var,
				// Clause:
				// ExecutionLink
				//    <schema>
				//    <input>
				//    output_var
				_as.addLink(EXECUTION_LINK,
				            schema,
				            input,
				            output_var),
				// Rewrite: (all outputs)
				output_var});
	Handle bl_h = bl.getHandle();
	Handle outputs = bindlink(&_as, bl_h);

	// Remove the BindLink from the AtomSpace as it is no longer useful
	_as.removeAtom(bl_h);

	HandleSeq outputs_hs = LinkCast(outputs)->getOutgoingSet();
	OC_ASSERT(outputs_hs.size() == 1, "There should be only one output");

	return outputs_hs.front();
}

double UREConfigReader::fetch_num_param(const string& schema_name, Handle input)
{
	Handle param_schema = _as.addNode(SCHEMA_NODE, schema_name);
	Handle output_h = fetch_execution_output(param_schema, input);
	return NumberNodeCast(output_h)->getValue();
}

bool UREConfigReader::fetch_bool_param(const string& pred_name, Handle input)
{
	Handle pred = _as.addNode(PREDICATE_NODE, pred_name);
	TruthValuePtr tv = _as.addLink(EVALUATION_LINK, pred, input)->getTruthValue();
	return tv->getMean() > 0.5;
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

#include "AliEveEventManager.h"
#include "AliEveEventManagerEditor.h"
#include "AliEveMultiView.h"
#include "AliEveMacroExecutor.h"
#include "AliEveMacro.h"
#include "AliSysInfo.h"
#include "AliCDBManager.h"

#include <TH2D.h>
#include <TTimeStamp.h>
#include <TROOT.h>
#include <TEveManager.h>
#include <TEveBrowser.h>
#include <TEveMacro.h>
#include <TGTab.h>
#include <TGFileBrowser.h>
#include <TInterpreter.h>
#include <TEnv.h>
#include <TPRegexp.h>
#include <TFolder.h>
#include <TSystem.h>
#include <TSystemDirectory.h>
#include <TList.h>

#include <iostream>

using namespace std;

class TEveProjectionManager;
class TEveGeoShape;
class TEveUtil;
class AliTriggerAnalysis;
class AliSysInfo;

TH2D *V0StateHistogram;
Bool_t gCenterProjectionsAtPrimaryVertex = kFALSE;

Int_t      g_pic_id  = 0;
Int_t      g_pic_max = 100;
TTimeStamp g_pic_prev(0, 0);

void alieve_init_import_macros();

void alieve_hlt(TString ocdbStorage="local://CDB")
{
    AliEveEventManager::SetCdbUri(ocdbStorage);         // current OCDB snapshot
    AliCDBManager* cdbManager = AliCDBManager::Instance();
    cdbManager->SetDefaultStorage(ocdbStorage);

    cout<<"Creating multiview...";
    AliEveMultiView *multiView = new AliEveMultiView(kTRUE);
    cout<<"created"<<endl;

    Info("alieve_init", "Adding standard macros.");
    TString  hack = gSystem->pwd(); // Problem with TGFileBrowser cding
    alieve_init_import_macros();
    gSystem->cd(Form("%s/../src/",gSystem->Getenv("ALICE_ROOT")));
    gROOT->ProcessLine(".L geom_gentle.C+");
    gROOT->ProcessLine(".L geom_gentle_trd.C+");
    gROOT->ProcessLine(".L geom_gentle_muon.C+");
    TEveUtil::LoadMacro("saveViews.C");
    gSystem->cd(hack);
    cout<<"Standard macros added"<<endl;

    new AliEveHLTZMQeventManager();
    gEve->AddEvent(AliEveEventManager::GetMaster());
    cout<<"Event manager created"<<endl;

    TEveUtil::AssertMacro("VizDB_scan.C");
    gSystem->ProcessEvents();
    cout<<"VizDB_scan loaded"<<endl;
    TEveBrowser *browser = gEve->GetBrowser();
    browser->ShowCloseTab(kFALSE);
    cout<<"browser created"<<endl;

    TEveUtil::LoadMacro("geom_gentle.C");
    cout<<"geom gentle loaded"<<endl;

    multiView->InitGeomGentle(geom_gentle(),
                              geom_gentle_rphi(),
                              geom_gentle_rhoz(),
                              geom_gentle_rhoz());
    cout<<"geom gentl inited"<<endl;

    TEveUtil::LoadMacro("geom_gentle_trd.C");
    multiView->InitGeomGentleTrd(geom_gentle_trd());

    TEveUtil::LoadMacro("geom_gentle_muon.C");
    multiView->InitGeomGentleMuon(geom_gentle_muon(), kFALSE, kFALSE, kTRUE);

    //============================================================================
    // Standard macros to execute -- not all are enabled by default.
    //============================================================================

    printf("============ Setting macro executor ============\n");

    AliEveMacroExecutor *exec = AliEveEventManager::GetMaster()->GetExecutor();
    printf("exec created\n");
    /*
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX",         "primary_vertex.C", "primary_vertex",             "",                kTRUE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX Ellipse", "primary_vertex.C", "primary_vertex_ellipse",     "",                kTRUE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX Box",     "primary_vertex.C", "primary_vertex_box",         "kFALSE, 3, 3, 3", kFALSE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX",         "primary_vertex.C", "primary_vertex_spd",         "",                kTRUE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX Ellipse", "primary_vertex.C", "primary_vertex_ellipse_spd", "",                kTRUE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX Box",     "primary_vertex.C", "primary_vertex_box_spd",     "kFALSE, 3, 3, 3", kFALSE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX",         "primary_vertex.C", "primary_vertex_tpc",         "",                kFALSE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX Ellipse", "primary_vertex.C", "primary_vertex_ellipse_tpc", "",                kFALSE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX Box",     "primary_vertex.C", "primary_vertex_box_tpc",     "kFALSE, 3, 3, 3", kFALSE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC Track",      "esd_tracks.C",        "esd_tracks",             "", kFALSE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC Track",      "esd_tracks.C",        "esd_tracks_MI",          "", kFALSE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC Track MUON", "esd_muon_tracks.C", "esd_muon_tracks",        "kTRUE,kFALSE", kTRUE));
    */

    // default appearance:
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC Tracks by category",  "esd_tracks.C", "esd_tracks_by_category",  "", kTRUE));

    // preset for cosmics:
    //exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC Tracks by category",  "esd_tracks.C", "esd_tracks_by_category",  "kGreen,kGreen,kGreen,kGreen,kGreen,kGreen,kGreen,kGreen,kGreen,kFALSE", kTRUE));

    //exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC FMD",        "fmd_esd.C",           "fmd_esd",                "", kTRUE));//huge leak
    //

    // ???
    // exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC TRD", "trd_detectors.C", "trd_detectors",         "", kFALSE));
    // trd_tracks disabled due to memory leaks
    cout<<"macros added to exec"<<endl;

    //----------------------------------------------------------------------------
    /* something is wrong here:
    slot = TEveWindow::CreateWindowInTab(browser->GetTabRight());
    slot->StartEmbedding();
    AliEveMacroExecutorWindow* exewin = new AliEveMacroExecutorWindow(exec);
    slot->StopEmbedding("DataSelection");
    exewin->PopulateMacros();
    */
    //============================================================================
    // Final GUI setup
    //============================================================================

    browser->GetTabRight()->SetTab(1);
    browser->StartEmbedding(TRootBrowser::kBottom);
    new AliEveEventManagerWindow(AliEveEventManager::GetMaster());
    browser->StopEmbedding("EventCtrl");

    browser->MoveResize(0, 0, gClient->GetDisplayWidth(),gClient->GetDisplayHeight() - 32);

    gEve->FullRedraw3D(kTRUE);
    gSystem->ProcessEvents();

    // move and rotate sub-views
    TGLViewer *glv1 = multiView->Get3DView()->GetGLViewer();
    TGLViewer *glv2 = multiView->GetRPhiView()->GetGLViewer();
    TGLViewer *glv3 = multiView->GetRhoZView()->GetGLViewer();
    TGLViewer *glv4 = multiView->GetMuonView()->GetGLViewer();

    glv1->CurrentCamera().RotateRad(-0.4, 0.6);
    glv2->CurrentCamera().Dolly(90, kFALSE, kFALSE);
    glv3->CurrentCamera().Dolly(2300, kFALSE, kFALSE);
    glv4->CurrentCamera().Dolly(1, kFALSE, kFALSE);

    AliEveEventManager::GetMaster()->AddNewEventCommand("alieve_online_on_new_event();");
    gEve->FullRedraw3D();
    gSystem->ProcessEvents();
    gEve->Redraw3D(kTRUE);

    // set autoload by default
    AliEveEventManager::GetMaster()->SetAutoLoad(true);
}

void alieve_online_on_new_event()
{
    if (AliEveEventManager::HasESD())
      {
	Double_t x[3] = { 0, 0, 0 };

        AliESDEvent* esd = AliEveEventManager::AssertESD();
        esd->GetPrimaryVertex()->GetXYZ(x);

        TTimeStamp ts(esd->GetTimeStamp());
        TString win_title("Eve Main Window -- Timestamp: ");
        win_title += ts.AsString("s");
        win_title += "; Event # in ESD file: ";
        win_title += esd->GetEventNumberInFile();
        gEve->GetBrowser()->SetWindowName(win_title);

	TEveElement* top = gEve->GetCurrentEvent();

	AliEveMultiView *mv = AliEveMultiView::Instance();

	mv->DestroyEventRPhi();
	if (gCenterProjectionsAtPrimaryVertex){
	  mv->SetCenterRPhi(x[0], x[1], x[2]);
	}
	mv->ImportEventRPhi(top);

	mv->DestroyEventRhoZ();
	if (gCenterProjectionsAtPrimaryVertex){
	  mv->SetCenterRhoZ(x[0], x[1], x[2]);
	}
	mv->ImportEventRhoZ(top);

	if (gCenterProjectionsAtPrimaryVertex)
	  mv->SetCenterMuon(x[0], x[1], x[2]);
	mv->ImportEventMuon(top);

	// Register image to amore.
	  TString id;      id.Form("online-viz-%03d", g_pic_id);
	  TString pic(id); pic += ".png";

	  //printf("In image dump: file='%s'.\n", pic.Data());

	  gEve->GetBrowser()->RaiseWindow();
	  gEve->FullRedraw3D();
	  gSystem->ProcessEvents();

	  // create screenshots from OpenGL views
	  //saveViews(pic.Data());

	  // send screenshot to AMORE
	  //int status = gSystem->Exec(Form("SendImageToAmore %s %s %d",id.Data(),pic.Data(),esd->GetRunNumber()));
	  //  printf("Post AMORE reg -- status=%d, run=%d.\n", status, esd->GetRunNumber());

	  //if (++g_pic_id >= g_pic_max) g_pic_id = 0;
	  //g_pic_prev.Set();
      }
}

void alieve_init_import_macros()
{
    // Put macros in the list of browsables, add a macro browser to
    // top-level GUI.

  TString macdir("$(ALICE_ROOT)/EVE/alice-macros");

    if (gSystem->Getenv("ALICE_ROOT") != 0)
    {
        gInterpreter->AddIncludePath(Form("%s/MUON", gSystem->Getenv("ALICE_ROOT")));
        gInterpreter->AddIncludePath(Form("%s/MUON/mapping", gSystem->Getenv("ALICE_ROOT")));
	gSystem->ExpandPathName(macdir);
    }

    TFolder* f = gEve->GetMacroFolder();
    void* dirhandle = gSystem->OpenDirectory(macdir.Data());
    if (dirhandle != 0)
    {
        char* filename;
        TPMERegexp re("\\.C$");
        TObjArray names;
        while ((filename = (char*)(gSystem->GetDirEntry(dirhandle))) != 0)
        {
            if (re.Match(filename))
                names.AddLast(new TObjString(filename));
        }
        names.Sort();

        for (Int_t ii=0; ii<names.GetEntries(); ++ii)
        {
            TObjString * si = (TObjString*) names.At(ii);
            f->Add(new TEveMacro(Form("%s/%s", macdir.Data(), (si->GetString()).Data())));
        }
    }
    gSystem->FreeDirectory(dirhandle);

    gROOT->GetListOfBrowsables()->Add(new TSystemDirectory(macdir.Data(), macdir.Data()));

    {
        TEveBrowser   *br = gEve->GetBrowser();
        TGFileBrowser *fb = 0;
        fb = br->GetFileBrowser();
        fb->GotoDir(macdir);
        {
            br->StartEmbedding(0);
            fb = br->MakeFileBrowser();
            fb->BrowseObj(f);
            fb->Show();
            br->StopEmbedding();
            br->SetTabTitle("Macros", 0);
            br->SetTab(0, 0);
        }
    }
}
<commit_msg>default macro for HLT ED<commit_after>/**************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

#include "AliEveEventManager.h"
#include "AliEveEventManagerEditor.h"
#include "AliEveMultiView.h"
#include "AliEveMacroExecutor.h"
#include "AliEveMacro.h"
#include "AliSysInfo.h"
#include "AliCDBManager.h"

#include <TH2D.h>
#include <TTimeStamp.h>
#include <TROOT.h>
#include <TEveManager.h>
#include <TEveBrowser.h>
#include <TEveMacro.h>
#include <TGTab.h>
#include <TGFileBrowser.h>
#include <TInterpreter.h>
#include <TEnv.h>
#include <TPRegexp.h>
#include <TFolder.h>
#include <TSystem.h>
#include <TSystemDirectory.h>
#include <TList.h>
#include "TString.h"

#include <iostream>

using namespace std;

class TEveProjectionManager;
class TEveGeoShape;
class TEveUtil;
class AliTriggerAnalysis;
class AliSysInfo;

TH2D *V0StateHistogram;
Bool_t gCenterProjectionsAtPrimaryVertex = kFALSE;

Int_t      g_pic_id  = 0;
Int_t      g_pic_max = 100;
TTimeStamp g_pic_prev(0, 0);

void alieve_init_import_macros();
void alieve_online_on_new_event();

void alieve_hlt(TString ocdbStorage="local://OCDB")
{
    if (gSystem->Getenv("ocdbStorage"))
      ocdbStorage=gSystem->Getenv("ocdbStorage");
    AliEveEventManager::SetCdbUri(ocdbStorage);         // current OCDB snapshot
    AliCDBManager* cdbManager = AliCDBManager::Instance();
    cdbManager->SetDefaultStorage(ocdbStorage);

    cout<<"Creating multiview...";
    AliEveMultiView *multiView = new AliEveMultiView(kTRUE);
    cout<<"created"<<endl;

    Info("alieve_init", "Adding standard macros.");
    alieve_init_import_macros();
    gROOT->ProcessLine(".L geom_gentle.C+");
    gROOT->ProcessLine(".L geom_gentle_trd.C+");
    gROOT->ProcessLine(".L geom_gentle_muon.C+");
    TEveUtil::LoadMacro("saveViews.C");
    cout<<"Standard macros added"<<endl;

    AliEveEventManager* eventManager = new AliEveHLTZMQeventManager();
    gEve->AddEvent(eventManager);
    cout<<"Event manager created"<<endl;

    TEveUtil::AssertMacro("VizDB_scan.C");
    gSystem->ProcessEvents();
    cout<<"VizDB_scan loaded"<<endl;
    TEveBrowser *browser = gEve->GetBrowser();
    browser->ShowCloseTab(kFALSE);
    cout<<"browser created"<<endl;

    TEveUtil::LoadMacro("geom_gentle.C");
    cout<<"geom gentle loaded"<<endl;

    multiView->InitGeomGentle(geom_gentle(),
                              geom_gentle_rphi(),
                              geom_gentle_rhoz(),
                              geom_gentle_rhoz());
    cout<<"geom gentl inited"<<endl;

    //TEveUtil::LoadMacro("geom_gentle_trd.C");
    multiView->InitGeomGentleTrd(geom_gentle_trd());

    //TEveUtil::LoadMacro("geom_gentle_muon.C");
    multiView->InitGeomGentleMuon(geom_gentle_muon(), kFALSE, kFALSE, kTRUE);

    printf("============ Setting macro executor ============\n");

    AliEveMacroExecutor *exec = AliEveEventManager::GetMaster()->GetExecutor();
    printf("exec created\n");
    /*
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX",         "primary_vertex.C", "primary_vertex",             "",                kTRUE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX Ellipse", "primary_vertex.C", "primary_vertex_ellipse",     "",                kTRUE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX Box",     "primary_vertex.C", "primary_vertex_box",         "kFALSE, 3, 3, 3", kFALSE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX",         "primary_vertex.C", "primary_vertex_spd",         "",                kTRUE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX Ellipse", "primary_vertex.C", "primary_vertex_ellipse_spd", "",                kTRUE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX Box",     "primary_vertex.C", "primary_vertex_box_spd",     "kFALSE, 3, 3, 3", kFALSE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX",         "primary_vertex.C", "primary_vertex_tpc",         "",                kFALSE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX Ellipse", "primary_vertex.C", "primary_vertex_ellipse_tpc", "",                kFALSE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC PVTX Box",     "primary_vertex.C", "primary_vertex_box_tpc",     "kFALSE, 3, 3, 3", kFALSE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC Track",      "esd_tracks.C",        "esd_tracks",             "", kFALSE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC Track",      "esd_tracks.C",        "esd_tracks_MI",          "", kFALSE));
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC Track MUON", "esd_muon_tracks.C", "esd_muon_tracks",        "kTRUE,kFALSE", kTRUE));
    */

    // default appearance:
    exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC Tracks by category",  "esd_tracks.C", "esd_tracks_by_category",  "", kTRUE));

    // preset for cosmics:
    //exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC Tracks by category",  "esd_tracks.C", "esd_tracks_by_category",  "kGreen,kGreen,kGreen,kGreen,kGreen,kGreen,kGreen,kGreen,kGreen,kFALSE", kTRUE));

    //exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC FMD",        "fmd_esd.C",           "fmd_esd",                "", kTRUE));//huge leak
    //

    // ???
    // exec->AddMacro(new AliEveMacro(AliEveMacro::kESD, "REC TRD", "trd_detectors.C", "trd_detectors",         "", kFALSE));
    // trd_tracks disabled due to memory leaks
    cout<<"macros added to exec"<<endl;

    //----------------------------------------------------------------------------
    /* something is wrong here:
    slot = TEveWindow::CreateWindowInTab(browser->GetTabRight());
    slot->StartEmbedding();
    AliEveMacroExecutorWindow* exewin = new AliEveMacroExecutorWindow(exec);
    slot->StopEmbedding("DataSelection");
    exewin->PopulateMacros();
    */
    //============================================================================
    // Final GUI setup
    //============================================================================

    browser->GetTabRight()->SetTab(1);
    browser->StartEmbedding(TRootBrowser::kBottom);
    new AliEveEventManagerWindow(AliEveEventManager::GetMaster());
    browser->StopEmbedding("EventCtrl");

    gEve->FullRedraw3D(kTRUE);
    gSystem->ProcessEvents();

    // move and rotate sub-views
    TGLViewer *glv1 = multiView->Get3DView()->GetGLViewer();
    TGLViewer *glv2 = multiView->GetRPhiView()->GetGLViewer();
    TGLViewer *glv3 = multiView->GetRhoZView()->GetGLViewer();
    TGLViewer *glv4 = multiView->GetMuonView()->GetGLViewer();

    glv1->CurrentCamera().RotateRad(-0.4, 0.6);
    glv2->CurrentCamera().Dolly(90, kFALSE, kFALSE);
    glv3->CurrentCamera().Dolly(2300, kFALSE, kFALSE);
    glv4->CurrentCamera().Dolly(1, kFALSE, kFALSE);

    AliEveEventManager::GetMaster()->AddNewEventCommand("alieve_online_on_new_event();");

    gEve->FullRedraw3D();
    gSystem->ProcessEvents();
    gEve->Redraw3D(kTRUE);

    // set autoload by default
    AliEveEventManager::GetMaster()->SetAutoLoad(true);
}

void alieve_online_on_new_event()
{
  if (!AliEveEventManager::HasESD()) return;

  AliESDEvent* esd = AliEveEventManager::AssertESD();

  Double_t x[3] = { 0, 0, 0 };
  esd->GetPrimaryVertex()->GetXYZ(x);

  TTimeStamp ts(esd->GetTimeStamp());
  TString win_title("Eve Main Window -- Timestamp: ");
  win_title += ts.AsString("s");
  win_title += "; Event # in ESD file: ";
  win_title += esd->GetEventNumberInFile();
  win_title += " | run: ";
  win_title += esd->GetRunNumber();
  gEve->GetBrowser()->SetWindowName(win_title);

	TEveElement* top = gEve->GetCurrentEvent();

	AliEveMultiView *mv = AliEveMultiView::Instance();

	mv->DestroyEventRPhi();
	if (gCenterProjectionsAtPrimaryVertex){
	  mv->SetCenterRPhi(x[0], x[1], x[2]);
	}
	mv->ImportEventRPhi(top);

	mv->DestroyEventRhoZ();
	if (gCenterProjectionsAtPrimaryVertex){
	  mv->SetCenterRhoZ(x[0], x[1], x[2]);
	}
	mv->ImportEventRhoZ(top);

	if (gCenterProjectionsAtPrimaryVertex)
	  mv->SetCenterMuon(x[0], x[1], x[2]);
	mv->ImportEventMuon(top);
}

void alieve_init_import_macros()
{
  // Put macros in the list of browsables, add a macro browser to
  // top-level GUI.

  TString macdir("$(ALICE_ROOT)/EVE/alice-macros");

  if (gSystem->Getenv("ALICE_ROOT") != 0)
  {
    gInterpreter->AddIncludePath(Form("%s/MUON", gSystem->Getenv("ALICE_ROOT")));
    gInterpreter->AddIncludePath(Form("%s/MUON/mapping", gSystem->Getenv("ALICE_ROOT")));
    gSystem->ExpandPathName(macdir);
  }

  TFolder* f = gEve->GetMacroFolder();
  void* dirhandle = gSystem->OpenDirectory(macdir.Data());
  if (dirhandle != 0)
  {
    char* filename;
    TPMERegexp re("\\.C$");
    TObjArray names;
    while ((filename = (char*)(gSystem->GetDirEntry(dirhandle))) != 0)
    {
      if (re.Match(filename))
        names.AddLast(new TObjString(filename));
    }
    names.Sort();

    for (Int_t ii=0; ii<names.GetEntries(); ++ii)
    {
      TObjString * si = (TObjString*) names.At(ii);
      f->Add(new TEveMacro(Form("%s/%s", macdir.Data(), (si->GetString()).Data())));
    }
  }
  gSystem->FreeDirectory(dirhandle);

  gROOT->GetListOfBrowsables()->Add(new TSystemDirectory(macdir.Data(), macdir.Data()));

  {
    TEveBrowser   *br = gEve->GetBrowser();
    TGFileBrowser *fb = 0;
    fb = br->GetFileBrowser();
    fb->GotoDir(macdir);
    {
      br->StartEmbedding(0);
      fb = br->MakeFileBrowser();
      fb->BrowseObj(f);
      fb->Show();
      br->StopEmbedding();
      br->SetTabTitle("Macros", 0);
      br->SetTab(0, 0);
    }
  }
}

<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2017 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *  @file EventCategorizerTools.cpp
 */

#include "EventCategorizerTools.h"
#include <TMath.h>
#include <vector>

using namespace std;

/**
* Method for determining type of event - back to back 2 gamma
*/
bool EventCategorizerTools::checkFor2Gamma(const JPetEvent& event, JPetStatistics& stats, bool saveHistos)
{
  if (event.getHits().size() < 2) return false;
  for(uint i = 0; i < event.getHits().size(); i++){
    for(uint j = i+1; j < event.getHits().size(); j++){
      JPetHit firstHit, secondHit;
      if(event.getHits().at(i).getTime() < event.getHits().at(j).getTime()){
        firstHit = event.getHits().at(i);
        secondHit = event.getHits().at(j);
      }else{
        firstHit = event.getHits().at(j);
        secondHit = event.getHits().at(i);
      }
      // Checking for back to back
      double thetaDiff = fabs(firstHit.getBarrelSlot().getTheta() - secondHit.getBarrelSlot().getTheta());
      if(thetaDiff > 177.0 && thetaDiff < 183.0){
        if(saveHistos){
          double distance = (secondHit.getPos()-firstHit.getPos()).Mag();
          TVector3 annhilationPoint = calculateAnnihilationPoint(firstHit, secondHit);
          stats.getHisto1D("2Gamma_Zpos")->Fill(firstHit.getPosZ());
          stats.getHisto1D("2Gamma_Zpos")->Fill(secondHit.getPosZ());
          stats.getHisto1D("2Gamma_TimeDiff")->Fill(secondHit.getTime()-firstHit.getTime());
          stats.getHisto1D("2Gamma_Dist")->Fill(distance);
          stats.getHisto1D("Annih_TOF")->Fill(calculateTOF(firstHit, secondHit));
          stats.getHisto2D("AnnihPoint_XY")->Fill(annhilationPoint.X(), annhilationPoint.Y());
          stats.getHisto2D("AnnihPoint_XZ")->Fill(annhilationPoint.X(), annhilationPoint.Z());
          stats.getHisto2D("AnnihPoint_YZ")->Fill(annhilationPoint.Y(), annhilationPoint.Z());
        }
        return true;
      }
    }
  }
  return false;
}

/**
* Method for determining type of event - 3Gamma
*/
bool EventCategorizerTools::checkFor3Gamma(const JPetEvent& event, JPetStatistics& stats, bool saveHistos)
{
  if (event.getHits().size() < 3) return false;
  for(uint i = 0; i < event.getHits().size(); i++){
    for(uint j = i+1; j < event.getHits().size(); j++){
      for(uint k = j+1; k < event.getHits().size(); k++){
        JPetHit& firstHit = event.getHits().at(i);
        JPetHit& secondHit = event.getHits().at(j);
        JPetHit& thirdHit = event.getHits().at(k);

        vector<double> thetaAngles;
        thetaAngles.push_back(firstHit.getBarrelSlot().getTheta());
        thetaAngles.push_back(secondHit.getBarrelSlot().getTheta());
        thetaAngles.push_back(thirdHit.getBarrelSlot().getTheta());
        sort(thetaAngles.begin(), thetaAngles.end());

        vector<double> relativeAngles;
        relativeAngles.push_back(thetaAngles.at(1)-thetaAngles.at(0));
        relativeAngles.push_back(thetaAngles.at(2)-thetaAngles.at(1));
        relativeAngles.push_back(360.0-thetaAngles.at(2)+thetaAngles.at(0));
        sort(relativeAngles.begin(), relativeAngles.end());
        double transformedX = relativeAngles.at(1)+relativeAngles.at(0);
        double transformedY = relativeAngles.at(1)-relativeAngles.at(0);

        if(saveHistos)
          stats.getHisto2D("3Gamma_Angles")->Fill(transformedX, transformedY);
      }
    }
  }
  return true;
}

/**
* Method for determining type of event - prompt
*/
bool EventCategorizerTools::checkForPrompt(
  const JPetEvent& event, JPetStatistics& stats, bool saveHistos,
  double deexTOTCutMin, double deexTOTCutMax)
{
  for(uint i = 0; i < event.getHits().size(); i++){
    JPetHit& hit = event.getHits().at(i);
    double tot = calculateTOT(hit);
    if(tot > deexTOTCutMin && tot < deexTOTCutMax){
      if(saveHistos) stats.getHisto1D("Deex_TOT_cut")->Fill(tot);
    }
  }
  return true;
}

/**
* Method for determining type of event - scatter
*/
bool EventCategorizerTools::checkForScatter(
  const JPetEvent& event,
  JPetStatistics& stats,
  bool saveHistos,
  double scatterTOFTimeDiff)
{
  if (event.getHits().size() < 2) return false;
  for(uint i = 0; i < event.getHits().size(); i++){
    for(uint j = i+1; j < event.getHits().size(); j++){
      JPetHit primaryHit, scatterHit;
      if(event.getHits().at(i).getTime() < event.getHits().at(j).getTime()){
        primaryHit = event.getHits().at(i);
        scatterHit = event.getHits().at(j);
      }else{
        primaryHit = event.getHits().at(j);
        scatterHit = event.getHits().at(i);
      }

      double scattAngle = calculateScatteringAngle(primaryHit, scatterHit);
      double scattTOF = calculateScatteringTime(primaryHit, scatterHit)/1000.0;
      double timeDiff = scatterHit.getTime() - primaryHit.getTime();

      if(saveHistos)
        stats.getHisto1D("ScatterTOF_TimeDiff")->Fill(fabs(scattTOF-timeDiff));

      if(fabs(scattTOF-timeDiff) < scatterTOFTimeDiff){
        if(saveHistos) {
          stats.getHisto2D("ScatterAngle_PrimaryTOT")->Fill(scattAngle, calculateTOT(primaryHit));
          stats.getHisto2D("ScatterAngle_ScatterTOT")->Fill(scattAngle, calculateTOT(scatterHit));
        }
        return true;
      }
    }
  }
  return false;
}

/**
* Calculation of the total TOT of the hit - Time over Threshold:
* the sum of the TOTs on all of the thresholds (1-4) and on the both sides (A,B)
*/
double EventCategorizerTools::calculateTOT(const JPetHit& hit)
{
	double tot = 0.0;

	std::vector<JPetSigCh> sigALead = hit.getSignalA().getRecoSignal()
    .getRawSignal().getPoints(JPetSigCh::Leading, JPetRawSignal::ByThrNum);
	std::vector<JPetSigCh> sigBLead = hit.getSignalB().getRecoSignal()
    .getRawSignal().getPoints(JPetSigCh::Leading, JPetRawSignal::ByThrNum);
	std::vector<JPetSigCh> sigATrail = hit.getSignalA().getRecoSignal()
    .getRawSignal().getPoints(JPetSigCh::Trailing, JPetRawSignal::ByThrNum);
	std::vector<JPetSigCh> sigBTrail = hit.getSignalB().getRecoSignal()
    .getRawSignal().getPoints(JPetSigCh::Trailing, JPetRawSignal::ByThrNum);

	for(uint i = 0; i < sigALead.size() && i < sigATrail.size(); i++)
		tot += (sigATrail.at(i).getValue() - sigALead.at(i).getValue());
	for( unsigned i = 0; i < sigBLead.size() && i < sigBTrail.size(); i++)
		tot += (sigBTrail.at(i).getValue() - sigBLead.at(i).getValue());

	return tot;
}

/**
* Calculation of distance between two hits
*/
double EventCategorizerTools::calculateDistance(const JPetHit& hit1, const JPetHit& hit2)
{
	return (hit1.getPos() - hit2.getPos()).Mag();
}

/**
* Calculation of time that light needs to travel the distance between primary gamma
* and scattered gamma. Return value in nanoseconds.
*/
double EventCategorizerTools::calculateScatteringTime(const JPetHit& hit1, const JPetHit& hit2)
{
	return calculateDistance(hit1, hit2)/kLightVelocity_cm_ns;
}

/**
* Calculation of scatter angle between primary hit and scattered hit.
* This function assumes that source of first gamma was in (0,0,0).
* Angle is calculated from scalar product, return value in degrees.
*/
double EventCategorizerTools::calculateScatteringAngle(const JPetHit& hit1, const JPetHit& hit2)
{
  return TMath::RadToDeg()*hit1.getPos().Angle(hit2.getPos() - hit1.getPos());
}

/**
* Calculation point in 3D, where annihilation occured
*/
TVector3 EventCategorizerTools::calculateAnnihilationPoint(const JPetHit& firstHit, const JPetHit& latterHit)
{
  double LORlength = calculateDistance(firstHit, latterHit);

  TVector3 middleOfLOR;
  middleOfLOR.SetX((firstHit.getPosX()+latterHit.getPosX())/2.0);
  middleOfLOR.SetY((firstHit.getPosY()+latterHit.getPosY())/2.0);
  middleOfLOR.SetZ((firstHit.getPosZ()+latterHit.getPosZ())/2.0);

  TVector3 versorOnLOR;
  versorOnLOR.SetX(fabs((latterHit.getPosX()-firstHit.getPosX())/LORlength));
  versorOnLOR.SetY(fabs((latterHit.getPosY()-firstHit.getPosY())/LORlength));
  versorOnLOR.SetZ(fabs((latterHit.getPosZ()-firstHit.getPosZ())/LORlength));

  TVector3 annihilationPoint;
  annihilationPoint.SetX(middleOfLOR.X()-versorOnLOR.X()*calculateTOF(firstHit, latterHit)*kLightVelocity_cm_ns/1000.0);
  annihilationPoint.SetY(middleOfLOR.Y()-versorOnLOR.Y()*calculateTOF(firstHit, latterHit)*kLightVelocity_cm_ns/1000.0);
  annihilationPoint.SetZ(middleOfLOR.Z()-versorOnLOR.Z()*calculateTOF(firstHit, latterHit)*kLightVelocity_cm_ns/1000.0);

  return annihilationPoint;
}

/**
* Calculation Time of flight
*/
double EventCategorizerTools::calculateTOF(const JPetHit& firstHit, const JPetHit& latterHit)
{
  double TOF = kUndefinedValue;
  if(firstHit.getTime() > latterHit.getTime()) {
    ERROR("First hit time should be earlier than later hit");
    return TOF;
  }
  TOF = firstHit.getTime()-latterHit.getTime();
  if(firstHit.getBarrelSlot().getTheta() < latterHit.getBarrelSlot().getTheta())
    return TOF;
  else return -1.0*TOF;
}
<commit_msg>return argument for deex method corr<commit_after>/**
 *  @copyright Copyright 2017 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *  @file EventCategorizerTools.cpp
 */

#include "EventCategorizerTools.h"
#include <TMath.h>
#include <vector>

using namespace std;

/**
* Method for determining type of event - back to back 2 gamma
*/
bool EventCategorizerTools::checkFor2Gamma(const JPetEvent& event, JPetStatistics& stats, bool saveHistos)
{
  if (event.getHits().size() < 2) return false;
  for(uint i = 0; i < event.getHits().size(); i++){
    for(uint j = i+1; j < event.getHits().size(); j++){
      JPetHit firstHit, secondHit;
      if(event.getHits().at(i).getTime() < event.getHits().at(j).getTime()){
        firstHit = event.getHits().at(i);
        secondHit = event.getHits().at(j);
      }else{
        firstHit = event.getHits().at(j);
        secondHit = event.getHits().at(i);
      }
      // Checking for back to back
      double thetaDiff = fabs(firstHit.getBarrelSlot().getTheta() - secondHit.getBarrelSlot().getTheta());
      if(thetaDiff > 177.0 && thetaDiff < 183.0){
        if(saveHistos){
          double distance = (secondHit.getPos()-firstHit.getPos()).Mag();
          TVector3 annhilationPoint = calculateAnnihilationPoint(firstHit, secondHit);
          stats.getHisto1D("2Gamma_Zpos")->Fill(firstHit.getPosZ());
          stats.getHisto1D("2Gamma_Zpos")->Fill(secondHit.getPosZ());
          stats.getHisto1D("2Gamma_TimeDiff")->Fill(secondHit.getTime()-firstHit.getTime());
          stats.getHisto1D("2Gamma_Dist")->Fill(distance);
          stats.getHisto1D("Annih_TOF")->Fill(calculateTOF(firstHit, secondHit));
          stats.getHisto2D("AnnihPoint_XY")->Fill(annhilationPoint.X(), annhilationPoint.Y());
          stats.getHisto2D("AnnihPoint_XZ")->Fill(annhilationPoint.X(), annhilationPoint.Z());
          stats.getHisto2D("AnnihPoint_YZ")->Fill(annhilationPoint.Y(), annhilationPoint.Z());
        }
        return true;
      }
    }
  }
  return false;
}

/**
* Method for determining type of event - 3Gamma
*/
bool EventCategorizerTools::checkFor3Gamma(const JPetEvent& event, JPetStatistics& stats, bool saveHistos)
{
  if (event.getHits().size() < 3) return false;
  for(uint i = 0; i < event.getHits().size(); i++){
    for(uint j = i+1; j < event.getHits().size(); j++){
      for(uint k = j+1; k < event.getHits().size(); k++){
        JPetHit& firstHit = event.getHits().at(i);
        JPetHit& secondHit = event.getHits().at(j);
        JPetHit& thirdHit = event.getHits().at(k);

        vector<double> thetaAngles;
        thetaAngles.push_back(firstHit.getBarrelSlot().getTheta());
        thetaAngles.push_back(secondHit.getBarrelSlot().getTheta());
        thetaAngles.push_back(thirdHit.getBarrelSlot().getTheta());
        sort(thetaAngles.begin(), thetaAngles.end());

        vector<double> relativeAngles;
        relativeAngles.push_back(thetaAngles.at(1)-thetaAngles.at(0));
        relativeAngles.push_back(thetaAngles.at(2)-thetaAngles.at(1));
        relativeAngles.push_back(360.0-thetaAngles.at(2)+thetaAngles.at(0));
        sort(relativeAngles.begin(), relativeAngles.end());
        double transformedX = relativeAngles.at(1)+relativeAngles.at(0);
        double transformedY = relativeAngles.at(1)-relativeAngles.at(0);

        if(saveHistos)
          stats.getHisto2D("3Gamma_Angles")->Fill(transformedX, transformedY);
      }
    }
  }
  return true;
}

/**
* Method for determining type of event - prompt
*/
bool EventCategorizerTools::checkForPrompt(
  const JPetEvent& event, JPetStatistics& stats, bool saveHistos,
  double deexTOTCutMin, double deexTOTCutMax)
{
  for(uint i = 0; i < event.getHits().size(); i++){
    JPetHit& hit = event.getHits().at(i);
    double tot = calculateTOT(hit);
    if(tot > deexTOTCutMin && tot < deexTOTCutMax){
      if(saveHistos) stats.getHisto1D("Deex_TOT_cut")->Fill(tot);
      return true;
    }
  }
  return false;
}

/**
* Method for determining type of event - scatter
*/
bool EventCategorizerTools::checkForScatter(
  const JPetEvent& event,
  JPetStatistics& stats,
  bool saveHistos,
  double scatterTOFTimeDiff)
{
  if (event.getHits().size() < 2) return false;
  for(uint i = 0; i < event.getHits().size(); i++){
    for(uint j = i+1; j < event.getHits().size(); j++){
      JPetHit primaryHit, scatterHit;
      if(event.getHits().at(i).getTime() < event.getHits().at(j).getTime()){
        primaryHit = event.getHits().at(i);
        scatterHit = event.getHits().at(j);
      }else{
        primaryHit = event.getHits().at(j);
        scatterHit = event.getHits().at(i);
      }

      double scattAngle = calculateScatteringAngle(primaryHit, scatterHit);
      double scattTOF = calculateScatteringTime(primaryHit, scatterHit)/1000.0;
      double timeDiff = scatterHit.getTime() - primaryHit.getTime();

      if(saveHistos)
        stats.getHisto1D("ScatterTOF_TimeDiff")->Fill(fabs(scattTOF-timeDiff));

      if(fabs(scattTOF-timeDiff) < scatterTOFTimeDiff){
        if(saveHistos) {
          stats.getHisto2D("ScatterAngle_PrimaryTOT")->Fill(scattAngle, calculateTOT(primaryHit));
          stats.getHisto2D("ScatterAngle_ScatterTOT")->Fill(scattAngle, calculateTOT(scatterHit));
        }
        return true;
      }
    }
  }
  return false;
}

/**
* Calculation of the total TOT of the hit - Time over Threshold:
* the sum of the TOTs on all of the thresholds (1-4) and on the both sides (A,B)
*/
double EventCategorizerTools::calculateTOT(const JPetHit& hit)
{
	double tot = 0.0;

	std::vector<JPetSigCh> sigALead = hit.getSignalA().getRecoSignal()
    .getRawSignal().getPoints(JPetSigCh::Leading, JPetRawSignal::ByThrNum);
	std::vector<JPetSigCh> sigBLead = hit.getSignalB().getRecoSignal()
    .getRawSignal().getPoints(JPetSigCh::Leading, JPetRawSignal::ByThrNum);
	std::vector<JPetSigCh> sigATrail = hit.getSignalA().getRecoSignal()
    .getRawSignal().getPoints(JPetSigCh::Trailing, JPetRawSignal::ByThrNum);
	std::vector<JPetSigCh> sigBTrail = hit.getSignalB().getRecoSignal()
    .getRawSignal().getPoints(JPetSigCh::Trailing, JPetRawSignal::ByThrNum);

	for(uint i = 0; i < sigALead.size() && i < sigATrail.size(); i++)
		tot += (sigATrail.at(i).getValue() - sigALead.at(i).getValue());
	for( unsigned i = 0; i < sigBLead.size() && i < sigBTrail.size(); i++)
		tot += (sigBTrail.at(i).getValue() - sigBLead.at(i).getValue());

	return tot;
}

/**
* Calculation of distance between two hits
*/
double EventCategorizerTools::calculateDistance(const JPetHit& hit1, const JPetHit& hit2)
{
	return (hit1.getPos() - hit2.getPos()).Mag();
}

/**
* Calculation of time that light needs to travel the distance between primary gamma
* and scattered gamma. Return value in nanoseconds.
*/
double EventCategorizerTools::calculateScatteringTime(const JPetHit& hit1, const JPetHit& hit2)
{
	return calculateDistance(hit1, hit2)/kLightVelocity_cm_ns;
}

/**
* Calculation of scatter angle between primary hit and scattered hit.
* This function assumes that source of first gamma was in (0,0,0).
* Angle is calculated from scalar product, return value in degrees.
*/
double EventCategorizerTools::calculateScatteringAngle(const JPetHit& hit1, const JPetHit& hit2)
{
  return TMath::RadToDeg()*hit1.getPos().Angle(hit2.getPos() - hit1.getPos());
}

/**
* Calculation point in 3D, where annihilation occured
*/
TVector3 EventCategorizerTools::calculateAnnihilationPoint(const JPetHit& firstHit, const JPetHit& latterHit)
{
  double LORlength = calculateDistance(firstHit, latterHit);

  TVector3 middleOfLOR;
  middleOfLOR.SetX((firstHit.getPosX()+latterHit.getPosX())/2.0);
  middleOfLOR.SetY((firstHit.getPosY()+latterHit.getPosY())/2.0);
  middleOfLOR.SetZ((firstHit.getPosZ()+latterHit.getPosZ())/2.0);

  TVector3 versorOnLOR;
  versorOnLOR.SetX(fabs((latterHit.getPosX()-firstHit.getPosX())/LORlength));
  versorOnLOR.SetY(fabs((latterHit.getPosY()-firstHit.getPosY())/LORlength));
  versorOnLOR.SetZ(fabs((latterHit.getPosZ()-firstHit.getPosZ())/LORlength));

  TVector3 annihilationPoint;
  annihilationPoint.SetX(middleOfLOR.X()-versorOnLOR.X()*calculateTOF(firstHit, latterHit)*kLightVelocity_cm_ns/1000.0);
  annihilationPoint.SetY(middleOfLOR.Y()-versorOnLOR.Y()*calculateTOF(firstHit, latterHit)*kLightVelocity_cm_ns/1000.0);
  annihilationPoint.SetZ(middleOfLOR.Z()-versorOnLOR.Z()*calculateTOF(firstHit, latterHit)*kLightVelocity_cm_ns/1000.0);

  return annihilationPoint;
}

/**
* Calculation Time of flight
*/
double EventCategorizerTools::calculateTOF(const JPetHit& firstHit, const JPetHit& latterHit)
{
  double TOF = kUndefinedValue;
  if(firstHit.getTime() > latterHit.getTime()) {
    ERROR("First hit time should be earlier than later hit");
    return TOF;
  }
  TOF = firstHit.getTime()-latterHit.getTime();
  if(firstHit.getBarrelSlot().getTheta() < latterHit.getBarrelSlot().getTheta())
    return TOF;
  else return -1.0*TOF;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2005 by Curtis Krauskopf
// Copyright (c) 2005 by Peter Kuemmel
//
// Code covered by the MIT License
// The authors make no representations about the suitability of this software
// for any purpose. It is provided "as is" without express or implied warranty.
////////////////////////////////////////////////////////////////////////////////

// This is an example of using the SetLongevity function for both
// singletons and globally and locally defined dynamically allocated
// objects.
//
// The program defines three classes:  Example, Keyboard and LogClass.
//
// The purpose of the Example class is to send a message to cout
// when an Example object is being destroyed.
//
// The Keyboard class is a singleton.
//
// The LogClass class is also a singleton.
//
// The pGlobal object is deleted using an adapter functor to
// customize Example's destruction (see destGlobal()).
// The glue that binds the adapter functor (above) with Loki's
// SetLongevity function is:
//
// Loki::Private::Adapter<Example>exampleAdapter = {&destGlobal};
// SetLongevity(pGlobal, globalPriority, exampleAdapter);
//
// An alternative Loki-compatible way of destroying pGlobal (without
// defining a global static functor) is to use the default parameter
// on SetLongevity:
//
// Example *pLocal = new Example("Destroying local Example");
// SetLongevity(pLocal, localPriority);
//
// The parameters passed by the user on main define the longevity values
// for (respectively):
//  1)  The global object
//  2)  The local object
//  3)  The Keyboard singleton
//  4)  The LogClass singleton
//
// Examples:
//    longevity 1 2 3 4
//    longevity 40 30 20 10
//

#include <iostream>
#include <loki/Singleton.h>   // for Loki::SingletonHolder

using namespace std;   // okay for small programs
using namespace Loki;  // okay for small programs

// These globals allow the priority for each object to be
// set in main() but used anywhere in the program.
int  globalPriority;
int  localPriority;
int  keyboardPriority;
int  logPriority;

// A generic example class that stores and echoes a const char.
//
class Example
{
public:
    Example(const char * s)
    {
        msg = s;
    };
    virtual ~Example()
    {
        echo(msg);
    }
    void echo(const char *s)
    {
        cout << s << endl;
    }
protected:
    const char *msg;
};

// A singleton Keyboard object derived from the Example class.
// Its longevity is set by the user on the command line.
//
class Keyboard : public Example
{
public:
    Keyboard() : Example("Destroying Keyboard")
    {  }
}
;

inline unsigned int GetLongevity(Keyboard *)
{
    return keyboardPriority;
}

typedef SingletonHolder<Keyboard, CreateUsingNew, SingletonWithLongevity> keyboard;

// A singleton LogClass object derived from the Example class.
// Its longevity is set by the user on the command line.
//
class LogClass : public Example
{
public:
    LogClass() : Example("Destroying LogClass")
    {  }
}
;

inline unsigned int GetLongevity(LogClass *)
{
    return logPriority;
}

typedef SingletonHolder<LogClass, CreateUsingNew, SingletonWithLongevity> LogBook;

// Instantiate a global Example object.  It's not a singleton
// but because it's instantiated with new (and therefore it isn't
// automatically destroyed) it can use the SetLongevity template function.
// Its longevity is determined by the user on the command line.
//
Example* pGlobal( new Example("Destroying global Example") );

// destGlobal() is called when the pGlobal object needs to be destroyed.
static void destGlobal()
{
    cout << "Going to delete pGlobal\n";
    delete pGlobal;
}

void help(const char *s)
{
    cout << "To use:\n";
    cout << s << " par1 par2 par3 par4\n";
    cout << "  where each par is a number that represents the object's ";
    cout << " longevity:\n";
    cout << "    par1: global object\n";
    cout << "    par2: local object\n";
    cout << "    par3: keyboard singleton\n";
    cout << "    par4: LogBook singleton\n";
    cout << "Example:  " << s << " 1 2 3 4" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 5)
    {
        help(argv[0]);
        return 0;
    }

    globalPriority = atoi(argv[1]);
    localPriority = atoi(argv[2]);
    keyboardPriority = atoi(argv[3]);
    logPriority = atoi(argv[4]);

    // Use an adapter functor to tie the destGlobal function to the
    // destruction priority for pGlobal.
    Loki::Private::Adapter<Example> exampleAdapter = { &destGlobal };
    SetLongevity(pGlobal, globalPriority, exampleAdapter);

    // Use Loki's private Deleter template function to destroy the
    // pLocal object for a user-defined priority.
    Example *pLocal = new Example("Destroying local Example");
    SetLongevity<Example, void (*)(Example*)>(pLocal, localPriority, &Loki::Private::Deleter<Example>::Delete);

    // Make the global and local objects announce their presense.
    pGlobal->echo("pGlobal created during program initialization.");
    pLocal->echo("pLocal created after main() started.");

    // Instantiate both singletons by calling them...
    LogBook::Instance().echo("LogClass singleton instantiated");
    keyboard::Instance().echo("Keyboard singleton instantiated");

    return 0;
}

<commit_msg>swap names<commit_after>////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2005 by Peter Kuemmel
//
// Code covered by the MIT License
// The author make no representations about the suitability of this software
// for any purpose. It is provided "as is" without express or implied warranty.
////////////////////////////////////////////////////////////////////////////////

#include <iostream>

#include <loki/Singleton.h>

struct L1
{
    L1(){std::cout << "create L1: " << this << "\n";}
    ~L1(){std::cout << "delete L1: " << this <<" \n";}
};

struct L2
{
    L2(){std::cout << "create L2 \n";}
    ~L2(){std::cout << "delete L2 \n";}
};

struct L3
{
    L3(){std::cout << "create L3 \n";}
    ~L3(){std::cout << "delete L3 \n";}
};

int main()
{
    Loki::SetLongevity
                (new L1, 1);
    Loki::SetLongevity<L1,    void (*)(L1*)>
                (new L1, 1, Loki::Private::Deleter<L1>::Delete);
    Loki::SetLongevity<L1,    Loki::Private::Deleter<L1>::Type>
                (new L1, 1, Loki::Private::Deleter<L1>::Delete);
    Loki::SetLongevity(new L2, 2);
    Loki::SetLongevity(new L1, 1);
    Loki::SetLongevity(new L3, 3);
    Loki::SetLongevity(new L1, 1);

    std::cout << "\n";
}

<|endoftext|>