<commit_before>/***********************************************************************
    filename:   CEGUIDefaultResourceProvider.cpp
    created:    8/7/2004
    author:     James '_mental_' O'Sullivan
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
 *
 *   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 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.
 ***************************************************************************/
#include "CEGUIDefaultResourceProvider.h"
#include "CEGUIExceptions.h"

#if defined(__WIN32__) || defined(_WIN32)
#   include <io.h>
#   include <windows.h>
#   include <string>

//----------------------------------------------------------------------------//
std::wstring Utf8ToUtf16(const std::string& utf8text)
{
    const int textLen = MultiByteToWideChar(CP_UTF8, 0, utf8text.c_str(),
                                            utf8text.size() + 1, 0, 0);

    if (textLen == 0)
        throw CEGUI::InvalidRequestException(
            "Utf8ToUtf16 - MultiByteToWideChar failed");

    std::wstring wideStr(textLen, 0);
    MultiByteToWideChar(CP_UTF8, 0, utf8text.c_str(), utf8text.size() + 1,
                        &wideStr[0], wideStr.size());
    return wideStr;
}

//----------------------------------------------------------------------------//
CEGUI::String Utf16ToString(const wchar_t* const utf16text)
{
    const int len = WideCharToMultiByte(CP_UTF8, 0, utf16text, -1,
                                        0, 0, 0, 0);
    if (!len)
        throw CEGUI::InvalidRequestException(
            "Utf16ToUtf8 - WideCharToMultiByte failed");

    CEGUI::utf8* buff = new CEGUI::utf8[len + 1];
    WideCharToMultiByte(CP_UTF8, 0, utf16text, -1,
                        reinterpret_cast<char*>(buff), len, 0, 0);
    const CEGUI::String result(buff);
    delete[] buff;

    return result;
}

//----------------------------------------------------------------------------//
#else
#   include <sys/types.h>
#   include <sys/stat.h>
#   include <dirent.h>
#   include <fnmatch.h>
#endif

// Start of CEGUI namespace section
namespace CEGUI
{

//----------------------------------------------------------------------------//
void DefaultResourceProvider::loadRawDataContainer(const String& filename,
                                                   RawDataContainer& output,
                                                   const String& resourceGroup)
{
    if (filename.empty())
        throw InvalidRequestException("DefaultResourceProvider::load: "
            "Filename supplied for data loading must be valid");

    const String final_filename(getFinalFilename(filename, resourceGroup));

#if defined(__WIN32__) || defined(_WIN32)
    FILE* file = _wfopen(Utf8ToUtf16(final_filename.c_str()).c_str(), L"rb");
#else
    FILE* file = fopen(final_filename.c_str(), "rb");
#endif

    if (file == 0)
        throw InvalidRequestException("DefaultResourceProvider::load: " +
            final_filename + " does not exist");

    fseek(file, 0, SEEK_END);
    const long size = ftell(file);
    fseek(file, 0, SEEK_SET);

    unsigned char* const buffer = new unsigned char[size];

    const size_t size_read = fread(buffer, sizeof(char), size, file);
    fclose(file);

    if (size_read != size)
    {
        delete[] buffer;
        throw GenericException("DefaultResourceProvider::loadRawDataContainer: "
            "A problem occurred while reading file: " + final_filename);
    }

    output.setData(buffer);
    output.setSize(size);
}

//----------------------------------------------------------------------------//
void DefaultResourceProvider::unloadRawDataContainer(RawDataContainer& data)
{
    uint8* const ptr = data.getDataPtr();
    delete[] ptr;
    data.setData(0);
    data.setSize(0);
}

//----------------------------------------------------------------------------//
void DefaultResourceProvider::setResourceGroupDirectory(
                                                const String& resourceGroup,
                                                const String& directory)
{
    if (directory.length() == 0)
        return;

#if defined(_WIN32) || defined(__WIN32__)
    // while we rarely use the unportable '\', the user may have
    const String separators("\\/");
#else
    const String separators("/");
#endif

    if (String::npos == separators.find(directory[directory.length() - 1]))
        d_resourceGroups[resourceGroup] = directory + '/';
    else
        d_resourceGroups[resourceGroup] = directory;
}

//----------------------------------------------------------------------------//
const String& DefaultResourceProvider::getResourceGroupDirectory(
                                                const String& resourceGroup)
{
    return d_resourceGroups[resourceGroup];
}

//----------------------------------------------------------------------------//
void DefaultResourceProvider::clearResourceGroupDirectory(
                                                const String& resourceGroup)
{
    ResourceGroupMap::iterator iter = d_resourceGroups.find(resourceGroup);

    if (iter != d_resourceGroups.end())
        d_resourceGroups.erase(iter);
}

//----------------------------------------------------------------------------//
String DefaultResourceProvider::getFinalFilename(
                                            const String& filename,
                                            const String& resourceGroup) const
{
    String final_filename;

    // look up resource group directory
    ResourceGroupMap::const_iterator iter =
        d_resourceGroups.find(resourceGroup.empty() ?
            d_defaultResourceGroup :
            resourceGroup);

    // if there was an entry for this group, use it's directory as the
    // first part of the filename
    if (iter != d_resourceGroups.end())
        final_filename = (*iter).second;

    // append the filename part that we were passed
    final_filename += filename;

    // return result
    return final_filename;
}

//----------------------------------------------------------------------------//
size_t DefaultResourceProvider::getResourceGroupFileNames(
    std::vector<String>& out_vec,
    const String& file_pattern,
    const String& resource_group)
{
    // look-up resource group name
    ResourceGroupMap::const_iterator iter =
        d_resourceGroups.find(resource_group.empty() ? d_defaultResourceGroup :
                              resource_group);
    // get directory that's set for the resource group
    const String dir_name(
        iter != d_resourceGroups.end() ? (*iter).second : "./");

    size_t entries = 0;

// Win32 code.
#if defined(__WIN32__) || defined(_WIN32)
    intptr_t f;
    struct _wfinddata_t fd;

    if ((f = _wfindfirst(Utf8ToUtf16((dir_name + file_pattern).c_str()).c_str(), &fd)) != -1)
    {
        do
        {
            if ((fd.attrib & _A_SUBDIR))
                continue;

            out_vec.push_back(Utf16ToString(fd.name));
            ++entries;
        }
        while (_wfindnext(f, &fd) == 0);

        _findclose(f);
    }

// Everybody else
#else
    DIR* dirp;

    if ((dirp = opendir(dir_name.c_str())))
    {
        struct dirent* dp;

        while ((dp = readdir(dirp)))
        {
            const String filename(dir_name + dp->d_name);
            struct stat s;

            if ((stat(filename.c_str(), &s) == 0) &&
                    S_ISREG(s.st_mode) &&
                    (fnmatch(file_pattern.c_str(), dp->d_name, 0) == 0))
            {
                out_vec.push_back(dp->d_name);
                ++entries;
            }
        }

        closedir(dirp);
    }
#endif

    return entries;
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section

<commit_msg>fix build issues relating to missing header in CEGUIDefaultResourceProvider.cpp<commit_after>/***********************************************************************
    filename:   CEGUIDefaultResourceProvider.cpp
    created:    8/7/2004
    author:     James '_mental_' O'Sullivan
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
 *
 *   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 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.
 ***************************************************************************/
#include "CEGUIDefaultResourceProvider.h"
#include "CEGUIExceptions.h"

#include <stdio.h>

#if defined(__WIN32__) || defined(_WIN32)
#   include <io.h>
#   include <windows.h>
#   include <string>

//----------------------------------------------------------------------------//
std::wstring Utf8ToUtf16(const std::string& utf8text)
{
    const int textLen = MultiByteToWideChar(CP_UTF8, 0, utf8text.c_str(),
                                            utf8text.size() + 1, 0, 0);

    if (textLen == 0)
        throw CEGUI::InvalidRequestException(
            "Utf8ToUtf16 - MultiByteToWideChar failed");

    std::wstring wideStr(textLen, 0);
    MultiByteToWideChar(CP_UTF8, 0, utf8text.c_str(), utf8text.size() + 1,
                        &wideStr[0], wideStr.size());
    return wideStr;
}

//----------------------------------------------------------------------------//
CEGUI::String Utf16ToString(const wchar_t* const utf16text)
{
    const int len = WideCharToMultiByte(CP_UTF8, 0, utf16text, -1,
                                        0, 0, 0, 0);
    if (!len)
        throw CEGUI::InvalidRequestException(
            "Utf16ToUtf8 - WideCharToMultiByte failed");

    CEGUI::utf8* buff = new CEGUI::utf8[len + 1];
    WideCharToMultiByte(CP_UTF8, 0, utf16text, -1,
                        reinterpret_cast<char*>(buff), len, 0, 0);
    const CEGUI::String result(buff);
    delete[] buff;

    return result;
}

//----------------------------------------------------------------------------//
#else
#   include <sys/types.h>
#   include <sys/stat.h>
#   include <dirent.h>
#   include <fnmatch.h>
#endif

// Start of CEGUI namespace section
namespace CEGUI
{

//----------------------------------------------------------------------------//
void DefaultResourceProvider::loadRawDataContainer(const String& filename,
                                                   RawDataContainer& output,
                                                   const String& resourceGroup)
{
    if (filename.empty())
        throw InvalidRequestException("DefaultResourceProvider::load: "
            "Filename supplied for data loading must be valid");

    const String final_filename(getFinalFilename(filename, resourceGroup));

#if defined(__WIN32__) || defined(_WIN32)
    FILE* file = _wfopen(Utf8ToUtf16(final_filename.c_str()).c_str(), L"rb");
#else
    FILE* file = fopen(final_filename.c_str(), "rb");
#endif

    if (file == 0)
        throw InvalidRequestException("DefaultResourceProvider::load: " +
            final_filename + " does not exist");

    fseek(file, 0, SEEK_END);
    const long size = ftell(file);
    fseek(file, 0, SEEK_SET);

    unsigned char* const buffer = new unsigned char[size];

    const size_t size_read = fread(buffer, sizeof(char), size, file);
    fclose(file);

    if (size_read != size)
    {
        delete[] buffer;
        throw GenericException("DefaultResourceProvider::loadRawDataContainer: "
            "A problem occurred while reading file: " + final_filename);
    }

    output.setData(buffer);
    output.setSize(size);
}

//----------------------------------------------------------------------------//
void DefaultResourceProvider::unloadRawDataContainer(RawDataContainer& data)
{
    uint8* const ptr = data.getDataPtr();
    delete[] ptr;
    data.setData(0);
    data.setSize(0);
}

//----------------------------------------------------------------------------//
void DefaultResourceProvider::setResourceGroupDirectory(
                                                const String& resourceGroup,
                                                const String& directory)
{
    if (directory.length() == 0)
        return;

#if defined(_WIN32) || defined(__WIN32__)
    // while we rarely use the unportable '\', the user may have
    const String separators("\\/");
#else
    const String separators("/");
#endif

    if (String::npos == separators.find(directory[directory.length() - 1]))
        d_resourceGroups[resourceGroup] = directory + '/';
    else
        d_resourceGroups[resourceGroup] = directory;
}

//----------------------------------------------------------------------------//
const String& DefaultResourceProvider::getResourceGroupDirectory(
                                                const String& resourceGroup)
{
    return d_resourceGroups[resourceGroup];
}

//----------------------------------------------------------------------------//
void DefaultResourceProvider::clearResourceGroupDirectory(
                                                const String& resourceGroup)
{
    ResourceGroupMap::iterator iter = d_resourceGroups.find(resourceGroup);

    if (iter != d_resourceGroups.end())
        d_resourceGroups.erase(iter);
}

//----------------------------------------------------------------------------//
String DefaultResourceProvider::getFinalFilename(
                                            const String& filename,
                                            const String& resourceGroup) const
{
    String final_filename;

    // look up resource group directory
    ResourceGroupMap::const_iterator iter =
        d_resourceGroups.find(resourceGroup.empty() ?
            d_defaultResourceGroup :
            resourceGroup);

    // if there was an entry for this group, use it's directory as the
    // first part of the filename
    if (iter != d_resourceGroups.end())
        final_filename = (*iter).second;

    // append the filename part that we were passed
    final_filename += filename;

    // return result
    return final_filename;
}

//----------------------------------------------------------------------------//
size_t DefaultResourceProvider::getResourceGroupFileNames(
    std::vector<String>& out_vec,
    const String& file_pattern,
    const String& resource_group)
{
    // look-up resource group name
    ResourceGroupMap::const_iterator iter =
        d_resourceGroups.find(resource_group.empty() ? d_defaultResourceGroup :
                              resource_group);
    // get directory that's set for the resource group
    const String dir_name(
        iter != d_resourceGroups.end() ? (*iter).second : "./");

    size_t entries = 0;

// Win32 code.
#if defined(__WIN32__) || defined(_WIN32)
    intptr_t f;
    struct _wfinddata_t fd;

    if ((f = _wfindfirst(Utf8ToUtf16((dir_name + file_pattern).c_str()).c_str(), &fd)) != -1)
    {
        do
        {
            if ((fd.attrib & _A_SUBDIR))
                continue;

            out_vec.push_back(Utf16ToString(fd.name));
            ++entries;
        }
        while (_wfindnext(f, &fd) == 0);

        _findclose(f);
    }

// Everybody else
#else
    DIR* dirp;

    if ((dirp = opendir(dir_name.c_str())))
    {
        struct dirent* dp;

        while ((dp = readdir(dirp)))
        {
            const String filename(dir_name + dp->d_name);
            struct stat s;

            if ((stat(filename.c_str(), &s) == 0) &&
                    S_ISREG(s.st_mode) &&
                    (fnmatch(file_pattern.c_str(), dp->d_name, 0) == 0))
            {
                out_vec.push_back(dp->d_name);
                ++entries;
            }
        }

        closedir(dirp);
    }
#endif

    return entries;
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section

<|endoftext|>


<commit_before>#include "find_redundant_motif.hpp"

bool is_included(const string &motif1, const string &motif2, unsigned int l) {
    for (unsigned int pos=0; pos < l; pos++) {
        auto const &successors = iupac_to_successors[motif1[pos]];
        if (find(successors.begin(), successors.end(), motif2[pos]) == successors.end())
            return false;
    }
    return true;
}

bool motifs_match(const string &motif1, const string &motif2, unsigned int l) {
    unordered_set<string> matching_motif1;
    unordered_set<string> matching_motif2;

    if(motif1 == motif2)
        return true;
    else
        return is_included(motif1, motif2, l) || is_included(motif2, motif1, l);
}

void filter_redundant_motif(vector<pair<const string, pair<int, Node *> > *> &remaining_hash_map_entries, unsigned int l) {

    unsigned int side_addition_limit = ceil(l / 2.0);
    //resetting node state
    for (auto const &entry : remaining_hash_map_entries)
        entry->second.second->reset_state();

    //finding nodes that were not processed yet
    auto entry_it = remaining_hash_map_entries.begin();
    while (entry_it != remaining_hash_map_entries.end()) {

        (*entry_it)->second.second->validate();
        string base = (*entry_it)->first;
        unsigned int letter_added_left = 0;
        unsigned int letter_added_right= 0;

        //getting into the loop
        bool found_motif = true;

        //while we still have motifs that overlap with the base
        while (found_motif) {
            found_motif = false;
            //for each entry
            for (auto &entry : remaining_hash_map_entries) {
                //that isn't tagged
                if(entry->second.second->get_state() != unvisited)
                    continue;

                //compute reverse_complement
                vector<string> motif_and_rc = {entry->first, reverse_complement(entry->first)};

                for (auto const &motif : motif_and_rc) {
                    /* motif      |------|-|
                       base [...]-|------| */
                    if (letter_added_right < side_addition_limit &&
                        motifs_match(string(base, base.size() - (l-1), l-1), string(motif, 0, l-1), l-1)) {
                        base.push_back(motif[l-1]);
                        found_motif = true;
                        letter_added_right++;
                    }
                    /* motif |-|-----|
                       base    |-----|-[...] */
                    else if (letter_added_left < side_addition_limit &&
                             motifs_match(string(base, 0, l-1), string(motif, 1, l-1), l-1)) {
                        base.insert(0, 1, motif[0]);
                        found_motif = true;
                        letter_added_left++;
                    }
                    else {
                        unsigned int pos = 0;
                        while ((pos + l) < base.size()) {
                            if(motifs_match(string(base, pos, l), motif, l)) {
                                found_motif = true;
                            }
                            pos++;
                        }
                    }
                    if(found_motif) {
                        std::cout << (*entry_it)->first << " " << motif << "\tbase: " << base << std::endl;
                        entry->second.second->suppress();
                        break;
                    }
                }
                if (found_motif)
                    break;
            }
        }
        entry_it = find_if(remaining_hash_map_entries.begin(),
                           remaining_hash_map_entries.end(),
                           [](const pair<const string, pair<int, Node *> > *entry) -> bool
                            { return entry->second.second->get_state() == unvisited; });
    }
    remaining_hash_map_entries.erase(
        remove_if(remaining_hash_map_entries.begin(),
                  remaining_hash_map_entries.end(),
                  [](auto &entry)
                    {return entry->second.second->get_state() != validated;}),
        remaining_hash_map_entries.end());
}
<commit_msg>[REFACTOR] Supressed redundant motif log for now (to be added when a verbose mode will be implemented)<commit_after>#include "find_redundant_motif.hpp"

bool is_included(const string &motif1, const string &motif2, unsigned int l) {
    for (unsigned int pos=0; pos < l; pos++) {
        auto const &successors = iupac_to_successors[motif1[pos]];
        if (find(successors.begin(), successors.end(), motif2[pos]) == successors.end())
            return false;
    }
    return true;
}

bool motifs_match(const string &motif1, const string &motif2, unsigned int l) {
    unordered_set<string> matching_motif1;
    unordered_set<string> matching_motif2;

    if(motif1 == motif2)
        return true;
    else
        return is_included(motif1, motif2, l) || is_included(motif2, motif1, l);
}

void filter_redundant_motif(vector<pair<const string, pair<int, Node *> > *> &remaining_hash_map_entries, unsigned int l) {

    unsigned int side_addition_limit = ceil(l / 2.0);
    //resetting node state
    for (auto const &entry : remaining_hash_map_entries)
        entry->second.second->reset_state();

    //finding nodes that were not processed yet
    auto entry_it = remaining_hash_map_entries.begin();
    while (entry_it != remaining_hash_map_entries.end()) {

        (*entry_it)->second.second->validate();
        string base = (*entry_it)->first;
        unsigned int letter_added_left = 0;
        unsigned int letter_added_right= 0;

        //getting into the loop
        bool found_motif = true;

        //while we still have motifs that overlap with the base
        while (found_motif) {
            found_motif = false;
            //for each entry
            for (auto &entry : remaining_hash_map_entries) {
                //that isn't tagged
                if(entry->second.second->get_state() != unvisited)
                    continue;

                //compute reverse_complement
                vector<string> motif_and_rc = {entry->first, reverse_complement(entry->first)};

                for (auto const &motif : motif_and_rc) {
                    /* motif      |------|-|
                       base [...]-|------| */
                    if (letter_added_right < side_addition_limit &&
                        motifs_match(string(base, base.size() - (l-1), l-1), string(motif, 0, l-1), l-1)) {
                        base.push_back(motif[l-1]);
                        found_motif = true;
                        letter_added_right++;
                    }
                    /* motif |-|-----|
                       base    |-----|-[...] */
                    else if (letter_added_left < side_addition_limit &&
                             motifs_match(string(base, 0, l-1), string(motif, 1, l-1), l-1)) {
                        base.insert(0, 1, motif[0]);
                        found_motif = true;
                        letter_added_left++;
                    }
                    else {
                        unsigned int pos = 0;
                        while ((pos + l) < base.size()) {
                            if(motifs_match(string(base, pos, l), motif, l)) {
                                found_motif = true;
                            }
                            pos++;
                        }
                    }
                    if(found_motif) {
                        //std::clog << (*entry_it)->first << " " << motif << "\tbase: " << base << std::endl;
                        entry->second.second->suppress();
                        break;
                    }
                }
                if (found_motif)
                    break;
            }
        }
        entry_it = find_if(remaining_hash_map_entries.begin(),
                           remaining_hash_map_entries.end(),
                           [](const pair<const string, pair<int, Node *> > *entry) -> bool
                            { return entry->second.second->get_state() == unvisited; });
    }
    remaining_hash_map_entries.erase(
        remove_if(remaining_hash_map_entries.begin(),
                  remaining_hash_map_entries.end(),
                  [](auto &entry)
                    {return entry->second.second->get_state() != validated;}),
        remaining_hash_map_entries.end());
}
<|endoftext|>


<commit_before>#include <ros.h>
#include <string.h>

#include "std_msgs/String.h"
#include "maelstrom_msgs/PwmRequests.h"
#include "maelstrom_msgs/ThrusterForces.h"
#include "maelstrom_msgs/LightInput.h"

#include "ForceToPwmLookup.h"

//incleder for IMU og trykksensor
#include "MPU6050/MPU6050.h"
#include "MS5803_14BA.h"
#include <Wire.h>
#include <geometry_msgs/Vector3.h>
#include "sensor_msgs/Imu.h"
#include "sensor_msgs/MagneticField.h"
#include "sensor_msgs/Temperature.h"
#include "sensor_msgs/FluidPressure.h"

#define MPU9150_I2C_ADDR 0x69
MPU6050 accelgyro(MPU9150_I2C_ADDR);

MS5803_14BA depthSensor;

ros::NodeHandle nh;

sensor_msgs::Imu imu_raw_msg;
sensor_msgs::MagneticField compass_msg;
sensor_msgs::Temperature temperature_msg;
sensor_msgs::FluidPressure pressure_msg;

ros::Publisher pub_imu("sensor_raw", &imu_raw_msg);

const int SensorReadDelay = 83;
unsigned long PrevoiusSensorReadMillis = 0;

int dbg_count = 0;

//Hold orden på pwm-pins til motor og lys
const int PwmCount = 7;
//                            ********MOTOR**********      LYS
const int PwmPins[PwmCount] = { 7, 8, 12, 13, 44, 45,      10};
const int LigthPwmPin = PwmPins[PwmCount-1]; //pin 10 er på Timer / Counter 2
int PwmValue[PwmCount];

void WritePwm(int pin, uint8_t value) {
  switch(pin) {
    //LYS
  case 10:
    analogWrite(pin, value);
    break;

    //MOTOR
  case 7:
    OCR4BH = 0;
    OCR4BL = value;
    break;
  case 8:
    OCR4CH = 0;
    OCR4CL = value;
    break;
  case 12:
    OCR1BH = 0;
    OCR1BL = value;
    break;
  case 13:
    OCR1CH = 0;
    OCR1CL = value;
    break;
  case 44:
    OCR5BH = 0;
    OCR5BL = value;
    break;
  case 45:
    OCR5CH = 0;
    OCR5CL = value;
    break;
  };
}

void InitPwm() {

  //sett alle pwmpinnene som utputt
  for(int i = 0; i < PwmCount; i++)
    pinMode(PwmPins[i], OUTPUT);

  //initialiser Timer/Counter 3, 4 og 5
  TCCR1A |= (1<<COM1B1) | (1<<COM1C1)  | (1<<WGM11) | (1<<WGM10);
  TCCR4A |= (1<<COM4B1) | (1<<COM4C1)  | (1<<WGM41) | (1<<WGM40);
  TCCR5A |= (1<<COM5B1) | (1<<COM5C1)  | (1<<WGM51) | (1<<WGM50);

  //sett Clock select
  //på Timer/Counter 1
  TCCR1B |= (1<<CS11) | (1<<CS10);
  TCCR1B &= ~(1<<CS12);
  //På Timer/Counter 4
  TCCR4B |= (1<<CS41) | (1<<CS40);
  TCCR4B &= ~(1<<CS42);
  //på Timer/Counter 5
  TCCR5B |= (1<<CS51) | (1<<CS50);
  TCCR5B &= ~(1<<CS52);

  //sett alle motorer til 0 Newton
  for(int i = 0; i < PwmCount; i++) {
    PwmValue[i] = ForceToPwm(0);
    WritePwm(PwmPins[i], PwmValue[i]);
  }
  //og så av lys
  PwmValue[LigthPwmPin] = 0;
  WritePwm(LigthPwmPin, 0);

}

maelstrom_msgs::PwmRequests  pwm_status_msg;
ros::Publisher pwm_status_pub("pwm_status", &pwm_status_msg);

std_msgs::String arduino_dbg_msg;
ros::Publisher arduino_dbg_pub("arduino_dbg", &arduino_dbg_msg);

void pwm_update( const maelstrom_msgs::ThrusterForces& force_input ){

  PwmValue[0] = ForceToPwm(force_input.F1);
  PwmValue[1] = ForceToPwm(force_input.F2);
  PwmValue[2] = ForceToPwm(force_input.F3);
  PwmValue[3] = ForceToPwm(force_input.F4);
  PwmValue[4] = ForceToPwm(force_input.F5);
  PwmValue[5] = ForceToPwm(force_input.F6);

  for(int i = 0; i < PwmCount; i++) {
    WritePwm(PwmPins[i], PwmValue[i]);
  }

  //Send PWM-verdiene tilbake som debugoutput
  pwm_status_msg.pwm1 = PwmValue[0];
  pwm_status_msg.pwm2 = PwmValue[1];
  pwm_status_msg.pwm3 = PwmValue[2];
  pwm_status_msg.pwm4 = PwmValue[3];
  pwm_status_msg.pwm5 = PwmValue[4];
  pwm_status_msg.pwm6 = PwmValue[5];
  pwm_status_msg.pwm7 = PwmValue[6];

  dbg_count = 0;

  pwm_status_pub.publish( &pwm_status_msg );
}

ros::Subscriber<maelstrom_msgs::ThrusterForces> pwm_input_sub("thruster_forces", &pwm_update );

void LightPwmUpdate( const maelstrom_msgs::LightInput &light_msg) {
  PwmValue[6] = light_msg.light_intensity;

  WritePwm(LigthPwmPin, PwmValue[6]);

  pwm_status_msg.pwm1 = PwmValue[0];
  pwm_status_msg.pwm2 = PwmValue[1];
  pwm_status_msg.pwm3 = PwmValue[2];
  pwm_status_msg.pwm4 = PwmValue[3];
  pwm_status_msg.pwm5 = PwmValue[4];
  pwm_status_msg.pwm6 = PwmValue[5];
  pwm_status_msg.pwm7 = PwmValue[6];
  pwm_status_pub.publish( &pwm_status_msg );
}

ros::Subscriber<maelstrom_msgs::LightInput> light_pwm_input_sub("LightPwm", &LightPwmUpdate );

double GyroLsbSens, AccelLsbSens;
void getFsRangeAndSetLsbSensisivity() {

  uint8_t GyroFsRange, AccelFsRange;

  GyroFsRange = accelgyro.getFullScaleGyroRange();
  /* Gyro
   * FS_SEL | Full Scale Range   | LSB Sensitivity
   * -------+--------------------+----------------
   * 0      | +/- 250 degrees/s  | 131 LSB/deg/s
   * 1      | +/- 500 degrees/s  | 65.5 LSB/deg/s
   * 2      | +/- 1000 degrees/s | 32.8 LSB/deg/s
   * 3      | +/- 2000 degrees/s | 16.4 LSB/deg/s
   */
  switch(GyroFsRange) {
  case 0:
    GyroLsbSens = 131.0;
    break;
  case 1:
    GyroLsbSens = 65.5;
    break;
  case 2:
    GyroLsbSens = 32.8;
    break;
  case 3:
    GyroLsbSens = 16.4;
    break;
  };

  AccelFsRange = accelgyro.getFullScaleAccelRange();
  /*Accelerometer
   * AFS_SEL | Full Scale Range | LSB Sensitivity
   * --------+------------------+----------------
   * 0       | +/- 2g           | 16384 LSB/g
   * 1       | +/- 4g           | 8192 LSB/g
   * 2       | +/- 8g           | 4096 LSB/g
   * 3       | +/- 16g          | 2048 LSB/g
   */
  switch(AccelFsRange) {
  case 0:
    AccelLsbSens = 16384.0;
    break;
  case 1:
    AccelLsbSens = 8192.0;
    break;
  case 2:
    AccelLsbSens = 4096.0;
    break;
  case 3:
    AccelLsbSens = 2048.0;
    break;
  };

}

void setup() {

  InitPwm();

  //start ROS-node
  nh.initNode();

  nh.advertise(pwm_status_pub);
  nh.advertise(arduino_dbg_pub);

  nh.advertise(pub_imu);
  nh.subscribe(pwm_input_sub);
  nh.subscribe(light_pwm_input_sub);
  nh.spinOnce();

  // Initialize the 'Wire' class for the I2C-bus.
  // I2C pins: 20 (SDA) og 21 (SCL) (Mega2560)
  Wire.begin();
  accelgyro.initialize();
  getFsRangeAndSetLsbSensisivity();

  depthSensor.initialize(false);

  nh.spinOnce();
  String dbg_msg =  String("init:\n") +
    (accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");
  arduino_dbg_msg.data = dbg_msg.c_str();
  arduino_dbg_pub.publish( &arduino_dbg_msg );

  nh.spinOnce();

}

void lesSensorer() {

  int16_t ax, ay, az;
  int16_t gx, gy, gz;
  int16_t mx, my, mz;

  accelgyro.getMotion9(&ax, &ay, &az, &gx, &gy, &gz, &mx, &my, &mz);

  //Accelerometerdata enhet: [m/s^2]
  imu_raw_msg.linear_acceleration.x = ax / AccelLsbSens; // OBS! MÅ VÆRE m/s^2!
  imu_raw_msg.linear_acceleration.y = ay / AccelLsbSens; // OBS! MÅ VÆRE m/s^2!
  imu_raw_msg.linear_acceleration.z = az / AccelLsbSens; // OBS! MÅ VÆRE m/s^2!

  //Gyrodata: enhet [rad/s]
  imu_raw_msg.angular_velocity.x = gx / GyroLsbSens; // OBS! MÅ VÆRE RAD/SEC
  imu_raw_msg.angular_velocity.y = gy / GyroLsbSens; // OBS! MÅ VÆRE RAD/SEC
  imu_raw_msg.angular_velocity.z = gz / GyroLsbSens; // OBS! MÅ VÆRE RAD/SEC

  // Kompass, enhet [T]
  // TODO finn ut om 0.3 er riktig skaleringsfaktor
  compass_msg.magnetic_field.x = mx * 0.3; // OBS! MÅ VÆRE TESLA! (IKKE MILLI/MICRO)
  compass_msg.magnetic_field.y = my * 0.3; // OBS! MÅ VÆRE TESLA! (IKKE MILLI/MICRO)
  compass_msg.magnetic_field.z = mz * 0.3; // OBS! MÅ VÆRE TESLA! (IKKE MILLI/MICRO)

  temperature_msg.temperature = ( (double)accelgyro.getTemperature() + 12412.0) / 340.0;

  depthSensor.read();
  pressure_msg.pressure = depthSensor.getPreassure(); // OBS! MÅ VÆRE I PASCAL
}

void loop(){

  nh.spinOnce();

  if( millis() - PrevoiusSensorReadMillis >= SensorReadDelay ) {
    PrevoiusSensorReadMillis = millis();

    lesSensorer();
    //nh.spinOnce();
    pub_imu.publish(&imu_raw_msg);
  }

  /*
  //String dbg_msg = "pwm updated after " + String(dbg_count) + " cycles";
  //String dbg_msg = "accelX = " ;//+ String(imu.read(MPU9150_ACCEL_XOUT_L, MPU9150_ACCEL_XOUT_H));
  String dbg_msg = String("GyroFsRange = ") + String(GyroFsRange) +
  String("\nAccelFsRange = ") + String(AccelFsRange);
  arduino_dbg_msg.data = dbg_msg.c_str();
  arduino_dbg_pub.publish( &arduino_dbg_msg );
  nh.spinOnce();
  */

}
<commit_msg>Wrong msg field name<commit_after>#include <ros.h>
#include <string.h>

#include "std_msgs/String.h"
#include "maelstrom_msgs/PwmRequests.h"
#include "maelstrom_msgs/ThrusterForces.h"
#include "maelstrom_msgs/LightInput.h"

#include "ForceToPwmLookup.h"

//incleder for IMU og trykksensor
#include "MPU6050/MPU6050.h"
#include "MS5803_14BA.h"
#include <Wire.h>
#include <geometry_msgs/Vector3.h>
#include "sensor_msgs/Imu.h"
#include "sensor_msgs/MagneticField.h"
#include "sensor_msgs/Temperature.h"
#include "sensor_msgs/FluidPressure.h"

#define MPU9150_I2C_ADDR 0x69
MPU6050 accelgyro(MPU9150_I2C_ADDR);

MS5803_14BA depthSensor;

ros::NodeHandle nh;

sensor_msgs::Imu imu_raw_msg;
sensor_msgs::MagneticField compass_msg;
sensor_msgs::Temperature temperature_msg;
sensor_msgs::FluidPressure pressure_msg;

ros::Publisher pub_imu("sensor_raw", &imu_raw_msg);

const int SensorReadDelay = 83;
unsigned long PrevoiusSensorReadMillis = 0;

int dbg_count = 0;

//Hold orden på pwm-pins til motor og lys
const int PwmCount = 7;
//                            ********MOTOR**********      LYS
const int PwmPins[PwmCount] = { 7, 8, 12, 13, 44, 45,      10};
const int LigthPwmPin = PwmPins[PwmCount-1]; //pin 10 er på Timer / Counter 2
int PwmValue[PwmCount];

void WritePwm(int pin, uint8_t value) {
  switch(pin) {
    //LYS
  case 10:
    analogWrite(pin, value);
    break;

    //MOTOR
  case 7:
    OCR4BH = 0;
    OCR4BL = value;
    break;
  case 8:
    OCR4CH = 0;
    OCR4CL = value;
    break;
  case 12:
    OCR1BH = 0;
    OCR1BL = value;
    break;
  case 13:
    OCR1CH = 0;
    OCR1CL = value;
    break;
  case 44:
    OCR5BH = 0;
    OCR5BL = value;
    break;
  case 45:
    OCR5CH = 0;
    OCR5CL = value;
    break;
  };
}

void InitPwm() {

  //sett alle pwmpinnene som utputt
  for(int i = 0; i < PwmCount; i++)
    pinMode(PwmPins[i], OUTPUT);

  //initialiser Timer/Counter 3, 4 og 5
  TCCR1A |= (1<<COM1B1) | (1<<COM1C1)  | (1<<WGM11) | (1<<WGM10);
  TCCR4A |= (1<<COM4B1) | (1<<COM4C1)  | (1<<WGM41) | (1<<WGM40);
  TCCR5A |= (1<<COM5B1) | (1<<COM5C1)  | (1<<WGM51) | (1<<WGM50);

  //sett Clock select
  //på Timer/Counter 1
  TCCR1B |= (1<<CS11) | (1<<CS10);
  TCCR1B &= ~(1<<CS12);
  //På Timer/Counter 4
  TCCR4B |= (1<<CS41) | (1<<CS40);
  TCCR4B &= ~(1<<CS42);
  //på Timer/Counter 5
  TCCR5B |= (1<<CS51) | (1<<CS50);
  TCCR5B &= ~(1<<CS52);

  //sett alle motorer til 0 Newton
  for(int i = 0; i < PwmCount; i++) {
    PwmValue[i] = ForceToPwm(0);
    WritePwm(PwmPins[i], PwmValue[i]);
  }
  //og så av lys
  PwmValue[LigthPwmPin] = 0;
  WritePwm(LigthPwmPin, 0);

}

maelstrom_msgs::PwmRequests  pwm_status_msg;
ros::Publisher pwm_status_pub("pwm_status", &pwm_status_msg);

std_msgs::String arduino_dbg_msg;
ros::Publisher arduino_dbg_pub("arduino_dbg", &arduino_dbg_msg);

void pwm_update( const maelstrom_msgs::ThrusterForces& force_input ){

  PwmValue[0] = ForceToPwm(force_input.F1);
  PwmValue[1] = ForceToPwm(force_input.F2);
  PwmValue[2] = ForceToPwm(force_input.F3);
  PwmValue[3] = ForceToPwm(force_input.F4);
  PwmValue[4] = ForceToPwm(force_input.F5);
  PwmValue[5] = ForceToPwm(force_input.F6);

  for(int i = 0; i < PwmCount; i++) {
    WritePwm(PwmPins[i], PwmValue[i]);
  }

  //Send PWM-verdiene tilbake som debugoutput
  pwm_status_msg.pwm1 = PwmValue[0];
  pwm_status_msg.pwm2 = PwmValue[1];
  pwm_status_msg.pwm3 = PwmValue[2];
  pwm_status_msg.pwm4 = PwmValue[3];
  pwm_status_msg.pwm5 = PwmValue[4];
  pwm_status_msg.pwm6 = PwmValue[5];
  pwm_status_msg.pwm7 = PwmValue[6];

  dbg_count = 0;

  pwm_status_pub.publish( &pwm_status_msg );
}

ros::Subscriber<maelstrom_msgs::ThrusterForces> pwm_input_sub("thruster_forces", &pwm_update );

void LightPwmUpdate( const maelstrom_msgs::LightInput &light_msg) {
  PwmValue[6] = light_msg.light_intensity;

  WritePwm(LigthPwmPin, PwmValue[6]);

  pwm_status_msg.pwm1 = PwmValue[0];
  pwm_status_msg.pwm2 = PwmValue[1];
  pwm_status_msg.pwm3 = PwmValue[2];
  pwm_status_msg.pwm4 = PwmValue[3];
  pwm_status_msg.pwm5 = PwmValue[4];
  pwm_status_msg.pwm6 = PwmValue[5];
  pwm_status_msg.pwm7 = PwmValue[6];
  pwm_status_pub.publish( &pwm_status_msg );
}

ros::Subscriber<maelstrom_msgs::LightInput> light_pwm_input_sub("LightPwm", &LightPwmUpdate );

double GyroLsbSens, AccelLsbSens;
void getFsRangeAndSetLsbSensisivity() {

  uint8_t GyroFsRange, AccelFsRange;

  GyroFsRange = accelgyro.getFullScaleGyroRange();
  /* Gyro
   * FS_SEL | Full Scale Range   | LSB Sensitivity
   * -------+--------------------+----------------
   * 0      | +/- 250 degrees/s  | 131 LSB/deg/s
   * 1      | +/- 500 degrees/s  | 65.5 LSB/deg/s
   * 2      | +/- 1000 degrees/s | 32.8 LSB/deg/s
   * 3      | +/- 2000 degrees/s | 16.4 LSB/deg/s
   */
  switch(GyroFsRange) {
  case 0:
    GyroLsbSens = 131.0;
    break;
  case 1:
    GyroLsbSens = 65.5;
    break;
  case 2:
    GyroLsbSens = 32.8;
    break;
  case 3:
    GyroLsbSens = 16.4;
    break;
  };

  AccelFsRange = accelgyro.getFullScaleAccelRange();
  /*Accelerometer
   * AFS_SEL | Full Scale Range | LSB Sensitivity
   * --------+------------------+----------------
   * 0       | +/- 2g           | 16384 LSB/g
   * 1       | +/- 4g           | 8192 LSB/g
   * 2       | +/- 8g           | 4096 LSB/g
   * 3       | +/- 16g          | 2048 LSB/g
   */
  switch(AccelFsRange) {
  case 0:
    AccelLsbSens = 16384.0;
    break;
  case 1:
    AccelLsbSens = 8192.0;
    break;
  case 2:
    AccelLsbSens = 4096.0;
    break;
  case 3:
    AccelLsbSens = 2048.0;
    break;
  };

}

void setup() {

  InitPwm();

  //start ROS-node
  nh.initNode();

  nh.advertise(pwm_status_pub);
  nh.advertise(arduino_dbg_pub);

  nh.advertise(pub_imu);
  nh.subscribe(pwm_input_sub);
  nh.subscribe(light_pwm_input_sub);
  nh.spinOnce();

  // Initialize the 'Wire' class for the I2C-bus.
  // I2C pins: 20 (SDA) og 21 (SCL) (Mega2560)
  Wire.begin();
  accelgyro.initialize();
  getFsRangeAndSetLsbSensisivity();

  depthSensor.initialize(false);

  nh.spinOnce();
  String dbg_msg =  String("init:\n") +
    (accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");
  arduino_dbg_msg.data = dbg_msg.c_str();
  arduino_dbg_pub.publish( &arduino_dbg_msg );

  nh.spinOnce();

}

void lesSensorer() {

  int16_t ax, ay, az;
  int16_t gx, gy, gz;
  int16_t mx, my, mz;

  accelgyro.getMotion9(&ax, &ay, &az, &gx, &gy, &gz, &mx, &my, &mz);

  //Accelerometerdata enhet: [m/s^2]
  imu_raw_msg.linear_acceleration.x = ax / AccelLsbSens; // OBS! MÅ VÆRE m/s^2!
  imu_raw_msg.linear_acceleration.y = ay / AccelLsbSens; // OBS! MÅ VÆRE m/s^2!
  imu_raw_msg.linear_acceleration.z = az / AccelLsbSens; // OBS! MÅ VÆRE m/s^2!

  //Gyrodata: enhet [rad/s]
  imu_raw_msg.angular_velocity.x = gx / GyroLsbSens; // OBS! MÅ VÆRE RAD/SEC
  imu_raw_msg.angular_velocity.y = gy / GyroLsbSens; // OBS! MÅ VÆRE RAD/SEC
  imu_raw_msg.angular_velocity.z = gz / GyroLsbSens; // OBS! MÅ VÆRE RAD/SEC

  // Kompass, enhet [T]
  // TODO finn ut om 0.3 er riktig skaleringsfaktor
  compass_msg.magnetic_field.x = mx * 0.3; // OBS! MÅ VÆRE TESLA! (IKKE MILLI/MICRO)
  compass_msg.magnetic_field.y = my * 0.3; // OBS! MÅ VÆRE TESLA! (IKKE MILLI/MICRO)
  compass_msg.magnetic_field.z = mz * 0.3; // OBS! MÅ VÆRE TESLA! (IKKE MILLI/MICRO)

  temperature_msg.temperature = ( (double)accelgyro.getTemperature() + 12412.0) / 340.0;

  depthSensor.read();
  pressure_msg.fluid_pressure = depthSensor.getPreassure(); // OBS! MÅ VÆRE I PASCAL
}

void loop(){

  nh.spinOnce();

  if( millis() - PrevoiusSensorReadMillis >= SensorReadDelay ) {
    PrevoiusSensorReadMillis = millis();

    lesSensorer();
    //nh.spinOnce();
    pub_imu.publish(&imu_raw_msg);
  }

  /*
  //String dbg_msg = "pwm updated after " + String(dbg_count) + " cycles";
  //String dbg_msg = "accelX = " ;//+ String(imu.read(MPU9150_ACCEL_XOUT_L, MPU9150_ACCEL_XOUT_H));
  String dbg_msg = String("GyroFsRange = ") + String(GyroFsRange) +
  String("\nAccelFsRange = ") + String(AccelFsRange);
  arduino_dbg_msg.data = dbg_msg.c_str();
  arduino_dbg_pub.publish( &arduino_dbg_msg );
  nh.spinOnce();
  */

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ChartType.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: bm $ $Date: 2004-01-26 09:12:48 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef CHART_CHARTTYPE_HXX
#define CHART_CHARTTYPE_HXX

#ifndef CHART_MUTEXCONTAINER_HXX
#include "MutexContainer.hxx"
#endif
#ifndef CHART_OPROPERTYSET_HXX
#include "OPropertySet.hxx"
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#include "ServiceMacros.hxx"

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XCHARTTYPE_HPP_
#include <com/sun/star/chart2/XChartType.hpp>
#endif

namespace chart
{

namespace impl
{
typedef ::cppu::WeakImplHelper1<
    ::com::sun::star::chart2::XChartType >
    ChartType_Base;
}

class ChartType :
    public helper::MutexContainer,
    public impl::ChartType_Base,
    public ::property::OPropertySet
{
public:
    ChartType( sal_Int32 nDim = 2 );
    virtual ~ChartType();

protected:
    // ____ XChartType ____
    // still abstract ! implement !
    virtual ::rtl::OUString SAL_CALL getChartType()
        throw (::com::sun::star::uno::RuntimeException) = 0;

    // ____ OPropertySet ____
    virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const
        throw(::com::sun::star::beans::UnknownPropertyException);

    // ____ OPropertySet ____
    virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();

    // ____ XPropertySet ____
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL
        getPropertySetInfo()
        throw (::com::sun::star::uno::RuntimeException);

//  virtual sal_Bool SAL_CALL convertFastPropertyValue
//         ( ::com::sun::star::uno::Any & rConvertedValue,
//           ::com::sun::star::uno::Any & rOldValue,
//           sal_Int32 nHandle,
//           const ::com::sun::star::uno::Any& rValue )
//      throw (::com::sun::star::lang::IllegalArgumentException);

    // declare this in derived classes !
    APPHELPER_XSERVICEINFO_DECL()

    /// merge XInterface implementations
     DECLARE_XINTERFACE()
    /// merge XTypeProvider implementations
     DECLARE_XTYPEPROVIDER()

private:
};

} //  namespace chart

// CHART_CHARTTYPE_HXX
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.110); FILE MERGED 2005/09/05 18:43:20 rt 1.2.110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ChartType.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 01:10:56 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CHART_CHARTTYPE_HXX
#define CHART_CHARTTYPE_HXX

#ifndef CHART_MUTEXCONTAINER_HXX
#include "MutexContainer.hxx"
#endif
#ifndef CHART_OPROPERTYSET_HXX
#include "OPropertySet.hxx"
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#include "ServiceMacros.hxx"

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XCHARTTYPE_HPP_
#include <com/sun/star/chart2/XChartType.hpp>
#endif

namespace chart
{

namespace impl
{
typedef ::cppu::WeakImplHelper1<
    ::com::sun::star::chart2::XChartType >
    ChartType_Base;
}

class ChartType :
    public helper::MutexContainer,
    public impl::ChartType_Base,
    public ::property::OPropertySet
{
public:
    ChartType( sal_Int32 nDim = 2 );
    virtual ~ChartType();

protected:
    // ____ XChartType ____
    // still abstract ! implement !
    virtual ::rtl::OUString SAL_CALL getChartType()
        throw (::com::sun::star::uno::RuntimeException) = 0;

    // ____ OPropertySet ____
    virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const
        throw(::com::sun::star::beans::UnknownPropertyException);

    // ____ OPropertySet ____
    virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();

    // ____ XPropertySet ____
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL
        getPropertySetInfo()
        throw (::com::sun::star::uno::RuntimeException);

//  virtual sal_Bool SAL_CALL convertFastPropertyValue
//         ( ::com::sun::star::uno::Any & rConvertedValue,
//           ::com::sun::star::uno::Any & rOldValue,
//           sal_Int32 nHandle,
//           const ::com::sun::star::uno::Any& rValue )
//      throw (::com::sun::star::lang::IllegalArgumentException);

    // declare this in derived classes !
    APPHELPER_XSERVICEINFO_DECL()

    /// merge XInterface implementations
     DECLARE_XINTERFACE()
    /// merge XTypeProvider implementations
     DECLARE_XTYPEPROVIDER()

private:
};

} //  namespace chart

// CHART_CHARTTYPE_HXX
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: VCartesianAxis.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _CHART2_VCARTESIANAXIS_HXX
#define _CHART2_VCARTESIANAXIS_HXX

#include "VAxisBase.hxx"
#include <basegfx/vector/b2dvector.hxx>

//.............................................................................
namespace chart
{
//.............................................................................

//-----------------------------------------------------------------------------
/**
*/

class VCartesianAxis : public VAxisBase
{
    //-------------------------------------------------------------------------
    // public methods
    //-------------------------------------------------------------------------
public:
    VCartesianAxis( const AxisProperties& rAxisProperties
           , const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier
           , sal_Int32 nDimensionIndex, sal_Int32 nDimensionCount
           , PlottingPositionHelper* pPosHelper = NULL //takes ownership
           );

    virtual ~VCartesianAxis();

    //-------------------------------------------------------------------------
    // partly chart2::XPlotter
    //-------------------------------------------------------------------------

    /*
    virtual ::rtl::OUString SAL_CALL getCoordinateSystemTypeID(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setTransformation( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >& xTransformationToLogicTarget, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >& xTransformationToFinalPage ) throw (::com::sun::star::uno::RuntimeException);
    */

    virtual void SAL_CALL createMaximumLabels();
    virtual void SAL_CALL createLabels();
    virtual void SAL_CALL updatePositions();

    virtual void SAL_CALL createShapes();

    virtual sal_Int32 estimateMaximumAutoMainIncrementCount();

    //-------------------------------------------------------------------------
    virtual TickmarkHelper* createTickmarkHelper();

    //-------------------------------------------------------------------------
    double      getLogicValueWhereMainLineCrossesOtherAxis() const;
    bool        getLogicValueWhereExtraLineCrossesOtherAxis( double& fCrossesOtherAxis) const;
    void        get2DAxisMainLine( ::basegfx::B2DVector& rStart, ::basegfx::B2DVector& rEnd, double fCrossesOtherAxis ) const;

    //-------------------------------------------------------------------------
    //Layout interface for cartesian axes:

    //the returned value describes the minimum size that is necessary
    //for the text labels in the direction orthogonal to the axis
    //(for an y-axis a width is returned; in case of an x-axis the value describes a height)
    //the return value is measured in screen dimension
    //As an example the MinimumOrthogonalSize of an x-axis equals the
    //Font Height if the label properties allow for labels parallel to the axis.
//    sal_Int32 calculateMinimumOrthogonalSize( /*... parallel...*/ );
    //Minimum->Preferred

    //returns true if the MinimumOrthogonalSize can be calculated
    //with the creation of at most one text shape
    //(this is e.g. true if the parameters allow for labels parallel to the axis.)
//    sal_bool  canQuicklyCalculateMinimumOrthogonalSize();

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------

protected: //methods
    bool    createTextShapes( const ::com::sun::star::uno::Reference<
                       ::com::sun::star::drawing::XShapes >& xTarget
                     , TickIter& rTickIter
                     , AxisLabelProperties& rAxisLabelProperties
                     , TickmarkHelper_2D* pTickmarkHelper );

    TickmarkHelper_2D* createTickmarkHelper2D();

    void    doStaggeringOfLabels( const AxisLabelProperties& rAxisLabelProperties
                            , TickmarkHelper_2D* pTickmarkHelper2D );
    bool    isAutoStaggeringOfLabelsAllowed( const AxisLabelProperties& rAxisLabelProperties
                            , TickmarkHelper_2D* pTickmarkHelper);
    bool    isBreakOfLabelsAllowed( const AxisLabelProperties& rAxisLabelProperties
                                                     , TickmarkHelper_2D* pTickmarkHelper );
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>INTEGRATION: CWS chart26_DEV300 (1.5.130); FILE MERGED 2008/04/23 19:27:24 iha 1.5.130.1: #i72994# good automatic placement of walls, grid lines and axes labels dependent on 3D rotation<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: VCartesianAxis.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _CHART2_VCARTESIANAXIS_HXX
#define _CHART2_VCARTESIANAXIS_HXX

#include "VAxisBase.hxx"
#include <basegfx/vector/b2dvector.hxx>

//.............................................................................
namespace chart
{
//.............................................................................

//-----------------------------------------------------------------------------
/**
*/

class VCartesianAxis : public VAxisBase
{
    //-------------------------------------------------------------------------
    // public methods
    //-------------------------------------------------------------------------
public:
    VCartesianAxis( const AxisProperties& rAxisProperties
           , const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier
           , sal_Int32 nDimensionIndex, sal_Int32 nDimensionCount
           , PlottingPositionHelper* pPosHelper = NULL //takes ownership
           );

    virtual ~VCartesianAxis();

    //-------------------------------------------------------------------------
    // partly chart2::XPlotter
    //-------------------------------------------------------------------------

    /*
    virtual ::rtl::OUString SAL_CALL getCoordinateSystemTypeID(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setTransformation( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >& xTransformationToLogicTarget, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >& xTransformationToFinalPage ) throw (::com::sun::star::uno::RuntimeException);
    */

    virtual void SAL_CALL createMaximumLabels();
    virtual void SAL_CALL createLabels();
    virtual void SAL_CALL updatePositions();

    virtual void SAL_CALL createShapes();

    virtual sal_Int32 estimateMaximumAutoMainIncrementCount();

    //-------------------------------------------------------------------------
    virtual TickmarkHelper* createTickmarkHelper();

    //-------------------------------------------------------------------------
    double      getLogicValueWhereMainLineCrossesOtherAxis() const;
    bool        getLogicValueWhereExtraLineCrossesOtherAxis( double& fCrossesOtherAxis) const;
    void        get2DAxisMainLine( ::basegfx::B2DVector& rStart, ::basegfx::B2DVector& rEnd, double fCrossesOtherAxis );

    //-------------------------------------------------------------------------
    //Layout interface for cartesian axes:

    //the returned value describes the minimum size that is necessary
    //for the text labels in the direction orthogonal to the axis
    //(for an y-axis a width is returned; in case of an x-axis the value describes a height)
    //the return value is measured in screen dimension
    //As an example the MinimumOrthogonalSize of an x-axis equals the
    //Font Height if the label properties allow for labels parallel to the axis.
//    sal_Int32 calculateMinimumOrthogonalSize( /*... parallel...*/ );
    //Minimum->Preferred

    //returns true if the MinimumOrthogonalSize can be calculated
    //with the creation of at most one text shape
    //(this is e.g. true if the parameters allow for labels parallel to the axis.)
//    sal_bool  canQuicklyCalculateMinimumOrthogonalSize();

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------

    struct ScreenPosAndLogicPos
    {
        double fLogicX;
        double fLogicY;
        double fLogicZ;

        B2DVector aScreenPos;
    };

protected: //methods
    bool    createTextShapes( const ::com::sun::star::uno::Reference<
                       ::com::sun::star::drawing::XShapes >& xTarget
                     , TickIter& rTickIter
                     , AxisLabelProperties& rAxisLabelProperties
                     , TickmarkHelper_2D* pTickmarkHelper );

    TickmarkHelper_2D* createTickmarkHelper2D();

    void    doStaggeringOfLabels( const AxisLabelProperties& rAxisLabelProperties
                            , TickmarkHelper_2D* pTickmarkHelper2D );
    bool    isAutoStaggeringOfLabelsAllowed( const AxisLabelProperties& rAxisLabelProperties
                            , TickmarkHelper_2D* pTickmarkHelper);
    bool    isBreakOfLabelsAllowed( const AxisLabelProperties& rAxisLabelProperties
                                                     , TickmarkHelper_2D* pTickmarkHelper );

    ::basegfx::B2DVector getScreenPosition( double fLogicX, double fLogicY, double fLogicZ ) const;
    ScreenPosAndLogicPos getScreenPosAndLogicPos( double fLogicX, double fLogicY, double fLogicZ ) const;
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|>


<commit_before>// This file is part of the dune-pymor project:
//   https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_PYMOR_LA_CONTAINER_AFFINE_HH
#define DUNE_PYMOR_LA_CONTAINER_AFFINE_HH

#include <memory>
#include <vector>
#include <type_traits>

#include <dune/stuff/common/string.hh>

#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/parameters/functional.hh>
#include "interfaces.hh"

namespace Dune {
namespace Pymor {
namespace LA {

template< class ContainerImp >
class AffinelyDecomposedConstContainer
  : public Parametric
{
  static_assert(std::is_base_of< ContainerInterface< typename ContainerImp::Traits >, ContainerImp >::value,
                "ContainerType must be derived from ContainerInterface");
public:
  typedef ContainerImp                        ContainerType;

  AffinelyDecomposedConstContainer()
    : hasAffinePart_(false)
    , num_components_(0)
  {}

  /**
   * \attention This class takes ownership of aff_ptr (in the sense, that you must not delete it manually)!
   */
  AffinelyDecomposedConstContainer(const ContainerType* aff_ptr)
    : hasAffinePart_(true)
    , num_components_(0)
    , affinePart_(aff_ptr)
  {}

  AffinelyDecomposedConstContainer(const std::shared_ptr< const ContainerType > aff_ptr)
    : hasAffinePart_(true)
    , num_components_(0)
    , affinePart_(aff_ptr)
  {}

  /**
   * \attention This class takes ownership of comp_ptr and coeff_ptr (in the sense, that you must not delete it manually)!
   */
  AffinelyDecomposedConstContainer(const ContainerType* comp_ptr, const ParameterFunctional* coeff_ptr)
    : hasAffinePart_(false)
    , num_components_(1)
  {
    components_.emplace_back(comp_ptr);
    coefficients_.emplace_back(coeff_ptr);
    inherit_parameter_type(coeff_ptr->parameter_type(), "coefficient_0");
  }

  /**
   * \attention This class takes ownership of coeff_ptr (in the sense, that you must not delete it manually)!
   */
  AffinelyDecomposedConstContainer(const std::shared_ptr< const ContainerType > comp_ptr,
                                   const ParameterFunctional* coeff_ptr)
    : hasAffinePart_(false)
    , num_components_(1)
  {
    components_.push_back(comp_ptr);
    coefficients_.emplace_back(coeff_ptr);
    inherit_parameter_type(coeff_ptr->parameter_type(), "coefficient_0");
  }

  /**
   * \attention This class takes ownership of comp_ptr (in the sense, that you must not delete it manually)!
   */
  AffinelyDecomposedConstContainer(const ContainerType* comp_ptr,
                                   const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    : hasAffinePart_(false)
    , num_components_(1)
  {
    components_.emplace_back(comp_ptr);
    coefficients_.push_back(coeff_ptr);
    inherit_parameter_type(coeff_ptr->parameter_type(), "coefficient_0");
  }

  AffinelyDecomposedConstContainer(const std::shared_ptr< const ContainerType > comp_ptr,
                                   const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    : hasAffinePart_(false)
    , num_components_(1)
  {
    components_.push_back(comp_ptr);
    coefficients_.push_back(coeff_ptr);
    inherit_parameter_type(coeff_ptr->parameter_type(), "coefficient_0");
  }

  bool has_affine_part() const
  {
    return hasAffinePart_;
  }

  unsigned int num_components() const
  {
    return num_components_;
  }

  /**
   * \attention This class takes ownership of aff_ptr (in the sense, that you must not delete it manually)!
   */
  void register_affine_part(const ContainerType* aff_ptr) throw (Exception::this_does_not_make_any_sense,
                                                                 Exception::sizes_do_not_match)
  {
    register_affine_part(std::shared_ptr< const ContainerType >(aff_ptr));
  }

  void register_affine_part(const std::shared_ptr< const ContainerType > aff_ptr)
    throw (Exception::this_does_not_make_any_sense, Exception::sizes_do_not_match)
  {
    if (hasAffinePart_)
      DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense,
                       "do not call register_affine_part(aff_ptr) if has_affine_part() == true!");
    if (num_components_ > 0 && !components_[0]->has_equal_shape(*aff_ptr))
      DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                       "the shape of aff_ptr does not match the shape of the existing containers!");
    affinePart_ = aff_ptr;
    hasAffinePart_ = true;
  }

  /**
   * \attention This class takes ownership of comp_ptr and coeff_ptr (in the sense, that you must not delete it manually)!
   */
  void register_component(const ContainerType* comp_ptr,
                          const ParameterFunctional* coeff_ptr) throw (Exception::sizes_do_not_match)
  {
    register_component(std::shared_ptr< const ContainerType >(comp_ptr),
                       std::shared_ptr< const ParameterFunctional >(coeff_ptr));
  }

  /**
   * \attention This class takes ownership of comp_ptr (in the sense, that you must not delete it manually)!
   */
  void register_component(const ContainerType* comp_ptr,
                          const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    throw (Exception::sizes_do_not_match)
  {
    register_component(std::shared_ptr< const ContainerType >(comp_ptr), coeff_ptr);
  }

  /**
   * \attention This class takes ownership of coeff_ptr (in the sense, that you must not delete it manually)!
   */
  void register_component(const std::shared_ptr< const ContainerType > comp_ptr,
                          const ParameterFunctional* coeff_ptr) throw (Exception::sizes_do_not_match)
  {
    register_component(comp_ptr, std::shared_ptr< const ParameterFunctional >(coeff_ptr));
  }

  void register_component(const std::shared_ptr< const ContainerType > comp_ptr,
                          const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    throw (Exception::sizes_do_not_match)
  {
    if (hasAffinePart_) {
      if (!affinePart_->has_equal_shape(*comp_ptr))
        DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                         "the shape of comp_ptr does not match the shape of the existing containers!");
    } else if (num_components_ > 0)
      if (!components_[0]->has_equal_shape(*comp_ptr))
        DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                         "the shape of aff_ptr does not match the shape of the existing components!");
    components_.push_back(comp_ptr);
    coefficients_.push_back(coeff_ptr);
    inherit_parameter_type(coeff_ptr->parameter_type(), "coefficient_" + Dune::Stuff::Common::toString(num_components_));
    ++num_components_;
  }

  std::shared_ptr< const ContainerType > affine_part() const throw (Exception::requirements_not_met)
  {
    if (!hasAffinePart_)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call affine_part() if has_affine_part() == false!");
    return affinePart_;
  }

  std::shared_ptr< const ContainerType > component(const int qq) const throw (Exception::requirements_not_met,
                                                                              Exception::index_out_of_range)
  {
    if (num_components_ == 0)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call component(" << qq << ") if num_components() == 0!");
    if (qq < 0 || qq >= int(num_components_))
      DUNE_PYMOR_THROW(Exception::index_out_of_range,
                       "the condition 0 < " << qq << " < num_components() = " << num_components_
                       << " is not satisfied!");
    return components_[qq];
  }

  std::shared_ptr< const ParameterFunctional > coefficient(const int qq) const throw (Exception::requirements_not_met,
                                                                                Exception::index_out_of_range)
  {
    if (num_components_ == 0)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call coefficient(" << qq << ") if num_components() == 0!");
    if (qq < 0 || qq >= int(num_components_))
      DUNE_PYMOR_THROW(Exception::index_out_of_range,
                       "the condition 0 < " << qq << " < num_components() = " << num_components_
                       << " is not satisfied!");
    return coefficients_[qq];
  }

  ContainerType freeze_parameter(const Parameter mu = Parameter()) const throw (Exception::wrong_parameter_type,
                                                                                Exception::requirements_not_met)
  {
    if (mu.type() != parameter_type())
      DUNE_PYMOR_THROW(Exception::wrong_parameter_type,
                       "the type of mu (" << mu.type() << ") does not match the parameter_type of this ("
                       << parameter_type() << ")!");
    if (num_components_ == 0 && !hasAffinePart_)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                 "do not call freeze_parameter() if num_components() == 0 and has_affine_part() == false!");
    if (components_.size() != num_components_) DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense, "");
    if (coefficients_.size() != num_components_) DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense, "");
    if (hasAffinePart_) {
      ContainerType result = affinePart_->copy();
      if (num_components_ > 0)
        for (unsigned int ii = 0; ii < num_components_; ++ii) {
          const Parameter muCoefficient = map_parameter(mu, "coefficient_" + Dune::Stuff::Common::toString(ii));
          result.axpy(coefficients_[ii]->evaluate(muCoefficient), *(components_[ii]));
        }
      return result;
    } else {
      ContainerType result = components_[0]->copy();
      const Parameter muCoefficient0 = map_parameter(mu, "coefficient_0");
      result.scal(coefficients_[0]->evaluate(muCoefficient0));
      for (unsigned int ii = 1; ii < num_components_; ++ii) {
        const Parameter muCoefficient = map_parameter(mu, "coefficient_" + Dune::Stuff::Common::toString(ii));
        result.axpy(coefficients_[ii]->evaluate(muCoefficient), *(components_[ii]));
      }
      return result;
    }
  }

private:
  bool hasAffinePart_;
  unsigned int num_components_;
  std::vector< std::shared_ptr< const ContainerType > > components_;
  std::vector< std::shared_ptr< const ParameterFunctional > > coefficients_;
  std::shared_ptr< const ContainerType > affinePart_;
}; // class AffinelyDecomposedConstContainer

template< class ContainerImp >
class AffinelyDecomposedContainer
  : public AffinelyDecomposedConstContainer< ContainerImp >
{
  typedef AffinelyDecomposedConstContainer< ContainerImp > BaseType;
public:
  typedef ContainerImp                        ContainerType;

  AffinelyDecomposedContainer()
    : BaseType()
  {}

  /**
   * \attention This class takes ownership of aff_ptr!
   */
  AffinelyDecomposedContainer(ContainerType* aff_ptr)
    : BaseType()
    , affinePart_(aff_ptr)
  {
    BaseType::register_affine_part(affinePart_);
  }

  AffinelyDecomposedContainer(std::shared_ptr< ContainerType > aff_ptr)
    : BaseType()
    , affinePart_(aff_ptr)
  {
    BaseType::register_affine_part(affinePart_);
  }

  /**
   * \attention This class takes ownership of aff_ptr!
   */
  AffinelyDecomposedContainer(ContainerType* comp_ptr, const ParameterFunctional* coeff_ptr)
    : BaseType()
  {
    components_.emplace_back(comp_ptr);
    BaseType::register_component(components_[0], std::shared_ptr< const ParameterFunctional >(coeff_ptr));
  }

  AffinelyDecomposedContainer(std::shared_ptr< ContainerType > comp_ptr, const ParameterFunctional* coeff_ptr)
    : BaseType()
  {
    components_.push_back(comp_ptr);
    BaseType::register_component(components_[0], std::shared_ptr< const ParameterFunctional >(coeff_ptr));
  }

  AffinelyDecomposedContainer(ContainerType* comp_ptr, const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    : BaseType()
  {
    components_.emplace_back(comp_ptr);
    BaseType::register_component(components_[0], coeff_ptr);
  }

  AffinelyDecomposedContainer(std::shared_ptr< ContainerType > comp_ptr,
                              const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    : BaseType()
  {
    components_.push_back(comp_ptr);
    BaseType::register_component(components_[0], coeff_ptr);
  }

  /**
   * \attention This class takes ownership of aff_ptr!
   */
  void register_affine_part(ContainerType* aff_ptr) throw (Exception::this_does_not_make_any_sense,
                                                           Exception::sizes_do_not_match)
  {
    affinePart_ = std::shared_ptr< ContainerType >(aff_ptr);
    BaseType::register_affine_part(affinePart_);
  }

  void register_affine_part(std::shared_ptr< ContainerType > aff_ptr) throw (Exception::this_does_not_make_any_sense,
                                                                             Exception::sizes_do_not_match)
  {
    affinePart_ = aff_ptr;
    BaseType::register_affine_part(affinePart_);
  }

  void register_component(ContainerType* comp_ptr,
                          const ParameterFunctional* coeff_ptr) throw (Exception::sizes_do_not_match)
  {
    register_component(std::shared_ptr< ContainerType >(comp_ptr),
                       std::shared_ptr< const ParameterFunctional >(coeff_ptr));
  }

  /**
   * \attention This class takes ownership of comp_ptr!
   */
  void register_component(ContainerType* comp_ptr,
                          const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    throw (Exception::sizes_do_not_match)
  {
    register_component(std::shared_ptr< ContainerType >(comp_ptr), coeff_ptr);
  }

  /**
   * \attention This class takes ownership of coeff_ptr!
   */
  void register_component(std::shared_ptr< ContainerType > comp_ptr,
                          const ParameterFunctional* coeff_ptr) throw (Exception::sizes_do_not_match)
  {
    register_component(comp_ptr, std::shared_ptr< const ParameterFunctional >(coeff_ptr));
  }

  void register_component(std::shared_ptr< ContainerType > comp_ptr,
                          const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    throw (Exception::sizes_do_not_match)
  {
    components_.push_back(comp_ptr);
    BaseType::register_component(comp_ptr, coeff_ptr);
  }

  std::shared_ptr< ContainerType > affine_part() const throw (Exception::requirements_not_met)
  {
    if (!BaseType::has_affine_part())
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call affine_part() if has_affine_part() == false!");
    return affinePart_;
  }

  std::shared_ptr< ContainerType > component(const int qq) throw (Exception::requirements_not_met,
                                                                  Exception::index_out_of_range)
  {
    if (BaseType::num_components() == 0)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call component(" << qq << ") if num_components() == 0!");
    if (qq < 0 || qq >= int(BaseType::num_components()))
      DUNE_PYMOR_THROW(Exception::index_out_of_range,
                       "the condition 0 < " << qq << " < num_components() = " << BaseType::num_components()
                       << " is not satisfied!");
    return components_[qq];
  }

private:
  std::vector< std::shared_ptr< ContainerType > > components_;
  std::shared_ptr< ContainerType > affinePart_;
}; // class AffinelyDecomposedContainer

} // namespace LA
} // namespace Pymor
} // namespace Dune

#endif // DUNE_PYMOR_LA_CONTAINER_AFFINE_HH
<commit_msg>[la.container.affine] return current index<commit_after>// This file is part of the dune-pymor project:
//   https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_PYMOR_LA_CONTAINER_AFFINE_HH
#define DUNE_PYMOR_LA_CONTAINER_AFFINE_HH

#include <memory>
#include <vector>
#include <type_traits>

#include <dune/stuff/common/string.hh>

#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/parameters/functional.hh>
#include "interfaces.hh"

namespace Dune {
namespace Pymor {
namespace LA {

template< class ContainerImp >
class AffinelyDecomposedConstContainer
  : public Parametric
{
  static_assert(std::is_base_of< ContainerInterface< typename ContainerImp::Traits >, ContainerImp >::value,
                "ContainerType must be derived from ContainerInterface");
public:
  typedef ContainerImp                        ContainerType;

  AffinelyDecomposedConstContainer()
    : hasAffinePart_(false)
    , num_components_(0)
  {}

  /**
   * \attention This class takes ownership of aff_ptr (in the sense, that you must not delete it manually)!
   */
  AffinelyDecomposedConstContainer(const ContainerType* aff_ptr)
    : hasAffinePart_(true)
    , num_components_(0)
    , affinePart_(aff_ptr)
  {}

  AffinelyDecomposedConstContainer(const std::shared_ptr< const ContainerType > aff_ptr)
    : hasAffinePart_(true)
    , num_components_(0)
    , affinePart_(aff_ptr)
  {}

  /**
   * \attention This class takes ownership of comp_ptr and coeff_ptr (in the sense, that you must not delete it manually)!
   */
  AffinelyDecomposedConstContainer(const ContainerType* comp_ptr, const ParameterFunctional* coeff_ptr)
    : hasAffinePart_(false)
    , num_components_(1)
  {
    components_.emplace_back(comp_ptr);
    coefficients_.emplace_back(coeff_ptr);
    inherit_parameter_type(coeff_ptr->parameter_type(), "coefficient_0");
  }

  /**
   * \attention This class takes ownership of coeff_ptr (in the sense, that you must not delete it manually)!
   */
  AffinelyDecomposedConstContainer(const std::shared_ptr< const ContainerType > comp_ptr,
                                   const ParameterFunctional* coeff_ptr)
    : hasAffinePart_(false)
    , num_components_(1)
  {
    components_.push_back(comp_ptr);
    coefficients_.emplace_back(coeff_ptr);
    inherit_parameter_type(coeff_ptr->parameter_type(), "coefficient_0");
  }

  /**
   * \attention This class takes ownership of comp_ptr (in the sense, that you must not delete it manually)!
   */
  AffinelyDecomposedConstContainer(const ContainerType* comp_ptr,
                                   const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    : hasAffinePart_(false)
    , num_components_(1)
  {
    components_.emplace_back(comp_ptr);
    coefficients_.push_back(coeff_ptr);
    inherit_parameter_type(coeff_ptr->parameter_type(), "coefficient_0");
  }

  AffinelyDecomposedConstContainer(const std::shared_ptr< const ContainerType > comp_ptr,
                                   const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    : hasAffinePart_(false)
    , num_components_(1)
  {
    components_.push_back(comp_ptr);
    coefficients_.push_back(coeff_ptr);
    inherit_parameter_type(coeff_ptr->parameter_type(), "coefficient_0");
  }

  bool has_affine_part() const
  {
    return hasAffinePart_;
  }

  unsigned int num_components() const
  {
    return num_components_;
  }

  /**
   * \attention This class takes ownership of aff_ptr (in the sense, that you must not delete it manually)!
   */
  void register_affine_part(const ContainerType* aff_ptr) throw (Exception::this_does_not_make_any_sense,
                                                                 Exception::sizes_do_not_match)
  {
    register_affine_part(std::shared_ptr< const ContainerType >(aff_ptr));
  }

  void register_affine_part(const std::shared_ptr< const ContainerType > aff_ptr)
    throw (Exception::this_does_not_make_any_sense, Exception::sizes_do_not_match)
  {
    if (hasAffinePart_)
      DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense,
                       "do not call register_affine_part(aff_ptr) if has_affine_part() == true!");
    if (num_components_ > 0 && !components_[0]->has_equal_shape(*aff_ptr))
      DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                       "the shape of aff_ptr does not match the shape of the existing containers!");
    affinePart_ = aff_ptr;
    hasAffinePart_ = true;
  }

  /**
   * \attention This class takes ownership of comp_ptr and coeff_ptr (in the sense, that you must not delete it manually)!
   */
  unsigned int register_component(const ContainerType* comp_ptr,
                                  const ParameterFunctional* coeff_ptr) throw (Exception::sizes_do_not_match)
  {
    return register_component(std::shared_ptr< const ContainerType >(comp_ptr),
                              std::shared_ptr< const ParameterFunctional >(coeff_ptr));
  }

  /**
   * \attention This class takes ownership of comp_ptr (in the sense, that you must not delete it manually)!
   */
  unsigned int register_component(const ContainerType* comp_ptr,
                                  const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    throw (Exception::sizes_do_not_match)
  {
    return register_component(std::shared_ptr< const ContainerType >(comp_ptr), coeff_ptr);
  }

  /**
   * \attention This class takes ownership of coeff_ptr (in the sense, that you must not delete it manually)!
   */
  unsigned int register_component(const std::shared_ptr< const ContainerType > comp_ptr,
                                  const ParameterFunctional* coeff_ptr) throw (Exception::sizes_do_not_match)
  {
    return register_component(comp_ptr, std::shared_ptr< const ParameterFunctional >(coeff_ptr));
  }

  unsigned int register_component(const std::shared_ptr< const ContainerType > comp_ptr,
                                  const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    throw (Exception::sizes_do_not_match)
  {
    if (hasAffinePart_) {
      if (!affinePart_->has_equal_shape(*comp_ptr))
        DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                         "the shape of comp_ptr does not match the shape of the existing containers!");
    } else if (num_components_ > 0)
      if (!components_[0]->has_equal_shape(*comp_ptr))
        DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                         "the shape of aff_ptr does not match the shape of the existing components!");
    components_.push_back(comp_ptr);
    coefficients_.push_back(coeff_ptr);
    inherit_parameter_type(coeff_ptr->parameter_type(), "coefficient_" + Dune::Stuff::Common::toString(num_components_));
    ++num_components_;
    return num_components_ - 1;
  }

  std::shared_ptr< const ContainerType > affine_part() const throw (Exception::requirements_not_met)
  {
    if (!hasAffinePart_)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call affine_part() if has_affine_part() == false!");
    return affinePart_;
  }

  std::shared_ptr< const ContainerType > component(const int qq) const throw (Exception::requirements_not_met,
                                                                              Exception::index_out_of_range)
  {
    if (num_components_ == 0)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call component(" << qq << ") if num_components() == 0!");
    if (qq < 0 || qq >= int(num_components_))
      DUNE_PYMOR_THROW(Exception::index_out_of_range,
                       "the condition 0 < " << qq << " < num_components() = " << num_components_
                       << " is not satisfied!");
    return components_[qq];
  }

  std::shared_ptr< const ParameterFunctional > coefficient(const int qq) const throw (Exception::requirements_not_met,
                                                                                Exception::index_out_of_range)
  {
    if (num_components_ == 0)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call coefficient(" << qq << ") if num_components() == 0!");
    if (qq < 0 || qq >= int(num_components_))
      DUNE_PYMOR_THROW(Exception::index_out_of_range,
                       "the condition 0 < " << qq << " < num_components() = " << num_components_
                       << " is not satisfied!");
    return coefficients_[qq];
  }

  ContainerType freeze_parameter(const Parameter mu = Parameter()) const throw (Exception::wrong_parameter_type,
                                                                                Exception::requirements_not_met)
  {
    if (mu.type() != parameter_type())
      DUNE_PYMOR_THROW(Exception::wrong_parameter_type,
                       "the type of mu (" << mu.type() << ") does not match the parameter_type of this ("
                       << parameter_type() << ")!");
    if (num_components_ == 0 && !hasAffinePart_)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                 "do not call freeze_parameter() if num_components() == 0 and has_affine_part() == false!");
    if (components_.size() != num_components_) DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense, "");
    if (coefficients_.size() != num_components_) DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense, "");
    if (hasAffinePart_) {
      ContainerType result = affinePart_->copy();
      if (num_components_ > 0)
        for (unsigned int ii = 0; ii < num_components_; ++ii) {
          const Parameter muCoefficient = map_parameter(mu, "coefficient_" + Dune::Stuff::Common::toString(ii));
          result.axpy(coefficients_[ii]->evaluate(muCoefficient), *(components_[ii]));
        }
      return result;
    } else {
      ContainerType result = components_[0]->copy();
      const Parameter muCoefficient0 = map_parameter(mu, "coefficient_0");
      result.scal(coefficients_[0]->evaluate(muCoefficient0));
      for (unsigned int ii = 1; ii < num_components_; ++ii) {
        const Parameter muCoefficient = map_parameter(mu, "coefficient_" + Dune::Stuff::Common::toString(ii));
        result.axpy(coefficients_[ii]->evaluate(muCoefficient), *(components_[ii]));
      }
      return result;
    }
  }

private:
  bool hasAffinePart_;
  unsigned int num_components_;
  std::vector< std::shared_ptr< const ContainerType > > components_;
  std::vector< std::shared_ptr< const ParameterFunctional > > coefficients_;
  std::shared_ptr< const ContainerType > affinePart_;
}; // class AffinelyDecomposedConstContainer

template< class ContainerImp >
class AffinelyDecomposedContainer
  : public AffinelyDecomposedConstContainer< ContainerImp >
{
  typedef AffinelyDecomposedConstContainer< ContainerImp > BaseType;
public:
  typedef ContainerImp                        ContainerType;

  AffinelyDecomposedContainer()
    : BaseType()
  {}

  /**
   * \attention This class takes ownership of aff_ptr!
   */
  AffinelyDecomposedContainer(ContainerType* aff_ptr)
    : BaseType()
    , affinePart_(aff_ptr)
  {
    BaseType::register_affine_part(affinePart_);
  }

  AffinelyDecomposedContainer(std::shared_ptr< ContainerType > aff_ptr)
    : BaseType()
    , affinePart_(aff_ptr)
  {
    BaseType::register_affine_part(affinePart_);
  }

  /**
   * \attention This class takes ownership of aff_ptr!
   */
  AffinelyDecomposedContainer(ContainerType* comp_ptr, const ParameterFunctional* coeff_ptr)
    : BaseType()
  {
    components_.emplace_back(comp_ptr);
    BaseType::register_component(components_[0], std::shared_ptr< const ParameterFunctional >(coeff_ptr));
  }

  AffinelyDecomposedContainer(std::shared_ptr< ContainerType > comp_ptr, const ParameterFunctional* coeff_ptr)
    : BaseType()
  {
    components_.push_back(comp_ptr);
    BaseType::register_component(components_[0], std::shared_ptr< const ParameterFunctional >(coeff_ptr));
  }

  AffinelyDecomposedContainer(ContainerType* comp_ptr, const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    : BaseType()
  {
    components_.emplace_back(comp_ptr);
    BaseType::register_component(components_[0], coeff_ptr);
  }

  AffinelyDecomposedContainer(std::shared_ptr< ContainerType > comp_ptr,
                              const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    : BaseType()
  {
    components_.push_back(comp_ptr);
    BaseType::register_component(components_[0], coeff_ptr);
  }

  /**
   * \attention This class takes ownership of aff_ptr!
   */
  void register_affine_part(ContainerType* aff_ptr) throw (Exception::this_does_not_make_any_sense,
                                                           Exception::sizes_do_not_match)
  {
    affinePart_ = std::shared_ptr< ContainerType >(aff_ptr);
    BaseType::register_affine_part(affinePart_);
  }

  void register_affine_part(std::shared_ptr< ContainerType > aff_ptr) throw (Exception::this_does_not_make_any_sense,
                                                                             Exception::sizes_do_not_match)
  {
    affinePart_ = aff_ptr;
    BaseType::register_affine_part(affinePart_);
  }

  unsigned int register_component(ContainerType* comp_ptr,
                                  const ParameterFunctional* coeff_ptr) throw (Exception::sizes_do_not_match)
  {
    return register_component(std::shared_ptr< ContainerType >(comp_ptr),
                              std::shared_ptr< const ParameterFunctional >(coeff_ptr));
  }

  /**
   * \attention This class takes ownership of comp_ptr!
   */
  unsigned int register_component(ContainerType* comp_ptr,
                                  const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    throw (Exception::sizes_do_not_match)
  {
    return register_component(std::shared_ptr< ContainerType >(comp_ptr), coeff_ptr);
  }

  /**
   * \attention This class takes ownership of coeff_ptr!
   */
  unsigned int register_component(std::shared_ptr< ContainerType > comp_ptr,
                                  const ParameterFunctional* coeff_ptr) throw (Exception::sizes_do_not_match)
  {
    return register_component(comp_ptr, std::shared_ptr< const ParameterFunctional >(coeff_ptr));
  }

  unsigned int register_component(std::shared_ptr< ContainerType > comp_ptr,
                                  const std::shared_ptr< const ParameterFunctional > coeff_ptr)
    throw (Exception::sizes_do_not_match)
  {
    components_.push_back(comp_ptr);
    return BaseType::register_component(comp_ptr, coeff_ptr);
  }

  std::shared_ptr< ContainerType > affine_part() const throw (Exception::requirements_not_met)
  {
    if (!BaseType::has_affine_part())
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call affine_part() if has_affine_part() == false!");
    return affinePart_;
  }

  std::shared_ptr< ContainerType > component(const int qq) throw (Exception::requirements_not_met,
                                                                  Exception::index_out_of_range)
  {
    if (BaseType::num_components() == 0)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call component(" << qq << ") if num_components() == 0!");
    if (qq < 0 || qq >= int(BaseType::num_components()))
      DUNE_PYMOR_THROW(Exception::index_out_of_range,
                       "the condition 0 < " << qq << " < num_components() = " << BaseType::num_components()
                       << " is not satisfied!");
    return components_[qq];
  }

private:
  std::vector< std::shared_ptr< ContainerType > > components_;
  std::shared_ptr< ContainerType > affinePart_;
}; // class AffinelyDecomposedContainer

} // namespace LA
} // namespace Pymor
} // namespace Dune

#endif // DUNE_PYMOR_LA_CONTAINER_AFFINE_HH
<|endoftext|>