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

#include "ComponentManager.h"

namespace ros2_components
{
ComponentManager::ComponentManager(rclcpp::node::Node::SharedPtr _localNode)
{
    using namespace std::placeholders;
    //Variable Assignments
    this->RosNode = _localNode;

    //Start responder thread
    this->responder_thread = std::make_unique<std::thread>(std::bind(&ComponentManager::RespondingTask,this));
    //Qos Profile
    //rmw_qos_profile_services_default
    component_manager_profile = rmw_qos_profile_parameters;
    component_manager_profile.depth = 1000;
    //component_manager_profile.history = RMW_QOS_POLICY_KEEP_ALL_HISTORY;

    //Subscriptions
    this->ListComponentsResponseSubscription = RosNode->create_subscription<ros2_components_msg::msg::ListComponentsResponse>("ListComponentsResponse", std::bind(&ComponentManager::ListComponentsResponseCallback, this,_1), component_manager_profile);

    //Publishers
    this->ListComponentsRequestPublisher = RosNode->create_publisher<ros2_components_msg::msg::ListComponentsRequest>("ListComponentsRequest",component_manager_profile);
    std::srand(std::time(0)); // use current time as seed for random generator
    LOG(Info) << "Created new instance of a ComponentManager" << std::endl;
}

ComponentManager::ComponentManager(rclcpp::node::Node::SharedPtr _localNode, EntityBase::SharedPtr _baseEntity): ComponentManager(_localNode)
{

    //Variable Assignments
    this->BaseEntity = _baseEntity; //TODO register to components and add change callbacks
    for(EntityBase::SharedPtr & child:BaseEntity->getAllChilds())
    {
        connect(child.get(), &EntityBase::childAdded, this, &ComponentManager::OnChildAdded, Qt::DirectConnection);
        connect(child.get(), &EntityBase::childRemoved,this, &ComponentManager::OnChildRemoved, Qt::DirectConnection);
    }
    //Subscriptions
    using namespace std::placeholders;
    this->ListComponentsRequestSubscription = RosNode->create_subscription<ros2_components_msg::msg::ListComponentsRequest>("ListComponentsRequest", std::bind(&ComponentManager::ListComponentsRequestCallback, this,_1), component_manager_profile);

    //Publishers
    this->ListComponentsResponsePublisher = RosNode->create_publisher<ros2_components_msg::msg::ListComponentsResponse>("ListComponentsResponse",component_manager_profile);

}

ComponentManager::~ComponentManager()
{
    this->abort =true;
    responder_thread->join();
}

bool ComponentManager::IDAlreadyInUse(uint64_t id)
{
    for(auto & myInfo: Components)
    {
        if(myInfo.id == id)
            return true;
    }
    return false;
}

std::vector<ComponentInfo> ComponentManager::ListComponents()
{
    return Components;
}

int64_t ComponentManager::CountComponents()
{
    return Components.size();
}

std::vector<string> ComponentManager::ListNodes()
{
    return this->RosNode->get_node_graph_interface()->get_node_names();
}

std::vector<ComponentInfo> ComponentManager::ListComponentsBy(ComponentListFilter filter)
{
    return filter.Filter(this->Components);
}

ComponentInfo ComponentManager::GetInfoToId(uint64_t id, bool *success)
{
    if(success != NULL)
        *success = false;
    for(auto & comp  : Components)
    {
        if(id == comp.id)
        {
            if(success != NULL)
                *success= true;
            return comp;
        }
    }
    ComponentInfo dummy;
    return dummy;
}

void ComponentManager::UpdateComponentsList()
{
    ros2_components_msg::msg::ListComponentsRequest::SharedPtr request = std::make_shared<ros2_components_msg::msg::ListComponentsRequest>();
    request->nodename = RosNode->get_name();
    this->ListComponentsRequestPublisher->publish(request);
}

bool ComponentManager::CheckIfChildsAreAvailable(uint64_t id)
{
    std::function<bool(uint64_t)> checkChilds = [&](uint64_t id) ->bool
    {
        bool success = false;
        ComponentInfo info = this->GetInfoToId(id,&success);
        if(!success)
            return false;
        for(int64_t & childId : info.childIds )
        {
            bool result = checkChilds(childId);
            return result;
        }
        return true;
    };
    return checkChilds(id);
}

void ComponentManager::ListComponentsRequestCallback(ros2_components_msg::msg::ListComponentsRequest::SharedPtr msg)
{
    if(RosNode->get_name() != msg->nodename)
    {
        triggerResponseQueue.push(true);
    }
}

void ComponentManager::ListComponentsResponseCallback(ros2_components_msg::msg::ListComponentsResponse::SharedPtr msg)
{
    if(RosNode->get_name() != msg->nodename)
    {
        bool foundInList = false;
        ComponentInfo currentInfo = ComponentInfoFactory::FromListComponentsResponseMessage(msg);
        for(auto & myInfo: Components)
        {
            if(myInfo.name == msg->componentname)
            {
                foundInList = true;
                myInfo = currentInfo;
                //TODO emit changed event and implement equal method
            }
        }
        if(!foundInList)
        {
            Components.push_back(currentInfo);
            emit NewComponentFound(currentInfo);
        }
    }

}

void ComponentManager::RespondingTask()
{
    int count = 0;
    while(!abort)
    {
        auto responseFunc = [&]()
        {
            if(BaseEntity)
            {
                ros2_components_msg::msg::ListComponentsResponse::SharedPtr msg = ComponentInfoFactory::FromEntity(this->BaseEntity).toRosMessage();
                msg->nodename = RosNode->get_name();
                this->ListComponentsResponsePublisher->publish(msg);
                std::function<void(EntityBase::SharedPtr)> iteratingFunc = [&](EntityBase::SharedPtr ent)
                {
                    auto respMsg = ComponentInfoFactory::FromEntity(ent).toRosMessage();
                    respMsg->nodename = RosNode->get_name();
                    this->ListComponentsResponsePublisher->publish(respMsg);
                    ent->IterateThroughAllChilds(iteratingFunc);
                };

                this->BaseEntity->IterateThroughAllChilds(iteratingFunc);
            }
        };
        while(triggerResponseQueue.empty() && !abort)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
            count ++;
            if(count > 100)
            {
                count = 0;
                responseFunc();
            }
        }
        while(!triggerResponseQueue.empty())
        {
            triggerResponseQueue.pop();
            responseFunc();
        }
    }
}

void ComponentManager::OnChildAdded(EntityBase::SharedPtr child, EntityBase::SharedPtr parent, bool remote)
{
    LOG(Info) << "Child added: " << child->getName() << std::endl;
    //Connect to add events
    connect(child.get(),&EntityBase::childAdded,this, &ComponentManager::OnChildAdded);
    connect(child.get(),&EntityBase::childRemoved,this, &ComponentManager::OnChildRemoved);

    //Publish component information
    ros2_components_msg::msg::ListComponentsResponse::SharedPtr msg = ComponentInfoFactory::FromEntity(child).toRosMessage();
    msg->nodename = RosNode->get_name();
    this->ListComponentsResponsePublisher->publish(msg);

}

void ComponentManager::OnChildRemoved(EntityBase::SharedPtr child, EntityBase::SharedPtr parent, bool remote)
{
    disconnect(child.get(), &EntityBase::childAdded, this, &ComponentManager::OnChildAdded);
    disconnect(child.get(), &EntityBase::childRemoved, this, &ComponentManager::OnChildRemoved);

    ros2_components_msg::msg::ListComponentsResponse::SharedPtr msg = ComponentInfoFactory::FromEntity(child).toRosMessage();
    msg->nodename = RosNode->get_name();
    msg->deleted = true;
    this->ListComponentsResponsePublisher->publish(msg);
}

}

<commit_msg>Added delete stub<commit_after>/*
 * Copyright 2016 <Lennart Nachtigall> <firesurfer65@yahoo.de>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "ComponentManager.h"

namespace ros2_components
{
ComponentManager::ComponentManager(rclcpp::node::Node::SharedPtr _localNode)
{
    using namespace std::placeholders;
    //Variable Assignments
    this->RosNode = _localNode;

    //Start responder thread
    this->responder_thread = std::make_unique<std::thread>(std::bind(&ComponentManager::RespondingTask,this));
    //Qos Profile
    //rmw_qos_profile_services_default
    component_manager_profile = rmw_qos_profile_parameters;
    component_manager_profile.depth = 1000;
    //component_manager_profile.history = RMW_QOS_POLICY_KEEP_ALL_HISTORY;

    //Subscriptions
    this->ListComponentsResponseSubscription = RosNode->create_subscription<ros2_components_msg::msg::ListComponentsResponse>("ListComponentsResponse", std::bind(&ComponentManager::ListComponentsResponseCallback, this,_1), component_manager_profile);

    //Publishers
    this->ListComponentsRequestPublisher = RosNode->create_publisher<ros2_components_msg::msg::ListComponentsRequest>("ListComponentsRequest",component_manager_profile);
    std::srand(std::time(0)); // use current time as seed for random generator
    LOG(Info) << "Created new instance of a ComponentManager" << std::endl;
}

ComponentManager::ComponentManager(rclcpp::node::Node::SharedPtr _localNode, EntityBase::SharedPtr _baseEntity): ComponentManager(_localNode)
{

    //Variable Assignments
    this->BaseEntity = _baseEntity; //TODO register to components and add change callbacks
    for(EntityBase::SharedPtr & child:BaseEntity->getAllChilds())
    {
        connect(child.get(), &EntityBase::childAdded, this, &ComponentManager::OnChildAdded, Qt::DirectConnection);
        connect(child.get(), &EntityBase::childRemoved,this, &ComponentManager::OnChildRemoved, Qt::DirectConnection);
    }
    //Subscriptions
    using namespace std::placeholders;
    this->ListComponentsRequestSubscription = RosNode->create_subscription<ros2_components_msg::msg::ListComponentsRequest>("ListComponentsRequest", std::bind(&ComponentManager::ListComponentsRequestCallback, this,_1), component_manager_profile);

    //Publishers
    this->ListComponentsResponsePublisher = RosNode->create_publisher<ros2_components_msg::msg::ListComponentsResponse>("ListComponentsResponse",component_manager_profile);

}

ComponentManager::~ComponentManager()
{
    this->abort =true;
    responder_thread->join();
}

bool ComponentManager::IDAlreadyInUse(uint64_t id)
{
    for(auto & myInfo: Components)
    {
        if(myInfo.id == id)
            return true;
    }
    return false;
}

std::vector<ComponentInfo> ComponentManager::ListComponents()
{
    return Components;
}

int64_t ComponentManager::CountComponents()
{
    return Components.size();
}

std::vector<string> ComponentManager::ListNodes()
{
    return this->RosNode->get_node_graph_interface()->get_node_names();
}

std::vector<ComponentInfo> ComponentManager::ListComponentsBy(ComponentListFilter filter)
{
    return filter.Filter(this->Components);
}

ComponentInfo ComponentManager::GetInfoToId(uint64_t id, bool *success)
{
    if(success != NULL)
        *success = false;
    for(auto & comp  : Components)
    {
        if(id == comp.id)
        {
            if(success != NULL)
                *success= true;
            return comp;
        }
    }
    ComponentInfo dummy;
    return dummy;
}

void ComponentManager::UpdateComponentsList()
{
    ros2_components_msg::msg::ListComponentsRequest::SharedPtr request = std::make_shared<ros2_components_msg::msg::ListComponentsRequest>();
    request->nodename = RosNode->get_name();
    this->ListComponentsRequestPublisher->publish(request);
}

bool ComponentManager::CheckIfChildsAreAvailable(uint64_t id)
{
    std::function<bool(uint64_t)> checkChilds = [&](uint64_t id) ->bool
    {
        bool success = false;
        ComponentInfo info = this->GetInfoToId(id,&success);
        if(!success)
            return false;
        for(int64_t & childId : info.childIds )
        {
            bool result = checkChilds(childId);
            return result;
        }
        return true;
    };
    return checkChilds(id);
}

void ComponentManager::ListComponentsRequestCallback(ros2_components_msg::msg::ListComponentsRequest::SharedPtr msg)
{
    if(RosNode->get_name() != msg->nodename)
    {
        triggerResponseQueue.push(true);
    }
}

void ComponentManager::ListComponentsResponseCallback(ros2_components_msg::msg::ListComponentsResponse::SharedPtr msg)
{
    if(RosNode->get_name() != msg->nodename)
    {
        bool foundInList = false;
        bool toDelete = false;
        ComponentInfo currentInfo = ComponentInfoFactory::FromListComponentsResponseMessage(msg);
        for(auto & myInfo: Components)
        {
            if(myInfo.name == msg->componentname)
            {
                if(!msg->deleted)
                {
                    foundInList = true;
                    myInfo = currentInfo;
                    emit ComponentChanged(myInfo);
                }
                else
                {
                    toDelete = true;
                    //TODO delete from list
                    emit ComponentDeleted(myInfo);
                }
            }
        }

        if(!foundInList)
        {
            Components.push_back(currentInfo);
            emit NewComponentFound(currentInfo);
        }
        if(toDelete)
        {
            //TODO
        }
    }

}

void ComponentManager::RespondingTask()
{
    int count = 0;
    while(!abort)
    {
        auto responseFunc = [&]()
        {
            if(BaseEntity)
            {
                ros2_components_msg::msg::ListComponentsResponse::SharedPtr msg = ComponentInfoFactory::FromEntity(this->BaseEntity).toRosMessage();
                msg->nodename = RosNode->get_name();
                this->ListComponentsResponsePublisher->publish(msg);
                std::function<void(EntityBase::SharedPtr)> iteratingFunc = [&](EntityBase::SharedPtr ent)
                {
                    auto respMsg = ComponentInfoFactory::FromEntity(ent).toRosMessage();
                    respMsg->nodename = RosNode->get_name();
                    this->ListComponentsResponsePublisher->publish(respMsg);
                    ent->IterateThroughAllChilds(iteratingFunc);
                };

                this->BaseEntity->IterateThroughAllChilds(iteratingFunc);
            }
        };
        while(triggerResponseQueue.empty() && !abort)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
            count ++;
            if(count > 100)
            {
                count = 0;
                responseFunc();
            }
        }
        while(!triggerResponseQueue.empty())
        {
            triggerResponseQueue.pop();
            responseFunc();
        }
    }
}

void ComponentManager::OnChildAdded(EntityBase::SharedPtr child, EntityBase::SharedPtr parent, bool remote)
{
    LOG(Info) << "Child added: " << child->getName() << std::endl;
    //Connect to add events
    connect(child.get(),&EntityBase::childAdded,this, &ComponentManager::OnChildAdded);
    connect(child.get(),&EntityBase::childRemoved,this, &ComponentManager::OnChildRemoved);

    //Publish component information
    ros2_components_msg::msg::ListComponentsResponse::SharedPtr msg = ComponentInfoFactory::FromEntity(child).toRosMessage();
    msg->nodename = RosNode->get_name();
    this->ListComponentsResponsePublisher->publish(msg);

}

void ComponentManager::OnChildRemoved(EntityBase::SharedPtr child, EntityBase::SharedPtr parent, bool remote)
{
    disconnect(child.get(), &EntityBase::childAdded, this, &ComponentManager::OnChildAdded);
    disconnect(child.get(), &EntityBase::childRemoved, this, &ComponentManager::OnChildRemoved);

    ros2_components_msg::msg::ListComponentsResponse::SharedPtr msg = ComponentInfoFactory::FromEntity(child).toRosMessage();
    msg->nodename = RosNode->get_name();
    msg->deleted = true;
    this->ListComponentsResponsePublisher->publish(msg);
}

}

<|endoftext|>


<commit_before>#include "akt/unique.h"

#include <stddef.h>

using namespace akt;

enum {
  STM32F4_UNIQUE_ID_REGISTER   = 0x1fff7a10u,
  STM32F103_UNIQUE_ID_REGISTER = 0x1ffff7e8u
};

#if defined(STM32F4XX)
#define UNIQUE_ID_REGISTER STM32F4_UNIQUE_ID_REGISTER
#elif defined(STM32F1XX)
#define UNIQUE_ID_REGISTER STM32F103_UNIQUE_ID_REGISTER
#else
#error "unique.cc doesn't know which type of mcu"
#endif

// copied from http://www.partow.net/programming/hashfunctions/index.html
unsigned int rs_hash(const uint8_t *in, size_t len) {
    unsigned int b    = 378551;
    unsigned int a    = 63689;
    unsigned int hash = 0;

    for(size_t i = 0; i < len; i++) {
        hash = hash * a + in[i];
        a    = a * b;
    }

    return hash;
}

void UniqueID::raw(id_t &result) {
    const id_t *hw_reg = (const id_t *) UNIQUE_ID_REGISTER;

    result.words[0] = hw_reg->words[0];
    result.words[1] = hw_reg->words[1];
    result.words[2] = hw_reg->words[2];
}

uint32_t UniqueID::hashed() {
    const id_t *hw_reg = (const id_t *) UNIQUE_ID_REGISTER;

    return rs_hash(hw_reg->bytes, sizeof(hw_reg->bytes));
}

const char *UniqueID::hex() {
    static char result[7];

    if (result[0] == 0) {
        uint32_t h = hashed();

        for(int i=0; i < 6; ++i) {
            uint32_t ch = h % 36; // 36 == A-Z plus 0-9

            if (ch < 10) {
                result[i] = '0' + ch;
            } else {
                result[i] = 'A' + ch - 10;
            }

            h = h/36;
        }

        result[6] = '\0';
    }

    return result;
}
<commit_msg>include hal.h to access STM32 processor definition<commit_after>#include "akt/unique.h"

#include "hal.h"

#include <stddef.h>

using namespace akt;

enum {
  STM32F4_UNIQUE_ID_REGISTER   = 0x1fff7a10u,
  STM32F103_UNIQUE_ID_REGISTER = 0x1ffff7e8u
};

#if defined(STM32F4XX)
#define UNIQUE_ID_REGISTER STM32F4_UNIQUE_ID_REGISTER
#elif defined(STM32F1XX)
#define UNIQUE_ID_REGISTER STM32F103_UNIQUE_ID_REGISTER
#else
#error "unique.cc doesn't know which type of mcu"
#endif

// copied from http://www.partow.net/programming/hashfunctions/index.html
unsigned int rs_hash(const uint8_t *in, size_t len) {
    unsigned int b    = 378551;
    unsigned int a    = 63689;
    unsigned int hash = 0;

    for(size_t i = 0; i < len; i++) {
        hash = hash * a + in[i];
        a    = a * b;
    }

    return hash;
}

void UniqueID::raw(id_t &result) {
    const id_t *hw_reg = (const id_t *) UNIQUE_ID_REGISTER;

    result.words[0] = hw_reg->words[0];
    result.words[1] = hw_reg->words[1];
    result.words[2] = hw_reg->words[2];
}

uint32_t UniqueID::hashed() {
    const id_t *hw_reg = (const id_t *) UNIQUE_ID_REGISTER;

    return rs_hash(hw_reg->bytes, sizeof(hw_reg->bytes));
}

const char *UniqueID::hex() {
    static char result[7];

    if (result[0] == 0) {
        uint32_t h = hashed();

        for(int i=0; i < 6; ++i) {
            uint32_t ch = h % 36; // 36 == A-Z plus 0-9

            if (ch < 10) {
                result[i] = '0' + ch;
            } else {
                result[i] = 'A' + ch - 10;
            }

            h = h/36;
        }

        result[6] = '\0';
    }

    return result;
}
<|endoftext|>


<commit_before>//
//  main.cpp
//  SequenceAlignment
//
//  Created by jinyang on 13-7-19.
//  Copyright (c) 2013年 jinyang. All rights reserved.
//
//********************************************************************************
// Some explain for GRN:
//  1.For sequence-alignment module, GRN is obtained from data-capture module;
//  2.The GRN matrix: line for REGULATOR, row for TARGET;
//  3.The elements are supposed to be 0, -1 and +1;
//  4.i.e.
//      If gene_A enhances gene_B, then the matrix records it as:
//      GRN[index_B][index_A] = 1;
//********************************************************************************
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

int getSequenceSize (string s)
{
    int i;
    for (i = 0; s[i] != '\0'; ++i);
    return i;
}

int MaxValue (int a, int b, int c)
{
    if(a<b)
        a=b;
    if(a<c)
        a=c;
    return a;
}

//alignment score;
int AlignScore (char s, char t)
{
    int score = 0;
    int GG = 1;
    int _G = 0;
    int GT = 0;
    if (s == t)
        score = GG;
    else if (s == ' ')
        score = _G;
    else if (t == ' ')
        score = _G;
    else if (s != t)
        score = GT;
    return score;
}

//Needleman_Wunch sequence alignment;
double alignSequence (string s, string t)
{
    int G_ = 0;
    int _G = 0;
    int m = getSequenceSize (t);
    int n = getSequenceSize (s);
    //cout << m << endl << n << endl;

    ofstream ofile;
    ofile.open("result_Haosen.txt");
    //int D[8][7];
    vector< vector<int> > D(m, vector<int>(n));
    //initialize the matrix D, (0, 0), 0-line, 0-row;
    D[0][0] = 0;
    for (int i = 1; i != m; ++i)
        D[i][0] = D[i-1][0] + G_;
    for (int i = 1; i != n; ++i)
        D[0][i] = D[0][i-1] + _G;
    for (int i = 1; i != m; ++i)
        for (int j = 1; j!= n; ++j)
            D[i][j] = MaxValue(D[i-1][j-1] + AlignScore(s[j],t[i]), D[i-1][j] + AlignScore(s[j], ' '), D[i][j-1] + AlignScore(' ', t[i]));
    return (double) (D[m-1][n-1] / (double) (MaxValue(m, n, 0) - 1));
}

//locate the end of matrix, and record ARRAY INDEX;
void EndIndex (double a[][250], int end[2])
{
    int linecounter = 0;
    int rowcounter = 0;
    for (int i = 0; i != 250; ++i)
    {
        for (int j = 0; j != 250; ++j)
        {
            if (a[i][j] != 2)
            {
                linecounter = i;
                rowcounter = j;
            }
            if (end[0] < linecounter)
                end[0] = linecounter;
            if (end[1] < rowcounter)
                end[1] = rowcounter;
        }
    }
}

void Prediction (double GRN[][250])
{
    ofstream testlog;
    testlog.open("/Users/jinyang/Documents/Program C++/SequenceAlignment/SequenceAlignment/test_log.txt");
    string sequence_inquire, sequence_align;
    int endindex[2] = {0, 0};//endindex[0] records end line, endindex[1] records end row;
    //double GRN[250][250];
    double similarity[250] = { 0 };
    //initialize sequence, espetially, add a ' ' in the beginning of each sequence;
    sequence_inquire = " ";
//******************************* test module ********************************************
    ifstream inquire;
    string s;
    inquire.open("/Users/jinyang/Documents/Program C++/SequenceAlignment/SequenceAlignment/test_inquire.txt");
    inquire >> s;
    //cout << s << endl;
    sequence_inquire += s;
    inquire.close();
    //testlog << "The inquire sequence: " << sequence_inquire << endl;
//****************************************************************************************
    //calculate similarities;
    ifstream sequence;
    sequence.open("/Users/jinyang/Documents/Program C++/SequenceAlignment/SequenceAlignment/test_sequence.txt");
    string t;
    for (int gene_index = 0; gene_index != 3; ++gene_index)
    {
        sequence_align = " ";
        sequence >> t;
        sequence_align += t;
        //testlog << "The " << gene_index + 1 << " sequence is: " << sequence_align << endl;
        //sequence_align += getGeneSequence(gene_index);
        similarity[gene_index] = alignSequence(sequence_inquire, sequence_align);
        testlog << similarity[gene_index] << '\t';
    }
    testlog << endl;
    sequence.close();
    //construct GRN with new gene;
//********************************* test module ******************************************
    for (int i = 0; i != 250; ++i)
    {
        for (int j = 0; j != 250; ++j)
        {
            GRN[i][j] = 2;
        }
    }
    GRN[0][2] = 1;
    GRN[1][0] = 1;
    GRN[2][0] = 0;
    GRN[2][1] = -1;
    GRN[2][2] = 0;
//****************************************************************************************
    EndIndex(GRN, endindex);
    cout << endindex[0] << '\t' << endindex[1] << endl;
    //prepare to insert new gene, make (endindex + 1) line and row 0;
    for (int i = 0; i != endindex[0] + 1; ++i)
    {
        GRN[i][endindex[1] + 1] = 0;
    }
    for (int j = 0; j != endindex[1] + 1; ++j)
    {
        GRN[endindex[0] + 1][j] = 0;
    }
    //insert new regulary value to (endindex[1] + 1) column;
    for (int i = 0; i != endindex[0] + 1; ++i)
    {
        int counter = 0;
        for (int j = 0; j != endindex[1] + 1; ++j)
        {
            if (GRN[i][j] != 2)
            {
                counter += 1;
                GRN[i][endindex[1] + 1] += similarity[j] * GRN[i][j];
            }
        }
        GRN[i][endindex[1] + 1] = GRN[i][endindex[1] + 1] / counter;
    }
    //insert new regulary value to (endindex[0] + 1) line;
    for (int j = 0; j != endindex[1] + 1; ++j)
    {
        int counter = 0;
        for (int i = 0; i != endindex[0] + 1; ++i)
        {
            if (GRN[i][j] != 2)
            {
                counter += 1;
                GRN[endindex[0] + 1][j] += similarity[i] * GRN[i][j];
            }
        }
        GRN[endindex[0] + 1][j] = GRN[endindex[0] + 1][j] / counter;
    }
    GRN[endindex[0] + 1][endindex[1] + 1] = 0;
//*********************** test module ****************************************************
    for (int i = 0; i != endindex[0] + 2; ++i)
    {
        for (int j = 0; j != endindex[1] + 2; ++j)
        {
            testlog << GRN[i][j] << '\t';
        }
        testlog << endl;
    }
//****************************************************************************************
    testlog.close();
}
int main()
{
    double GRN[250][250];
    Prediction(GRN);
    return 0;
}
<commit_msg>test<commit_after>//
//  main.cpp
//  SequenceAlignment
//
//  Created by jinyang on 13-7-19.
//  Copyright (c) 2013年 jinyang. All rights reserved.
//
//*******************************************************************************
// Some explain for GRN:
//  1.For sequence-alignment module, GRN is obtained from data-capture module;
//  2.The GRN matrix: line for REGULATOR, row for TARGET;
//  3.The elements are supposed to be 0, -1 and +1;
//  4.i.e.
//      If gene_A enhances gene_B, then the matrix records it as:
//      GRN[index_B][index_A] = 1;
//*******************************************************************************
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

int getSequenceSize (string s)
{
    int i;
    for (i = 0; s[i] != '\0'; ++i);
    return i;
}

int MaxValue (int a, int b, int c)
{
    if(a<b)
        a=b;
    if(a<c)
        a=c;
    return a;
}

//alignment score;
int AlignScore (char s, char t)
{
    int score = 0;
    int GG = 1;
    int _G = 0;
    int GT = 0;
    if (s == t)
        score = GG;
    else if (s == ' ')
        score = _G;
    else if (t == ' ')
        score = _G;
    else if (s != t)
        score = GT;
    return score;
}

//Needleman_Wunch sequence alignment;
double alignSequence (string s, string t)
{
    int G_ = 0;
    int _G = 0;
    int m = getSequenceSize (t);
    int n = getSequenceSize (s);
    //cout << m << endl << n << endl;

    ofstream ofile;
    ofile.open("result_Haosen.txt");
    //int D[8][7];
    vector< vector<int> > D(m, vector<int>(n));
    //initialize the matrix D, (0, 0), 0-line, 0-row;
    D[0][0] = 0;
    for (int i = 1; i != m; ++i)
        D[i][0] = D[i-1][0] + G_;
    for (int i = 1; i != n; ++i)
        D[0][i] = D[0][i-1] + _G;
    for (int i = 1; i != m; ++i)
        for (int j = 1; j!= n; ++j)
            D[i][j] = MaxValue(D[i-1][j-1] + AlignScore(s[j],t[i]), D[i-1][j] + AlignScore(s[j], ' '), D[i][j-1] + AlignScore(' ', t[i]));
    return (double) (D[m-1][n-1] / (double) (MaxValue(m, n, 0) - 1));
}

//locate the end of matrix, and record ARRAY INDEX;
void EndIndex (double a[][250], int end[2])
{
    int linecounter = 0;
    int rowcounter = 0;
    for (int i = 0; i != 250; ++i)
    {
        for (int j = 0; j != 250; ++j)
        {
            if (a[i][j] != 2)
            {
                linecounter = i;
                rowcounter = j;
            }
            if (end[0] < linecounter)
                end[0] = linecounter;
            if (end[1] < rowcounter)
                end[1] = rowcounter;
        }
    }
}

void Prediction (double GRN[][250])
{
    ofstream testlog;
    testlog.open("/Users/jinyang/Documents/Program C++/SequenceAlignment/SequenceAlignment/test_log.txt");
    string sequence_inquire, sequence_align;
    int endindex[2] = {0, 0};//endindex[0] records end line, endindex[1] records end row;
    //double GRN[250][250];
    double similarity[250] = { 0 };
    //initialize sequence, espetially, add a ' ' in the beginning of each sequence;
    sequence_inquire = " ";
//******************************* test module ********************************************
    ifstream inquire;
    string s;
    inquire.open("/Users/jinyang/Documents/Program C++/SequenceAlignment/SequenceAlignment/test_inquire.txt");
    inquire >> s;
    //cout << s << endl;
    sequence_inquire += s;
    inquire.close();
    //testlog << "The inquire sequence: " << sequence_inquire << endl;
//****************************************************************************************
    //calculate similarities;
    ifstream sequence;
    sequence.open("/Users/jinyang/Documents/Program C++/SequenceAlignment/SequenceAlignment/test_sequence.txt");
    string t;
    for (int gene_index = 0; gene_index != 3; ++gene_index)
    {
        sequence_align = " ";
        sequence >> t;
        sequence_align += t;
        //testlog << "The " << gene_index + 1 << " sequence is: " << sequence_align << endl;
        //sequence_align += getGeneSequence(gene_index);
        similarity[gene_index] = alignSequence(sequence_inquire, sequence_align);
        testlog << similarity[gene_index] << '\t';
    }
    testlog << endl;
    sequence.close();
    //construct GRN with new gene;
//********************************* test module ******************************************
    for (int i = 0; i != 250; ++i)
    {
        for (int j = 0; j != 250; ++j)
        {
            GRN[i][j] = 2;
        }
    }
    GRN[0][2] = 1;
    GRN[1][0] = 1;
    GRN[2][0] = 0;
    GRN[2][1] = -1;
    GRN[2][2] = 0;
//****************************************************************************************
    EndIndex(GRN, endindex);
    cout << endindex[0] << '\t' << endindex[1] << endl;
    //prepare to insert new gene, make (endindex + 1) line and row 0;
    for (int i = 0; i != endindex[0] + 1; ++i)
    {
        GRN[i][endindex[1] + 1] = 0;
    }
    for (int j = 0; j != endindex[1] + 1; ++j)
    {
        GRN[endindex[0] + 1][j] = 0;
    }
    //insert new regulary value to (endindex[1] + 1) column;
    for (int i = 0; i != endindex[0] + 1; ++i)
    {
        int counter = 0;
        for (int j = 0; j != endindex[1] + 1; ++j)
        {
            if (GRN[i][j] != 2)
            {
                counter += 1;
                GRN[i][endindex[1] + 1] += similarity[j] * GRN[i][j];
            }
        }
        GRN[i][endindex[1] + 1] = GRN[i][endindex[1] + 1] / counter;
    }
    //insert new regulary value to (endindex[0] + 1) line;
    for (int j = 0; j != endindex[1] + 1; ++j)
    {
        int counter = 0;
        for (int i = 0; i != endindex[0] + 1; ++i)
        {
            if (GRN[i][j] != 2)
            {
                counter += 1;
                GRN[endindex[0] + 1][j] += similarity[i] * GRN[i][j];
            }
        }
        GRN[endindex[0] + 1][j] = GRN[endindex[0] + 1][j] / counter;
    }
    GRN[endindex[0] + 1][endindex[1] + 1] = 0;
//*********************** test module ****************************************************
    for (int i = 0; i != endindex[0] + 2; ++i)
    {
        for (int j = 0; j != endindex[1] + 2; ++j)
        {
            testlog << GRN[i][j] << '\t';
        }
        testlog << endl;
    }
//****************************************************************************************
    testlog.close();
}
int main()
{
    double GRN[250][250];
    Prediction(GRN);
    return 0;
}
<|endoftext|>


<commit_before>/***********************************************************************
 util.cpp - Utility functions required by several of the example
 	programs.

 Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by
 MySQL AB, and (c) 2004-2006 by Educational Technology Resources, Inc.
 Others may also hold copyrights on code in this file.  See the CREDITS
 file in the top directory of the distribution for details.

 This file is part of MySQL++.

 MySQL++ is free software; you can redistribute it and/or modify it
 under the terms of the GNU Lesser General Public License as published
 by the Free Software Foundation; either version 2.1 of the License, or
 (at your option) any later version.

 MySQL++ is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include "util.h"

#include <iostream>
#include <iomanip>
#include <stdlib.h>

// This include isn't needed by util module.  It's just a test of the
// new SSQLS feature allowing the structure to be defined in many
// modules without having a multiply-defined static variable error.
#define MYSQLPP_SSQLS_NO_STATICS
#include "stock.h"

using namespace std;

const char* kpcSampleDatabase = "mysql_cpp_data";

//// utf8trans /////////////////////////////////////////////////////////
// Converts a Unicode string encoded in UTF-8 form (which the MySQL
// database uses) to a form suitable for outputting to the standard C++
// cout stream.  Functionality is platform-specific.

char*
utf8trans(const char* utf8_str, char* out_buf, int buf_len)
{
#ifdef MYSQLPP_PLATFORM_WINDOWS
	// It's Win32, so assume console output, where output needs to be in
	// local ANSI code page by default.
	wchar_t ucs2_buf[100];
	static const int ub_chars = sizeof(ucs2_buf) / sizeof(ucs2_buf[0]);

	// First, convert UTF-8 string to UCS-2
	if (MultiByteToWideChar(CP_UTF8, 0, utf8_str, -1,
			ucs2_buf, ub_chars) > 0) {
		// Next, convert UCS-2 to local code page.
		CPINFOEX cpi;
		GetCPInfoEx(CP_OEMCP, 0, &cpi);
		WideCharToMultiByte(cpi.CodePage, 0, ucs2_buf, -1,
				out_buf, buf_len, 0, 0);
		return out_buf;
	}
	else {
		int err = GetLastError();
		if (err == ERROR_NO_UNICODE_TRANSLATION) {
			cerr << "Bad data in UTF-8 string" << endl;
		}
		else {
			cerr << "Unknown error in Unicode translation: " <<
					GetLastError() << endl;
		}
		return 0;
	}
#else
	// Assume a modern Unixy platform, where the system's terminal I/O
	// code handles UTF-8 directly.  (e.g. common Linux distributions
	// since 2001 or so, recent versions of Mac OS X, etc.)
	strncpy(out_buf, utf8_str, buf_len);
	return out_buf;
#endif
}

//// print_stock_header ////////////////////////////////////////////////
// Display a header suitable for use with print_stock_rows().

void
print_stock_header(int rows)
{
	cout << "Records found: " << rows << endl << endl;
	cout.setf(ios::left);
	cout << setw(21) << "Item" <<
			setw(10) << "Num" <<
			setw(10) << "Weight" <<
			setw(10) << "Price" <<
			"Date" << endl << endl;
}

//// print_stock_row ///////////////////////////////////////////////////
// Print out a row of data from the stock table, in a format compatible
// with the header printed out in the previous function.

void
print_stock_row(const mysqlpp::sql_char& item, mysqlpp::sql_bigint num,
		mysqlpp::sql_double weight, mysqlpp::sql_double price,
		const mysqlpp::sql_date& date)
{
	// We do UTF-8 translation on item field because there is Unicode
	// data in this field in the sample database, and some systems
	// cannot handle UTF-8 sent directly to cout.
	char buf[100];
	cout << setw(20) << utf8trans(item.c_str(), buf, sizeof(buf)) << ' ' <<
			setw(9) << num << ' ' <<
			setw(9) << weight << ' ' <<
			setw(9) << price << ' ' <<
			date << endl;
}

//// print_stock_row ///////////////////////////////////////////////////
// Take a Row from the example 'stock' table, break it up into fields,
// and call the above version of this function.

void
print_stock_row(const mysqlpp::Row& row)
{
	// The brief code below illustrates several aspects of the library
	// worth noting:
	//
	// 1. You can subscript a row by integer (position of the field in
	// the row) or by string (name of field in the row).  The former is
	// more efficient, while the latter trades some efficiency for
	// robustness in the face of schema changes.  (Consider using SSQLS
	// if you need a tradeoff in between these two positions.)
	//
	// 2. You can also get at a row's field's with Row::at(), which is
	// much like Row::operator[](int).  Besides the syntax difference,
	// the only practical difference is that only at() can access field
	// 0: this is because '0' can be converted to both int and to const
	// char*, so the compiler rightly complains that it can't decide
	// which overload to call.
	//
	// 3. Notice that we make an explicit temporary copy of the first
	// field, which is the only string field.  We must tolerate the
	// inefficiency of this copy, because Row::operator[] returns a
	// ColData object, which goes away after it is converted to some
	// other form.  So, while we could have made print_stock_row()
	// take a const char* argument (as past versions mistakenly did!)
	// this would result in a dangling pointer, since it points into the
	// ColData object, which is dead by the time the pointer is
	// evaluated in print_stock_row().  It will probably even work this
	// way, but like any memory bug, it can wreak subtle havoc.
	std::string item(row.at(0));
	print_stock_row(item, row["num"], row[2], row[3], row[4]);
}

//// print_stock_rows //////////////////////////////////////////////////
// Print out a number of rows from the example 'stock' table.

void
print_stock_rows(mysqlpp::Result& res)
{
	print_stock_header(res.size());

	// Use the Result class's read-only random access iterator to walk
	// through the query results.
	mysqlpp::Result::iterator i;
	for (i = res.begin(); i != res.end(); ++i) {
		// Notice that a dereferenced result iterator can be converted
		// to a Row object, which makes for easier element access.
		print_stock_row(*i);
	}
}

//// get_stock_table ///////////////////////////////////////////////////
// Retreive the entire contents of the example 'stock' table.

void
get_stock_table(mysqlpp::Query& query, mysqlpp::Result& res)
{
	// Reset the query object, in case we're re-using it.
	query.reset();

	// You can write to the query object like you would any ostream.
	query << "select * from stock";

	// Show the query string.  If you call preview(), it must be before
	// you call execute() or store() or use().
	cout << "Query: " << query.preview() << endl;

	// Execute the query, storing the results in memory.
	res = query.store();
}

//// print_stock_table /////////////////////////////////////////////////
// Simply retrieve and print the entire contents of the stock table.

void
print_stock_table(mysqlpp::Query& query)
{
	mysqlpp::Result res;
	get_stock_table(query, res);
	print_stock_rows(res);
}

//// connect_to_db /////////////////////////////////////////////////////
// Establishes a connection to a MySQL database server, optionally
// attaching to database kdb.  This is basically a command-line parser
// for the examples, since the example programs' arguments give us the
// information we need to establish the server connection.

bool
connect_to_db(int argc, char *argv[], mysqlpp::Connection& con,
		const char *kdb)
{
	if (argc < 1) {
		cerr << "Bad argument count: " << argc << '!' << endl;
		return false;
	}

	if (!kdb) {
		kdb = kpcSampleDatabase;
	}

	if ((argc > 1) && (argv[1][0] == '-')) {
		cout << "usage: " << argv[0] <<
				" [host] [user] [password] [port]" << endl;
		cout << endl << "\tConnects to database ";
		if (strlen(kdb) > 0) {
			cout << '"' << kdb << '"';
		}
		else {
			cout << "server";
		}
		cout << " on localhost using your user" << endl;
		cout << "\tname and no password by default." << endl << endl;
		return false;
	}

	if (argc == 1) {
		con.connect(kdb);
	}
	else if (argc == 2) {
		con.connect(kdb, argv[1]);
	}
	else if (argc == 3) {
		con.connect(kdb, argv[1], argv[2]);
	}
	else if (argc == 4) {
		con.connect(kdb, argv[1], argv[2], argv[3]);
	}
	else if (argc >= 5) {
		con.connect(kdb, argv[1], argv[2], argv[3], atoi(argv[4]));
	}

	if (con) {
		return true;
	}
	else {
		cerr << "Database connection failed: " << con.error() << endl;
		return false;
	}
}
<commit_msg>Disabling the multiply defined static member fix test when Visual C++ 2003 is detected.<commit_after>/***********************************************************************
 util.cpp - Utility functions required by several of the example
 	programs.

 Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by
 MySQL AB, and (c) 2004-2006 by Educational Technology Resources, Inc.
 Others may also hold copyrights on code in this file.  See the CREDITS
 file in the top directory of the distribution for details.

 This file is part of MySQL++.

 MySQL++ is free software; you can redistribute it and/or modify it
 under the terms of the GNU Lesser General Public License as published
 by the Free Software Foundation; either version 2.1 of the License, or
 (at your option) any later version.

 MySQL++ is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include "util.h"

#include <iostream>
#include <iomanip>
#include <stdlib.h>

// This include isn't needed by util module.  It's just a test of the
// new SSQLS feature allowing the structure to be defined in many
// modules without having a multiply-defined static variable error.
// Don't do this for VC++ 2003: it doesn't support variadic macros,
// which this feature depends on.
#if !defined(_MSC_VER) || _MSC_VER >= 1400
#	define MYSQLPP_SSQLS_NO_STATICS
#	include "stock.h"
#endif

using namespace std;

const char* kpcSampleDatabase = "mysql_cpp_data";

//// utf8trans /////////////////////////////////////////////////////////
// Converts a Unicode string encoded in UTF-8 form (which the MySQL
// database uses) to a form suitable for outputting to the standard C++
// cout stream.  Functionality is platform-specific.

char*
utf8trans(const char* utf8_str, char* out_buf, int buf_len)
{
#ifdef MYSQLPP_PLATFORM_WINDOWS
	// It's Win32, so assume console output, where output needs to be in
	// local ANSI code page by default.
	wchar_t ucs2_buf[100];
	static const int ub_chars = sizeof(ucs2_buf) / sizeof(ucs2_buf[0]);

	// First, convert UTF-8 string to UCS-2
	if (MultiByteToWideChar(CP_UTF8, 0, utf8_str, -1,
			ucs2_buf, ub_chars) > 0) {
		// Next, convert UCS-2 to local code page.
		CPINFOEX cpi;
		GetCPInfoEx(CP_OEMCP, 0, &cpi);
		WideCharToMultiByte(cpi.CodePage, 0, ucs2_buf, -1,
				out_buf, buf_len, 0, 0);
		return out_buf;
	}
	else {
		int err = GetLastError();
		if (err == ERROR_NO_UNICODE_TRANSLATION) {
			cerr << "Bad data in UTF-8 string" << endl;
		}
		else {
			cerr << "Unknown error in Unicode translation: " <<
					GetLastError() << endl;
		}
		return 0;
	}
#else
	// Assume a modern Unixy platform, where the system's terminal I/O
	// code handles UTF-8 directly.  (e.g. common Linux distributions
	// since 2001 or so, recent versions of Mac OS X, etc.)
	strncpy(out_buf, utf8_str, buf_len);
	return out_buf;
#endif
}

//// print_stock_header ////////////////////////////////////////////////
// Display a header suitable for use with print_stock_rows().

void
print_stock_header(int rows)
{
	cout << "Records found: " << rows << endl << endl;
	cout.setf(ios::left);
	cout << setw(21) << "Item" <<
			setw(10) << "Num" <<
			setw(10) << "Weight" <<
			setw(10) << "Price" <<
			"Date" << endl << endl;
}

//// print_stock_row ///////////////////////////////////////////////////
// Print out a row of data from the stock table, in a format compatible
// with the header printed out in the previous function.

void
print_stock_row(const mysqlpp::sql_char& item, mysqlpp::sql_bigint num,
		mysqlpp::sql_double weight, mysqlpp::sql_double price,
		const mysqlpp::sql_date& date)
{
	// We do UTF-8 translation on item field because there is Unicode
	// data in this field in the sample database, and some systems
	// cannot handle UTF-8 sent directly to cout.
	char buf[100];
	cout << setw(20) << utf8trans(item.c_str(), buf, sizeof(buf)) << ' ' <<
			setw(9) << num << ' ' <<
			setw(9) << weight << ' ' <<
			setw(9) << price << ' ' <<
			date << endl;
}

//// print_stock_row ///////////////////////////////////////////////////
// Take a Row from the example 'stock' table, break it up into fields,
// and call the above version of this function.

void
print_stock_row(const mysqlpp::Row& row)
{
	// The brief code below illustrates several aspects of the library
	// worth noting:
	//
	// 1. You can subscript a row by integer (position of the field in
	// the row) or by string (name of field in the row).  The former is
	// more efficient, while the latter trades some efficiency for
	// robustness in the face of schema changes.  (Consider using SSQLS
	// if you need a tradeoff in between these two positions.)
	//
	// 2. You can also get at a row's field's with Row::at(), which is
	// much like Row::operator[](int).  Besides the syntax difference,
	// the only practical difference is that only at() can access field
	// 0: this is because '0' can be converted to both int and to const
	// char*, so the compiler rightly complains that it can't decide
	// which overload to call.
	//
	// 3. Notice that we make an explicit temporary copy of the first
	// field, which is the only string field.  We must tolerate the
	// inefficiency of this copy, because Row::operator[] returns a
	// ColData object, which goes away after it is converted to some
	// other form.  So, while we could have made print_stock_row()
	// take a const char* argument (as past versions mistakenly did!)
	// this would result in a dangling pointer, since it points into the
	// ColData object, which is dead by the time the pointer is
	// evaluated in print_stock_row().  It will probably even work this
	// way, but like any memory bug, it can wreak subtle havoc.
	std::string item(row.at(0));
	print_stock_row(item, row["num"], row[2], row[3], row[4]);
}

//// print_stock_rows //////////////////////////////////////////////////
// Print out a number of rows from the example 'stock' table.

void
print_stock_rows(mysqlpp::Result& res)
{
	print_stock_header(res.size());

	// Use the Result class's read-only random access iterator to walk
	// through the query results.
	mysqlpp::Result::iterator i;
	for (i = res.begin(); i != res.end(); ++i) {
		// Notice that a dereferenced result iterator can be converted
		// to a Row object, which makes for easier element access.
		print_stock_row(*i);
	}
}

//// get_stock_table ///////////////////////////////////////////////////
// Retreive the entire contents of the example 'stock' table.

void
get_stock_table(mysqlpp::Query& query, mysqlpp::Result& res)
{
	// Reset the query object, in case we're re-using it.
	query.reset();

	// You can write to the query object like you would any ostream.
	query << "select * from stock";

	// Show the query string.  If you call preview(), it must be before
	// you call execute() or store() or use().
	cout << "Query: " << query.preview() << endl;

	// Execute the query, storing the results in memory.
	res = query.store();
}

//// print_stock_table /////////////////////////////////////////////////
// Simply retrieve and print the entire contents of the stock table.

void
print_stock_table(mysqlpp::Query& query)
{
	mysqlpp::Result res;
	get_stock_table(query, res);
	print_stock_rows(res);
}

//// connect_to_db /////////////////////////////////////////////////////
// Establishes a connection to a MySQL database server, optionally
// attaching to database kdb.  This is basically a command-line parser
// for the examples, since the example programs' arguments give us the
// information we need to establish the server connection.

bool
connect_to_db(int argc, char *argv[], mysqlpp::Connection& con,
		const char *kdb)
{
	if (argc < 1) {
		cerr << "Bad argument count: " << argc << '!' << endl;
		return false;
	}

	if (!kdb) {
		kdb = kpcSampleDatabase;
	}

	if ((argc > 1) && (argv[1][0] == '-')) {
		cout << "usage: " << argv[0] <<
				" [host] [user] [password] [port]" << endl;
		cout << endl << "\tConnects to database ";
		if (strlen(kdb) > 0) {
			cout << '"' << kdb << '"';
		}
		else {
			cout << "server";
		}
		cout << " on localhost using your user" << endl;
		cout << "\tname and no password by default." << endl << endl;
		return false;
	}

	if (argc == 1) {
		con.connect(kdb);
	}
	else if (argc == 2) {
		con.connect(kdb, argv[1]);
	}
	else if (argc == 3) {
		con.connect(kdb, argv[1], argv[2]);
	}
	else if (argc == 4) {
		con.connect(kdb, argv[1], argv[2], argv[3]);
	}
	else if (argc >= 5) {
		con.connect(kdb, argv[1], argv[2], argv[3], atoi(argv[4]));
	}

	if (con) {
		return true;
	}
	else {
		cerr << "Database connection failed: " << con.error() << endl;
		return false;
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbImageMetadata.h"
#include <iostream>
#include "boost/optional.hpp"
#include <bitset>
#include <utility>
#include <cstdlib>
#include "otbStopwatch.h"

int otbImageMetadataTest(int, char*[])
{
  using namespace otb;

  MetaData::Time mytime;
  int year, month;
  char buffer[] = "2009-12-10T10:30:18.142149Z";
  int count = std::sscanf(buffer, "%4d-%2d-%2dT%2d:%2d:%2d%lfZ",
    &year,
    &month,
    &mytime.tm_mday,
    &mytime.tm_hour,
    &mytime.tm_min,
    &mytime.tm_sec,
    &mytime.frac_sec);

  std::cout << "sscanf result: "<< count << "\n";
  std::cout << "Time = "<< year << " "<< month << " " << mytime.tm_mday << " " << mytime.tm_hour << " " << mytime.tm_min << " " << mytime.tm_sec << " " << mytime.frac_sec << "\n";
  return 0;

  MDNum someKey;
  someKey = static_cast<MDNum>(3);
  if (someKey == MDNum::PhysicalGain)
    {
    std::cout << "Found physical gain\n";
    }

  struct FirstTry
    {
    std::array< boost::optional<double>, static_cast<int>(MDNum::END) > NumKeys;
    };

  struct SecondTry
    {
      std::bitset< static_cast<int>(MDNum::END) > NumFlag;
      std::array<double, static_cast<int>(MDNum::END) > NumKeys;
    };

  class ThirdTry
    {
    public:
    std::pair<
      std::bitset< static_cast<int>(MDNum::END) >,
      std::array<double, static_cast<int>(MDNum::END) > >NumKeys;
    };

  std::cout << "First try size: "<<sizeof(FirstTry)<< "\n";
  std::cout << "Second try size: "<<sizeof(SecondTry)<< "\n";
  std::cout << "Third try size: "<<sizeof(ThirdTry)<< "\n";

  FirstTry firstStruct;
  SecondTry secondStruct;
  ThirdTry thirdStruct;

  int total = static_cast<int>(MDNum::END);
  int loops = 10000000;
  Stopwatch chrono;
  double val= 0.0;
  chrono.Start();
  for (int i=0 ; i< loops ; ++i)
    {
    int pos = rand() % total;
    if (firstStruct.NumKeys[pos] == boost::none)
      {
      firstStruct.NumKeys[pos] = val+1.0;
      }
    else
      {
      firstStruct.NumKeys[pos] = firstStruct.NumKeys[pos].get() + val;
      }
    }
  chrono.Stop();
  std::cout << "First try chrono : "<< chrono.GetElapsedMilliseconds() << "\n";

  val= 0.0;
  chrono.Restart();
  for (int i=0 ; i< loops ; ++i)
    {
    int pos = rand() % total;
    if (secondStruct.NumFlag[pos] == false)
      {
      secondStruct.NumKeys[pos] = val+1.0;
      secondStruct.NumFlag[pos] = true;
      }
    else
      {
      secondStruct.NumKeys[pos] = secondStruct.NumKeys[pos] + val;
      }
    }
  chrono.Stop();
  std::cout << "Second try chrono : "<< chrono.GetElapsedMilliseconds() << "\n";

  val= 0.0;
  chrono.Restart();
  for (int i=0 ; i< loops ; ++i)
    {
    int pos = rand() % total;
    if (thirdStruct.NumKeys.first[pos] == false)
      {
      thirdStruct.NumKeys.second[pos] = val+1.0;
      thirdStruct.NumKeys.first[pos] = true;
      }
    else
      {
      thirdStruct.NumKeys.second[pos] = thirdStruct.NumKeys.second[pos] + val;
      }
    }
  chrono.Stop();
  std::cout << "Third try chrono : "<< chrono.GetElapsedMilliseconds() << "\n";

  ImageMetadata md;
  md.Add(MDStr::SensorID, "PHR");
  md.Add(MDGeom::ProjectionWKT, std::string("UTM projRef"));

  ImageMetadataBase bmd;
  bmd.Add(MDStr::BandName, "B3");
  bmd.Add(MDNum::PhysicalGain , 2.0);
  bmd.Add(MDNum::PhysicalBias,  1.0);
  md.Bands.push_back(bmd);

  bmd.Add(MDStr::BandName, "B2");
  bmd.Add(MDNum::PhysicalGain , 3.0);
  bmd.Add(MDNum::PhysicalBias,  2.0);
  md.Bands.push_back(bmd);

  bmd.Add(MDStr::BandName, "B1");
  bmd.Add(MDNum::NoData, -10000.0);
  bmd.Add(MDNum::PhysicalGain , 4.0);
  bmd.Add(MDNum::PhysicalBias,  3.0);
  md.Bands.push_back(bmd);

  ImageMetadata md2;

  md2 = md;

  md.Add(MDGeom::ProjectionWKT, std::string("Lambert projRef"));
  //~ md.GeoTransform[5] = 1.0;

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

  return 0;
}
<commit_msg>TEST: test code for time parsing<commit_after>/*
 * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbImageMetadata.h"
#include <iostream>
#include "boost/optional.hpp"
#include <bitset>
#include <utility>
#include <cstdlib>
#include "otbStopwatch.h"

int otbImageMetadataTest(int, char*[])
{
  using namespace otb;

  MetaData::Time mytime;
  int year, month;
  char buffer[] = "2009-08-10T10:30:08.142149Z";

  std::string bufferStr("2009-08-10T10:30:08.142149Z");

  try
    {
    mytime = boost::lexical_cast<MetaData::Time>(buffer);
    }
  catch(boost::bad_lexical_cast&)
    {
    std::cout << "Bad cast into MetaData::Time\n";
    }
  std::cout << "mytime : "<< mytime << "\n";

  try
    {
    mytime = Utils::LexicalCast<MetaData::Time,char*>(buffer, std::string("T"));
    mytime = Utils::LexicalCast<MetaData::Time,std::string>(bufferStr, std::string("T"));
    }
  catch(std::runtime_error&)
    {
    std::cout << "Bad Utils::LexicalCast into MetaData::Time\n";
    }

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

  MDNum someKey;
  someKey = static_cast<MDNum>(3);
  if (someKey == MDNum::PhysicalGain)
    {
    std::cout << "Found physical gain\n";
    }

  struct FirstTry
    {
    std::array< boost::optional<double>, static_cast<int>(MDNum::END) > NumKeys;
    };

  struct SecondTry
    {
      std::bitset< static_cast<int>(MDNum::END) > NumFlag;
      std::array<double, static_cast<int>(MDNum::END) > NumKeys;
    };

  class ThirdTry
    {
    public:
    std::pair<
      std::bitset< static_cast<int>(MDNum::END) >,
      std::array<double, static_cast<int>(MDNum::END) > >NumKeys;
    };

  std::cout << "First try size: "<<sizeof(FirstTry)<< "\n";
  std::cout << "Second try size: "<<sizeof(SecondTry)<< "\n";
  std::cout << "Third try size: "<<sizeof(ThirdTry)<< "\n";

  FirstTry firstStruct;
  SecondTry secondStruct;
  ThirdTry thirdStruct;

  int total = static_cast<int>(MDNum::END);
  int loops = 10000000;
  Stopwatch chrono;
  double val= 0.0;
  chrono.Start();
  for (int i=0 ; i< loops ; ++i)
    {
    int pos = rand() % total;
    if (firstStruct.NumKeys[pos] == boost::none)
      {
      firstStruct.NumKeys[pos] = val+1.0;
      }
    else
      {
      firstStruct.NumKeys[pos] = firstStruct.NumKeys[pos].get() + val;
      }
    }
  chrono.Stop();
  std::cout << "First try chrono : "<< chrono.GetElapsedMilliseconds() << "\n";

  val= 0.0;
  chrono.Restart();
  for (int i=0 ; i< loops ; ++i)
    {
    int pos = rand() % total;
    if (secondStruct.NumFlag[pos] == false)
      {
      secondStruct.NumKeys[pos] = val+1.0;
      secondStruct.NumFlag[pos] = true;
      }
    else
      {
      secondStruct.NumKeys[pos] = secondStruct.NumKeys[pos] + val;
      }
    }
  chrono.Stop();
  std::cout << "Second try chrono : "<< chrono.GetElapsedMilliseconds() << "\n";

  val= 0.0;
  chrono.Restart();
  for (int i=0 ; i< loops ; ++i)
    {
    int pos = rand() % total;
    if (thirdStruct.NumKeys.first[pos] == false)
      {
      thirdStruct.NumKeys.second[pos] = val+1.0;
      thirdStruct.NumKeys.first[pos] = true;
      }
    else
      {
      thirdStruct.NumKeys.second[pos] = thirdStruct.NumKeys.second[pos] + val;
      }
    }
  chrono.Stop();
  std::cout << "Third try chrono : "<< chrono.GetElapsedMilliseconds() << "\n";

  ImageMetadata md;
  md.Add(MDStr::SensorID, "PHR");
  md.Add(MDGeom::ProjectionWKT, std::string("UTM projRef"));

  ImageMetadataBase bmd;
  bmd.Add(MDStr::BandName, "B3");
  bmd.Add(MDNum::PhysicalGain , 2.0);
  bmd.Add(MDNum::PhysicalBias,  1.0);
  md.Bands.push_back(bmd);

  bmd.Add(MDStr::BandName, "B2");
  bmd.Add(MDNum::PhysicalGain , 3.0);
  bmd.Add(MDNum::PhysicalBias,  2.0);
  md.Bands.push_back(bmd);

  bmd.Add(MDStr::BandName, "B1");
  bmd.Add(MDNum::NoData, -10000.0);
  bmd.Add(MDNum::PhysicalGain , 4.0);
  bmd.Add(MDNum::PhysicalBias,  3.0);
  md.Bands.push_back(bmd);

  ImageMetadata md2;

  md2 = md;

  md.Add(MDGeom::ProjectionWKT, std::string("Lambert projRef"));
  //~ md.GeoTransform[5] = 1.0;

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

  return 0;
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2009-07-08 11:04:08 +0200 (Mi, 08 Jul 2009) $
Version:   $Revision: 18029 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkPlanarFigure.h"
#include "mitkGeometry2D.h"

mitk::PlanarFigure::PlanarFigure()
: m_FigurePlaced( false ),
  m_SelectedControlPoint( -1 ),
  m_Geometry2D( NULL ),
  m_FeaturesMTime( 0 )
{
  m_ControlPoints = VertexContainerType::New();
  m_PolyLines = VertexContainerVectorType::New();
  m_HelperPolyLines = VertexContainerVectorType::New();
  m_HelperPolyLinesToBePainted = BoolContainerType::New();

  // Currently only single-time-step geometries are supported
  this->InitializeTimeSlicedGeometry( 1 );
}

mitk::PlanarFigure::~PlanarFigure()
{
}

void mitk::PlanarFigure::SetGeometry2D( mitk::Geometry2D *geometry )
{
  this->SetGeometry( geometry );
  m_Geometry2D = geometry;
}

const mitk::Geometry2D *mitk::PlanarFigure::GetGeometry2D() const
{
  return m_Geometry2D;
}

void mitk::PlanarFigure::PlaceFigure( const mitk::Point2D& point )
{
  for ( unsigned int i = 0; i < this->GetNumberOfControlPoints(); ++i )
  {
    m_ControlPoints->InsertElement( i, this->ApplyControlPointConstraints( i, point ) );
  }

  m_FigurePlaced = true;
  m_SelectedControlPoint = 1;
}

bool mitk::PlanarFigure::AddControlPoint( const mitk::Point2D& point )
{
  if ( m_NumberOfControlPoints < this->GetMaximumNumberOfControlPoints() )
  {
    m_ControlPoints->InsertElement( m_NumberOfControlPoints,
      this->ApplyControlPointConstraints( m_NumberOfControlPoints, point ) );
    ++m_NumberOfControlPoints;
    ++m_SelectedControlPoint;
    return true;
  }
  else
  {
    return false;
  }
}

bool mitk::PlanarFigure::SetControlPoint( unsigned int index, const Point2D& point, bool createIfDoesNotExist )
{
  if (createIfDoesNotExist)
  {
    m_ControlPoints->InsertElement( index, this->ApplyControlPointConstraints( index, point ) );
    return true;
  }
  else if ( index < m_ControlPoints->Size() )
  {
    m_ControlPoints->InsertElement( index, this->ApplyControlPointConstraints( index, point ) );
    return true;
  }
  else
  {
    return false;
  }
}

bool mitk::PlanarFigure::SetCurrentControlPoint( const Point2D& point )
{
  if ( (m_SelectedControlPoint < 0) || (m_SelectedControlPoint >= (int)m_NumberOfControlPoints) )
  {
    return false;
  }

  return this->SetControlPoint(m_SelectedControlPoint, point, false);
}

unsigned int mitk::PlanarFigure::GetNumberOfControlPoints() const
{
  return m_NumberOfControlPoints;
}

bool mitk::PlanarFigure::SelectControlPoint( unsigned int index )
{
  if ( index < this->GetNumberOfControlPoints() )
  {
    m_SelectedControlPoint = index;
    return true;
  }
  else
  {
    return false;
  }
}

void mitk::PlanarFigure::DeselectControlPoint()
{
  m_SelectedControlPoint = -1;
}

const mitk::PlanarFigure::VertexContainerType *
mitk::PlanarFigure::GetControlPoints() const
{
  return m_ControlPoints;
}

mitk::PlanarFigure::VertexContainerType *
mitk::PlanarFigure::GetControlPoints()
{
  return m_ControlPoints;
}

mitk::Point2D& mitk::PlanarFigure::GetControlPoint( unsigned int index ) const
{
  if ( index < m_NumberOfControlPoints )
  {
    return m_ControlPoints->ElementAt( index );
  }

  itkExceptionMacro( << "GetControlPoint(): Invalid index!" );
}

mitk::Point3D mitk::PlanarFigure::GetWorldControlPoint( unsigned int index ) const
{
  Point3D point3D;
  if ( (m_Geometry2D != NULL) && (index < m_NumberOfControlPoints) )
  {
    m_Geometry2D->Map( m_ControlPoints->ElementAt( index ), point3D );
    return point3D;
  }

  itkExceptionMacro( << "GetWorldControlPoint(): Invalid index!" );
}

mitk::PlanarFigure::VertexContainerType *
mitk::PlanarFigure::GetPolyLine(unsigned int index)
{
  if ((m_PolyLines->ElementAt( index )) && (m_PolyLines->ElementAt( index )->GetMTime() < m_ControlPoints->GetMTime()) )
  {
    this->GeneratePolyLine();
  }

  return m_PolyLines->ElementAt( index );
}

const mitk::PlanarFigure::VertexContainerType *
mitk::PlanarFigure::GetPolyLine(unsigned int index) const
{
  return m_PolyLines->ElementAt( index );
}

const mitk::PlanarFigure::VertexContainerType *
mitk::PlanarFigure::GetHelperPolyLine(unsigned int index, double mmPerDisplayUnit, unsigned int displayHeight)
{
  if ((m_HelperPolyLines->ElementAt( index )) && (m_HelperPolyLines->ElementAt( index )->GetMTime() < m_ControlPoints->GetMTime()) )
  {
    this->GenerateHelperPolyLine(mmPerDisplayUnit, displayHeight);
  }

  return m_HelperPolyLines->ElementAt( index );
}

/** \brief Returns the number of features available for this PlanarFigure
* (such as, radius, area, ...). */
unsigned int mitk::PlanarFigure::GetNumberOfFeatures() const
{
  return m_Features.size();
}

const char *mitk::PlanarFigure::GetFeatureName( unsigned int index ) const
{
  if ( index < m_Features.size() )
  {
    return m_Features[index].Name.c_str();
  }
  else
  {
    return NULL;
  }
}

const char *mitk::PlanarFigure::GetFeatureUnit( unsigned int index ) const
{
  if ( index < m_Features.size() )
  {
    return m_Features[index].Unit.c_str();
  }
  else
  {
    return NULL;
  }
}

double mitk::PlanarFigure::GetQuantity( unsigned int index ) const
{
  if ( index < m_Features.size() )
  {
    return m_Features[index].Quantity;
  }
  else
  {
    return 0.0;
  }
}

bool mitk::PlanarFigure::IsFeatureActive( unsigned int index ) const
{
  if ( index < m_Features.size() )
  {
    return m_Features[index].Active;
  }
  else
  {
    return false;
  }
}

void mitk::PlanarFigure::EvaluateFeatures()
{
  if ( m_FeaturesMTime < m_ControlPoints->GetMTime() )
  {
    this->EvaluateFeaturesInternal();

    m_FeaturesMTime = m_ControlPoints->GetMTime();
  }
}

void mitk::PlanarFigure::UpdateOutputInformation()
{
  // Bounds are NOT calculated here, since the Geometry2D defines a fixed
  // frame (= bounds) for the planar figure.
  Superclass::UpdateOutputInformation();
  this->GetTimeSlicedGeometry()->UpdateInformation();
}

void mitk::PlanarFigure::SetRequestedRegionToLargestPossibleRegion()
{
}

bool mitk::PlanarFigure::RequestedRegionIsOutsideOfTheBufferedRegion()
{
  return false;
}

bool mitk::PlanarFigure::VerifyRequestedRegion()
{
  return true;
}

void mitk::PlanarFigure::SetRequestedRegion( itk::DataObject * /*data*/ )
{

}

void mitk::PlanarFigure::ResetNumberOfControlPoints( int numberOfControlPoints )
{
  m_NumberOfControlPoints = numberOfControlPoints;
}

mitk::Point2D mitk::PlanarFigure::ApplyControlPointConstraints( unsigned int index, const Point2D& point )
{
  Point2D indexPoint;
  m_Geometry2D->WorldToIndex( point, indexPoint );

  BoundingBox::BoundsArrayType bounds = m_Geometry2D->GetBounds();
  if ( indexPoint[0] < bounds[0] ) { indexPoint[0] = bounds[0]; }
  if ( indexPoint[0] > bounds[1] ) { indexPoint[0] = bounds[1]; }
  if ( indexPoint[1] < bounds[2] ) { indexPoint[1] = bounds[2]; }
  if ( indexPoint[1] > bounds[3] ) { indexPoint[1] = bounds[3]; }

  Point2D constrainedPoint;
  m_Geometry2D->IndexToWorld( indexPoint, constrainedPoint );

  return constrainedPoint;
}

unsigned int mitk::PlanarFigure::AddFeature( const char *featureName, const char *unitName )
{
  unsigned int index = m_Features.size();

  Feature newFeature( featureName, unitName );
  m_Features.push_back( newFeature );

  return index;
}

void mitk::PlanarFigure::SetFeatureName( unsigned int index, const char *featureName )
{
  if ( index < m_Features.size() )
  {
    m_Features[index].Name = featureName;
  }
}

void mitk::PlanarFigure::SetFeatureUnit( unsigned int index, const char *unitName )
{
  if ( index < m_Features.size() )
  {
    m_Features[index].Unit = unitName;
  }
}

void mitk::PlanarFigure::SetQuantity( unsigned int index, double quantity )
{
  if ( index < m_Features.size() )
  {
    m_Features[index].Quantity = quantity;
  }
}

void mitk::PlanarFigure::ActivateFeature( unsigned int index )
{
  if ( index < m_Features.size() )
  {
    m_Features[index].Active = true;
  }
}

void mitk::PlanarFigure::DeactivateFeature( unsigned int index )
{
  if ( index < m_Features.size() )
  {
    m_Features[index].Active = false;
  }
}

void mitk::PlanarFigure::InitializeTimeSlicedGeometry( unsigned int timeSteps )
{
  mitk::TimeSlicedGeometry::Pointer timeGeometry = this->GetTimeSlicedGeometry();

  mitk::Geometry2D::Pointer geometry2D = mitk::Geometry2D::New();
  geometry2D->Initialize();

  if ( timeSteps > 1 )
  {
    mitk::ScalarType timeBounds[] = {0.0, 1.0};
    geometry2D->SetTimeBounds( timeBounds );
  }

  // The geometry is propagated automatically to all time steps,
  // if EvenlyTimed is true...
  timeGeometry->InitializeEvenlyTimed( geometry2D, timeSteps );
}

void mitk::PlanarFigure::PrintSelf( std::ostream& os, itk::Indent indent) const
{
  Superclass::PrintSelf( os, indent );
  os << indent << this->GetNameOfClass() << ":\n";

  if (this->IsClosed())
    os << indent << "This figure is closed\n";
  else
    os << indent << "This figure is not closed\n";
  os << indent << "Minimum number of control points: " << this->GetMinimumNumberOfControlPoints() << std::endl;
  os << indent << "Maximum number of control points: " << this->GetMaximumNumberOfControlPoints() << std::endl;
  os << indent << "Current number of control points: " << this->GetNumberOfControlPoints() << std::endl;
  os << indent << "Control points:" << std::endl;
  mitk::PlanarFigure::VertexContainerType::ConstIterator it;
  for ( unsigned int i = 0; i < this->GetNumberOfControlPoints(); ++i )
  {
    os << indent.GetNextIndent() << i << ": " << m_ControlPoints->ElementAt( i ) << std::endl;
  }
  os << indent << "Geometry:\n";
  this->GetGeometry2D()->Print(os, indent.GetNextIndent());
}

unsigned short mitk::PlanarFigure::GetPolyLinesSize()
{
  return m_PolyLines->size();
}

unsigned short mitk::PlanarFigure::GetHelperPolyLinesSize()
{
  return m_HelperPolyLines->size();
}

bool mitk::PlanarFigure::IsHelperToBePainted(unsigned int index)
{
  return m_HelperPolyLinesToBePainted->GetElement( index );
}

bool mitk::PlanarFigure::ResetOnPointSelect()
{
  return false;
}
<commit_msg>FIX (#3619): Adjust number of points in SetControlPoint()<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2009-07-08 11:04:08 +0200 (Mi, 08 Jul 2009) $
Version:   $Revision: 18029 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkPlanarFigure.h"
#include "mitkGeometry2D.h"

mitk::PlanarFigure::PlanarFigure()
: m_FigurePlaced( false ),
  m_SelectedControlPoint( -1 ),
  m_Geometry2D( NULL ),
  m_FeaturesMTime( 0 )
{
  m_ControlPoints = VertexContainerType::New();
  m_PolyLines = VertexContainerVectorType::New();
  m_HelperPolyLines = VertexContainerVectorType::New();
  m_HelperPolyLinesToBePainted = BoolContainerType::New();

  // Currently only single-time-step geometries are supported
  this->InitializeTimeSlicedGeometry( 1 );
}

mitk::PlanarFigure::~PlanarFigure()
{
}

void mitk::PlanarFigure::SetGeometry2D( mitk::Geometry2D *geometry )
{
  this->SetGeometry( geometry );
  m_Geometry2D = geometry;
}

const mitk::Geometry2D *mitk::PlanarFigure::GetGeometry2D() const
{
  return m_Geometry2D;
}

void mitk::PlanarFigure::PlaceFigure( const mitk::Point2D& point )
{
  for ( unsigned int i = 0; i < this->GetNumberOfControlPoints(); ++i )
  {
    m_ControlPoints->InsertElement( i, this->ApplyControlPointConstraints( i, point ) );
  }

  m_FigurePlaced = true;
  m_SelectedControlPoint = 1;
}

bool mitk::PlanarFigure::AddControlPoint( const mitk::Point2D& point )
{
  if ( m_NumberOfControlPoints < this->GetMaximumNumberOfControlPoints() )
  {
    m_ControlPoints->InsertElement( m_NumberOfControlPoints,
      this->ApplyControlPointConstraints( m_NumberOfControlPoints, point ) );
    ++m_NumberOfControlPoints;
    ++m_SelectedControlPoint;
    return true;
  }
  else
  {
    return false;
  }
}

bool mitk::PlanarFigure::SetControlPoint( unsigned int index, const Point2D& point, bool createIfDoesNotExist )
{
  if (createIfDoesNotExist)
  {
    m_ControlPoints->InsertElement( index, this->ApplyControlPointConstraints( index, point ) );
    if ( m_NumberOfControlPoints <= index )
    {
      m_NumberOfControlPoints = index + 1;
    }
    return true;
  }
  else if ( index < m_NumberOfControlPoints )
  {
    m_ControlPoints->InsertElement( index, this->ApplyControlPointConstraints( index, point ) );
    return true;
  }
  else
  {
    return false;
  }
}

bool mitk::PlanarFigure::SetCurrentControlPoint( const Point2D& point )
{
  if ( (m_SelectedControlPoint < 0) || (m_SelectedControlPoint >= (int)m_NumberOfControlPoints) )
  {
    return false;
  }

  return this->SetControlPoint(m_SelectedControlPoint, point, false);
}

unsigned int mitk::PlanarFigure::GetNumberOfControlPoints() const
{
  return m_NumberOfControlPoints;
}

bool mitk::PlanarFigure::SelectControlPoint( unsigned int index )
{
  if ( index < this->GetNumberOfControlPoints() )
  {
    m_SelectedControlPoint = index;
    return true;
  }
  else
  {
    return false;
  }
}

void mitk::PlanarFigure::DeselectControlPoint()
{
  m_SelectedControlPoint = -1;
}

const mitk::PlanarFigure::VertexContainerType *
mitk::PlanarFigure::GetControlPoints() const
{
  return m_ControlPoints;
}

mitk::PlanarFigure::VertexContainerType *
mitk::PlanarFigure::GetControlPoints()
{
  return m_ControlPoints;
}

mitk::Point2D& mitk::PlanarFigure::GetControlPoint( unsigned int index ) const
{
  if ( index < m_NumberOfControlPoints )
  {
    return m_ControlPoints->ElementAt( index );
  }

  itkExceptionMacro( << "GetControlPoint(): Invalid index!" );
}

mitk::Point3D mitk::PlanarFigure::GetWorldControlPoint( unsigned int index ) const
{
  Point3D point3D;
  if ( (m_Geometry2D != NULL) && (index < m_NumberOfControlPoints) )
  {
    m_Geometry2D->Map( m_ControlPoints->ElementAt( index ), point3D );
    return point3D;
  }

  itkExceptionMacro( << "GetWorldControlPoint(): Invalid index!" );
}

mitk::PlanarFigure::VertexContainerType *
mitk::PlanarFigure::GetPolyLine(unsigned int index)
{
  if ((m_PolyLines->ElementAt( index )) && (m_PolyLines->ElementAt( index )->GetMTime() < m_ControlPoints->GetMTime()) )
  {
    this->GeneratePolyLine();
  }

  return m_PolyLines->ElementAt( index );
}

const mitk::PlanarFigure::VertexContainerType *
mitk::PlanarFigure::GetPolyLine(unsigned int index) const
{
  return m_PolyLines->ElementAt( index );
}

const mitk::PlanarFigure::VertexContainerType *
mitk::PlanarFigure::GetHelperPolyLine(unsigned int index, double mmPerDisplayUnit, unsigned int displayHeight)
{
  if ((m_HelperPolyLines->ElementAt( index )) && (m_HelperPolyLines->ElementAt( index )->GetMTime() < m_ControlPoints->GetMTime()) )
  {
    this->GenerateHelperPolyLine(mmPerDisplayUnit, displayHeight);
  }

  return m_HelperPolyLines->ElementAt( index );
}

/** \brief Returns the number of features available for this PlanarFigure
* (such as, radius, area, ...). */
unsigned int mitk::PlanarFigure::GetNumberOfFeatures() const
{
  return m_Features.size();
}

const char *mitk::PlanarFigure::GetFeatureName( unsigned int index ) const
{
  if ( index < m_Features.size() )
  {
    return m_Features[index].Name.c_str();
  }
  else
  {
    return NULL;
  }
}

const char *mitk::PlanarFigure::GetFeatureUnit( unsigned int index ) const
{
  if ( index < m_Features.size() )
  {
    return m_Features[index].Unit.c_str();
  }
  else
  {
    return NULL;
  }
}

double mitk::PlanarFigure::GetQuantity( unsigned int index ) const
{
  if ( index < m_Features.size() )
  {
    return m_Features[index].Quantity;
  }
  else
  {
    return 0.0;
  }
}

bool mitk::PlanarFigure::IsFeatureActive( unsigned int index ) const
{
  if ( index < m_Features.size() )
  {
    return m_Features[index].Active;
  }
  else
  {
    return false;
  }
}

void mitk::PlanarFigure::EvaluateFeatures()
{
  if ( m_FeaturesMTime < m_ControlPoints->GetMTime() )
  {
    this->EvaluateFeaturesInternal();

    m_FeaturesMTime = m_ControlPoints->GetMTime();
  }
}

void mitk::PlanarFigure::UpdateOutputInformation()
{
  // Bounds are NOT calculated here, since the Geometry2D defines a fixed
  // frame (= bounds) for the planar figure.
  Superclass::UpdateOutputInformation();
  this->GetTimeSlicedGeometry()->UpdateInformation();
}

void mitk::PlanarFigure::SetRequestedRegionToLargestPossibleRegion()
{
}

bool mitk::PlanarFigure::RequestedRegionIsOutsideOfTheBufferedRegion()
{
  return false;
}

bool mitk::PlanarFigure::VerifyRequestedRegion()
{
  return true;
}

void mitk::PlanarFigure::SetRequestedRegion( itk::DataObject * /*data*/ )
{

}

void mitk::PlanarFigure::ResetNumberOfControlPoints( int numberOfControlPoints )
{
  m_NumberOfControlPoints = numberOfControlPoints;
}

mitk::Point2D mitk::PlanarFigure::ApplyControlPointConstraints( unsigned int index, const Point2D& point )
{
  if ( m_Geometry2D ==  NULL )
  {
    return point;
  }

  Point2D indexPoint;
  m_Geometry2D->WorldToIndex( point, indexPoint );

  BoundingBox::BoundsArrayType bounds = m_Geometry2D->GetBounds();
  if ( indexPoint[0] < bounds[0] ) { indexPoint[0] = bounds[0]; }
  if ( indexPoint[0] > bounds[1] ) { indexPoint[0] = bounds[1]; }
  if ( indexPoint[1] < bounds[2] ) { indexPoint[1] = bounds[2]; }
  if ( indexPoint[1] > bounds[3] ) { indexPoint[1] = bounds[3]; }

  Point2D constrainedPoint;
  m_Geometry2D->IndexToWorld( indexPoint, constrainedPoint );

  return constrainedPoint;
}

unsigned int mitk::PlanarFigure::AddFeature( const char *featureName, const char *unitName )
{
  unsigned int index = m_Features.size();

  Feature newFeature( featureName, unitName );
  m_Features.push_back( newFeature );

  return index;
}

void mitk::PlanarFigure::SetFeatureName( unsigned int index, const char *featureName )
{
  if ( index < m_Features.size() )
  {
    m_Features[index].Name = featureName;
  }
}

void mitk::PlanarFigure::SetFeatureUnit( unsigned int index, const char *unitName )
{
  if ( index < m_Features.size() )
  {
    m_Features[index].Unit = unitName;
  }
}

void mitk::PlanarFigure::SetQuantity( unsigned int index, double quantity )
{
  if ( index < m_Features.size() )
  {
    m_Features[index].Quantity = quantity;
  }
}

void mitk::PlanarFigure::ActivateFeature( unsigned int index )
{
  if ( index < m_Features.size() )
  {
    m_Features[index].Active = true;
  }
}

void mitk::PlanarFigure::DeactivateFeature( unsigned int index )
{
  if ( index < m_Features.size() )
  {
    m_Features[index].Active = false;
  }
}

void mitk::PlanarFigure::InitializeTimeSlicedGeometry( unsigned int timeSteps )
{
  mitk::TimeSlicedGeometry::Pointer timeGeometry = this->GetTimeSlicedGeometry();

  mitk::Geometry2D::Pointer geometry2D = mitk::Geometry2D::New();
  geometry2D->Initialize();

  if ( timeSteps > 1 )
  {
    mitk::ScalarType timeBounds[] = {0.0, 1.0};
    geometry2D->SetTimeBounds( timeBounds );
  }

  // The geometry is propagated automatically to all time steps,
  // if EvenlyTimed is true...
  timeGeometry->InitializeEvenlyTimed( geometry2D, timeSteps );
}

void mitk::PlanarFigure::PrintSelf( std::ostream& os, itk::Indent indent) const
{
  Superclass::PrintSelf( os, indent );
  os << indent << this->GetNameOfClass() << ":\n";

  if (this->IsClosed())
    os << indent << "This figure is closed\n";
  else
    os << indent << "This figure is not closed\n";
  os << indent << "Minimum number of control points: " << this->GetMinimumNumberOfControlPoints() << std::endl;
  os << indent << "Maximum number of control points: " << this->GetMaximumNumberOfControlPoints() << std::endl;
  os << indent << "Current number of control points: " << this->GetNumberOfControlPoints() << std::endl;
  os << indent << "Control points:" << std::endl;
  mitk::PlanarFigure::VertexContainerType::ConstIterator it;
  for ( unsigned int i = 0; i < this->GetNumberOfControlPoints(); ++i )
  {
    os << indent.GetNextIndent() << i << ": " << m_ControlPoints->ElementAt( i ) << std::endl;
  }
  os << indent << "Geometry:\n";
  this->GetGeometry2D()->Print(os, indent.GetNextIndent());
}

unsigned short mitk::PlanarFigure::GetPolyLinesSize()
{
  return m_PolyLines->size();
}

unsigned short mitk::PlanarFigure::GetHelperPolyLinesSize()
{
  return m_HelperPolyLines->size();
}

bool mitk::PlanarFigure::IsHelperToBePainted(unsigned int index)
{
  return m_HelperPolyLinesToBePainted->GetElement( index );
}

bool mitk::PlanarFigure::ResetOnPointSelect()
{
  return false;
}
<|endoftext|>


<commit_before>/*============================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

============================================================================*/

#include "QmitkOtsuTool3DGUI.h"
#include "mitkOtsuTool3D.h"

#include <QMessageBox>

MITK_TOOL_GUI_MACRO(MITKSEGMENTATIONUI_EXPORT, QmitkOtsuTool3DGUI, "")

QmitkOtsuTool3DGUI::QmitkOtsuTool3DGUI() : QmitkAutoMLSegmentationToolGUIBase()
{
}

void QmitkOtsuTool3DGUI::ConnectNewTool(mitk::AutoSegmentationWithPreviewTool* newTool)
{
  Superclass::ConnectNewTool(newTool);

  newTool->IsTimePointChangeAwareOff();
  m_FirstPreviewComputation = true;
}

void QmitkOtsuTool3DGUI::InitializeUI(QBoxLayout* mainLayout)
{
  m_Controls.setupUi(this);
  mainLayout->addLayout(m_Controls.verticalLayout);

  connect(m_Controls.previewButton, SIGNAL(clicked()), this, SLOT(OnPreviewBtnClicked()));
  connect(m_Controls.m_Spinbox, SIGNAL(valueChanged(int)), this, SLOT(OnRegionSpinboxChanged(int)));
  connect(m_Controls.advancedSettingsButton, SIGNAL(toggled(bool)), this, SLOT(OnAdvancedSettingsButtonToggled(bool)));

  this->OnAdvancedSettingsButtonToggled(false);

  Superclass::InitializeUI(mainLayout);
}

void QmitkOtsuTool3DGUI::OnRegionSpinboxChanged(int numberOfRegions)
{
  // we have to change to minimum number of histogram bins accordingly
  int curBinValue = m_Controls.m_BinsSpinBox->value();
  if (curBinValue < numberOfRegions)
    m_Controls.m_BinsSpinBox->setValue(numberOfRegions);
}

void QmitkOtsuTool3DGUI::OnAdvancedSettingsButtonToggled(bool toggled)
{
  m_Controls.m_ValleyCheckbox->setVisible(toggled);
  m_Controls.binLabel->setVisible(toggled);
  m_Controls.m_BinsSpinBox->setVisible(toggled);

  auto tool = this->GetConnectedToolAs<mitk::OtsuTool3D>();
  if (toggled && nullptr != tool)
  {
    int max = tool->GetMaxNumberOfBins();
    if (max >= m_Controls.m_BinsSpinBox->minimum())
    {
      m_Controls.m_BinsSpinBox->setMaximum(max);
    }
  }
}

void QmitkOtsuTool3DGUI::OnPreviewBtnClicked()
{
  auto tool = this->GetConnectedToolAs<mitk::OtsuTool3D>();
  if (nullptr != tool)
  {
    if (!m_FirstPreviewComputation ||
      (tool->GetNumberOfRegions() == static_cast<unsigned int>(m_Controls.m_Spinbox->value()) &&
      tool->GetUseValley() == m_Controls.m_ValleyCheckbox->isChecked() &&
      tool->GetNumberOfBins() == static_cast<unsigned int>(m_Controls.m_BinsSpinBox->value())))
      return;

    m_FirstPreviewComputation = false;

    try
    {
      int proceed;
      QMessageBox *messageBox = new QMessageBox(QMessageBox::Question,
                                                nullptr,
                                                "The otsu segmentation computation may take several minutes depending "
                                                "on the number of Regions you selected. Proceed anyway?",
                                                QMessageBox::Ok | QMessageBox::Cancel);
      if (m_Controls.m_Spinbox->value() >= 5)
      {
        proceed = messageBox->exec();
        if (proceed != QMessageBox::Ok)
          return;
      }

      tool->SetNumberOfRegions(static_cast<unsigned int>(m_Controls.m_Spinbox->value()));
      tool->SetUseValley(m_Controls.m_ValleyCheckbox->isChecked());
      tool->SetNumberOfBins(static_cast<unsigned int>(m_Controls.m_BinsSpinBox->value()));

      tool->UpdatePreview();
    }
    catch (...)
    {
      this->setCursor(Qt::ArrowCursor);
      QMessageBox *messageBox =
        new QMessageBox(QMessageBox::Critical,
                        nullptr,
                        "itkOtsuFilter error: image dimension must be in {2, 3} and no RGB images can be handled.");
      messageBox->exec();
      delete messageBox;
      return;
    }

    this->SetLabelSetPreview(tool->GetMLPreview());
    tool->IsTimePointChangeAwareOn();
  }
}

void QmitkOtsuTool3DGUI::EnableWidgets(bool enabled)
{
  Superclass::EnableWidgets(enabled);
  m_Controls.m_ValleyCheckbox->setEnabled(enabled);
  m_Controls.binLabel->setEnabled(enabled);
  m_Controls.m_BinsSpinBox->setEnabled(enabled);
  m_Controls.previewButton->setEnabled(enabled);
}
<commit_msg>Fixed T28243<commit_after>/*============================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

============================================================================*/

#include "QmitkOtsuTool3DGUI.h"
#include "mitkOtsuTool3D.h"

#include <QMessageBox>

MITK_TOOL_GUI_MACRO(MITKSEGMENTATIONUI_EXPORT, QmitkOtsuTool3DGUI, "")

QmitkOtsuTool3DGUI::QmitkOtsuTool3DGUI() : QmitkAutoMLSegmentationToolGUIBase()
{
}

void QmitkOtsuTool3DGUI::ConnectNewTool(mitk::AutoSegmentationWithPreviewTool* newTool)
{
  Superclass::ConnectNewTool(newTool);

  newTool->IsTimePointChangeAwareOff();
  m_FirstPreviewComputation = true;
}

void QmitkOtsuTool3DGUI::InitializeUI(QBoxLayout* mainLayout)
{
  m_Controls.setupUi(this);
  mainLayout->addLayout(m_Controls.verticalLayout);

  connect(m_Controls.previewButton, SIGNAL(clicked()), this, SLOT(OnPreviewBtnClicked()));
  connect(m_Controls.m_Spinbox, SIGNAL(valueChanged(int)), this, SLOT(OnRegionSpinboxChanged(int)));
  connect(m_Controls.advancedSettingsButton, SIGNAL(toggled(bool)), this, SLOT(OnAdvancedSettingsButtonToggled(bool)));

  this->OnAdvancedSettingsButtonToggled(false);

  Superclass::InitializeUI(mainLayout);
}

void QmitkOtsuTool3DGUI::OnRegionSpinboxChanged(int numberOfRegions)
{
  // we have to change to minimum number of histogram bins accordingly
  int curBinValue = m_Controls.m_BinsSpinBox->value();
  if (curBinValue < numberOfRegions)
    m_Controls.m_BinsSpinBox->setValue(numberOfRegions);
}

void QmitkOtsuTool3DGUI::OnAdvancedSettingsButtonToggled(bool toggled)
{
  m_Controls.m_ValleyCheckbox->setVisible(toggled);
  m_Controls.binLabel->setVisible(toggled);
  m_Controls.m_BinsSpinBox->setVisible(toggled);

  auto tool = this->GetConnectedToolAs<mitk::OtsuTool3D>();
  if (toggled && nullptr != tool)
  {
    int max = tool->GetMaxNumberOfBins();
    if (max >= m_Controls.m_BinsSpinBox->minimum())
    {
      m_Controls.m_BinsSpinBox->setMaximum(max);
    }
  }
}

void QmitkOtsuTool3DGUI::OnPreviewBtnClicked()
{
  auto tool = this->GetConnectedToolAs<mitk::OtsuTool3D>();
  if (nullptr != tool)
  {
    if (!m_FirstPreviewComputation &&
      (tool->GetNumberOfRegions() == static_cast<unsigned int>(m_Controls.m_Spinbox->value()) &&
      tool->GetUseValley() == m_Controls.m_ValleyCheckbox->isChecked() &&
      tool->GetNumberOfBins() == static_cast<unsigned int>(m_Controls.m_BinsSpinBox->value())))
      return;

    m_FirstPreviewComputation = false;

    try
    {
      int proceed;
      QMessageBox *messageBox = new QMessageBox(QMessageBox::Question,
                                                nullptr,
                                                "The otsu segmentation computation may take several minutes depending "
                                                "on the number of Regions you selected. Proceed anyway?",
                                                QMessageBox::Ok | QMessageBox::Cancel);
      if (m_Controls.m_Spinbox->value() >= 5)
      {
        proceed = messageBox->exec();
        if (proceed != QMessageBox::Ok)
          return;
      }

      tool->SetNumberOfRegions(static_cast<unsigned int>(m_Controls.m_Spinbox->value()));
      tool->SetUseValley(m_Controls.m_ValleyCheckbox->isChecked());
      tool->SetNumberOfBins(static_cast<unsigned int>(m_Controls.m_BinsSpinBox->value()));

      tool->UpdatePreview();
    }
    catch (...)
    {
      this->setCursor(Qt::ArrowCursor);
      QMessageBox *messageBox =
        new QMessageBox(QMessageBox::Critical,
                        nullptr,
                        "itkOtsuFilter error: image dimension must be in {2, 3} and no RGB images can be handled.");
      messageBox->exec();
      delete messageBox;
      return;
    }

    this->SetLabelSetPreview(tool->GetMLPreview());
    tool->IsTimePointChangeAwareOn();
  }
}

void QmitkOtsuTool3DGUI::EnableWidgets(bool enabled)
{
  Superclass::EnableWidgets(enabled);
  m_Controls.m_ValleyCheckbox->setEnabled(enabled);
  m_Controls.binLabel->setEnabled(enabled);
  m_Controls.m_BinsSpinBox->setEnabled(enabled);
  m_Controls.previewButton->setEnabled(enabled);
}
<|endoftext|>


<commit_before><commit_msg>Несколько функций для булов<commit_after><|endoftext|>