<commit_before>/*
    This file is part of WARG's computer-vision

    Copyright (c) 2015, Waterloo Aerial Robotics Group (WARG)
    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. Usage of this code MUST be explicitly referenced to WARG and this code
       cannot be used in any competition against WARG.
    4. Neither the name of the WARG 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 WARG ''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 WARG 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 "object_detector.h"
#include "pixel_target.h"
#include <vector>
#include "frame.h"

using namespace std;
using namespace cv;

ObjectDetector::ObjectDetector(Filter * filter, ContourCreator * contourCreator){
    this->filter = filter;
    this->ccreator = contourCreator;
}

void ObjectDetector::process_frame(Frame * f){
    Mat & src = f->get_img();
    Mat * filtered = filter->filter(src);
    vector<vector<Point> > contours = *(ccreator->get_contours(*filtered));
    delete filtered;
    for(vector<Point> contour : contours){
        string type;
        Point2d centroid;
        double area;
        double perimeter;
        Scalar colour;
        Point2d error;
        double errorAngle;

        // get info from contours/image

        PixelTarget * p = new PixelTarget(type, centroid, area, perimeter, colour, error, errorAngle);
        f->add_target(p);
    }
}

ObjectDetector::~ObjectDetector(){

}
<commit_msg>added information calculation for pixeltargets/objects<commit_after>/*
    This file is part of WARG's computer-vision

    Copyright (c) 2015, Waterloo Aerial Robotics Group (WARG)
    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. Usage of this code MUST be explicitly referenced to WARG and this code
       cannot be used in any competition against WARG.
    4. Neither the name of the WARG 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 WARG ''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 WARG 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 "object_detector.h"
#include "pixel_target.h"
#include <vector>
#include "frame.h"

using namespace std;
using namespace cv;

ObjectDetector::ObjectDetector(Filter * filter, ContourCreator * contourCreator){
    this->filter = filter;
    this->ccreator = contourCreator;
}

void ObjectDetector::process_frame(Frame * f){
    Mat & src = f->get_img();
    Mat * filtered = filter->filter(src);
    vector<vector<Point> > contours = *(ccreator->get_contours(*filtered));
    delete filtered;
    for(vector<Point> contour : contours){
        string type;
        Point2d centroid;
        double area;
        double perimeter;
        Scalar colour;
        Point2d error;
        double errorAngle;

        // get info from contours/image
        Moments mu = moments(contour, false);
        centroid = Point2d( mu.m10/mu.m00 , mu.m01/mu.m00 );
        perimeter = arcLength(contour, true);
        area = contourArea(contour);
        // TODO: Calculate location error
        Mat mask = Mat::zeros(f->size(), CV_8UC1);
        drawContours(mask, vector({contour}), 0, Scalar(255), CV_FILLED);
        colour = mean(*f, mask);

        PixelTarget * p = new PixelTarget(type, centroid, area, perimeter, colour, error, errorAngle);
        f->add_target(p);
    }
}

ObjectDetector::~ObjectDetector(){

}
<|endoftext|>


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

// $Id: IconbarTool.cc,v 1.3 2003/08/12 01:01:16 fluxgen Exp $

#include "IconbarTool.hh"

#include "Screen.hh"
#include "ImageControl.hh"
#include "IconbarTheme.hh"
#include "Window.hh"
#include "IconButton.hh"
#include "Workspace.hh"

#include <iostream>
using namespace std;
class ShowTextCmd: public FbTk::Command {
    void execute() {
        cerr<<"ShowTextCmd"<<endl;
    }
};

IconbarTool::IconbarTool(const FbTk::FbWindow &parent, IconbarTheme &theme, BScreen &screen):
    ToolbarItem(ToolbarItem::RELATIVE),
    m_screen(screen),
    m_icon_container(parent),
    m_theme(theme),
    m_focused_pm(0),
    m_unfocused_pm(0),
    m_empty_pm(0) {

    theme.reconfigSig().attach(this);

    screen.clientListSig().attach(this);
    screen.currentWorkspaceSig().attach(this);

    update(0);
    renderTheme();
}

IconbarTool::~IconbarTool() {
    while (!m_icon_list.empty()) {
        delete m_icon_list.back();
        m_icon_list.pop_back();
    }

    // remove cached images
    if (m_focused_pm)
        m_screen.imageControl().removeImage(m_focused_pm);
    if (m_unfocused_pm)
        m_screen.imageControl().removeImage(m_focused_pm);
    if (m_empty_pm)
        m_screen.imageControl().removeImage(m_empty_pm);

}

void IconbarTool::move(int x, int y) {
    m_icon_container.move(x, y);
}

void IconbarTool::resize(unsigned int width, unsigned int height) {
    m_icon_container.resize(width, height);
    renderTheme();
}

void IconbarTool::moveResize(int x, int y,
                             unsigned int width, unsigned int height) {

    m_icon_container.moveResize(x, y, width, height);
    renderTheme();
}

void IconbarTool::show() {
    m_icon_container.show();
}

void IconbarTool::hide() {
    m_icon_container.hide();
}

unsigned int IconbarTool::width() const {
    return m_icon_container.width();
}

unsigned int IconbarTool::height() const {
    return m_icon_container.height();
}

void IconbarTool::update(FbTk::Subject *subj) {

    // just focus signal?
    if (subj != 0 && typeid(*subj) == typeid(FluxboxWindow::WinSubject)) {
        // we handle everything except die signal here
        FluxboxWindow::WinSubject *winsubj = static_cast<FluxboxWindow::WinSubject *>(subj);
        if (subj != &(winsubj->win().dieSig())) {
            renderTheme();
            return;
        }
    }

    // ok, we got some signal that we need to update our iconbar container

    // remove all clients and add them again...the only way to do it now
    m_icon_container.removeAll();

    while (!m_icon_list.empty()) {
        delete m_icon_list.back();
        m_icon_list.pop_back();
    }

    // get current workspace and all it's clients
    Workspace &space = *m_screen.currentWorkspace();
    // build a ItemList and add it (faster than adding single items)
    Container::ItemList items;
    Workspace::Windows::iterator it = space.windowList().begin();
    Workspace::Windows::iterator it_end = space.windowList().end();
    for (; it != it_end; ++it) {
        // we just want windows that has clients
        if ((*it)->clientList().size() == 0)
            continue;

        IconButton *button = new IconButton(m_icon_container, m_theme.focusedText().font(), **it);
        items.push_back(button);
        m_icon_list.push_back(button);

        (*it)->focusSig().attach(this);
        (*it)->dieSig().attach(this);
    }

    m_icon_container.showSubwindows();
    m_icon_container.insertItems(items);

    renderTheme();
}

void IconbarTool::renderTheme() {
    Pixmap tmp = m_focused_pm;
    if (m_theme.focusedTexture().type() == (FbTk::Texture::FLAT | FbTk::Texture::SOLID)) {
        m_focused_pm = 0;
    } else {
        m_focused_pm = m_screen.imageControl().renderImage(m_icon_container.maxWidthPerClient(),
                                                           m_icon_container.height(),
                                                           m_theme.focusedTexture());
    }

    if (tmp)
        m_screen.imageControl().removeImage(tmp);

    tmp = m_unfocused_pm;
    if (m_theme.unfocusedTexture().type() == (FbTk::Texture::FLAT | FbTk::Texture::SOLID)) {
        m_unfocused_pm = 0;
    } else {
        m_unfocused_pm = m_screen.imageControl().renderImage(m_icon_container.maxWidthPerClient(),
                                                             m_icon_container.height(),
                                                             m_theme.unfocusedTexture());
    }
    if (tmp)
        m_screen.imageControl().removeImage(tmp);

    // if we dont have any icons then we should render empty texture
    tmp = m_empty_pm;
    if (m_theme.emptyTexture().type() == (FbTk::Texture::FLAT | FbTk::Texture::SOLID)) {
        m_empty_pm = 0;
        m_icon_container.setBackgroundColor(m_theme.emptyTexture().color());
    } else {
        m_empty_pm = m_screen.imageControl().renderImage(m_icon_container.width(), m_icon_container.height(),
                                                         m_theme.emptyTexture());
        m_icon_container.setBackgroundPixmap(m_empty_pm);
    }

    if (tmp)
        m_screen.imageControl().removeImage(m_empty_pm);

    // update buttons
    IconList::iterator icon_it = m_icon_list.begin();
    IconList::iterator icon_it_end = m_icon_list.end();
    for (; icon_it != icon_it_end; ++icon_it) {

        IconButton &button = *(*icon_it);

        if (button.win().isFocused()) { // focused texture
            button.setGC(m_theme.focusedText().textGC());
            button.setFont(m_theme.focusedText().font());
            button.setJustify(m_theme.focusedText().justify());

            if (m_focused_pm != 0)
                button.setBackgroundPixmap(m_focused_pm);
            else
                button.setBackgroundColor(m_theme.focusedTexture().color());

        } else { // unfocused
            button.setGC(m_theme.unfocusedText().textGC());
            button.setFont(m_theme.unfocusedText().font());
            button.setJustify(m_theme.unfocusedText().justify());

            if (m_unfocused_pm != 0)
                button.setBackgroundPixmap(m_unfocused_pm);
            else
                button.setBackgroundColor(m_theme.unfocusedTexture().color());
        }

        button.clear();
    }
}
<commit_msg>optimized focus change rendering<commit_after>// IconbarTool.cc
// Copyright (c) 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)
//                and Simon Bowden    (rathnor at users.sourceforge.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

// $Id: IconbarTool.cc,v 1.4 2003/08/12 11:09:46 fluxgen Exp $

#include "IconbarTool.hh"

#include "Screen.hh"
#include "ImageControl.hh"
#include "IconbarTheme.hh"
#include "Window.hh"
#include "IconButton.hh"
#include "Workspace.hh"

#include <iostream>
using namespace std;
class ShowTextCmd: public FbTk::Command {
    void execute() {
        cerr<<"ShowTextCmd"<<endl;
    }
};

IconbarTool::IconbarTool(const FbTk::FbWindow &parent, IconbarTheme &theme, BScreen &screen):
    ToolbarItem(ToolbarItem::RELATIVE),
    m_screen(screen),
    m_icon_container(parent),
    m_theme(theme),
    m_focused_pm(0),
    m_unfocused_pm(0),
    m_empty_pm(0) {

    // setup signals
    theme.reconfigSig().attach(this);
    screen.clientListSig().attach(this);
    screen.currentWorkspaceSig().attach(this);

    update(0);
    renderTheme();
}

IconbarTool::~IconbarTool() {
    while (!m_icon_list.empty()) {
        delete m_icon_list.back();
        m_icon_list.pop_back();
    }

    // remove cached images
    if (m_focused_pm)
        m_screen.imageControl().removeImage(m_focused_pm);
    if (m_unfocused_pm)
        m_screen.imageControl().removeImage(m_focused_pm);
    if (m_empty_pm)
        m_screen.imageControl().removeImage(m_empty_pm);

}

void IconbarTool::move(int x, int y) {
    m_icon_container.move(x, y);
}

void IconbarTool::resize(unsigned int width, unsigned int height) {
    m_icon_container.resize(width, height);
    renderTheme();
}

void IconbarTool::moveResize(int x, int y,
                             unsigned int width, unsigned int height) {

    m_icon_container.moveResize(x, y, width, height);
    renderTheme();
}

void IconbarTool::show() {
    m_icon_container.show();
}

void IconbarTool::hide() {
    m_icon_container.hide();
}

unsigned int IconbarTool::width() const {
    return m_icon_container.width();
}

unsigned int IconbarTool::height() const {
    return m_icon_container.height();
}

void IconbarTool::update(FbTk::Subject *subj) {

    // just focus signal?
    if (subj != 0 && typeid(*subj) == typeid(FluxboxWindow::WinSubject)) {
        // we handle everything except die signal here
        FluxboxWindow::WinSubject *winsubj = static_cast<FluxboxWindow::WinSubject *>(subj);
        if (subj != &(winsubj->win().dieSig())) {
            renderButton(winsubj->win());
            return;
        }
    }

    // ok, we got some signal that we need to update our iconbar container

    // remove all clients and add them again...the only way to do it now
    m_icon_container.removeAll();

    while (!m_icon_list.empty()) {
        delete m_icon_list.back();
        m_icon_list.pop_back();
    }

    // get current workspace and all it's clients
    Workspace &space = *m_screen.currentWorkspace();
    // build a ItemList and add it (faster than adding single items)
    Container::ItemList items;
    Workspace::Windows::iterator it = space.windowList().begin();
    Workspace::Windows::iterator it_end = space.windowList().end();
    for (; it != it_end; ++it) {
        // we just want windows that has clients
        if ((*it)->clientList().size() == 0)
            continue;

        IconButton *button = new IconButton(m_icon_container, m_theme.focusedText().font(), **it);
        items.push_back(button);
        m_icon_list.push_back(button);

        (*it)->focusSig().attach(this);
        (*it)->dieSig().attach(this);
    }

    m_icon_container.showSubwindows();
    m_icon_container.insertItems(items);

    renderTheme();
}

void IconbarTool::renderButton(FluxboxWindow &win) {

    IconList::iterator icon_it = m_icon_list.begin();
    IconList::iterator icon_it_end = m_icon_list.end();
    for (; icon_it != icon_it_end; ++icon_it) {
        if (&(*icon_it)->win() == &win)
            break;
    }
    if (icon_it == m_icon_list.end())
        return;

    IconButton &button = *(*icon_it);

    if (button.win().isFocused()) { // focused texture
        button.setGC(m_theme.focusedText().textGC());
        button.setFont(m_theme.focusedText().font());
        button.setJustify(m_theme.focusedText().justify());

        if (m_focused_pm != 0)
            button.setBackgroundPixmap(m_focused_pm);
        else
            button.setBackgroundColor(m_theme.focusedTexture().color());

    } else { // unfocused
        button.setGC(m_theme.unfocusedText().textGC());
        button.setFont(m_theme.unfocusedText().font());
        button.setJustify(m_theme.unfocusedText().justify());

        if (m_unfocused_pm != 0)
            button.setBackgroundPixmap(m_unfocused_pm);
        else
            button.setBackgroundColor(m_theme.unfocusedTexture().color());
    }

}

void IconbarTool::renderTheme() {
    Pixmap tmp = m_focused_pm;
    if (m_theme.focusedTexture().type() == (FbTk::Texture::FLAT | FbTk::Texture::SOLID)) {
        m_focused_pm = 0;
    } else {
        m_focused_pm = m_screen.imageControl().renderImage(m_icon_container.maxWidthPerClient(),
                                                           m_icon_container.height(),
                                                           m_theme.focusedTexture());
    }

    if (tmp)
        m_screen.imageControl().removeImage(tmp);

    tmp = m_unfocused_pm;
    if (m_theme.unfocusedTexture().type() == (FbTk::Texture::FLAT | FbTk::Texture::SOLID)) {
        m_unfocused_pm = 0;
    } else {
        m_unfocused_pm = m_screen.imageControl().renderImage(m_icon_container.maxWidthPerClient(),
                                                             m_icon_container.height(),
                                                             m_theme.unfocusedTexture());
    }
    if (tmp)
        m_screen.imageControl().removeImage(tmp);

    // if we dont have any icons then we should render empty texture
    tmp = m_empty_pm;
    if (m_theme.emptyTexture().type() == (FbTk::Texture::FLAT | FbTk::Texture::SOLID)) {
        m_empty_pm = 0;
        m_icon_container.setBackgroundColor(m_theme.emptyTexture().color());
    } else {
        m_empty_pm = m_screen.imageControl().renderImage(m_icon_container.width(), m_icon_container.height(),
                                                         m_theme.emptyTexture());
        m_icon_container.setBackgroundPixmap(m_empty_pm);
    }

    if (tmp)
        m_screen.imageControl().removeImage(m_empty_pm);

    // update buttons
    IconList::iterator icon_it = m_icon_list.begin();
    IconList::iterator icon_it_end = m_icon_list.end();
    for (; icon_it != icon_it_end; ++icon_it) {

        IconButton &button = *(*icon_it);

        if (button.win().isFocused()) { // focused texture
            button.setGC(m_theme.focusedText().textGC());
            button.setFont(m_theme.focusedText().font());
            button.setJustify(m_theme.focusedText().justify());

            if (m_focused_pm != 0)
                button.setBackgroundPixmap(m_focused_pm);
            else
                button.setBackgroundColor(m_theme.focusedTexture().color());

        } else { // unfocused
            button.setGC(m_theme.unfocusedText().textGC());
            button.setFont(m_theme.unfocusedText().font());
            button.setJustify(m_theme.unfocusedText().justify());

            if (m_unfocused_pm != 0)
                button.setBackgroundPixmap(m_unfocused_pm);
            else
                button.setBackgroundColor(m_theme.unfocusedTexture().color());
        }

        button.clear();
    }
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include "IndexWriter.h"
#include <fnord-fts/AnalyzerAdapter.h>

using namespace fnord;

namespace cm {

RefPtr<IndexWriter> IndexWriter::openIndex(
    const String& index_path,
    const String& conf_path) {
  if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {
    RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path);
  }

  /* set up feature schema */
  FeatureSchema feature_schema;
  feature_schema.registerFeature("shop_id", 1, 1);
  feature_schema.registerFeature("category1", 2, 1);
  feature_schema.registerFeature("category2", 3, 1);
  feature_schema.registerFeature("category3", 4, 1);
  feature_schema.registerFeature("price_cents", 8, 1);

  feature_schema.registerFeature("title~de", 5, 2);
  feature_schema.registerFeature("description~de", 6, 2);
  feature_schema.registerFeature("size_description~de", 14, 2);
  feature_schema.registerFeature("material_description~de", 15, 2);
  feature_schema.registerFeature("basic_attributes~de", 16, 2);
  feature_schema.registerFeature("tags_as_text~de", 7, 2);
  feature_schema.registerFeature("title~pl", 18, 2);
  feature_schema.registerFeature("description~pl", 19, 2);
  feature_schema.registerFeature("size_description~pl", 20, 2);
  feature_schema.registerFeature("material_description~pl", 21, 2);
  feature_schema.registerFeature("basic_attributes~pl", 22, 2);
  feature_schema.registerFeature("tags_as_text~pl", 23, 2);
  feature_schema.registerFeature("image_filename", 24, 2);
  feature_schema.registerFeature("cm_clicked_terms", 31, 2);

  feature_schema.registerFeature("shop_name", 26, 3);
  feature_schema.registerFeature("shop_platform", 27, 3);
  feature_schema.registerFeature("shop_country", 28, 3);
  feature_schema.registerFeature("shop_rating_alt", 9, 3);
  feature_schema.registerFeature("shop_rating_alt2", 15, 3);
  feature_schema.registerFeature("shop_products_count", 10, 3);
  feature_schema.registerFeature("shop_orders_count", 11, 3);
  feature_schema.registerFeature("shop_rating_count", 12, 3);
  feature_schema.registerFeature("shop_rating_avg", 13, 3);
  feature_schema.registerFeature("cm_views", 29, 3);
  feature_schema.registerFeature("cm_clicks", 30, 3);
  feature_schema.registerFeature("cm_ctr", 32, 3);
  feature_schema.registerFeature("cm_ctr_norm", 33, 3);
  feature_schema.registerFeature("cm_ctr_std", 34, 3);
  feature_schema.registerFeature("cm_ctr_norm_std", 35, 3);

  /* open mdb */
  auto db_path = FileUtil::joinPaths(index_path, "db");
  FileUtil::mkdir_p(db_path);
  auto db = mdb::MDB::open(db_path, false, 68719476736lu); // 64 GiB

  /* open lucene */
  RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(conf_path));
  auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);

  auto fts_path = FileUtil::joinPaths(index_path, "fts");
  bool create = false;
  if (!FileUtil::exists(fts_path)) {
    FileUtil::mkdir_p(fts_path);
    create = true;
  }

  auto fts =
      fts::newLucene<fts::IndexWriter>(
          fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),
          adapter,
          create,
          fts::IndexWriter::MaxFieldLengthLIMITED);

  return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, fts));
}

IndexWriter::IndexWriter(
    FeatureSchema schema,
    RefPtr<mdb::MDB> db,
    std::shared_ptr<fts::IndexWriter> fts) :
    schema_(schema),
    db_(db),
    db_txn_(db_->startTransaction()),
    feature_idx_(new FeatureIndexWriter(&schema_)),
    fts_(fts) {}

IndexWriter::~IndexWriter() {
  if (db_txn_.get()) {
    db_txn_->commit();
  }

  fts_->close();
}

void IndexWriter::updateDocument(const IndexRequest& index_request) {
  stat_documents_indexed_total_.incr(1);
  auto docid = index_request.item.docID();
  feature_idx_->updateDocument(index_request, db_txn_.get());
  auto doc = feature_idx_->findDocument(docid, db_txn_.get());
  rebuildFTS(doc);
  stat_documents_indexed_success_.incr(1);
}

void IndexWriter::commit() {
  db_txn_->commit();
  db_txn_ = db_->startTransaction();
  fts_->commit();
}

void IndexWriter::rebuildFTS(DocID docid) {
  auto doc = feature_idx_->findDocument(docid, db_txn_.get());
  doc->debugPrint();
  rebuildFTS(doc);
}

void IndexWriter::rebuildFTS(RefPtr<Document> doc) {
  stat_documents_indexed_fts_.incr(1);
  auto fts_doc = fts::newLucene<fts::Document>();

  fnord::logDebug(
      "cm.indexwriter",
      "Rebuilding FTS Index for docid=$0",
      doc->docID().docid);

  fts_doc->add(
      fts::newLucene<fts::Field>(
          L"_docid",
          StringUtil::convertUTF8To16(doc->docID().docid),
          fts::Field::STORE_YES,
          fts::Field::INDEX_NOT_ANALYZED_NO_NORMS));

  HashMap<String, String> fts_fields_anal;
  for (const auto& f : doc->fields()) {

    /* title~LANG */
    if (StringUtil::beginsWith(f.first, "title~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "title~","title~");
      fts_fields_anal[k] += " " + f.second;
    }

    /* description~LANG */
    else if (StringUtil::beginsWith(f.first, "description~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "description~","text~");
      fts_fields_anal[k] += " " + f.second;
    }

    /* size_description~LANG */
    else if (StringUtil::beginsWith(f.first, "size_description~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "size_description~","text~");
      fts_fields_anal[k] += " " + f.second;
    }

    /* material_description~LANG */
    else if (StringUtil::beginsWith(f.first, "material_description~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "material_description~","text~");
      fts_fields_anal[k] += " " + f.second;
    }

    /* manufacturing_description~LANG */
    else if (StringUtil::beginsWith(f.first, "manufacturing_description~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "manufacturing_description~","text~");
      fts_fields_anal[k] += " " + f.second;
    }

    /* tags_as_text~LANG */
    else if (StringUtil::beginsWith(f.first, "tags_as_text~")) {
      fts_fields_anal["tags"] += " " + f.second;
    }

    /* shop_name */
    else if (f.first == "shop_name") {
      fts_fields_anal["tags"] += " " + f.second;
    }

    /* cm_clicked_terms */
    else if (f.first == "cm_clicked_terms") {
      fts_doc->add(
          fts::newLucene<fts::Field>(
              L"cm_clicked_terms",
              StringUtil::convertUTF8To16(f.second),
              fts::Field::STORE_NO,
              fts::Field::INDEX_ANALYZED));
    }

    else if (f.first == "cm_ctr_norm_std") {
      fts_doc->add(
          fts::newLucene<fts::Field>(
              L"cm_ctr_norm_std",
              StringUtil::convertUTF8To16(f.second),
              fts::Field::STORE_YES,
              fts::Field::INDEX_NOT_ANALYZED));
    }
  }

  for (const auto& f : fts_fields_anal) {
    fts_doc->add(
        fts::newLucene<fts::Field>(
            StringUtil::convertUTF8To16(f.first),
            StringUtil::convertUTF8To16(f.second),
            fts::Field::STORE_NO,
            fts::Field::INDEX_ANALYZED));
  }

  auto del_term = fts::newLucene<fts::Term>(
      L"_docid",
      StringUtil::convertUTF8To16(doc->docID().docid));

  fts_->updateDocument(del_term, fts_doc);
}

void IndexWriter::rebuildFTS() {
  //docs_->listDocuments([this] (const DocID& docid) -> bool {
  //  rebuildFTS(docid);
  //  return true;
  //});
}

RefPtr<mdb::MDBTransaction> IndexWriter::dbTransaction() {
  return db_txn_;
}

void IndexWriter::exportStats(const String& prefix) {
  exportStat(
      StringUtil::format("$0/documents_indexed_total", prefix),
      &stat_documents_indexed_total_,
      fnord::stats::ExportMode::EXPORT_DELTA);

  exportStat(
      StringUtil::format("$0/documents_indexed_success", prefix),
      &stat_documents_indexed_success_,
      fnord::stats::ExportMode::EXPORT_DELTA);

  exportStat(
      StringUtil::format("$0/documents_indexed_error", prefix),
      &stat_documents_indexed_error_,
      fnord::stats::ExportMode::EXPORT_DELTA);

  exportStat(
      StringUtil::format("$0/documents_indexed_fts", prefix),
      &stat_documents_indexed_fts_,
      fnord::stats::ExportMode::EXPORT_DELTA);
}

} // namespace cm
<commit_msg>boost with cm_ctr_norm_std<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include "IndexWriter.h"
#include <fnord-fts/AnalyzerAdapter.h>

using namespace fnord;

namespace cm {

RefPtr<IndexWriter> IndexWriter::openIndex(
    const String& index_path,
    const String& conf_path) {
  if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {
    RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path);
  }

  /* set up feature schema */
  FeatureSchema feature_schema;
  feature_schema.registerFeature("shop_id", 1, 1);
  feature_schema.registerFeature("category1", 2, 1);
  feature_schema.registerFeature("category2", 3, 1);
  feature_schema.registerFeature("category3", 4, 1);
  feature_schema.registerFeature("price_cents", 8, 1);

  feature_schema.registerFeature("title~de", 5, 2);
  feature_schema.registerFeature("description~de", 6, 2);
  feature_schema.registerFeature("size_description~de", 14, 2);
  feature_schema.registerFeature("material_description~de", 15, 2);
  feature_schema.registerFeature("basic_attributes~de", 16, 2);
  feature_schema.registerFeature("tags_as_text~de", 7, 2);
  feature_schema.registerFeature("title~pl", 18, 2);
  feature_schema.registerFeature("description~pl", 19, 2);
  feature_schema.registerFeature("size_description~pl", 20, 2);
  feature_schema.registerFeature("material_description~pl", 21, 2);
  feature_schema.registerFeature("basic_attributes~pl", 22, 2);
  feature_schema.registerFeature("tags_as_text~pl", 23, 2);
  feature_schema.registerFeature("image_filename", 24, 2);
  feature_schema.registerFeature("cm_clicked_terms", 31, 2);

  feature_schema.registerFeature("shop_name", 26, 3);
  feature_schema.registerFeature("shop_platform", 27, 3);
  feature_schema.registerFeature("shop_country", 28, 3);
  feature_schema.registerFeature("shop_rating_alt", 9, 3);
  feature_schema.registerFeature("shop_rating_alt2", 15, 3);
  feature_schema.registerFeature("shop_products_count", 10, 3);
  feature_schema.registerFeature("shop_orders_count", 11, 3);
  feature_schema.registerFeature("shop_rating_count", 12, 3);
  feature_schema.registerFeature("shop_rating_avg", 13, 3);
  feature_schema.registerFeature("cm_views", 29, 3);
  feature_schema.registerFeature("cm_clicks", 30, 3);
  feature_schema.registerFeature("cm_ctr", 32, 3);
  feature_schema.registerFeature("cm_ctr_norm", 33, 3);
  feature_schema.registerFeature("cm_ctr_std", 34, 3);
  feature_schema.registerFeature("cm_ctr_norm_std", 35, 3);

  /* open mdb */
  auto db_path = FileUtil::joinPaths(index_path, "db");
  FileUtil::mkdir_p(db_path);
  auto db = mdb::MDB::open(db_path, false, 68719476736lu); // 64 GiB

  /* open lucene */
  RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(conf_path));
  auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);

  auto fts_path = FileUtil::joinPaths(index_path, "fts");
  bool create = false;
  if (!FileUtil::exists(fts_path)) {
    FileUtil::mkdir_p(fts_path);
    create = true;
  }

  auto fts =
      fts::newLucene<fts::IndexWriter>(
          fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),
          adapter,
          create,
          fts::IndexWriter::MaxFieldLengthLIMITED);

  return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, fts));
}

IndexWriter::IndexWriter(
    FeatureSchema schema,
    RefPtr<mdb::MDB> db,
    std::shared_ptr<fts::IndexWriter> fts) :
    schema_(schema),
    db_(db),
    db_txn_(db_->startTransaction()),
    feature_idx_(new FeatureIndexWriter(&schema_)),
    fts_(fts) {}

IndexWriter::~IndexWriter() {
  if (db_txn_.get()) {
    db_txn_->commit();
  }

  fts_->close();
}

void IndexWriter::updateDocument(const IndexRequest& index_request) {
  stat_documents_indexed_total_.incr(1);
  auto docid = index_request.item.docID();
  feature_idx_->updateDocument(index_request, db_txn_.get());
  auto doc = feature_idx_->findDocument(docid, db_txn_.get());
  rebuildFTS(doc);
  stat_documents_indexed_success_.incr(1);
}

void IndexWriter::commit() {
  db_txn_->commit();
  db_txn_ = db_->startTransaction();
  fts_->commit();
}

void IndexWriter::rebuildFTS(DocID docid) {
  auto doc = feature_idx_->findDocument(docid, db_txn_.get());
  doc->debugPrint();
  rebuildFTS(doc);
}

void IndexWriter::rebuildFTS(RefPtr<Document> doc) {
  stat_documents_indexed_fts_.incr(1);
  auto fts_doc = fts::newLucene<fts::Document>();

  fnord::logDebug(
      "cm.indexwriter",
      "Rebuilding FTS Index for docid=$0",
      doc->docID().docid);

  fts_doc->add(
      fts::newLucene<fts::Field>(
          L"_docid",
          StringUtil::convertUTF8To16(doc->docID().docid),
          fts::Field::STORE_YES,
          fts::Field::INDEX_NOT_ANALYZED_NO_NORMS));

  double boost = 1.0;

  HashMap<String, String> fts_fields_anal;
  for (const auto& f : doc->fields()) {

    /* title~LANG */
    if (StringUtil::beginsWith(f.first, "title~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "title~","title~");
      fts_fields_anal[k] += " " + f.second;
    }

    /* description~LANG */
    else if (StringUtil::beginsWith(f.first, "description~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "description~","text~");
      fts_fields_anal[k] += " " + f.second;
    }

    /* size_description~LANG */
    else if (StringUtil::beginsWith(f.first, "size_description~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "size_description~","text~");
      fts_fields_anal[k] += " " + f.second;
    }

    /* material_description~LANG */
    else if (StringUtil::beginsWith(f.first, "material_description~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "material_description~","text~");
      fts_fields_anal[k] += " " + f.second;
    }

    /* manufacturing_description~LANG */
    else if (StringUtil::beginsWith(f.first, "manufacturing_description~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "manufacturing_description~","text~");
      fts_fields_anal[k] += " " + f.second;
    }

    /* tags_as_text~LANG */
    else if (StringUtil::beginsWith(f.first, "tags_as_text~")) {
      fts_fields_anal["tags"] += " " + f.second;
    }

    /* shop_name */
    else if (f.first == "shop_name") {
      fts_fields_anal["tags"] += " " + f.second;
    }

    /* cm_clicked_terms */
    else if (f.first == "cm_clicked_terms") {
      fts_doc->add(
          fts::newLucene<fts::Field>(
              L"cm_clicked_terms",
              StringUtil::convertUTF8To16(f.second),
              fts::Field::STORE_NO,
              fts::Field::INDEX_ANALYZED));
    }

    else if (f.first == "cm_ctr_norm_std") {
      boost = std::stod(f.second);
      //fts_doc->add(
      //    fts::newLucene<fts::Field>(
      //        L"cm_ctr_norm_std",
      //        StringUtil::convertUTF8To16(f.second),
      //        fts::Field::STORE_YES,
      //        fts::Field::INDEX_NOT_ANALYZED));
    }
  }

  for (const auto& f : fts_fields_anal) {
    fts_doc->add(
        fts::newLucene<fts::Field>(
            StringUtil::convertUTF8To16(f.first),
            StringUtil::convertUTF8To16(f.second),
            fts::Field::STORE_NO,
            fts::Field::INDEX_ANALYZED));
  }

  fts_doc->setBoost(boost);

  auto del_term = fts::newLucene<fts::Term>(
      L"_docid",
      StringUtil::convertUTF8To16(doc->docID().docid));

  fts_->updateDocument(del_term, fts_doc);
}

void IndexWriter::rebuildFTS() {
  //docs_->listDocuments([this] (const DocID& docid) -> bool {
  //  rebuildFTS(docid);
  //  return true;
  //});
}

RefPtr<mdb::MDBTransaction> IndexWriter::dbTransaction() {
  return db_txn_;
}

void IndexWriter::exportStats(const String& prefix) {
  exportStat(
      StringUtil::format("$0/documents_indexed_total", prefix),
      &stat_documents_indexed_total_,
      fnord::stats::ExportMode::EXPORT_DELTA);

  exportStat(
      StringUtil::format("$0/documents_indexed_success", prefix),
      &stat_documents_indexed_success_,
      fnord::stats::ExportMode::EXPORT_DELTA);

  exportStat(
      StringUtil::format("$0/documents_indexed_error", prefix),
      &stat_documents_indexed_error_,
      fnord::stats::ExportMode::EXPORT_DELTA);

  exportStat(
      StringUtil::format("$0/documents_indexed_fts", prefix),
      &stat_documents_indexed_fts_,
      fnord::stats::ExportMode::EXPORT_DELTA);
}

} // namespace cm
<|endoftext|>


<commit_before>/**
 *  CTrajectoryProblem class.
 *  This class describes the trajectory problem, i.e., it allows to specify
 *  for example initial conditions and number of steps.
 *
 *  Created for Copasi by Stefan Hoops 2002
 */

#include <string>

//#define COPASI_TRACE_CONSTRUCTION
#include "copasi.h"
#include "model/CModel.h"
#include "model/CState.h"
#include "utilities/CGlobals.h"
#include "utilities/CReadConfig.h"
#include "utilities/CWriteConfig.h"
#include "CScanProblem.h"

#include "trajectory/CTrajectoryTask.h"
#include "trajectory/CTrajectoryProblem.h"
#include "steadystate/CSteadyStateTask.h"
#include "steadystate/CSteadyStateProblem.h"
/**
 *  Default constructor.
 *
 */
CScanProblem::CScanProblem():
    mpModel(NULL),
    mProcessTrajectory(false),
    mpTrajectory(NULL),
    mProcessSteadyState(false),
    mpSteadyState(NULL),
    mScanItemList()
{CONSTRUCTOR_TRACE;}

/**
 *  Copy constructor.
 *  @param "const CTrajectoryProblem &" src
 */
CScanProblem::CScanProblem(const CScanProblem & src):
    mpModel(src.mpModel),
    mProcessTrajectory(src.mProcessTrajectory),
    mpTrajectory(src.mpTrajectory),
    mProcessSteadyState(src.mProcessSteadyState),
    mpSteadyState(src.mpSteadyState),
    mScanItemList(src.mScanItemList)
{CONSTRUCTOR_TRACE;}

/**
 *  Destructor.
 */
CScanProblem::~CScanProblem()
{DESTRUCTOR_TRACE;}

/**
 *  Size of the scanItem vector
 */
unsigned C_INT32 CScanProblem::getListSize() const
  {return mScanItemList.size();}

/**
 *  Add a Scan Item to the vector ScanItem
 * @param const CMethodParameterList & Item
 */
void CScanProblem::addScanItem(const CMethodParameterList & Item)
{mScanItemList.add(Item);}

/*
  Remove a parameter from the list
 */
void CScanProblem::removeScanItem(const std::string & name)
{
  mScanItemList.remove(name);
}

/*
  Swap
 */
void CScanProblem::swapScanItem(unsigned C_INT32 indexFrom, unsigned C_INT32 indexTo)
{
  mScanItemList.swap(indexFrom, indexTo);
}

/**
 *  Get a Scan Item from the vector ScanItem
 * @param "C_INT32" itemNumber
 */
CMethodParameterList * CScanProblem::getScanItem(C_INT32 itemNumber)
{return mScanItemList[itemNumber];}

/**
 *  Add a parameter to a scan item
 * @param "const C_INT32" itemNumber
 * @param "const std::string &" name
 * @param "const double &" value
 */
void CScanProblem::addScanItemParameter(const C_INT32 itemNumber,
                                        const std::string & name,
                                        const double & value)
{mScanItemList[itemNumber]->add(name, value);}

/**
 *  Get a parameter from a scan item
 * @param "const C_INT32" itemNumber
 * @param "const std::string &" name
 */
const double & CScanProblem::getScanItemParameter(const C_INT32 itemNumber,
    const std::string & name)
{return mScanItemList[itemNumber]->getValue(name);}

/**
 *  Set the value of a parameter in a scan item
 * @param "const C_INT32" itemNumber
 * @param "const std::string &" name
 * @param "const double &" value
 */
void CScanProblem::setScanItemParameter(const C_INT32 itemNumber,
                                        const std::string & name,
                                        const double & value)
{mScanItemList[itemNumber]->setValue(name, value);}

/**
 * Load a trajectory problem
 * @param "CReadConfig &" configBuffer
 */

void CScanProblem::load(CReadConfig & configBuffer,
                        CReadConfig::Mode mode)
{
  /*  if (configBuffer.getVersion() < "4.0")
      {
        mpModel = Copasi->Model;
        configBuffer.getVariable("EndTime", "C_FLOAT64",
                                 (void *) & mEndTime,
                                 CReadConfig::LOOP);
        configBuffer.getVariable("Points", "C_INT32",
                                 (void *) & mStepNumber);
        mStepNumberSetLast = true;
        mStartTime = 0.0;
        sync();
        mpInitialState = mpModel->getInitialState();
      }
    else
      {
        string Tmp;

        configBuffer.getVariable("TrajectoryProblemModel", "string", &Tmp, mode);
        if (Tmp == Copasi->Model->getTitle())
          mpModel = Copasi->Model;
        else
          fatalError();

        configBuffer.getVariable("TrajectoryProblemStepNumber",
                                 "C_INT32", &mStepNumber);
        configBuffer.getVariable("TrajectoryProblemStepSize",
                                 "C_FLOAT64", &mStepSize);
        configBuffer.getVariable("TrajectoryProblemSetLast",
                                 "bool", &mStepNumberSetLast);
        configBuffer.getVariable("TrajectoryProblemStartTime",
                                 "C_FLOAT64", &mStartTime);
        configBuffer.getVariable("TrajectoryProblemEndTime",
                                 "C_FLOAT64", &mEndTime);
        mpInitialState = new CState;
        mpInitialState->load(configBuffer);
      }
  */
  mpSteadyState->load(configBuffer);
  mpTrajectory->load(configBuffer);
}

/**
 * Save a trajectory problem
 * @param "CWriteConfig &" configBuffer
 */

void CScanProblem::save(CWriteConfig & configBuffer) const
  {
    /*
        string Tmp = mpModel->getTitle();
        configBuffer.setVariable("TrajectoryProblemModel", "string", &Tmp);

        configBuffer.setVariable("TrajectoryProblemStepNumber",
                                 "C_INT32", &mStepNumber);
        configBuffer.setVariable("TrajectoryProblemStepSize",
                                 "C_FLOAT64", &mStepSize);
        configBuffer.setVariable("TrajectoryProblemSetLast",
                                 "bool", &mStepNumberSetLast);
        configBuffer.setVariable("TrajectoryProblemStartTime",
                                 "C_FLOAT64", &mStartTime);
        configBuffer.setVariable("TrajectoryProblemEndTime",
                                 "C_FLOAT64", &mEndTime);
        mpInitialState->save(configBuffer);
    */
    mpSteadyState->save(configBuffer);
    mpTrajectory->save(configBuffer);
  }

bool CScanProblem::processTrajectory() const {return mProcessTrajectory;}

bool CScanProblem::setProcessTrajectory(const bool & processTrajectory)
{
  mProcessTrajectory = processTrajectory;
  return true;
}

bool CScanProblem::processSteadyState() const {return mProcessSteadyState;}

bool CScanProblem::setProcessSteadyState(const bool & processSteadyState)
{
  mProcessSteadyState = processSteadyState;
  return true;
}

void CScanProblem::setModel(CModel * pModel) {mpModel = pModel;}

CModel * CScanProblem::getModel() const {return mpModel;}

void CScanProblem::calculate()
{
  if ((mpSteadyState != NULL) && mProcessSteadyState)
    {
      // std::cout << "COptProblem: mpSteadyState";
      mpSteadyState->process();
    }
  if ((mpTrajectory != NULL) && mProcessTrajectory)
    {
      // std::cout << "COptProblem: mpTrajectory";
      mpTrajectory->process();
    }
}

void CScanProblem::setSteadyStateTask(CSteadyStateTask* pSteadyStateTask)
{
  mpSteadyState = pSteadyStateTask;
}

void CScanProblem::setTrajectoryTask(CTrajectoryTask* pTrajectoryTask)
{
  mpTrajectory = pTrajectoryTask;
}
<commit_msg>add the compile/setinitializestate necessary to run the steadystate/trajectory task,<commit_after>/**
 *  CTrajectoryProblem class.
 *  This class describes the trajectory problem, i.e., it allows to specify
 *  for example initial conditions and number of steps.
 *
 *  Created for Copasi by Stefan Hoops 2002
 */

#include <string>

//#define COPASI_TRACE_CONSTRUCTION
#include "copasi.h"
#include "model/CModel.h"
#include "model/CState.h"
#include "utilities/CGlobals.h"
#include "utilities/CReadConfig.h"
#include "utilities/CWriteConfig.h"
#include "CScanProblem.h"

#include "trajectory/CTrajectoryTask.h"
#include "trajectory/CTrajectoryProblem.h"
#include "steadystate/CSteadyStateTask.h"
#include "steadystate/CSteadyStateProblem.h"
/**
 *  Default constructor.
 *
 */
CScanProblem::CScanProblem():
    mpModel(NULL),
    mProcessTrajectory(false),
    mpTrajectory(NULL),
    mProcessSteadyState(false),
    mpSteadyState(NULL),
    mScanItemList()
{CONSTRUCTOR_TRACE;}

/**
 *  Copy constructor.
 *  @param "const CTrajectoryProblem &" src
 */
CScanProblem::CScanProblem(const CScanProblem & src):
    mpModel(src.mpModel),
    mProcessTrajectory(src.mProcessTrajectory),
    mpTrajectory(src.mpTrajectory),
    mProcessSteadyState(src.mProcessSteadyState),
    mpSteadyState(src.mpSteadyState),
    mScanItemList(src.mScanItemList)
{CONSTRUCTOR_TRACE;}

/**
 *  Destructor.
 */
CScanProblem::~CScanProblem()
{DESTRUCTOR_TRACE;}

/**
 *  Size of the scanItem vector
 */
unsigned C_INT32 CScanProblem::getListSize() const
  {return mScanItemList.size();}

/**
 *  Add a Scan Item to the vector ScanItem
 * @param const CMethodParameterList & Item
 */
void CScanProblem::addScanItem(const CMethodParameterList & Item)
{mScanItemList.add(Item);}

/*
  Remove a parameter from the list
 */
void CScanProblem::removeScanItem(const std::string & name)
{
  mScanItemList.remove(name);
}

/*
  Swap
 */
void CScanProblem::swapScanItem(unsigned C_INT32 indexFrom, unsigned C_INT32 indexTo)
{
  mScanItemList.swap(indexFrom, indexTo);
}

/**
 *  Get a Scan Item from the vector ScanItem
 * @param "C_INT32" itemNumber
 */
CMethodParameterList * CScanProblem::getScanItem(C_INT32 itemNumber)
{return mScanItemList[itemNumber];}

/**
 *  Add a parameter to a scan item
 * @param "const C_INT32" itemNumber
 * @param "const std::string &" name
 * @param "const double &" value
 */
void CScanProblem::addScanItemParameter(const C_INT32 itemNumber,
                                        const std::string & name,
                                        const double & value)
{mScanItemList[itemNumber]->add(name, value);}

/**
 *  Get a parameter from a scan item
 * @param "const C_INT32" itemNumber
 * @param "const std::string &" name
 */
const double & CScanProblem::getScanItemParameter(const C_INT32 itemNumber,
    const std::string & name)
{return mScanItemList[itemNumber]->getValue(name);}

/**
 *  Set the value of a parameter in a scan item
 * @param "const C_INT32" itemNumber
 * @param "const std::string &" name
 * @param "const double &" value
 */
void CScanProblem::setScanItemParameter(const C_INT32 itemNumber,
                                        const std::string & name,
                                        const double & value)
{mScanItemList[itemNumber]->setValue(name, value);}

/**
 * Load a trajectory problem
 * @param "CReadConfig &" configBuffer
 */

void CScanProblem::load(CReadConfig & configBuffer,
                        CReadConfig::Mode mode)
{
  /*  if (configBuffer.getVersion() < "4.0")
      {
        mpModel = Copasi->Model;
        configBuffer.getVariable("EndTime", "C_FLOAT64",
                                 (void *) & mEndTime,
                                 CReadConfig::LOOP);
        configBuffer.getVariable("Points", "C_INT32",
                                 (void *) & mStepNumber);
        mStepNumberSetLast = true;
        mStartTime = 0.0;
        sync();
        mpInitialState = mpModel->getInitialState();
      }
    else
      {
        string Tmp;

        configBuffer.getVariable("TrajectoryProblemModel", "string", &Tmp, mode);
        if (Tmp == Copasi->Model->getTitle())
          mpModel = Copasi->Model;
        else
          fatalError();

        configBuffer.getVariable("TrajectoryProblemStepNumber",
                                 "C_INT32", &mStepNumber);
        configBuffer.getVariable("TrajectoryProblemStepSize",
                                 "C_FLOAT64", &mStepSize);
        configBuffer.getVariable("TrajectoryProblemSetLast",
                                 "bool", &mStepNumberSetLast);
        configBuffer.getVariable("TrajectoryProblemStartTime",
                                 "C_FLOAT64", &mStartTime);
        configBuffer.getVariable("TrajectoryProblemEndTime",
                                 "C_FLOAT64", &mEndTime);
        mpInitialState = new CState;
        mpInitialState->load(configBuffer);
      }
  */
  mpSteadyState->load(configBuffer);
  mpTrajectory->load(configBuffer);
}

/**
 * Save a trajectory problem
 * @param "CWriteConfig &" configBuffer
 */

void CScanProblem::save(CWriteConfig & configBuffer) const
  {
    /*
        string Tmp = mpModel->getTitle();
        configBuffer.setVariable("TrajectoryProblemModel", "string", &Tmp);

        configBuffer.setVariable("TrajectoryProblemStepNumber",
                                 "C_INT32", &mStepNumber);
        configBuffer.setVariable("TrajectoryProblemStepSize",
                                 "C_FLOAT64", &mStepSize);
        configBuffer.setVariable("TrajectoryProblemSetLast",
                                 "bool", &mStepNumberSetLast);
        configBuffer.setVariable("TrajectoryProblemStartTime",
                                 "C_FLOAT64", &mStartTime);
        configBuffer.setVariable("TrajectoryProblemEndTime",
                                 "C_FLOAT64", &mEndTime);
        mpInitialState->save(configBuffer);
    */
    mpSteadyState->save(configBuffer);
    mpTrajectory->save(configBuffer);
  }

bool CScanProblem::processTrajectory() const {return mProcessTrajectory;}

bool CScanProblem::setProcessTrajectory(const bool & processTrajectory)
{
  mProcessTrajectory = processTrajectory;
  return true;
}

bool CScanProblem::processSteadyState() const {return mProcessSteadyState;}

bool CScanProblem::setProcessSteadyState(const bool & processSteadyState)
{
  mProcessSteadyState = processSteadyState;
  return true;
}

void CScanProblem::setModel(CModel * pModel) {mpModel = pModel;}

CModel * CScanProblem::getModel() const {return mpModel;}

void CScanProblem::calculate()
{
  if ((mpSteadyState != NULL) && mProcessSteadyState)
    {
      // std::cout << "COptProblem: mpSteadyState";
      mpSteadyState->getProblem()->getModel()->compile();
      mpSteadyState->getProblem()->
      setInitialState(mpSteadyState->getProblem()->getModel()->getInitialState());
      mpSteadyState->process();
    }
  if ((mpTrajectory != NULL) && mProcessTrajectory)
    {
      // std::cout << "COptProblem: mpTrajectory";
      mpTrajectory->getProblem()->getModel()->compile();
      mpTrajectory->getProblem()->
      setInitialState(mpTrajectory->getProblem()->getModel()->getInitialState());
      mpTrajectory->getProblem()->
      setStartTime(mpTrajectory->getProblem()->getStartTime());
      mpTrajectory->process();
    }
}

void CScanProblem::setSteadyStateTask(CSteadyStateTask* pSteadyStateTask)
{
  mpSteadyState = pSteadyStateTask;
}

void CScanProblem::setTrajectoryTask(CTrajectoryTask* pTrajectoryTask)
{
  mpTrajectory = pTrajectoryTask;
}
<|endoftext|>


<commit_before>// ----------------------------------------------------------------
// libpion: a C++ framework for building lightweight HTTP interfaces
// -----------------------------------------------------------------
// Copyright (C) 2007 Atomic Labs, Inc.  (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file COPYING or copy at http://www.boost.org/LICENSE_1_0.txt
//

#include <boost/filesystem/operations.hpp>
#include <libpion/PionConfig.hpp>
#include <libpion/PionPlugin.hpp>

#ifdef PION_WIN32
	#include <windows.h>
#else
	#include <dlfcn.h>
#endif

namespace pion {	// begin namespace pion

// static members of PionEngine

const std::string			PionPlugin::PION_PLUGIN_CREATE("pion_create_");
const std::string			PionPlugin::PION_PLUGIN_DESTROY("pion_destroy_");
#ifdef PION_WIN32
	const std::string			PionPlugin::PION_PLUGIN_EXTENSION(".dll");
#else
	const std::string			PionPlugin::PION_PLUGIN_EXTENSION(".so");
#endif
const std::string			PionPlugin::PION_CONFIG_EXTENSION(".conf");
std::vector<std::string>	PionPlugin::m_plugin_dirs;
PionPlugin::PluginMap		PionPlugin::m_plugin_map;
boost::mutex				PionPlugin::m_plugin_mutex;
PionPlugin::StaticEntryPointList	*PionPlugin::m_entry_points_ptr = NULL;

#ifdef PION_STATIC_LINKING
	boost::mutex				StaticEntryPointHelper::m_entrypoint_mutex;
#endif

// PionEngine member functions

void PionPlugin::checkCygwinPath(boost::filesystem::path& final_path,
								 const std::string& start_path)
{
#if defined(PION_WIN32) && defined(PION_CYGWIN_DIRECTORY)
	// try prepending PION_CYGWIN_DIRECTORY if not complete
	if (! final_path.is_complete() && final_path.has_root_directory()) {
		final_path = boost::filesystem::path(std::string(PION_CYGWIN_DIRECTORY) + start_path);
	}
#endif
}

void PionPlugin::addPluginDirectory(const std::string& dir)
{
#ifdef PION_WIN32
	// work around bug in boost::filesystem on Windows -> do not plugin directories
	// basically, if you create a path object on Windows, then convert it to
	// directory_string() or file_string(), then try to construct
	// a new path object based on the string, it throws an exception (ugh!!!)
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	m_plugin_dirs.push_back(dir);
#else
	boost::filesystem::path plugin_path(dir);
	checkCygwinPath(plugin_path, dir);
	if (! boost::filesystem::exists(plugin_path) )
		throw DirectoryNotFoundException(dir);
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	m_plugin_dirs.push_back(plugin_path.directory_string());
#endif
}

void PionPlugin::resetPluginDirectories(void)
{
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	m_plugin_dirs.clear();
}

void PionPlugin::open(const std::string& plugin_file)
{
	releaseData();	// make sure we're not already pointing to something

	// use a temporary object first since openPlugin() may throw
	PionPluginData plugin_data(getPluginName(plugin_file));

	// check to see if we already have a matching shared library
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	PluginMap::iterator itr = m_plugin_map.find(plugin_data.m_plugin_name);
	if (itr == m_plugin_map.end()) {
		// no plug-ins found with the same name

		// open up the shared library using our temporary data object
		openPlugin(plugin_file, plugin_data);	// may throw

		// all is good -> insert it into the plug-in map
		m_plugin_data = new PionPluginData(plugin_data);
		m_plugin_map.insert( std::make_pair(m_plugin_data->m_plugin_name,
											m_plugin_data) );
	} else {
		// found an existing plug-in with the same name
		m_plugin_data = itr->second;
	}

	// increment the number of references
	++ m_plugin_data->m_references;
}

void PionPlugin::openStaticLinked(const std::string& plugin_name,
								  void *create_func,
								  void *destroy_func)
{
	releaseData();	// make sure we're not already pointing to something

	// check to see if we already have a matching shared library
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	PluginMap::iterator itr = m_plugin_map.find(plugin_name);
	if (itr == m_plugin_map.end()) {
		// no plug-ins found with the same name

		// all is good -> insert it into the plug-in map
		m_plugin_data = new PionPluginData(plugin_name);
		m_plugin_data->m_lib_handle = NULL; // this will indicate that we are using statically linked plug-in
		m_plugin_data->m_create_func = create_func;
		m_plugin_data->m_destroy_func = destroy_func;
		m_plugin_map.insert(std::make_pair(m_plugin_data->m_plugin_name,
										   m_plugin_data));
	} else {
		// found an existing plug-in with the same name
		m_plugin_data = itr->second;
	}

	// increment the number of references
	++ m_plugin_data->m_references;
}

void PionPlugin::releaseData(void)
{
	if (m_plugin_data != NULL) {
		boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
		// double-check after locking mutex
		if (m_plugin_data != NULL && --m_plugin_data->m_references == 0) {

// The handling of dynamic libraries on Windows is EXTREMELY buggy, so if
// we are running on Windows, never release the shared libraries
#ifndef PION_WIN32
			// no more references to the plug-in library

			// release the shared object
			closeDynamicLibrary(m_plugin_data->m_lib_handle);

			// remove it from the plug-in map
			PluginMap::iterator itr = m_plugin_map.find(m_plugin_data->m_plugin_name);
			// check itr just to be safe (it SHOULD always find a match)
			if (itr != m_plugin_map.end())
				m_plugin_map.erase(itr);

			// release the heap object
			delete m_plugin_data;
#endif

		}
		m_plugin_data = NULL;
	}
}

void PionPlugin::grabData(const PionPlugin& p)
{
	releaseData();	// make sure we're not already pointing to something
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	m_plugin_data = const_cast<PionPluginData*>(p.m_plugin_data);
	if (m_plugin_data != NULL) {
		++ m_plugin_data->m_references;
	}
}

bool PionPlugin::findFile(std::string& path_to_file, const std::string& name,
						  const std::string& extension)
{
	// first, try the name as-is
	if (checkForFile(path_to_file, name, "", extension))
		return true;

	// nope, check search paths
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	for (std::vector<std::string>::iterator i = m_plugin_dirs.begin();
		 i != m_plugin_dirs.end(); ++i)
	{
		if (checkForFile(path_to_file, *i, name, extension))
			return true;
	}

	// no plug-in file found
	return false;
}

bool PionPlugin::checkForFile(std::string& final_path, const std::string& start_path,
							  const std::string& name, const std::string& extension)
{
	// check for cygwin path oddities
	boost::filesystem::path cygwin_safe_path(start_path);
	checkCygwinPath(cygwin_safe_path, start_path);
	boost::filesystem::path test_path(cygwin_safe_path);

	// if a name is specified, append it to the test path
	if (! name.empty())
		test_path /= name;

	// check for existence of plug-in (without extension)
	if (boost::filesystem::exists(test_path)) {
		final_path = test_path.file_string();
		return true;
	}

	// next, try appending the plug-in extension
	if (name.empty()) {
		// no "name" specified -> append it directly to start_path
		test_path = boost::filesystem::path(start_path + extension);
		// in this case, we need to re-check for the cygwin oddities
		checkCygwinPath(test_path, start_path + extension);
	} else {
		// name is specified, so we can just re-use cygwin_safe_path
		test_path = cygwin_safe_path /
			boost::filesystem::path(name + extension);
	}

	// re-check for existence of plug-in (after adding extension)
	if (boost::filesystem::exists(test_path)) {
		final_path = test_path.file_string();
		return true;
	}

	// no plug-in file found
	return false;
}

void PionPlugin::openPlugin(const std::string& plugin_file,
							PionPluginData& plugin_data)
{
	// get the name of the plugin (for create/destroy symbol names)
	plugin_data.m_plugin_name = getPluginName(plugin_file);

	// attempt to open the plugin; note that this tries all search paths
	// and also tries a variety of platform-specific extensions
	plugin_data.m_lib_handle = loadDynamicLibrary(plugin_file.c_str());
	if (plugin_data.m_lib_handle == NULL)
		throw PluginNotFoundException(plugin_file);

	// find the function used to create new plugin objects
	plugin_data.m_create_func =
		getLibrarySymbol(plugin_data.m_lib_handle,
						 PION_PLUGIN_CREATE + plugin_data.m_plugin_name);
	if (plugin_data.m_create_func == NULL) {
		closeDynamicLibrary(plugin_data.m_lib_handle);
		throw PluginMissingCreateException(plugin_file);
	}

	// find the function used to destroy existing plugin objects
	plugin_data.m_destroy_func =
		getLibrarySymbol(plugin_data.m_lib_handle,
						 PION_PLUGIN_DESTROY + plugin_data.m_plugin_name);
	if (plugin_data.m_destroy_func == NULL) {
		closeDynamicLibrary(plugin_data.m_lib_handle);
		throw PluginMissingDestroyException(plugin_file);
	}
}

std::string PionPlugin::getPluginName(const std::string& plugin_file)
{
	// strip path
#ifdef PION_WIN32
	std::string::size_type pos = plugin_file.find_last_of('\\');
#else
	std::string::size_type pos = plugin_file.find_last_of('/');
#endif
	std::string plugin_name = (pos == std::string::npos ?
							   plugin_file : plugin_file.substr(pos+1));
	pos = plugin_name.find('.');

	// truncate extension
	if (pos != std::string::npos)
		plugin_name.resize(pos);

	return plugin_name;
}

void *PionPlugin::loadDynamicLibrary(const std::string& plugin_file)
{
#ifdef PION_WIN32
	#ifdef BOOST_MSVC
		return LoadLibraryA(plugin_file.c_str());
	#else
		return LoadLibrary(plugin_file.c_str());
	#endif
#else
	return dlopen(plugin_file.c_str(), RTLD_LAZY);
#endif
}

void PionPlugin::closeDynamicLibrary(void *lib_handle)
{
#ifdef PION_WIN32
	FreeLibrary((HINSTANCE) lib_handle);
#else
	dlclose(lib_handle);
#endif
}

void *PionPlugin::getLibrarySymbol(void *lib_handle, const std::string& symbol)
{
#ifdef PION_WIN32
	return (void*)GetProcAddress((HINSTANCE) lib_handle, symbol.c_str());
#else
	return dlsym(lib_handle, symbol.c_str());
#endif
}

bool PionPlugin::findStaticEntryPoint(const std::string& plugin_name,
									  void **create_func,
									  void **destroy_func)
{
	// check simple case first: no entry points exist
	if (m_entry_points_ptr == NULL || m_entry_points_ptr->empty())
		return false;

	// try to find the entry point for the plugin
	for (std::list<StaticEntryPoint>::const_iterator i = m_entry_points_ptr->begin();
		 i != m_entry_points_ptr->end(); ++i) {
			if (i->m_plugin_name==plugin_name) {
				*create_func  = i->m_create_func;
				*destroy_func = i->m_destroy_func;
				return true;
			}
	}
	return false;
}

void PionPlugin::addStaticEntryPoint(const std::string& plugin_name,
									 void *create_func,
									 void *destroy_func)
{
	m_entry_points_ptr->push_back(StaticEntryPoint(plugin_name, create_func, destroy_func));
}

}	// end namespace pion
<commit_msg>http://trac.atomiclabs.com/libpion/ticket/2 Forgot to check for NULL pointer when adding a static entry point<commit_after>// ----------------------------------------------------------------
// libpion: a C++ framework for building lightweight HTTP interfaces
// -----------------------------------------------------------------
// Copyright (C) 2007 Atomic Labs, Inc.  (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file COPYING or copy at http://www.boost.org/LICENSE_1_0.txt
//

#include <boost/filesystem/operations.hpp>
#include <libpion/PionConfig.hpp>
#include <libpion/PionPlugin.hpp>

#ifdef PION_WIN32
	#include <windows.h>
#else
	#include <dlfcn.h>
#endif

namespace pion {	// begin namespace pion

// static members of PionEngine

const std::string			PionPlugin::PION_PLUGIN_CREATE("pion_create_");
const std::string			PionPlugin::PION_PLUGIN_DESTROY("pion_destroy_");
#ifdef PION_WIN32
	const std::string			PionPlugin::PION_PLUGIN_EXTENSION(".dll");
#else
	const std::string			PionPlugin::PION_PLUGIN_EXTENSION(".so");
#endif
const std::string			PionPlugin::PION_CONFIG_EXTENSION(".conf");
std::vector<std::string>	PionPlugin::m_plugin_dirs;
PionPlugin::PluginMap		PionPlugin::m_plugin_map;
boost::mutex				PionPlugin::m_plugin_mutex;
PionPlugin::StaticEntryPointList	*PionPlugin::m_entry_points_ptr = NULL;

#ifdef PION_STATIC_LINKING
	boost::mutex				StaticEntryPointHelper::m_entrypoint_mutex;
#endif

// PionEngine member functions

void PionPlugin::checkCygwinPath(boost::filesystem::path& final_path,
								 const std::string& start_path)
{
#if defined(PION_WIN32) && defined(PION_CYGWIN_DIRECTORY)
	// try prepending PION_CYGWIN_DIRECTORY if not complete
	if (! final_path.is_complete() && final_path.has_root_directory()) {
		final_path = boost::filesystem::path(std::string(PION_CYGWIN_DIRECTORY) + start_path);
	}
#endif
}

void PionPlugin::addPluginDirectory(const std::string& dir)
{
#ifdef PION_WIN32
	// work around bug in boost::filesystem on Windows -> do not plugin directories
	// basically, if you create a path object on Windows, then convert it to
	// directory_string() or file_string(), then try to construct
	// a new path object based on the string, it throws an exception (ugh!!!)
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	m_plugin_dirs.push_back(dir);
#else
	boost::filesystem::path plugin_path(dir);
	checkCygwinPath(plugin_path, dir);
	if (! boost::filesystem::exists(plugin_path) )
		throw DirectoryNotFoundException(dir);
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	m_plugin_dirs.push_back(plugin_path.directory_string());
#endif
}

void PionPlugin::resetPluginDirectories(void)
{
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	m_plugin_dirs.clear();
}

void PionPlugin::open(const std::string& plugin_file)
{
	releaseData();	// make sure we're not already pointing to something

	// use a temporary object first since openPlugin() may throw
	PionPluginData plugin_data(getPluginName(plugin_file));

	// check to see if we already have a matching shared library
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	PluginMap::iterator itr = m_plugin_map.find(plugin_data.m_plugin_name);
	if (itr == m_plugin_map.end()) {
		// no plug-ins found with the same name

		// open up the shared library using our temporary data object
		openPlugin(plugin_file, plugin_data);	// may throw

		// all is good -> insert it into the plug-in map
		m_plugin_data = new PionPluginData(plugin_data);
		m_plugin_map.insert( std::make_pair(m_plugin_data->m_plugin_name,
											m_plugin_data) );
	} else {
		// found an existing plug-in with the same name
		m_plugin_data = itr->second;
	}

	// increment the number of references
	++ m_plugin_data->m_references;
}

void PionPlugin::openStaticLinked(const std::string& plugin_name,
								  void *create_func,
								  void *destroy_func)
{
	releaseData();	// make sure we're not already pointing to something

	// check to see if we already have a matching shared library
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	PluginMap::iterator itr = m_plugin_map.find(plugin_name);
	if (itr == m_plugin_map.end()) {
		// no plug-ins found with the same name

		// all is good -> insert it into the plug-in map
		m_plugin_data = new PionPluginData(plugin_name);
		m_plugin_data->m_lib_handle = NULL; // this will indicate that we are using statically linked plug-in
		m_plugin_data->m_create_func = create_func;
		m_plugin_data->m_destroy_func = destroy_func;
		m_plugin_map.insert(std::make_pair(m_plugin_data->m_plugin_name,
										   m_plugin_data));
	} else {
		// found an existing plug-in with the same name
		m_plugin_data = itr->second;
	}

	// increment the number of references
	++ m_plugin_data->m_references;
}

void PionPlugin::releaseData(void)
{
	if (m_plugin_data != NULL) {
		boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
		// double-check after locking mutex
		if (m_plugin_data != NULL && --m_plugin_data->m_references == 0) {

// The handling of dynamic libraries on Windows is EXTREMELY buggy, so if
// we are running on Windows, never release the shared libraries
#ifndef PION_WIN32
			// no more references to the plug-in library

			// release the shared object
			closeDynamicLibrary(m_plugin_data->m_lib_handle);

			// remove it from the plug-in map
			PluginMap::iterator itr = m_plugin_map.find(m_plugin_data->m_plugin_name);
			// check itr just to be safe (it SHOULD always find a match)
			if (itr != m_plugin_map.end())
				m_plugin_map.erase(itr);

			// release the heap object
			delete m_plugin_data;
#endif

		}
		m_plugin_data = NULL;
	}
}

void PionPlugin::grabData(const PionPlugin& p)
{
	releaseData();	// make sure we're not already pointing to something
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	m_plugin_data = const_cast<PionPluginData*>(p.m_plugin_data);
	if (m_plugin_data != NULL) {
		++ m_plugin_data->m_references;
	}
}

bool PionPlugin::findFile(std::string& path_to_file, const std::string& name,
						  const std::string& extension)
{
	// first, try the name as-is
	if (checkForFile(path_to_file, name, "", extension))
		return true;

	// nope, check search paths
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	for (std::vector<std::string>::iterator i = m_plugin_dirs.begin();
		 i != m_plugin_dirs.end(); ++i)
	{
		if (checkForFile(path_to_file, *i, name, extension))
			return true;
	}

	// no plug-in file found
	return false;
}

bool PionPlugin::checkForFile(std::string& final_path, const std::string& start_path,
							  const std::string& name, const std::string& extension)
{
	// check for cygwin path oddities
	boost::filesystem::path cygwin_safe_path(start_path);
	checkCygwinPath(cygwin_safe_path, start_path);
	boost::filesystem::path test_path(cygwin_safe_path);

	// if a name is specified, append it to the test path
	if (! name.empty())
		test_path /= name;

	// check for existence of plug-in (without extension)
	if (boost::filesystem::exists(test_path)) {
		final_path = test_path.file_string();
		return true;
	}

	// next, try appending the plug-in extension
	if (name.empty()) {
		// no "name" specified -> append it directly to start_path
		test_path = boost::filesystem::path(start_path + extension);
		// in this case, we need to re-check for the cygwin oddities
		checkCygwinPath(test_path, start_path + extension);
	} else {
		// name is specified, so we can just re-use cygwin_safe_path
		test_path = cygwin_safe_path /
			boost::filesystem::path(name + extension);
	}

	// re-check for existence of plug-in (after adding extension)
	if (boost::filesystem::exists(test_path)) {
		final_path = test_path.file_string();
		return true;
	}

	// no plug-in file found
	return false;
}

void PionPlugin::openPlugin(const std::string& plugin_file,
							PionPluginData& plugin_data)
{
	// get the name of the plugin (for create/destroy symbol names)
	plugin_data.m_plugin_name = getPluginName(plugin_file);

	// attempt to open the plugin; note that this tries all search paths
	// and also tries a variety of platform-specific extensions
	plugin_data.m_lib_handle = loadDynamicLibrary(plugin_file.c_str());
	if (plugin_data.m_lib_handle == NULL)
		throw PluginNotFoundException(plugin_file);

	// find the function used to create new plugin objects
	plugin_data.m_create_func =
		getLibrarySymbol(plugin_data.m_lib_handle,
						 PION_PLUGIN_CREATE + plugin_data.m_plugin_name);
	if (plugin_data.m_create_func == NULL) {
		closeDynamicLibrary(plugin_data.m_lib_handle);
		throw PluginMissingCreateException(plugin_file);
	}

	// find the function used to destroy existing plugin objects
	plugin_data.m_destroy_func =
		getLibrarySymbol(plugin_data.m_lib_handle,
						 PION_PLUGIN_DESTROY + plugin_data.m_plugin_name);
	if (plugin_data.m_destroy_func == NULL) {
		closeDynamicLibrary(plugin_data.m_lib_handle);
		throw PluginMissingDestroyException(plugin_file);
	}
}

std::string PionPlugin::getPluginName(const std::string& plugin_file)
{
	// strip path
#ifdef PION_WIN32
	std::string::size_type pos = plugin_file.find_last_of('\\');
#else
	std::string::size_type pos = plugin_file.find_last_of('/');
#endif
	std::string plugin_name = (pos == std::string::npos ?
							   plugin_file : plugin_file.substr(pos+1));
	pos = plugin_name.find('.');

	// truncate extension
	if (pos != std::string::npos)
		plugin_name.resize(pos);

	return plugin_name;
}

void *PionPlugin::loadDynamicLibrary(const std::string& plugin_file)
{
#ifdef PION_WIN32
	#ifdef BOOST_MSVC
		return LoadLibraryA(plugin_file.c_str());
	#else
		return LoadLibrary(plugin_file.c_str());
	#endif
#else
	return dlopen(plugin_file.c_str(), RTLD_LAZY);
#endif
}

void PionPlugin::closeDynamicLibrary(void *lib_handle)
{
#ifdef PION_WIN32
	FreeLibrary((HINSTANCE) lib_handle);
#else
	dlclose(lib_handle);
#endif
}

void *PionPlugin::getLibrarySymbol(void *lib_handle, const std::string& symbol)
{
#ifdef PION_WIN32
	return (void*)GetProcAddress((HINSTANCE) lib_handle, symbol.c_str());
#else
	return dlsym(lib_handle, symbol.c_str());
#endif
}

bool PionPlugin::findStaticEntryPoint(const std::string& plugin_name,
									  void **create_func,
									  void **destroy_func)
{
	// check simple case first: no entry points exist
	if (m_entry_points_ptr == NULL || m_entry_points_ptr->empty())
		return false;

	// try to find the entry point for the plugin
	for (std::list<StaticEntryPoint>::const_iterator i = m_entry_points_ptr->begin();
		 i != m_entry_points_ptr->end(); ++i) {
			if (i->m_plugin_name==plugin_name) {
				*create_func  = i->m_create_func;
				*destroy_func = i->m_destroy_func;
				return true;
			}
	}
	return false;
}

void PionPlugin::addStaticEntryPoint(const std::string& plugin_name,
									 void *create_func,
									 void *destroy_func)
{
	if (m_entry_points_ptr == NULL)
		m_entry_points_ptr = new StaticEntryPointList;
	m_entry_points_ptr->push_back(StaticEntryPoint(plugin_name, create_func, destroy_func));
}

}	// end namespace pion
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015, 2016, 2017, Intel Corporation
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * 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.
 *
 *     * Neither the name of Intel Corporation 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
 * 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 LOG OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef PLATFORMIO_HPP_INCLUDE
#define PLATFORMIO_HPP_INCLUDE

#include <stdint.h>
#include <string>
#include <vector>
#include <map>

namespace geopm
{
    /// @brief Abstract base class describing a signal provided by a
    /// platform that can be sampled.
    class ISignal
    {
        public:
            ISignal() {}
            virtual ~ISignal() {}
            /// @brief Get the signal parameter name.
            /// @param [out] signal_name The name of the feature
            ///        being measured.
            virtual std::string name(void) const = 0;
            /// @brief Get the type of the domain under measurement.
            /// @return One of the values from the geopm_domain_type_e
            ///         enum described in PlatformTopology.hpp.
            virtual int domain_type(void) const = 0;
            /// @brief Get the index of the domain under measurement.
            /// @return The index of the domain within the set of
            ///        domains of the same type on the platform.
            virtual int domain_idx(void) const = 0;
            /// @brief Get the value of the signal.
            /// @return The value of the parameter measured in SI
            ///         units.
            virtual double sample(void) const = 0;
            /// @brief Format the value of the signal into a printable
            ///        form including units.
            /// @param sample output of a previous call to the
            ///        sample() method.
            /// @return Printable version of the signal suited for
            ///         output in a log file.
            virtual std::string log(double sample) const = 0;
    };

    /// @brief Abstract base class describing a control provided by a
    /// platform that can be adjusted.
    class IControl
    {
        public:
            IControl() {}
            virtual ~IControl() {}
            /// @brief Get the control parameter name.
            /// @param [out] control_name The name of the feature
            ///        under control.
            virtual std::string name(void) const = 0;
            /// @brief Get the type of the domain under control.
            /// @return One of the values from the geopm_domain_type_e
            ///         enum described in PlatformTopology.hpp.
            virtual int domain_type(void) const = 0;
            /// @brief Get the index of the domain under control.
            /// @return The index of the domain within the set of
            ///        domains of the same type on the platform.
            virtual int domain_idx(void) const = 0;
            /// @brief Set the value for the control.
            /// @param [in] setting value in SI units of the parameter
            ///        controlled by the object.
            virtual void adjust(double setting) = 0;
    };

    /// @brief Class which is a collection of all valid control and
    /// signal objects for a platform
    class IPlatformIO
    {
        public:
            enum m_domain_e {
                /// @brief Group of MPI processes used for control
                M_DOMAIN_PROCESS_GROUP,
                /// @brief Coherent memory domain
                M_DOMAIN_BOARD,
                /// @brief Single processor package
                M_DOMAIN_PACKAGE,
                /// @brief All CPU's within a package
                M_DOMAIN_PACKAGE_CORE,
                /// @brief Everything on package other than the cores
                M_DOMAIN_PACKAGE_UNCORE,
                /// @brief Single processing unit
                M_DOMAIN_CPU,
                /// @brief Standard off package DIMM (DRAM or NAND)
                M_DOMAIN_BOARD_MEMORY,
                /// @brief On package memory (MCDRAM)
                M_DOMAIN_PACKAGE_MEMORY,
                /// @brief Network interface controller
                M_DOMAIN_NIC,
                /// @brief Software defined grouping of tiles
                M_DOMAIN_TILE_GROUP,
                /// @brief Group of CPU's that share a cache
                M_DOMAIN_TILE,
            };

            IPlatformIO() {}
            virtual ~IPlatformIO() {}
            /// @brief Push a signal onto the end of the vector that
            ///        can be sampled.
            /// @param [in] signal_name Name of the signal requested.
            /// @param [in] domain_type One of the values from the
            ///        geopm_domain_type_e enum described in
            ///        PlatformTopology.hpp.
            /// @param [in] domain_idx The index of the domain within
            ///        the set of domains of the same type on the
            ///        platform.
            /// @return Index of signal when sample() method is called
            ///         or -1 if the signal is not valid on the
            ///         platform.
            virtual int push_signal(const std::string &signal_name,
                                    int domain_type,
                                    int domain_idx) = 0;
            /// @brief Push a control onto the end of the vector that
            ///        can be adjusted.
            /// @param [in] control_name Name of the control requested.
            /// @param [in] domain_type One of the values from the
            ///        geopm_domain_type_e enum described in
            ///        PlatformTopology.hpp.
            /// @param [in] domain_idx The index of the domain within
            ///        the set of domains of the same type on the
            ///        platform.
            /// @return Pointer to an IControl object if the requested
            ///         control is valid, otherwise returns NULL.
            virtual int push_control(const std::string &control_name,
                                     int domain_type,
                                     int domain_idx) = 0;
            /// @brief Remove all signals and controls.  Must be
            ///        called before pushing signals or controls once
            ///        they have been sampled or adjusted.
            virtual void clear(void) = 0;
            /// @brief Sample a single signal that has been pushed on
            ///        to the signal stack.
            /// @param [in] signal_idx index returned by a previous call
            ///        to push_signal() method.
            virtual double sample(int signal_idx) = 0;
            /// @brief Format the value of the signal into a printable
            ///        form including units.
            /// @param signal_idx index returned by a previous call
            ///        to push_signal() method.
            /// @return Printable version of the signal suited for
            ///         output in a log file.
            virtual std::string log(int signal_idx, double sample) = 0;
            /// @brief Adjust a single control that has been pushed on
            ///        to the control stack.
            /// @param [in] control_idx index returned by a previous call
            ///        to push_control() method.
            virtual void adjust(int control_idx,
                                double setting) = 0;
            /// @brief Measure the signals specified by the previous
            ///        call to the config() method.
            /// @param [out] signal Vector of signal values measured
            ///        from the platform in SI units.  The order of
            ///        these signals is determined by the previous
            ///        call to the config() method.
            virtual void sample(std::vector<double> &signal) = 0;
            /// @brief Set values of controls specified by the previous
            ///        calls to push_control().
            /// @brief [in] control_idx Index of control to be
            ///        adjusted.
            /// @param [in] setting Vector of control parameter values
            ///        in SI units.  The order of these controls is
            ///        determined by the previous call to the config()
            ///        method.
            virtual void adjust(const std::vector<double> &setting) = 0;
            /// @brief Fill string with the msr-safe whitelist file contents
            ///        reflecting all known MSRs for the current platform.
            /// @return String formatted to be written to
            ///        an msr-safe whitelist file.
            virtual std::string msr_whitelist(void) = 0;
            /// @brief Fill string with the msr-safe whitelist file
            ///        contents reflecting all known MSRs for the
            ///        specified platform.
            /// @param cpuid [in] The CPUID of the platform.
            /// @return String formatted to be written to an msr-safe
            ///         whitelist file.
            virtual std::string msr_whitelist(int cpuid) = 0;
    };

    IPlatformIO &platform_io(void);

}

#endif
<commit_msg>Reverse order of classes in PlatformIO.hpp.<commit_after>/*
 * Copyright (c) 2015, 2016, 2017, Intel Corporation
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * 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.
 *
 *     * Neither the name of Intel Corporation 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
 * 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 LOG OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef PLATFORMIO_HPP_INCLUDE
#define PLATFORMIO_HPP_INCLUDE

#include <stdint.h>
#include <string>
#include <vector>
#include <map>

namespace geopm
{
    /// @brief Class which is a collection of all valid control and
    /// signal objects for a platform
    class IPlatformIO
    {
        public:
            enum m_domain_e {
                /// @brief Group of MPI processes used for control
                M_DOMAIN_PROCESS_GROUP,
                /// @brief Coherent memory domain
                M_DOMAIN_BOARD,
                /// @brief Single processor package
                M_DOMAIN_PACKAGE,
                /// @brief All CPU's within a package
                M_DOMAIN_PACKAGE_CORE,
                /// @brief Everything on package other than the cores
                M_DOMAIN_PACKAGE_UNCORE,
                /// @brief Single processing unit
                M_DOMAIN_CPU,
                /// @brief Standard off package DIMM (DRAM or NAND)
                M_DOMAIN_BOARD_MEMORY,
                /// @brief On package memory (MCDRAM)
                M_DOMAIN_PACKAGE_MEMORY,
                /// @brief Network interface controller
                M_DOMAIN_NIC,
                /// @brief Software defined grouping of tiles
                M_DOMAIN_TILE_GROUP,
                /// @brief Group of CPU's that share a cache
                M_DOMAIN_TILE,
            };

            IPlatformIO() {}
            virtual ~IPlatformIO() {}
            /// @brief Push a signal onto the end of the vector that
            ///        can be sampled.
            /// @param [in] signal_name Name of the signal requested.
            /// @param [in] domain_type One of the values from the
            ///        geopm_domain_type_e enum described in
            ///        PlatformTopology.hpp.
            /// @param [in] domain_idx The index of the domain within
            ///        the set of domains of the same type on the
            ///        platform.
            /// @return Index of signal when sample() method is called
            ///         or -1 if the signal is not valid on the
            ///         platform.
            virtual int push_signal(const std::string &signal_name,
                                    int domain_type,
                                    int domain_idx) = 0;
            /// @brief Push a control onto the end of the vector that
            ///        can be adjusted.
            /// @param [in] control_name Name of the control requested.
            /// @param [in] domain_type One of the values from the
            ///        geopm_domain_type_e enum described in
            ///        PlatformTopology.hpp.
            /// @param [in] domain_idx The index of the domain within
            ///        the set of domains of the same type on the
            ///        platform.
            /// @return Pointer to an IControl object if the requested
            ///         control is valid, otherwise returns NULL.
            virtual int push_control(const std::string &control_name,
                                     int domain_type,
                                     int domain_idx) = 0;
            /// @brief Remove all signals and controls.  Must be
            ///        called before pushing signals or controls once
            ///        they have been sampled or adjusted.
            virtual void clear(void) = 0;
            /// @brief Sample a single signal that has been pushed on
            ///        to the signal stack.
            /// @param [in] signal_idx index returned by a previous call
            ///        to push_signal() method.
            virtual double sample(int signal_idx) = 0;
            /// @brief Format the value of the signal into a printable
            ///        form including units.
            /// @param signal_idx index returned by a previous call
            ///        to push_signal() method.
            /// @return Printable version of the signal suited for
            ///         output in a log file.
            virtual std::string log(int signal_idx, double sample) = 0;
            /// @brief Adjust a single control that has been pushed on
            ///        to the control stack.
            /// @param [in] control_idx index returned by a previous call
            ///        to push_control() method.
            virtual void adjust(int control_idx,
                                double setting) = 0;
            /// @brief Measure the signals specified by the previous
            ///        call to the config() method.
            /// @param [out] signal Vector of signal values measured
            ///        from the platform in SI units.  The order of
            ///        these signals is determined by the previous
            ///        call to the config() method.
            virtual void sample(std::vector<double> &signal) = 0;
            /// @brief Set values of controls specified by the previous
            ///        calls to push_control().
            /// @brief [in] control_idx Index of control to be
            ///        adjusted.
            /// @param [in] setting Vector of control parameter values
            ///        in SI units.  The order of these controls is
            ///        determined by the previous call to the config()
            ///        method.
            virtual void adjust(const std::vector<double> &setting) = 0;
            /// @brief Fill string with the msr-safe whitelist file contents
            ///        reflecting all known MSRs for the current platform.
            /// @return String formatted to be written to
            ///        an msr-safe whitelist file.
            virtual std::string msr_whitelist(void) = 0;
            /// @brief Fill string with the msr-safe whitelist file
            ///        contents reflecting all known MSRs for the
            ///        specified platform.
            /// @param cpuid [in] The CPUID of the platform.
            /// @return String formatted to be written to an msr-safe
            ///         whitelist file.
            virtual std::string msr_whitelist(int cpuid) = 0;
    };

    IPlatformIO &platform_io(void);

    /// @brief Abstract base class describing a signal provided by a
    /// platform that can be sampled.
    class ISignal
    {
        public:
            ISignal() {}
            virtual ~ISignal() {}
            /// @brief Get the signal parameter name.
            /// @param [out] signal_name The name of the feature
            ///        being measured.
            virtual std::string name(void) const = 0;
            /// @brief Get the type of the domain under measurement.
            /// @return One of the values from the IPlatformIO::m_domain_e
            ///         enum described in PlatformTopology.hpp.
            virtual int domain_type(void) const = 0;
            /// @brief Get the index of the domain under measurement.
            /// @return The index of the domain within the set of
            ///        domains of the same type on the platform.
            virtual int domain_idx(void) const = 0;
            /// @brief Get the value of the signal.
            /// @return The value of the parameter measured in SI
            ///         units.
            virtual double sample(void) const = 0;
            /// @brief Format the value of the signal into a printable
            ///        form including units.
            /// @param sample output of a previous call to the
            ///        sample() method.
            /// @return Printable version of the signal suited for
            ///         output in a log file.
            virtual std::string log(double sample) const = 0;
    };

    /// @brief Abstract base class describing a control provided by a
    /// platform that can be adjusted.
    class IControl
    {
        public:
            IControl() {}
            virtual ~IControl() {}
            /// @brief Get the control parameter name.
            /// @param [out] control_name The name of the feature
            ///        under control.
            virtual std::string name(void) const = 0;
            /// @brief Get the type of the domain under control.
            /// @return One of the values from the geopm_domain_type_e
            ///         enum described in PlatformTopology.hpp.
            virtual int domain_type(void) const = 0;
            /// @brief Get the index of the domain under control.
            /// @return The index of the domain within the set of
            ///        domains of the same type on the platform.
            virtual int domain_idx(void) const = 0;
            /// @brief Set the value for the control.
            /// @param [in] setting value in SI units of the parameter
            ///        controlled by the object.
            virtual void adjust(double setting) = 0;
    };

}

#endif
<|endoftext|>


<commit_before>#include "RapidVertex.h"

#include <iostream>

#include "TMath.h"

void RapidVertex::smearVertex() {
    double xS = 0.010817 + 0.03784*TMath::Exp(-0.0815*vertexTrue_.X());
    double yS = 0.010817 + 0.03784*TMath::Exp(-0.0815*vertexTrue_.Y());
    double zS = 0.010817 + 0.03784*TMath::Exp(-0.0815*vertexTrue_.Z());
    vertexSmeared_ = ROOT::Math::XYZPoint(xS, yS, zS);
    vertex_ = std::make_pair(vertexTrue_, vertexSmeared_);
}

<commit_msg>Updated z smearing parameters<commit_after>#include "RapidVertex.h"

#include <iostream>

#include "TMath.h"

void RapidVertex::smearVertex() {
    double xS = 0.010817 + 0.03784*TMath::Exp(-0.0815*vertexTrue_.X());
    double yS = 0.010817 + 0.03784*TMath::Exp(-0.0815*vertexTrue_.Y());
    double zS = 0.04252  + 0.2235 *TMath::Exp(-0.0814*vertexTrue_.Z());
    vertexSmeared_ = ROOT::Math::XYZPoint(xS, yS, zS);
    vertex_ = std::make_pair(vertexTrue_, vertexSmeared_);
}

<|endoftext|>