<commit_before>#include <DrawingAlgoApp.h>

#include <algorithm>
#include <fstream>
#include <sstream>

#include <SFML/OpenGL.hpp>

// signum function
template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

//
// Pixel struct definition
DrawingAlgoApp::Pixel::Pixel()
    : R(0), G(0), B(0)
{}

DrawingAlgoApp::Pixel::Pixel(uint R, uint G, uint B)
    : R(R), G(G), B(B)
{}

DrawingAlgoApp::Pixel::Pixel(uint hex) {
    R = (hex & 0xFF0000) >> 2*8;
    G = (hex & 0x00FF00) >> 8;
    B = hex & 0x0000FF;
}

//
// DrawingAlgoApp class definition
DrawingAlgoApp::DrawingAlgoApp()
    : Super(800u, 600u, "Drawing Algorithms", sf::Style::Close),
    _num_pixels(_width*_height),
    _draw_type(DrawingType::None),
    _mouse_pos_cache(0, 0)
{
    _pixel_data.reset(new Pixel[_width*_height]);

    ClearPixelData();
}

DrawingAlgoApp::~DrawingAlgoApp()
{}

//
// render loop events
bool DrawingAlgoApp::OnInit() {
    if (!Super::OnInit())
        return false;

    // adjusting help text
    const auto append_text = R"(
C = Clear Pixelbuffer
X = Capture Screen
Modes:
1 = None
2 = Line
3 = Circle
4 = Bezier
)";

    auto help = _help_text.getString();
    help.insert(help.getSize(), append_text);
    _help_text.setString(help);

    // Set the screen color for clearing
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // rgba

    return true;
}

void DrawingAlgoApp::OnRender() {
    // render the pixel buffer
    RenderPixelArray();

    // render "HUD"
    Super::RenderHelpText();
    Super::RenderFPS();
    Super::RenderMousePos();
}

//
// drawing helper
void DrawingAlgoApp::SetPixel(uint x, uint y, const Pixel &pix) {
    if (x >= _width || y >= _height)
        return;

    auto idx = (_height - 1 - y) * _width + x;
    idx = std::min(idx, _num_pixels-1);

    auto size = sizeof(pix);
    memcpy(&_pixel_data[idx], &pix, size);
}

void DrawingAlgoApp::ClearPixelData() {
    memset(_pixel_data.get(), 0, sizeof(Pixel)*_width*_height);
}

void DrawingAlgoApp::RenderPixelArray() {
    // draw pixel data
    glDrawPixels(_width, _height, GL_RGB, GL_UNSIGNED_BYTE, _pixel_data.get());

    // Flush drawing commands
    glFlush();
}

void DrawingAlgoApp::SaveAsPPM(const char* filename) {
    using std::endl;

    const auto magic_number = "P6";
    const auto bytes_per_pixel = 3;

    std::stringstream ss;
    ss << _width;
    const auto width = ss.str();

    ss = std::stringstream();
    ss << _height;
    const auto height = ss.str();

    ss = std::stringstream();
    ss << 255;
    const auto max_color = ss.str();

    std::ofstream out(filename);
    out << magic_number << endl;
    out << width << " " << height << endl;
    out << max_color << "\n";

    for (auto h = 0U; h < _height; ++h) {
        for (auto w = 0U; w < _width; ++w) {
             auto& pix = _pixel_data[(_height - h - 1)*_width + w];
             out << pix.G << pix.B << pix.R;
        }
    }
}

//
// drawing algorithms
void DrawingAlgoApp::DrawLineBresenham(uint x1, uint y1, uint x2, uint y2, const Pixel& pix) {
    // Startpunkt
    int x = x1, y = y1;

    int dx = x2 - x1;
    int dy = y2 - y1;

    // Schrittrichtung fr Diagonalschritt ermitteln (sgn liefert -1, 0, 1)
    int diagonal_dx = sgn(dx);
    int diagonal_dy = sgn(dy);

    int errSR, errLR;               // Fehleranpassung in schneller Richtung (SR) und langsamer Richtung (LR)
    int parallel_dx, parallel_dy;   // Schrittweite fr Parallelschritt
    int num_elements;               // Anzahl zu zeichnender Pixel

    // Unterscheidung zwischen schneller und langsamer Richtung
    if (std::abs(dx) > std::abs(dy)) {
        // x ist schnelle Richtung, d.h. mache keinen Schritt in y-Richtung bei Parallelschritt
        parallel_dx = diagonal_dx;
        parallel_dy = 0;
        errSR = std::abs(dx)*2;
        errLR = std::abs(dy)*2;
        num_elements = std::abs(dx);    // Anzahl zu zeichnender Pixel in schneller Richtung
    } else {
        // y ist schnelle Richtung, d.h. mache keinen Schritt in x-Richtung bei Parallelschritt
        parallel_dx = 0;
        parallel_dy = diagonal_dy;
        errSR = std::abs(dy)*2;
        errLR = std::abs(dx)*2;
        num_elements = std::abs(dy);    // Anzahl zu zeichnender Pixel in schneller Richtung
    }

    // Fehlervariable initialisieren
    int error = errLR - num_elements;

    for (int i = 0; i < num_elements; ++i) {
        SetPixel(x, y, pix);

        // Fehlervariable aktualisieren (Schritt in schneller Richtung)
        error += errLR;
        if(error <= 0) {
            // Nur Schritt in schnelle Richtung (nur parallel)
            x += parallel_dx;
            y += parallel_dy;
        }
        else {
            // Schritt in langsame und schnelle Richtung (diagonal)
            x += diagonal_dx;
            y += diagonal_dy;

            // Fehlervariable aktualisieren (Schritt in langsamer Richtung)
            error -= errSR;
        }
    }
}

void DrawingAlgoApp::DrawLineMidpoint(uint x1, uint y1, uint x2, uint y2, const Pixel& pix) {
    int x = x1;
    int y = y1;
    int dx = x2 - x1;
    int dy = y2 - y1;
    int f = dy - dx/2;

    // immer Schritt in schnelle Richtung, gelegentlich in langsame Richtung
    for (int i = 1; i <= dx; ++i) {
        SetPixel(x, y, pix);
        x++;
        if (f > 0) {
            y += 1;
            f -= dx; }
        f += dy;
    }
}

void DrawingAlgoApp::DrawCircle(uint posx, uint posy, uint radius, const Pixel& pix) {
    int x1 = 0;
    int y1 = radius;
    int f  = 1 - radius;
    int dx = 3;
    int dy = 2 - 2*radius;

    while(x1 <= y1) {
        // drawing each possible arc
        SetPixel(posx+x1, posy-y1, pix);
        SetPixel(posx+x1, posy+y1, pix);
        SetPixel(posx-x1, posy-y1, pix);
        SetPixel(posx-x1, posy+y1, pix);
        SetPixel(posx+y1, posy-x1, pix);
        SetPixel(posx+y1, posy+x1, pix);
        SetPixel(posx-y1, posy-x1, pix);
        SetPixel(posx-y1, posy+x1, pix);

        x1++;
        if(f > 0) {
            y1--;
            f  += dy;
            dy += 2;
        }
        f  += dx;
        dx +=2;
    }
}

void DrawingAlgoApp::DrawBezier(const std::vector<Point2D>& support_points) {
    const auto t_stepsize = .01f;
    const auto size = support_points.size();

    // TODO: rasterize curve
    std::vector<Point2D> points;

    if (size < 2U)
        return;

    std::unique_ptr<std::unique_ptr<Point2D[]>[]> b(new std::unique_ptr<Point2D[]>[size]);
    for (auto i = 0U; i < size; ++i)
        b[i].reset(new Point2D[size]);

    for (float t = .0f; t <= 1.f; t += t_stepsize) {
        // de Casteljau algorithm
        // for i = 0 .. n
        for (auto i = 0u; i < size; ++i) {
            //    b(i,0) = bi
            b[i][0] = support_points[i];
        }

        // for j = 1 .. n
        for (auto j = 1u; j < size; ++j) {
            // for i = j .. n
            for (auto i = j; i < size; ++i) {
                // b(i,j) = (1-t) * b(i-1,j-1) + t * b(i,j-1)
                b[i][j] = (1.f - t) * b[i-1][j-1] + t * b[i][j-1];
            }
        }

        // p(t) = b(n,n)
        points.push_back(b[size-1][size-1]);
    }

    // render support points in red
    for (auto& p: support_points) {
        DrawCircle(static_cast<uint>(p.x), static_cast<uint>(p.y), 1, Pixel(0xFF0000));
    }

    // render curve
    auto p0 = *points.cbegin();
    for (auto it = points.cbegin() + 1; it != points.cend(); ++it) {
        auto& p1 = *it;

        DrawLineBresenham(static_cast<uint>(p0.x),
                          static_cast<uint>(p0.y),
                          static_cast<uint>(p1.x),
                          static_cast<uint>(p1.y));

        p0 = p1;
    }

}

//
// event handler
void DrawingAlgoApp::OnKeyReleased(sf::Keyboard::Key key, bool ctrl, bool alt, bool shift, bool system) {
    typedef sf::Keyboard::Key Key;

    // key 'h' and 'f' are handled by SFMLApp
    Super::OnKeyReleased(key, ctrl, alt, shift, system);

    switch (key) {
    case Key::C:
        ClearPixelData();

        // clear bezier points
        _bezier_points.clear();
        break;
    case Key::X:
        SaveAsPPM();
        break;
    case Key::Num1:
        _draw_type = DrawingType::None;
        break;
    case Key::Num2:
        _draw_type = DrawingType::Line;
        break;
    case Key::Num3:
        _draw_type = DrawingType::Circle;
        break;
    case Key::Num4:
        _draw_type = DrawingType::Bezier;
        break;
    }
}

void DrawingAlgoApp::OnMouseButtonPressed(sf::Mouse::Button button, int x, int y) {
    _mouse_pos_cache.x = x;
    _mouse_pos_cache.y = y;
}

void DrawingAlgoApp::OnMouseButtonReleased(sf::Mouse::Button button, int x, int y) {
    auto& cachex = _mouse_pos_cache.x;
    auto& cachey = _mouse_pos_cache.y;

    switch (_draw_type) {
    case DrawingType::Line:
        DrawLineBresenham(cachex, cachey, x, y);
        break;
    case DrawingType::Circle:
        {
            // calc distance between cache and current point
            auto dx = cachex - x;
            auto dy = cachey - y;
            auto radius = std::sqrt(dx*dx + dy*dy);

            DrawCircle(cachex, cachey, static_cast<int>(radius));
        }
        break;
    case DrawingType::Bezier:
        // add point to support_points!
        _bezier_points.push_back(Point2D(cachex, cachey));

        // clear pixeldata
        ClearPixelData();

        // render bezier
        DrawBezier(_bezier_points);
        break;
    }
}<commit_msg>converted encoding to UTF8 without BOM<commit_after>#include <DrawingAlgoApp.h>

#include <algorithm>
#include <fstream>
#include <sstream>

#include <SFML/OpenGL.hpp>

// signum function
template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

//
// Pixel struct definition
DrawingAlgoApp::Pixel::Pixel()
    : R(0), G(0), B(0)
{}

DrawingAlgoApp::Pixel::Pixel(uint R, uint G, uint B)
    : R(R), G(G), B(B)
{}

DrawingAlgoApp::Pixel::Pixel(uint hex) {
    R = (hex & 0xFF0000) >> 2*8;
    G = (hex & 0x00FF00) >> 8;
    B = hex & 0x0000FF;
}

//
// DrawingAlgoApp class definition
DrawingAlgoApp::DrawingAlgoApp()
    : Super(800u, 600u, "Drawing Algorithms", sf::Style::Close),
    _num_pixels(_width*_height),
    _draw_type(DrawingType::None),
    _mouse_pos_cache(0, 0)
{
    _pixel_data.reset(new Pixel[_width*_height]);

    ClearPixelData();
}

DrawingAlgoApp::~DrawingAlgoApp()
{}

//
// render loop events
bool DrawingAlgoApp::OnInit() {
    if (!Super::OnInit())
        return false;

    // adjusting help text
    const auto append_text = R"(
C = Clear Pixelbuffer
X = Capture Screen
Modes:
1 = None
2 = Line
3 = Circle
4 = Bezier
)";

    auto help = _help_text.getString();
    help.insert(help.getSize(), append_text);
    _help_text.setString(help);

    // Set the screen color for clearing
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // rgba

    return true;
}

void DrawingAlgoApp::OnRender() {
    // render the pixel buffer
    RenderPixelArray();

    // render "HUD"
    Super::RenderHelpText();
    Super::RenderFPS();
    Super::RenderMousePos();
}

//
// drawing helper
void DrawingAlgoApp::SetPixel(uint x, uint y, const Pixel &pix) {
    if (x >= _width || y >= _height)
        return;

    auto idx = (_height - 1 - y) * _width + x;
    idx = std::min(idx, _num_pixels-1);

    auto size = sizeof(pix);
    memcpy(&_pixel_data[idx], &pix, size);
}

void DrawingAlgoApp::ClearPixelData() {
    memset(_pixel_data.get(), 0, sizeof(Pixel)*_width*_height);
}

void DrawingAlgoApp::RenderPixelArray() {
    // draw pixel data
    glDrawPixels(_width, _height, GL_RGB, GL_UNSIGNED_BYTE, _pixel_data.get());

    // Flush drawing commands
    glFlush();
}

void DrawingAlgoApp::SaveAsPPM(const char* filename) {
    using std::endl;

    const auto magic_number = "P6";
    const auto bytes_per_pixel = 3;

    std::stringstream ss;
    ss << _width;
    const auto width = ss.str();

    ss = std::stringstream();
    ss << _height;
    const auto height = ss.str();

    ss = std::stringstream();
    ss << 255;
    const auto max_color = ss.str();

    std::ofstream out(filename);
    out << magic_number << endl;
    out << width << " " << height << endl;
    out << max_color << "\n";

    for (auto h = 0U; h < _height; ++h) {
        for (auto w = 0U; w < _width; ++w) {
             auto& pix = _pixel_data[(_height - h - 1)*_width + w];
             out << pix.G << pix.B << pix.R;
        }
    }
}

//
// drawing algorithms
void DrawingAlgoApp::DrawLineBresenham(uint x1, uint y1, uint x2, uint y2, const Pixel& pix) {
    // Startpunkt
    int x = x1, y = y1;

    int dx = x2 - x1;
    int dy = y2 - y1;

    // Schrittrichtung für Diagonalschritt ermitteln (sgn liefert -1, 0, 1)
    int diagonal_dx = sgn(dx);
    int diagonal_dy = sgn(dy);

    int errSR, errLR;               // Fehleranpassung in schneller Richtung (SR) und langsamer Richtung (LR)
    int parallel_dx, parallel_dy;   // Schrittweite für Parallelschritt
    int num_elements;               // Anzahl zu zeichnender Pixel

    // Unterscheidung zwischen schneller und langsamer Richtung
    if (std::abs(dx) > std::abs(dy)) {
        // x ist schnelle Richtung, d.h. mache keinen Schritt in y-Richtung bei Parallelschritt
        parallel_dx = diagonal_dx;
        parallel_dy = 0;
        errSR = std::abs(dx)*2;
        errLR = std::abs(dy)*2;
        num_elements = std::abs(dx);    // Anzahl zu zeichnender Pixel in schneller Richtung
    } else {
        // y ist schnelle Richtung, d.h. mache keinen Schritt in x-Richtung bei Parallelschritt
        parallel_dx = 0;
        parallel_dy = diagonal_dy;
        errSR = std::abs(dy)*2;
        errLR = std::abs(dx)*2;
        num_elements = std::abs(dy);    // Anzahl zu zeichnender Pixel in schneller Richtung
    }

    // Fehlervariable initialisieren
    int error = errLR - num_elements;

    for (int i = 0; i < num_elements; ++i) {
        SetPixel(x, y, pix);

        // Fehlervariable aktualisieren (Schritt in schneller Richtung)
        error += errLR;
        if(error <= 0) {
            // Nur Schritt in schnelle Richtung (nur parallel)
            x += parallel_dx;
            y += parallel_dy;
        }
        else {
            // Schritt in langsame und schnelle Richtung (diagonal)
            x += diagonal_dx;
            y += diagonal_dy;

            // Fehlervariable aktualisieren (Schritt in langsamer Richtung)
            error -= errSR;
        }
    }
}

void DrawingAlgoApp::DrawLineMidpoint(uint x1, uint y1, uint x2, uint y2, const Pixel& pix) {
    int x = x1;
    int y = y1;
    int dx = x2 - x1;
    int dy = y2 - y1;
    int f = dy - dx/2;

    // immer Schritt in schnelle Richtung, gelegentlich in langsame Richtung
    for (int i = 1; i <= dx; ++i) {
        SetPixel(x, y, pix);
        x++;
        if (f > 0) {
            y += 1;
            f -= dx; }
        f += dy;
    }
}

void DrawingAlgoApp::DrawCircle(uint posx, uint posy, uint radius, const Pixel& pix) {
    int x1 = 0;
    int y1 = radius;
    int f  = 1 - radius;
    int dx = 3;
    int dy = 2 - 2*radius;

    while(x1 <= y1) {
        // drawing each possible arc
        SetPixel(posx+x1, posy-y1, pix);
        SetPixel(posx+x1, posy+y1, pix);
        SetPixel(posx-x1, posy-y1, pix);
        SetPixel(posx-x1, posy+y1, pix);
        SetPixel(posx+y1, posy-x1, pix);
        SetPixel(posx+y1, posy+x1, pix);
        SetPixel(posx-y1, posy-x1, pix);
        SetPixel(posx-y1, posy+x1, pix);

        x1++;
        if(f > 0) {
            y1--;
            f  += dy;
            dy += 2;
        }
        f  += dx;
        dx +=2;
    }
}

void DrawingAlgoApp::DrawBezier(const std::vector<Point2D>& support_points) {
    const auto t_stepsize = .01f;
    const auto size = support_points.size();

    // TODO: rasterize curve
    std::vector<Point2D> points;

    if (size < 2U)
        return;

    std::unique_ptr<std::unique_ptr<Point2D[]>[]> b(new std::unique_ptr<Point2D[]>[size]);
    for (auto i = 0U; i < size; ++i)
        b[i].reset(new Point2D[size]);

    for (float t = .0f; t <= 1.f; t += t_stepsize) {
        // de Casteljau algorithm
        // for i = 0 .. n
        for (auto i = 0u; i < size; ++i) {
            //    b(i,0) = bi
            b[i][0] = support_points[i];
        }

        // for j = 1 .. n
        for (auto j = 1u; j < size; ++j) {
            // for i = j .. n
            for (auto i = j; i < size; ++i) {
                // b(i,j) = (1-t) * b(i-1,j-1) + t * b(i,j-1)
                b[i][j] = (1.f - t) * b[i-1][j-1] + t * b[i][j-1];
            }
        }

        // p(t) = b(n,n)
        points.push_back(b[size-1][size-1]);
    }

    // render support points in red
    for (auto& p: support_points) {
        DrawCircle(static_cast<uint>(p.x), static_cast<uint>(p.y), 1, Pixel(0xFF0000));
    }

    // render curve
    auto p0 = *points.cbegin();
    for (auto it = points.cbegin() + 1; it != points.cend(); ++it) {
        auto& p1 = *it;

        DrawLineBresenham(static_cast<uint>(p0.x),
                          static_cast<uint>(p0.y),
                          static_cast<uint>(p1.x),
                          static_cast<uint>(p1.y));

        p0 = p1;
    }

}

//
// event handler
void DrawingAlgoApp::OnKeyReleased(sf::Keyboard::Key key, bool ctrl, bool alt, bool shift, bool system) {
    typedef sf::Keyboard::Key Key;

    // key 'h' and 'f' are handled by SFMLApp
    Super::OnKeyReleased(key, ctrl, alt, shift, system);

    switch (key) {
    case Key::C:
        ClearPixelData();

        // clear bezier points
        _bezier_points.clear();
        break;
    case Key::X:
        SaveAsPPM();
        break;
    case Key::Num1:
        _draw_type = DrawingType::None;
        break;
    case Key::Num2:
        _draw_type = DrawingType::Line;
        break;
    case Key::Num3:
        _draw_type = DrawingType::Circle;
        break;
    case Key::Num4:
        _draw_type = DrawingType::Bezier;
        break;
    }
}

void DrawingAlgoApp::OnMouseButtonPressed(sf::Mouse::Button button, int x, int y) {
    _mouse_pos_cache.x = x;
    _mouse_pos_cache.y = y;
}

void DrawingAlgoApp::OnMouseButtonReleased(sf::Mouse::Button button, int x, int y) {
    auto& cachex = _mouse_pos_cache.x;
    auto& cachey = _mouse_pos_cache.y;

    switch (_draw_type) {
    case DrawingType::Line:
        DrawLineBresenham(cachex, cachey, x, y);
        break;
    case DrawingType::Circle:
        {
            // calc distance between cache and current point
            auto dx = cachex - x;
            auto dy = cachey - y;
            auto radius = std::sqrt(dx*dx + dy*dy);

            DrawCircle(cachex, cachey, static_cast<int>(radius));
        }
        break;
    case DrawingType::Bezier:
        // add point to support_points!
        _bezier_points.push_back(Point2D(cachex, cachey));

        // clear pixeldata
        ClearPixelData();

        // render bezier
        DrawBezier(_bezier_points);
        break;
    }
}<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

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

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

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

#include "vtkActor.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkSphereSource.h"
#include "vtkUnsignedCharArray.h"

#include <mitkImage.h>
#include <mitkPicFileReader.h>

#include <mitkDataStorage.h>
#include <mitkLevelWindow.h>
#include <mitkLevelWindowProperty.h>

#include <mitkVtkLayerController.h>
#include <mitkVtkPropRenderer.h>
#include <vtkMitkRenderProp.h>

#include <itksys/SystemTools.hxx>

#include <fstream>
int mitkVtkPropRendererTest(int argc, char *argv[])
{
  // independently read header of pic file
  mitkIpPicDescriptor *picheader = nullptr;
  if (argc >= 1)
  {
    if (itksys::SystemTools::LowerCase(itksys::SystemTools::GetFilenameExtension(argv[1])).find(".pic") !=
        std::string::npos)
      picheader = mitkIpPicGetHeader(argv[1], nullptr);
  }
  if (picheader == nullptr)
  {
    std::cout << "file not found/not a pic-file - test not applied [PASSED]" << std::endl;
    std::cout << "[TEST DONE]" << std::endl;
    return EXIT_SUCCESS;
  }

  static long int sum_orig_Pic3D_pic_gz = 14685408;

  mitkIpPicGetTags(argv[1], picheader);

  // Read pic-Image from file
  std::cout << "Reading image: ";
  mitk::PicFileReader::Pointer reader = mitk::PicFileReader::New();
  reader->SetFileName(argv[1]);
  reader->Update();
  std::cout << "[PASSED]" << std::endl;

  mitk::Image::Pointer image = reader->GetOutput();

  std::cout << "Creating node: ";
  mitk::DataNode::Pointer node = mitk::DataNode::New();
  node->SetData(image);
  std::cout << "[PASSED]" << std::endl;

  std::cout << "Creating DataStorage: ";
  mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New();
  std::cout << "[PASSED]" << std::endl;

  std::cout << "Adding node via DataStorage: ";
  ds->Add(node);
  std::cout << "[PASSED]" << std::endl;

  std::cout << "Adding level-window property: ";
  mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New();
  mitk::LevelWindow levelwindow;
  levelwindow.SetAuto(image);
  levWinProp->SetLevelWindow(levelwindow);
  node->GetPropertyList()->SetProperty("levelwindow", levWinProp);
  std::cout << "[PASSED]" << std::endl;

  std::cout << "Creating a vtk sphere: ";
  vtkSphereSource *sphere = vtkSphereSource::New();
  sphere->SetRadius(1.0);
  sphere->SetThetaResolution(18);
  sphere->SetPhiResolution(18);

  vtkPolyDataMapper *map = vtkPolyDataMapper::New();
  map->SetInput(sphere->GetOutput());
  sphere->Delete();

  vtkActor *aSphere = vtkActor::New();
  aSphere->SetMapper(map);
  map->Delete();
  aSphere->GetProperty()->SetColor(0, 0, 1); // sphere color blue
  std::cout << "[PASSED]" << std::endl;

  std::cout << "Creating a renderer for the sphere: ";
  vtkRenderer *sphereRenderer = vtkRenderer::New();
  sphereRenderer->AddActor(aSphere);
  aSphere->Delete();
  // sphereRenderer->SetBackground(1,1,1); // Background color white
  std::cout << "[PASSED]" << std::endl;

  std::cout << "Creating vtkRenderWindow and VtkPropRenderer: ";
  vtkRenderWindow *renderWindow = vtkRenderWindow::New();
  mitk::VtkPropRenderer::Pointer propRenderer = mitk::VtkPropRenderer::New("the renderer", renderWindow);
  // propRenderer->SetMapperID(2);
  std::cout << "[PASSED]" << std::endl;

  // renderWindow->AddRenderer(sphereRenderer);
  // renderWindow->SetErase(0);

  std::cout << "BaseRenderer::SetData(iterator): ";
  propRenderer->SetDataStorage(ds);
  std::cout << "[PASSED]" << std::endl;

  std::cout << "Creating vtkMitkRenderProp and connecting it to the VtkPropRenderer: ";
  vtkMitkRenderProp *renderProp = vtkMitkRenderProp::New();
  renderProp->SetPropRenderer(propRenderer);
  propRenderer->GetVtkRenderer()->AddViewProp(renderProp);
  std::cout << "[PASSED]" << std::endl;

  std::cout << "Inserting the sphere into the foreground of the VtkLayerController: ";
  mitk::VtkLayerController::GetInstance(renderWindow)->InsertForegroundRenderer(sphereRenderer, true);
  std::cout << "[PASSED]" << std::endl;

  // mouse interaction for debugging
  // vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  // iren->SetRenderWindow(renderWindow);

  std::cout << "Setting and getting size of renderWindow: ";
  renderWindow->SetSize(400, 400);
  int *size = renderWindow->GetSize();
  std::cout << "[PASSED]" << std::endl;

  std::cout << "Do the rendering: ";
  renderWindow->Render();
  std::cout << "[PASSED]" << std::endl;

  // iren->Start();

  std::cout << "Testing to pick a world position: ";
  mitk::Point2D p;
  mitk::Point3D p_mm;
  p[0] = 10;
  p[1] = 10;
  propRenderer->PickWorldPoint(p, p_mm);
  std::cout << "returned world position: " << p_mm << "\n";

  std::cout << "Creating vtkUnsignedCharArray: ";
  vtkUnsignedCharArray *vtkImage = vtkUnsignedCharArray::New();
  std::cout << "[PASSED]" << std::endl;

  cout << "Reading image from renderWindow" << std::endl;
  renderWindow->GetRGBACharPixelData(0, 0, size[0] - 1, size[1] - 1, 0, vtkImage);
  cout << "Read " << size[0] * size[1] << " data points\n";

  cout << "Computing sum of all RGBA values..\n";
  long int sum_now = 0;
  for (int i = 0; i < size[0] * size[1]; i++)
    sum_now += vtkImage->GetValue(i);
  std::cout << "Sum of all RGBA values: " << sum_now << "\n";
  std::cout << "Sum should be: " << sum_orig_Pic3D_pic_gz << "\n";

  // std::string Pic3d_pic_gz_str("Pic3D.pic.gz");
  // std::cout << "pic3d " << Pic3d_pic_gz_str << "\n";
  // std::cout << "argv " << argv_str << "\n";
  // std::cout << "find " << (int) argv_str.find("Pic3D.pic.gz") << "\n";
  // std::cout << "size " << argv_str.size() << "\n";

  // if(argv_str.size() - ((int) argv_str.find("Pic3D.pic.gz")) == 12)
  //{
  //  std::cout << "Input image is Pic3D.pic.gz\n";
  //  std::cout << "Sum should be: " << sum_orig_Pic3D_pic_gz << "\n";
  //  if(sum_orig_Pic3D_pic_gz!=sum_now)
  //  {
  //    std::cout<<"[FAILED]"<<std::endl;
  //    return EXIT_FAILURE;
  //  }
  //  std::cout<<"[PASSED]"<<std::endl;
  //}
  // else
  //{
  //  std::cout<<"Unknown image, comparison test skipped"<<std::endl;
  //}

  propRenderer->GetVtkRenderer()->RemoveViewProp(renderProp);
  renderProp->Delete();
  propRenderer = nullptr;
  sphereRenderer->Delete();

  renderWindow->Delete();

  vtkImage->Delete();
  ds = nullptr;

  std::cout << "[TEST DONE]" << std::endl;
  return EXIT_SUCCESS;
}
<commit_msg>Remove dangling test cpp file<commit_after><|endoftext|>


<commit_before>void Pi0SpectrumLHC11h(const char* dataset="collection.xml",
		       bool recompile = false
)
{
  TStopwatch timer;
  timer.Start();

    TStringToken libs("Core,Tree,Geom,VMC,Physics,Minuit,Gui,XMLParser,Minuit2,Proof,STEERBase,ESD,AOD,OADB,ANALYSIS,ANALYSISalice,CDB,RAWDatabase,STEER,CORRFW,PHOSUtils,PHOSbase,PHOSpi0Calib,PHOSrec,PHOSshuttle,PHOSsim,PWGGAPHOSTasks", ",");
  while( libs.NextToken() )
    gSystem->Load( Form("lib%s", libs.Data()) );

  gSystem->Load("libTree.so");
  gSystem->Load("libGeom.so");
  gSystem->Load("libVMC.so");
  gSystem->Load("libPhysics.so");

  //load analysis framework
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice"); //AliAnalysisTaskSE

  gSystem->AddIncludePath("-I$ALICE_ROOT/include -I$ALICE_ROOT/PHOS");

  // A task can be compiled dynamically with AClic
  if( recompile ) {
    gROOT->LoadMacro("AliCaloPhoton.cxx+g");
    gROOT->LoadMacro("AliAnalysisTaskPi0Flow.cxx+g");
  }
  else {
    gSystem->Load("libPWGGAPHOSTasks.so");
  }

  // Connect to alien
  TString token = gSystem->Getenv("GRID_TOKEN") ;
  if (1) // token == "OK" )
    TGrid::Connect("alien://");
  else
    AliInfo("You are not connected to the GRID") ;

  cout << "Pi0Analysis: processing collection " << dataset << endl;

  // Create the chain
  TChain* chain = new TChain("aodTree");

  TGridCollection * collection = dynamic_cast<TGridCollection*>(TAlienCollection::Open(dataset));

  TAlienResult* result = collection->GetGridResult("",0 ,0);
  TList* rawFileList = result->GetFileInfoList();

  for (Int_t counter=0 ; counter < rawFileList->GetEntries() ; counter++) {
    TFileInfo * fi =  static_cast<TFileInfo*>(rawFileList->At(counter)) ;
    const char * rawFile = fi->GetCurrentUrl()->GetUrl() ;
    printf("Processing %s\n", rawFile) ;
    chain->Add(rawFile);
    printf("Chain: %d entries.\n",chain->GetEntriesFast());
  }

  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("Pi0Spectrum");
  mgr->SetCommonFileName("histos.root");

  // AOD input handler
  AliAODInputHandler* aodH = new AliAODInputHandler();
  mgr->SetInputEventHandler(aodH);

  // Debug level
  mgr->SetDebugLevel(999999);

  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskEventplane.C");
  AliEPSelectionTask *taskEP = AddTaskEventplane() ;

  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskVZEROEPSelection.C");
  AliVZEROEPSelectionTask *selTask = AddTaskVZEROEPSelection();

  // Add my task
  AliAnalysisTaskPi0Flow* task;
  if ( recompile ) {
    task = new AliAnalysisTaskPi0Flow("AliAnalysisTaskPi0Flow");
    //task->SetPeriod(AliAnalysisTaskPi0Flow::kLHC11h);
    mgr->AddTask(task);
    mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
    mgr->ConnectOutput(task, 1, mgr->CreateContainer("outCont1", TList::Class(),AliAnalysisManager::kOutputContainer,"output.root"));
  } else {
    gROOT->LoadMacro("$ALICE_ROOT/PWGGA/PHOSTasks/PHOS_PbPb/AddTaskPHOSPi0Flow.C");
    task = AddTaskPHOSPi0Flow();
  }

/*
  TFile *fBadMap = TFile::Open("alien:///alice/cern.ch/user/p/prsnko/BadMaps/BadMap_LHC10h_period1.root");
  //  TFile *fBadMap = TFile::Open("BadMap_LHC10h_period1.root");
  if(fBadMap->IsOpen()){
    printf("\n\n...Adding PHOS bad channel map \n") ;
    gROOT->cd();
    char key[55] ;
    for(Int_t mod=1;mod<4; mod++){
      sprintf(key,"PHOS_BadMap_mod%d",mod) ;
      TH2I * h = (TH2I*)fBadMap->Get(key) ;
      if(h)
        task1->SetPHOSBadMap(mod,h) ;
    }
    fBadMap->Close() ;
  }
*/

  // // Create containers for input/output
  // AliAnalysisDataContainer *cinput   = mgr->GetCommonInputContainer();
  // AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("pi0SpecOut1",TList::Class(),AliAnalysisManager::kOutputContainer,"histos.root");

  // // Connect input/output
  // mgr->ConnectInput(task1 , 0, cinput);
  // mgr->ConnectOutput(task1, 1, coutput1);

  if (mgr->InitAnalysis()) {
    mgr->PrintStatus();
    mgr->StartAnalysis("local", chain);
  }

  timer.Stop();
  timer.Print();
}
<commit_msg>Added AliPHOSEPFlattener recompilation to Pi0SpectrumLHC11h.C,<commit_after>void Pi0SpectrumLHC11h(const char* dataset="collection.xml",
		       bool recompile = true
)
{
  TStopwatch timer;
  timer.Start();

    TStringToken libs("Core,Tree,Geom,VMC,Physics,Minuit,Gui,XMLParser,Minuit2,Proof,STEERBase,ESD,AOD,OADB,ANALYSIS,ANALYSISalice,CDB,RAWDatabase,STEER,CORRFW,PHOSUtils,PHOSbase,PHOSpi0Calib,PHOSrec,PHOSshuttle,PHOSsim,PWGGAPHOSTasks", ",");
  while( libs.NextToken() )
    gSystem->Load( Form("lib%s", libs.Data()) );

  gSystem->Load("libTree.so");
  gSystem->Load("libGeom.so");
  gSystem->Load("libVMC.so");
  gSystem->Load("libPhysics.so");

  //load analysis framework
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice"); //AliAnalysisTaskSE

  gSystem->AddIncludePath("-I$ALICE_ROOT/include -I$ALICE_ROOT/PHOS");

  // A task can be compiled dynamically with AClic
  if( recompile ) {
    gROOT->LoadMacro("AliCaloPhoton.cxx+g");
    gROOT->LoadMacro("AliAnalysisTaskPi0Flow.cxx+g");
    gROOT->LoadMacro("AliPHOSEPFlattener.cxx+g");
  }
  else {
    gSystem->Load("libPWGGAPHOSTasks.so");
  }

  // Connect to alien
  TString token = gSystem->Getenv("GRID_TOKEN") ;
  if (1) // token == "OK" )
    TGrid::Connect("alien://");
  else
    AliInfo("You are not connected to the GRID") ;

  cout << "Pi0Analysis: processing collection " << dataset << endl;

  // Create the chain
  TChain* chain = new TChain("aodTree");

  TGridCollection * collection = dynamic_cast<TGridCollection*>(TAlienCollection::Open(dataset));

  TAlienResult* result = collection->GetGridResult("",0 ,0);
  TList* rawFileList = result->GetFileInfoList();

  for (Int_t counter=0 ; counter < rawFileList->GetEntries() ; counter++) {
    TFileInfo * fi =  static_cast<TFileInfo*>(rawFileList->At(counter)) ;
    const char * rawFile = fi->GetCurrentUrl()->GetUrl() ;
    printf("Processing %s\n", rawFile) ;
    chain->Add(rawFile);
    printf("Chain: %d entries.\n",chain->GetEntriesFast());
  }

  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("Pi0Spectrum");
  mgr->SetCommonFileName("histos.root");

  // AOD input handler
  AliAODInputHandler* aodH = new AliAODInputHandler();
  mgr->SetInputEventHandler(aodH);

  // Debug level
  mgr->SetDebugLevel(999999);

  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskEventplane.C");
  AliEPSelectionTask *taskEP = AddTaskEventplane() ;

  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskVZEROEPSelection.C");
  AliVZEROEPSelectionTask *selTask = AddTaskVZEROEPSelection();

  // Add my task
  AliAnalysisTaskPi0Flow* task;
  if ( recompile ) {
    task = new AliAnalysisTaskPi0Flow("AliAnalysisTaskPi0Flow");
    //task->SetPeriod(AliAnalysisTaskPi0Flow::kLHC11h);
    mgr->AddTask(task);
    mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
    mgr->ConnectOutput(task, 1, mgr->CreateContainer("outCont1", TList::Class(),AliAnalysisManager::kOutputContainer,"output.root"));
  } else {
    gROOT->LoadMacro("$ALICE_ROOT/PWGGA/PHOSTasks/PHOS_PbPb/AddTaskPHOSPi0Flow.C");
    task = AddTaskPHOSPi0Flow();
  }

/*
  TFile *fBadMap = TFile::Open("alien:///alice/cern.ch/user/p/prsnko/BadMaps/BadMap_LHC10h_period1.root");
  //  TFile *fBadMap = TFile::Open("BadMap_LHC10h_period1.root");
  if(fBadMap->IsOpen()){
    printf("\n\n...Adding PHOS bad channel map \n") ;
    gROOT->cd();
    char key[55] ;
    for(Int_t mod=1;mod<4; mod++){
      sprintf(key,"PHOS_BadMap_mod%d",mod) ;
      TH2I * h = (TH2I*)fBadMap->Get(key) ;
      if(h)
        task1->SetPHOSBadMap(mod,h) ;
    }
    fBadMap->Close() ;
  }
*/

  // // Create containers for input/output
  // AliAnalysisDataContainer *cinput   = mgr->GetCommonInputContainer();
  // AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("pi0SpecOut1",TList::Class(),AliAnalysisManager::kOutputContainer,"histos.root");

  // // Connect input/output
  // mgr->ConnectInput(task1 , 0, cinput);
  // mgr->ConnectOutput(task1, 1, coutput1);

  if (mgr->InitAnalysis()) {
    mgr->PrintStatus();
    mgr->StartAnalysis("local", chain);
  }

  timer.Stop();
  timer.Print();
}
<|endoftext|>


<commit_before><commit_msg>ClientAuthOperation: Stop warning on invalid auto requestAuthCode call<commit_after><|endoftext|>


<commit_before>#include <vector>
#include <iostream>
#include <algorithm>

#ifndef REMOVE_VALUES
#ifndef CHECK_VALUES
#error "define one of REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

#ifdef REMOVE_VALUES
#ifdef CHECK_VALUES
#error "define either REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

int main()
{
	std::vector<int> myValues;
  for ( long int i=0L; i<100000000L; ++i )
		myValues.push_back(i%3);

	int iOriginalSize = myValues.size();
#ifdef REMOVE_VALUES
	myValues.erase(std::remove_if(myValues.begin(),myValues.end(),[](int i) { return i == 2; }),myValues.end());
#endif
	int sum = 0;
  for ( unsigned int i=0; i<myValues.size(); ++i )
	{
#ifdef CHECK_VALUES
		if ( myValues[i] != 2 )
		{
#endif
			sum += myValues[i];
#ifdef CHECK_VALUES
		}
#endif
	}

}
<commit_msg>Check vs Remove - not so not so clear<commit_after>#include <vector>
#include <iostream>
#include <algorithm>

#ifndef REMOVE_VALUES
#ifndef CHECK_VALUES
#error "define one of REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

#ifdef REMOVE_VALUES
#ifdef CHECK_VALUES
#error "define either REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

int main()
{
	std::vector<int> myValues;
	for ( long int i=0L; i<10000000L; ++i )
		myValues.push_back(i%3);

	int iOriginalSize = myValues.size();
#ifdef REMOVE_VALUES
	myValues.erase(std::remove_if(myValues.begin(),myValues.end(),[](int i) { return i == 2; }),myValues.end());
#endif

	const int iterations = 100;
	for ( int iteration=0; iteration < iterations; ++iteration )
	{
		int sum = 0;
		for ( unsigned int i=0; i<myValues.size(); ++i )
		{
#ifdef CHECK_VALUES
			if ( myValues[i] != 2 )
			{
#endif
				sum += myValues[i];
#ifdef CHECK_VALUES
			}
#endif
		}
	}
}
<|endoftext|>


<commit_before>#include <queue>
#include <iostream>
#include <sstream>
#include "nfa.h"
#include "utils.cpp"

string error_message = "NFA Creation Error : ";

void verify_state_set(const set<string>& states, const set<string>& state_set) {

    set<string>::const_iterator it;
    for (it = state_set.begin(); it != state_set.end(); ++it) {
        if(!states.count(*it))
            throw error_message + "State '" + *it + "' does not belong to Q!";
    }
}

void verify_states(set<string> states, set<string> initial, set<string> final) {
    if(initial.size() != 1)
        throw error_message + "There should be one and only one initial state!";

    if(final.size() < 1 || final.size() > states.size() )
        throw error_message + "Final states should be between 1 and total number of states!";

    // Verify if all the states in initial and final belong to state vector

    if (!states.count(*initial.begin()))
        throw error_message + "Initial state '" + *initial.begin() + "' does not belong to Q!";

    try {
        verify_state_set(states, final);
    } catch (const string& message) {
        cout << "Invalid Final State!" << endl;
        throw;
    }
}

void nfa::set_states(const set<string> &states, const set<string> &initial, const set<string> &final) {
    verify_states(states, initial, final);

    this->states = states;
    this->final = final;
    this->initial = *initial.begin();
}

void nfa::set_alphabet(const set<string> &alphabet) {
    if(alphabet.count("e"))
        throw "NFA Parse Error : Language alphabet 'e' clashes with keyword for epsilon!";

    this->alphabet = alphabet;
}

void nfa::add_transition(const string& current_state, const string& alphabet, const set<string>& result) {
    verify_state_set(states, result);
    transitions[make_pair(current_state, alphabet)] = result;
}

const set<string> nfa::get_states(const string& state, const string& alphabet) {
    pair<string, string> key = make_pair(state, alphabet);
    if(!transitions.count(key))
        throw "NFA Error : Invalid Transition!";

    return transitions[key];
}

const set<string> nfa::get_states(const set<string> &states, const string &alphabet) {
    set<string> compound_states;

    set<string>::const_iterator it;
    for(it = states.begin(); it != states.end(); ++it) {
        set<string> out_state = get_states(*it, alphabet);
        compound_states.insert(out_state.begin(), out_state.end());
    }

    return compound_states;
}

const set<string> nfa::get_epsilon_closure(const string &state) {
    set<string> key;
    key.insert(state);

    if(epsilon_closures.count(key))
        return epsilon_closures[key];

    set<string> epsilon_states;

    queue<string> remaining;
    remaining.push(state);

    while (!remaining.empty()) {
        string current = remaining.front();

        epsilon_states.insert(current);

        set<string> epsilon_moves = get_states(current, "e");
        set<string>::const_iterator it;
        for(it = epsilon_moves.begin(); it != epsilon_moves.end(); ++it) {
            if(!epsilon_states.count(*it))
                remaining.push(*it);
        }

        remaining.pop();
    }

    epsilon_closures[key] = epsilon_states;

    return epsilon_states;
}

const set<string> nfa::get_epsilon_closure(const set<string> &states) {
    if (epsilon_closures.count(states))
        return epsilon_closures[states];

    set<string> epsilon_states;

    set<string>::const_iterator it;
    for(it = states.begin(); it != states.end(); ++it) {
        set<string> current_states = get_epsilon_closure(*it);
        epsilon_states.insert(current_states.begin(), current_states.end());
    }

    epsilon_closures[states] = epsilon_states;

    return epsilon_states;
}

bool nfa::is_final(const set<string> &states) {
    set<string>::const_iterator it;

    for(it = states.begin(); it != states.end(); ++it) {
        if(contains(final, *it))
            return true;
    }

    return false;
}

string nfa::format_output(ostringstream& oss, vector< set<string> >& dfa_states) {
    cout << "\nInitial State : " << endl;
    string initial_state = to_string(dfa_states[0], ',');
    cout << "{ " << initial_state << " }" << endl;

    oss << (string) "Q0 : { " << initial_state << " }" << endl;
    oss << "F : {";

    cout << "Final States : " << endl;
    string prefix = "Q : {";
    const char* delim = " ";
    for (int i = 0; i < dfa_states.size(); ++i) {
        set<string> current = dfa_states[i];

        prefix+= " { " + to_string(current, ',') + " },";

        if(is_final(current)) {
            string final_state = to_string(current, ',');
            cout << "{ " << final_state << " }" << endl;

            oss << delim << "{ " << final_state << " }";
            delim = ", ";
        }
    }
    oss << " }" << endl;

    // Add states and languages to output
    unsigned long index = prefix.length()-1;
    if(prefix[index] == ',')
        prefix.erase(prefix.begin() + index);
    prefix += " }\n";
    prefix += "E : { " + to_string(alphabet, ',') + " }\n";

    return prefix + "\n" + oss.str();
}

string nfa::to_dfa() {
    ostringstream oss;
    cout << "DFA Conversion : \n" << endl;
    set<string> initial = get_epsilon_closure(this->initial);

    queue< set<string> > remaining;
    remaining.push(initial);

    vector< set<string> > dfa_states;

    set<string>::const_iterator it;

    while(!remaining.empty()) {
        set<string> current = remaining.front();
        remaining.pop();

        if(contains(dfa_states, current))
            continue;

        string current_set = to_string(current, ',');
        cout << "For state : { " << current_set << " }" << endl;
        for (it = alphabet.begin(); it != alphabet.end(); ++it) {
            set<string> epsilon_state = get_epsilon_closure(get_states(current, *it));

            string epsilon_set = to_string(epsilon_state, ',');
            cout << "    " << *it << " -> { " << epsilon_set << " }" << endl;

            oss << (string) "T({ " << current_set << " }, " << *it << " ) : { " << epsilon_set << " }" << endl;

            if (!contains(dfa_states, epsilon_state) && !epsilon_state.empty())
                remaining.push(epsilon_state);
        }

        dfa_states.push_back(current);
        cout << endl;
        oss<<endl;
    }

    return format_output(oss, dfa_states);
}

const string get_transition_string(const map< pair<string, string>, set<string> > m) {
    string output;
    map< pair<string, string>, set<string> >::const_iterator it;

    for(it = m.begin(); it != m.end(); ++it) {
        output += "(" + it->first.first + ", " + it->first.second + ") -> { " + to_string(it->second, ',') + " }\n";
    }

    return output;
}

string nfa::tostring() {
    return "Alphabet:\n"
            "{ " + to_string(alphabet, ',') + " }"
            "\n\nStates:\n"
            "{ " + to_string(states, ',') + " }"
            "\n\nInitial State : \n" +
            initial +
            "\n\nFinal States:\n"
            "{ " + to_string(final, ',') + " }"
            "\n\nTransitions:\n" +
            get_transition_string(transitions);
}<commit_msg>Added phi as a state in DFA<commit_after>#include <queue>
#include <iostream>
#include <sstream>
#include "nfa.h"
#include "utils.cpp"

string error_message = "NFA Creation Error : ";

void verify_state_set(const set<string>& states, const set<string>& state_set) {

    set<string>::const_iterator it;
    for (it = state_set.begin(); it != state_set.end(); ++it) {
        if(!states.count(*it))
            throw error_message + "State '" + *it + "' does not belong to Q!";
    }
}

void verify_states(set<string> states, set<string> initial, set<string> final) {
    if(initial.size() != 1)
        throw error_message + "There should be one and only one initial state!";

    if(final.size() < 1 || final.size() > states.size() )
        throw error_message + "Final states should be between 1 and total number of states!";

    // Verify if all the states in initial and final belong to state vector

    if (!states.count(*initial.begin()))
        throw error_message + "Initial state '" + *initial.begin() + "' does not belong to Q!";

    try {
        verify_state_set(states, final);
    } catch (const string& message) {
        cout << "Invalid Final State!" << endl;
        throw;
    }
}

void nfa::set_states(const set<string> &states, const set<string> &initial, const set<string> &final) {
    verify_states(states, initial, final);

    this->states = states;
    this->final = final;
    this->initial = *initial.begin();
}

void nfa::set_alphabet(const set<string> &alphabet) {
    if(alphabet.count("e"))
        throw "NFA Parse Error : Language alphabet 'e' clashes with keyword for epsilon!";

    this->alphabet = alphabet;
}

void nfa::add_transition(const string& current_state, const string& alphabet, const set<string>& result) {
    verify_state_set(states, result);
    transitions[make_pair(current_state, alphabet)] = result;
}

const set<string> nfa::get_states(const string& state, const string& alphabet) {
    pair<string, string> key = make_pair(state, alphabet);
    if(!transitions.count(key))
        throw "NFA Error : Invalid Transition!";

    return transitions[key];
}

const set<string> nfa::get_states(const set<string> &states, const string &alphabet) {
    set<string> compound_states;

    set<string>::const_iterator it;
    for(it = states.begin(); it != states.end(); ++it) {
        set<string> out_state = get_states(*it, alphabet);
        compound_states.insert(out_state.begin(), out_state.end());
    }

    return compound_states;
}

const set<string> nfa::get_epsilon_closure(const string &state) {
    set<string> key;
    key.insert(state);

    if(epsilon_closures.count(key))
        return epsilon_closures[key];

    set<string> epsilon_states;

    queue<string> remaining;
    remaining.push(state);

    while (!remaining.empty()) {
        string current = remaining.front();

        epsilon_states.insert(current);

        set<string> epsilon_moves = get_states(current, "e");
        set<string>::const_iterator it;
        for(it = epsilon_moves.begin(); it != epsilon_moves.end(); ++it) {
            if(!epsilon_states.count(*it))
                remaining.push(*it);
        }

        remaining.pop();
    }

    epsilon_closures[key] = epsilon_states;

    return epsilon_states;
}

const set<string> nfa::get_epsilon_closure(const set<string> &states) {
    if (epsilon_closures.count(states))
        return epsilon_closures[states];

    set<string> epsilon_states;

    set<string>::const_iterator it;
    for(it = states.begin(); it != states.end(); ++it) {
        set<string> current_states = get_epsilon_closure(*it);
        epsilon_states.insert(current_states.begin(), current_states.end());
    }

    epsilon_closures[states] = epsilon_states;

    return epsilon_states;
}

bool nfa::is_final(const set<string> &states) {
    set<string>::const_iterator it;

    for(it = states.begin(); it != states.end(); ++it) {
        if(contains(final, *it))
            return true;
    }

    return false;
}

string nfa::format_output(ostringstream& oss, vector< set<string> >& dfa_states) {
    cout << "\nInitial State : " << endl;
    string initial_state = to_string(dfa_states[0], ',');
    cout << "{ " << initial_state << " }" << endl;

    oss << (string) "Q0 : { " << initial_state << " }" << endl;
    oss << "F : {";

    cout << "Final States : " << endl;
    string prefix = "Q : {";
    const char* delim = " ";
    for (int i = 0; i < dfa_states.size(); ++i) {
        set<string> current = dfa_states[i];

        prefix+= " { " + to_string(current, ',') + " },";

        if(is_final(current)) {
            string final_state = to_string(current, ',');
            cout << "{ " << final_state << " }" << endl;

            oss << delim << "{ " << final_state << " }";
            delim = ", ";
        }
    }
    oss << " }" << endl;

    // Add states and languages to output
    unsigned long index = prefix.length()-1;
    if(prefix[index] == ',')
        prefix.erase(prefix.begin() + index);
    prefix += " }\n";
    prefix += "E : { " + to_string(alphabet, ',') + " }\n";

    return prefix + "\n" + oss.str();
}

string nfa::to_dfa() {
    ostringstream oss;
    cout << "DFA Conversion : \n" << endl;
    set<string> initial = get_epsilon_closure(this->initial);

    queue< set<string> > remaining;
    remaining.push(initial);

    vector< set<string> > dfa_states;

    set<string>::const_iterator it;

    while(!remaining.empty()) {
        set<string> current = remaining.front();
        remaining.pop();

        if(contains(dfa_states, current))
            continue;

        dfa_states.push_back(current);

        if(current.empty())
            continue;

        string current_set = to_string(current, ',');
        cout << "For state : { " << current_set << " }" << endl;
        for (it = alphabet.begin(); it != alphabet.end(); ++it) {
            set<string> epsilon_state = get_epsilon_closure(get_states(current, *it));

            string epsilon_set = to_string(epsilon_state, ',');
            cout << "    " << *it << " -> { " << epsilon_set << " }" << endl;

            oss << (string) "T({ " << current_set << " }, " << *it << " ) : { " << epsilon_set << " }" << endl;

            if (!contains(dfa_states, epsilon_state))
                remaining.push(epsilon_state);
        }

        cout << endl;
        oss << endl;
    }

    return format_output(oss, dfa_states);
}

const string get_transition_string(const map< pair<string, string>, set<string> > m) {
    string output;
    map< pair<string, string>, set<string> >::const_iterator it;

    for(it = m.begin(); it != m.end(); ++it) {
        output += "(" + it->first.first + ", " + it->first.second + ") -> { " + to_string(it->second, ',') + " }\n";
    }

    return output;
}

string nfa::tostring() {
    return "Alphabet:\n"
            "{ " + to_string(alphabet, ',') + " }"
            "\n\nStates:\n"
            "{ " + to_string(states, ',') + " }"
            "\n\nInitial State : \n" +
            initial +
            "\n\nFinal States:\n"
            "{ " + to_string(final, ',') + " }"
            "\n\nTransitions:\n" +
            get_transition_string(transitions);
}<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkScalarImageToHistogramGeneratorTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkScalarImageToHistogramGenerator.h"
#include "itkImage.h"
#include "itkImageRegionIteratorWithIndex.h"

int itkScalarImageToHistogramGeneratorTest( int , char * [] )
{

    {
    typedef unsigned long                         PixelType;
    const unsigned int imageSize=256;
    const unsigned int                            Dimension = 2;

    typedef itk::Image< PixelType, Dimension >    ImageType;

    ImageType::Pointer image = ImageType::New();

    ImageType::RegionType region;
    ImageType::SizeType   size;
    ImageType::IndexType  start;

    size[0] = imageSize;
    size[1] = imageSize;

    start[0] = 0;
    start[1] = 0;

    region.SetIndex( start );
    region.SetSize( size );

    image->SetRegions( region );
    image->Allocate();

    //  Now fill up the image will all the combinations of
    //  values from 0-imageSize.
    itk::ImageRegionIteratorWithIndex< ImageType >  it( image, region );
    it.GoToBegin();

    while( !it.IsAtEnd() )
      {
      it.Set( it.GetIndex()[0] );
      ++it;
      }

    typedef itk::Statistics::ScalarImageToHistogramGenerator<
      ImageType
      >   HistogramGeneratorType;

    HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New();

    histogramGenerator->SetInput(  image  );

    histogramGenerator->SetNumberOfBins( imageSize );
    histogramGenerator->SetMarginalScale( 10.0 );
    histogramGenerator->Compute();

    typedef HistogramGeneratorType::HistogramType  HistogramType;

    const HistogramType * histogram = histogramGenerator->GetOutput();

    const unsigned int histogramSize = histogram->Size();

    std::cout << "Histogram size " << histogramSize << std::endl;

    const unsigned int channel = 0;  // the only channel

    for( unsigned int bin=0; bin < histogramSize; bin++ )
      {
      if( histogram->GetFrequency( bin, channel ) != imageSize )
        {
        std::cerr << "Error in bin= " << bin << " channel = " << channel << std::endl;
        std::cerr << "Frequency was= " <<  histogram->GetFrequency( bin, channel ) << " Instead of the expected " << imageSize << std::endl;
        return EXIT_FAILURE;
        }
      }
    }
    {
    const unsigned int NumberOfBins=4;
    typedef unsigned long                         PixelType;
    // NOTE :  it is not uncommon to have a 3D image with more than 4096 * 4096 voxels in the background (i.e. 0'th histogram bin), and this causes an overflow event
    const unsigned int imageSize=4096+NumberOfBins;  // Note 4096^2 = 16777216, which is greater than the number that can be accurately incremented by a floating point number.
    //const unsigned int imageSize=406+NumberOfBins;  // Note 4096^2 = 16777216, which is greater than the number that can be accurately incremented by a floating point number.
    const unsigned int                            Dimension = 2;

    typedef itk::Image< PixelType, Dimension >    ImageType;

    ImageType::Pointer image = ImageType::New();

    ImageType::RegionType region;
    ImageType::SizeType   size;
    ImageType::IndexType  start;

    size[0] = imageSize;
    size[1] = imageSize;

    start[0] = 0;
    start[1] = 0;

    region.SetIndex( start );
    region.SetSize( size );

    image->SetRegions( region );
    image->Allocate();

    //  Now fill up the image will all the combinations of
    //  values from 0-imageSize.
    itk::ImageRegionIteratorWithIndex< ImageType >  it( image, region );

    it.GoToBegin();
    for(unsigned int temp=0;temp<NumberOfBins;temp++)
      {
      it.Set((temp+1)*1000); //Make it have a range
      ++it;
      }

    while( !it.IsAtEnd() )
      {
      it.Set( 0 );
      ++it;
      }

    typedef itk::Statistics::ScalarImageToHistogramGenerator<
      ImageType
      >   HistogramGeneratorType;

    HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New();

    histogramGenerator->SetInput(  image  );

    histogramGenerator->SetNumberOfBins( 4 );
    histogramGenerator->SetMarginalScale( 10.0 );
    histogramGenerator->Compute();

    typedef HistogramGeneratorType::HistogramType  HistogramType;

    const HistogramType * histogram = histogramGenerator->GetOutput();

    const unsigned int histogramSize = histogram->Size();

    std::cout << "Histogram size " << histogramSize << std::endl;

    const unsigned int channel = 0;  // the only channel

    int status=EXIT_SUCCESS;
      {
      const unsigned int bin=0;
      if( histogram->GetFrequency( bin, channel ) == 16777216 ) {
        std::cerr << "Error in bin= " << bin << " channel = " << channel << std::endl;
        std::cerr << "Frequency was= " <<  (unsigned int)histogram->GetFrequency( bin, channel )
          << " which is the maximum integer value representable by a 32bit floating point number " << std::endl;
        status=EXIT_FAILURE;
      }

      if( histogram->GetFrequency( bin, channel ) != imageSize*imageSize - NumberOfBins +1)
        {
        std::cerr << "Error in bin= " << bin << " channel = " << channel << std::endl;
        std::cerr << "Frequency was= " <<  (unsigned int)histogram->GetFrequency( bin, channel ) << " Instead of the expected " << imageSize*imageSize - NumberOfBins +1 << std::endl;
        status=EXIT_FAILURE;
        }
      }
    for( unsigned int bin=1; bin < histogramSize; bin++ )
      {
      if( histogram->GetFrequency( bin, channel ) != 1 )
        {
        std::cerr << "Error in bin= " << bin << " channel = " << channel << std::endl;
        std::cerr << "Frequency was= " <<  (unsigned int)histogram->GetFrequency( bin, channel ) << " Instead of the expected " << 1 << std::endl;
        status=EXIT_FAILURE;
        }
      }
    return status;
    }

  return EXIT_SUCCESS;

}

<commit_msg>STYLE: Improving formating.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkScalarImageToHistogramGeneratorTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkScalarImageToHistogramGenerator.h"
#include "itkImage.h"
#include "itkImageRegionIteratorWithIndex.h"

int itkScalarImageToHistogramGeneratorTest( int , char * [] )
{

    {
    typedef unsigned long                         PixelType;
    const unsigned int imageSize=256;
    const unsigned int                            Dimension = 2;

    typedef itk::Image< PixelType, Dimension >    ImageType;

    ImageType::Pointer image = ImageType::New();

    ImageType::RegionType region;
    ImageType::SizeType   size;
    ImageType::IndexType  start;

    size[0] = imageSize;
    size[1] = imageSize;

    start[0] = 0;
    start[1] = 0;

    region.SetIndex( start );
    region.SetSize( size );

    image->SetRegions( region );
    image->Allocate();

    //  Now fill up the image will all the combinations of
    //  values from 0-imageSize.
    itk::ImageRegionIteratorWithIndex< ImageType >  it( image, region );
    it.GoToBegin();

    while( !it.IsAtEnd() )
      {
      it.Set( it.GetIndex()[0] );
      ++it;
      }

    typedef itk::Statistics::ScalarImageToHistogramGenerator<
      ImageType
      >   HistogramGeneratorType;

    HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New();

    histogramGenerator->SetInput(  image  );

    histogramGenerator->SetNumberOfBins( imageSize );
    histogramGenerator->SetMarginalScale( 10.0 );
    histogramGenerator->Compute();

    typedef HistogramGeneratorType::HistogramType  HistogramType;

    const HistogramType * histogram = histogramGenerator->GetOutput();

    const unsigned int histogramSize = histogram->Size();

    std::cout << "Histogram size " << histogramSize << std::endl;

    const unsigned int channel = 0;  // the only channel

    for( unsigned int bin=0; bin < histogramSize; bin++ )
      {
      if( histogram->GetFrequency( bin, channel ) != imageSize )
        {
        std::cerr << "Error in bin= " << bin << " channel = " << channel << std::endl;
        std::cerr << "Frequency was= " <<  histogram->GetFrequency( bin, channel ) << " Instead of the expected " << imageSize << std::endl;
        return EXIT_FAILURE;
        }
      }
    }

    {
    const unsigned int NumberOfBins = 4;
    typedef unsigned long PixelType;

    // NOTE :  it is not uncommon to have a 3D image with more than 4096 * 4096
    // voxels in the background (i.e. 0'th histogram bin), and this causes an
    // overflow event
    const unsigned int imageSize=4096+NumberOfBins;

    // Note 4096^2 = 16777216, which is greater than the number that can be
    // accurately incremented by a floating point number.
    //const unsigned int imageSize=406+NumberOfBins;  // Note 4096^2 =
    //16777216, which is greater than the number that can be accurately
    //incremented by a floating point number.
    const unsigned int                            Dimension = 2;

    typedef itk::Image< PixelType, Dimension >    ImageType;

    ImageType::Pointer image = ImageType::New();

    ImageType::RegionType region;
    ImageType::SizeType   size;
    ImageType::IndexType  start;

    size[0] = imageSize;
    size[1] = imageSize;

    start[0] = 0;
    start[1] = 0;

    region.SetIndex( start );
    region.SetSize( size );

    image->SetRegions( region );
    image->Allocate();

    //  Now fill up the image will all the combinations of
    //  values from 0-imageSize.
    itk::ImageRegionIteratorWithIndex< ImageType >  it( image, region );

    it.GoToBegin();
    for(unsigned int temp=0;temp<NumberOfBins;temp++)
      {
      it.Set((temp+1)*1000); //Make it have a range
      ++it;
      }

    while( !it.IsAtEnd() )
      {
      it.Set( 0 );
      ++it;
      }

    typedef itk::Statistics::ScalarImageToHistogramGenerator<
      ImageType
      >   HistogramGeneratorType;

    HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New();

    histogramGenerator->SetInput(  image  );

    histogramGenerator->SetNumberOfBins( 4 );
    histogramGenerator->SetMarginalScale( 10.0 );

    try
      {
      histogramGenerator->Compute();
      std::cout << "Failed to catch expected exception about saturation of counters" << std::endl;
      }
    catch( itk::ExceptionObject & excp )
      {
      std::cout << "Get Expected Exception" << std::endl;
      std::cout << excp << std::endl;
      }

    typedef HistogramGeneratorType::HistogramType  HistogramType;

    const HistogramType * histogram = histogramGenerator->GetOutput();

    const unsigned int histogramSize = histogram->Size();

    std::cout << "Histogram size " << histogramSize << std::endl;

    const unsigned int channel = 0;  // the only channel

    int status=EXIT_SUCCESS;
      {

      const unsigned int bin = 0;

      if( histogram->GetFrequency( bin, channel ) == 16777216 )
        {
        std::cerr << "Error in bin= " << bin << " channel = " << channel << std::endl;
        std::cerr << "Frequency was= " <<  (unsigned int)histogram->GetFrequency( bin, channel )
          << " which is the maximum integer value representable by a 32bit floating point number " << std::endl;
        status = EXIT_FAILURE;
        }

      if( histogram->GetFrequency( bin, channel ) != imageSize*imageSize - NumberOfBins + 1 )
        {
        std::cerr << "Error in bin= " << bin << " channel = " << channel << std::endl;
        std::cerr << "Frequency was= " <<  (unsigned int)histogram->GetFrequency( bin, channel ) << " Instead of the expected " << imageSize*imageSize - NumberOfBins +1 << std::endl;
        status = EXIT_FAILURE;
        }
      }

    for( unsigned int bin=1; bin < histogramSize; bin++ )
      {
      if( histogram->GetFrequency( bin, channel ) != 1 )
        {
        std::cerr << "Error in bin= " << bin << " channel = " << channel << std::endl;
        std::cerr << "Frequency was= " <<  (unsigned int)histogram->GetFrequency( bin, channel ) << " Instead of the expected " << 1 << std::endl;
        status = EXIT_FAILURE;
        }
      }

    return status;
    }

  return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: attributes.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 16:28:42 $
 *
 *  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 _CONFIGMGR_MISC_ATTRIBUTES_HXX_
#define _CONFIGMGR_MISC_ATTRIBUTES_HXX_

#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

/*----------------------------------------
*
*   Attributlist implementation
*
*----------------------------------------*/

using namespace ::cppu;
using namespace ::rtl;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::uno;

struct AttributeListImpl_impl;
class AttributeListImpl : public WeakImplHelper1< XAttributeList >
{
protected:
    ~AttributeListImpl();

public:
    AttributeListImpl();
    AttributeListImpl( const AttributeListImpl & );

public:
    virtual sal_Int16 SAL_CALL getLength(void) throw (RuntimeException);
    virtual OUString  SAL_CALL getNameByIndex(sal_Int16 i) throw (RuntimeException);
    virtual OUString  SAL_CALL getTypeByIndex(sal_Int16 i) throw (RuntimeException);
    virtual OUString  SAL_CALL getTypeByName(const OUString& aName) throw (RuntimeException);
    virtual OUString  SAL_CALL getValueByIndex(sal_Int16 i) throw (RuntimeException);
    virtual OUString  SAL_CALL getValueByName(const OUString& aName) throw (RuntimeException);

public:
    void addAttribute( const OUString &sName , const OUString &sType , const OUString &sValue );
    void clear();

private:
    struct AttributeListImpl_impl *m_pImpl;
};

#endif // _CONFIGMGR_MISC_ATTRIBUTES_HXX_

<commit_msg>INTEGRATION: CWS changefileheader (1.2.58); FILE MERGED 2008/04/01 15:19:45 thb 1.2.58.3: #i85898# Stripping all external header guards 2008/04/01 10:58:41 thb 1.2.58.2: #i85898# Stripping all external header guards 2008/03/28 15:36:37 rt 1.2.58.1: #i87441# Change license header to LPGL v3.<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: attributes.hxx,v $
 * $Revision: 1.3 $
 *
 * 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 _CONFIGMGR_MISC_ATTRIBUTES_HXX_
#define _CONFIGMGR_MISC_ATTRIBUTES_HXX_

#include <com/sun/star/xml/sax/XAttributeList.hpp>
#include <cppuhelper/implbase1.hxx>

/*----------------------------------------
*
*   Attributlist implementation
*
*----------------------------------------*/

using namespace ::cppu;
using namespace ::rtl;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::uno;

struct AttributeListImpl_impl;
class AttributeListImpl : public WeakImplHelper1< XAttributeList >
{
protected:
    ~AttributeListImpl();

public:
    AttributeListImpl();
    AttributeListImpl( const AttributeListImpl & );

public:
    virtual sal_Int16 SAL_CALL getLength(void) throw (RuntimeException);
    virtual OUString  SAL_CALL getNameByIndex(sal_Int16 i) throw (RuntimeException);
    virtual OUString  SAL_CALL getTypeByIndex(sal_Int16 i) throw (RuntimeException);
    virtual OUString  SAL_CALL getTypeByName(const OUString& aName) throw (RuntimeException);
    virtual OUString  SAL_CALL getValueByIndex(sal_Int16 i) throw (RuntimeException);
    virtual OUString  SAL_CALL getValueByName(const OUString& aName) throw (RuntimeException);

public:
    void addAttribute( const OUString &sName , const OUString &sType , const OUString &sValue );
    void clear();

private:
    struct AttributeListImpl_impl *m_pImpl;
};

#endif // _CONFIGMGR_MISC_ATTRIBUTES_HXX_

<|endoftext|>


<commit_before>#ifndef Bull_Constants_hpp
#define Bull_Constants_hpp

#include <cmath>

namespace Bull
{
    constexpr float Pi = std::acos(-1);
}

#endif // Bull_Constants_hpp
<commit_msg>Math/Constants Add more constants<commit_after>#ifndef Bull_Constants_hpp
#define Bull_Constants_hpp

#include <cmath>

namespace Bull
{
    constexpr float Pi = std::acos(-1.f);

    constexpr float PiPow2 = std::pow(Pi, 2.f);

    constexpr float PiPow3 = std::pow(Pi, 3.f);

    constexpr float Sqrt2 = std::sqrt(2.f);

    constexpr float Sqrt3 = std::sqrt(3.f);
}

#endif // Bull_Constants_hpp
<|endoftext|>


<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring> // memcpy

#ifndef NDEBUG
#include <iostream>
#include <ostream>
#endif

#ifndef __SYNTHESIS__
//#include <boost/thread/mutex.hpp>
//#include <boost/thread/locks.hpp>
#endif

#include "../rand_iterator.h"

namespace burst
{
namespace memory
{

//enum { N = 1024 };

#ifndef __SYNTHESIS__
//static boost::mutex mtx;
#endif

struct node;
typedef node* node_ptr;

// node ---------------------------------------------------

struct node
{
    region::size_type pos;
    region::size_type size;
    region::size_type pred_pos;
    region::size_type allocated;
};

inline void make_node(
        volatile uint8_t* mem,
        region::size_type pos,
        region::size_type size,
        region::size_type pred_pos,
        bool allocated
        )
{
#pragma HLS INLINE
    node n;
    n.pos = pos;
    n.size = size;
    n.pred_pos = pred_pos;
    n.allocated = allocated;
    {
#ifndef __SYNTHESIS__
//      boost::lock_guard<boost::mutex> l(mtx);
#endif
        memcpy((uint8_t*)mem + pos, &n, sizeof(n));
    }
}

// Order matters!
inline void merge_nodes(
        volatile uint8_t* mem,
        node const& n1,
        node const& n2,
        bool allocated
        )
{
#pragma HLS INLINE
    make_node(mem, n1.pos, n1.size + n2.size, n1.pred_pos, allocated);
}

inline node get_node(volatile uint8_t* mem, region::size_type pos)
{
#pragma HLS INLINE
    node n;
    {
#ifndef __SYNTHESIS__
//      boost::lock_guard<boost::mutex> l(mtx);
#endif
        memcpy(&n, (uint8_t*)mem + pos, sizeof(n));
    }
    return n;
}

inline node get_node_from_ptr(volatile void const* ptr)
{
#pragma HLS INLINE
    node n;
    {
#ifndef __SYNTHESIS__
//        boost::lock_guard<boost::mutex> l(mtx);
#endif
        memcpy(&n, (void const*)ptr, sizeof(n));
    }
    return n;
}

inline node prev_node(volatile uint8_t* mem, node const& n)
{
#pragma HLS INLINE
    return get_node(mem, n.pred_pos);
}

inline node next_node(volatile uint8_t* mem, node const& n)
{
#pragma HLS INLINE
	region::size_type addr = n.pos + n.size;
    return get_node(mem, addr);
}

inline region::size_type get_data_addr(node const& n)
{
#pragma HLS INLINE
    return n.pos + sizeof(n);
}

inline bool operator!=(node const& n1, node const& n2)
{
    return n1.pos       != n2.pos       ||
           n1.size      != n2.size      ||
           n1.pred_pos  != n2.pred_pos  ||
           n1.allocated != n2.allocated
           ;
}

#ifndef NDEBUG
inline std::ostream& operator<<(std::ostream& out, node n)
{
    out << '(' << n.pos
        << ',' << n.size
        << ',' << n.pred_pos
        << ',' << n.allocated
         << ')';
    return out;
}
#endif

// list ---------------------------------------------------

static bool free_list_initialized = false;

inline void free_list_init(volatile uint8_t* mem, region::size_type N)
{
#pragma HLS INLINE
    make_node(mem, 0, N, 0, false);
}

inline node free_list_insert_first(volatile uint8_t* mem, region::size_type size)
{
#pragma HLS INLINE
	region::size_type addr = 0;

    node n = get_node(mem, addr);

    while (n.size < size || n.allocated)
    {
        n = next_node(mem, n);
    }

    node n1;
    n1.pos = n.pos;
    n1.size = size;
    n1.pred_pos = n.pred_pos;
    n1.allocated = true;

    node n2;
    n2.pos = n.pos + size;
    n2.size = n.size - size;
    n2.pred_pos = n.pos;
    n2.allocated = n.allocated;

    make_node(mem, n1.pos, n1.size, n1.pred_pos, n1.allocated);
    make_node(mem, n2.pos, n2.size, n2.pred_pos, n2.allocated);

    return n1;
}

#ifndef NDEBUG
inline void free_list_print(volatile uint8_t* mem, region::size_type N)
{
#ifndef __SYNTHESIS__
    node n = get_node(mem, 0);
    std::cout << "n= get_node(0): "<<n<< std::endl;

    while (n.pos + n.size < N)
    {
        n = next_node(mem, n);
        std::cout <<"n=next_node(n): "<<n<< std::endl;
    }
#endif
}
#endif

// interface ----------------------------------------------

inline region::region()
    : data(nullptr)
    , N(0)
{
}

inline region::region(volatile uint8_t* a, region::size_type n)
    : data(a)
    , N(n)
{
}

template <typename T>
inline rand_iterator<T> region::allocate(region::size_type n)
{
    if (!free_list_initialized)
    {
        free_list_init(data, N);
        free_list_initialized = true;
    }

    // Bytes
    region::size_type size = n * sizeof(T);

    node nd = free_list_insert_first(data, size + sizeof(node));

    return rand_iterator<T>(
            data,
            static_cast<difference_type>(get_data_addr(nd) / sizeof(T)) // TODO!
            );
}

template <typename T>
inline void region::deallocate(rand_iterator<T> ptr)
{
    if (!free_list_initialized)
    {
        free_list_init(data, N);
        free_list_initialized = true;
    }

    volatile uint8_t* ptr8 = ptr.data() + ptr.pos() * sizeof(T);
    node n1 = get_node_from_ptr(ptr8 - sizeof(node));
    node n2 = next_node(data, n1);

    make_node(data, n1.pos, n1.size, n1.pred_pos, false);

    if (!n2.allocated)
        merge_nodes(data, n1, n2, false);

    n1 = get_node(data, n1.pos);
    node n3 = prev_node(data, n1);

    if (!n3.allocated && n1 != n3)
        merge_nodes(data, n3, n1, false);
}

inline bool region::valid() const
{
	return data != nullptr;
}

//-------------------------------------------------------------------------------------------------
// Allocate/deallocate on one of the default memory regions
//

template <typename T>
inline rand_iterator<T> allocate(region::size_type n, region_id id)
{
    assert(id < RegionMax);

    return default_regions[id].allocate<T>(n);
}

template <typename T>
inline void deallocate(rand_iterator<T> ptr, region_id id)
{
    assert(id < RegionMax);

    default_regions[id].deallocate(ptr);
}

} // namespace memory
} // namespace burst
<commit_msg>Prevent overly strong optimization..<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring> // memcpy

#ifndef NDEBUG
#include <iostream>
#include <ostream>
#endif

#ifndef __SYNTHESIS__
//#include <boost/thread/mutex.hpp>
//#include <boost/thread/locks.hpp>
#endif

#include "../rand_iterator.h"

namespace burst
{
namespace memory
{

//enum { N = 1024 };

#ifndef __SYNTHESIS__
//static boost::mutex mtx;
#endif

struct node;
typedef node* node_ptr;

// node ---------------------------------------------------

struct node
{
    region::size_type pos;
    region::size_type size;
    region::size_type pred_pos;
    region::size_type allocated;
};

inline void make_node(
        volatile uint8_t* mem,
        region::size_type pos,
        region::size_type size,
        region::size_type pred_pos,
        bool allocated
        )
{
#pragma HLS INLINE
    node n;
    n.pos = pos;
    n.size = size;
    n.pred_pos = pred_pos;
    n.allocated = allocated;
    {
#ifndef __SYNTHESIS__
//      boost::lock_guard<boost::mutex> l(mtx);
#endif
        memcpy((uint8_t*)mem + pos, &n, sizeof(n));
    }
}

// Order matters!
inline void merge_nodes(
        volatile uint8_t* mem,
        node const& n1,
        node const& n2,
        bool allocated
        )
{
#pragma HLS INLINE
    make_node(mem, n1.pos, n1.size + n2.size, n1.pred_pos, allocated);
}

inline node get_node(volatile uint8_t* mem, region::size_type pos)
{
#pragma HLS INLINE
    node n;
    {
#ifndef __SYNTHESIS__
//      boost::lock_guard<boost::mutex> l(mtx);
#endif
        memcpy(&n, (uint8_t*)mem + pos, sizeof(n));
    }
    return n;
}

inline node get_node_from_ptr(volatile void const* ptr)
{
#pragma HLS INLINE
    node n;
    {
#ifndef __SYNTHESIS__
//        boost::lock_guard<boost::mutex> l(mtx);
#endif
        memcpy(&n, (void const*)ptr, sizeof(n));
    }
    return n;
}

inline node prev_node(volatile uint8_t* mem, node const& n)
{
#pragma HLS INLINE
    return get_node(mem, n.pred_pos);
}

inline node next_node(volatile uint8_t* mem, node const& n)
{
#pragma HLS INLINE
	region::size_type addr = n.pos + n.size;
    return get_node(mem, addr);
}

inline region::size_type get_data_addr(node const& n)
{
#pragma HLS INLINE
    return n.pos + sizeof(n);
}

inline bool operator!=(node const& n1, node const& n2)
{
    return n1.pos       != n2.pos       ||
           n1.size      != n2.size      ||
           n1.pred_pos  != n2.pred_pos  ||
           n1.allocated != n2.allocated
           ;
}

#ifndef NDEBUG
inline std::ostream& operator<<(std::ostream& out, node n)
{
    out << '(' << n.pos
        << ',' << n.size
        << ',' << n.pred_pos
        << ',' << n.allocated
         << ')';
    return out;
}
#endif

// list ---------------------------------------------------

static bool free_list_initialized = false;

inline void free_list_init(volatile uint8_t* mem, region::size_type N)
{
#pragma HLS INLINE
    make_node(mem, 0, N, 0, false);
}

inline node free_list_insert_first(volatile uint8_t* mem, region::size_type size)
{
#pragma HLS INLINE
	region::size_type addr = 0;

    node n = get_node(mem, addr);

    while (n.size < size || n.allocated)
    {
        n = next_node(mem, n);
    }

    node n1;
    n1.pos = n.pos;
    n1.size = size;
    n1.pred_pos = n.pred_pos;
    n1.allocated = true;

    node n2;
    n2.pos = n.pos + size;
    n2.size = n.size - size;
    n2.pred_pos = n.pos;
    n2.allocated = n.allocated;

    make_node(mem, n1.pos, n1.size, n1.pred_pos, n1.allocated);
    make_node(mem, n2.pos, n2.size, n2.pred_pos, n2.allocated);

    return n1;
}

#ifndef NDEBUG
inline void free_list_print(volatile uint8_t* mem, region::size_type N)
{
#ifndef __SYNTHESIS__
    node n = get_node(mem, 0);
    std::cout << "n= get_node(0): "<<n<< std::endl;

    while (n.pos + n.size < N)
    {
        n = next_node(mem, n);
        std::cout <<"n=next_node(n): "<<n<< std::endl;
    }
#endif
}
#endif

// interface ----------------------------------------------

inline region::region()
    : data(nullptr)
    , N(0)
{
}

inline region::region(volatile uint8_t* a, region::size_type n)
    : data(a)
    , N(n)
{
}

template <typename T>
inline rand_iterator<T> region::allocate(region::size_type n)
{
    if (!free_list_initialized)
    {
        free_list_init(data, N);
        free_list_initialized = true;
    }

    // Bytes
    region::size_type size = n * sizeof(T);

    node nd = free_list_insert_first(data, size + sizeof(node));

    return rand_iterator<T>(
            data,
            static_cast<difference_type>(get_data_addr(nd) / sizeof(T)) // TODO!
            );
}

template <typename T>
inline void region::deallocate(rand_iterator<T> ptr)
{
    if (!free_list_initialized)
    {
        free_list_init(data, N);
        free_list_initialized = true;
    }

    volatile uint8_t* ptr8 = ptr.data() + ptr.pos() * sizeof(T);
    node n1 = get_node_from_ptr(ptr8 - sizeof(node));
    node n2 = next_node(data, n1);

    make_node(data, n1.pos, n1.size, n1.pred_pos, false);

    if (!n2.allocated)
        merge_nodes(data, n1, n2, false);

    n1 = get_node(data, n1.pos);
    node n3 = prev_node(data, n1);

    if (!n3.allocated && n1 != n3)
        merge_nodes(data, n3, n1, false);
}

inline bool region::valid() const
{
	return data != nullptr;
}

//-------------------------------------------------------------------------------------------------
// Allocate/deallocate on one of the default memory regions
//

template <typename T>
inline rand_iterator<T> allocate(region::size_type n, region_id id)
{
    assert(id < RegionMax);

    auto reg = default_regions[id]; // Local copy, HLS seems to optimize
                                    // this away otherwise..
    return reg.allocate<T>(n);
}

template <typename T>
inline void deallocate(rand_iterator<T> ptr, region_id id)
{
    assert(id < RegionMax);

    default_regions[id].deallocate(ptr);
}

} // namespace memory
} // namespace burst
<|endoftext|>