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

  Program:   Visualization Toolkit
  Module:    vtkFloatScalars.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkFloatScalars.hh"

vtkScalars *vtkFloatScalars::MakeObject(int sze, int ext)
{
  return new vtkFloatScalars(sze,ext);
}

// Description:
// Deep copy of scalars.
vtkFloatScalars& vtkFloatScalars::operator=(const vtkFloatScalars& fs)
{
  this->S = fs.S;
  return *this;
}

void vtkFloatScalars::GetScalars(vtkIdList& ptId, vtkFloatScalars& fs)
{
  for (int i=0; i<ptId.GetNumberOfIds(); i++)
    {
    fs.InsertScalar(i,this->S.GetValue(ptId.GetId(i)));
    }
}

void vtkFloatScalars::GetScalars(int p1, int p2, vtkFloatScalars& fs)
{
  memcpy(fs.GetPtr(0), this->S.GetPtr(p1), sizeof(float)*(p2-p1+1));
}

<commit_msg>PERF: Used WritePtr instead of for loop.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkFloatScalars.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkFloatScalars.hh"

vtkScalars *vtkFloatScalars::MakeObject(int sze, int ext)
{
  return new vtkFloatScalars(sze,ext);
}

// Description:
// Deep copy of scalars.
vtkFloatScalars& vtkFloatScalars::operator=(const vtkFloatScalars& fs)
{
  this->S = fs.S;
  return *this;
}

void vtkFloatScalars::GetScalars(vtkIdList& ptId, vtkFloatScalars& fs)
{
  int NumberOfIds = ptId.GetNumberOfIds();
  float *value = fs.WritePtr (0, NumberOfIds);

  for (int i=0; i<NumberOfIds; i++, value++)
    {
    *value = this->S.GetValue(ptId.GetId(i));
    }
}

void vtkFloatScalars::GetScalars(int p1, int p2, vtkFloatScalars& fs)
{
  memcpy(fs.GetPtr(0), this->S.GetPtr(p1), sizeof(float)*(p2-p1+1));
}

<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2017 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

// Automatically generated file do not change!
#include <inviwo/core/common/inviwomodulefactoryobject.h>
#include <inviwo/core/common/version.h>
#include <@LIBRARY_HEADER@>
#include <@MODULE_HEADER@>

namespace inviwo {

InviwoModuleFactoryObject* create@MODULE@Module() {
    return new InviwoModuleFactoryObjectTemplate<@MODULE_NAME@>(
@MODULE_ARGS@
    );
}

extern "C" {

@API_DEFINE@ InviwoModuleFactoryObject* createModule() {
    return create@MODULE@Module();
}

}

}  //namespace<commit_msg>CMake: fix for static builds, closes inviwo/inviwo-dev#2065<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2017 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

// Automatically generated file do not change!
#include <inviwo/core/common/inviwomodulefactoryobject.h>
#include <inviwo/core/common/version.h>
#include <@LIBRARY_HEADER@>
#include <@MODULE_HEADER@>

namespace inviwo {

InviwoModuleFactoryObject* create@MODULE@Module() {
    return new InviwoModuleFactoryObjectTemplate<@MODULE_NAME@>(
@MODULE_ARGS@
    );
}

#ifdef INVIWO_ALL_DYN_LINK
extern "C" {
@API_DEFINE@ InviwoModuleFactoryObject* createModule() {
    return create@MODULE@Module();
}
}
#endif

}  //namespace<|endoftext|>


<commit_before><commit_msg>Bail saving window placement if the function is called after WM_DESTROY (window_delegate_ is NULL).<commit_after><|endoftext|>


<commit_before>#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif

#include "bmp_heightmap_loader.hpp"
#include "code/ylikuutio/triangulation/quad_triangulation.hpp"
#include "code/ylikuutio/common/globals.hpp"
#include "code/ylikuutio/common/global_variables.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <cstdio>   // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.
#include <cstring>  // std::memcmp, std::strcmp, std::strlen, std::strncmp
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
#include <string>   // std::string
#include <vector>   // std::vector

namespace loaders
{
    bool load_BMP_world(
            std::string image_path,
            std::vector<glm::vec3>& out_vertices,
            std::vector<glm::vec2>& out_UVs,
            std::vector<glm::vec3>& out_normals,
            uint32_t &image_width,
            uint32_t &image_height,
            std::string color_channel,
            uint32_t x_step,
            uint32_t z_step,
            std::string triangulation_type)
    {
        std::cout << "Loading BMP file " << image_path << " ...\n";

        uint8_t header_size = 54;

        // Data read from the header of the BMP file
        uint8_t header[header_size];
        uint32_t image_size;
        // Actual RGB image data.
        uint8_t *image_data;

        // Open the file
        const char* char_image_path = image_path.c_str();
        std::FILE* file = std::fopen(char_image_path, "rb");
        if (!file)
        {
            std::cerr << image_path << " could not be opened.\n";
            return false;
        }

        // Read the header, i.e. the 54 first bytes

        // If less than 54 bytes are read, it's a problem.
        if (std::fread(header, 1, sizeof(header), file) != sizeof(header))
        {
            std::cerr << "not a correct BMP file.\n";
            std::fclose(file);
            return false;
        }

        // A BMP files always begins with "BM"
        if ((header[0] != 'B') || (header[1] != 'M'))
        {
            std::cerr << "not a correct BMP file.\n";
            std::fclose(file);
            return false;
        }

        // Make sure this is a 24bpp file
        if (*(uint32_t*) &header[0x1e] != 0)
        {
            std::cerr << "not a correct BMP file.\n";
            std::fclose(file);
            return false;
        }

        if (*(uint32_t*) &header[0x1c] != 24)
        {
            std::cerr << "not a correct BMP file.\n";
            std::fclose(file);
            return false;
        }

        // Read the information about the image
        image_size = *(uint32_t*) &header[0x22];
        image_width = *(uint32_t*) &header[0x12];
        image_height = *(uint32_t*) &header[0x16];

        // Define world size.
        uint32_t world_size = image_width * image_height;

        // Some BMP files are misformatted, guess missing information
        if (image_size == 0)
        {
            image_size = image_width * image_height * 3; // 3 : one byte for each Red, Green and Blue component
        }

        // Create a buffer.
        image_data = new uint8_t[image_size];

        if (image_data == nullptr)
        {
            std::cerr << "Reserving memory for image data failed.\n";
            std::fclose(file);
            return false;
        }

        // Read the actual image data from the file into the buffer.
        if (std::fread(image_data, 1, sizeof(image_data), file) != sizeof(image_data))
        {
            std::cerr << "Reading image data from file failed.\n";
            std::fclose(file);
            delete image_data;
            return false;
        }

        // Everything is in memory now, the file can be closed
        std::fclose(file);

        uint8_t *image_pointer;
        image_pointer = image_data;

        float* vertex_data;
        vertex_data = new float[world_size];

        if (vertex_data == nullptr)
        {
            std::cerr << "Reserving memory for vertex data failed.\n";
            delete image_data;
            return false;
        }

        float* vertex_pointer;
        vertex_pointer = vertex_data;

        const char* char_color_channel = color_channel.c_str();

        // start processing image_data.
        for (int32_t z = image_height - 1; z >= 0; z--)
        {
            uint32_t image_width_in_bytes = 3 * image_width;
            image_pointer = image_data + z * image_width_in_bytes;

            for (int32_t x = 0; x < image_width; x++)
            {
                uint32_t y;

                if (std::strcmp(char_color_channel, "blue") == 0)
                {
                    y = static_cast<float>(*image_pointer);       // y-coordinate is the blue (B) value.
                }
                else if (std::strcmp(char_color_channel, "green") == 0)
                {
                    y = static_cast<float>(*(image_pointer + 1)); // y-coordinate is the green (G) value.
                }
                else if (std::strcmp(char_color_channel, "red") == 0)
                {
                    y = static_cast<float>(*(image_pointer + 2)); // y-coordinate is the red (R) value.
                }
                // y-coordinate is the mean of R, G, & B.
                else if ((std::strcmp(char_color_channel, "mean") == 0) || (std::strcmp(char_color_channel, "all") == 0))
                {
                    y = (static_cast<float>(*image_pointer) + static_cast<float>(*(image_pointer + 1)) + static_cast<float>(*(image_pointer + 2))) / 3.0f;
                }
                else
                {
                    std::cerr << "invalid color channel!\n";
                    delete image_data;
                    delete vertex_data;
                    return false;
                }

                *vertex_pointer++ = y;
                image_pointer += 3; // R, G, & B.
            }
        }

        delete image_data;

        std::cout << "color channel in use: " << color_channel << "\n";

        TriangulateQuadsStruct triangulate_quads_struct;
        triangulate_quads_struct.image_width = image_width;
        triangulate_quads_struct.image_height = image_height;
        triangulate_quads_struct.x_step = x_step;
        triangulate_quads_struct.z_step = z_step;
        triangulate_quads_struct.triangulation_type = triangulation_type;
        triangulate_quads_struct.sphere_radius = NAN;
        triangulate_quads_struct.spherical_world_struct = SphericalWorldStruct(); // not used, but is needed in the function call.

        bool result = geometry::triangulate_quads(vertex_data, triangulate_quads_struct, out_vertices, out_UVs, out_normals);
        delete vertex_data;
        return result;
    }
}
<commit_msg>Bugfix: read `header_size` (54) bytes instead of `sizeof(header)` (8).<commit_after>#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif

#include "bmp_heightmap_loader.hpp"
#include "code/ylikuutio/triangulation/quad_triangulation.hpp"
#include "code/ylikuutio/common/globals.hpp"
#include "code/ylikuutio/common/global_variables.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <cstdio>   // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.
#include <cstring>  // std::memcmp, std::strcmp, std::strlen, std::strncmp
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
#include <string>   // std::string
#include <vector>   // std::vector

namespace loaders
{
    bool load_BMP_world(
            std::string image_path,
            std::vector<glm::vec3>& out_vertices,
            std::vector<glm::vec2>& out_UVs,
            std::vector<glm::vec3>& out_normals,
            uint32_t &image_width,
            uint32_t &image_height,
            std::string color_channel,
            uint32_t x_step,
            uint32_t z_step,
            std::string triangulation_type)
    {
        std::cout << "Loading BMP file " << image_path << " ...\n";

        uint8_t header_size = 54;

        // Data read from the header of the BMP file
        uint8_t header[header_size];
        uint32_t image_size;
        // Actual RGB image data.
        uint8_t *image_data;

        // Open the file
        const char* char_image_path = image_path.c_str();
        std::FILE* file = std::fopen(char_image_path, "rb");
        if (!file)
        {
            std::cerr << image_path << " could not be opened.\n";
            return false;
        }

        // Read the header, i.e. the 54 first bytes

        // If less than 54 bytes are read, it's a problem.
        if (std::fread(header, 1, header_size, file) != header_size)
        {
            std::cerr << "not a correct BMP file.\n";
            std::fclose(file);
            return false;
        }

        // A BMP files always begins with "BM"
        if ((header[0] != 'B') || (header[1] != 'M'))
        {
            std::cerr << "not a correct BMP file.\n";
            std::fclose(file);
            return false;
        }

        // Make sure this is a 24bpp file
        if (*(uint32_t*) &header[0x1e] != 0)
        {
            std::cerr << "not a correct BMP file.\n";
            std::fclose(file);
            return false;
        }

        if (*(uint32_t*) &header[0x1c] != 24)
        {
            std::cerr << "not a correct BMP file.\n";
            std::fclose(file);
            return false;
        }

        // Read the information about the image
        image_size = *(uint32_t*) &header[0x22];
        image_width = *(uint32_t*) &header[0x12];
        image_height = *(uint32_t*) &header[0x16];

        // Define world size.
        uint32_t world_size = image_width * image_height;

        // Some BMP files are misformatted, guess missing information
        if (image_size == 0)
        {
            image_size = image_width * image_height * 3; // 3 : one byte for each Red, Green and Blue component
        }

        // Create a buffer.
        image_data = new uint8_t[image_size];

        if (image_data == nullptr)
        {
            std::cerr << "Reserving memory for image data failed.\n";
            std::fclose(file);
            return false;
        }

        // Read the actual image data from the file into the buffer.
        if (std::fread(image_data, 1, sizeof(image_data), file) != sizeof(image_data))
        {
            std::cerr << "Reading image data from file failed.\n";
            std::fclose(file);
            delete image_data;
            return false;
        }

        // Everything is in memory now, the file can be closed
        std::fclose(file);

        uint8_t *image_pointer;
        image_pointer = image_data;

        float* vertex_data;
        vertex_data = new float[world_size];

        if (vertex_data == nullptr)
        {
            std::cerr << "Reserving memory for vertex data failed.\n";
            delete image_data;
            return false;
        }

        float* vertex_pointer;
        vertex_pointer = vertex_data;

        const char* char_color_channel = color_channel.c_str();

        // start processing image_data.
        for (int32_t z = image_height - 1; z >= 0; z--)
        {
            uint32_t image_width_in_bytes = 3 * image_width;
            image_pointer = image_data + z * image_width_in_bytes;

            for (int32_t x = 0; x < image_width; x++)
            {
                uint32_t y;

                if (std::strcmp(char_color_channel, "blue") == 0)
                {
                    y = static_cast<float>(*image_pointer);       // y-coordinate is the blue (B) value.
                }
                else if (std::strcmp(char_color_channel, "green") == 0)
                {
                    y = static_cast<float>(*(image_pointer + 1)); // y-coordinate is the green (G) value.
                }
                else if (std::strcmp(char_color_channel, "red") == 0)
                {
                    y = static_cast<float>(*(image_pointer + 2)); // y-coordinate is the red (R) value.
                }
                // y-coordinate is the mean of R, G, & B.
                else if ((std::strcmp(char_color_channel, "mean") == 0) || (std::strcmp(char_color_channel, "all") == 0))
                {
                    y = (static_cast<float>(*image_pointer) + static_cast<float>(*(image_pointer + 1)) + static_cast<float>(*(image_pointer + 2))) / 3.0f;
                }
                else
                {
                    std::cerr << "invalid color channel!\n";
                    delete image_data;
                    delete vertex_data;
                    return false;
                }

                *vertex_pointer++ = y;
                image_pointer += 3; // R, G, & B.
            }
        }

        delete image_data;

        std::cout << "color channel in use: " << color_channel << "\n";

        TriangulateQuadsStruct triangulate_quads_struct;
        triangulate_quads_struct.image_width = image_width;
        triangulate_quads_struct.image_height = image_height;
        triangulate_quads_struct.x_step = x_step;
        triangulate_quads_struct.z_step = z_step;
        triangulate_quads_struct.triangulation_type = triangulation_type;
        triangulate_quads_struct.sphere_radius = NAN;
        triangulate_quads_struct.spherical_world_struct = SphericalWorldStruct(); // not used, but is needed in the function call.

        bool result = geometry::triangulate_quads(vertex_data, triangulate_quads_struct, out_vertices, out_UVs, out_normals);
        delete vertex_data;
        return result;
    }
}
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt 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.

=========================================================================*/
#ifndef __otbFuzzyDescriptorsModelManager_txx
#define __otbFuzzyDescriptorsModelManager_txx

#include "otbFuzzyDescriptorsModelManager.h"
#include "itkExceptionObject.h"
#include "itksys/SystemTools.hxx"
#include "tinyxml.h"

namespace otb {

FuzzyDescriptorsModelManager
::FuzzyDescriptorsModelManager()
{}

FuzzyDescriptorsModelManager::PairType
FuzzyDescriptorsModelManager
::GetDescriptor(const char * model, const DescriptorsModelType & descModel)
{
  PairType out;
  bool found = false;
  DescriptorsModelType::const_iterator it = descModel.begin();

  while( it!=descModel.end() && found == false)
    {
      if( (*it).first == model )
        {
          out = (*it);
        }
    }

  if( found == false )
    {
      itkGenericExceptionMacro(<<"No models named "<<model<<" found...");
    }

  return out;
}

void
FuzzyDescriptorsModelManager
::AddDescriptor( PairType modelPair, DescriptorsModelType & descModel )
{
  descModel.push_back(modelPair);
}

void
FuzzyDescriptorsModelManager
::AddDescriptor( std::string key, std::vector<double> model, DescriptorsModelType &
 descModel )
{
  PairType lPair( key, model );
  descModel.push_back(lPair);
}

void
FuzzyDescriptorsModelManager
::Print( const DescriptorsModelType & descModel )
{
  for(unsigned int i=0; i<descModel.size(); i++)
    {
      std::cout<<"Descriptor "<<descModel[i].first<<" parameters:" <<std::endl;
      const ParameterType & param = descModel[i].second;

      for(unsigned int j=0; j<param.size(); j++)
        {
          std::cout<<param[j]<<"  ";
        }
      std::cout<<std::endl;
    }
}

FuzzyDescriptorsModelManager::DescriptorsModelType
FuzzyDescriptorsModelManager
::Read(const std::string & filename)
{
  // Check if the filename is not empty
  if( filename.empty() == true )
    {
      itkGenericExceptionMacro(<<"The XML output FileName is empty");
    }

  // Check that the right extension is given : expected .xml */
  if (itksys::SystemTools::GetFilenameLastExtension(filename) != ".xml")
    {
    itkGenericExceptionMacro(<<itksys::SystemTools::GetFilenameLastExtension(filename)
                      <<" is a wrong Extension FileName : Expected .xml");
    }

  // Open the xml file
  TiXmlDocument doc(filename.c_str());
  if (!doc.LoadFile())
    {
    itkGenericExceptionMacro(<<"Can't open file "<<filename);
    }

  DescriptorsModelType descModel;

  TiXmlHandle hDoc(&doc);
  TiXmlHandle root    = hDoc.FirstChildElement("FuzzydDescriptorsModel");

  // Iterate through the tree to get all the stats
  for( TiXmlElement* currentStat = root.FirstChildElement().ToElement();
       currentStat != NULL;
       currentStat = currentStat->NextSiblingElement() )
    {
      PairType currentDescriptor;
      // Store the descriptor type name
      std::string lol;
      currentDescriptor.first = currentStat->Attribute("name");

      // The size is not stored in the XML file
      // Store the value in a std::vector, get the size and then
      // build a measurement vector
      ParameterType param;

      for( TiXmlElement* sample = currentStat->FirstChildElement("Parameter");
           sample != NULL;
           sample = sample->NextSiblingElement() )
        {
          // Get the current value of the descriptor
          double value;
          sample->QueryDoubleAttribute("value", &value);
          // Store the value
          param.push_back(value);
        }

      // Add descriptor parmaeters
      currentDescriptor.second = param;

      // Add the pai to the model
      descModel.push_back(currentDescriptor);
    }

  return descModel;
}

void
FuzzyDescriptorsModelManager
::Save(const std::string & filename, DescriptorsModelType & model )
{
  // Check if the filename is not empty
  if( filename.empty() == true )
    {
      itkGenericExceptionMacro(<<"The XML output FileName is empty");
    }

  // Check that the right extension is given : expected .xml */
  if (itksys::SystemTools::GetFilenameLastExtension(filename) != ".xml")
    {
      itkGenericExceptionMacro(<<itksys::SystemTools::GetFilenameLastExtension(filename)
                        <<" is a wrong Extension FileName : Expected .xml");
    }

  // Write the XML file
  TiXmlDocument doc;

  TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
  doc.LinkEndChild( decl );

  TiXmlElement * root = new TiXmlElement( "FuzzydDescriptorsModel");
  doc.LinkEndChild( root );

  // Iterate through the input
  for (unsigned int i = 0; i < model.size(); i++)
    {
      // The current statistic
      TiXmlElement * desc = new TiXmlElement("Descriptor");
      desc->SetAttribute("name", model[i].first.c_str());
      root->LinkEndChild( desc );

      ParameterType param = model[i].second;
      // Store the value for this statistic
      for(unsigned int cindex = 0; cindex < param.size(); ++cindex)
        {
          // For each value in Measurementvector
          TiXmlElement * curStatisticVector = new TiXmlElement("Parameter");
          curStatisticVector->SetDoubleAttribute("value", param[cindex]);
          desc->LinkEndChild(curStatisticVector);
        }
    }

  // Finally, write the file
  doc.SaveFile( filename.c_str() );
}

} // End namespace otb

#endif
<commit_msg>BUG: fixed wrong ifdef<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

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

#include "otbFuzzyDescriptorsModelManager.h"
#include "itkExceptionObject.h"
#include "itksys/SystemTools.hxx"
#include "tinyxml.h"

namespace otb {

FuzzyDescriptorsModelManager
::FuzzyDescriptorsModelManager()
{}

FuzzyDescriptorsModelManager::PairType
FuzzyDescriptorsModelManager
::GetDescriptor(const char * model, const DescriptorsModelType & descModel)
{
  PairType out;
  bool found = false;
  DescriptorsModelType::const_iterator it = descModel.begin();

  while( it!=descModel.end() && found == false)
    {
      if( (*it).first == model )
        {
          out = (*it);
        }
    }

  if( found == false )
    {
      itkGenericExceptionMacro(<<"No models named "<<model<<" found...");
    }

  return out;
}

void
FuzzyDescriptorsModelManager
::AddDescriptor( PairType modelPair, DescriptorsModelType & descModel )
{
  descModel.push_back(modelPair);
}

void
FuzzyDescriptorsModelManager
::AddDescriptor( std::string key, std::vector<double> model, DescriptorsModelType &
 descModel )
{
  PairType lPair( key, model );
  descModel.push_back(lPair);
}

void
FuzzyDescriptorsModelManager
::Print( const DescriptorsModelType & descModel )
{
  for(unsigned int i=0; i<descModel.size(); i++)
    {
      std::cout<<"Descriptor "<<descModel[i].first<<" parameters:" <<std::endl;
      const ParameterType & param = descModel[i].second;

      for(unsigned int j=0; j<param.size(); j++)
        {
          std::cout<<param[j]<<"  ";
        }
      std::cout<<std::endl;
    }
}

FuzzyDescriptorsModelManager::DescriptorsModelType
FuzzyDescriptorsModelManager
::Read(const std::string & filename)
{
  // Check if the filename is not empty
  if( filename.empty() == true )
    {
      itkGenericExceptionMacro(<<"The XML output FileName is empty");
    }

  // Check that the right extension is given : expected .xml */
  if (itksys::SystemTools::GetFilenameLastExtension(filename) != ".xml")
    {
    itkGenericExceptionMacro(<<itksys::SystemTools::GetFilenameLastExtension(filename)
                      <<" is a wrong Extension FileName : Expected .xml");
    }

  // Open the xml file
  TiXmlDocument doc(filename.c_str());
  if (!doc.LoadFile())
    {
    itkGenericExceptionMacro(<<"Can't open file "<<filename);
    }

  DescriptorsModelType descModel;

  TiXmlHandle hDoc(&doc);
  TiXmlHandle root    = hDoc.FirstChildElement("FuzzydDescriptorsModel");

  // Iterate through the tree to get all the stats
  for( TiXmlElement* currentStat = root.FirstChildElement().ToElement();
       currentStat != NULL;
       currentStat = currentStat->NextSiblingElement() )
    {
      PairType currentDescriptor;
      // Store the descriptor type name
      std::string lol;
      currentDescriptor.first = currentStat->Attribute("name");

      // The size is not stored in the XML file
      // Store the value in a std::vector, get the size and then
      // build a measurement vector
      ParameterType param;

      for( TiXmlElement* sample = currentStat->FirstChildElement("Parameter");
           sample != NULL;
           sample = sample->NextSiblingElement() )
        {
          // Get the current value of the descriptor
          double value;
          sample->QueryDoubleAttribute("value", &value);
          // Store the value
          param.push_back(value);
        }

      // Add descriptor parmaeters
      currentDescriptor.second = param;

      // Add the pai to the model
      descModel.push_back(currentDescriptor);
    }

  return descModel;
}

void
FuzzyDescriptorsModelManager
::Save(const std::string & filename, DescriptorsModelType & model )
{
  // Check if the filename is not empty
  if( filename.empty() == true )
    {
      itkGenericExceptionMacro(<<"The XML output FileName is empty");
    }

  // Check that the right extension is given : expected .xml */
  if (itksys::SystemTools::GetFilenameLastExtension(filename) != ".xml")
    {
      itkGenericExceptionMacro(<<itksys::SystemTools::GetFilenameLastExtension(filename)
                        <<" is a wrong Extension FileName : Expected .xml");
    }

  // Write the XML file
  TiXmlDocument doc;

  TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
  doc.LinkEndChild( decl );

  TiXmlElement * root = new TiXmlElement( "FuzzydDescriptorsModel");
  doc.LinkEndChild( root );

  // Iterate through the input
  for (unsigned int i = 0; i < model.size(); i++)
    {
      // The current statistic
      TiXmlElement * desc = new TiXmlElement("Descriptor");
      desc->SetAttribute("name", model[i].first.c_str());
      root->LinkEndChild( desc );

      ParameterType param = model[i].second;
      // Store the value for this statistic
      for(unsigned int cindex = 0; cindex < param.size(); ++cindex)
        {
          // For each value in Measurementvector
          TiXmlElement * curStatisticVector = new TiXmlElement("Parameter");
          curStatisticVector->SetDoubleAttribute("value", param[cindex]);
          desc->LinkEndChild(curStatisticVector);
        }
    }

  // Finally, write the file
  doc.SaveFile( filename.c_str() );
}

} // End namespace otb

<|endoftext|>


<commit_before>// Copyright 2018 Global Phasing Ltd.

#include "gemmi/chemcomp.hpp"    // for ChemComp
#include "gemmi/to_chemcomp.hpp" // for add_chemcomp_to_block
#include "gemmi/tostr.hpp"       // for tostr

#include "common.h"
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>

namespace py = pybind11;
using namespace gemmi;

PYBIND11_MAKE_OPAQUE(std::vector<Restraints::Bond>)
PYBIND11_MAKE_OPAQUE(std::vector<Restraints::Angle>)
PYBIND11_MAKE_OPAQUE(std::vector<Restraints::Torsion>)
PYBIND11_MAKE_OPAQUE(std::vector<Restraints::Chirality>)
PYBIND11_MAKE_OPAQUE(std::vector<Restraints::Plane>)
PYBIND11_MAKE_OPAQUE(std::vector<ChemComp::Atom>)

void add_chemcomp(py::module& m) {
  py::class_<ChemComp> chemcomp(m, "ChemComp");
  py::class_<ChemComp::Atom> chemcompatom(chemcomp, "Atom");

  py::class_<Restraints> restraints(m, "Restraints");
  py::class_<Restraints::Bond> restraintsbond(restraints, "Bond");
  py::class_<Restraints::Angle> restraintsangle(restraints, "Angle");
  py::class_<Restraints::Torsion> restraintstorsion(restraints, "Torsion");
  py::class_<Restraints::Chirality> restraintschirality(restraints, "Chirality");
  py::class_<Restraints::Plane> restraintsplane(restraints, "Plane");

  py::bind_vector<std::vector<Restraints::Bond>>(m, "RestraintsBonds");
  py::bind_vector<std::vector<Restraints::Angle>>(m, "RestraintsAngles");
  py::bind_vector<std::vector<Restraints::Torsion>>(m, "RestraintsTorsions");
  py::bind_vector<std::vector<Restraints::Chirality>>(m, "RestraintsChirs");
  py::bind_vector<std::vector<Restraints::Plane>>(m, "RestraintsPlanes");
  py::bind_vector<std::vector<ChemComp::Atom>>(m, "ChemCompAtoms");

  py::enum_<BondType>(m, "BondType")
    .value("Unspec", BondType::Unspec)
    .value("Single", BondType::Single)
    .value("Double", BondType::Double)
    .value("Triple", BondType::Triple)
    .value("Aromatic", BondType::Aromatic)
    .value("Deloc", BondType::Deloc)
    .value("Metal", BondType::Metal);

  py::enum_<ChiralityType>(m, "ChiralityType")
    .value("Positive", ChiralityType::Positive)
    .value("Negative", ChiralityType::Negative)
    .value("Both", ChiralityType::Both);

  py::enum_<Restraints::DistanceOf>(restraints, "DistanceOf")
    .value("ElectronCloud", Restraints::DistanceOf::ElectronCloud)
    .value("Nucleus", Restraints::DistanceOf::Nucleus);

  py::class_<Restraints::AtomId>(restraints, "AtomId")
    .def(py::init([](int comp, const std::string& atom) {
          return new Restraints::AtomId{comp, atom};
    }))
    .def(py::init([](const std::string& atom) {
          return new Restraints::AtomId{1, atom};
    }))
    .def_readwrite("comp", &Restraints::AtomId::comp)
    .def_readwrite("atom", &Restraints::AtomId::atom)
    .def("get_from",
         (Atom* (Restraints::AtomId::*)(Residue&, Residue*, char) const)
         &Restraints::AtomId::get_from,
         py::arg("res1"), py::arg("res2"), py::arg("altloc"),
         py::return_value_policy::reference)
    .def("__repr__", [](const Restraints::AtomId& self) {
        return tostr("<gemmi.Restraints.AtomId ", self.comp, ' ', self.atom, '>');
    });
  restraintsbond
    .def_readwrite("id1", &Restraints::Bond::id1)
    .def_readwrite("id2", &Restraints::Bond::id2)
    .def_readwrite("type", &Restraints::Bond::type)
    .def_readwrite("aromatic", &Restraints::Bond::aromatic)
    .def_readwrite("value", &Restraints::Bond::value)
    .def_readwrite("esd", &Restraints::Bond::esd)
    .def_readwrite("value_nucleus", &Restraints::Bond::value_nucleus)
    .def_readwrite("esd_nucleus", &Restraints::Bond::esd_nucleus)
    .def("lexicographic_str", &Restraints::Bond::lexicographic_str)
    .def("__repr__", [](const Restraints::Bond& self) {
        return "<gemmi.Restraints.Bond " + self.str() + ">";
    });
  restraintsangle
    .def_readwrite("id1", &Restraints::Angle::id1)
    .def_readwrite("id2", &Restraints::Angle::id2)
    .def_readwrite("id3", &Restraints::Angle::id3)
    .def_readwrite("value", &Restraints::Angle::value)
    .def_readwrite("esd", &Restraints::Angle::esd)
    .def("__repr__", [](const Restraints::Angle& self) {
        return "<gemmi.Restraints.Angle " + self.str() + ">";
    });
  restraintstorsion
    .def_readwrite("label", &Restraints::Torsion::label)
    .def_readwrite("id1", &Restraints::Torsion::id1)
    .def_readwrite("id2", &Restraints::Torsion::id2)
    .def_readwrite("id3", &Restraints::Torsion::id3)
    .def_readwrite("id4", &Restraints::Torsion::id4)
    .def_readwrite("value", &Restraints::Torsion::value)
    .def_readwrite("esd", &Restraints::Torsion::esd)
    .def_readwrite("period", &Restraints::Torsion::period)
    .def("__repr__", [](const Restraints::Torsion& self) {
        return "<gemmi.Restraints.Torsion " + self.str() + ">";
    });
  restraintschirality
    .def_readwrite("id_ctr", &Restraints::Chirality::id_ctr)
    .def_readwrite("id1", &Restraints::Chirality::id1)
    .def_readwrite("id2", &Restraints::Chirality::id2)
    .def_readwrite("id3", &Restraints::Chirality::id3)
    .def_readwrite("sign", &Restraints::Chirality::sign)
    .def("is_wrong", &Restraints::Chirality::is_wrong)
    .def("__repr__", [](const Restraints::Chirality& self) {
        return "<gemmi.Restraints.Chirality " + self.str() + ">";
    });
  restraintsplane
    .def_readwrite("label", &Restraints::Plane::label)
    .def_readwrite("ids", &Restraints::Plane::ids)
    .def_readwrite("esd", &Restraints::Plane::esd)
    .def("__repr__", [](const Restraints::Plane& self) {
        return "<gemmi.Restraints.Plane " + self.str() + ">";
    });
  restraints
    .def_readwrite("bonds", &Restraints::bonds)
    .def_readwrite("angles", &Restraints::angles)
    .def_readwrite("torsions", &Restraints::torsions)
    .def_readwrite("chirs", &Restraints::chirs)
    .def_readwrite("planes", &Restraints::planes)
    .def("empty", &Restraints::empty)
    .def("get_bond", &Restraints::get_bond,
         py::return_value_policy::reference_internal)
    .def("get_bond", [](Restraints& self,
                        const std::string& a1, const std::string& a2)
                                                      -> Restraints::Bond& {
            auto it = self.find_bond(a1, a2);
            if (it == self.bonds.end())
              fail("Bond restraint not found: " + a1 + "-" + a2);
            return *it;
         }, py::return_value_policy::reference_internal)
    .def("find_shortest_path", &Restraints::find_shortest_path)
    .def("chiral_abs_volume", &Restraints::chiral_abs_volume)
    ;

  chemcompatom
    .def_readonly("id", &ChemComp::Atom::id)
    .def_readonly("el", &ChemComp::Atom::el)
    .def_readonly("charge", &ChemComp::Atom::charge)
    .def_readonly("chem_type", &ChemComp::Atom::chem_type)
    .def("is_hydrogen", &ChemComp::Atom::is_hydrogen)
    ;
  chemcomp
    .def_readonly("name", &ChemComp::name)
    .def_readonly("group", &ChemComp::group)
    .def_readonly("atoms", &ChemComp::atoms)
    .def_readonly("rt", &ChemComp::rt)
    .def("get_atom", &ChemComp::get_atom)
    .def("find_atom", [](ChemComp& self, const std::string& atom_id) {
        auto it = self.find_atom(atom_id);
        return it != self.atoms.end() ? &*it : nullptr;
    }, py::return_value_policy::reference_internal)
    .def("remove_hydrogens", &ChemComp::remove_hydrogens)
    ;
  m.def("make_chemcomp_from_block", &make_chemcomp_from_block);
  m.def("add_chemcomp_to_block", &add_chemcomp_to_block);
  m.def("make_chemcomp_with_restraints", &make_chemcomp_with_restraints);
}
<commit_msg>python: make ChemComp.name/group mutable<commit_after>// Copyright 2018 Global Phasing Ltd.

#include "gemmi/chemcomp.hpp"    // for ChemComp
#include "gemmi/to_chemcomp.hpp" // for add_chemcomp_to_block
#include "gemmi/tostr.hpp"       // for tostr

#include "common.h"
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>

namespace py = pybind11;
using namespace gemmi;

PYBIND11_MAKE_OPAQUE(std::vector<Restraints::Bond>)
PYBIND11_MAKE_OPAQUE(std::vector<Restraints::Angle>)
PYBIND11_MAKE_OPAQUE(std::vector<Restraints::Torsion>)
PYBIND11_MAKE_OPAQUE(std::vector<Restraints::Chirality>)
PYBIND11_MAKE_OPAQUE(std::vector<Restraints::Plane>)
PYBIND11_MAKE_OPAQUE(std::vector<ChemComp::Atom>)

void add_chemcomp(py::module& m) {
  py::class_<ChemComp> chemcomp(m, "ChemComp");
  py::class_<ChemComp::Atom> chemcompatom(chemcomp, "Atom");

  py::class_<Restraints> restraints(m, "Restraints");
  py::class_<Restraints::Bond> restraintsbond(restraints, "Bond");
  py::class_<Restraints::Angle> restraintsangle(restraints, "Angle");
  py::class_<Restraints::Torsion> restraintstorsion(restraints, "Torsion");
  py::class_<Restraints::Chirality> restraintschirality(restraints, "Chirality");
  py::class_<Restraints::Plane> restraintsplane(restraints, "Plane");

  py::bind_vector<std::vector<Restraints::Bond>>(m, "RestraintsBonds");
  py::bind_vector<std::vector<Restraints::Angle>>(m, "RestraintsAngles");
  py::bind_vector<std::vector<Restraints::Torsion>>(m, "RestraintsTorsions");
  py::bind_vector<std::vector<Restraints::Chirality>>(m, "RestraintsChirs");
  py::bind_vector<std::vector<Restraints::Plane>>(m, "RestraintsPlanes");
  py::bind_vector<std::vector<ChemComp::Atom>>(m, "ChemCompAtoms");

  py::enum_<BondType>(m, "BondType")
    .value("Unspec", BondType::Unspec)
    .value("Single", BondType::Single)
    .value("Double", BondType::Double)
    .value("Triple", BondType::Triple)
    .value("Aromatic", BondType::Aromatic)
    .value("Deloc", BondType::Deloc)
    .value("Metal", BondType::Metal);

  py::enum_<ChiralityType>(m, "ChiralityType")
    .value("Positive", ChiralityType::Positive)
    .value("Negative", ChiralityType::Negative)
    .value("Both", ChiralityType::Both);

  py::enum_<Restraints::DistanceOf>(restraints, "DistanceOf")
    .value("ElectronCloud", Restraints::DistanceOf::ElectronCloud)
    .value("Nucleus", Restraints::DistanceOf::Nucleus);

  py::class_<Restraints::AtomId>(restraints, "AtomId")
    .def(py::init([](int comp, const std::string& atom) {
          return new Restraints::AtomId{comp, atom};
    }))
    .def(py::init([](const std::string& atom) {
          return new Restraints::AtomId{1, atom};
    }))
    .def_readwrite("comp", &Restraints::AtomId::comp)
    .def_readwrite("atom", &Restraints::AtomId::atom)
    .def("get_from",
         (Atom* (Restraints::AtomId::*)(Residue&, Residue*, char) const)
         &Restraints::AtomId::get_from,
         py::arg("res1"), py::arg("res2"), py::arg("altloc"),
         py::return_value_policy::reference)
    .def("__repr__", [](const Restraints::AtomId& self) {
        return tostr("<gemmi.Restraints.AtomId ", self.comp, ' ', self.atom, '>');
    });
  restraintsbond
    .def_readwrite("id1", &Restraints::Bond::id1)
    .def_readwrite("id2", &Restraints::Bond::id2)
    .def_readwrite("type", &Restraints::Bond::type)
    .def_readwrite("aromatic", &Restraints::Bond::aromatic)
    .def_readwrite("value", &Restraints::Bond::value)
    .def_readwrite("esd", &Restraints::Bond::esd)
    .def_readwrite("value_nucleus", &Restraints::Bond::value_nucleus)
    .def_readwrite("esd_nucleus", &Restraints::Bond::esd_nucleus)
    .def("lexicographic_str", &Restraints::Bond::lexicographic_str)
    .def("__repr__", [](const Restraints::Bond& self) {
        return "<gemmi.Restraints.Bond " + self.str() + ">";
    });
  restraintsangle
    .def_readwrite("id1", &Restraints::Angle::id1)
    .def_readwrite("id2", &Restraints::Angle::id2)
    .def_readwrite("id3", &Restraints::Angle::id3)
    .def_readwrite("value", &Restraints::Angle::value)
    .def_readwrite("esd", &Restraints::Angle::esd)
    .def("__repr__", [](const Restraints::Angle& self) {
        return "<gemmi.Restraints.Angle " + self.str() + ">";
    });
  restraintstorsion
    .def_readwrite("label", &Restraints::Torsion::label)
    .def_readwrite("id1", &Restraints::Torsion::id1)
    .def_readwrite("id2", &Restraints::Torsion::id2)
    .def_readwrite("id3", &Restraints::Torsion::id3)
    .def_readwrite("id4", &Restraints::Torsion::id4)
    .def_readwrite("value", &Restraints::Torsion::value)
    .def_readwrite("esd", &Restraints::Torsion::esd)
    .def_readwrite("period", &Restraints::Torsion::period)
    .def("__repr__", [](const Restraints::Torsion& self) {
        return "<gemmi.Restraints.Torsion " + self.str() + ">";
    });
  restraintschirality
    .def_readwrite("id_ctr", &Restraints::Chirality::id_ctr)
    .def_readwrite("id1", &Restraints::Chirality::id1)
    .def_readwrite("id2", &Restraints::Chirality::id2)
    .def_readwrite("id3", &Restraints::Chirality::id3)
    .def_readwrite("sign", &Restraints::Chirality::sign)
    .def("is_wrong", &Restraints::Chirality::is_wrong)
    .def("__repr__", [](const Restraints::Chirality& self) {
        return "<gemmi.Restraints.Chirality " + self.str() + ">";
    });
  restraintsplane
    .def_readwrite("label", &Restraints::Plane::label)
    .def_readwrite("ids", &Restraints::Plane::ids)
    .def_readwrite("esd", &Restraints::Plane::esd)
    .def("__repr__", [](const Restraints::Plane& self) {
        return "<gemmi.Restraints.Plane " + self.str() + ">";
    });
  restraints
    .def_readwrite("bonds", &Restraints::bonds)
    .def_readwrite("angles", &Restraints::angles)
    .def_readwrite("torsions", &Restraints::torsions)
    .def_readwrite("chirs", &Restraints::chirs)
    .def_readwrite("planes", &Restraints::planes)
    .def("empty", &Restraints::empty)
    .def("get_bond", &Restraints::get_bond,
         py::return_value_policy::reference_internal)
    .def("get_bond", [](Restraints& self,
                        const std::string& a1, const std::string& a2)
                                                      -> Restraints::Bond& {
            auto it = self.find_bond(a1, a2);
            if (it == self.bonds.end())
              fail("Bond restraint not found: " + a1 + "-" + a2);
            return *it;
         }, py::return_value_policy::reference_internal)
    .def("find_shortest_path", &Restraints::find_shortest_path)
    .def("chiral_abs_volume", &Restraints::chiral_abs_volume)
    ;

  chemcompatom
    .def_readonly("id", &ChemComp::Atom::id)
    .def_readonly("el", &ChemComp::Atom::el)
    .def_readonly("charge", &ChemComp::Atom::charge)
    .def_readonly("chem_type", &ChemComp::Atom::chem_type)
    .def("is_hydrogen", &ChemComp::Atom::is_hydrogen)
    ;
  chemcomp
    .def_readwrite("name", &ChemComp::name)
    .def_readwrite("group", &ChemComp::group)
    .def_readonly("atoms", &ChemComp::atoms)
    .def_readonly("rt", &ChemComp::rt)
    .def("get_atom", &ChemComp::get_atom)
    .def("find_atom", [](ChemComp& self, const std::string& atom_id) {
        auto it = self.find_atom(atom_id);
        return it != self.atoms.end() ? &*it : nullptr;
    }, py::return_value_policy::reference_internal)
    .def("remove_hydrogens", &ChemComp::remove_hydrogens)
    ;
  m.def("make_chemcomp_from_block", &make_chemcomp_from_block);
  m.def("add_chemcomp_to_block", &add_chemcomp_to_block);
  m.def("make_chemcomp_with_restraints", &make_chemcomp_with_restraints);
}
<|endoftext|>


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

  Program:   Advanced Normalization Tools
  Module:    $RCSfile: itkPreservationOfPrincipalDirectionTensorReorientationImageFilter.cxx,v $
  Language:  C++
  Date:      $Date: 2009/03/17 19:01:36 $
  Version:   $Revision: 1.2 $

  Copyright (c) ConsortiumOfANTS. All rights reserved.
  See accompanying COPYING.txt or
 http://sourceforge.net/projects/advants/files/ANTS/ANTSCopyright.txt 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.

=========================================================================*/
#ifndef _itkPreservationOfPrincipalDirectionTensorReorientationImageFilter_cxx
#define _itkPreservationOfPrincipalDirectionTensorReorientationImageFilter_cxx

#include "itkConstNeighborhoodIterator.h"
#include "itkNeighborhoodInnerProduct.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageRegionConstIterator.h"
#include "itkNeighborhoodAlgorithm.h"
#include "itkOffset.h"
#include "itkProgressReporter.h"
#include "itkObjectFactory.h"
#include "itkVector.h"
#include "itkPreservationOfPrincipalDirectionTensorReorientationImageFilter.h"
#include "itkVectorLinearInterpolateImageFunction.h"
#include "itkNumericTraitsFixedArrayPixel.h"
#include "itkCentralDifferenceImageFunction.h"

#include "itkVariableSizeMatrix.h"
#include "itkDecomposeTensorFunction.h"
#include "itkSymmetricSecondRankTensor.h"

#include <vnl/vnl_cross.h>
#include <vnl/vnl_inverse.h>
#include "vnl/algo/vnl_qr.h"
#include "vnl/algo/vnl_svd.h"
// #include <vnl/vnl_inverse_transpose.h>

namespace itk
{
template <typename TTensorImage, typename TVectorImage>
PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage, TVectorImage>
::PreservationOfPrincipalDirectionTensorReorientationImageFilter()
{
  m_DisplacementField = NULL;
  m_DirectionTransform = NULL;
  m_AffineTransform = NULL;
  m_InverseAffineTransform = NULL;
  m_UseAffine = false;
  m_UseImageDirection = true;
}

template <typename TTensorImage, typename TVectorImage>
void
PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage, TVectorImage>
::DirectionCorrectTransform( AffineTransformPointer transform, AffineTransformPointer direction )
{
  AffineTransformPointer directionTranspose = AffineTransformType::New();

  directionTranspose->SetIdentity();

  typename AffineTransformType::MatrixType dirTransposeMatrix( direction->GetMatrix().GetTranspose()  );
  directionTranspose->SetMatrix( dirTransposeMatrix );

  transform->Compose( direction, true  );
  transform->Compose( directionTranspose,   false );
}

template <typename TTensorImage, typename TVectorImage>
typename PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage, TVectorImage>::TensorType
PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage, TVectorImage>
::ApplyReorientation(InverseTransformPointer deformation, TensorType tensor )
{
  VnlMatrixType DT(3, 3);

  DT.fill(0);
  DT(0, 0) = tensor[0];
  DT(1, 1) = tensor[3];
  DT(2, 2) = tensor[5];
  DT(1, 0) = DT(0, 1) = tensor[1];
  DT(2, 0) = DT(0, 2) = tensor[2];
  DT(2, 1) = DT(1, 2) = tensor[4];

  vnl_symmetric_eigensystem<RealType> eig(DT);
  TensorType                          outTensor;

  TransformInputVectorType ev1;
  TransformInputVectorType ev2;
  TransformInputVectorType ev3;
  for( unsigned int i = 0; i < 3; i++ )
    {
    ev1[i] = eig.get_eigenvector(2)[i];
    ev2[i] = eig.get_eigenvector(1)[i];
    ev3[i] = eig.get_eigenvector(0)[i];
    }

  TransformOutputVectorType ev1r = deformation->TransformVector( ev1 );
  ev1r.Normalize();

  // Get aspect of rotated e2 that is perpendicular to rotated e1
  TransformOutputVectorType ev2a = deformation->TransformVector( ev2 );
  if( (ev2a * ev1r) < 0 )
    {
    ev2a = ev2a * (-1.0);
    }
  TransformOutputVectorType ev2r = ev2a - (ev2a * ev1r) * ev1r;
  ev2r.Normalize();

  TransformOutputVectorType ev3r = CrossProduct( ev1r, ev2r );
  ev3r.Normalize();

  VnlVectorType e1(3);
  VnlVectorType e2(3);
  VnlVectorType e3(3);
  for( unsigned int i = 0; i < 3; i++ )
    {
    e1[i] = ev1r[i];
    e2[i] = ev2r[i];
    e3[i] = ev3r[i];
    }

  VnlMatrixType DTrotated = eig.get_eigenvalue(2) * outer_product(e1, e1)
    + eig.get_eigenvalue(1) * outer_product(e2, e2) + eig.get_eigenvalue(0) * outer_product(e3, e3);

  outTensor[0] = DTrotated(0, 0);
  outTensor[1] = DTrotated(0, 1);
  outTensor[2] = DTrotated(0, 2);
  outTensor[3] = DTrotated(1, 1);
  outTensor[4] = DTrotated(1, 2);
  outTensor[5] = DTrotated(2, 2);

  return outTensor;
}

template <typename TTensorImage, typename TVectorImage>
typename PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage,
                                                                        TVectorImage>::AffineTransformPointer
PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage, TVectorImage>
::GetLocalDeformation(DisplacementFieldPointer field, typename DisplacementFieldType::IndexType index)
{
  AffineTransformPointer affineTransform = AffineTransformType::New();

  affineTransform->SetIdentity();

  typename AffineTransformType::MatrixType jMatrix;
  jMatrix.Fill(0.0);

  typename DisplacementFieldType::SizeType size = field->GetLargestPossibleRegion().GetSize();
  typename DisplacementFieldType::SpacingType spacing = field->GetSpacing();

  typename DisplacementFieldType::IndexType ddrindex;
  typename DisplacementFieldType::IndexType ddlindex;

  typename DisplacementFieldType::IndexType difIndex[ImageDimension][2];

  unsigned int posoff = 1;
  RealType     difspace = 1.0;
  RealType     space = 1.0;
  if( posoff == 0 )
    {
    difspace = 1.0;
    }
  RealType mindist = 1.0;
  RealType dist = 100.0;
  bool     oktosample = true;
  for( unsigned int row = 0; row < ImageDimension; row++ )
    {
    dist = fabs( (RealType)index[row]);
    if( dist < mindist )
      {
      oktosample = false;
      }
    dist = fabs( (RealType)size[row] - (RealType)index[row]);
    if( dist < mindist )
      {
      oktosample = false;
      }
    }

  if( oktosample )
    {
    typename DisplacementFieldType::PixelType cpix = m_DisplacementField->GetPixel(index);
    cpix = this->TransformVectorByDirection(cpix);
    // itkCentralDifferenceImageFunction does not support vector images so do this manually here
    for( unsigned int row = 0; row < ImageDimension; row++ )
      {
      difIndex[row][0] = index;
      difIndex[row][1] = index;
      ddrindex = index;
      ddlindex = index;
      if( (int) index[row] < (int)(size[row] - 2) )
        {
        difIndex[row][0][row] = index[row] + posoff;
        ddrindex[row] = index[row] + posoff * 2;
        }
      if( index[row] > 1 )
        {
        difIndex[row][1][row] = index[row] - 1;
        ddlindex[row] = index[row] - 2;
        }

      RealType h = 1;
      space = 1.0; // should use image spacing here?

      typename DisplacementFieldType::PixelType rpix = m_DisplacementField->GetPixel( difIndex[row][1] );
      typename DisplacementFieldType::PixelType lpix = m_DisplacementField->GetPixel( difIndex[row][0] );
      typename DisplacementFieldType::PixelType rrpix = m_DisplacementField->GetPixel( ddrindex );
      typename DisplacementFieldType::PixelType llpix = m_DisplacementField->GetPixel( ddlindex );

      if( this->m_UseImageDirection )
        {
        rpix = this->TransformVectorByDirection(rpix);
        lpix = this->TransformVectorByDirection(lpix);
        rrpix = this->TransformVectorByDirection(rrpix);
        llpix = this->TransformVectorByDirection(llpix);
        }

      rpix = rpix * h + cpix * (1. - h);
      lpix = lpix * h + cpix * (1. - h);
      rrpix = rrpix * h + rpix * (1. - h);
      llpix = llpix * h + lpix * (1. - h);

      typename DisplacementFieldType::PixelType dPix
        = ( lpix * 8.0 + llpix - rrpix - rpix * 8.0 ) * space / (12.0); // 4th order centered difference
      // typename DisplacementFieldType::PixelType dPix=( lpix - rpix )*space/(2.0*h); //4th order centered difference
      for( unsigned int col = 0; col < ImageDimension; col++ )
        {
        RealType val = dPix[col] / spacing[col];

        if( row == col )
          {
          val += 1.0;
          }

        jMatrix(col, row) = val;
        }
      }
    }
  for( unsigned int jx = 0; jx < ImageDimension; jx++ )
    {
    for( unsigned int jy = 0; jy < ImageDimension; jy++ )
      {
      if( !vnl_math_isfinite(jMatrix(jx, jy) )  )
        {
        oktosample = false;
        }
      }
    }

  if( !oktosample )
    {
    jMatrix.Fill(0.0);
    for( unsigned int i = 0; i < ImageDimension; i++ )
      {
      jMatrix(i, i) = 1.0;
      }
    }

  affineTransform->SetMatrix( jMatrix );
  // this->DirectionCorrectTransform( affineTransform, this->m_DirectionTransform );

  return affineTransform;
}

template <typename TTensorImage, typename TVectorImage>
void
PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage, TVectorImage>
::GenerateData()
{
  // get input and output images
  // FIXME - use buffered region, etc
  InputImagePointer  input = this->GetInput();
  OutputImagePointer output = this->GetOutput();

  this->m_DirectionTransform = AffineTransformType::New();
  this->m_DirectionTransform->SetIdentity();
  AffineTransformPointer directionTranspose = AffineTransformType::New();
  directionTranspose->SetIdentity();

  if( this->m_UseAffine )
    {
    this->m_DirectionTransform->SetMatrix( input->GetDirection() );
    if( this->m_UseImageDirection )
      {
      this->DirectionCorrectTransform( this->m_AffineTransform, this->m_DirectionTransform );
      }
    this->m_InverseAffineTransform = this->m_AffineTransform->GetInverseTransform();

    output->SetRegions( input->GetLargestPossibleRegion() );
    output->SetSpacing( input->GetSpacing() );
    output->SetOrigin( input->GetOrigin() );
    output->SetDirection( input->GetDirection() );
    output->Allocate();
    }
  else
    {
    this->m_DirectionTransform->SetMatrix( m_DisplacementField->GetDirection() );

    output->SetRegions( m_DisplacementField->GetLargestPossibleRegion() );
    output->SetSpacing( m_DisplacementField->GetSpacing() );
    output->SetOrigin( m_DisplacementField->GetOrigin() );
    output->SetDirection( m_DisplacementField->GetDirection() );
    output->Allocate();
    }

  ImageRegionIteratorWithIndex<OutputImageType> outputIt( output, output->GetLargestPossibleRegion() );

  VariableMatrixType jMatrixAvg;
  jMatrixAvg.SetSize(ImageDimension, ImageDimension);
  jMatrixAvg.Fill(0.0);
  // for all voxels
  for( outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++outputIt )
    {
    InverseTransformPointer localDeformation;

    // FIXME - eventually this will be callable via a generic transform base class
    if( this->m_UseAffine )
      {
      localDeformation = this->m_InverseAffineTransform;
      }
    else
      {
      AffineTransformPointer deformation = this->GetLocalDeformation( this->m_DisplacementField, outputIt.GetIndex() );
      localDeformation = deformation->GetInverseTransform();
      }

    TensorType inTensor = input->GetPixel(outputIt.GetIndex() );
    TensorType outTensor;

    // valid values?
    bool hasNans = false;
    for( unsigned int jj = 0; jj < 6; jj++ )
      {
      if( vnl_math_isnan( inTensor[jj] ) || vnl_math_isinf( inTensor[jj]) )
        {
        hasNans = true;;
        }
      }

    bool     isNull = false;
    RealType trace = inTensor[0] + inTensor[3] + inTensor[5];
    if( trace <= 0 )
      {
      isNull = true;
      }

    if( hasNans || isNull )
      {
      outTensor = inTensor;
      }
    else
      {
      outTensor = this->ApplyReorientation( localDeformation, inTensor );
      }
    // valid values?
    for( unsigned int jj = 0; jj < 6; jj++ )
      {
      if( vnl_math_isnan( outTensor[jj] ) || vnl_math_isinf( outTensor[jj]) )
        {
        outTensor[jj] = 0;
        }
      }

    outputIt.Set( outTensor );
    }
}

/**
 * Standard "PrintSelf" method
 */
template <typename TTensorImage, typename TVectorImage>
void
PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage, TVectorImage>
::PrintSelf(
  std::ostream& os,
  Indent indent) const
{
  Superclass::PrintSelf( os, indent );
}
} // end namespace itk

#endif
<commit_msg>FIX: updated for new transforms methods<commit_after>/*=========================================================================

  Program:   Advanced Normalization Tools
  Module:    $RCSfile: itkPreservationOfPrincipalDirectionTensorReorientationImageFilter.cxx,v $
  Language:  C++
  Date:      $Date: 2009/03/17 19:01:36 $
  Version:   $Revision: 1.2 $

  Copyright (c) ConsortiumOfANTS. All rights reserved.
  See accompanying COPYING.txt or
 http://sourceforge.net/projects/advants/files/ANTS/ANTSCopyright.txt 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.

=========================================================================*/
#ifndef _itkPreservationOfPrincipalDirectionTensorReorientationImageFilter_cxx
#define _itkPreservationOfPrincipalDirectionTensorReorientationImageFilter_cxx

#include "itkConstNeighborhoodIterator.h"
#include "itkNeighborhoodInnerProduct.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageRegionConstIterator.h"
#include "itkNeighborhoodAlgorithm.h"
#include "itkOffset.h"
#include "itkProgressReporter.h"
#include "itkObjectFactory.h"
#include "itkVector.h"
#include "itkPreservationOfPrincipalDirectionTensorReorientationImageFilter.h"
#include "itkVectorLinearInterpolateImageFunction.h"
#include "itkNumericTraitsFixedArrayPixel.h"
#include "itkCentralDifferenceImageFunction.h"

#include "itkVariableSizeMatrix.h"
#include "itkDecomposeTensorFunction.h"
#include "itkSymmetricSecondRankTensor.h"

#include <vnl/vnl_cross.h>
#include <vnl/vnl_inverse.h>
#include "vnl/algo/vnl_qr.h"
#include "vnl/algo/vnl_svd.h"
// #include <vnl/vnl_inverse_transpose.h>

namespace itk
{
template <typename TTensorImage, typename TVectorImage>
PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage, TVectorImage>
::PreservationOfPrincipalDirectionTensorReorientationImageFilter()
{
  m_DisplacementField = NULL;
  m_DirectionTransform = NULL;
  m_AffineTransform = NULL;
  m_InverseAffineTransform = NULL;
  m_UseAffine = false;
  m_UseImageDirection = true;
}

template <typename TTensorImage, typename TVectorImage>
void
PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage, TVectorImage>
::DirectionCorrectTransform( AffineTransformPointer transform, AffineTransformPointer direction )
{
  AffineTransformPointer directionTranspose = AffineTransformType::New();

  directionTranspose->SetIdentity();

  typename AffineTransformType::MatrixType dirTransposeMatrix( direction->GetMatrix().GetTranspose()  );
  directionTranspose->SetMatrix( dirTransposeMatrix );

  transform->Compose( direction, true  );
  transform->Compose( directionTranspose,   false );
}

template <typename TTensorImage, typename TVectorImage>
typename PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage, TVectorImage>::TensorType
PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage, TVectorImage>
::ApplyReorientation(InverseTransformPointer deformation, TensorType tensor )
{
  VnlMatrixType DT(3, 3);

  DT.fill(0);
  DT(0, 0) = tensor[0];
  DT(1, 1) = tensor[3];
  DT(2, 2) = tensor[5];
  DT(1, 0) = DT(0, 1) = tensor[1];
  DT(2, 0) = DT(0, 2) = tensor[2];
  DT(2, 1) = DT(1, 2) = tensor[4];

  vnl_symmetric_eigensystem<RealType> eig(DT);
  TensorType                          outTensor;

  TransformInputVectorType ev1;
  TransformInputVectorType ev2;
  TransformInputVectorType ev3;
  for( unsigned int i = 0; i < 3; i++ )
    {
    ev1[i] = eig.get_eigenvector(2)[i];
    ev2[i] = eig.get_eigenvector(1)[i];
    ev3[i] = eig.get_eigenvector(0)[i];
    }

  TransformOutputVectorType ev1r = deformation->TransformVector( ev1 );
  ev1r.Normalize();

  // Get aspect of rotated e2 that is perpendicular to rotated e1
  TransformOutputVectorType ev2a = deformation->TransformVector( ev2 );
  if( (ev2a * ev1r) < 0 )
    {
    ev2a = ev2a * (-1.0);
    }
  TransformOutputVectorType ev2r = ev2a - (ev2a * ev1r) * ev1r;
  ev2r.Normalize();

  TransformOutputVectorType ev3r = CrossProduct( ev1r, ev2r );
  ev3r.Normalize();

  VnlVectorType e1(3);
  VnlVectorType e2(3);
  VnlVectorType e3(3);
  for( unsigned int i = 0; i < 3; i++ )
    {
    e1[i] = ev1r[i];
    e2[i] = ev2r[i];
    e3[i] = ev3r[i];
    }

  VnlMatrixType DTrotated = eig.get_eigenvalue(2) * outer_product(e1, e1)
    + eig.get_eigenvalue(1) * outer_product(e2, e2) + eig.get_eigenvalue(0) * outer_product(e3, e3);

  outTensor[0] = DTrotated(0, 0);
  outTensor[1] = DTrotated(0, 1);
  outTensor[2] = DTrotated(0, 2);
  outTensor[3] = DTrotated(1, 1);
  outTensor[4] = DTrotated(1, 2);
  outTensor[5] = DTrotated(2, 2);

  return outTensor;
}

template <typename TTensorImage, typename TVectorImage>
typename PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage,
                                                                        TVectorImage>::AffineTransformPointer
PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage, TVectorImage>
::GetLocalDeformation(DisplacementFieldPointer field, typename DisplacementFieldType::IndexType index)
{
  AffineTransformPointer affineTransform = AffineTransformType::New();

  affineTransform->SetIdentity();

  typename AffineTransformType::MatrixType jMatrix;
  jMatrix.Fill(0.0);

  typename DisplacementFieldType::SizeType size = field->GetLargestPossibleRegion().GetSize();
  typename DisplacementFieldType::SpacingType spacing = field->GetSpacing();

  typename DisplacementFieldType::IndexType ddrindex;
  typename DisplacementFieldType::IndexType ddlindex;

  typename DisplacementFieldType::IndexType difIndex[ImageDimension][2];

  unsigned int posoff = 1;
  RealType     difspace = 1.0;
  RealType     space = 1.0;
  if( posoff == 0 )
    {
    difspace = 1.0;
    }
  RealType mindist = 1.0;
  RealType dist = 100.0;
  bool     oktosample = true;
  for( unsigned int row = 0; row < ImageDimension; row++ )
    {
    dist = fabs( (RealType)index[row]);
    if( dist < mindist )
      {
      oktosample = false;
      }
    dist = fabs( (RealType)size[row] - (RealType)index[row]);
    if( dist < mindist )
      {
      oktosample = false;
      }
    }

  if( oktosample )
    {
    typename DisplacementFieldType::PixelType cpix = m_DisplacementField->GetPixel(index);
    cpix = this->TransformVectorByDirection(cpix);
    // itkCentralDifferenceImageFunction does not support vector images so do this manually here
    for( unsigned int row = 0; row < ImageDimension; row++ )
      {
      difIndex[row][0] = index;
      difIndex[row][1] = index;
      ddrindex = index;
      ddlindex = index;
      if( (int) index[row] < (int)(size[row] - 2) )
        {
        difIndex[row][0][row] = index[row] + posoff;
        ddrindex[row] = index[row] + posoff * 2;
        }
      if( index[row] > 1 )
        {
        difIndex[row][1][row] = index[row] - 1;
        ddlindex[row] = index[row] - 2;
        }

      RealType h = 1;
      space = 1.0; // should use image spacing here?

      typename DisplacementFieldType::PixelType rpix = m_DisplacementField->GetPixel( difIndex[row][1] );
      typename DisplacementFieldType::PixelType lpix = m_DisplacementField->GetPixel( difIndex[row][0] );
      typename DisplacementFieldType::PixelType rrpix = m_DisplacementField->GetPixel( ddrindex );
      typename DisplacementFieldType::PixelType llpix = m_DisplacementField->GetPixel( ddlindex );

      if( this->m_UseImageDirection )
        {
        rpix = this->TransformVectorByDirection(rpix);
        lpix = this->TransformVectorByDirection(lpix);
        rrpix = this->TransformVectorByDirection(rrpix);
        llpix = this->TransformVectorByDirection(llpix);
        }

      rpix = rpix * h + cpix * (1. - h);
      lpix = lpix * h + cpix * (1. - h);
      rrpix = rrpix * h + rpix * (1. - h);
      llpix = llpix * h + lpix * (1. - h);

      typename DisplacementFieldType::PixelType dPix
        = ( lpix * 8.0 + llpix - rrpix - rpix * 8.0 ) * space / (12.0); // 4th order centered difference
      // typename DisplacementFieldType::PixelType dPix=( lpix - rpix )*space/(2.0*h); //4th order centered difference
      for( unsigned int col = 0; col < ImageDimension; col++ )
        {
        RealType val = dPix[col] / spacing[col];

        if( row == col )
          {
          val += 1.0;
          }

        jMatrix(col, row) = val;
        }
      }
    }
  for( unsigned int jx = 0; jx < ImageDimension; jx++ )
    {
    for( unsigned int jy = 0; jy < ImageDimension; jy++ )
      {
      if( !vnl_math_isfinite(jMatrix(jx, jy) )  )
        {
        oktosample = false;
        }
      }
    }

  if( !oktosample )
    {
    jMatrix.Fill(0.0);
    for( unsigned int i = 0; i < ImageDimension; i++ )
      {
      jMatrix(i, i) = 1.0;
      }
    }

  affineTransform->SetMatrix( jMatrix );
  // this->DirectionCorrectTransform( affineTransform, this->m_DirectionTransform );

  return affineTransform;
}

template <typename TTensorImage, typename TVectorImage>
void
PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage, TVectorImage>
::GenerateData()
{
  // get input and output images
  // FIXME - use buffered region, etc
  InputImagePointer  input = this->GetInput();
  OutputImagePointer output = this->GetOutput();

  this->m_DirectionTransform = AffineTransformType::New();
  this->m_DirectionTransform->SetIdentity();
  AffineTransformPointer directionTranspose = AffineTransformType::New();
  directionTranspose->SetIdentity();

  if( this->m_UseAffine )
    {
    this->m_DirectionTransform->SetMatrix( input->GetDirection() );
    if( this->m_UseImageDirection )
      {
      this->DirectionCorrectTransform( this->m_AffineTransform, this->m_DirectionTransform );
      }
    this->m_InverseAffineTransform = this->m_AffineTransform->GetInverseTransform();

    output->SetRegions( input->GetLargestPossibleRegion() );
    output->SetSpacing( input->GetSpacing() );
    output->SetOrigin( input->GetOrigin() );
    output->SetDirection( input->GetDirection() );
    output->Allocate();
    }
  else
    {
    this->m_DirectionTransform->SetMatrix( m_DisplacementField->GetDirection() );

    output->SetRegions( m_DisplacementField->GetLargestPossibleRegion() );
    output->SetSpacing( m_DisplacementField->GetSpacing() );
    output->SetOrigin( m_DisplacementField->GetOrigin() );
    output->SetDirection( m_DisplacementField->GetDirection() );
    output->Allocate();

    this->m_DisplacementTransform = DisplacementFieldTransformType::New();
    this->m_DisplacementTransform->SetDisplacementField( m_DisplacementField );
    }

  ImageRegionIteratorWithIndex<OutputImageType> outputIt( output, output->GetLargestPossibleRegion() );

  VariableMatrixType jMatrixAvg;
  jMatrixAvg.SetSize(ImageDimension, ImageDimension);
  jMatrixAvg.Fill(0.0);

  std::cout << "Iterating over image" << std::endl;
  // for all voxels
  for( outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++outputIt )
    {
    InverseTransformPointer localDeformation;

    // FIXME - eventually this will be callable via a generic transform base class
    if( this->m_UseAffine )
      {
      localDeformation = this->m_InverseAffineTransform;
      }
    else
      {
      AffineTransformPointer deformation = this->GetLocalDeformation( this->m_DisplacementField, outputIt.GetIndex() );
      localDeformation = deformation->GetInverseTransform();
      }

    TensorType inTensor = input->GetPixel(outputIt.GetIndex() );
    TensorType outTensor;

    // valid values?
    bool hasNans = false;
    for( unsigned int jj = 0; jj < 6; jj++ )
      {
      if( vnl_math_isnan( inTensor[jj] ) || vnl_math_isinf( inTensor[jj]) )
        {
        hasNans = true;;
        }
      }

    bool     isNull = false;
    RealType trace = inTensor[0] + inTensor[3] + inTensor[5];
    if( trace <= 0.0 )
      {
      isNull = true;
      }

    if( hasNans || isNull )
      {
      outTensor = inTensor;
      }
    else
      {
      // outTensor = inTensor;
      // InverseTransformPointer localDeformation;
      if( this->m_UseAffine )
        {
        outTensor = this->m_AffineTransform->TransformDiffusionTensor( inTensor );
        // localDeformation = this->m_InverseAffineTransform;
        }
      else
        {
        typename DisplacementFieldType::PointType pt;
        this->m_DisplacementField->TransformIndexToPhysicalPoint( outputIt.GetIndex(), pt );
        outTensor = this->m_DisplacementTransform->TransformDiffusionTensor( inTensor, pt );
        // AffineTransformPointer deformation = this->GetLocalDeformation( this->m_DeformationField, outputIt.GetIndex()
        // );
        // localDeformation = deformation->GetInverseTransform();
        }

      /*
      std::cout << "apply";
      outTensor = this->ApplyReorientation( localDeformation, inTensor );
      std::cout << " ok" << std::endl;
      */
      }
    // valid values?
    for( unsigned int jj = 0; jj < 6; jj++ )
      {
      if( vnl_math_isnan( outTensor[jj] ) || vnl_math_isinf( outTensor[jj]) )
        {
        outTensor[jj] = 0;
        }
      }

    outputIt.Set( outTensor );
    }
}

/**
 * Standard "PrintSelf" method
 */
template <typename TTensorImage, typename TVectorImage>
void
PreservationOfPrincipalDirectionTensorReorientationImageFilter<TTensorImage, TVectorImage>
::PrintSelf(
  std::ostream& os,
  Indent indent) const
{
  Superclass::PrintSelf( os, indent );
}
} // end namespace itk

#endif
<|endoftext|>


<commit_before>//===-- tsan_go.cc --------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// ThreadSanitizer runtime for Go language.
//
//===----------------------------------------------------------------------===//

#include "tsan_rtl.h"
#include "tsan_symbolize.h"
#include "sanitizer_common/sanitizer_common.h"
#include <stdlib.h>

namespace __tsan {

struct ThreadStatePlaceholder {
  uptr opaque[sizeof(ThreadState) / sizeof(uptr) + kCacheLineSize];
};

static ThreadState *goroutines[kMaxTid];

void InitializeInterceptors() {
}

void InitializeDynamicAnnotations() {
}

bool IsExpectedReport(uptr addr, uptr size) {
  return false;
}

void internal_start_thread(void(*func)(void*), void *arg) {
}

extern "C" int goCallbackCommentPc(uptr pc, char **img, char **rtn,
                                   char **filename, int *lineno);
extern "C" void free(void *p);

ReportStack *SymbolizeCode(uptr addr) {
  ReportStack *s = NewReportStackEntry(addr);
  char *img, *rtn, *filename;
  int lineno;
  if (goCallbackCommentPc(addr, &img, &rtn, &filename, &lineno)) {
    s->module = internal_strdup(img);
    s->offset = addr;
    s->func = internal_strdup(rtn);
    s->file = internal_strdup(filename);
    s->line = lineno;
    s->col = 0;
    free(img);
    free(rtn);
    free(filename);
  }
  return s;
}

ReportStack *SymbolizeData(uptr addr) {
  return 0;
}

ReportStack *NewReportStackEntry(uptr addr) {
  ReportStack *ent = (ReportStack*)internal_alloc(MBlockReportStack,
                                                  sizeof(ReportStack));
  internal_memset(ent, 0, sizeof(*ent));
  ent->pc = addr;
  return ent;
}

void *internal_alloc(MBlockType typ, uptr sz) {
  return InternalAlloc(sz);
}

void internal_free(void *p) {
  InternalFree(p);
}

extern "C" {

enum Tsan1EventType {
	NOOP,               // Should not appear.
	READ,               // {tid, pc, addr, size}
	WRITE,              // {tid, pc, addr, size}
	READER_LOCK,        // {tid, pc, lock, 0}
	WRITER_LOCK,        // {tid, pc, lock, 0}
	UNLOCK,             // {tid, pc, lock, 0}
	UNLOCK_OR_INIT,     // {tid, pc, lock, 0}
	LOCK_CREATE,        // {tid, pc, lock, 0}
	LOCK_DESTROY,       // {tid, pc, lock, 0}
	THR_CREATE_BEFORE,  // Parent thread's event. {tid, pc, 0, 0}
	THR_CREATE_AFTER,   // Parent thread's event. {tid, 0, 0, child_tid}/* 10 */
	THR_START,          // Child thread's event {tid, CallStack, 0, parent_tid}
	THR_FIRST_INSN,     // Used only by valgrind.
	THR_END,            // {tid, 0, 0, 0}
	THR_JOIN_AFTER,     // {tid, pc, joined_tid}
	THR_STACK_TOP,      // {tid, pc, stack_top, stack_size_if_known}
	RTN_EXIT,           // {tid, 0, 0, 0}
	RTN_CALL,           // {tid, pc, 0, 0}
	SBLOCK_ENTER,       // {tid, pc, 0, 0}
	SIGNAL,             // {tid, pc, obj, 0}
	WAIT,               // {tid, pc, obj, 0} /* 20 */
	CYCLIC_BARRIER_INIT,         // {tid, pc, obj, n}
	CYCLIC_BARRIER_WAIT_BEFORE,  // {tid, pc, obj, 0}
	CYCLIC_BARRIER_WAIT_AFTER,   // {tid, pc, obj, 0}
	PCQ_CREATE,         // {tid, pc, pcq_addr, 0}
	PCQ_DESTROY,        // {tid, pc, pcq_addr, 0}
	PCQ_PUT,            // {tid, pc, pcq_addr, 0}
	PCQ_GET,            // {tid, pc, pcq_addr, 0}
	STACK_MEM_DIE,      // deprecated.
	MALLOC,             // {tid, pc, addr, size}
	FREE,               // {tid, pc, addr, 0} /* 30 */
	MMAP,               // {tid, pc, addr, size}
	MUNMAP,             // {tid, pc, addr, size}
	PUBLISH_RANGE,      // may be deprecated later.
	UNPUBLISH_RANGE,    // deprecated. TODO(kcc): get rid of this.
	HB_LOCK,            // {tid, pc, addr, 0}
	NON_HB_LOCK,        // {tid, pc, addr, 0}
	IGNORE_READS_BEG,   // {tid, pc, 0, 0}
	IGNORE_READS_END,   // {tid, pc, 0, 0}
	IGNORE_WRITES_BEG,  // {tid, pc, 0, 0}
	IGNORE_WRITES_END,  // {tid, pc, 0, 0}
	SET_THREAD_NAME,    // {tid, pc, name_str, 0}
	SET_LOCK_NAME,      // {tid, pc, lock, lock_name_str}
	TRACE_MEM,          // {tid, pc, addr, 0}
	EXPECT_RACE,        // {tid, descr_str, ptr, size}
	BENIGN_RACE,        // {tid, descr_str, ptr, size}
	EXPECT_RACE_BEGIN,  // {tid, pc, 0, 0}
	EXPECT_RACE_END,    // {tid, pc, 0, 0}
	VERBOSITY,          // Used for debugging.
	STACK_TRACE,        // {tid, pc, 0, 0}, for debugging.
	FLUSH_STATE,        // {tid, pc, 0, 0}
	PC_DESCRIPTION,     // {0, pc, descr_str, 0}, for ts_offline.
	PRINT_MESSAGE,      // {tid, pc, message_str, 0}, for ts_offline.
	FLUSH_EXPECTED_RACES,  // {0, 0, 0, 0}
	LAST_EVENT          // Should not appear.
};

static void AllocGoroutine(int tid) {
  goroutines[tid] = (ThreadState*)internal_alloc(MBlockThreadContex,
      sizeof(ThreadState));
  internal_memset(goroutines[tid], 0, sizeof(ThreadState));
}

void __tsan_init() {
  AllocGoroutine(0);
  ThreadState *thr = goroutines[0];
  thr->in_rtl++;
  Initialize(thr);
  thr->in_rtl--;
}

void __tsan_fini() {
  // FIXME: Not necessary thread 0.
  ThreadState *thr = goroutines[0];
  thr->in_rtl++;
  int res = Finalize(thr);
  thr->in_rtl--;
  exit(res);
}

void __tsan_event(int typ, int tid, void *pc, void *addr, int info) {
  ThreadState *thr = goroutines[tid];
  switch (typ) {
  case READ:
    MemoryAccess(thr, (uptr)pc, (uptr)addr, 0, false);
    break;
  case WRITE:
    MemoryAccess(thr, (uptr)pc, (uptr)addr, 0, true);
    break;
  case RTN_EXIT:
    FuncExit(thr);
    break;
  case RTN_CALL:
    FuncEntry(thr, (uptr)pc);
    break;
  case SBLOCK_ENTER:
    break;
  case SIGNAL:
    thr->in_rtl++;
    Release(thr, (uptr)pc, (uptr)addr);
    thr->in_rtl--;
    break;
  case WAIT:
    thr->in_rtl++;
    Acquire(thr, (uptr)pc, (uptr)addr);
    thr->in_rtl--;
    break;
  case MALLOC:
    thr->in_rtl++;
    MemoryResetRange(thr, (uptr)pc, (uptr)addr, (uptr)info);
    thr->in_rtl--;
    break;
  case FREE:
    break;
  case THR_START: {
    if (tid == 0)
      return;
    ThreadState *parent = goroutines[info];
    AllocGoroutine(tid);
    thr = goroutines[tid];
    thr->in_rtl++;
    parent->in_rtl++;
    int tid2 = ThreadCreate(parent, (uptr)pc, 0, true);
    ThreadStart(thr, tid2);
    parent->in_rtl--;
    thr->in_rtl--;
    break;
  }
  case THR_END: {
    thr->in_rtl++;
    ThreadFinish(thr);
    thr->in_rtl--;
    break;
  }
  default:
    Printf("Unknown event type %d\n", typ);
    Die();
  }
}

}  // extern "C"
}  // namespace __tsan
<commit_msg>tsan: treat malloc() as memory access in Go<commit_after>//===-- tsan_go.cc --------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// ThreadSanitizer runtime for Go language.
//
//===----------------------------------------------------------------------===//

#include "tsan_rtl.h"
#include "tsan_symbolize.h"
#include "sanitizer_common/sanitizer_common.h"
#include <stdlib.h>

namespace __tsan {

struct ThreadStatePlaceholder {
  uptr opaque[sizeof(ThreadState) / sizeof(uptr) + kCacheLineSize];
};

static ThreadState *goroutines[kMaxTid];

void InitializeInterceptors() {
}

void InitializeDynamicAnnotations() {
}

bool IsExpectedReport(uptr addr, uptr size) {
  return false;
}

void internal_start_thread(void(*func)(void*), void *arg) {
}

extern "C" int goCallbackCommentPc(uptr pc, char **img, char **rtn,
                                   char **filename, int *lineno);
extern "C" void free(void *p);

ReportStack *SymbolizeCode(uptr addr) {
  ReportStack *s = NewReportStackEntry(addr);
  char *img, *rtn, *filename;
  int lineno;
  if (goCallbackCommentPc(addr, &img, &rtn, &filename, &lineno)) {
    s->module = internal_strdup(img);
    s->offset = addr;
    s->func = internal_strdup(rtn);
    s->file = internal_strdup(filename);
    s->line = lineno;
    s->col = 0;
    free(img);
    free(rtn);
    free(filename);
  }
  return s;
}

ReportStack *SymbolizeData(uptr addr) {
  return 0;
}

ReportStack *NewReportStackEntry(uptr addr) {
  ReportStack *ent = (ReportStack*)internal_alloc(MBlockReportStack,
                                                  sizeof(ReportStack));
  internal_memset(ent, 0, sizeof(*ent));
  ent->pc = addr;
  return ent;
}

void *internal_alloc(MBlockType typ, uptr sz) {
  return InternalAlloc(sz);
}

void internal_free(void *p) {
  InternalFree(p);
}

extern "C" {

enum Tsan1EventType {
	NOOP,               // Should not appear.
	READ,               // {tid, pc, addr, size}
	WRITE,              // {tid, pc, addr, size}
	READER_LOCK,        // {tid, pc, lock, 0}
	WRITER_LOCK,        // {tid, pc, lock, 0}
	UNLOCK,             // {tid, pc, lock, 0}
	UNLOCK_OR_INIT,     // {tid, pc, lock, 0}
	LOCK_CREATE,        // {tid, pc, lock, 0}
	LOCK_DESTROY,       // {tid, pc, lock, 0}
	THR_CREATE_BEFORE,  // Parent thread's event. {tid, pc, 0, 0}
	THR_CREATE_AFTER,   // Parent thread's event. {tid, 0, 0, child_tid}/* 10 */
	THR_START,          // Child thread's event {tid, CallStack, 0, parent_tid}
	THR_FIRST_INSN,     // Used only by valgrind.
	THR_END,            // {tid, 0, 0, 0}
	THR_JOIN_AFTER,     // {tid, pc, joined_tid}
	THR_STACK_TOP,      // {tid, pc, stack_top, stack_size_if_known}
	RTN_EXIT,           // {tid, 0, 0, 0}
	RTN_CALL,           // {tid, pc, 0, 0}
	SBLOCK_ENTER,       // {tid, pc, 0, 0}
	SIGNAL,             // {tid, pc, obj, 0}
	WAIT,               // {tid, pc, obj, 0} /* 20 */
	CYCLIC_BARRIER_INIT,         // {tid, pc, obj, n}
	CYCLIC_BARRIER_WAIT_BEFORE,  // {tid, pc, obj, 0}
	CYCLIC_BARRIER_WAIT_AFTER,   // {tid, pc, obj, 0}
	PCQ_CREATE,         // {tid, pc, pcq_addr, 0}
	PCQ_DESTROY,        // {tid, pc, pcq_addr, 0}
	PCQ_PUT,            // {tid, pc, pcq_addr, 0}
	PCQ_GET,            // {tid, pc, pcq_addr, 0}
	STACK_MEM_DIE,      // deprecated.
	MALLOC,             // {tid, pc, addr, size}
	FREE,               // {tid, pc, addr, 0} /* 30 */
	MMAP,               // {tid, pc, addr, size}
	MUNMAP,             // {tid, pc, addr, size}
	PUBLISH_RANGE,      // may be deprecated later.
	UNPUBLISH_RANGE,    // deprecated. TODO(kcc): get rid of this.
	HB_LOCK,            // {tid, pc, addr, 0}
	NON_HB_LOCK,        // {tid, pc, addr, 0}
	IGNORE_READS_BEG,   // {tid, pc, 0, 0}
	IGNORE_READS_END,   // {tid, pc, 0, 0}
	IGNORE_WRITES_BEG,  // {tid, pc, 0, 0}
	IGNORE_WRITES_END,  // {tid, pc, 0, 0}
	SET_THREAD_NAME,    // {tid, pc, name_str, 0}
	SET_LOCK_NAME,      // {tid, pc, lock, lock_name_str}
	TRACE_MEM,          // {tid, pc, addr, 0}
	EXPECT_RACE,        // {tid, descr_str, ptr, size}
	BENIGN_RACE,        // {tid, descr_str, ptr, size}
	EXPECT_RACE_BEGIN,  // {tid, pc, 0, 0}
	EXPECT_RACE_END,    // {tid, pc, 0, 0}
	VERBOSITY,          // Used for debugging.
	STACK_TRACE,        // {tid, pc, 0, 0}, for debugging.
	FLUSH_STATE,        // {tid, pc, 0, 0}
	PC_DESCRIPTION,     // {0, pc, descr_str, 0}, for ts_offline.
	PRINT_MESSAGE,      // {tid, pc, message_str, 0}, for ts_offline.
	FLUSH_EXPECTED_RACES,  // {0, 0, 0, 0}
	LAST_EVENT          // Should not appear.
};

static void AllocGoroutine(int tid) {
  goroutines[tid] = (ThreadState*)internal_alloc(MBlockThreadContex,
      sizeof(ThreadState));
  internal_memset(goroutines[tid], 0, sizeof(ThreadState));
}

void __tsan_init() {
  AllocGoroutine(0);
  ThreadState *thr = goroutines[0];
  thr->in_rtl++;
  Initialize(thr);
  thr->in_rtl--;
}

void __tsan_fini() {
  // FIXME: Not necessary thread 0.
  ThreadState *thr = goroutines[0];
  thr->in_rtl++;
  int res = Finalize(thr);
  thr->in_rtl--;
  exit(res);
}

void __tsan_event(int typ, int tid, void *pc, void *addr, int info) {
  ThreadState *thr = goroutines[tid];
  switch (typ) {
  case READ:
    MemoryAccess(thr, (uptr)pc, (uptr)addr, 0, false);
    break;
  case WRITE:
    MemoryAccess(thr, (uptr)pc, (uptr)addr, 0, true);
    break;
  case RTN_EXIT:
    FuncExit(thr);
    break;
  case RTN_CALL:
    FuncEntry(thr, (uptr)pc);
    break;
  case SBLOCK_ENTER:
    break;
  case SIGNAL:
    thr->in_rtl++;
    Release(thr, (uptr)pc, (uptr)addr);
    thr->in_rtl--;
    break;
  case WAIT:
    thr->in_rtl++;
    Acquire(thr, (uptr)pc, (uptr)addr);
    thr->in_rtl--;
    break;
  case MALLOC:
    thr->in_rtl++;
    MemoryResetRange(thr, (uptr)pc, (uptr)addr, (uptr)info);
    MemoryAccessRange(thr, (uptr)pc, (uptr)addr, (uptr)info, true);
    thr->in_rtl--;
    break;
  case FREE:
    break;
  case THR_START: {
    if (tid == 0)
      return;
    ThreadState *parent = goroutines[info];
    AllocGoroutine(tid);
    thr = goroutines[tid];
    thr->in_rtl++;
    parent->in_rtl++;
    int tid2 = ThreadCreate(parent, (uptr)pc, 0, true);
    ThreadStart(thr, tid2);
    parent->in_rtl--;
    thr->in_rtl--;
    break;
  }
  case THR_END: {
    thr->in_rtl++;
    ThreadFinish(thr);
    thr->in_rtl--;
    break;
  }
  default:
    Printf("Unknown event type %d\n", typ);
    Die();
  }
}

}  // extern "C"
}  // namespace __tsan
<|endoftext|>


<commit_before>//
// (C) CharLS Team 2016, all rights reserved. See the accompanying "License.txt" for licensed use.
//

#include "dicomsamples.h"
#include "util.h"
#include "../src/charls.h"
#include <iostream>
#include <vector>
#include <array>

#define COUNT(x) (sizeof(x)/sizeof((x)[0]))

namespace
{

bool contains_string(const uint8_t* container, const uint8_t* bytesToFind, unsigned int bytesLength) noexcept
{
    for (unsigned int j = 0; j < bytesLength; ++j)
    {
        if (bytesToFind[j] != container[j])
            return false;
    }

    return true;
}

int FindString(std::vector<uint8_t>& container, const uint8_t* bytesToFind, size_t bytesLength)
{
    for (size_t i = 0; i < container.size() - bytesLength; ++i)
    {
        if (contains_string(&container[i], bytesToFind, bytesLength))
            return i;
    }
    return -1;
}

void TestDicomSampleImage(const char* name)
{
    std::vector<uint8_t> data;
    const bool success = ReadFile(name, &data, 9);

    Assert::IsTrue(success);

    const std::array<uint8_t, 8> pixeldataStart = {0x00, 0x00, 0x01, 0x00, 0xFF, 0xD8, 0xFF, 0xF7};

    const int offset = FindString(data, pixeldataStart.data(), pixeldataStart.size());

    data.erase(data.begin(), data.begin() + offset - 4);

    // remove the DICOM fragment headers (in the concerned images they occur every 64k)
    for (unsigned int i =  0; i < data.size(); i+= 64 * 1024)
    {
        data.erase(data.begin() + i, data.begin() + i + 8);
    }

    JlsParameters params{};
    auto error = JpegLsReadHeader(data.data(), data.size(), &params, nullptr);
    Assert::IsTrue(error == charls::ApiResult::OK);

    std::vector<uint8_t> dataUnc;
    dataUnc.resize(static_cast<size_t>(params.stride) * params.height);

    error = JpegLsDecode(dataUnc.data(), dataUnc.size(), data.data(), data.size(), nullptr, nullptr);
    Assert::IsTrue(error == charls::ApiResult::OK);
    std::cout << ".";
}

} // namespace

void TestDicomWG4Images()
{
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/XA1_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/CT2_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/MG1_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/MR1_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/MR2_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/MR3_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/MR4_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/NM1_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/RG1_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/RG2_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/RG3_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/SC1_JLSL");
}
<commit_msg>Update size parameter to size_t<commit_after>//
// (C) CharLS Team 2016, all rights reserved. See the accompanying "License.txt" for licensed use.
//

#include "dicomsamples.h"
#include "util.h"
#include "../src/charls.h"
#include <iostream>
#include <vector>
#include <array>

#define COUNT(x) (sizeof(x)/sizeof((x)[0]))

namespace
{

bool ContainsString(const uint8_t* container, const uint8_t* bytesToFind, size_t bytesLength) noexcept
{
    for (size_t j = 0; j < bytesLength; ++j)
    {
        if (bytesToFind[j] != container[j])
            return false;
    }

    return true;
}

int FindString(std::vector<uint8_t>& container, const uint8_t* bytesToFind, size_t bytesLength)
{
    for (size_t i = 0; i < container.size() - bytesLength; ++i)
    {
        if (ContainsString(&container[i], bytesToFind, bytesLength))
            return static_cast<int>(i);
    }
    return -1;
}

void TestDicomSampleImage(const char* name)
{
    std::vector<uint8_t> data;
    const bool success = ReadFile(name, &data, 9);

    Assert::IsTrue(success);

    const std::array<uint8_t, 8> pixeldataStart = {0x00, 0x00, 0x01, 0x00, 0xFF, 0xD8, 0xFF, 0xF7};

    const int offset = FindString(data, pixeldataStart.data(), pixeldataStart.size());

    data.erase(data.begin(), data.begin() + offset - 4);

    // remove the DICOM fragment headers (in the concerned images they occur every 64k)
    for (unsigned int i =  0; i < data.size(); i+= 64 * 1024)
    {
        data.erase(data.begin() + i, data.begin() + i + 8);
    }

    JlsParameters params{};
    auto error = JpegLsReadHeader(data.data(), data.size(), &params, nullptr);
    Assert::IsTrue(error == charls::ApiResult::OK);

    std::vector<uint8_t> dataUnc;
    dataUnc.resize(static_cast<size_t>(params.stride) * params.height);

    error = JpegLsDecode(dataUnc.data(), dataUnc.size(), data.data(), data.size(), nullptr, nullptr);
    Assert::IsTrue(error == charls::ApiResult::OK);
    std::cout << ".";
}

} // namespace

void TestDicomWG4Images()
{
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/XA1_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/CT2_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/MG1_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/MR1_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/MR2_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/MR3_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/MR4_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/NM1_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/RG1_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/RG2_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/RG3_JLSL");
    TestDicomSampleImage("test/compsamples_jpegls/IMAGES/JLSL/SC1_JLSL");
}
<|endoftext|>