<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id: wkb.cpp 19 2005-03-22 13:53:27Z pavlenko $

#include <mapnik/global.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/geom_util.hpp>
#include <mapnik/feature.hpp>

// boost
#include <boost/utility.hpp>

namespace mapnik
{
struct wkb_reader : boost::noncopyable
{
private:
    enum wkbByteOrder {
        wkbXDR=0,
        wkbNDR=1
    };
    const char* wkb_;
    unsigned size_;
    unsigned pos_;
    wkbByteOrder byteOrder_;
    bool needSwap_;
    wkbFormat format_;

public:

    enum wkbGeometryType {
        wkbPoint=1,
        wkbLineString=2,
        wkbPolygon=3,
        wkbMultiPoint=4,
        wkbMultiLineString=5,
        wkbMultiPolygon=6,
        wkbGeometryCollection=7
    };

    wkb_reader(const char* wkb,unsigned size,wkbFormat format)
        : wkb_(wkb),
          size_(size),
          pos_(0),
          format_(format)
    {
        switch (format_)
        {
        case wkbSpatiaLite:
            byteOrder_ = (wkbByteOrder) wkb_[1];
            pos_ = 39;
            break;

        case wkbGeneric:
        default:
            byteOrder_ = (wkbByteOrder) wkb_[0];
            pos_ = 1;
            break;
        }

#ifndef MAPNIK_BIG_ENDIAN
        needSwap_=byteOrder_?wkbXDR:wkbNDR;
#else
        needSwap_=byteOrder_?wkbNDR:wkbXDR;
#endif
    }

    ~wkb_reader() {}

    void read_multi(Feature & feature)
    {
        int type=read_integer();
        switch (type)
        {
        case wkbPoint:
            read_point(feature);
            break;
        case wkbLineString:
            read_linestring(feature);
            break;
        case wkbPolygon:
            read_polygon(feature);
            break;
        case wkbMultiPoint:
            read_multipoint(feature);
            break;
        case wkbMultiLineString:
            read_multilinestring(feature);
            break;
        case wkbMultiPolygon:
            read_multipolygon(feature);
            break;
        case wkbGeometryCollection:
            break;
        default:
            break;
        }
    }

    void read(Feature & feature)
    {
        int type=read_integer();
        switch (type)
        {
        case wkbPoint:
            read_point(feature);
            break;
        case wkbLineString:
            read_linestring(feature);
            break;
        case wkbPolygon:
            read_polygon(feature);
            break;
        case wkbMultiPoint:
            read_multipoint_2(feature);
            break;
        case wkbMultiLineString:
            read_multilinestring_2(feature);
            break;
        case wkbMultiPolygon:
            read_multipolygon_2(feature);
            break;
        case wkbGeometryCollection:
            break;
        default:
            break;
        }
    }

private:

    int read_integer()
    {
        boost::int32_t n;
        if (needSwap_)
        {
            read_int32_xdr(wkb_+pos_,n);
        }
        else
        {
            read_int32_ndr(wkb_+pos_,n);
        }
        pos_+=4;

        return n;
    }

    double read_double()
    {
        double d;
        if (needSwap_)
        {
            read_double_xdr(wkb_ + pos_, d);
        }
        else
        {
            read_double_ndr(wkb_ + pos_, d);
        }
        pos_+=8;

        return d;
    }

    void read_coords(CoordinateArray& ar)
    {
        int size=sizeof(coord<double,2>)*ar.size();
        if (!needSwap_)
        {
            std::memcpy(&ar[0],wkb_+pos_,size);
            pos_+=size;
        }
        else
        {
            for (unsigned i=0;i<ar.size();++i)
            {
                read_double_xdr(wkb_ + pos_,ar[i].x);
                read_double_xdr(wkb_ + pos_ + 8,ar[i].y);
                pos_ += 16;
            }
        }

    }

    void read_point(Feature & feature)
    {
        geometry_type * pt = new geometry_type(Point);
        double x = read_double();
        double y = read_double();
        pt->move_to(x,y);
        feature.add_geometry(pt);
    }

    void read_multipoint(Feature & feature)
    {
        int num_points = read_integer();
        for (int i=0;i<num_points;++i)
        {
            pos_+=5;
            read_point(feature);
        }
    }

    void read_multipoint_2(Feature & feature)
    {
        geometry_type * pt = new geometry_type(Point);
        int num_points = read_integer();
        for (int i=0;i<num_points;++i)
        {
            pos_+=5;
            double x = read_double();
            double y = read_double();
            pt->move_to(x,y);
        }
        feature.add_geometry(pt);
    }

    void read_linestring(Feature & feature)
    {
        geometry_type * line = new geometry_type(LineString);
        int num_points=read_integer();
        CoordinateArray ar(num_points);
        read_coords(ar);
        line->set_capacity(num_points);
        line->move_to(ar[0].x,ar[0].y);
        for (int i=1;i<num_points;++i)
        {
            line->line_to(ar[i].x,ar[i].y);
        }
        feature.add_geometry(line);
    }

    void read_multilinestring(Feature & feature)
    {
        int num_lines=read_integer();
        for (int i=0;i<num_lines;++i)
        {
            pos_+=5;
            read_linestring(feature);
        }
    }

    void read_multilinestring_2(Feature & feature)
    {
        geometry_type * line = new geometry_type(LineString);
        int num_lines=read_integer();
        unsigned capacity = 0;
        for (int i=0;i<num_lines;++i)
        {
            pos_+=5;
            int num_points=read_integer();
            capacity+=num_points;
            CoordinateArray ar(num_points);
            read_coords(ar);
            line->set_capacity(capacity);
            line->move_to(ar[0].x,ar[0].y);
            for (int i=1;i<num_points;++i)
            {
                line->line_to(ar[i].x,ar[i].y);
            }
        }
        feature.add_geometry(line);
    }

    void read_polygon(Feature & feature)
    {
        geometry_type * poly = new geometry_type(Polygon);
        int num_rings=read_integer();
        unsigned capacity = 0;
        for (int i=0;i<num_rings;++i)
        {
            int num_points=read_integer();
            capacity+=num_points;
            CoordinateArray ar(num_points);
            read_coords(ar);
            poly->set_capacity(capacity);
            poly->move_to(ar[0].x,ar[0].y);
            for (int j=1;j<num_points;++j)
            {
                poly->line_to(ar[j].x,ar[j].y);
            }
        }
        feature.add_geometry(poly);
    }

    void read_multipolygon(Feature & feature)
    {
        int num_polys=read_integer();
        for (int i=0;i<num_polys;++i)
        {
            pos_+=5;
            read_polygon(feature);
        }
    }

    void read_multipolygon_2(Feature & feature)
    {
        geometry_type * poly = new geometry_type(Polygon);
        int num_polys=read_integer();
        unsigned capacity = 0;
        for (int i=0;i<num_polys;++i)
        {
            pos_+=5;
            int num_rings=read_integer();
            for (int i=0;i<num_rings;++i)
            {
                int num_points=read_integer();
                capacity += num_points;
                CoordinateArray ar(num_points);
                read_coords(ar);
                poly->set_capacity(capacity);
                poly->move_to(ar[0].x,ar[0].y);

                for (int j=1;j<num_points;++j)
                {
                    poly->line_to(ar[j].x,ar[j].y);
                }
                poly->line_to(ar[0].x,ar[0].y);
            }
        }
        feature.add_geometry(poly);
    }
};

void geometry_utils::from_wkb (Feature & feature,
                               const char* wkb,
                               unsigned size,
                               bool multiple_geometries,
                               wkbFormat format)
{
    wkb_reader reader(wkb,size,format);
    if (multiple_geometries)
        return reader.read_multi(feature);
    else
        return reader.read(feature);
}
}
<commit_msg>+ fixed bad errors when parsing wkb<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id: wkb.cpp 19 2005-03-22 13:53:27Z pavlenko $

#include <mapnik/global.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/geom_util.hpp>
#include <mapnik/feature.hpp>

// boost
#include <boost/utility.hpp>

namespace mapnik
{
struct wkb_reader : boost::noncopyable
{
private:
    enum wkbByteOrder {
        wkbXDR=0,
        wkbNDR=1
    };
    const char* wkb_;
    unsigned size_;
    unsigned pos_;
    wkbByteOrder byteOrder_;
    bool needSwap_;
    wkbFormat format_;

public:

    enum wkbGeometryType {
        wkbPoint=1,
        wkbLineString=2,
        wkbPolygon=3,
        wkbMultiPoint=4,
        wkbMultiLineString=5,
        wkbMultiPolygon=6,
        wkbGeometryCollection=7
    };

    wkb_reader(const char* wkb,unsigned size,wkbFormat format)
        : wkb_(wkb),
          size_(size),
          pos_(0),
          format_(format)
    {
        switch (format_)
        {
        case wkbSpatiaLite:
            byteOrder_ = (wkbByteOrder) wkb_[1];
            pos_ = 39;
            break;

        case wkbGeneric:
        default:
            byteOrder_ = (wkbByteOrder) wkb_[0];
            pos_ = 1;
            break;
        }

#ifndef MAPNIK_BIG_ENDIAN
        needSwap_=byteOrder_?wkbXDR:wkbNDR;
#else
        needSwap_=byteOrder_?wkbNDR:wkbXDR;
#endif
    }

    ~wkb_reader() {}

    void read_multi(Feature & feature)
    {
        int type=read_integer();
        switch (type)
        {
        case wkbPoint:
            read_point(feature);
            break;
        case wkbLineString:
            read_linestring(feature);
            break;
        case wkbPolygon:
            read_polygon(feature);
            break;
        case wkbMultiPoint:
            read_multipoint(feature);
            break;
        case wkbMultiLineString:
            read_multilinestring(feature);
            break;
        case wkbMultiPolygon:
            read_multipolygon(feature);
            break;
        case wkbGeometryCollection:
            break;
        default:
            break;
        }
    }

    void read(Feature & feature)
    {
        int type=read_integer();
        switch (type)
        {
        case wkbPoint:
            read_point(feature);
            break;
        case wkbLineString:
            read_linestring(feature);
            break;
        case wkbPolygon:
            read_polygon(feature);
            break;
        case wkbMultiPoint:
            read_multipoint_2(feature);
            break;
        case wkbMultiLineString:
            read_multilinestring_2(feature);
            break;
        case wkbMultiPolygon:
            read_multipolygon_2(feature);
            break;
        case wkbGeometryCollection:
            break;
        default:
            break;
        }
    }

private:

    int read_integer()
    {
        boost::int32_t n;
        if (needSwap_)
        {
            read_int32_xdr(wkb_+pos_,n);
        }
        else
        {
            read_int32_ndr(wkb_+pos_,n);
        }
        pos_+=4;

        return n;
    }

    double read_double()
    {
        double d;
        if (needSwap_)
        {
            read_double_xdr(wkb_ + pos_, d);
        }
        else
        {
            read_double_ndr(wkb_ + pos_, d);
        }
        pos_+=8;

        return d;
    }

    void read_coords(CoordinateArray& ar)
    {
        int size=sizeof(coord<double,2>)*ar.size();
        if (!needSwap_)
        {
            std::memcpy(&ar[0],wkb_+pos_,size);
            pos_+=size;
        }
        else
        {
            for (unsigned i=0;i<ar.size();++i)
            {
                read_double_xdr(wkb_ + pos_,ar[i].x);
                read_double_xdr(wkb_ + pos_ + 8,ar[i].y);
                pos_ += 16;
            }
        }

    }

    void read_point(Feature & feature)
    {
        geometry_type * pt = new geometry_type(Point);
        double x = read_double();
        double y = read_double();
        pt->move_to(x,y);
        feature.add_geometry(pt);
    }

    void read_multipoint(Feature & feature)
    {
        int num_points = read_integer();
        for (int i=0;i<num_points;++i)
        {
            pos_+=5;
            read_point(feature);
        }
    }

    void read_multipoint_2(Feature & feature)
    {
        geometry_type * pt = new geometry_type(Point);
        int num_points = read_integer();
        for (int i=0;i<num_points;++i)
        {
            pos_+=5;
            double x = read_double();
            double y = read_double();
            pt->move_to(x,y);
        }
        feature.add_geometry(pt);
    }

    void read_linestring(Feature & feature)
    {
        geometry_type * line = new geometry_type(LineString);
        int num_points=read_integer();
        CoordinateArray ar(num_points);
        read_coords(ar);
        line->set_capacity(num_points);
        line->move_to(ar[0].x,ar[0].y);
        for (int i=1;i<num_points;++i)
        {
            line->line_to(ar[i].x,ar[i].y);
        }
        feature.add_geometry(line);
    }

    void read_multilinestring(Feature & feature)
    {
        int num_lines=read_integer();
        for (int i=0;i<num_lines;++i)
        {
            pos_+=5;
            read_linestring(feature);
        }
    }

    void read_multilinestring_2(Feature & feature)
    {
        geometry_type * line = new geometry_type(LineString);
        int num_lines=read_integer();
        unsigned capacity = 0;
        for (int i=0;i<num_lines;++i)
        {
            pos_+=5;
            int num_points=read_integer();
            capacity+=num_points;
            CoordinateArray ar(num_points);
            read_coords(ar);
            line->set_capacity(capacity);
            line->move_to(ar[0].x,ar[0].y);
            for (int j=1;j<num_points;++j)
            {
                line->line_to(ar[j].x,ar[j].y);
            }
        }
        feature.add_geometry(line);
    }

    void read_polygon(Feature & feature)
    {
        geometry_type * poly = new geometry_type(Polygon);
        int num_rings=read_integer();
        unsigned capacity = 0;
        for (int i=0;i<num_rings;++i)
        {
            int num_points=read_integer();
            capacity+=num_points;
            CoordinateArray ar(num_points);
            read_coords(ar);
            poly->set_capacity(capacity);
            poly->move_to(ar[0].x,ar[0].y);
            for (int j=1;j<num_points;++j)
            {
                poly->line_to(ar[j].x,ar[j].y);
            }
        }
        feature.add_geometry(poly);
    }

    void read_multipolygon(Feature & feature)
    {
        int num_polys=read_integer();
        for (int i=0;i<num_polys;++i)
        {
            pos_+=5;
            read_polygon(feature);
        }
    }

    void read_multipolygon_2(Feature & feature)
    {
        geometry_type * poly = new geometry_type(Polygon);
        int num_polys=read_integer();
        unsigned capacity = 0;
        for (int i=0;i<num_polys;++i)
        {
            pos_+=5;
            int num_rings=read_integer();
            for (int r=0;r<num_rings;++r)
            {
                int num_points=read_integer();
                capacity += num_points;
                CoordinateArray ar(num_points);
                read_coords(ar);
                poly->set_capacity(capacity);
                poly->move_to(ar[0].x,ar[0].y);

                for (int j=1;j<num_points;++j)
                {
                    poly->line_to(ar[j].x,ar[j].y);
                }
                poly->line_to(ar[0].x,ar[0].y);
            }
        }
        feature.add_geometry(poly);
    }
};

void geometry_utils::from_wkb (Feature & feature,
                               const char* wkb,
                               unsigned size,
                               bool multiple_geometries,
                               wkbFormat format)
{
    wkb_reader reader(wkb,size,format);
    if (multiple_geometries)
        return reader.read_multi(feature);
    else
        return reader.read(feature);
}
}
<|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.

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

#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperParameter.h"
#include "otbWrapperChoiceParameter.h"
#include "itksys/SystemTools.hxx"

int main(int argc, char* argv[])
{
  if (argc < 3)
    {
    std::cerr << "Usage : " << argv[0] << " module_path  output_script" << std::endl;
    return EXIT_FAILURE;
    }
  std::string module_path(argv[1]);
  std::string output_path(argv[2]);

  otb::Wrapper::ApplicationRegistry::SetApplicationPath(module_path);

  std::vector<std::string> appList = otb::Wrapper::ApplicationRegistry::GetAvailableApplications(false);

  otb::Wrapper::Application::Pointer appPtr;

  std::ofstream ofs;
  ofs.open(output_path.c_str());

  for (unsigned int i=0 ; i < appList.size() ; ++i)
    {
    appPtr = otb::Wrapper::ApplicationRegistry::CreateApplication(appList[i],false);
    if (appPtr.IsNull())
      {
      std::cout << "Error loading application "<< appList[i] << std::endl;
      return EXIT_FAILURE;
      }
    std::vector<std::string> keys = appPtr->GetParametersKeys();

    ofs << "# completion for application "<< appList[i] << std::endl;
    ofs << "_otbcli_"<<appList[i]<<"()" << std::endl;
    ofs << "{" << std::endl;

    ofs << "  local cur prev" << std::endl;
    ofs << "  COMPREPLY=()" << std::endl;
    ofs << "  _get_comp_words_by_ref cur prev" << std::endl;
    ofs << "  case \"$cur\" in" << std::endl;
    ofs << "    -*)" << std::endl;
    ofs << "      key_list=\"";
    for (unsigned int k=0 ; k < keys.size() ; k++ )
      {
      ofs << "-" << keys[k] << " ";
      }
    ofs << "\"" << std::endl;
    ofs << "      COMPREPLY=( $( compgen -W '$key_list' -- $cur) )" << std::endl;
    ofs << "      return 0" << std::endl;
    ofs << "      ;;" << std::endl;
    ofs << "  esac" << std::endl;

    // detect choice parameters
    std::vector<std::string> choiceKeys;
    for (unsigned int k=0 ; k < keys.size() ; k++ )
      {
      if ( appPtr->GetParameterType(keys[k]) == otb::Wrapper::ParameterType_Choice)
        {
        choiceKeys.push_back(keys[k]);
        }
      }
    if (choiceKeys.size())
      {
      ofs << "  case \"$prev\" in" << std::endl;
      for (unsigned int k=0 ; k < choiceKeys.size() ; k++)
        {
        ofs << "    -" << choiceKeys[k] << ")" << std::endl;
        ofs << "      key_list=\"";
        std::vector<std::string> choices = dynamic_cast<otb::Wrapper::ChoiceParameter*>(appPtr->GetParameterByKey(choiceKeys[k]))->GetChoiceKeys();
        for (unsigned int j=0 ; j < choices.size() ; j++)
          {
          ofs << choices[j];
          if (j+1 < choices.size() )
            {
            ofs << " ";
            }
          }
        ofs << "\"" << std::endl;
        ofs << "      COMPREPLY=( $( compgen -W '$key_list' -- $cur) )" << std::endl;
        ofs << "      ;;" << std::endl;
        }
      ofs << "  esac" << std::endl;
      }

    ofs << "  return 0" << std::endl;
    ofs << "}" << std::endl;
    ofs << "complete -o default -F _otbcli_" << appList[i] << " otbcli_"<< appList[i] << std::endl;
    }
  ofs.close();

  return EXIT_SUCCESS;
}
<commit_msg>DOC: document completionGenerator usage<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 "otbWrapperApplicationRegistry.h"
#include "otbWrapperParameter.h"
#include "otbWrapperChoiceParameter.h"
#include "itksys/SystemTools.hxx"

/**
 * Small executable to :
 *  - find available application
 *  - get list of parameters
 *  - and fill a bash completion script
 *
 * This script can be sourced to be used, or deployed into a folder such as
 *    /etc/bash_completion.d
 * For choice parameters, the completion will propose the available choices
 */

int main(int argc, char* argv[])
{
  if (argc < 3)
    {
    std::cerr << "Usage : " << argv[0] << " module_path  output_script" << std::endl;
    return EXIT_FAILURE;
    }
  std::string module_path(argv[1]);
  std::string output_path(argv[2]);

  otb::Wrapper::ApplicationRegistry::SetApplicationPath(module_path);

  std::vector<std::string> appList = otb::Wrapper::ApplicationRegistry::GetAvailableApplications(false);

  otb::Wrapper::Application::Pointer appPtr;

  std::ofstream ofs;
  ofs.open(output_path.c_str());

  for (unsigned int i=0 ; i < appList.size() ; ++i)
    {
    appPtr = otb::Wrapper::ApplicationRegistry::CreateApplication(appList[i],false);
    if (appPtr.IsNull())
      {
      std::cout << "Error loading application "<< appList[i] << std::endl;
      return EXIT_FAILURE;
      }
    std::vector<std::string> keys = appPtr->GetParametersKeys();

    ofs << "# completion for application "<< appList[i] << std::endl;
    ofs << "_otbcli_"<<appList[i]<<"()" << std::endl;
    ofs << "{" << std::endl;

    ofs << "  local cur prev" << std::endl;
    ofs << "  COMPREPLY=()" << std::endl;
    ofs << "  _get_comp_words_by_ref cur prev" << std::endl;
    ofs << "  case \"$cur\" in" << std::endl;
    ofs << "    -*)" << std::endl;
    ofs << "      key_list=\"";
    for (unsigned int k=0 ; k < keys.size() ; k++ )
      {
      ofs << "-" << keys[k] << " ";
      }
    ofs << "\"" << std::endl;
    ofs << "      COMPREPLY=( $( compgen -W '$key_list' -- $cur) )" << std::endl;
    ofs << "      return 0" << std::endl;
    ofs << "      ;;" << std::endl;
    ofs << "  esac" << std::endl;

    // detect choice parameters
    std::vector<std::string> choiceKeys;
    for (unsigned int k=0 ; k < keys.size() ; k++ )
      {
      if ( appPtr->GetParameterType(keys[k]) == otb::Wrapper::ParameterType_Choice)
        {
        choiceKeys.push_back(keys[k]);
        }
      }
    if (choiceKeys.size())
      {
      ofs << "  case \"$prev\" in" << std::endl;
      for (unsigned int k=0 ; k < choiceKeys.size() ; k++)
        {
        ofs << "    -" << choiceKeys[k] << ")" << std::endl;
        ofs << "      key_list=\"";
        std::vector<std::string> choices = dynamic_cast<otb::Wrapper::ChoiceParameter*>(appPtr->GetParameterByKey(choiceKeys[k]))->GetChoiceKeys();
        for (unsigned int j=0 ; j < choices.size() ; j++)
          {
          ofs << choices[j];
          if (j+1 < choices.size() )
            {
            ofs << " ";
            }
          }
        ofs << "\"" << std::endl;
        ofs << "      COMPREPLY=( $( compgen -W '$key_list' -- $cur) )" << std::endl;
        ofs << "      ;;" << std::endl;
        }
      ofs << "  esac" << std::endl;
      }

    ofs << "  return 0" << std::endl;
    ofs << "}" << std::endl;
    ofs << "complete -o default -F _otbcli_" << appList[i] << " otbcli_"<< appList[i] << std::endl;
    }
  ofs.close();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * DefaultForwardChainerCB.cc
 *
 * Copyright (C) 2015 Misgana Bayetta
 *
 * Author: Misgana Bayetta <misgana.bayetta@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <opencog/atomutils/AtomUtils.h>
#include <opencog/guile/SchemeSmob.h>
#include <opencog/atoms/bind/BindLink.h>

#include "DefaultForwardChainerCB.h"
#include "PLNCommons.h"

using namespace opencog;

DefaultForwardChainerCB::DefaultForwardChainerCB(
        AtomSpace* as, source_selection_mode ts_mode /*=TV_FITNESS_BASED*/) :
        ForwardChainerCallBack(as)
{
    as_ = as;
    fcim_ = new ForwardChainInputMatchCB(as);
    fcpm_ = new ForwardChainPatternMatchCB(as);
    ts_mode_ = ts_mode;
}

DefaultForwardChainerCB::~DefaultForwardChainerCB()
{
    delete fcim_;
    delete fcpm_;
}

/**
 * choose rule based on premises of rule matching the source
 * uses temporary atomspace to limit the search space
 *
 * @param fcmem forward chainer's working memory
 * @return a vector of chosen rules
 */

vector<Rule*> DefaultForwardChainerCB::choose_rule(FCMemory& fcmem)
{
    Handle source = fcmem.get_cur_source();
    if (source == Handle::UNDEFINED or NodeCast(source))
        throw InvalidParamException(TRACE_INFO,
                                    "Needs a source atom of type LINK");
    HandleSeq chosen_bindlinks;

    if (LinkCast(source)) {
        AtomSpace rule_atomspace;
        Handle source_cpy = rule_atomspace.addAtom(source);

        // Copy rules to the temporary atomspace.
        vector<Rule*> rules = fcmem.get_rules();
        for (Rule* r : rules) {
            rule_atomspace.addAtom(r->get_handle());
        }

        // Create bindlink with source as an implicant.
        PLNCommons pc(&rule_atomspace);
        Handle copy = pc.replace_nodes_with_varnode(source_cpy, NODE);
        Handle bind_link = pc.create_bindLink(copy, false);

        // Pattern match.
        BindLinkPtr bl(BindLinkCast(bind_link));
        DefaultImplicator imp(&rule_atomspace);
        imp.implicand = bl->get_implicand();
        imp.set_type_restrictions(bl->get_typemap());
        bl->imply(&imp);

        // Get matched bindLinks.
        HandleSeq matches = imp.result_list;
        if (matches.empty()) {
            logger().debug(
                    "No matching BindLink was found.Returning empty vector");
            return vector<Rule*> { };
        }

        HandleSeq bindlinks;
        for (Handle hm : matches) {
            //get all BindLinks whose part of their premise matches with hm
            HandleSeq hs = get_rootlinks(hm, &rule_atomspace, BIND_LINK);
            for (Handle hi : hs) {
                if (find(bindlinks.begin(), bindlinks.end(), hi) == bindlinks.end()) {
                    bindlinks.push_back(hi);
                }
            }
        }

        // Copy handles to main atomspace.
        for (Handle h : bindlinks) {
            chosen_bindlinks.push_back(as_->addAtom(h));
        }
    }

    // Try to find specialized rules that contain the source node.
    if (NodeCast(source)) {
        chosen_bindlinks = get_rootlinks(source, as_, BIND_LINK);
    }

    // Find the rules containing the bindLink in copied_back.
    vector<Rule*> matched_rules;
    vector<Rule*> rules = fcmem.get_rules();
    for (Rule* r : rules) {
        auto it = find(chosen_bindlinks.begin(), chosen_bindlinks.end(),
                       r->get_handle()); //xxx not matching
        if (it != chosen_bindlinks.end()) {
            matched_rules.push_back(r);
        }
    }

    return matched_rules;
}

/**
 * Gets all top level links of certain types and subclasses that
 * contain @param hsource
 *
 * @param hsource handle whose top level links are to be searched
 * @param as the atomspace in which search is to be done
 * @param link_type the root link types to be searched
 * @param subclasses a flag that tells to look subclasses of @link_type
 */
HandleSeq DefaultForwardChainerCB::get_rootlinks(Handle hsource, AtomSpace* as,
                                                 Type link_type,
                                                 bool subclasses)
{
    auto outgoing = [as](Handle h) {return as->getOutgoing(h);};
    PLNCommons pc(as);
    HandleSeq chosen_roots;
    HandleSeq candidates_roots;
    pc.get_root_links(hsource, candidates_roots);

    for (Handle hr : candidates_roots) {
        bool notexist = find(chosen_roots.begin(), chosen_roots.end(), hr)
                == chosen_roots.end();
        auto type = as->getType(hr);
        bool subtype = (subclasses and classserver().isA(type, link_type));
        if (((type == link_type) or subtype) and notexist) {
            //make sure matches are actually part of the premise list rather than the output of the bindLink
            Handle hpremise = outgoing(outgoing(hr)[1])[0]; //extracting premise from (BindLink((ListLinK..)(ImpLink (premise) (..))))
            if (pc.exists_in(hpremise, hsource)) {
                chosen_roots.push_back(hr);
            }
        }

    }

    return chosen_roots;
}
HandleSeq DefaultForwardChainerCB::choose_premises(FCMemory& fcmem)
{
    HandleSeq inputs;
    PLNCommons pc(as_);
    Handle hsource = fcmem.get_cur_source();

    // Get everything associated with the source handle.
    UnorderedHandleSet neighbors = get_distant_neighbors(hsource, 2);

    // Add all root links of atoms in @param neighbors.
    for (auto hn : neighbors) {
        if (hn->getType() != VARIABLE_NODE) {
            HandleSeq roots;
            pc.get_root_links(hn, roots);
            for (auto r : roots) {
                if (find(inputs.begin(), inputs.end(), r) == inputs.end() and r->getType()
                        != BIND_LINK)
                    inputs.push_back(r);
            }
        }
    }

    return inputs;
}

Handle DefaultForwardChainerCB::choose_next_source(FCMemory& fcmem)
{
    HandleSeq tlist = fcmem.get_premise_list();
    map<Handle, float> tournament_elem;
    PLNCommons pc(as_);
    Handle hchosen = Handle::UNDEFINED;

    for (Handle t : tlist) {
        switch (ts_mode_) {
        case TV_FITNESS_BASED: {
            float fitness = pc.tv_fitness(t);
            tournament_elem[t] = fitness;
        }
            break;
        case STI_BASED:
            tournament_elem[t] = t->getSTI();
            break;
        default:
            throw RuntimeException(TRACE_INFO,
                                   "Unknown source selection mode.");
            break;
        }
    }

    //!Choose a new source that has never been chosen before.
    //!xxx FIXME since same handle might be chosen multiple times the following
    //!code doesn't guarantee all sources have been exhaustively looked.
    for (size_t i = 0; i < tournament_elem.size(); i++) {
        Handle hselected = pc.tournament_select(tournament_elem);
        if (fcmem.isin_source_list(hselected)) {
            continue;
        } else {
            hchosen = hselected;
            break;
        }
    }

    return hchosen;
}

//TODO applier should check on atoms (Inference.matched_atoms when Inference.Rule =Cur_Rule), for mutex rules
HandleSeq DefaultForwardChainerCB::apply_rule(FCMemory& fcmem)
{
    Rule * cur_rule = fcmem.get_cur_rule();
    fcpm_->set_fcmem(&fcmem);

    BindLinkPtr bl(BindLinkCast(cur_rule->get_handle()));
    bl->imply(fcpm_);

    HandleSeq product = fcpm_->get_products();

    //! Make sure the inferences made are new.
    HandleSeq new_product;
    for (auto h : product) {
        if (not fcmem.isin_premise_list(h))
            new_product.push_back(h);
    }

    return new_product;
}
<commit_msg>Set ForwardChainPatternMatchCB implicand and type restrictions<commit_after>/*
 * DefaultForwardChainerCB.cc
 *
 * Copyright (C) 2015 Misgana Bayetta
 *
 * Author: Misgana Bayetta <misgana.bayetta@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <opencog/atomutils/AtomUtils.h>
#include <opencog/guile/SchemeSmob.h>
#include <opencog/atoms/bind/BindLink.h>

#include "DefaultForwardChainerCB.h"
#include "PLNCommons.h"

using namespace opencog;

DefaultForwardChainerCB::DefaultForwardChainerCB(
        AtomSpace* as, source_selection_mode ts_mode /*=TV_FITNESS_BASED*/) :
        ForwardChainerCallBack(as)
{
    as_ = as;
    fcim_ = new ForwardChainInputMatchCB(as);
    fcpm_ = new ForwardChainPatternMatchCB(as);
    ts_mode_ = ts_mode;
}

DefaultForwardChainerCB::~DefaultForwardChainerCB()
{
    delete fcim_;
    delete fcpm_;
}

/**
 * choose rule based on premises of rule matching the source
 * uses temporary atomspace to limit the search space
 *
 * @param fcmem forward chainer's working memory
 * @return a vector of chosen rules
 */

vector<Rule*> DefaultForwardChainerCB::choose_rule(FCMemory& fcmem)
{
    Handle source = fcmem.get_cur_source();
    if (source == Handle::UNDEFINED or NodeCast(source))
        throw InvalidParamException(TRACE_INFO,
                                    "Needs a source atom of type LINK");
    HandleSeq chosen_bindlinks;

    if (LinkCast(source)) {
        AtomSpace rule_atomspace;
        Handle source_cpy = rule_atomspace.addAtom(source);

        // Copy rules to the temporary atomspace.
        vector<Rule*> rules = fcmem.get_rules();
        for (Rule* r : rules) {
            rule_atomspace.addAtom(r->get_handle());
        }

        // Create bindlink with source as an implicant.
        PLNCommons pc(&rule_atomspace);
        Handle copy = pc.replace_nodes_with_varnode(source_cpy, NODE);
        Handle bind_link = pc.create_bindLink(copy, false);

        // Pattern match.
        BindLinkPtr bl(BindLinkCast(bind_link));
        DefaultImplicator imp(&rule_atomspace);
        imp.implicand = bl->get_implicand();
        imp.set_type_restrictions(bl->get_typemap());
        bl->imply(&imp);

        // Get matched bindLinks.
        HandleSeq matches = imp.result_list;
        if (matches.empty()) {
            logger().debug(
                    "No matching BindLink was found.Returning empty vector");
            return vector<Rule*> { };
        }

        HandleSeq bindlinks;
        for (Handle hm : matches) {
            //get all BindLinks whose part of their premise matches with hm
            HandleSeq hs = get_rootlinks(hm, &rule_atomspace, BIND_LINK);
            for (Handle hi : hs) {
                if (find(bindlinks.begin(), bindlinks.end(), hi) == bindlinks.end()) {
                    bindlinks.push_back(hi);
                }
            }
        }

        // Copy handles to main atomspace.
        for (Handle h : bindlinks) {
            chosen_bindlinks.push_back(as_->addAtom(h));
        }
    }

    // Try to find specialized rules that contain the source node.
    if (NodeCast(source)) {
        chosen_bindlinks = get_rootlinks(source, as_, BIND_LINK);
    }

    // Find the rules containing the bindLink in copied_back.
    vector<Rule*> matched_rules;
    vector<Rule*> rules = fcmem.get_rules();
    for (Rule* r : rules) {
        auto it = find(chosen_bindlinks.begin(), chosen_bindlinks.end(),
                       r->get_handle()); //xxx not matching
        if (it != chosen_bindlinks.end()) {
            matched_rules.push_back(r);
        }
    }

    return matched_rules;
}

/**
 * Gets all top level links of certain types and subclasses that
 * contain @param hsource
 *
 * @param hsource handle whose top level links are to be searched
 * @param as the atomspace in which search is to be done
 * @param link_type the root link types to be searched
 * @param subclasses a flag that tells to look subclasses of @link_type
 */
HandleSeq DefaultForwardChainerCB::get_rootlinks(Handle hsource, AtomSpace* as,
                                                 Type link_type,
                                                 bool subclasses)
{
    auto outgoing = [as](Handle h) {return as->getOutgoing(h);};
    PLNCommons pc(as);
    HandleSeq chosen_roots;
    HandleSeq candidates_roots;
    pc.get_root_links(hsource, candidates_roots);

    for (Handle hr : candidates_roots) {
        bool notexist = find(chosen_roots.begin(), chosen_roots.end(), hr)
                == chosen_roots.end();
        auto type = as->getType(hr);
        bool subtype = (subclasses and classserver().isA(type, link_type));
        if (((type == link_type) or subtype) and notexist) {
            //make sure matches are actually part of the premise list rather than the output of the bindLink
            Handle hpremise = outgoing(outgoing(hr)[1])[0]; //extracting premise from (BindLink((ListLinK..)(ImpLink (premise) (..))))
            if (pc.exists_in(hpremise, hsource)) {
                chosen_roots.push_back(hr);
            }
        }

    }

    return chosen_roots;
}
HandleSeq DefaultForwardChainerCB::choose_premises(FCMemory& fcmem)
{
    HandleSeq inputs;
    PLNCommons pc(as_);
    Handle hsource = fcmem.get_cur_source();

    // Get everything associated with the source handle.
    UnorderedHandleSet neighbors = get_distant_neighbors(hsource, 2);

    // Add all root links of atoms in @param neighbors.
    for (auto hn : neighbors) {
        if (hn->getType() != VARIABLE_NODE) {
            HandleSeq roots;
            pc.get_root_links(hn, roots);
            for (auto r : roots) {
                if (find(inputs.begin(), inputs.end(), r) == inputs.end() and r->getType()
                        != BIND_LINK)
                    inputs.push_back(r);
            }
        }
    }

    return inputs;
}

Handle DefaultForwardChainerCB::choose_next_source(FCMemory& fcmem)
{
    HandleSeq tlist = fcmem.get_premise_list();
    map<Handle, float> tournament_elem;
    PLNCommons pc(as_);
    Handle hchosen = Handle::UNDEFINED;

    for (Handle t : tlist) {
        switch (ts_mode_) {
        case TV_FITNESS_BASED: {
            float fitness = pc.tv_fitness(t);
            tournament_elem[t] = fitness;
        }
            break;
        case STI_BASED:
            tournament_elem[t] = t->getSTI();
            break;
        default:
            throw RuntimeException(TRACE_INFO,
                                   "Unknown source selection mode.");
            break;
        }
    }

    //!Choose a new source that has never been chosen before.
    //!xxx FIXME since same handle might be chosen multiple times the following
    //!code doesn't guarantee all sources have been exhaustively looked.
    for (size_t i = 0; i < tournament_elem.size(); i++) {
        Handle hselected = pc.tournament_select(tournament_elem);
        if (fcmem.isin_source_list(hselected)) {
            continue;
        } else {
            hchosen = hselected;
            break;
        }
    }

    return hchosen;
}

//TODO applier should check on atoms (Inference.matched_atoms when Inference.Rule =Cur_Rule), for mutex rules
HandleSeq DefaultForwardChainerCB::apply_rule(FCMemory& fcmem)
{
    Rule * cur_rule = fcmem.get_cur_rule();
    fcpm_->set_fcmem(&fcmem);

    BindLinkPtr bl(BindLinkCast(cur_rule->get_handle()));
    fcpm_->implicand = bl->get_implicand();
    fcpm_->set_type_restrictions(bl->get_typemap());
    bl->imply(fcpm_);

    HandleSeq product = fcpm_->get_products();

    //! Make sure the inferences made are new.
    HandleSeq new_product;
    for (auto h : product) {
        if (not fcmem.isin_premise_list(h))
            new_product.push_back(h);
    }

    return new_product;
}
<|endoftext|>


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

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

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

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

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

// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif

#include "itkFEMSolverCrankNicolson.h"

#include "FEM/itkFEMLoadNode.h"
#include "FEM/itkFEMLoadElementBase.h"
#include "FEM/itkFEMLoadBCMFC.h"

#include "FEM/itkFEMUtility.h"
#include "FEM/itkFEMObjectFactory.h"

namespace itk {
namespace fem {

void SolverCrankNicolson::InitializeForSolution()
{
  m_ls->SetSystemOrder(NGFN+NMFC);
  m_ls->SetNumberOfVectors(5);
  m_ls->SetNumberOfSolutions(2);
  m_ls->SetNumberOfMatrices(2);
  m_ls->InitializeMatrix(SumMatrixIndex);
  m_ls->InitializeMatrix(DifferenceMatrixIndex);
  m_ls->InitializeVector(ForceTIndex);
  m_ls->InitializeVector(ForceTMinus1Index);
  m_ls->InitializeVector(SolutionTMinus1Index);
  m_ls->InitializeVector(DiffMatrixBySolutionTMinus1Index);
  m_ls->InitializeSolution(SolutionTIndex);
  m_ls->InitializeSolution(TotalSolutionIndex);
}

/*
 * Assemble the master stiffness matrix (also apply the MFCs to K)
 */
void SolverCrankNicolson::AssembleKandM()
{

  // if no DOFs exist in a system, we have nothing to do
  if (NGFN<=0) return;

  NMFC=0;  // number of MFC in a system

  // temporary storage for pointers to LoadBCMFC objects
  typedef std::vector<LoadBCMFC::Pointer> MFCArray;
  MFCArray mfcLoads;

  /*
   * Before we can start the assembly procedure, we need to know,
   * how many boundary conditions (MFCs) there are in a system.
   */
  mfcLoads.clear();
  // search for MFC's in Loads array, because they affect the master stiffness matrix
  for(LoadArray::iterator l=load.begin(); l!=load.end(); l++) {
    if ( LoadBCMFC::Pointer l1=dynamic_cast<LoadBCMFC*>( &(*(*l))) ) {
      // store the index of an LoadBCMFC object for later
      l1->Index=NMFC;
      // store the pointer to a LoadBCMFC object for later
      mfcLoads.push_back(l1);
      // increase the number of MFC
      NMFC++;
    }
  }

  /*
   * Now we can assemble the master stiffness matrix
   * from element stiffness matrices
   */
  InitializeForSolution();

std::cout << "Begin Assembly." << std::endl;
  /*
   * Step over all elements
   */
  for(ElementArray::iterator e=el.begin(); e!=el.end(); e++)
  {
    vnl_matrix<Float> Ke=(*e)->Ke();  /*Copy the element stiffness matrix for faster access. */
    vnl_matrix<Float> Me=(*e)->Me();  /*Copy the element mass matrix for faster access. */
    int Ne=(*e)->GetNumberOfDegreesOfFreedom();          /*... same for element DOF */

    /* step over all rows in in element matrix */
    for(int j=0; j<Ne; j++)
    {
      /* step over all columns in in element matrix */
      for(int k=0; k<Ne; k++)
      {
        /* error checking. all GFN should be =>0 and <NGFN */
        if ( (*e)->GetDegreeOfFreedom(j) < 0 ||
             (*e)->GetDegreeOfFreedom(j) >= NGFN ||
             (*e)->GetDegreeOfFreedom(k) < 0 ||
             (*e)->GetDegreeOfFreedom(k) >= NGFN  )
        {
          throw FEMExceptionSolution(__FILE__,__LINE__,"SolverCrankNicolson::AssembleK()","Illegal GFN!");
        }

        /* Here we finaly update the corresponding element
         * in the master stiffness matrix. We first check if
         * element in Ke is zero, to prevent zeros from being
         * allocated in sparse matrix.
         */
        if ( Ke(j,k)!=Float(0.0) || Me(j,k) != Float(0.0) )
        {
          // left hand side matrix
          Float temp1=Ke(j,k), temp2=Me(j,k);
          Float lhsval=(Me(j,k) + m_alpha*m_deltaT*Ke(j,k));
          m_ls->AddMatrixValue( (*e)->GetDegreeOfFreedom(j) ,
                    (*e)->GetDegreeOfFreedom(k),
                    lhsval, SumMatrixIndex );
          //if (j==k) std::cout << temp1 << " " << temp2 << endl;
          // right hand side matrix
          Float rhsval=(Me(j,k) - (1.-m_alpha)*m_deltaT*Ke(j,k));
          m_ls->AddMatrixValue( (*e)->GetDegreeOfFreedom(j) ,
                    (*e)->GetDegreeOfFreedom(k),
                    rhsval, DifferenceMatrixIndex );
        }
      }

    }

  }

//  BUG SHOULD DO THIS ABOVE! FIXME
//  M=rho*M;

  /* step over all types of BCs */
  this->ApplyBC();  // BUG  -- are BCs applied appropriately to the problem?
  std::cout << "Done Assembling." << std::endl;
}

/*
 * Assemble the master force vector
 */
void SolverCrankNicolson::AssembleFforTimeStep(int dim) {
/* if no DOFs exist in a system, we have nothing to do */
  if (NGFN<=0) return;

  unsigned int i=0;
  Float temp=0.0;

  AssembleF(dim); // assuming assemblef uses index 0 in vector!

  typedef std::map<Element::DegreeOfFreedomIDType,Float> BCTermType;
  BCTermType bcterm;

   /* Step over all Loads */
  for(LoadArray::iterator l=load.begin(); l!=load.end(); l++)
  {
    Load::Pointer l0=*l;
    if ( LoadBC::Pointer l1=dynamic_cast<LoadBC*>(&*l0) )
    {
      bcterm[ l1->m_element->GetDegreeOfFreedom(l1->m_dof) ]=l1->m_value[dim];
    }
  } // end for LoadArray::iterator l

  // Now set the solution t_minus1 vector to fit the BCs
  for( BCTermType::iterator q=bcterm.begin(); q!=bcterm.end(); q++)
  {
    m_ls->SetVectorValue(q->first,0.0,SolutionTMinus1Index); //FIXME?
  }

  m_ls->MultiplyMatrixVector(DiffMatrixBySolutionTMinus1Index,
                             DifferenceMatrixIndex,SolutionTMinus1Index);

  for (unsigned int index=0; index<NGFN; index++) RecomputeForceVector(index);

  // Now set the solution and force vector to fit the BCs
  for( BCTermType::iterator q=bcterm.begin(); q!=bcterm.end(); q++)
  {
    Float t1=q->first;  Float t2=q->second;
    m_ls->SetVectorValue(q->first,q->second,ForceTIndex);
  }

}

void  SolverCrankNicolson::RecomputeForceVector(unsigned int index)
{//
  Float ft   = m_ls->GetVectorValue(index,ForceTIndex);
  Float ftm1 = m_ls->GetVectorValue(index,ForceTMinus1Index);
  Float utm1 = m_ls->GetVectorValue(index,DiffMatrixBySolutionTMinus1Index);
  m_ls->SetVectorValue(index , m_deltaT*(m_alpha*ftm1+(1.-m_alpha)*ft)+utm1 , ForceTIndex);
  m_ls->SetVectorValue(index ,ft,ForceTMinus1Index); // now set t minus one force vector correctly
}

/*
 * Solve for the displacement vector u
 */
void SolverCrankNicolson::Solve()
{
  std::cout << " begin solve " << std::endl;
 /* FIXME - must verify that this is correct use of wrapper */
  /* FIXME Initialize the solution vector */
  m_ls->InitializeSolution(SolutionTIndex);
  m_ls->Solve();
  AddToDisplacements();
}

/*
 * Copy solution vector u to the corresponding nodal values, which are
 * stored in node objects). This is standard post processing of the solution.
 */
void SolverCrankNicolson::AddToDisplacements()
{
  /*
   * Copy the resulting displacements from
   * solution vector back to node objects.
   */
  Float mins=0.0, maxs=0.0;
  Float mins2=0.0, maxs2=0.0;
  for(int i=0;i<NGFN;i++)
  {

    Float temp=m_ls->GetSolutionValue(i,SolutionTIndex);
    if (temp < mins2 )  mins2=temp;
    else if (temp > maxs2 )  maxs2=temp;
//  note: set rather than add - i.e. last solution of system not total solution
    m_ls->SetVectorValue(i,m_ls->GetSolutionValue(i,SolutionTIndex),SolutionTMinus1Index);
    m_ls->AddSolutionValue(i,m_ls->GetSolutionValue(i,SolutionTIndex),TotalSolutionIndex);

    temp=m_ls->GetSolutionValue(i,TotalSolutionIndex);
    if (temp < mins )  mins=temp;
    else if (temp > maxs )  maxs=temp;
  }

  std::cout << " min cur solution val " << mins2 << endl;
  std::cout << " max cur solution val " << maxs2 << endl;
  std::cout << " min tot solution val " << mins << endl;
  std::cout << " max tot solution val " << maxs << endl;

}

void SolverCrankNicolson::PrintDisplacements()
{
  cout <<  " printing current displacements " << endl;
  for(int i=0;i<NGFN;i++)
  {
    cout << m_ls->GetVectorValue(i,SolutionTMinus1Index) << endl;
  }
}

void SolverCrankNicolson::PrintForce()
{
  cout <<  " printing current forces " << endl;
  for(int i=0;i<NGFN;i++)
  {
    cout << m_ls->GetVectorValue(i,ForceTIndex) << endl;
  }
}

}} // end namespace itk::fem
<commit_msg>fixed some warning messages<commit_after>/*=========================================================================

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

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

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

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

// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif

#include "itkFEMSolverCrankNicolson.h"

#include "FEM/itkFEMLoadNode.h"
#include "FEM/itkFEMLoadElementBase.h"
#include "FEM/itkFEMLoadBCMFC.h"

#include "FEM/itkFEMUtility.h"
#include "FEM/itkFEMObjectFactory.h"

namespace itk {
namespace fem {

void SolverCrankNicolson::InitializeForSolution()
{
  m_ls->SetSystemOrder(NGFN+NMFC);
  m_ls->SetNumberOfVectors(5);
  m_ls->SetNumberOfSolutions(2);
  m_ls->SetNumberOfMatrices(2);
  m_ls->InitializeMatrix(SumMatrixIndex);
  m_ls->InitializeMatrix(DifferenceMatrixIndex);
  m_ls->InitializeVector(ForceTIndex);
  m_ls->InitializeVector(ForceTMinus1Index);
  m_ls->InitializeVector(SolutionTMinus1Index);
  m_ls->InitializeVector(DiffMatrixBySolutionTMinus1Index);
  m_ls->InitializeSolution(SolutionTIndex);
  m_ls->InitializeSolution(TotalSolutionIndex);
}

/*
 * Assemble the master stiffness matrix (also apply the MFCs to K)
 */
void SolverCrankNicolson::AssembleKandM()
{

  // if no DOFs exist in a system, we have nothing to do
  if (NGFN<=0) return;

  NMFC=0;  // number of MFC in a system

  // temporary storage for pointers to LoadBCMFC objects
  typedef std::vector<LoadBCMFC::Pointer> MFCArray;
  MFCArray mfcLoads;

  /*
   * Before we can start the assembly procedure, we need to know,
   * how many boundary conditions (MFCs) there are in a system.
   */
  mfcLoads.clear();
  // search for MFC's in Loads array, because they affect the master stiffness matrix
  for(LoadArray::iterator l=load.begin(); l!=load.end(); l++) {
    if ( LoadBCMFC::Pointer l1=dynamic_cast<LoadBCMFC*>( &(*(*l))) ) {
      // store the index of an LoadBCMFC object for later
      l1->Index=NMFC;
      // store the pointer to a LoadBCMFC object for later
      mfcLoads.push_back(l1);
      // increase the number of MFC
      NMFC++;
    }
  }

  /*
   * Now we can assemble the master stiffness matrix
   * from element stiffness matrices
   */
  InitializeForSolution();

std::cout << "Begin Assembly." << std::endl;
  /*
   * Step over all elements
   */
  for(ElementArray::iterator e=el.begin(); e!=el.end(); e++)
  {
    vnl_matrix<Float> Ke=(*e)->Ke();  /*Copy the element stiffness matrix for faster access. */
    vnl_matrix<Float> Me=(*e)->Me();  /*Copy the element mass matrix for faster access. */
    int Ne=(*e)->GetNumberOfDegreesOfFreedom();          /*... same for element DOF */

    /* step over all rows in in element matrix */
    for(int j=0; j<Ne; j++)
    {
      /* step over all columns in in element matrix */
      for(int k=0; k<Ne; k++)
      {
        /* error checking. all GFN should be =>0 and <NGFN */
        if ( (*e)->GetDegreeOfFreedom(j) >= NGFN ||
             (*e)->GetDegreeOfFreedom(k) >= NGFN  )
        {
          throw FEMExceptionSolution(__FILE__,__LINE__,"SolverCrankNicolson::AssembleK()","Illegal GFN!");
        }

        /* Here we finaly update the corresponding element
         * in the master stiffness matrix. We first check if
         * element in Ke is zero, to prevent zeros from being
         * allocated in sparse matrix.
         */
        if ( Ke(j,k)!=Float(0.0) || Me(j,k) != Float(0.0) )
        {
          // left hand side matrix
          Float lhsval=(Me(j,k) + m_alpha*m_deltaT*Ke(j,k));
          m_ls->AddMatrixValue( (*e)->GetDegreeOfFreedom(j) ,
                    (*e)->GetDegreeOfFreedom(k),
                    lhsval, SumMatrixIndex );
          // right hand side matrix
          Float rhsval=(Me(j,k) - (1.-m_alpha)*m_deltaT*Ke(j,k));
          m_ls->AddMatrixValue( (*e)->GetDegreeOfFreedom(j) ,
                    (*e)->GetDegreeOfFreedom(k),
                    rhsval, DifferenceMatrixIndex );
        }
      }

    }

  }

//  BUG SHOULD DO THIS ABOVE! FIXME
//  M=rho*M;

  /* step over all types of BCs */
  this->ApplyBC();  // BUG  -- are BCs applied appropriately to the problem?
  std::cout << "Done Assembling." << std::endl;
}

/*
 * Assemble the master force vector
 */
void SolverCrankNicolson::AssembleFforTimeStep(int dim) {
/* if no DOFs exist in a system, we have nothing to do */
  if (NGFN<=0) return;

  AssembleF(dim); // assuming assemblef uses index 0 in vector!

  typedef std::map<Element::DegreeOfFreedomIDType,Float> BCTermType;
  BCTermType bcterm;

   /* Step over all Loads */
  for(LoadArray::iterator l=load.begin(); l!=load.end(); l++)
  {
    Load::Pointer l0=*l;
    if ( LoadBC::Pointer l1=dynamic_cast<LoadBC*>(&*l0) )
    {
      bcterm[ l1->m_element->GetDegreeOfFreedom(l1->m_dof) ]=l1->m_value[dim];
    }
  } // end for LoadArray::iterator l

  // Now set the solution t_minus1 vector to fit the BCs
  for( BCTermType::iterator q=bcterm.begin(); q!=bcterm.end(); q++)
  {
    m_ls->SetVectorValue(q->first,0.0,SolutionTMinus1Index); //FIXME?
  }

  m_ls->MultiplyMatrixVector(DiffMatrixBySolutionTMinus1Index,
                             DifferenceMatrixIndex,SolutionTMinus1Index);

  for (unsigned int index=0; index<NGFN; index++) RecomputeForceVector(index);

  // Now set the solution and force vector to fit the BCs
  for( BCTermType::iterator q=bcterm.begin(); q!=bcterm.end(); q++)
  {
    m_ls->SetVectorValue(q->first,q->second,ForceTIndex);
  }

}

void  SolverCrankNicolson::RecomputeForceVector(unsigned int index)
{//
  Float ft   = m_ls->GetVectorValue(index,ForceTIndex);
  Float ftm1 = m_ls->GetVectorValue(index,ForceTMinus1Index);
  Float utm1 = m_ls->GetVectorValue(index,DiffMatrixBySolutionTMinus1Index);
  m_ls->SetVectorValue(index , m_deltaT*(m_alpha*ftm1+(1.-m_alpha)*ft)+utm1 , ForceTIndex);
  m_ls->SetVectorValue(index ,ft,ForceTMinus1Index); // now set t minus one force vector correctly
}

/*
 * Solve for the displacement vector u
 */
void SolverCrankNicolson::Solve()
{
  std::cout << " begin solve " << std::endl;
 /* FIXME - must verify that this is correct use of wrapper */
  /* FIXME Initialize the solution vector */
  m_ls->InitializeSolution(SolutionTIndex);
  m_ls->Solve();
  AddToDisplacements();
}

/*
 * Copy solution vector u to the corresponding nodal values, which are
 * stored in node objects). This is standard post processing of the solution.
 */
void SolverCrankNicolson::AddToDisplacements()
{
  /*
   * Copy the resulting displacements from
   * solution vector back to node objects.
   */
  Float mins=0.0, maxs=0.0;
  Float mins2=0.0, maxs2=0.0;
  for(unsigned int i=0;i<NGFN;i++)
  {

    Float temp=m_ls->GetSolutionValue(i,SolutionTIndex);
    if (temp < mins2 )  mins2=temp;
    else if (temp > maxs2 )  maxs2=temp;
//  note: set rather than add - i.e. last solution of system not total solution
    m_ls->SetVectorValue(i,m_ls->GetSolutionValue(i,SolutionTIndex),SolutionTMinus1Index);
    m_ls->AddSolutionValue(i,m_ls->GetSolutionValue(i,SolutionTIndex),TotalSolutionIndex);

    temp=m_ls->GetSolutionValue(i,TotalSolutionIndex);
    if (temp < mins )  mins=temp;
    else if (temp > maxs )  maxs=temp;
  }

  std::cout << " min cur solution val " << mins2 << endl;
  std::cout << " max cur solution val " << maxs2 << endl;
  std::cout << " min tot solution val " << mins << endl;
  std::cout << " max tot solution val " << maxs << endl;

}

void SolverCrankNicolson::PrintDisplacements()
{
  cout <<  " printing current displacements " << endl;
  for(unsigned int i=0;i<NGFN;i++)
  {
    cout << m_ls->GetVectorValue(i,SolutionTMinus1Index) << endl;
  }
}

void SolverCrankNicolson::PrintForce()
{
  cout <<  " printing current forces " << endl;
  for(unsigned int i=0;i<NGFN;i++)
  {
    cout << m_ls->GetVectorValue(i,ForceTIndex) << endl;
  }
}

}} // end namespace itk::fem
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2012 - 2013 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/

#include "merspecifykitinformation.h"
#include "merconstants.h"
#include "merdevicefactory.h"
#include "mersdkkitinformation.h"

#include <utils/pathchooser.h>
#include <projectexplorer/projectexplorerconstants.h>

using namespace ProjectExplorer;

namespace Mer {
namespace Internal {

MerSpecifyKitInformationWidget::MerSpecifyKitInformationWidget(Kit *k) :
    KitConfigWidget(k)
{
    m_chooser = new Utils::PathChooser;
    m_chooser->setExpectedKind(Utils::PathChooser::File);
    m_chooser->setFileName(MerSpecifyKitInformation::specifyPath(k));
    connect(m_chooser, SIGNAL(changed(QString)), this, SLOT(pathWasChanged()));
}

QString MerSpecifyKitInformationWidget::displayName() const
{
    return tr("Specify:");
}

QString MerSpecifyKitInformationWidget::toolTip() const
{
    return tr("Path for specify tool.");
}

void MerSpecifyKitInformationWidget::refresh()
{
    if (!m_ignoreChange)
        m_chooser->setFileName(MerSpecifyKitInformation::specifyPath(m_kit));
}

void MerSpecifyKitInformationWidget::makeReadOnly()
{
    m_chooser->setEnabled(false);
}

bool MerSpecifyKitInformationWidget::visibleInKit()
{
    return MerDeviceFactory::canCreate(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(m_kit));
}

QWidget *MerSpecifyKitInformationWidget::mainWidget() const
{
    return m_chooser->lineEdit();
}

QWidget *MerSpecifyKitInformationWidget::buttonWidget() const
{
    return m_chooser->buttonAtIndex(0);
}

void MerSpecifyKitInformationWidget::pathWasChanged()
{
    m_ignoreChange = true;
    MerSpecifyKitInformation::setSpecifyPath(m_kit, m_chooser->fileName());
    m_ignoreChange = false;
}

MerSpecifyKitInformation::MerSpecifyKitInformation()
{
    setObjectName(QLatin1String("MerSpecifyKitInformation"));
}

Core::Id MerSpecifyKitInformation::dataId() const
{
    return Core::Id(Constants::MER_KIT_SPECIFY_INFORMATION);
}

unsigned int MerSpecifyKitInformation::priority() const
{
    return 23;
}

QVariant MerSpecifyKitInformation::defaultValue(Kit *k) const
{
    Q_UNUSED(k)
    return QString();
}

QList<Task> MerSpecifyKitInformation::validate(const Kit *k) const
{
    QList<Task> result;
    const Utils::FileName file = MerSpecifyKitInformation::specifyPath(k);
    if (!file.toFileInfo().isFile()) {
        const QString message = QCoreApplication::translate("MerSdk",
                                                            "No valid specify tool found");
        return QList<Task>() << Task(Task::Error, message, Utils::FileName(), -1,
                                     Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM));
    }
    return result;
}

KitConfigWidget *MerSpecifyKitInformation::createConfigWidget(Kit *k) const
{
    return new MerSpecifyKitInformationWidget(k);
}

KitInformation::ItemList MerSpecifyKitInformation::toUserOutput(Kit *k) const
{
    return ItemList() << qMakePair(tr("Specify"), specifyPath(k).toUserOutput());
}

Utils::FileName MerSpecifyKitInformation::specifyPath(const Kit *k)
{
    if (!k)
        return Utils::FileName();
    return Utils::FileName::fromString(k->value(Core::Id(Constants::MER_KIT_SPECIFY_INFORMATION)).toString());
}

void MerSpecifyKitInformation::setSpecifyPath(Kit *k, const Utils::FileName &v)
{
    k->setValue(Core::Id(Constants::MER_KIT_SPECIFY_INFORMATION), v.toString());
}

} // Internal
} // Mer
<commit_msg>Jolla: Show specify info in kit page for mer kits only<commit_after>/****************************************************************************
**
** Copyright (C) 2012 - 2013 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/

#include "merspecifykitinformation.h"
#include "merconstants.h"
#include "merdevicefactory.h"
#include "mersdkkitinformation.h"
#include "mersdkmanager.h"

#include <utils/pathchooser.h>
#include <projectexplorer/projectexplorerconstants.h>

using namespace ProjectExplorer;

namespace Mer {
namespace Internal {

MerSpecifyKitInformationWidget::MerSpecifyKitInformationWidget(Kit *k) :
    KitConfigWidget(k)
{
    m_chooser = new Utils::PathChooser;
    m_chooser->setExpectedKind(Utils::PathChooser::File);
    m_chooser->setFileName(MerSpecifyKitInformation::specifyPath(k));
    connect(m_chooser, SIGNAL(changed(QString)), this, SLOT(pathWasChanged()));
}

QString MerSpecifyKitInformationWidget::displayName() const
{
    return tr("Specify:");
}

QString MerSpecifyKitInformationWidget::toolTip() const
{
    return tr("Path for specify tool.");
}

void MerSpecifyKitInformationWidget::refresh()
{
    if (!m_ignoreChange)
        m_chooser->setFileName(MerSpecifyKitInformation::specifyPath(m_kit));
}

void MerSpecifyKitInformationWidget::makeReadOnly()
{
    m_chooser->setEnabled(false);
}

bool MerSpecifyKitInformationWidget::visibleInKit()
{
    return MerDeviceFactory::canCreate(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(m_kit));
}

QWidget *MerSpecifyKitInformationWidget::mainWidget() const
{
    return m_chooser->lineEdit();
}

QWidget *MerSpecifyKitInformationWidget::buttonWidget() const
{
    return m_chooser->buttonAtIndex(0);
}

void MerSpecifyKitInformationWidget::pathWasChanged()
{
    m_ignoreChange = true;
    MerSpecifyKitInformation::setSpecifyPath(m_kit, m_chooser->fileName());
    m_ignoreChange = false;
}

MerSpecifyKitInformation::MerSpecifyKitInformation()
{
    setObjectName(QLatin1String("MerSpecifyKitInformation"));
}

Core::Id MerSpecifyKitInformation::dataId() const
{
    return Core::Id(Constants::MER_KIT_SPECIFY_INFORMATION);
}

unsigned int MerSpecifyKitInformation::priority() const
{
    return 23;
}

QVariant MerSpecifyKitInformation::defaultValue(Kit *k) const
{
    Q_UNUSED(k)
    return QString();
}

QList<Task> MerSpecifyKitInformation::validate(const Kit *k) const
{
    QList<Task> result;
    const Utils::FileName file = MerSpecifyKitInformation::specifyPath(k);
    if (MerSdkManager::isMerKit(k) && !file.toFileInfo().isFile()) {
        const QString message = QCoreApplication::translate("MerSdk",
                                                            "No valid specify tool found");
        return QList<Task>() << Task(Task::Error, message, Utils::FileName(), -1,
                                     Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM));
    }
    return result;
}

KitConfigWidget *MerSpecifyKitInformation::createConfigWidget(Kit *k) const
{
    return new MerSpecifyKitInformationWidget(k);
}

KitInformation::ItemList MerSpecifyKitInformation::toUserOutput(Kit *k) const
{
    if (MerDeviceFactory::canCreate(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(k)))
        return ItemList() << qMakePair(tr("Specify"), specifyPath(k).toUserOutput());
    else
        return ProjectExplorer::KitInformation::ItemList();
}

Utils::FileName MerSpecifyKitInformation::specifyPath(const Kit *k)
{
    if (!k)
        return Utils::FileName();
    return Utils::FileName::fromString(k->value(Core::Id(Constants::MER_KIT_SPECIFY_INFORMATION)).toString());
}

void MerSpecifyKitInformation::setSpecifyPath(Kit *k, const Utils::FileName &v)
{
    k->setValue(Core::Id(Constants::MER_KIT_SPECIFY_INFORMATION), v.toString());
}

} // Internal
} // Mer
<|endoftext|>


<commit_before>/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/

#include "cesdkhandler.h"

#include <QtCore/QFile>
#include <QtCore/QDebug>
#include <QtCore/QXmlStreamReader>

using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
using ProjectExplorer::Environment;

CeSdkInfo::CeSdkInfo()
    : m_major(0), m_minor(0)
{
}

void CeSdkInfo::addToEnvironment(Environment &env)
{
    qDebug() << "adding " << name() << "to Environment";
    env.set("INCLUDE", m_include);
    env.set("LIB", m_lib);
    env.prependOrSetPath(m_bin);
    qDebug()<<e.toStringList();
}

CeSdkHandler::CeSdkHandler()
{
}

QString CeSdkHandler::platformName(const QString &qtpath)
{
    QString platformName;
    QString CE_SDK;
    QString CE_ARCH;
    QFile f(qtpath);
    if (f.exists() && f.open(QIODevice::ReadOnly)) {
        while (!f.atEnd()) {
            QByteArray line = f.readLine();
            if (line.startsWith("CE_SDK")) {
                int index = line.indexOf('=');
                if (index >= 0) {
                    CE_SDK = line.mid(index + 1).trimmed();
                }
            } else if (line.startsWith("CE_ARCH")) {
                int index = line.indexOf('=');
                if (index >= 0) {
                    CE_ARCH = line.mid(index + 1).trimmed();
                }
            }
            if (!CE_SDK.isEmpty() && !CE_ARCH.isEmpty()) {
                platformName = CE_SDK + " (" + CE_ARCH + ")";
                break;
            }
        }
    }
    return platformName;
}

bool CeSdkHandler::parse(const QString &vsdir)
{
    // look at the file at %VCInstallDir%/vcpackages/WCE.VCPlatform.config
    // and scan through all installed sdks...
    m_list.clear();

    VCInstallDir = vsdir + "/VC/";
    VSInstallDir = vsdir;

    QDir vStudioDir(VCInstallDir);
    if (!vStudioDir.cd("vcpackages"))
        return false;

    QFile configFile(vStudioDir.absoluteFilePath(QLatin1String("WCE.VCPlatform.config")));
    qDebug()<<"##";
    if (!configFile.exists() || !configFile.open(QIODevice::ReadOnly))
        return false;

    qDebug()<<"parsing";

    QString currentElement;
    CeSdkInfo currentItem;
    QXmlStreamReader xml(&configFile);
    while (!xml.atEnd()) {
        xml.readNext();
        if (xml.isStartElement()) {
            currentElement = xml.name().toString();
            if (currentElement == QLatin1String("Platform"))
                currentItem = CeSdkInfo();
            else if (currentElement == QLatin1String("Directories")) {
                QXmlStreamAttributes attr = xml.attributes();
                currentItem.m_include = fixPaths(attr.value(QLatin1String("Include")).toString());
                currentItem.m_lib = fixPaths(attr.value(QLatin1String("Library")).toString());
                currentItem.m_bin = fixPaths(attr.value(QLatin1String("Path")).toString());
            }
        } else if (xml.isEndElement()) {
            if (xml.name().toString() == QLatin1String("Platform"))
                m_list.append(currentItem);
        } else if (xml.isCharacters() && !xml.isWhitespace()) {
            if (currentElement == QLatin1String("PlatformName"))
                currentItem.m_name = xml.text().toString();
            else if (currentElement == QLatin1String("OSMajorVersion"))
                currentItem.m_major = xml.text().toString().toInt();
            else if (currentElement == QLatin1String("OSMinorVersion"))
                currentItem.m_minor = xml.text().toString().toInt();
        }
    }

    if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) {
        qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString();
        return false;
    }
    return m_list.size() > 0 ? true : false;
}

CeSdkInfo CeSdkHandler::find(const QString &name)
{
    qDebug() << "looking for platform " << name;
    for (QList<CeSdkInfo>::iterator it = m_list.begin(); it != m_list.end(); ++it) {
        qDebug() << "...." << it->name();
        if (it->name() == name)
            return *it;
    }
    return CeSdkInfo();
}
<commit_msg>Fixes: -Wno-undefined would have saved me.<commit_after>/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/

#include "cesdkhandler.h"

#include <QtCore/QFile>
#include <QtCore/QDebug>
#include <QtCore/QXmlStreamReader>

using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
using ProjectExplorer::Environment;

CeSdkInfo::CeSdkInfo()
    : m_major(0), m_minor(0)
{
}

void CeSdkInfo::addToEnvironment(Environment &env)
{
    qDebug() << "adding " << name() << "to Environment";
    env.set("INCLUDE", m_include);
    env.set("LIB", m_lib);
    env.prependOrSetPath(m_bin);
    qDebug()<<env.toStringList();
}

CeSdkHandler::CeSdkHandler()
{
}

QString CeSdkHandler::platformName(const QString &qtpath)
{
    QString platformName;
    QString CE_SDK;
    QString CE_ARCH;
    QFile f(qtpath);
    if (f.exists() && f.open(QIODevice::ReadOnly)) {
        while (!f.atEnd()) {
            QByteArray line = f.readLine();
            if (line.startsWith("CE_SDK")) {
                int index = line.indexOf('=');
                if (index >= 0) {
                    CE_SDK = line.mid(index + 1).trimmed();
                }
            } else if (line.startsWith("CE_ARCH")) {
                int index = line.indexOf('=');
                if (index >= 0) {
                    CE_ARCH = line.mid(index + 1).trimmed();
                }
            }
            if (!CE_SDK.isEmpty() && !CE_ARCH.isEmpty()) {
                platformName = CE_SDK + " (" + CE_ARCH + ")";
                break;
            }
        }
    }
    return platformName;
}

bool CeSdkHandler::parse(const QString &vsdir)
{
    // look at the file at %VCInstallDir%/vcpackages/WCE.VCPlatform.config
    // and scan through all installed sdks...
    m_list.clear();

    VCInstallDir = vsdir + "/VC/";
    VSInstallDir = vsdir;

    QDir vStudioDir(VCInstallDir);
    if (!vStudioDir.cd("vcpackages"))
        return false;

    QFile configFile(vStudioDir.absoluteFilePath(QLatin1String("WCE.VCPlatform.config")));
    qDebug()<<"##";
    if (!configFile.exists() || !configFile.open(QIODevice::ReadOnly))
        return false;

    qDebug()<<"parsing";

    QString currentElement;
    CeSdkInfo currentItem;
    QXmlStreamReader xml(&configFile);
    while (!xml.atEnd()) {
        xml.readNext();
        if (xml.isStartElement()) {
            currentElement = xml.name().toString();
            if (currentElement == QLatin1String("Platform"))
                currentItem = CeSdkInfo();
            else if (currentElement == QLatin1String("Directories")) {
                QXmlStreamAttributes attr = xml.attributes();
                currentItem.m_include = fixPaths(attr.value(QLatin1String("Include")).toString());
                currentItem.m_lib = fixPaths(attr.value(QLatin1String("Library")).toString());
                currentItem.m_bin = fixPaths(attr.value(QLatin1String("Path")).toString());
            }
        } else if (xml.isEndElement()) {
            if (xml.name().toString() == QLatin1String("Platform"))
                m_list.append(currentItem);
        } else if (xml.isCharacters() && !xml.isWhitespace()) {
            if (currentElement == QLatin1String("PlatformName"))
                currentItem.m_name = xml.text().toString();
            else if (currentElement == QLatin1String("OSMajorVersion"))
                currentItem.m_major = xml.text().toString().toInt();
            else if (currentElement == QLatin1String("OSMinorVersion"))
                currentItem.m_minor = xml.text().toString().toInt();
        }
    }

    if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) {
        qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString();
        return false;
    }
    return m_list.size() > 0 ? true : false;
}

CeSdkInfo CeSdkHandler::find(const QString &name)
{
    qDebug() << "looking for platform " << name;
    for (QList<CeSdkInfo>::iterator it = m_list.begin(); it != m_list.end(); ++it) {
        qDebug() << "...." << it->name();
        if (it->name() == name)
            return *it;
    }
    return CeSdkInfo();
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "qmlproject.h"
#include "qmlprojectfile.h"
#include "qmlprojectmanagerconstants.h"
#include "fileformat/qmlprojectitem.h"
#include "qmlprojectrunconfiguration.h"

#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/filewatcher.h>
#include <qmljseditor/qmljsmodelmanagerinterface.h>

#include <QTextStream>
#include <QDeclarativeComponent>
#include <QtDebug>

namespace QmlProjectManager {

QmlProject::QmlProject(Internal::Manager *manager, const QString &fileName)
    : m_manager(manager),
      m_fileName(fileName),
      m_modelManager(ExtensionSystem::PluginManager::instance()->getObject<QmlJSEditor::ModelManagerInterface>()),
      m_fileWatcher(new ProjectExplorer::FileWatcher(this)),
      m_targetFactory(new Internal::QmlProjectTargetFactory(this))
{
    setSupportedTargetIds(QSet<QString>() << QLatin1String(Constants::QML_VIEWER_TARGET_ID));
    QFileInfo fileInfo(m_fileName);
    m_projectName = fileInfo.completeBaseName();

    m_file = new Internal::QmlProjectFile(this, fileName);
    m_rootNode = new Internal::QmlProjectNode(this, m_file);

    m_fileWatcher->addFile(fileName),
    connect(m_fileWatcher, SIGNAL(fileChanged(QString)),
            this, SLOT(refreshProjectFile()));

    m_manager->registerProject(this);
}

QmlProject::~QmlProject()
{
    m_manager->unregisterProject(this);

    delete m_rootNode;
}

QDir QmlProject::projectDir() const
{
    return QFileInfo(file()->fileName()).dir();
}

QString QmlProject::filesFileName() const
{ return m_fileName; }

void QmlProject::parseProject(RefreshOptions options)
{
    if (options & Files) {
        if (options & ProjectFile)
            delete m_projectItem.data();
        if (!m_projectItem) {
            QFile file(m_fileName);
            if (file.open(QFile::ReadOnly)) {
                QDeclarativeComponent *component = new QDeclarativeComponent(&m_engine, this);
                component->setData(file.readAll(), QUrl::fromLocalFile(m_fileName));
                if (component->isReady()
                    && qobject_cast<QmlProjectItem*>(component->create())) {
                    m_projectItem = qobject_cast<QmlProjectItem*>(component->create());
                    connect(m_projectItem.data(), SIGNAL(qmlFilesChanged(QSet<QString>, QSet<QString>)),
                            this, SLOT(refreshFiles(QSet<QString>, QSet<QString>)));
                    connect(m_projectItem.data(), SIGNAL(importPathsChanged()), this, SLOT(refreshImportPaths()));
                    refreshImportPaths();
                } else {
                    Core::MessageManager *messageManager = Core::ICore::instance()->messageManager();
                    messageManager->printToOutputPane(tr("Error while loading project file!"));
                    messageManager->printToOutputPane(component->errorString(), true);
                }
            }
        }
        if (m_projectItem) {
            m_projectItem.data()->setSourceDirectory(projectDir().path());
            m_modelManager->updateSourceFiles(m_projectItem.data()->files(), true);
        }
        m_rootNode->refresh();
    }

    if (options & Configuration) {
        // update configuration
    }

    if (options & Files)
        emit fileListChanged();
}

void QmlProject::refresh(RefreshOptions options)
{
    parseProject(options);

    if (options & Files)
        m_rootNode->refresh();
}

QStringList QmlProject::convertToAbsoluteFiles(const QStringList &paths) const
{
    const QDir projectDir(QFileInfo(m_fileName).dir());
    QStringList absolutePaths;
    foreach (const QString &file, paths) {
        QFileInfo fileInfo(projectDir, file);
        absolutePaths.append(fileInfo.absoluteFilePath());
    }
    absolutePaths.removeDuplicates();
    return absolutePaths;
}

QStringList QmlProject::files() const
{
    QStringList files;
    if (m_projectItem) {
        files = m_projectItem.data()->files();
    } else {
        files = m_files;
    }
    return files;
}

bool QmlProject::validProjectFile() const
{
    return !m_projectItem.isNull();
}

QStringList QmlProject::importPaths() const
{
    QStringList importPaths;
    if (m_projectItem)
        importPaths = m_projectItem.data()->importPaths();
    return importPaths;
}

bool QmlProject::addFiles(const QStringList &filePaths)
{
    QStringList toAdd;
    foreach (const QString &filePath, filePaths) {
        if (!m_projectItem.data()->matchesFile(filePath))
            toAdd << filePaths;
    }
    return toAdd.isEmpty();
}

void QmlProject::refreshProjectFile()
{
    refresh(QmlProject::ProjectFile | Files);
}

void QmlProject::refreshFiles(const QSet<QString> &/*added*/, const QSet<QString> &removed)
{
    refresh(Files);
    if (!removed.isEmpty())
        m_modelManager->removeFiles(removed.toList());
}

void QmlProject::refreshImportPaths()
{
    m_modelManager->setProjectImportPaths(importPaths());
}

QString QmlProject::displayName() const
{
    return m_projectName;
}

QString QmlProject::id() const
{
    return QLatin1String("QmlProjectManager.QmlProject");
}

Core::IFile *QmlProject::file() const
{
    return m_file;
}

Internal::Manager *QmlProject::projectManager() const
{
    return m_manager;
}

QList<ProjectExplorer::Project *> QmlProject::dependsOn()
{
    return QList<Project *>();
}

ProjectExplorer::BuildConfigWidget *QmlProject::createConfigWidget()
{
    return 0;
}

QList<ProjectExplorer::BuildConfigWidget*> QmlProject::subConfigWidgets()
{
    return QList<ProjectExplorer::BuildConfigWidget*>();
}

Internal::QmlProjectTargetFactory *QmlProject::targetFactory() const
{
    return m_targetFactory;
}

Internal::QmlProjectTarget *QmlProject::activeTarget() const
{
    return static_cast<Internal::QmlProjectTarget *>(Project::activeTarget());
}

Internal::QmlProjectNode *QmlProject::rootProjectNode() const
{
    return m_rootNode;
}

QStringList QmlProject::files(FilesMode) const
{
    return files();
}

bool QmlProject::fromMap(const QVariantMap &map)
{
    if (!Project::fromMap(map))
        return false;

    if (targets().isEmpty()) {
        Internal::QmlProjectTarget *target(targetFactory()->create(this, QLatin1String(Constants::QML_VIEWER_TARGET_ID)));
        addTarget(target);
    }

    refresh(Everything);
    // FIXME workaround to guarantee that run/debug actions are enabled if a valid file exists
    QmlProjectRunConfiguration *runConfig = static_cast<QmlProjectRunConfiguration*>(activeTarget()->activeRunConfiguration());
    if (runConfig)
        runConfig->changeCurrentFile(0);

    return true;
}

} // namespace QmlProjectManager

<commit_msg>Fix crash when loading a .qmlproject with a custom run configuration<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "qmlproject.h"
#include "qmlprojectfile.h"
#include "qmlprojectmanagerconstants.h"
#include "fileformat/qmlprojectitem.h"
#include "qmlprojectrunconfiguration.h"

#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/filewatcher.h>
#include <qmljseditor/qmljsmodelmanagerinterface.h>

#include <QTextStream>
#include <QDeclarativeComponent>
#include <QtDebug>

namespace QmlProjectManager {

QmlProject::QmlProject(Internal::Manager *manager, const QString &fileName)
    : m_manager(manager),
      m_fileName(fileName),
      m_modelManager(ExtensionSystem::PluginManager::instance()->getObject<QmlJSEditor::ModelManagerInterface>()),
      m_fileWatcher(new ProjectExplorer::FileWatcher(this)),
      m_targetFactory(new Internal::QmlProjectTargetFactory(this))
{
    setSupportedTargetIds(QSet<QString>() << QLatin1String(Constants::QML_VIEWER_TARGET_ID));
    QFileInfo fileInfo(m_fileName);
    m_projectName = fileInfo.completeBaseName();

    m_file = new Internal::QmlProjectFile(this, fileName);
    m_rootNode = new Internal::QmlProjectNode(this, m_file);

    m_fileWatcher->addFile(fileName),
    connect(m_fileWatcher, SIGNAL(fileChanged(QString)),
            this, SLOT(refreshProjectFile()));

    m_manager->registerProject(this);
}

QmlProject::~QmlProject()
{
    m_manager->unregisterProject(this);

    delete m_rootNode;
}

QDir QmlProject::projectDir() const
{
    return QFileInfo(file()->fileName()).dir();
}

QString QmlProject::filesFileName() const
{ return m_fileName; }

void QmlProject::parseProject(RefreshOptions options)
{
    if (options & Files) {
        if (options & ProjectFile)
            delete m_projectItem.data();
        if (!m_projectItem) {
            QFile file(m_fileName);
            if (file.open(QFile::ReadOnly)) {
                QDeclarativeComponent *component = new QDeclarativeComponent(&m_engine, this);
                component->setData(file.readAll(), QUrl::fromLocalFile(m_fileName));
                if (component->isReady()
                    && qobject_cast<QmlProjectItem*>(component->create())) {
                    m_projectItem = qobject_cast<QmlProjectItem*>(component->create());
                    connect(m_projectItem.data(), SIGNAL(qmlFilesChanged(QSet<QString>, QSet<QString>)),
                            this, SLOT(refreshFiles(QSet<QString>, QSet<QString>)));
                    connect(m_projectItem.data(), SIGNAL(importPathsChanged()), this, SLOT(refreshImportPaths()));
                    refreshImportPaths();
                } else {
                    Core::MessageManager *messageManager = Core::ICore::instance()->messageManager();
                    messageManager->printToOutputPane(tr("Error while loading project file!"));
                    messageManager->printToOutputPane(component->errorString(), true);
                }
            }
        }
        if (m_projectItem) {
            m_projectItem.data()->setSourceDirectory(projectDir().path());
            m_modelManager->updateSourceFiles(m_projectItem.data()->files(), true);
        }
        m_rootNode->refresh();
    }

    if (options & Configuration) {
        // update configuration
    }

    if (options & Files)
        emit fileListChanged();
}

void QmlProject::refresh(RefreshOptions options)
{
    parseProject(options);

    if (options & Files)
        m_rootNode->refresh();
}

QStringList QmlProject::convertToAbsoluteFiles(const QStringList &paths) const
{
    const QDir projectDir(QFileInfo(m_fileName).dir());
    QStringList absolutePaths;
    foreach (const QString &file, paths) {
        QFileInfo fileInfo(projectDir, file);
        absolutePaths.append(fileInfo.absoluteFilePath());
    }
    absolutePaths.removeDuplicates();
    return absolutePaths;
}

QStringList QmlProject::files() const
{
    QStringList files;
    if (m_projectItem) {
        files = m_projectItem.data()->files();
    } else {
        files = m_files;
    }
    return files;
}

bool QmlProject::validProjectFile() const
{
    return !m_projectItem.isNull();
}

QStringList QmlProject::importPaths() const
{
    QStringList importPaths;
    if (m_projectItem)
        importPaths = m_projectItem.data()->importPaths();
    return importPaths;
}

bool QmlProject::addFiles(const QStringList &filePaths)
{
    QStringList toAdd;
    foreach (const QString &filePath, filePaths) {
        if (!m_projectItem.data()->matchesFile(filePath))
            toAdd << filePaths;
    }
    return toAdd.isEmpty();
}

void QmlProject::refreshProjectFile()
{
    refresh(QmlProject::ProjectFile | Files);
}

void QmlProject::refreshFiles(const QSet<QString> &/*added*/, const QSet<QString> &removed)
{
    refresh(Files);
    if (!removed.isEmpty())
        m_modelManager->removeFiles(removed.toList());
}

void QmlProject::refreshImportPaths()
{
    m_modelManager->setProjectImportPaths(importPaths());
}

QString QmlProject::displayName() const
{
    return m_projectName;
}

QString QmlProject::id() const
{
    return QLatin1String("QmlProjectManager.QmlProject");
}

Core::IFile *QmlProject::file() const
{
    return m_file;
}

Internal::Manager *QmlProject::projectManager() const
{
    return m_manager;
}

QList<ProjectExplorer::Project *> QmlProject::dependsOn()
{
    return QList<Project *>();
}

ProjectExplorer::BuildConfigWidget *QmlProject::createConfigWidget()
{
    return 0;
}

QList<ProjectExplorer::BuildConfigWidget*> QmlProject::subConfigWidgets()
{
    return QList<ProjectExplorer::BuildConfigWidget*>();
}

Internal::QmlProjectTargetFactory *QmlProject::targetFactory() const
{
    return m_targetFactory;
}

Internal::QmlProjectTarget *QmlProject::activeTarget() const
{
    return static_cast<Internal::QmlProjectTarget *>(Project::activeTarget());
}

Internal::QmlProjectNode *QmlProject::rootProjectNode() const
{
    return m_rootNode;
}

QStringList QmlProject::files(FilesMode) const
{
    return files();
}

bool QmlProject::fromMap(const QVariantMap &map)
{
    if (!Project::fromMap(map))
        return false;

    if (targets().isEmpty()) {
        Internal::QmlProjectTarget *target(targetFactory()->create(this, QLatin1String(Constants::QML_VIEWER_TARGET_ID)));
        addTarget(target);
    }

    refresh(Everything);
    // FIXME workaround to guarantee that run/debug actions are enabled if a valid file exists
    QmlProjectRunConfiguration *runConfig = qobject_cast<QmlProjectRunConfiguration*>(activeTarget()->activeRunConfiguration());
    if (runConfig)
        runConfig->changeCurrentFile(0);

    return true;
}

} // namespace QmlProjectManager

<|endoftext|>