<commit_before>// secondary.C --- Secondary domain for solute transport.
//
// Copyright 2008 Per Abrahamsen, Mikkel Mollerup and KU.
//
// This file is part of Daisy.
//
// Daisy is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// Daisy 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 Public License for more details.
//
// You should have received a copy of the GNU Lesser Public License
// along with Daisy; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#define BUILD_DLL

#include "secondary.h"
#include "block_model.h"
#include "librarian.h"
#include "assertion.h"
#include "frame.h"
#include "soil.h"

// secondary component.

const char *const Secondary::component = "secondary";

symbol
Secondary::library_id () const
{
  static const symbol id (component);
  return id;
}

Secondary::Secondary (const BlockModel& al)
  : name (al.type_name ())
{ }

Secondary::Secondary (const symbol name_)
  : name (name_)
{ }

Secondary::~Secondary ()
{ }

static struct SecondaryInit : public DeclareComponent
{
  SecondaryInit ()
    : DeclareComponent (Secondary::component, "\
Specify secondary domain.\n\
\n\
The secondary domain consist typically of soil fractures or other\n\
inter-aggregate pores small enough to be dominated by capillarity, yet\n\
so large that water moves fast enough that the solute equilibrium with\n\
the primary domain (typically intra-aggregate pores) can not be maintained.\n\
\n\
This allows a pulse of water to be move through saturated or near\n\
saturated soil without solutes in the new water being mixed with\n\
solutes in the old water.  The effects are twofold: It allows solutes\n\
applied to the surface to reach deeper soil layers much faster than it\n\
would otherwise, and it protects solutes in the soil matrix from being\n\
washed out with fast moving new water.")
  { }
} Secondary_init;

// "none" model.

struct SecondaryNone : public Secondary
{
  double h_lim (const size_t, const Soil&) const
  // Pressure act. secondary domain. [cm]
  { return 0.0; }
  double K (const size_t, const Soil&, const double h) const
  // Conductivity in sec. dom. [cm/h]
  { return 0.0; }
  double alpha () const         // Exchange rate between domain [h^-1]
  { return 0.0; }

  explicit SecondaryNone (const BlockModel& al)
    : Secondary (al)
  {}
  SecondaryNone ()
    : Secondary ("none")
  {}
};

std::auto_ptr<Secondary>
Secondary::create_none ()
{ return std::auto_ptr<Secondary> (new SecondaryNone ());  }

static struct SecondaryNoneSyntax : public DeclareModel
{
  Model* make (const BlockModel& al) const
  { return new SecondaryNone (al); }
  SecondaryNoneSyntax ()
    : DeclareModel (Secondary::component, "none", "No secondary domain.\n\
\n\
There is always full equilibrium between solute in different size\n\
matrix pores.")
  { }
  void load_frame (Frame& frame) const
  {
  }
} SecondaryNone_syntax;

// "alpha" model.

struct SecondaryAlpha : public Secondary
{
  const double alpha_;

  double alpha () const         // The value of the 'alpha' parameter.
  { return alpha_; }

  SecondaryAlpha (const BlockModel& al)
    : Secondary (al),
      alpha_ (al.number ("alpha"))
  {}
};

static struct SecondaryAlphaSyntax : public DeclareBase
{
  SecondaryAlphaSyntax ()
    : DeclareBase (Secondary::component, "alpha",
                   "Shared base class for non-empty secondary domains.")
  { }
  void load_frame (Frame& frame) const
  {
    frame.declare ("alpha", "h^-1", Attribute::Const, "\
Exchange rate between primary and secondary water.");
  }
} SecondaryAlpha_syntax;

// "pressure" model.

struct SecondaryPressure : public SecondaryAlpha
{
  const double h_lim_;
  const double K_;

  double h_lim (const size_t, const Soil&) const
  // The value of the 'h_lim' parameter.
  { return h_lim_; }
  double K (const size_t cell, const Soil& soil, const double h) const
  {
    if (h < h_lim (cell, soil))
      return 0.0;
    else
      return K_;
  }
  SecondaryPressure (const BlockModel& al)
    : SecondaryAlpha (al),
      h_lim_ (al.number ("h_lim")),
      K_ (al.number ("K"))
  {}
};

static struct SecondaryPressureSyntax : public DeclareModel
{
  Model* make (const BlockModel& al) const
  { return new SecondaryPressure (al); }
  SecondaryPressureSyntax ()
    : DeclareModel (Secondary::component, "pressure", "alpha", "\
Horizon has secondary domain specifyed by pressure thresshold.\n\
\n\
The secondary domain consist of water in matrix pores larger than\n\
what corresponds to the specified pressure. ")
  { }
  void load_frame (Frame& frame) const
  {
    frame.declare ("h_lim", "cm", Attribute::Const, "\
Minimal pressure needed for activating secondary domain.");
    frame.declare ("K", "cm/h", Attribute::Const, "\
Water conductivity when secondary domain is active.\n\
If the secondary domain is already included in the normal conductivity\n\
curve, specify 0.0 use that value instead.");
    frame.set ("K", 0.0);
  }
} SecondaryPressure_syntax;

// "cracks" model.

struct SecondaryCracks : public SecondaryAlpha
{
  const double aperture;       // [m]
  const double density;         // [m^-1]
  const double Theta_crack;     // []
  const double K_crack;              // [cm/h]

  double h_lim (const size_t cell, const Soil& soil) const
  {
    const double Theta_sat = soil.Theta (cell, 0.0, 0.0);
    if (Theta_crack >= Theta_sat)
      throw "Space occupied by cracks larger than soil porosity";
    const double Theta_lim = Theta_sat - Theta_crack;
    daisy_assert (Theta_lim > 0.0);
    return soil.h (cell, Theta_lim);
  }
  double K (const size_t cell, const Soil& soil, const double h) const
  {
    if (h < h_lim (cell, soil))
      return 0.0;
    else
      return K_crack;
  }

  static double find_K (const double aperture, const double density)
  { return -42.42e42; }
  SecondaryCracks (const BlockModel& al)
    : SecondaryAlpha (al),
      aperture (al.number ("h_aperture")),
      density (al.number ("density")),
      Theta_crack (aperture * density),
      K_crack (find_K (aperture, density))
  {
    daisy_assert (Theta_crack >= 0.0);
    daisy_assert (Theta_crack <= 1.0);
  }
};

static struct SecondaryCracksSyntax : public DeclareModel
{
  Model* make (const BlockModel& al) const
  { return new SecondaryCracks (al); }
  SecondaryCracksSyntax ()
    : DeclareModel (Secondary::component, "aperture", "alpha", "\
Secondary domain specified by aperture and density of soil cracks.")
  { }
  void load_frame (Frame& frame) const
  {
    frame.declare ("aperture", "m", Attribute::Const, "\
Average distance between walls in cracks.");
    frame.declare ("density", "m^-1", Attribute::Const, "\
Density of cracks.");
  }
} SecondaryCracks_syntax;

// secondary.C ends here.
<commit_msg>x61<commit_after>// secondary.C --- Secondary domain for solute transport.
//
// Copyright 2008 Per Abrahamsen, Mikkel Mollerup and KU.
//
// This file is part of Daisy.
//
// Daisy is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// Daisy 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 Public License for more details.
//
// You should have received a copy of the GNU Lesser Public License
// along with Daisy; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#define BUILD_DLL

#include "secondary.h"
#include "block_model.h"
#include "librarian.h"
#include "assertion.h"
#include "frame.h"
#include "soil.h"
#include "check.h"

// secondary component.

const char *const Secondary::component = "secondary";

symbol
Secondary::library_id () const
{
  static const symbol id (component);
  return id;
}

Secondary::Secondary (const BlockModel& al)
  : name (al.type_name ())
{ }

Secondary::Secondary (const symbol name_)
  : name (name_)
{ }

Secondary::~Secondary ()
{ }

static struct SecondaryInit : public DeclareComponent
{
  SecondaryInit ()
    : DeclareComponent (Secondary::component, "\
Specify secondary domain.\n\
\n\
The secondary domain consist typically of soil fractures or other\n\
inter-aggregate pores small enough to be dominated by capillarity, yet\n\
so large that water moves fast enough that the solute equilibrium with\n\
the primary domain (typically intra-aggregate pores) can not be maintained.\n\
\n\
This allows a pulse of water to be move through saturated or near\n\
saturated soil without solutes in the new water being mixed with\n\
solutes in the old water.  The effects are twofold: It allows solutes\n\
applied to the surface to reach deeper soil layers much faster than it\n\
would otherwise, and it protects solutes in the soil matrix from being\n\
washed out with fast moving new water.")
  { }
} Secondary_init;

// "none" model.

struct SecondaryNone : public Secondary
{
  double h_lim (const size_t, const Soil&) const
  // Pressure act. secondary domain. [cm]
  { return 0.0; }
  double K (const size_t, const Soil&, const double h) const
  // Conductivity in sec. dom. [cm/h]
  { return 0.0; }
  double alpha () const         // Exchange rate between domain [h^-1]
  { return 0.0; }

  explicit SecondaryNone (const BlockModel& al)
    : Secondary (al)
  {}
  SecondaryNone ()
    : Secondary ("none")
  {}
};

std::auto_ptr<Secondary>
Secondary::create_none ()
{ return std::auto_ptr<Secondary> (new SecondaryNone ());  }

static struct SecondaryNoneSyntax : public DeclareModel
{
  Model* make (const BlockModel& al) const
  { return new SecondaryNone (al); }
  SecondaryNoneSyntax ()
    : DeclareModel (Secondary::component, "none", "No secondary domain.\n\
\n\
There is always full equilibrium between solute in different size\n\
matrix pores.")
  { }
  void load_frame (Frame& frame) const
  {
  }
} SecondaryNone_syntax;

// "alpha" model.

struct SecondaryAlpha : public Secondary
{
  const double alpha_;

  double alpha () const         // The value of the 'alpha' parameter.
  { return alpha_; }

  SecondaryAlpha (const BlockModel& al)
    : Secondary (al),
      alpha_ (al.number ("alpha"))
  {}
};

static struct SecondaryAlphaSyntax : public DeclareBase
{
  SecondaryAlphaSyntax ()
    : DeclareBase (Secondary::component, "alpha",
                   "Shared base class for non-empty secondary domains.")
  { }
  void load_frame (Frame& frame) const
  {
    frame.declare ("alpha", "h^-1", Attribute::Const, "\
Exchange rate between primary and secondary water.");
  }
} SecondaryAlpha_syntax;

// "pressure" model.

struct SecondaryPressure : public SecondaryAlpha
{
  const double h_lim_;
  const double K_;

  double h_lim (const size_t, const Soil&) const
  // The value of the 'h_lim' parameter.
  { return h_lim_; }
  double K (const size_t cell, const Soil& soil, const double h) const
  {
    if (h < h_lim (cell, soil))
      return 0.0;
    else
      return K_;
  }
  SecondaryPressure (const BlockModel& al)
    : SecondaryAlpha (al),
      h_lim_ (al.number ("h_lim")),
      K_ (al.number ("K"))
  {}
};

static struct SecondaryPressureSyntax : public DeclareModel
{
  Model* make (const BlockModel& al) const
  { return new SecondaryPressure (al); }
  SecondaryPressureSyntax ()
    : DeclareModel (Secondary::component, "pressure", "alpha", "\
Horizon has secondary domain specifyed by pressure thresshold.\n\
\n\
The secondary domain consist of water in matrix pores larger than\n\
what corresponds to the specified pressure. ")
  { }
  void load_frame (Frame& frame) const
  {
    frame.declare ("h_lim", "cm", Check::positive (), Attribute::Const, "\
Minimal pressure needed for activating secondary domain.");
    frame.declare ("K", "cm/h", Check::non_negative (), Attribute::Const, "\
Water conductivity when secondary domain is active.\n\
If the secondary domain is already included in the normal conductivity\n\
curve, specify 0.0 use that value instead.");
    frame.set ("K", 0.0);
  }
} SecondaryPressure_syntax;

// "cracks" model.

struct SecondaryCracks : public SecondaryAlpha
{
  const double aperture;       // [m]
  const double density;         // [m^-1]
  const double Theta_crack;     // []
  const double K_crack;              // [cm/h]

  double h_lim (const size_t cell, const Soil& soil) const
  {
    const double Theta_sat = soil.Theta (cell, 0.0, 0.0);
    if (Theta_crack >= Theta_sat)
      throw "Space occupied by cracks larger than soil porosity";
    const double Theta_lim = Theta_sat - Theta_crack;
    daisy_assert (Theta_lim > 0.0);
    return soil.h (cell, Theta_lim);
  }
  double K (const size_t cell, const Soil& soil, const double h) const
  {
    if (h < h_lim (cell, soil))
      return 0.0;
    else
      return K_crack;
  }

  static double find_K (const double aperture, const double density)
  { return -42.42e42; }
  SecondaryCracks (const BlockModel& al)
    : SecondaryAlpha (al),
      aperture (al.number ("h_aperture")),
      density (al.number ("density")),
      Theta_crack (aperture * density),
      K_crack (find_K (aperture, density))
  {
    daisy_assert (Theta_crack >= 0.0);
    daisy_assert (Theta_crack <= 1.0);
  }
};

static struct SecondaryCracksSyntax : public DeclareModel
{
  Model* make (const BlockModel& al) const
  { return new SecondaryCracks (al); }
  SecondaryCracksSyntax ()
    : DeclareModel (Secondary::component, "aperture", "alpha", "\
Secondary domain specified by aperture and density of soil cracks.")
  { }
  static bool check_alist (const Metalib&, const Frame& al, Treelog& msg)
  {
    bool ok = true;

    const double Theta = al.number ("aperture") * al.number ("density");
    if (Theta >= 1.0)
      {
        ok = false;
        msg.error ("Volume fraction of cracks exceed 1.0");
      }
    return ok;
  }
  void load_frame (Frame& frame) const
  {
    frame.add_check (check_alist);
    frame.declare ("aperture", "m", Check::positive (), Attribute::Const, "\
Average distance between walls in cracks.");
    frame.declare ("density", "m^-1", Check::positive (), Attribute::Const, "\
Density of cracks.");
  }
} SecondaryCracks_syntax;

// secondary.C ends here.
<|endoftext|>


<commit_before>#include "eigen_solver.hpp"

#include <iomanip>

#include "error.hpp"
#include "files.hpp"

using std::endl;
using std::cout;
using std::cin;

const static int out_w = 14;

namespace mocc{
    EigenSolver::EigenSolver( const pugi::xml_node &input,
            const CoreMesh &mesh ):
        fss_( input, mesh ),
        fission_source_( fss_.n_reg() ),
        fission_source_prev_( fss_.n_reg() ),
        min_iterations_( 0 )
    {
        LogFile << "Initializing Eigenvalue solver..." << std::endl;

        if( input.empty() ) {
            throw EXCEPT("No input specified for the eigenvalue solver.");
        }

        // grab the convergence constraints from the XML
        int in_int = 0;
        real_t in_float = 0.0;

        // K tolerance
        in_float = input.attribute("k_tol").as_float(-1.0);
        if( in_float <= 0.0 ) {
            throw EXCEPT("Invalid k tolerance.");
        }
        tolerance_k_ = in_float;

        // Psi tolerance
        in_float = input.attribute("psi_tol").as_float(-1.0);
        if( in_float <= 0.0 ) {
            throw EXCEPT("Invalid psi tolerance.");
        }
        tolerance_psi_ = in_float;

        // Max iterations
        in_int = input.attribute("max_iter").as_int(-1);
        if( in_int < 0 ) {
            throw EXCEPT("Invalid number of maximum iterations.");
        }
        max_iterations_ = in_int;

        // Min iterations
        if( !input.attribute("min_iter").empty() ) {
            in_int = input.attribute("min_iter").as_int(-1);
            if( (in_int < 0) || (in_int > (int)max_iterations_) ) {
                throw EXCEPT("Invalid number of minimum iterations.");
            }
            min_iterations_ = in_int;
        }

        // CMFD acceleration
        bool do_cmfd = input.attribute("cmfd").as_bool(false);
        if( do_cmfd ) {
            // construct the CMFD solver using the mesh from the transport
            // sweeper
            cmfd_.reset( new CMFD( input.child("cmfd"), (Mesh*)&mesh,
                        fss_.sweeper()->get_homogenized_xsmesh() ) );
            // Associate the sweeper with the coarse data from the CMFD solver
            CoarseData * const cd = cmfd_->get_data();
            fss_.sweeper()->set_coarse_data( cd );
        }

        LogFile << "Done initializing Eigenvalue solver." << std::endl;

        return;
    }

    // Perform a full-blown eigenvalue solve. Start with a guess for the
    // fission source (flat), start doing power iteration. Once we have that
    // working, we will start factoring in CMFD and other fancy tricks
    void EigenSolver::solve() {
        keff_ = 1.0;
        keff_prev_ = 1.0;

        // initialize the fixed source solver and calculation the initial
        // fission source
        fss_.initialize();

        // Hand a reference to the fission source to the fixed source solver
        fss_.set_fission_source(&fission_source_);

        error_k_ = tolerance_k_; // K residual
        error_psi_ = tolerance_psi_; // L-2 norm of the fission source residual

        fss_.sweeper()->calc_fission_source(keff_, fission_source_);

        cout << std::setw(out_w) << "Time"
             << std::setw(out_w) << "Iter."
             << std::setw(out_w) << "k"
             << std::setw(out_w) << "k error"
             << std::setw(out_w) << "psi error" << endl;

        for( size_t n_iterations=0; n_iterations < max_iterations_;
                n_iterations++ )
        {
            this->step();

            // Check for convergence
            error_k_ = fabs(keff_-keff_prev_);

            // use the old fission source to store the difference between new
            // and old, since we will be filling it with new in the next
            // iteration anyways.
            real_t e = 0.0;
            for( int i=0; i<(int)fission_source_.size(); i++ ) {
                e += std::pow((fission_source_(i)-fission_source_prev_(i)), 2);
            }
            error_psi_ = std::sqrt( e );

            convergence_.push_back(
                    ConvergenceCriteria(keff_, error_k_, error_psi_) );

            this->print( n_iterations+1, convergence_.back() );

            if( n_iterations >= max_iterations_ ) {
                std::cout << "Maximum number of iterations reached!"
                          << std::endl;
                break;
            }

            if( (error_k_ < tolerance_k_) && (error_psi_ < tolerance_psi_ ) &&
                (n_iterations >= min_iterations_) ) {
                std::cout << "Convergence criteria met!" << std::endl;
                break;
            }
        }
    }

    void EigenSolver::step() {
        // Store the old fission source
        fission_source_prev_ = fission_source_;

        if( cmfd_ && cmfd_->is_enabled() ) {
            this->do_cmfd();
        }

        // Perform a group sweep with the FSS
        fss_.sweeper()->calc_fission_source(keff_, fission_source_);
        fss_.step();

        // Get the total fission sources
        real_t tfis1 = fss_.sweeper()->total_fission(false);
        real_t tfis2 = fss_.sweeper()->total_fission(true);

        // update estimate for k
        keff_prev_ = keff_;
        keff_ = keff_ * tfis1/tfis2;
    }

    void EigenSolver::print( int iter, ConvergenceCriteria conv ) {
        teestream tee(std::cout, LogFile);
        LogScreen << std::setw(out_w) << std::fixed << std::setprecision(5)
             << RootTimer.time() << std::setw(out_w)
             << iter << conv << endl;
        return;
    }

    void EigenSolver::do_cmfd() {
        assert(cmfd_);
        assert(cmfd_->is_enabled());
        // push homogenized flux onto the coarse mesh, solve, and pull it
        // back.
        cmfd_->coarse_data().flux = fss_.sweeper()->get_pin_flux();

        // Set the convergence criteria for this solve, there are a few ways we
        // can do this

        CMFDConvergence conv = CMFDConvergence::FIXED;
        switch( conv ) {
        case CMFDConvergence::FIXED:
            cmfd_->set_k_tolerance(tolerance_k_/10.0);
            cmfd_->set_psi_tolerance(tolerance_psi_/10.0);
            break;
        case CMFDConvergence::FLOAT:
            real_t k_tol = std::max(error_k_/1000.0, tolerance_k_/10.0);
            cmfd_->set_k_tolerance( k_tol );

            real_t psi_tol = std::max(error_psi_/1000.0, tolerance_psi_/10.0);
            cmfd_->set_psi_tolerance( psi_tol );
            break;
        }
        cmfd_->solve(keff_, fss_.sweeper()->flux());
        fss_.sweeper()->set_pin_flux( cmfd_->flux() );
        return;
    }

    std::ostream& operator<<( std::ostream &os, ConvergenceCriteria conv) {
        std::ios::fmtflags flags = os.flags();

        os   << std::setw(out_w) << std::fixed
                 << std::setprecision(10) << conv.k
             << std::setw(out_w) << std::scientific
                 << std::setprecision(6) << conv.error_k
             << std::setw(out_w) << std::setiosflags(std::ios::scientific)
                 << std::setprecision(6) << conv.error_psi;

        os.flags(flags);
        return os;
    }
};
<commit_msg>Tighten fixed CMFD convergence criteria<commit_after>#include "eigen_solver.hpp"

#include <iomanip>

#include "error.hpp"
#include "files.hpp"

using std::endl;
using std::cout;
using std::cin;

const static int out_w = 14;

namespace mocc{
    EigenSolver::EigenSolver( const pugi::xml_node &input,
            const CoreMesh &mesh ):
        fss_( input, mesh ),
        fission_source_( fss_.n_reg() ),
        fission_source_prev_( fss_.n_reg() ),
        min_iterations_( 0 )
    {
        LogFile << "Initializing Eigenvalue solver..." << std::endl;

        if( input.empty() ) {
            throw EXCEPT("No input specified for the eigenvalue solver.");
        }

        // grab the convergence constraints from the XML
        int in_int = 0;
        real_t in_float = 0.0;

        // K tolerance
        in_float = input.attribute("k_tol").as_float(-1.0);
        if( in_float <= 0.0 ) {
            throw EXCEPT("Invalid k tolerance.");
        }
        tolerance_k_ = in_float;

        // Psi tolerance
        in_float = input.attribute("psi_tol").as_float(-1.0);
        if( in_float <= 0.0 ) {
            throw EXCEPT("Invalid psi tolerance.");
        }
        tolerance_psi_ = in_float;

        // Max iterations
        in_int = input.attribute("max_iter").as_int(-1);
        if( in_int < 0 ) {
            throw EXCEPT("Invalid number of maximum iterations.");
        }
        max_iterations_ = in_int;

        // Min iterations
        if( !input.attribute("min_iter").empty() ) {
            in_int = input.attribute("min_iter").as_int(-1);
            if( (in_int < 0) || (in_int > (int)max_iterations_) ) {
                throw EXCEPT("Invalid number of minimum iterations.");
            }
            min_iterations_ = in_int;
        }

        // CMFD acceleration
        bool do_cmfd = input.attribute("cmfd").as_bool(false);
        if( do_cmfd ) {
            // construct the CMFD solver using the mesh from the transport
            // sweeper
            cmfd_.reset( new CMFD( input.child("cmfd"), (Mesh*)&mesh,
                        fss_.sweeper()->get_homogenized_xsmesh() ) );
            // Associate the sweeper with the coarse data from the CMFD solver
            CoarseData * const cd = cmfd_->get_data();
            fss_.sweeper()->set_coarse_data( cd );
        }

        LogFile << "Done initializing Eigenvalue solver." << std::endl;

        return;
    }

    // Perform a full-blown eigenvalue solve. Start with a guess for the
    // fission source (flat), start doing power iteration. Once we have that
    // working, we will start factoring in CMFD and other fancy tricks
    void EigenSolver::solve() {
        keff_ = 1.0;
        keff_prev_ = 1.0;

        // initialize the fixed source solver and calculation the initial
        // fission source
        fss_.initialize();

        // Hand a reference to the fission source to the fixed source solver
        fss_.set_fission_source(&fission_source_);

        error_k_ = tolerance_k_; // K residual
        error_psi_ = tolerance_psi_; // L-2 norm of the fission source residual

        fss_.sweeper()->calc_fission_source(keff_, fission_source_);

        cout << std::setw(out_w) << "Time"
             << std::setw(out_w) << "Iter."
             << std::setw(out_w) << "k"
             << std::setw(out_w) << "k error"
             << std::setw(out_w) << "psi error" << endl;

        for( size_t n_iterations=0; n_iterations < max_iterations_;
                n_iterations++ )
        {
            this->step();

            // Check for convergence
            error_k_ = fabs(keff_-keff_prev_);

            // use the old fission source to store the difference between new
            // and old, since we will be filling it with new in the next
            // iteration anyways.
            real_t e = 0.0;
            for( int i=0; i<(int)fission_source_.size(); i++ ) {
                e += std::pow((fission_source_(i)-fission_source_prev_(i)), 2);
            }
            error_psi_ = std::sqrt( e );

            convergence_.push_back(
                    ConvergenceCriteria(keff_, error_k_, error_psi_) );

            this->print( n_iterations+1, convergence_.back() );

            if( n_iterations >= max_iterations_ ) {
                std::cout << "Maximum number of iterations reached!"
                          << std::endl;
                break;
            }

            if( (error_k_ < tolerance_k_) && (error_psi_ < tolerance_psi_ ) &&
                (n_iterations >= min_iterations_) ) {
                std::cout << "Convergence criteria met!" << std::endl;
                break;
            }
        }
    }

    void EigenSolver::step() {
        // Store the old fission source
        fission_source_prev_ = fission_source_;

        if( cmfd_ && cmfd_->is_enabled() ) {
            this->do_cmfd();
        }

        // Perform a group sweep with the FSS
        fss_.sweeper()->calc_fission_source(keff_, fission_source_);
        fss_.step();

        // Get the total fission sources
        real_t tfis1 = fss_.sweeper()->total_fission(false);
        real_t tfis2 = fss_.sweeper()->total_fission(true);

        // update estimate for k
        keff_prev_ = keff_;
        keff_ = keff_ * tfis1/tfis2;
    }

    void EigenSolver::print( int iter, ConvergenceCriteria conv ) {
        LogScreen << std::setw(out_w) << std::fixed << std::setprecision(5)
             << RootTimer.time() << std::setw(out_w)
             << iter << conv << endl;
        return;
    }

    void EigenSolver::do_cmfd() {
        assert(cmfd_);
        assert(cmfd_->is_enabled());
        // push homogenized flux onto the coarse mesh, solve, and pull it
        // back.
        cmfd_->coarse_data().flux = fss_.sweeper()->get_pin_flux();

        // Set the convergence criteria for this solve, there are a few ways we
        // can do this

        CMFDConvergence conv = CMFDConvergence::FIXED;
        switch( conv ) {
        case CMFDConvergence::FIXED:
            cmfd_->set_k_tolerance(tolerance_k_/100.0);
            cmfd_->set_psi_tolerance(tolerance_psi_/100.0);
            break;
        case CMFDConvergence::FLOAT:
            real_t k_tol = std::max(error_k_/1000.0, tolerance_k_/10.0);
            cmfd_->set_k_tolerance( k_tol );

            real_t psi_tol = std::max(error_psi_/1000.0, tolerance_psi_/10.0);
            cmfd_->set_psi_tolerance( psi_tol );
            break;
        }
        cmfd_->solve(keff_, fss_.sweeper()->flux());
        fss_.sweeper()->set_pin_flux( cmfd_->flux() );
        return;
    }

    std::ostream& operator<<( std::ostream &os, ConvergenceCriteria conv) {
        std::ios::fmtflags flags = os.flags();

        os   << std::setw(out_w) << std::fixed
                 << std::setprecision(10) << conv.k
             << std::setw(out_w) << std::scientific
                 << std::setprecision(6) << conv.error_k
             << std::setw(out_w) << std::setiosflags(std::ios::scientific)
                 << std::setprecision(6) << conv.error_psi;

        os.flags(flags);
        return os;
    }
};
<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015-2016 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "version.h"

const TCHAR* PluginVersionString = _T("0.1.3-alpha");
<commit_msg>Bump plugin version to 0.1.4-alpha<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015-2016 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "version.h"

const TCHAR* PluginVersionString = _T("0.1.4-alpha");
<|endoftext|>


<commit_before>// $Id: RDFSection.C,v 1.5 2000/10/18 12:53:17 oliver Exp $

#include <BALL/STRUCTURE/RDFSection.h>
#include <BALL/FORMAT/parameters.h>

using namespace std;

namespace BALL
{

	RDFSection::RDFSection()
		:	ParameterSection(),
		 	rdf_()
	{
	}

	RDFSection::RDFSection(const RDFSection& rdf_section)
		:	ParameterSection(),
			rdf_(rdf_section.rdf_)
	{
	}

	RDFSection::~RDFSection()
		throw()
	{
	}

	void RDFSection::destroy()
	{
		clear();
	}

	void RDFSection::clear()
		throw()
	{
		rdf_.clear();
	}

	void RDFSection::set(const RDFSection& rdf_section)
	{
		rdf_.set(rdf_section.rdf_);
	}

	const RDFSection& RDFSection::operator = (const RDFSection& rdf_section)
	{
		rdf_.set(rdf_section.rdf_);
		return *this;
	}

	RadialDistributionFunction RDFSection::getRDF() const
	{
		return rdf_;
	}

	bool RDFSection::extractSection(Parameters& parameters,
			const String& section_name)
	{
		if (!parameters.isValid())
		{
			return false;
		}

		int type;

		// extract the basis information
		ParameterSection::extractSection(parameters, section_name);

		if (options.has("type"))
		{
			if (options.get("type") == "piecewise_polynomial")
			{
				type = PIECEWISE_POLYNOMIAL;
			}
			else
			{
				Log.error() << "RDFSection::extractSection(): "
					<< "Unknown type.";
				return false;
			}
		}
		else
		{
			Log.warn() << "RDFSection::extractSection(): "
				<< "no type given, assuming piecewise_polynomial." << endl;
			type = PIECEWISE_POLYNOMIAL;
		}

		PiecewisePolynomial poly;
		Interval interval;
		std::vector<Interval> intervals;
		Size number_of_intervals;
		Size degree;
		Coefficients coeffs;
		std::vector<Coefficients> coefficients;
		String upper_limit;

		switch(type)
		{

			case PIECEWISE_POLYNOMIAL:

				if (options.has("degree"))
				{
					degree = options.get("degree").toInt();
				}
				else
				{
					Log.warn() << "RDFSection::extractSection(): "
						<< "No degree given, assuming 4." << endl;
					degree = 4;
				}
				coeffs.resize(degree);

				number_of_intervals = getNumberOfKeys();
				intervals.resize(number_of_intervals);
				coefficients.resize(number_of_intervals);

				for (Size i = 0; i < number_of_intervals; ++i)
				{
					interval.first = getValue(i, 0).toFloat();
					// special case: an upper limit can be infinity
					upper_limit = getValue(i, 1);
					if (upper_limit == "inf")
					{
						interval.second = INFINITY;
					}
					else
					{
						interval.second = getValue(i, 1).toFloat();
					}
					for (Size col = 0; col < degree; ++col)
					{
						coeffs[col] = getValue(i, col + 2).toFloat();
					}
					intervals[i] = interval;
					coefficients[i] = coeffs;
				}

				poly.set(degree, intervals, coefficients);
				rdf_ = RadialDistributionFunction(poly);
				return true;

			default:

				Log.error() << "RDFSection::extractSection(): "
					<< "Unknown type." << endl;
				return false;
		}

	}

} // namespace BALL
<commit_msg>fixed: throw()s fixed: merge conflicts changed: canonified interface<commit_after>// $Id: RDFSection.C,v 1.6 2000/10/18 13:54:36 anker Exp $

#include <BALL/STRUCTURE/RDFSection.h>
#include <BALL/FORMAT/parameters.h>

using namespace std;

namespace BALL
{

	RDFSection::RDFSection() throw()
		:	ParameterSection(),
		 	rdf_()
	{
	}

	RDFSection::RDFSection(const RDFSection& rdf_section) throw()
		:	ParameterSection(),
			rdf_(rdf_section.rdf_)
	{
	}

	RDFSection::~RDFSection() throw()
	{
		clear();

		valid_ = false;
	}

	void RDFSection::clear() throw()
	{
		rdf_.clear();

		ParameterSection::clear();
	}

	const RDFSection& RDFSection::operator = (const RDFSection& rdf_section)
		throw()
	{
		ParameterSection::operator = (rdf_section);
		rdf_ = rdf_section.rdf_;

		return *this;
	}

	const RadialDistributionFunction& RDFSection::getRDF() const throw()
	{
		return rdf_;
	}

	bool RDFSection::operator == (const RDFSection& section) const throw()
	{
		return (ParameterSection::operator == (section)
			&& (rdf_ == section.rdf_));
	}

	bool RDFSection::extractSection(Parameters& parameters,
			const String& section_name) throw()
	{
		if (!parameters.isValid())
		{
			return false;
		}

		int type;

		// extract the basis information
		ParameterSection::extractSection(parameters, section_name);

		if (options.has("type"))
		{
			if (options.get("type") == "piecewise_polynomial")
			{
				type = PIECEWISE_POLYNOMIAL;
			}
			else
			{
				Log.error() << "RDFSection::extractSection(): "
					<< "Unknown type.";
				return false;
			}
		}
		else
		{
			Log.warn() << "RDFSection::extractSection(): "
				<< "no type given, assuming piecewise_polynomial." << endl;
			type = PIECEWISE_POLYNOMIAL;
		}

		PiecewisePolynomial poly;
		Interval interval;
		std::vector<Interval> intervals;
		Size number_of_intervals;
		Size degree;
		Coefficients coeffs;
		std::vector<Coefficients> coefficients;
		String upper_limit;

		switch(type)
		{

			case PIECEWISE_POLYNOMIAL:

				if (options.has("degree"))
				{
					degree = options.get("degree").toInt();
				}
				else
				{
					Log.warn() << "RDFSection::extractSection(): "
						<< "No degree given, assuming 4." << endl;
					degree = 4;
				}
				coeffs.resize(degree);

				number_of_intervals = getNumberOfKeys();
				intervals.resize(number_of_intervals);
				coefficients.resize(number_of_intervals);

				for (Size i = 0; i < number_of_intervals; ++i)
				{
					interval.first = getValue(i, 0).toFloat();
					// special case: an upper limit can be infinity
					upper_limit = getValue(i, 1);
					if (upper_limit == "inf")
					{
						interval.second = INFINITY;
					}
					else
					{
						interval.second = getValue(i, 1).toFloat();
					}
					for (Size col = 0; col < degree; ++col)
					{
						coeffs[col] = getValue(i, col + 2).toFloat();
					}
					intervals[i] = interval;
					coefficients[i] = coeffs;
				}

				poly.set(degree, intervals, coefficients);
				rdf_ = RadialDistributionFunction(poly);
				return true;

			default:

				Log.error() << "RDFSection::extractSection(): "
					<< "Unknown type." << endl;
				return false;
		}

	}

} // namespace BALL
<|endoftext|>


<commit_before>/**
* @file ProcedualTerrain.cpp
*/
#include "ProcedualTerrain.h"
#include "Texture.h"
#include "d3dx12.h"
#include "PSO.h"
#include "Texture.h"
#include "Graphics.h"
#include "GamePad.h"
#include <DirectXMath.h>

using Microsoft::WRL::ComPtr;
using namespace DirectX;

/**
* n``p_f[^^.
*/
struct Vertex {
  XMFLOAT3 position;
};

/**
* 葱In`.
*
* @param commandAllocator R}hXg쐬p̃AP[^.
*
* @retval true  .
* @retval false s.
*/
bool ProcedualTerrain::Init(const ComPtr<ID3D12Device>& device, const ComPtr<ID3D12DescriptorHeap>& csuDescriptorHeap)
{
  if (FAILED(device->CreateCommittedResource(
    &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
    D3D12_HEAP_FLAG_NONE,
    &CD3DX12_RESOURCE_DESC::Buffer(vertexCount * sizeof(Vertex)),
    D3D12_RESOURCE_STATE_GENERIC_READ,
    nullptr,
    IID_PPV_ARGS(&vertexBuffer)
  ))) {
    return false;
  }
  vertexBuffer->SetName(L"ProcedualTerrain Vertex Buffer");
  CD3DX12_RANGE range(0, 0);
  void* vertexBufferAddress;
  if (FAILED(vertexBuffer->Map(0, &range, &vertexBufferAddress))) {
    return false;
  }
  Vertex* pVertex = static_cast<Vertex*>(vertexBufferAddress);

  // lp`𓙕_f[^쐬.
  const XMVECTORF32 factor = { 100.0f / static_cast<float>(width - 1), 1, -100.0f / static_cast<float>(height - 1), 1 };
  const XMVECTORF32 offset = { -50, 0, 50, 0 };
  for (size_t z = 0; z < height; ++z) {
    for (size_t x = 0; x < width; ++x) {
      const XMVECTORF32 ipos = { static_cast<float>(x), 0, static_cast<float>(z), 1 };
      const XMVECTOR pos = ipos * factor + offset;
      XMStoreFloat3(&pVertex->position, pos);
      ++pVertex;
    }
  }
  vertexBuffer->Unmap(0, nullptr);
  vertexBufferView.BufferLocation = vertexBuffer->GetGPUVirtualAddress();
  vertexBufferView.StrideInBytes = sizeof(Vertex);
  vertexBufferView.SizeInBytes = static_cast<UINT>(vertexCount * sizeof(Vertex));

  const int indexListSize = static_cast<int>(indexCount * sizeof(uint16_t));
  if (FAILED(device->CreateCommittedResource(
    &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
    D3D12_HEAP_FLAG_NONE,
    &CD3DX12_RESOURCE_DESC::Buffer(indexListSize),
    D3D12_RESOURCE_STATE_GENERIC_READ,
    nullptr,
    IID_PPV_ARGS(&indexBuffer)
  ))) {
    return false;
  }
  indexBuffer->SetName(L"ProcedualTerrain Index Buffer");
  void* indexBufferAddress;
  if (FAILED(indexBuffer->Map(0, &range, &indexBufferAddress))) {
    return false;
  }
  uint16_t* pIndexBuffer = static_cast<uint16_t*>(indexBufferAddress);
  for (size_t z = 0; z < height - 1; ++z) {
    for (size_t x = 0; x < width - 1; ++x) {
      pIndexBuffer[0] = static_cast<uint16_t>(x + z * width);
      pIndexBuffer[1] = static_cast<uint16_t>((x + 1) + z * width);
      pIndexBuffer[2] = static_cast<uint16_t>(x + (z + 1) * width);
      pIndexBuffer[3] = static_cast<uint16_t>((x + 1) + (z + 1) * width);
	  pIndexBuffer += 4;
    }
  }
  indexBuffer->Unmap(0, nullptr);
  indexBufferView.BufferLocation = indexBuffer->GetGPUVirtualAddress();
  indexBufferView.Format = DXGI_FORMAT_R16_UINT;
  indexBufferView.SizeInBytes = indexListSize;

  const size_t constantBufferSize = (sizeof(ConstantBuffer) + 255) & ~255;
  if (FAILED(device->CreateCommittedResource(
	  &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
	  D3D12_HEAP_FLAG_NONE,
	  &CD3DX12_RESOURCE_DESC::Buffer(constantBufferSize),
	  D3D12_RESOURCE_STATE_GENERIC_READ,
	  nullptr,
	  IID_PPV_ARGS(&constantBuffer)
  ))) {
	  return false;
  }
  indexBuffer->SetName(L"ProcedualTerrain Constant Buffer");
  void* constantBufferAddress;
  if (FAILED(constantBuffer->Map(0, &range, &constantBufferAddress))) {
	  return false;
  }
  pConstantBuffer = static_cast<ConstantBuffer*>(constantBufferAddress);
  Update();

  constantBufferView.BufferLocation = constantBuffer->GetGPUVirtualAddress();
  constantBufferView.SizeInBytes = constantBufferSize;
  const UINT handleSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  cbGPUAddress = CD3DX12_GPU_DESCRIPTOR_HANDLE(csuDescriptorHeap->GetGPUDescriptorHandleForHeapStart(), 10, handleSize);
  cbCPUAddress = CD3DX12_CPU_DESCRIPTOR_HANDLE(csuDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), 10, handleSize);
  device->CreateConstantBufferView(&constantBufferView, cbCPUAddress);

  return true;
}

/**
* XV
*/
void ProcedualTerrain::Update()
{
	if (!pConstantBuffer) {
		return;
	}
#if 0
	const GamePad& gamepad = GetGamePad(0);
	if (gamepad.buttons & GamePad::DPAD_LEFT) {
		rotEye.y -= 2.0f / 180.0f * 3.1415926f;
	}
	if (gamepad.buttons & GamePad::DPAD_RIGHT) {
		rotEye.y += 2.0f / 180.0f * 3.1415926f;
	}
	if (gamepad.buttons & GamePad::DPAD_UP) {
		rotEye.x -= 2.0f / 180.0f * 3.1415926f;
	}
	if (gamepad.buttons & GamePad::DPAD_DOWN) {
		rotEye.x += 2.0f / 180.0f * 3.1415926f;
	}
#endif
	Graphics::Graphics& graphics = Graphics::Graphics::Get();
	ConstantBuffer& constant = *pConstantBuffer;
    rotEye = { 3.14159265f / 3.0f, 0 };
	const XMMATRIX matEye = XMMatrixRotationX(rotEye.x) * XMMatrixRotationY(rotEye.y);
	const XMVECTOR eyePos = XMVector4Transform(XMVECTOR{ 0, 0, -70, 1 }, matEye);
	const XMVECTOR eyeUp = XMVector4Transform(XMVECTOR{ 0, 1, 0, 1 }, matEye);
	const XMMATRIX matView = XMMatrixLookAtLH(eyePos, XMVECTOR{ 0, 0, 0, 1 }, eyeUp);
	const XMMATRIX matProjection = XMMatrixPerspectiveFovLH(45.0f*(3.14f / 180.0f), graphics.viewport.Width / graphics.viewport.Height, 1.0f, 1000.0f);
	XMStoreFloat3(&constant.cbFrame.eye, eyePos);
	XMStoreFloat3(&constant.cbFrame.lightDir, XMVECTOR{1.0f / 1.41421356f, -1.0f / 1.41421356f, 0, 1});
	constant.cbFrame.lightDiffuse = XMFLOAT3A(0.8f, 0.8f, 0.7f);
	constant.cbFrame.lightSpecular = XMFLOAT3A(0.8f, 0.8f, 0.7f);
	constant.cbFrame.lightAmbient = XMFLOAT3A(0.1f, 0.05f, 0.1f);
    static float base = 0;
    base += 0.005f;
	constant.cbTerrain = { 25, 100, 100, base };
	XMStoreFloat4x4A(&constant.cbFrame.matViewProjection, XMMatrixTranspose(matView * matProjection));
}

/**
* `.
*
* @param commandList  `R}hs̃R}hXg.
* @param cbTableIndex 萔obt@蓖Ă郋[gfXNv^e[ũCfbNX.
*/
void ProcedualTerrain::Draw(ID3D12GraphicsCommandList* commandList, uint32_t cbTableIndex) const
{
  Graphics::Graphics& graphics = Graphics::Graphics::Get();
  const PSO& pso = GetPSO(PSOType_Terrain);
  commandList->SetGraphicsRootSignature(pso.rootSignature.Get());
  commandList->SetPipelineState(pso.pso.Get());
  ID3D12DescriptorHeap* heapList[] = { graphics.csuDescriptorHeap.Get() };
  commandList->SetDescriptorHeaps(_countof(heapList), heapList);
  commandList->RSSetViewports(1, &graphics.viewport);
  commandList->RSSetScissorRects(1, &graphics.scissorRect);

  commandList->SetGraphicsRootDescriptorTable(cbTableIndex, cbGPUAddress);
  commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST);
  commandList->IASetVertexBuffers(0, 1, &vertexBufferView);
  commandList->IASetIndexBuffer(&indexBufferView);
  commandList->DrawIndexedInstanced(indexCount, 1, 0, 0, 0);
}
<commit_msg>視点移動と組み合わせた疑似無限スクロールを実装.<commit_after>/**
* @file ProcedualTerrain.cpp
*/
#include "ProcedualTerrain.h"
#include "Texture.h"
#include "d3dx12.h"
#include "PSO.h"
#include "Texture.h"
#include "Graphics.h"
#include "GamePad.h"
#include <DirectXMath.h>

using Microsoft::WRL::ComPtr;
using namespace DirectX;

/**
* n``p_f[^^.
*/
struct Vertex {
  XMFLOAT3 position;
};

/**
* 葱In`.
*
* @param commandAllocator R}hXg쐬p̃AP[^.
*
* @retval true  .
* @retval false s.
*/
bool ProcedualTerrain::Init(const ComPtr<ID3D12Device>& device, const ComPtr<ID3D12DescriptorHeap>& csuDescriptorHeap)
{
  if (FAILED(device->CreateCommittedResource(
    &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
    D3D12_HEAP_FLAG_NONE,
    &CD3DX12_RESOURCE_DESC::Buffer(vertexCount * sizeof(Vertex)),
    D3D12_RESOURCE_STATE_GENERIC_READ,
    nullptr,
    IID_PPV_ARGS(&vertexBuffer)
  ))) {
    return false;
  }
  vertexBuffer->SetName(L"ProcedualTerrain Vertex Buffer");
  CD3DX12_RANGE range(0, 0);
  void* vertexBufferAddress;
  if (FAILED(vertexBuffer->Map(0, &range, &vertexBufferAddress))) {
    return false;
  }
  Vertex* pVertex = static_cast<Vertex*>(vertexBufferAddress);

  // lp`𓙕_f[^쐬.
  const XMVECTORF32 factor = { 100.0f / static_cast<float>(width - 1), 1, -100.0f / static_cast<float>(height - 1), 1 };
  const XMVECTORF32 offset = { -50, 0, 50, 0 };
  for (size_t z = 0; z < height; ++z) {
    for (size_t x = 0; x < width; ++x) {
      const XMVECTORF32 ipos = { static_cast<float>(x), 0, static_cast<float>(z), 1 };
      const XMVECTOR pos = ipos * factor + offset;
      XMStoreFloat3(&pVertex->position, pos);
      ++pVertex;
    }
  }
  vertexBuffer->Unmap(0, nullptr);
  vertexBufferView.BufferLocation = vertexBuffer->GetGPUVirtualAddress();
  vertexBufferView.StrideInBytes = sizeof(Vertex);
  vertexBufferView.SizeInBytes = static_cast<UINT>(vertexCount * sizeof(Vertex));

  const int indexListSize = static_cast<int>(indexCount * sizeof(uint16_t));
  if (FAILED(device->CreateCommittedResource(
    &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
    D3D12_HEAP_FLAG_NONE,
    &CD3DX12_RESOURCE_DESC::Buffer(indexListSize),
    D3D12_RESOURCE_STATE_GENERIC_READ,
    nullptr,
    IID_PPV_ARGS(&indexBuffer)
  ))) {
    return false;
  }
  indexBuffer->SetName(L"ProcedualTerrain Index Buffer");
  void* indexBufferAddress;
  if (FAILED(indexBuffer->Map(0, &range, &indexBufferAddress))) {
    return false;
  }
  uint16_t* pIndexBuffer = static_cast<uint16_t*>(indexBufferAddress);
  for (size_t z = 0; z < height - 1; ++z) {
    for (size_t x = 0; x < width - 1; ++x) {
      pIndexBuffer[0] = static_cast<uint16_t>(x + z * width);
      pIndexBuffer[1] = static_cast<uint16_t>((x + 1) + z * width);
      pIndexBuffer[2] = static_cast<uint16_t>(x + (z + 1) * width);
      pIndexBuffer[3] = static_cast<uint16_t>((x + 1) + (z + 1) * width);
	  pIndexBuffer += 4;
    }
  }
  indexBuffer->Unmap(0, nullptr);
  indexBufferView.BufferLocation = indexBuffer->GetGPUVirtualAddress();
  indexBufferView.Format = DXGI_FORMAT_R16_UINT;
  indexBufferView.SizeInBytes = indexListSize;

  const size_t constantBufferSize = (sizeof(ConstantBuffer) + 255) & ~255;
  if (FAILED(device->CreateCommittedResource(
	  &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
	  D3D12_HEAP_FLAG_NONE,
	  &CD3DX12_RESOURCE_DESC::Buffer(constantBufferSize),
	  D3D12_RESOURCE_STATE_GENERIC_READ,
	  nullptr,
	  IID_PPV_ARGS(&constantBuffer)
  ))) {
	  return false;
  }
  indexBuffer->SetName(L"ProcedualTerrain Constant Buffer");
  void* constantBufferAddress;
  if (FAILED(constantBuffer->Map(0, &range, &constantBufferAddress))) {
	  return false;
  }
  pConstantBuffer = static_cast<ConstantBuffer*>(constantBufferAddress);
  Update();

  constantBufferView.BufferLocation = constantBuffer->GetGPUVirtualAddress();
  constantBufferView.SizeInBytes = constantBufferSize;
  const UINT handleSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  cbGPUAddress = CD3DX12_GPU_DESCRIPTOR_HANDLE(csuDescriptorHeap->GetGPUDescriptorHandleForHeapStart(), 10, handleSize);
  cbCPUAddress = CD3DX12_CPU_DESCRIPTOR_HANDLE(csuDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), 10, handleSize);
  device->CreateConstantBufferView(&constantBufferView, cbCPUAddress);

  rotEye = { 3.14159265f / 3.0f, 0 };

  return true;
}

/**
* XV
*/
void ProcedualTerrain::Update()
{
	if (!pConstantBuffer) {
		return;
	}
#if 0
	const GamePad& gamepad = GetGamePad(0);
	if (gamepad.buttons & GamePad::DPAD_LEFT) {
		rotEye.y -= 2.0f / 180.0f * 3.1415926f;
	}
	if (gamepad.buttons & GamePad::DPAD_RIGHT) {
		rotEye.y += 2.0f / 180.0f * 3.1415926f;
	}
	if (gamepad.buttons & GamePad::DPAD_UP) {
		rotEye.x -= 2.0f / 180.0f * 3.1415926f;
	}
	if (gamepad.buttons & GamePad::DPAD_DOWN) {
		rotEye.x += 2.0f / 180.0f * 3.1415926f;
	}
#endif
    static float offsetZ = 0;
    static float base = 0;
    const float limitOffsetZ = 100.0f / static_cast<float>(height - 1);
    offsetZ += 0.1f;
    if (offsetZ >= limitOffsetZ) {
      offsetZ -= limitOffsetZ;
      base += limitOffsetZ;
    }
    Graphics::Graphics& graphics = Graphics::Graphics::Get();
	ConstantBuffer& constant = *pConstantBuffer;
	const XMMATRIX matEye = XMMatrixRotationX(rotEye.x) * XMMatrixRotationY(rotEye.y) * XMMatrixTranslation(0, 0, offsetZ);
	const XMVECTOR eyePos = XMVector4Transform(XMVECTOR{ 0, 0, -70, 1 }, matEye);
    const XMVECTOR eyeForcus = XMVector4Transform(XMVECTOR{ 0, 0, 0, 1 }, matEye);
    const XMVECTOR eyeUp = XMVector4Transform(XMVECTOR{ 0, 1, 0, 1 }, matEye);
	const XMMATRIX matView = XMMatrixLookAtLH(eyePos, eyeForcus, eyeUp);
	const XMMATRIX matProjection = XMMatrixPerspectiveFovLH(45.0f*(3.14f / 180.0f), graphics.viewport.Width / graphics.viewport.Height, 1.0f, 1000.0f);
	XMStoreFloat3(&constant.cbFrame.eye, eyePos);
	XMStoreFloat3(&constant.cbFrame.lightDir, XMVECTOR{1.0f / 1.41421356f, -1.0f / 1.41421356f, 0, 1});
	constant.cbFrame.lightDiffuse = XMFLOAT3A(0.8f, 0.8f, 0.7f);
	constant.cbFrame.lightSpecular = XMFLOAT3A(0.8f, 0.8f, 0.7f);
	constant.cbFrame.lightAmbient = XMFLOAT3A(0.1f, 0.05f, 0.1f);
	constant.cbTerrain = { 25, 100, 100, base };
	XMStoreFloat4x4A(&constant.cbFrame.matViewProjection, XMMatrixTranspose(matView * matProjection));
}

/**
* `.
*
* @param commandList  `R}hs̃R}hXg.
* @param cbTableIndex 萔obt@蓖Ă郋[gfXNv^e[ũCfbNX.
*/
void ProcedualTerrain::Draw(ID3D12GraphicsCommandList* commandList, uint32_t cbTableIndex) const
{
  Graphics::Graphics& graphics = Graphics::Graphics::Get();
  const PSO& pso = GetPSO(PSOType_Terrain);
  commandList->SetGraphicsRootSignature(pso.rootSignature.Get());
  commandList->SetPipelineState(pso.pso.Get());
  ID3D12DescriptorHeap* heapList[] = { graphics.csuDescriptorHeap.Get() };
  commandList->SetDescriptorHeaps(_countof(heapList), heapList);
  commandList->RSSetViewports(1, &graphics.viewport);
  commandList->RSSetScissorRects(1, &graphics.scissorRect);

  commandList->SetGraphicsRootDescriptorTable(cbTableIndex, cbGPUAddress);
  commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST);
  commandList->IASetVertexBuffers(0, 1, &vertexBufferView);
  commandList->IASetIndexBuffer(&indexBufferView);
  commandList->DrawIndexedInstanced(indexCount, 1, 0, 0, 0);
}
<|endoftext|>


<commit_before>#include <vector>

#include "caffe/filler.hpp"
#include "caffe/layers/bias_layer.hpp"
#include "caffe/util/math_functions.hpp"

namespace caffe {

template <typename Dtype>
void BiasLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {
  if (bottom.size() == 1 && this->blobs_.size() > 0) {
    LOG(INFO) << "Skipping parameter initialization";
  } else if (bottom.size() == 1) {
    // bias is a learned parameter; initialize it
    const BiasParameter& param = this->layer_param_.bias_param();
    const int axis = bottom[0]->CanonicalAxisIndex(param.axis());
    const int num_axes = param.num_axes();
    CHECK_GE(num_axes, -1) << "num_axes must be non-negative, "
                           << "or -1 to extend to the end of bottom[0]";
    if (num_axes >= 0) {
      CHECK_GE(bottom[0]->num_axes(), axis + num_axes)
          << "bias blob's shape extends past bottom[0]'s shape when applied "
          << "starting with bottom[0] axis = " << axis;
    }
    this->blobs_.resize(1);
    const vector<int>::const_iterator& shape_start =
        bottom[0]->shape().begin() + axis;
    const vector<int>::const_iterator& shape_end =
        (num_axes == -1) ? bottom[0]->shape().end() : (shape_start + num_axes);
    vector<int> bias_shape(shape_start, shape_end);
    this->blobs_[0].reset(new Blob<Dtype>(bias_shape));
    shared_ptr<Filler<Dtype> > filler(GetFiller<Dtype>(param.filler()));
    filler->Fill(this->blobs_[0].get());
  }
  this->param_propagate_down_.resize(this->blobs_.size(), true);
}

template <typename Dtype>
void BiasLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {
  const BiasParameter& param = this->layer_param_.bias_param();
  Blob<Dtype>* bias = (bottom.size() > 1) ? bottom[1] : this->blobs_[0].get();
  // Always set axis == 0 in special case where bias is a scalar
  // (num_axes == 0). Mathematically equivalent for any choice of axis, so the
  // actual setting can be safely ignored; and computation is most efficient
  // with axis == 0 and (therefore) outer_dim_ == 1.
  const int axis = (bias->num_axes() == 0) ?
      0 : bottom[0]->CanonicalAxisIndex(param.axis());
  CHECK_GE(bottom[0]->num_axes(), axis + bias->num_axes())
      << "bias blob's shape extends past bottom[0]'s shape when applied "
      << "starting with bottom[0] axis = " << axis;
  for (int i = 0; i < bias->num_axes(); ++i) {
    CHECK_EQ(bottom[0]->shape(axis + i), bias->shape(i))
        << "dimension mismatch between bottom[0]->shape(" << axis + i
        << ") and bias->shape(" << i << ")";
  }
  outer_dim_ = bottom[0]->count(0, axis);
  bias_dim_ = bias->count();
  inner_dim_ = bottom[0]->count(axis + bias->num_axes());
  dim_ = bias_dim_ * inner_dim_;
  if (bottom[0] != top[0]) {
    top[0]->ReshapeLike(*bottom[0]);
  }
  bias_multiplier_.Reshape(vector<int>(1, inner_dim_));
  if (bias_multiplier_.cpu_data()[inner_dim_ - 1] != Dtype(1)) {
    caffe_set(inner_dim_, Dtype(1), bias_multiplier_.mutable_cpu_data());
  }
}

template <typename Dtype>
void BiasLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {
  const Dtype* bias_data =
      ((bottom.size() > 1) ? bottom[1] : this->blobs_[0].get())->cpu_data();
  Dtype* top_data = top[0]->mutable_cpu_data();
  if (bottom[0] != top[0]) {
    const Dtype* bottom_data = bottom[0]->cpu_data();
    caffe_copy(bottom[0]->count(), bottom_data, top_data);
  }
  for (int n = 0; n < outer_dim_; ++n) {
    caffe_cpu_gemm(CblasNoTrans, CblasNoTrans, bias_dim_,
        inner_dim_, Dtype(1), Dtype(1), bias_data,
        bias_multiplier_.cpu_data(), Dtype(1), top_data);
    top_data += dim_;
  }
}

template <typename Dtype>
void BiasLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
  if (propagate_down[0] && bottom[0] != top[0]) {
    const Dtype* top_diff = top[0]->cpu_diff();
    Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
    caffe_copy(bottom[0]->count(), top_diff, bottom_diff);
  }
  // in-place, we don't need to do anything with the data diff
  const bool bias_param = (bottom.size() == 1);
  if ((!bias_param && propagate_down[1]) ||
      (bias_param && this->param_propagate_down_[0])) {
    const Dtype* top_diff = top[0]->cpu_diff();
    Dtype* bias_diff = (bias_param ? this->blobs_[0].get() : bottom[1])
        ->mutable_cpu_diff();
    bool accum = bias_param;
    for (int n = 0; n < outer_dim_; ++n) {
      caffe_cpu_gemv(CblasNoTrans, bias_dim_, inner_dim_, Dtype(1),
          top_diff, bias_multiplier_.cpu_data(), Dtype(accum), bias_diff);
      top_diff += dim_;
      accum = true;
    }
  }
}

#ifdef CPU_ONLY
STUB_GPU(BiasLayer);
#endif

INSTANTIATE_CLASS(BiasLayer);
REGISTER_LAYER_CLASS(Bias);

}  // namespace caffe
<commit_msg>Remove incorrect cast of gemm int arg to Dtype in BiasLayer<commit_after>#include <vector>

#include "caffe/filler.hpp"
#include "caffe/layers/bias_layer.hpp"
#include "caffe/util/math_functions.hpp"

namespace caffe {

template <typename Dtype>
void BiasLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {
  if (bottom.size() == 1 && this->blobs_.size() > 0) {
    LOG(INFO) << "Skipping parameter initialization";
  } else if (bottom.size() == 1) {
    // bias is a learned parameter; initialize it
    const BiasParameter& param = this->layer_param_.bias_param();
    const int axis = bottom[0]->CanonicalAxisIndex(param.axis());
    const int num_axes = param.num_axes();
    CHECK_GE(num_axes, -1) << "num_axes must be non-negative, "
                           << "or -1 to extend to the end of bottom[0]";
    if (num_axes >= 0) {
      CHECK_GE(bottom[0]->num_axes(), axis + num_axes)
          << "bias blob's shape extends past bottom[0]'s shape when applied "
          << "starting with bottom[0] axis = " << axis;
    }
    this->blobs_.resize(1);
    const vector<int>::const_iterator& shape_start =
        bottom[0]->shape().begin() + axis;
    const vector<int>::const_iterator& shape_end =
        (num_axes == -1) ? bottom[0]->shape().end() : (shape_start + num_axes);
    vector<int> bias_shape(shape_start, shape_end);
    this->blobs_[0].reset(new Blob<Dtype>(bias_shape));
    shared_ptr<Filler<Dtype> > filler(GetFiller<Dtype>(param.filler()));
    filler->Fill(this->blobs_[0].get());
  }
  this->param_propagate_down_.resize(this->blobs_.size(), true);
}

template <typename Dtype>
void BiasLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {
  const BiasParameter& param = this->layer_param_.bias_param();
  Blob<Dtype>* bias = (bottom.size() > 1) ? bottom[1] : this->blobs_[0].get();
  // Always set axis == 0 in special case where bias is a scalar
  // (num_axes == 0). Mathematically equivalent for any choice of axis, so the
  // actual setting can be safely ignored; and computation is most efficient
  // with axis == 0 and (therefore) outer_dim_ == 1.
  const int axis = (bias->num_axes() == 0) ?
      0 : bottom[0]->CanonicalAxisIndex(param.axis());
  CHECK_GE(bottom[0]->num_axes(), axis + bias->num_axes())
      << "bias blob's shape extends past bottom[0]'s shape when applied "
      << "starting with bottom[0] axis = " << axis;
  for (int i = 0; i < bias->num_axes(); ++i) {
    CHECK_EQ(bottom[0]->shape(axis + i), bias->shape(i))
        << "dimension mismatch between bottom[0]->shape(" << axis + i
        << ") and bias->shape(" << i << ")";
  }
  outer_dim_ = bottom[0]->count(0, axis);
  bias_dim_ = bias->count();
  inner_dim_ = bottom[0]->count(axis + bias->num_axes());
  dim_ = bias_dim_ * inner_dim_;
  if (bottom[0] != top[0]) {
    top[0]->ReshapeLike(*bottom[0]);
  }
  bias_multiplier_.Reshape(vector<int>(1, inner_dim_));
  if (bias_multiplier_.cpu_data()[inner_dim_ - 1] != Dtype(1)) {
    caffe_set(inner_dim_, Dtype(1), bias_multiplier_.mutable_cpu_data());
  }
}

template <typename Dtype>
void BiasLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {
  const Dtype* bias_data =
      ((bottom.size() > 1) ? bottom[1] : this->blobs_[0].get())->cpu_data();
  Dtype* top_data = top[0]->mutable_cpu_data();
  if (bottom[0] != top[0]) {
    const Dtype* bottom_data = bottom[0]->cpu_data();
    caffe_copy(bottom[0]->count(), bottom_data, top_data);
  }
  for (int n = 0; n < outer_dim_; ++n) {
    caffe_cpu_gemm(CblasNoTrans, CblasNoTrans, bias_dim_,
        inner_dim_, 1, Dtype(1), bias_data,
        bias_multiplier_.cpu_data(), Dtype(1), top_data);
    top_data += dim_;
  }
}

template <typename Dtype>
void BiasLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
  if (propagate_down[0] && bottom[0] != top[0]) {
    const Dtype* top_diff = top[0]->cpu_diff();
    Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
    caffe_copy(bottom[0]->count(), top_diff, bottom_diff);
  }
  // in-place, we don't need to do anything with the data diff
  const bool bias_param = (bottom.size() == 1);
  if ((!bias_param && propagate_down[1]) ||
      (bias_param && this->param_propagate_down_[0])) {
    const Dtype* top_diff = top[0]->cpu_diff();
    Dtype* bias_diff = (bias_param ? this->blobs_[0].get() : bottom[1])
        ->mutable_cpu_diff();
    bool accum = bias_param;
    for (int n = 0; n < outer_dim_; ++n) {
      caffe_cpu_gemv(CblasNoTrans, bias_dim_, inner_dim_, Dtype(1),
          top_diff, bias_multiplier_.cpu_data(), Dtype(accum), bias_diff);
      top_diff += dim_;
      accum = true;
    }
  }
}

#ifdef CPU_ONLY
STUB_GPU(BiasLayer);
#endif

INSTANTIATE_CLASS(BiasLayer);
REGISTER_LAYER_CLASS(Bias);

}  // namespace caffe
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: textsearch.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 01:26:10 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_unotools.hxx"

#ifndef INCLUDED_I18NPOOL_MSLANGID_HXX
#include <i18npool/mslangid.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _INTN_HXX //autogen
//#include <tools/intn.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HDL_
#include <com/sun/star/util/SearchFlags.hdl>
#endif
#ifndef _COM_SUN_STAR_I18N_TRANSLITERATIONMODULES_HPP_
#include <com/sun/star/i18n/TransliterationModules.hpp>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _UNOTOOLS_TEXTSEARCH_HXX
#include <unotools/textsearch.hxx>
#endif

using namespace ::com::sun::star::util;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

// ............................................................................
namespace utl
{
// ............................................................................

SearchParam::SearchParam( const String &rText,
                                SearchType eType,
                                BOOL bCaseSensitive,
                                BOOL bWrdOnly,
                                BOOL bSearchInSel )
{
    sSrchStr        = rText;
    eSrchType       = eType;

    bWordOnly       = bWrdOnly;
    bSrchInSel      = bSearchInSel;
    bCaseSense      = bCaseSensitive;

    nTransliterationFlags = 0;

    // Werte fuer "Gewichtete Levenshtein-Distanz"
    bLEV_Relaxed    = TRUE;
    nLEV_OtherX     = 2;
    nLEV_ShorterY   = 1;
    nLEV_LongerZ    = 3;
}

SearchParam::SearchParam( const SearchParam& rParam )
{
    sSrchStr        = rParam.sSrchStr;
    sReplaceStr     = rParam.sReplaceStr;
    eSrchType       = rParam.eSrchType;

    bWordOnly       = rParam.bWordOnly;
    bSrchInSel      = rParam.bSrchInSel;
    bCaseSense      = rParam.bCaseSense;

    bLEV_Relaxed    = rParam.bLEV_Relaxed;
    nLEV_OtherX     = rParam.nLEV_OtherX;
    nLEV_ShorterY   = rParam.nLEV_ShorterY;
    nLEV_LongerZ    = rParam.nLEV_LongerZ;

    nTransliterationFlags = rParam.nTransliterationFlags;
}

//  Klasse zum Suchen eines Strings in einem Text. Es wird genau nach
//  dem String gesucht.
//  ( Die Unterscheidung der Gross/Klein-Schreibung kann mit einen Flag
//  unterdrueckt werden )

TextSearch::TextSearch(const SearchParam & rParam, LanguageType eLang )
{
    if( LANGUAGE_NONE == eLang )
        eLang = LANGUAGE_SYSTEM;
    ::com::sun::star::lang::Locale aLocale(
            MsLangId::convertLanguageToLocale( LanguageType(eLang)));

    Init( rParam, aLocale);
}

TextSearch::TextSearch(const SearchParam & rParam, const CharClass& rCClass )
{
    Init( rParam, rCClass.getLocale() );
}

TextSearch::TextSearch( const SearchOptions& rPara )
{
    try
    {
        Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();
        xTextSearch = Reference< XTextSearch > ( xMSF->createInstance(
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                        "com.sun.star.util.TextSearch" ) ) ), UNO_QUERY );
        xTextSearch->setOptions( rPara );
    }
    catch ( Exception& )
    {
        DBG_ERRORFILE( "TextSearch ctor: Exception caught!" );
    }
}

void TextSearch::Init( const SearchParam & rParam,
                        const ::com::sun::star::lang::Locale& rLocale )
{
    // convert SearchParam to the UNO SearchOptions
    SearchOptions aSOpt;

    switch( rParam.GetSrchType() )
    {
    case SearchParam::SRCH_REGEXP:
        aSOpt.algorithmType = SearchAlgorithms_REGEXP;
        if( rParam.IsSrchInSelection() )
            aSOpt.searchFlag |= SearchFlags::REG_NOT_BEGINOFLINE |
                                SearchFlags::REG_NOT_ENDOFLINE;
        break;

    case SearchParam::SRCH_LEVDIST:
        aSOpt.algorithmType = SearchAlgorithms_APPROXIMATE;
        aSOpt.changedChars = rParam.GetLEVOther();
        aSOpt.deletedChars = rParam.GetLEVLonger();
        aSOpt.insertedChars = rParam.GetLEVShorter();
        if( rParam.IsSrchRelaxed() )
            aSOpt.searchFlag |= SearchFlags::LEV_RELAXED;
        break;

//  case SearchParam::SRCH_NORMAL:
    default:
        aSOpt.algorithmType = SearchAlgorithms_ABSOLUTE;
        if( rParam.IsSrchWordOnly() )
            aSOpt.searchFlag |= SearchFlags::NORM_WORD_ONLY;
        break;
    }
    aSOpt.searchString = rParam.GetSrchStr();
    aSOpt.replaceString = rParam.GetReplaceStr();
    aSOpt.Locale = rLocale;
    aSOpt.transliterateFlags = rParam.GetTransliterationFlags();
    if( !rParam.IsCaseSensitive() )
    {
        aSOpt.searchFlag |= SearchFlags::ALL_IGNORE_CASE;
        aSOpt.transliterateFlags |= ::com::sun::star::i18n::TransliterationModules_IGNORE_CASE;
    }

    try
    {
        Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();
        xTextSearch = Reference< XTextSearch > ( xMSF->createInstance(
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                        "com.sun.star.util.TextSearch" ) ) ), UNO_QUERY );
        xTextSearch->setOptions( aSOpt );
    }
    catch ( Exception& )
    {
        DBG_ERRORFILE( "TextSearch ctor: Exception caught!" );
    }
}

void TextSearch::SetLocale( const ::com::sun::star::util::SearchOptions& rOptions,
                            const ::com::sun::star::lang::Locale& rLocale )
{
    // convert SearchParam to the UNO SearchOptions
    SearchOptions aSOpt( rOptions );
    aSOpt.Locale = rLocale;

    try
    {
        Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();
        xTextSearch = Reference< XTextSearch > ( xMSF->createInstance(
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                        "com.sun.star.util.TextSearch" ) ) ), UNO_QUERY );
        xTextSearch->setOptions( aSOpt );
    }
    catch ( Exception& )
    {
        DBG_ERRORFILE( "TextSearch ctor: Exception caught!" );
    }
}

TextSearch::~TextSearch()
{
}

/*
 * Die allgemeinen Methoden zu Suchen. Diese rufen dann die entpsrecheden
 * Methoden fuer die normale Suche oder der Suche nach Regular-Expressions
 * ueber die MethodenPointer auf.
 */
#if defined _MSC_VER
#pragma optimize("", off)
#endif
int TextSearch::SearchFrwrd( const String & rStr, xub_StrLen* pStart,
                            xub_StrLen* pEnde, SearchResult* pRes )
{
    int nRet = 0;
    try
    {
        if( xTextSearch.is() )
        {
            SearchResult aRet( xTextSearch->searchForward(
                                                    rStr, *pStart, *pEnde ));
            if( 1 == aRet.subRegExpressions )
            {
                nRet = 1;
                // the XTextsearch returns in startOffset the higher position
                // and the endposition is allways exclusive.
                // The caller of this function will have in startPos the
                // lower pos. and end
                *pStart = (xub_StrLen)aRet.startOffset[ 0 ];
                *pEnde = (xub_StrLen)aRet.endOffset[ 0 ];
                if( pRes )
                    *pRes = aRet;
            }
        }
    }
    catch ( Exception& )
    {
        DBG_ERRORFILE( "SearchForward: Exception caught!" );
    }
    return nRet;
}

int TextSearch::SearchBkwrd( const String & rStr, xub_StrLen* pStart,
                            xub_StrLen* pEnde, SearchResult* pRes )
{
    int nRet = 0;
    try
    {
        if( xTextSearch.is() )
        {
            SearchResult aRet( xTextSearch->searchBackward(
                                                    rStr, *pStart, *pEnde ));
            if( aRet.subRegExpressions )
            {
                nRet = 1;
                // the XTextsearch returns in startOffset the higher position
                // and the endposition is allways exclusive.
                // The caller of this function will have in startPos the
                // lower pos. and end
                *pEnde = (xub_StrLen)aRet.startOffset[ 0 ];
                *pStart = (xub_StrLen)aRet.endOffset[ 0 ];
                if( pRes )
                    *pRes = aRet;
            }
        }
    }
    catch ( Exception& )
    {
        DBG_ERRORFILE( "SearchBackward: Exception caught!" );
    }
    return nRet;
}

#if defined _MSC_VER
#pragma optimize("", on)
#endif

// ............................................................................
}   // namespace utl
// ............................................................................

<commit_msg>INTEGRATION: CWS c15v2_SRC680 (1.12.22); FILE MERGED 2007/03/16 10:27:17 dr 1.12.22.1: #146394# #146464# creating object may fail<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: textsearch.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: ihi $ $Date: 2007-03-26 12:46:42 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_unotools.hxx"

#ifndef INCLUDED_I18NPOOL_MSLANGID_HXX
#include <i18npool/mslangid.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _INTN_HXX //autogen
//#include <tools/intn.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HDL_
#include <com/sun/star/util/SearchFlags.hdl>
#endif
#ifndef _COM_SUN_STAR_I18N_TRANSLITERATIONMODULES_HPP_
#include <com/sun/star/i18n/TransliterationModules.hpp>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _UNOTOOLS_TEXTSEARCH_HXX
#include <unotools/textsearch.hxx>
#endif

using namespace ::com::sun::star::util;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

// ............................................................................
namespace utl
{
// ............................................................................

SearchParam::SearchParam( const String &rText,
                                SearchType eType,
                                BOOL bCaseSensitive,
                                BOOL bWrdOnly,
                                BOOL bSearchInSel )
{
    sSrchStr        = rText;
    eSrchType       = eType;

    bWordOnly       = bWrdOnly;
    bSrchInSel      = bSearchInSel;
    bCaseSense      = bCaseSensitive;

    nTransliterationFlags = 0;

    // Werte fuer "Gewichtete Levenshtein-Distanz"
    bLEV_Relaxed    = TRUE;
    nLEV_OtherX     = 2;
    nLEV_ShorterY   = 1;
    nLEV_LongerZ    = 3;
}

SearchParam::SearchParam( const SearchParam& rParam )
{
    sSrchStr        = rParam.sSrchStr;
    sReplaceStr     = rParam.sReplaceStr;
    eSrchType       = rParam.eSrchType;

    bWordOnly       = rParam.bWordOnly;
    bSrchInSel      = rParam.bSrchInSel;
    bCaseSense      = rParam.bCaseSense;

    bLEV_Relaxed    = rParam.bLEV_Relaxed;
    nLEV_OtherX     = rParam.nLEV_OtherX;
    nLEV_ShorterY   = rParam.nLEV_ShorterY;
    nLEV_LongerZ    = rParam.nLEV_LongerZ;

    nTransliterationFlags = rParam.nTransliterationFlags;
}

//  Klasse zum Suchen eines Strings in einem Text. Es wird genau nach
//  dem String gesucht.
//  ( Die Unterscheidung der Gross/Klein-Schreibung kann mit einen Flag
//  unterdrueckt werden )

TextSearch::TextSearch(const SearchParam & rParam, LanguageType eLang )
{
    if( LANGUAGE_NONE == eLang )
        eLang = LANGUAGE_SYSTEM;
    ::com::sun::star::lang::Locale aLocale(
            MsLangId::convertLanguageToLocale( LanguageType(eLang)));

    Init( rParam, aLocale);
}

TextSearch::TextSearch(const SearchParam & rParam, const CharClass& rCClass )
{
    Init( rParam, rCClass.getLocale() );
}

TextSearch::TextSearch( const SearchOptions& rPara )
{
    try
    {
        Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();
        xTextSearch = Reference< XTextSearch > ( xMSF->createInstance(
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                        "com.sun.star.util.TextSearch" ) ) ), UNO_QUERY_THROW );
        xTextSearch->setOptions( rPara );
    }
    catch ( Exception& )
    {
        DBG_ERRORFILE( "TextSearch ctor: Exception caught!" );
    }
}

void TextSearch::Init( const SearchParam & rParam,
                        const ::com::sun::star::lang::Locale& rLocale )
{
    // convert SearchParam to the UNO SearchOptions
    SearchOptions aSOpt;

    switch( rParam.GetSrchType() )
    {
    case SearchParam::SRCH_REGEXP:
        aSOpt.algorithmType = SearchAlgorithms_REGEXP;
        if( rParam.IsSrchInSelection() )
            aSOpt.searchFlag |= SearchFlags::REG_NOT_BEGINOFLINE |
                                SearchFlags::REG_NOT_ENDOFLINE;
        break;

    case SearchParam::SRCH_LEVDIST:
        aSOpt.algorithmType = SearchAlgorithms_APPROXIMATE;
        aSOpt.changedChars = rParam.GetLEVOther();
        aSOpt.deletedChars = rParam.GetLEVLonger();
        aSOpt.insertedChars = rParam.GetLEVShorter();
        if( rParam.IsSrchRelaxed() )
            aSOpt.searchFlag |= SearchFlags::LEV_RELAXED;
        break;

//  case SearchParam::SRCH_NORMAL:
    default:
        aSOpt.algorithmType = SearchAlgorithms_ABSOLUTE;
        if( rParam.IsSrchWordOnly() )
            aSOpt.searchFlag |= SearchFlags::NORM_WORD_ONLY;
        break;
    }
    aSOpt.searchString = rParam.GetSrchStr();
    aSOpt.replaceString = rParam.GetReplaceStr();
    aSOpt.Locale = rLocale;
    aSOpt.transliterateFlags = rParam.GetTransliterationFlags();
    if( !rParam.IsCaseSensitive() )
    {
        aSOpt.searchFlag |= SearchFlags::ALL_IGNORE_CASE;
        aSOpt.transliterateFlags |= ::com::sun::star::i18n::TransliterationModules_IGNORE_CASE;
    }

    try
    {
        Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();
        xTextSearch = Reference< XTextSearch > ( xMSF->createInstance(
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                        "com.sun.star.util.TextSearch" ) ) ), UNO_QUERY_THROW );
        xTextSearch->setOptions( aSOpt );
    }
    catch ( Exception& )
    {
        DBG_ERRORFILE( "TextSearch ctor: Exception caught!" );
    }
}

void TextSearch::SetLocale( const ::com::sun::star::util::SearchOptions& rOptions,
                            const ::com::sun::star::lang::Locale& rLocale )
{
    // convert SearchParam to the UNO SearchOptions
    SearchOptions aSOpt( rOptions );
    aSOpt.Locale = rLocale;

    try
    {
        Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();
        xTextSearch = Reference< XTextSearch > ( xMSF->createInstance(
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                        "com.sun.star.util.TextSearch" ) ) ), UNO_QUERY_THROW );
        xTextSearch->setOptions( aSOpt );
    }
    catch ( Exception& )
    {
        DBG_ERRORFILE( "TextSearch ctor: Exception caught!" );
    }
}

TextSearch::~TextSearch()
{
}

/*
 * Die allgemeinen Methoden zu Suchen. Diese rufen dann die entpsrecheden
 * Methoden fuer die normale Suche oder der Suche nach Regular-Expressions
 * ueber die MethodenPointer auf.
 */
#if defined _MSC_VER
#pragma optimize("", off)
#endif
int TextSearch::SearchFrwrd( const String & rStr, xub_StrLen* pStart,
                            xub_StrLen* pEnde, SearchResult* pRes )
{
    int nRet = 0;
    try
    {
        if( xTextSearch.is() )
        {
            SearchResult aRet( xTextSearch->searchForward(
                                                    rStr, *pStart, *pEnde ));
            if( 1 == aRet.subRegExpressions )
            {
                nRet = 1;
                // the XTextsearch returns in startOffset the higher position
                // and the endposition is allways exclusive.
                // The caller of this function will have in startPos the
                // lower pos. and end
                *pStart = (xub_StrLen)aRet.startOffset[ 0 ];
                *pEnde = (xub_StrLen)aRet.endOffset[ 0 ];
                if( pRes )
                    *pRes = aRet;
            }
        }
    }
    catch ( Exception& )
    {
        DBG_ERRORFILE( "SearchForward: Exception caught!" );
    }
    return nRet;
}

int TextSearch::SearchBkwrd( const String & rStr, xub_StrLen* pStart,
                            xub_StrLen* pEnde, SearchResult* pRes )
{
    int nRet = 0;
    try
    {
        if( xTextSearch.is() )
        {
            SearchResult aRet( xTextSearch->searchBackward(
                                                    rStr, *pStart, *pEnde ));
            if( aRet.subRegExpressions )
            {
                nRet = 1;
                // the XTextsearch returns in startOffset the higher position
                // and the endposition is allways exclusive.
                // The caller of this function will have in startPos the
                // lower pos. and end
                *pEnde = (xub_StrLen)aRet.startOffset[ 0 ];
                *pStart = (xub_StrLen)aRet.endOffset[ 0 ];
                if( pRes )
                    *pRes = aRet;
            }
        }
    }
    catch ( Exception& )
    {
        DBG_ERRORFILE( "SearchBackward: Exception caught!" );
    }
    return nRet;
}

#if defined _MSC_VER
#pragma optimize("", on)
#endif

// ............................................................................
}   // namespace utl
// ............................................................................

<|endoftext|>


<commit_before>//===--- StatisticsRequired.cpp - "Statistics To Gather" Related Typing ---===//
//
// This file is part of the Election Method Mathematics
// Application (EMMA) project.
//
// Copyright (c) 2015 - 2016 Frank D. Martinez and the EMMA project authors
// Licensed under the GNU Affero General Public License, version 3.0.
//
// See the file called "LICENSE" included with this distribution
// for license information.
//
//===----------------------------------------------------------------------===//
//
// Typing relating to statistics the application should gather.
// Keeps track of which information the application should
// collect.
//
//===----------------------------------------------------------------------===//

#include "StatisticsRequired.h"
#include <iostream>

namespace Emma {
  StatisticsRequired::StatisticsRequired() {}
  StatisticsRequired::StatisticsRequired(const RawParsedOptions rpo) {
    std::cout << "only collecting the default baseline statistics for now" << std::endl;
  }
  IndividualElectionStatistics StatisticsRequired::getIndividualElectionStatistics() const {
    return each_election;
  }
  OverviewStatistics StatisticsRequired::getOverviewStatistics() const {
    return simulation_wide;
  }
}
<commit_msg>presenting commentary to Users in a way which does not look as careless<commit_after>//===--- StatisticsRequired.cpp - "Statistics To Gather" Related Typing ---===//
//
// This file is part of the Election Method Mathematics
// Application (EMMA) project.
//
// Copyright (c) 2015 - 2016 Frank D. Martinez and the EMMA project authors
// Licensed under the GNU Affero General Public License, version 3.0.
//
// See the file called "LICENSE" included with this distribution
// for license information.
//
//===----------------------------------------------------------------------===//
//
// Typing relating to statistics the application should gather.
// Keeps track of which information the application should
// collect.
//
//===----------------------------------------------------------------------===//

#include "StatisticsRequired.h"
#include <iostream>

namespace Emma {
  StatisticsRequired::StatisticsRequired() {}
  StatisticsRequired::StatisticsRequired(const RawParsedOptions rpo) {
    std::cout << "Note: We are only collecting the default baseline statistics for now" << std::endl;
  }
  IndividualElectionStatistics StatisticsRequired::getIndividualElectionStatistics() const {
    return each_election;
  }
  OverviewStatistics StatisticsRequired::getOverviewStatistics() const {
    return simulation_wide;
  }
}
<|endoftext|>