<commit_before>/* $Id: naviersystem.C,v 1.1 2006-06-29 20:49:42 roystgnr Exp $ */

/* The Next Great Finite Element Library. */
/* Copyright (C) 2003  Benjamin S. Kirk */

/* 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#include "naviersystem.h"

#include "fe_base.h"
#include "quadrature.h"

void NavierSystem::init_data ()
{
  // Add the velocity components "u" & "v".  They
  // will be approximated using second-order approximation.
  this->add_variable ("u", SECOND);
  this->add_variable ("v", SECOND);

  // Add the pressure variable "p". This will
  // be approximated with a first-order basis,
  // providing an LBB-stable pressure-velocity pair.
  this->add_variable ("p", FIRST);

  // Do the parent's initialization after variables are defined
  FEMSystem::init_data();

  // Tell the system to march u and v forward in time, but
  // leave p as a constraint only
  this->time_evolving(0);
  this->time_evolving(1);

  // Get references to the finite elements we need
  fe_velocity = element_fe[this->variable_type(0)];
  fe_pressure = element_fe[this->variable_type(2)];
  fe_side_vel = side_fe[this->variable_type(0)];

  // To enable FE optimizations, we should prerequest all the data
  // we will need to build the linear system.
  fe_velocity->get_JxW();
  fe_velocity->get_phi();
  fe_velocity->get_dphi();

  fe_pressure->get_phi();

  fe_side_vel->get_JxW();
  fe_side_vel->get_phi();
  fe_side_vel->get_xyz();

  // Useful debugging options
  // this->verify_analytic_jacobians = 1e-6;
  // this->print_jacobians = true;
}

bool NavierSystem::element_time_derivative (bool request_jacobian)
{
  // First we get some references to cell-specific data that
  // will be used to assemble the linear system.

  // Element Jacobian * quadrature weights for interior integration
  const std::vector<Real> &JxW = fe_velocity->get_JxW();

  // The velocity shape functions at interior quadrature points.
  const std::vector<std::vector<Real> > &phi = fe_velocity->get_phi();

  // The velocity shape function gradients at interior
  // quadrature points.
  const std::vector<std::vector<RealGradient> > &dphi =
    fe_velocity->get_dphi();

  // The pressure shape functions at interior
  // quadrature points.
  const std::vector<std::vector<Real> > &psi = fe_pressure->get_phi();

  // The number of local degrees of freedom in each variable
  const unsigned int n_u_dofs = dof_indices_var[0].size();
  assert (n_u_dofs == dof_indices_var[1].size());
  const unsigned int n_p_dofs = dof_indices_var[2].size();

  // The subvectors and submatrices we need to fill:
  DenseSubMatrix<Number> &Kuu = *elem_subjacobians[0][0];
  DenseSubMatrix<Number> &Kvv = *elem_subjacobians[1][1];
  DenseSubMatrix<Number> &Kuv = *elem_subjacobians[0][1];
  DenseSubMatrix<Number> &Kvu = *elem_subjacobians[1][0];
  DenseSubMatrix<Number> &Kup = *elem_subjacobians[0][2];
  DenseSubMatrix<Number> &Kvp = *elem_subjacobians[1][2];
  DenseSubVector<Number> &Fu = *elem_subresiduals[0];
  DenseSubVector<Number> &Fv = *elem_subresiduals[1];

  // Now we will build the element Jacobian and residual.
  // Constructing the residual requires the solution and its
  // gradient from the previous timestep.  This must be
  // calculated at each quadrature point by summing the
  // solution degree-of-freedom values by the appropriate
  // weight functions.
  unsigned int n_qpoints = element_qrule->n_points();

  for (unsigned int qp=0; qp != n_qpoints; qp++)
    {
      // Compute the solution & its gradient at the old Newton iterate
      Number u = interior_value(0, qp),
             v = interior_value(1, qp),
             p = interior_value(2, qp);
      Gradient grad_u = interior_gradient(0, qp),
               grad_v = interior_gradient(1, qp);

      // Definitions for convenience.  It is sometimes simpler to do a
      // dot product if you have the full vector at your disposal.
      const NumberVectorValue U     (u,     v);
      const Number  u_x = grad_u(0);
      const Number  u_y = grad_u(1);
      const Number  v_x = grad_v(0);
      const Number  v_y = grad_v(1);

      // First, an i-loop over the velocity degrees of freedom.
      // We know that n_u_dofs == n_v_dofs so we can compute contributions
      // for both at the same time.
      for (unsigned int i=0; i != n_u_dofs; i++)
        {
          Fu(i) += JxW[qp] *
                   (-Reynolds*(U*grad_u)*phi[i][qp] + // convection term
                    p*dphi[i][qp](0) -                // pressure term
                    (grad_u*dphi[i][qp]));            // diffusion term

          Fv(i) += JxW[qp] *
                   (-Reynolds*(U*grad_v)*phi[i][qp] + // convection term
                    p*dphi[i][qp](1) -                // pressure term
                    (grad_v*dphi[i][qp]));            // diffusion term

          // Note that the Fp block is identically zero unless we are using
          // some kind of artificial compressibility scheme...

          // Matrix contributions for the uu and vv couplings.
          if (request_jacobian)
            for (unsigned int j=0; j != n_u_dofs; j++)
              {
                Kuu(i,j) += JxW[qp] *
 /* convection term */      (-Reynolds*(U*dphi[j][qp])*phi[i][qp] -
 /* diffusion term  */       (dphi[i][qp]*dphi[j][qp]) -
 /* Newton term     */       Reynolds*u_x*phi[i][qp]*phi[j][qp]);

                Kuv(i,j) += JxW[qp] *
 /* Newton term     */      -Reynolds*u_y*phi[i][qp]*phi[j][qp];

                Kvv(i,j) += JxW[qp] *
 /* convection term */      (-Reynolds*(U*dphi[j][qp])*phi[i][qp] -
 /* diffusion term  */       (dphi[i][qp]*dphi[j][qp]) -
 /* Newton term     */       Reynolds*v_y*phi[i][qp]*phi[j][qp]);

                Kvu(i,j) += JxW[qp] *
 /* Newton term     */      -Reynolds*v_x*phi[i][qp]*phi[j][qp];
            }

          // Matrix contributions for the up and vp couplings.
          if (request_jacobian)
            for (unsigned int j=0; j != n_p_dofs; j++)
              {
                Kup(i,j) += JxW[qp]*psi[j][qp]*dphi[i][qp](0);
                Kvp(i,j) += JxW[qp]*psi[j][qp]*dphi[i][qp](1);
              }
        }
    } // end of the quadrature point qp-loop

  return request_jacobian;
}

bool NavierSystem::element_constraint (bool request_jacobian)
{
  // Here we define some references to cell-specific data that
  // will be used to assemble the linear system.

  // Element Jacobian * quadrature weight for interior integration
  const std::vector<Real> &JxW = fe_velocity->get_JxW();

  // The velocity shape function gradients at interior
  // quadrature points.
  const std::vector<std::vector<RealGradient> > &dphi =
    fe_velocity->get_dphi();

  // The pressure shape functions at interior
  // quadrature points.
  const std::vector<std::vector<Real> > &psi = fe_pressure->get_phi();

  // The number of local degrees of freedom in each variable
  const unsigned int n_u_dofs = dof_indices_var[0].size();
  const unsigned int n_p_dofs = dof_indices_var[2].size();

  // The subvectors and submatrices we need to fill:
  DenseSubMatrix<Number> &Kpu = *elem_subjacobians[2][0];
  DenseSubMatrix<Number> &Kpv = *elem_subjacobians[2][1];
  DenseSubVector<Number> &Fp = *elem_subresiduals[2];

  // Add the constraint given by the continuity equation
  unsigned int n_qpoints = element_qrule->n_points();
  for (unsigned int qp=0; qp != n_qpoints; qp++)
    {
      // Compute the velocity gradient at the old Newton iterate
      Gradient grad_u = interior_gradient(0, qp),
               grad_v = interior_gradient(1, qp);

      // Now a loop over the pressure degrees of freedom.  This
      // computes the contributions of the continuity equation.
      for (unsigned int i=0; i != n_p_dofs; i++)
        {
          Fp(i) += JxW[qp] * psi[i][qp] *
                   (grad_u(0) + grad_v(1));

          if (request_jacobian)
            for (unsigned int j=0; j != n_u_dofs; j++)
              {
                Kpu(i,j) += JxW[qp]*psi[i][qp]*dphi[j][qp](0);
                Kpv(i,j) += JxW[qp]*psi[i][qp]*dphi[j][qp](1);
              }
        }
    } // end of the quadrature point qp-loop

  return request_jacobian;
}

bool NavierSystem::side_constraint (bool request_jacobian)
{
  // Here we define some references to cell-specific data that
  // will be used to assemble the linear system.

  // Element Jacobian * quadrature weight for side integration
  const std::vector<Real> &JxW_side = fe_side_vel->get_JxW();

  // The velocity shape functions at side quadrature points.
  const std::vector<std::vector<Real> > &phi_side =
    fe_side_vel->get_phi();

  // The XYZ locations (in physical space) of the
  // quadrature points on the side.  This is where
  // we will interpolate the boundary value function.
  const std::vector<Point > &qside_point = fe_side_vel->get_xyz();

  // The number of local degrees of freedom in u and v
  const unsigned int n_u_dofs = dof_indices_var[0].size();

  // The subvectors and submatrices we need to fill:
  DenseSubMatrix<Number> &Kuu = *elem_subjacobians[0][0];
  DenseSubMatrix<Number> &Kvv = *elem_subjacobians[1][1];

  DenseSubVector<Number> &Fu = *elem_subresiduals[0];
  DenseSubVector<Number> &Fv = *elem_subresiduals[1];

  // For this example we will use Dirichlet velocity boundary
  // conditions imposed at each timestep via the penalty method.

  // The penalty value.  \f$ \frac{1}{\epsilon} \f$
  const Real penalty = 1.e10;

  unsigned int n_sidepoints = side_qrule->n_points();
  for (unsigned int qp=0; qp != n_sidepoints; qp++)
    {
      // Compute the solution at the old Newton iterate
      Number u = side_value(0, qp),
             v = side_value(1, qp);

      // The location of the current boundary quadrature point
      // const Real xf = qside_point[qp](0);
      const Real yf = qside_point[qp](1);

      // Set u = 1 on the top boundary, 0 everywhere else
      const Real u_value = (yf > 1.0 - TOLERANCE) ? 1. : 0.;

      // Set v = 0 everywhere
      const Real v_value = 0.;

      for (unsigned int i=0; i != n_u_dofs; i++)
        {
          Fu(i) += JxW_side[qp] * penalty *
                   (u - u_value) * phi_side[i][qp];
          Fv(i) += JxW_side[qp] * penalty *
                   (v - v_value) * phi_side[i][qp];

          if (request_jacobian)
            for (unsigned int j=0; j != n_u_dofs; j++)
              {
                Kuu(i,j) += JxW_side[qp] * penalty *
                            phi_side[i][qp] * phi_side[j][qp];
                Kvv(i,j) += JxW_side[qp] * penalty *
                            phi_side[i][qp] * phi_side[j][qp];
              }
        }
    }

  return request_jacobian;
}
<commit_msg>Avoid "&phi" and "&psi" - so Firefox won't render them as actual greek letters in the documentation pages<commit_after>/* $Id: naviersystem.C,v 1.2 2006-07-20 21:37:19 roystgnr Exp $ */

/* The Next Great Finite Element Library. */
/* Copyright (C) 2003  Benjamin S. Kirk */

/* 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#include "naviersystem.h"

#include "fe_base.h"
#include "quadrature.h"

void NavierSystem::init_data ()
{
  // Add the velocity components "u" & "v".  They
  // will be approximated using second-order approximation.
  this->add_variable ("u", SECOND);
  this->add_variable ("v", SECOND);

  // Add the pressure variable "p". This will
  // be approximated with a first-order basis,
  // providing an LBB-stable pressure-velocity pair.
  this->add_variable ("p", FIRST);

  // Do the parent's initialization after variables are defined
  FEMSystem::init_data();

  // Tell the system to march u and v forward in time, but
  // leave p as a constraint only
  this->time_evolving(0);
  this->time_evolving(1);

  // Get references to the finite elements we need
  fe_velocity = element_fe[this->variable_type(0)];
  fe_pressure = element_fe[this->variable_type(2)];
  fe_side_vel = side_fe[this->variable_type(0)];

  // To enable FE optimizations, we should prerequest all the data
  // we will need to build the linear system.
  fe_velocity->get_JxW();
  fe_velocity->get_phi();
  fe_velocity->get_dphi();

  fe_pressure->get_phi();

  fe_side_vel->get_JxW();
  fe_side_vel->get_phi();
  fe_side_vel->get_xyz();

  // Useful debugging options
  // this->verify_analytic_jacobians = 1e-6;
  // this->print_jacobians = true;
}

bool NavierSystem::element_time_derivative (bool request_jacobian)
{
  // First we get some references to cell-specific data that
  // will be used to assemble the linear system.

  // Element Jacobian * quadrature weights for interior integration
  const std::vector<Real> &JxW = fe_velocity->get_JxW();

  // The velocity shape functions at interior quadrature points.
  const std::vector<std::vector<Real> >& phi = fe_velocity->get_phi();

  // The velocity shape function gradients at interior
  // quadrature points.
  const std::vector<std::vector<RealGradient> >& dphi =
    fe_velocity->get_dphi();

  // The pressure shape functions at interior
  // quadrature points.
  const std::vector<std::vector<Real> >& psi = fe_pressure->get_phi();

  // The number of local degrees of freedom in each variable
  const unsigned int n_u_dofs = dof_indices_var[0].size();
  assert (n_u_dofs == dof_indices_var[1].size());
  const unsigned int n_p_dofs = dof_indices_var[2].size();

  // The subvectors and submatrices we need to fill:
  DenseSubMatrix<Number> &Kuu = *elem_subjacobians[0][0];
  DenseSubMatrix<Number> &Kvv = *elem_subjacobians[1][1];
  DenseSubMatrix<Number> &Kuv = *elem_subjacobians[0][1];
  DenseSubMatrix<Number> &Kvu = *elem_subjacobians[1][0];
  DenseSubMatrix<Number> &Kup = *elem_subjacobians[0][2];
  DenseSubMatrix<Number> &Kvp = *elem_subjacobians[1][2];
  DenseSubVector<Number> &Fu = *elem_subresiduals[0];
  DenseSubVector<Number> &Fv = *elem_subresiduals[1];

  // Now we will build the element Jacobian and residual.
  // Constructing the residual requires the solution and its
  // gradient from the previous timestep.  This must be
  // calculated at each quadrature point by summing the
  // solution degree-of-freedom values by the appropriate
  // weight functions.
  unsigned int n_qpoints = element_qrule->n_points();

  for (unsigned int qp=0; qp != n_qpoints; qp++)
    {
      // Compute the solution & its gradient at the old Newton iterate
      Number u = interior_value(0, qp),
             v = interior_value(1, qp),
             p = interior_value(2, qp);
      Gradient grad_u = interior_gradient(0, qp),
               grad_v = interior_gradient(1, qp);

      // Definitions for convenience.  It is sometimes simpler to do a
      // dot product if you have the full vector at your disposal.
      const NumberVectorValue U     (u,     v);
      const Number  u_x = grad_u(0);
      const Number  u_y = grad_u(1);
      const Number  v_x = grad_v(0);
      const Number  v_y = grad_v(1);

      // First, an i-loop over the velocity degrees of freedom.
      // We know that n_u_dofs == n_v_dofs so we can compute contributions
      // for both at the same time.
      for (unsigned int i=0; i != n_u_dofs; i++)
        {
          Fu(i) += JxW[qp] *
                   (-Reynolds*(U*grad_u)*phi[i][qp] + // convection term
                    p*dphi[i][qp](0) -                // pressure term
                    (grad_u*dphi[i][qp]));            // diffusion term

          Fv(i) += JxW[qp] *
                   (-Reynolds*(U*grad_v)*phi[i][qp] + // convection term
                    p*dphi[i][qp](1) -                // pressure term
                    (grad_v*dphi[i][qp]));            // diffusion term

          // Note that the Fp block is identically zero unless we are using
          // some kind of artificial compressibility scheme...

          // Matrix contributions for the uu and vv couplings.
          if (request_jacobian)
            for (unsigned int j=0; j != n_u_dofs; j++)
              {
                Kuu(i,j) += JxW[qp] *
 /* convection term */      (-Reynolds*(U*dphi[j][qp])*phi[i][qp] -
 /* diffusion term  */       (dphi[i][qp]*dphi[j][qp]) -
 /* Newton term     */       Reynolds*u_x*phi[i][qp]*phi[j][qp]);

                Kuv(i,j) += JxW[qp] *
 /* Newton term     */      -Reynolds*u_y*phi[i][qp]*phi[j][qp];

                Kvv(i,j) += JxW[qp] *
 /* convection term */      (-Reynolds*(U*dphi[j][qp])*phi[i][qp] -
 /* diffusion term  */       (dphi[i][qp]*dphi[j][qp]) -
 /* Newton term     */       Reynolds*v_y*phi[i][qp]*phi[j][qp]);

                Kvu(i,j) += JxW[qp] *
 /* Newton term     */      -Reynolds*v_x*phi[i][qp]*phi[j][qp];
            }

          // Matrix contributions for the up and vp couplings.
          if (request_jacobian)
            for (unsigned int j=0; j != n_p_dofs; j++)
              {
                Kup(i,j) += JxW[qp]*psi[j][qp]*dphi[i][qp](0);
                Kvp(i,j) += JxW[qp]*psi[j][qp]*dphi[i][qp](1);
              }
        }
    } // end of the quadrature point qp-loop

  return request_jacobian;
}

bool NavierSystem::element_constraint (bool request_jacobian)
{
  // Here we define some references to cell-specific data that
  // will be used to assemble the linear system.

  // Element Jacobian * quadrature weight for interior integration
  const std::vector<Real> &JxW = fe_velocity->get_JxW();

  // The velocity shape function gradients at interior
  // quadrature points.
  const std::vector<std::vector<RealGradient> >& dphi =
    fe_velocity->get_dphi();

  // The pressure shape functions at interior
  // quadrature points.
  const std::vector<std::vector<Real> >& psi = fe_pressure->get_phi();

  // The number of local degrees of freedom in each variable
  const unsigned int n_u_dofs = dof_indices_var[0].size();
  const unsigned int n_p_dofs = dof_indices_var[2].size();

  // The subvectors and submatrices we need to fill:
  DenseSubMatrix<Number> &Kpu = *elem_subjacobians[2][0];
  DenseSubMatrix<Number> &Kpv = *elem_subjacobians[2][1];
  DenseSubVector<Number> &Fp = *elem_subresiduals[2];

  // Add the constraint given by the continuity equation
  unsigned int n_qpoints = element_qrule->n_points();
  for (unsigned int qp=0; qp != n_qpoints; qp++)
    {
      // Compute the velocity gradient at the old Newton iterate
      Gradient grad_u = interior_gradient(0, qp),
               grad_v = interior_gradient(1, qp);

      // Now a loop over the pressure degrees of freedom.  This
      // computes the contributions of the continuity equation.
      for (unsigned int i=0; i != n_p_dofs; i++)
        {
          Fp(i) += JxW[qp] * psi[i][qp] *
                   (grad_u(0) + grad_v(1));

          if (request_jacobian)
            for (unsigned int j=0; j != n_u_dofs; j++)
              {
                Kpu(i,j) += JxW[qp]*psi[i][qp]*dphi[j][qp](0);
                Kpv(i,j) += JxW[qp]*psi[i][qp]*dphi[j][qp](1);
              }
        }
    } // end of the quadrature point qp-loop

  return request_jacobian;
}

bool NavierSystem::side_constraint (bool request_jacobian)
{
  // Here we define some references to cell-specific data that
  // will be used to assemble the linear system.

  // Element Jacobian * quadrature weight for side integration
  const std::vector<Real> &JxW_side = fe_side_vel->get_JxW();

  // The velocity shape functions at side quadrature points.
  const std::vector<std::vector<Real> >& phi_side =
    fe_side_vel->get_phi();

  // The XYZ locations (in physical space) of the
  // quadrature points on the side.  This is where
  // we will interpolate the boundary value function.
  const std::vector<Point > &qside_point = fe_side_vel->get_xyz();

  // The number of local degrees of freedom in u and v
  const unsigned int n_u_dofs = dof_indices_var[0].size();

  // The subvectors and submatrices we need to fill:
  DenseSubMatrix<Number> &Kuu = *elem_subjacobians[0][0];
  DenseSubMatrix<Number> &Kvv = *elem_subjacobians[1][1];

  DenseSubVector<Number> &Fu = *elem_subresiduals[0];
  DenseSubVector<Number> &Fv = *elem_subresiduals[1];

  // For this example we will use Dirichlet velocity boundary
  // conditions imposed at each timestep via the penalty method.

  // The penalty value.  \f$ \frac{1}{\epsilon} \f$
  const Real penalty = 1.e10;

  unsigned int n_sidepoints = side_qrule->n_points();
  for (unsigned int qp=0; qp != n_sidepoints; qp++)
    {
      // Compute the solution at the old Newton iterate
      Number u = side_value(0, qp),
             v = side_value(1, qp);

      // The location of the current boundary quadrature point
      // const Real xf = qside_point[qp](0);
      const Real yf = qside_point[qp](1);

      // Set u = 1 on the top boundary, 0 everywhere else
      const Real u_value = (yf > 1.0 - TOLERANCE) ? 1. : 0.;

      // Set v = 0 everywhere
      const Real v_value = 0.;

      for (unsigned int i=0; i != n_u_dofs; i++)
        {
          Fu(i) += JxW_side[qp] * penalty *
                   (u - u_value) * phi_side[i][qp];
          Fv(i) += JxW_side[qp] * penalty *
                   (v - v_value) * phi_side[i][qp];

          if (request_jacobian)
            for (unsigned int j=0; j != n_u_dofs; j++)
              {
                Kuu(i,j) += JxW_side[qp] * penalty *
                            phi_side[i][qp] * phi_side[j][qp];
                Kvv(i,j) += JxW_side[qp] * penalty *
                            phi_side[i][qp] * phi_side[j][qp];
              }
        }
    }

  return request_jacobian;
}
<|endoftext|>


<commit_before>#include "local_alignment.hpp"
using namespace std;

int LocalAlignment::match_cost(TSequence seq1, TSequence seq2, int i, int j, Score<int, Simple> scores) {
  if (seq1[i-1] == seq2[j-1]) return scoreMatch(scores);
  else return scoreMismatch(scores);
}

int LocalAlignment::max(int * array, int size) {
  int i = 0;
  int max = 0;
  for (i = 0; i < size; i++){
    if(array[i] > max) {
      max = array[i];
    }
  }
  return max;
}

int LocalAlignment::smith_waterman(TSequence seq1, TSequence seq2, Score<int, Simple> scores){
  TAlign align;
  resize(rows(align), 2);
  assignSource(row(align,0),seq1);
  assignSource(row(align,1),seq2);
  TRow &row1 = row(align,0);
  TRow &row2 = row(align,1);

  int seq1Len = length(seq1);
  int seq2Len = length(seq2);
  int matrix[seq1Len + 1][seq2Len + 1];
  int currentCosts[3];
  int i = 0;
  int j= 0;

  for(i =0; i < seq1Len + 1; i++) {
    for(j = 0; j < seq2Len + 1; j++) {
      matrix[i][j] = 0;
    }
  }

  for(i =0; i < seq1Len + 1; i++) {
    for(j = 0; j < seq2Len + 1; j++) {
      cout << matrix[i][j] << " ";
    }
    cout << "\n";
  }
  for(i = 1; i < seq1Len + 1; i++) {
    for(j = 1; j < seq2Len + 1; j++) {
      currentCosts[DIAGONAL] = matrix[i-1][j-1] + LocalAlignment::match_cost(seq1, seq2, i, j, scores);
      currentCosts[TOP] = matrix[i-1][j] + scoreGap(scores);
      currentCosts[LEFT] = matrix[i][j-1] + scoreGap(scores);
      matrix[i][j] = LocalAlignment::max(currentCosts, 3);
    }
  }

  for(i =0; i < seq1Len + 1; i++) {
    for(j = 0; j < seq2Len + 1; j++) {
      cout << matrix[i][j] << " ";
    }
    cout << "\n";
  }
  return 0;
}
<commit_msg>backtrace working now, using the same backtrace code as needleman with minor modifications. need to refactor<commit_after>#include "local_alignment.hpp"
using namespace std;

int LocalAlignment::match_cost(TSequence seq1, TSequence seq2, int i, int j, Score<int, Simple> scores) {
  if (seq1[i-1] == seq2[j-1]) return scoreMatch(scores);
  else return scoreMismatch(scores);
}

int LocalAlignment::max(int * array, int size) {
  int i = 0;
  int max = 0;
  for (i = 0; i < size; i++){
    if(array[i] > max) {
      max = array[i];
    }
  }
  return max;
}

int LocalAlignment::smith_waterman(TSequence seq1, TSequence seq2, Score<int, Simple> scores){
  TAlign align;
  resize(rows(align), 2);
  assignSource(row(align,0),seq1);
  assignSource(row(align,1),seq2);
  TRow &row1 = row(align,0);
  TRow &row2 = row(align,1);

  int seq1Len = length(seq1);
  int seq2Len = length(seq2);
  int matrix[seq1Len + 1][seq2Len + 1];
  int currentCosts[3];
  int i = 0;
  int j= 0;

  int max_i = 0;
  int max_j = 0;
  for(i =0; i < seq1Len + 1; i++) {
    for(j = 0; j < seq2Len + 1; j++) {
      matrix[i][j] = 0;
    }
  }

  /*for(i =0; i < seq1Len + 1; i++) {
    for(j = 0; j < seq2Len + 1; j++) {
      cout << matrix[i][j] << " ";
    }
    cout << "\n";
  }*/

  for(i = 1; i < seq1Len + 1; i++) {
    for(j = 1; j < seq2Len + 1; j++) {
      currentCosts[DIAGONAL] = matrix[i-1][j-1] + LocalAlignment::match_cost(seq1, seq2, i, j, scores);
      currentCosts[TOP] = matrix[i-1][j] + scoreGap(scores);
      currentCosts[LEFT] = matrix[i][j-1] + scoreGap(scores);
      matrix[i][j] = LocalAlignment::max(currentCosts, 3);
      if(matrix[i][j] > matrix[max_i][max_j]) {
        max_i = i;
        max_j = j;
      }
    }
  }

/*
  for(i =0; i < seq1Len + 1; i++) {
    for(j = 0; j < seq2Len + 1; j++) {
      cout << matrix[i][j] << " ";
    }
    cout << "\n";
  }
  */

  i = max_i;
  j = max_j;
  //need to refactor this backtrace as it's pretty much a copy paste of the other one
  int pos, match, mismatch, vgap, hgap;
  while ( (i > 0 || j > 0) && matrix[i][j] > 0)
  {
    pos = matrix[i][j];
    match = matrix[i-1][j-1] + scoreMatch(scores);
    mismatch = matrix[i-1][j-1] + scoreMismatch(scores);
    vgap = matrix[i][j-1] + scoreGap(scores);
    hgap = matrix[i-1][j] + scoreGap(scores);
    //printf("Pos:%d, Match:%d, Current:%d\n", pos, match, matrix[i][j]);
    if (i > 0 && j > 0 && (pos == match || pos == mismatch))
    {
      i--;
      j--;
    }

    else if (j > 0 && pos == vgap)
    {
      insertGap(row1, i);
      j--;
    }

    else if (i > 0 && pos == hgap)
    {
      insertGap(row2, j);
      i--;
    }

    else
    {
      cout << "You distroyed the universe! You're on your own now :( \n";
      exit(1);
    }
  }

  cout << align << "\n";
  return matrix[max_i][max_j];
}
<|endoftext|>


<commit_before>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */
#include "dlgfilters.h"
#include "dlglistindexedfiles.h"
#include "simplesearchgui.h"
#include "searchtabs.h"
#include "histogram.h"
#include "searchview.h"
#include <QtGui/QListWidget>
#include <QtGui/QListWidgetItem>
#include <QtGui/QLineEdit>
#include <QtGui/QVBoxLayout>
#include <QtGui/QStackedWidget>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QFileDialog>
#include <QtGui/QComboBox>
#include <QtGui/QMenu>
#include <QtGui/QMenuBar>
#include <QtGui/QAction>
#include <QtCore/QString>
#include <QtCore/QDebug>
#include <QtCore/QCoreApplication>
#include <QtCore/QProcess>
#include <QtCore/QTimer>
#include <string>
#include <map>
#include <vector>
using namespace std;

SimpleSearchGui::SimpleSearchGui (QWidget * parent, Qt::WFlags flags)
    : QMainWindow (parent, flags)
{
    mainview = new QStackedWidget();

    QWidget* statuswidget = new QWidget();
    QVBoxLayout *statuslayout = new QVBoxLayout;
    statusview = new QLabel();
    statusview->setAlignment(Qt::AlignTop);
    statusview->setMargin(25);
    indexing = false;
    running = false;
    starting = true;
    indexeddirs = new QListWidget();
    adddir = new QPushButton("add directory");
    removedir = new QPushButton("remove directory");
    toggleindexing = new QPushButton("start indexing");
    toggledaemon = new QPushButton("stop daemon");
    statuslayout->addWidget(statusview);
    QHBoxLayout *hlayout = new QHBoxLayout;
    hlayout->addWidget(toggledaemon);
    hlayout->addWidget(toggleindexing);
    statuslayout->addLayout(hlayout);

    histogram = new Histogram();
    fieldnames = new QComboBox();
    fieldnames->addItems(strigi.getFieldNames());
    fieldnames->setCurrentIndex(fieldnames->findText("mtime"));
/*    vector<string> backends = ClientInterface::getBackEnds();
    if (backends.size() > 1) {
        backendsList = new QComboBox();
        for (uint i = 0; i< backends.size(); ++i) {
            QString backend = backends[i].c_str();
            backendsList->insertItem(i, backend);
        }
        statuslayout->addWidget(backendsList);
    } else {*/
        backendsList = 0;
//    }
    statuslayout->addWidget(indexeddirs);
    hlayout = new QHBoxLayout;
    hlayout->addWidget(adddir);
    hlayout->addWidget(removedir);
    statuslayout->addLayout(hlayout);
    statuswidget->setLayout(statuslayout);

    tabs = new SearchTabs();
    tabs->addTab("kde", "kde");
    tabs->addTab("msg", "mimetype:message/*");
    tabs->addTab("irc", "path:*konversation*log");
    tabs->addTab("mail", "mimetype:text/x-mail");
    tabs->addTab("audio", "mimetype:audio/*");
    tabs->addTab("other",
        "-kde -mimetype:message/* -mimetype:text/x-mail -mimetype:audio/*");
    tabs->addTab("all", "");
    mainview->addWidget(tabs);
    mainview->addWidget(statuswidget);
    asyncstrigi.updateStatus();
    mainview->setCurrentIndex(1);

    queryfield = new QLineEdit();
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(mainview);
    layout->addWidget(queryfield);
    layout->addWidget(histogram);
    layout->addWidget(fieldnames);

    centralview = new QWidget();
    centralview->setLayout(layout);
    setCentralWidget(centralview);

    createActions();
    createMenus();

    connect(queryfield, SIGNAL(textChanged(const QString&)),
        this, SLOT(query(const QString&)));
    connect(toggleindexing, SIGNAL(clicked()),
        this, SLOT(toggleIndexing()));
    connect(toggledaemon, SIGNAL(clicked()),
        this, SLOT(toggleDaemon()));
    connect(adddir, SIGNAL(clicked()),
        this, SLOT(addDirectory()));
    connect(removedir, SIGNAL(clicked()),
        this, SLOT(removeDirectory()));
    queryfield->setFocus(Qt::ActiveWindowFocusReason);

    connect (&asyncstrigi,SIGNAL(statusUpdated(const QMap<QString, QString>& )),
        this, SLOT(updateStatus(const QMap<QString, QString>& )));
    connect(&asyncstrigi,
        SIGNAL(gotHistogram(const QString&,const QList<StringUIntPair>&)),
        this, SLOT(getHistogram(const QString&,const QList<StringUIntPair>&)));
    connect (tabs->getSearchView(), SIGNAL(gotHits(const QString&)),
        this, SLOT(callHistogram(const QString&)));
    connect(fieldnames, SIGNAL(currentIndexChanged(const QString&)),
        this, SLOT(setHistogramField(const QString&)));

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(updateStatus()));
    timer->start(2000);
    asyncstrigi.updateStatus();
}
void
SimpleSearchGui::createMenus() {
    fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction(fileExitAct);

    editMenu = menuBar()->addMenu(tr("&Edit"));
    editMenu->addAction(editFiltersAct);
    editMenu->addAction(editListIndexedFilesAct);
}
void
SimpleSearchGui::createActions() {
    fileExitAct = new QAction(tr("&Exit"), this);
    fileExitAct->setShortcut(tr("Ctrl+Q"));
    fileExitAct->setStatusTip(tr("Quit the program"));
    connect(fileExitAct, SIGNAL(triggered()), this, SLOT(close()));

    editFiltersAct = new QAction(tr("Edit Filters"), this);
    editFiltersAct->setStatusTip(tr("Edit filename filters"));
    connect(editFiltersAct, SIGNAL(triggered()), this, SLOT(editFilters()));

    editListIndexedFilesAct = new QAction(tr("List indexed files"), this);
    editListIndexedFilesAct->setStatusTip(tr("Show files indexed by strigi"));
    connect(editListIndexedFilesAct, SIGNAL(triggered()), this, SLOT(editListIndexedFiles()));
}
void
SimpleSearchGui::query(const QString& item) {
    QString query = item.trimmed();
    if (query.length() == 0) {
        tabs->setQuery(QString());
        asyncstrigi.updateStatus();
        mainview->setCurrentIndex(1);
    } else {
        mainview->setCurrentIndex(0);
        tabs->setQuery(query);
        asyncstrigi.clearRequests(StrigiAsyncClient::Histogram);
    }
    histogram->clear();
}
void
SimpleSearchGui::updateStatus() {
    if (statusview->isVisible()) {
        asyncstrigi.updateStatus();
    }
}
void
SimpleSearchGui::updateStatus(const QMap<QString, QString>& s) {
//    static bool first = true;
    static bool attemptedstart = false;
//    if (!first && !statusview->isVisible()) return;
//    first = false;
    QMap<QString, QString> status (s);
    if (status.size() == 0) {
        running = false;
        editFiltersAct->setEnabled(false);
        editListIndexedFilesAct->setEnabled(false);
        status["Status"] = "Daemon is not running";
    } else {
        attemptedstart = true;
        starting = false;
        running = true;
        editFiltersAct->setEnabled(true);
        editListIndexedFilesAct->setEnabled(true);
        if (indexeddirs->count() == 0) {
            updateDirectories();
        }
    }
    toggleindexing->setEnabled(running);
    adddir->setEnabled(running);
    removedir->setEnabled(running);
    queryfield->setEnabled(running);
    toggledaemon->setText((running)?"stop daemon":"start daemon");
    toggledaemon->setEnabled(true);
    if (backendsList) {
        backendsList->setEnabled(!running);
    }
    bool idxng = status["Status"] == "indexing";
    if (idxng != indexing) {
        indexing = idxng;
        toggleindexing->setText((indexing)?"stop indexing":"start indexing");
    }

    QMap<QString,QString>::const_iterator i;
    QString text;
    for (i = status.begin(); i != status.end(); ++i) {
        text += i.key();
        text += ":\t";
        text += i.value();
        text += '\n';
    }
    statusview->setText(text);
}
void
SimpleSearchGui::startDaemon() {
    toggledaemon->setEnabled(false);
    starting = true;
    // try to start the daemon
    QFileInfo exe = QCoreApplication::applicationDirPath()
    + "/../../daemon/strigidaemon";
    QStringList args;
    if (backendsList) {
        args += backendsList->currentText();
    }
    if (exe.exists()) {
        // start not installed version
        QProcess::startDetached(exe.absoluteFilePath(), args);
    } else {
        exe = QCoreApplication::applicationDirPath()+"/strigidaemon";
        if (exe.exists()) {
            QProcess::startDetached(exe.absoluteFilePath(), args);
        } else {
            // start installed version
            QProcess::startDetached("strigidaemon");
        }
    }
}
void
SimpleSearchGui::toggleDaemon() {
    if (running) {
        strigi.stopDaemon();
        indexeddirs->clear();
    } else {
        startDaemon();
    }
}
void
SimpleSearchGui::toggleIndexing() {
    if (indexing) {
        strigi.stopIndexing();
    } else {
        strigi.startIndexing();
    }
}
void
SimpleSearchGui::addDirectory() {
    // open file dialog
    QString dir = QFileDialog::getExistingDirectory (this);
    if (dir.size() <= 0) return;
    for (int i=0; i<indexeddirs->count(); ++i) {
        QString text = indexeddirs->item(i)->text();
        if (dir.startsWith(text)) {
            return;
        }
        if (text.startsWith(dir)) {
            indexeddirs->takeItem(i);
            i = 0;
        }
    }
    indexeddirs->addItem(dir);
    setDirectories();
}
void
SimpleSearchGui::removeDirectory() {
    int i = indexeddirs->currentRow();
    if (i == -1) return;
    indexeddirs->takeItem(i);
    setDirectories();
}
void
SimpleSearchGui::setDirectories() {
    QStringList s;
    for (int i=0; i<indexeddirs->count(); ++i) {
        QString text = indexeddirs->item(i)->text();
        s.append(text);
    }
    strigi.setIndexedDirectories(s);
    updateDirectories();
}
void
SimpleSearchGui::updateDirectories() {
    indexeddirs->clear();
    indexeddirs->addItems(strigi.getIndexedDirectories());
}
void
SimpleSearchGui::editFilters() {
    QList<QPair<bool,QString> > filters;
    filters = strigi.getFilters();

    DlgFilters dlg(filters);
    if (dlg.exec() && filters != dlg.getFilters()) {
        strigi.setFilters(dlg.getFilters());
    }
}
void
SimpleSearchGui::editListIndexedFiles() {
    QStringList files = strigi.getIndexedFiles();
    DlgListIndexedFiles dlg(files);
    dlg.exec();
}
void
SimpleSearchGui::setHistogramField(const QString& fieldname) {
    QString query = queryfield->text().trimmed();
    if (query.length()) {
        asyncstrigi.clearRequests(StrigiAsyncClient::Histogram);
        asyncstrigi.addGetHistogramRequest(query, fieldname, "");
    }
    histogram->clear();
}
void
SimpleSearchGui::getHistogram(const QString& query,
        const QList<StringUIntPair>& h) {
    histogram->setData(h);
}
void
SimpleSearchGui::callHistogram(const QString& query) {
    if (query.length() && mainview->currentIndex() == 0) {
        asyncstrigi.clearRequests(StrigiAsyncClient::Histogram);
        histogram->clear();
        asyncstrigi.addGetHistogramRequest(query, fieldnames->currentText(),"");
    }
}
<commit_msg>Show histogram on the left side instead of on the bottom.<commit_after>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */
#include "dlgfilters.h"
#include "dlglistindexedfiles.h"
#include "simplesearchgui.h"
#include "searchtabs.h"
#include "histogram.h"
#include "searchview.h"
#include <QtGui/QListWidget>
#include <QtGui/QListWidgetItem>
#include <QtGui/QLineEdit>
#include <QtGui/QVBoxLayout>
#include <QtGui/QStackedWidget>
#include <QtGui/QLabel>
#include <QtGui/QDockWidget>
#include <QtGui/QPushButton>
#include <QtGui/QFileDialog>
#include <QtGui/QComboBox>
#include <QtGui/QMenu>
#include <QtGui/QMenuBar>
#include <QtGui/QAction>
#include <QtCore/QString>
#include <QtCore/QDebug>
#include <QtCore/QCoreApplication>
#include <QtCore/QProcess>
#include <QtCore/QTimer>
#include <string>
#include <map>
#include <vector>
using namespace std;

SimpleSearchGui::SimpleSearchGui (QWidget * parent, Qt::WFlags flags)
    : QMainWindow (parent, flags)
{
    mainview = new QStackedWidget();

    QWidget* statuswidget = new QWidget();
    QVBoxLayout *statuslayout = new QVBoxLayout;
    statusview = new QLabel();
    statusview->setAlignment(Qt::AlignTop);
    statusview->setMargin(25);
    indexing = false;
    running = false;
    starting = true;
    indexeddirs = new QListWidget();
    adddir = new QPushButton("add directory");
    removedir = new QPushButton("remove directory");
    toggleindexing = new QPushButton("start indexing");
    toggledaemon = new QPushButton("stop daemon");
    statuslayout->addWidget(statusview);
    QHBoxLayout *hlayout = new QHBoxLayout;
    hlayout->addWidget(toggledaemon);
    hlayout->addWidget(toggleindexing);
    statuslayout->addLayout(hlayout);

    histogram = new Histogram();
    histogram->setOrientation(Qt::Vertical);
    fieldnames = new QComboBox();
    fieldnames->addItems(strigi.getFieldNames());
    fieldnames->setCurrentIndex(fieldnames->findText("mtime"));
/*    vector<string> backends = ClientInterface::getBackEnds();
    if (backends.size() > 1) {
        backendsList = new QComboBox();
        for (uint i = 0; i< backends.size(); ++i) {
            QString backend = backends[i].c_str();
            backendsList->insertItem(i, backend);
        }
        statuslayout->addWidget(backendsList);
    } else {*/
        backendsList = 0;
//    }
    statuslayout->addWidget(indexeddirs);
    hlayout = new QHBoxLayout;
    hlayout->addWidget(adddir);
    hlayout->addWidget(removedir);
    statuslayout->addLayout(hlayout);
    statuswidget->setLayout(statuslayout);

    tabs = new SearchTabs();
    tabs->addTab("kde", "kde");
    tabs->addTab("msg", "mimetype:message/*");
    tabs->addTab("irc", "path:*konversation*log");
    tabs->addTab("mail", "mimetype:text/x-mail");
    tabs->addTab("audio", "mimetype:audio/*");
    tabs->addTab("other",
        "-kde -mimetype:message/* -mimetype:text/x-mail -mimetype:audio/*");
    tabs->addTab("all", "");
    mainview->addWidget(tabs);
    mainview->addWidget(statuswidget);
    asyncstrigi.updateStatus();
    mainview->setCurrentIndex(1);

    queryfield = new QLineEdit();
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(mainview);
    layout->addWidget(queryfield);

    QVBoxLayout* histlayout = new QVBoxLayout();
    QDockWidget* histwidget = new QDockWidget();
    histwidget->setFeatures(QDockWidget::NoDockWidgetFeatures);
    QWidget* histw = new QWidget();
    histw->setLayout(histlayout);
    histwidget->setWidget(histw);
    histlayout->addWidget(fieldnames);
    histlayout->addWidget(histogram);
    addDockWidget(Qt::LeftDockWidgetArea, histwidget);

    centralview = new QWidget();
    centralview->setLayout(layout);
    setCentralWidget(centralview);

    createActions();
    createMenus();

    connect(queryfield, SIGNAL(textChanged(const QString&)),
        this, SLOT(query(const QString&)));
    connect(toggleindexing, SIGNAL(clicked()),
        this, SLOT(toggleIndexing()));
    connect(toggledaemon, SIGNAL(clicked()),
        this, SLOT(toggleDaemon()));
    connect(adddir, SIGNAL(clicked()),
        this, SLOT(addDirectory()));
    connect(removedir, SIGNAL(clicked()),
        this, SLOT(removeDirectory()));
    queryfield->setFocus(Qt::ActiveWindowFocusReason);

    connect (&asyncstrigi,SIGNAL(statusUpdated(const QMap<QString, QString>& )),
        this, SLOT(updateStatus(const QMap<QString, QString>& )));
    connect(&asyncstrigi,
        SIGNAL(gotHistogram(const QString&,const QList<StringUIntPair>&)),
        this, SLOT(getHistogram(const QString&,const QList<StringUIntPair>&)));
    connect (tabs->getSearchView(), SIGNAL(gotHits(const QString&)),
        this, SLOT(callHistogram(const QString&)));
    connect(fieldnames, SIGNAL(currentIndexChanged(const QString&)),
        this, SLOT(setHistogramField(const QString&)));

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(updateStatus()));
    timer->start(2000);
    asyncstrigi.updateStatus();
}
void
SimpleSearchGui::createMenus() {
    fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction(fileExitAct);

    editMenu = menuBar()->addMenu(tr("&Edit"));
    editMenu->addAction(editFiltersAct);
    editMenu->addAction(editListIndexedFilesAct);
}
void
SimpleSearchGui::createActions() {
    fileExitAct = new QAction(tr("&Exit"), this);
    fileExitAct->setShortcut(tr("Ctrl+Q"));
    fileExitAct->setStatusTip(tr("Quit the program"));
    connect(fileExitAct, SIGNAL(triggered()), this, SLOT(close()));

    editFiltersAct = new QAction(tr("Edit Filters"), this);
    editFiltersAct->setStatusTip(tr("Edit filename filters"));
    connect(editFiltersAct, SIGNAL(triggered()), this, SLOT(editFilters()));

    editListIndexedFilesAct = new QAction(tr("List indexed files"), this);
    editListIndexedFilesAct->setStatusTip(tr("Show files indexed by strigi"));
    connect(editListIndexedFilesAct, SIGNAL(triggered()), this, SLOT(editListIndexedFiles()));
}
void
SimpleSearchGui::query(const QString& item) {
    QString query = item.trimmed();
    if (query.length() == 0) {
        tabs->setQuery(QString());
        asyncstrigi.updateStatus();
        mainview->setCurrentIndex(1);
    } else {
        mainview->setCurrentIndex(0);
        tabs->setQuery(query);
        asyncstrigi.clearRequests(StrigiAsyncClient::Histogram);
    }
    histogram->clear();
}
void
SimpleSearchGui::updateStatus() {
    if (statusview->isVisible()) {
        asyncstrigi.updateStatus();
    }
}
void
SimpleSearchGui::updateStatus(const QMap<QString, QString>& s) {
//    static bool first = true;
    static bool attemptedstart = false;
//    if (!first && !statusview->isVisible()) return;
//    first = false;
    QMap<QString, QString> status (s);
    if (status.size() == 0) {
        running = false;
        editFiltersAct->setEnabled(false);
        editListIndexedFilesAct->setEnabled(false);
        status["Status"] = "Daemon is not running";
    } else {
        attemptedstart = true;
        starting = false;
        running = true;
        editFiltersAct->setEnabled(true);
        editListIndexedFilesAct->setEnabled(true);
        if (indexeddirs->count() == 0) {
            updateDirectories();
        }
    }
    toggleindexing->setEnabled(running);
    adddir->setEnabled(running);
    removedir->setEnabled(running);
    queryfield->setEnabled(running);
    toggledaemon->setText((running)?"stop daemon":"start daemon");
    toggledaemon->setEnabled(true);
    if (backendsList) {
        backendsList->setEnabled(!running);
    }
    bool idxng = status["Status"] == "indexing";
    if (idxng != indexing) {
        indexing = idxng;
        toggleindexing->setText((indexing)?"stop indexing":"start indexing");
    }

    QMap<QString,QString>::const_iterator i;
    QString text;
    for (i = status.begin(); i != status.end(); ++i) {
        text += i.key();
        text += ":\t";
        text += i.value();
        text += '\n';
    }
    statusview->setText(text);
}
void
SimpleSearchGui::startDaemon() {
    toggledaemon->setEnabled(false);
    starting = true;
    // try to start the daemon
    QFileInfo exe = QCoreApplication::applicationDirPath()
    + "/../../daemon/strigidaemon";
    QStringList args;
    if (backendsList) {
        args += backendsList->currentText();
    }
    if (exe.exists()) {
        // start not installed version
        QProcess::startDetached(exe.absoluteFilePath(), args);
    } else {
        exe = QCoreApplication::applicationDirPath()+"/strigidaemon";
        if (exe.exists()) {
            QProcess::startDetached(exe.absoluteFilePath(), args);
        } else {
            // start installed version
            QProcess::startDetached("strigidaemon");
        }
    }
}
void
SimpleSearchGui::toggleDaemon() {
    if (running) {
        strigi.stopDaemon();
        indexeddirs->clear();
    } else {
        startDaemon();
    }
}
void
SimpleSearchGui::toggleIndexing() {
    if (indexing) {
        strigi.stopIndexing();
    } else {
        strigi.startIndexing();
    }
}
void
SimpleSearchGui::addDirectory() {
    // open file dialog
    QString dir = QFileDialog::getExistingDirectory (this);
    if (dir.size() <= 0) return;
    for (int i=0; i<indexeddirs->count(); ++i) {
        QString text = indexeddirs->item(i)->text();
        if (dir.startsWith(text)) {
            return;
        }
        if (text.startsWith(dir)) {
            indexeddirs->takeItem(i);
            i = 0;
        }
    }
    indexeddirs->addItem(dir);
    setDirectories();
}
void
SimpleSearchGui::removeDirectory() {
    int i = indexeddirs->currentRow();
    if (i == -1) return;
    indexeddirs->takeItem(i);
    setDirectories();
}
void
SimpleSearchGui::setDirectories() {
    QStringList s;
    for (int i=0; i<indexeddirs->count(); ++i) {
        QString text = indexeddirs->item(i)->text();
        s.append(text);
    }
    strigi.setIndexedDirectories(s);
    updateDirectories();
}
void
SimpleSearchGui::updateDirectories() {
    indexeddirs->clear();
    indexeddirs->addItems(strigi.getIndexedDirectories());
}
void
SimpleSearchGui::editFilters() {
    QList<QPair<bool,QString> > filters;
    filters = strigi.getFilters();

    DlgFilters dlg(filters);
    if (dlg.exec() && filters != dlg.getFilters()) {
        strigi.setFilters(dlg.getFilters());
    }
}
void
SimpleSearchGui::editListIndexedFiles() {
    QStringList files = strigi.getIndexedFiles();
    DlgListIndexedFiles dlg(files);
    dlg.exec();
}
void
SimpleSearchGui::setHistogramField(const QString& fieldname) {
    QString query = queryfield->text().trimmed();
    if (query.length()) {
        asyncstrigi.clearRequests(StrigiAsyncClient::Histogram);
        asyncstrigi.addGetHistogramRequest(query, fieldname, "");
    }
    histogram->clear();
}
void
SimpleSearchGui::getHistogram(const QString& query,
        const QList<StringUIntPair>& h) {
    histogram->setData(h);
}
void
SimpleSearchGui::callHistogram(const QString& query) {
    if (query.length() && mainview->currentIndex() == 0) {
        asyncstrigi.clearRequests(StrigiAsyncClient::Histogram);
        histogram->clear();
        asyncstrigi.addGetHistogramRequest(query, fieldnames->currentText(),"");
    }
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

namespace etl {

#ifdef ETL_VECTORIZE_FULL

//VECTORIZE_FULL enables VECTORIZE_EXPR
#ifndef ETL_VECTORIZE_EXPR
#define ETL_VECTORIZE_EXPR
#endif

//VECTORIZE_FULL enables VECTORIZE_IMPL
#ifndef ETL_VECTORIZE_IMPL
#define ETL_VECTORIZE_IMPL
#endif

#endif //ETL_VECTORIZE_FULL

//Flag to enable auto-vectorization of expressions
#ifdef ETL_VECTORIZE_EXPR
constexpr const bool vectorize_expr = true;
#else
constexpr const bool vectorize_expr   = false; ///< Boolean flag indicating if the expression are automatically vectorized
#endif

//Flag to enable vectorized implementation of algorithms
#ifdef ETL_VECTORIZE_IMPL
constexpr const bool vectorize_impl = true;
#else
constexpr const bool vectorize_impl   = false; ///< Boolean flag indicating if the implementations are automatically vectorized
#endif

//Flag to disable the creation of temporary in expressions
#ifdef ETL_NO_TEMPORARY
constexpr const bool create_temporary = false;
#else
constexpr const bool create_temporary = true; ///< Boolean flag indicating if temporaries are created
#endif

//Flag to allow conv_valid_multi to use FFT
#ifdef ETL_CONV_VALID_FFT
constexpr const bool conv_valid_fft = true;
#else
constexpr const bool conv_valid_fft = false; ///< Boolean flag indicating if temporaries are created
#endif

#ifdef ETL_PARALLEL_THREADS
constexpr const std::size_t threads = ETL_PARALLEL_THREADS;
#else
const std::size_t threads = std::thread::hardware_concurrency(); ///< Number of threads
#endif

#ifdef ETL_PARALLEL
constexpr const bool parallel = true;
#else
constexpr const bool parallel = false; ///< Boolean flag indicating if expressions and implementations are parallelized (alpha)
#endif

#ifdef ETL_MKL_MODE

//MKL mode enables BLAS mode
#ifndef ETL_BLAS_MODE
#define ETL_BLAS_MODE
#endif

constexpr const bool is_mkl_enabled = true;
constexpr const bool has_fast_fft = true;

#else

constexpr const bool is_mkl_enabled = false;
constexpr const bool has_fast_fft = false;

#endif

//Flag to enable the use of CBLAS library
#ifdef ETL_BLAS_MODE
constexpr const bool is_cblas_enabled = true;
#else
constexpr const bool is_cblas_enabled = false;
#endif

#ifdef ETL_CUDA
static_assert(false, "ETL_CUDA should never be set directly");
#endif

#ifdef ETL_CUBLAS_MODE
constexpr const bool is_cublas_enabled = true;
#define ETL_CUDA
#else
constexpr const bool is_cublas_enabled = false;
#endif

#ifdef ETL_CUFFT_MODE
#define ETL_CUDA
constexpr const bool is_cufft_enabled = true;
#else
constexpr const bool is_cufft_enabled = false;
#endif

//Flag to perform elementwise multiplication by default (operator*)
//instead of matrix(vector) multiplication
#ifdef ETL_ELEMENT_WISE_MULTIPLICATION
constexpr const bool is_element_wise_mul_default = true;
#else
constexpr const bool is_element_wise_mul_default = false; ///< Boolean flag indicating if multiplication of two expression means matrix multiplication (false) or element-wise multiplication (true)
#endif

//Flag to prevent division to be done by multiplication
#ifdef ETL_STRICT_DIV
constexpr const bool is_div_strict = true;
#else
constexpr const bool is_div_strict               = false; ///< Boolean flag indicating if division can be done by multiplication (false) or not (true)
#endif

//Flag to disable unrolling of vectorized loops
#ifdef ETL_NO_UNROLL_VECT
constexpr const bool unroll_vectorized_loops = false;
#else
constexpr const bool unroll_vectorized_loops     = true; ///< Boolean flag indicating if vectorized loops are getting unrolled
#endif

//Flag to disable unrolling of non-vectorized loops
#ifdef ETL_NO_UNROLL_NON_VECT
constexpr const bool unroll_normal_loops = false;
#else
constexpr const bool unroll_normal_loops         = true; ///< Boolean flag indicating if normal loops are getting unrolled
#endif

/*!
 * \brief Vectorization mode
 */
enum class vector_mode_t {
    NONE,
    SSE3,
    AVX,
    AVX512
};

#ifdef __AVX512F__
constexpr const vector_mode_t vector_mode = vector_mode_t::AVX512;
#elif defined(__AVX__)
constexpr const vector_mode_t vector_mode = vector_mode_t::AVX;
#elif defined(__SSE3__)
constexpr const vector_mode_t vector_mode = vector_mode_t::SSE3;
#else
constexpr const vector_mode_t vector_mode = vector_mode_t::NONE; ///< The vector mode in use
#endif

#ifdef __AVX512F__
constexpr const bool avx512_enabled = true;
#else
constexpr const bool avx512_enabled = false;
#endif

#ifdef __AVX__
constexpr const bool avx_enabled = true;
#else
constexpr const bool avx_enabled = false;
#endif

#ifdef __SSE3__
constexpr const bool sse3_enabled = true;
#else
constexpr const bool sse3_enabled = false;
#endif

#ifdef __INTEL_COMPILER
constexpr const bool intel_compiler = true;
#else
constexpr const bool intel_compiler = false; ///< Indicates if the project is compiled with intel
#endif

} //end of namespace etl
<commit_msg>New config flag: is_blas_parallel<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

namespace etl {

#ifdef ETL_VECTORIZE_FULL

//VECTORIZE_FULL enables VECTORIZE_EXPR
#ifndef ETL_VECTORIZE_EXPR
#define ETL_VECTORIZE_EXPR
#endif

//VECTORIZE_FULL enables VECTORIZE_IMPL
#ifndef ETL_VECTORIZE_IMPL
#define ETL_VECTORIZE_IMPL
#endif

#endif //ETL_VECTORIZE_FULL

//Flag to enable auto-vectorization of expressions
#ifdef ETL_VECTORIZE_EXPR
constexpr const bool vectorize_expr = true;
#else
constexpr const bool vectorize_expr   = false; ///< Boolean flag indicating if the expression are automatically vectorized
#endif

//Flag to enable vectorized implementation of algorithms
#ifdef ETL_VECTORIZE_IMPL
constexpr const bool vectorize_impl = true;
#else
constexpr const bool vectorize_impl   = false; ///< Boolean flag indicating if the implementations are automatically vectorized
#endif

//Flag to disable the creation of temporary in expressions
#ifdef ETL_NO_TEMPORARY
constexpr const bool create_temporary = false;
#else
constexpr const bool create_temporary = true; ///< Boolean flag indicating if temporaries are created
#endif

//Flag to allow conv_valid_multi to use FFT
#ifdef ETL_CONV_VALID_FFT
constexpr const bool conv_valid_fft = true;
#else
constexpr const bool conv_valid_fft = false; ///< Boolean flag indicating if temporaries are created
#endif

#ifdef ETL_PARALLEL_THREADS
constexpr const std::size_t threads = ETL_PARALLEL_THREADS;
#else
const std::size_t threads = std::thread::hardware_concurrency(); ///< Number of threads
#endif

#ifdef ETL_PARALLEL
constexpr const bool parallel = true;
#else
constexpr const bool parallel = false; ///< Boolean flag indicating if expressions and implementations are parallelized (alpha)
#endif

#ifdef ETL_MKL_MODE

//MKL mode enables BLAS mode
#ifndef ETL_BLAS_MODE
#define ETL_BLAS_MODE
#endif

constexpr const bool is_mkl_enabled = true;
constexpr const bool has_fast_fft = true;

#else

constexpr const bool is_mkl_enabled = false;
constexpr const bool has_fast_fft = false;

#endif

//Flag to enable the use of CBLAS library
#ifdef ETL_BLAS_MODE
constexpr const bool is_cblas_enabled = true;
#else
constexpr const bool is_cblas_enabled = false;
#endif

//Flag to indicate that blas is multithreaded
#ifdef ETL_BLAS_THREADS
constexpr const bool is_blas_parallel = true;
#else
constexpr const bool is_blas_parallel = false;
#endif

#ifdef ETL_CUDA
static_assert(false, "ETL_CUDA should never be set directly");
#endif

#ifdef ETL_CUBLAS_MODE
constexpr const bool is_cublas_enabled = true;
#define ETL_CUDA
#else
constexpr const bool is_cublas_enabled = false;
#endif

#ifdef ETL_CUFFT_MODE
#define ETL_CUDA
constexpr const bool is_cufft_enabled = true;
#else
constexpr const bool is_cufft_enabled = false;
#endif

//Flag to perform elementwise multiplication by default (operator*)
//instead of matrix(vector) multiplication
#ifdef ETL_ELEMENT_WISE_MULTIPLICATION
constexpr const bool is_element_wise_mul_default = true;
#else
constexpr const bool is_element_wise_mul_default = false; ///< Boolean flag indicating if multiplication of two expression means matrix multiplication (false) or element-wise multiplication (true)
#endif

//Flag to prevent division to be done by multiplication
#ifdef ETL_STRICT_DIV
constexpr const bool is_div_strict = true;
#else
constexpr const bool is_div_strict               = false; ///< Boolean flag indicating if division can be done by multiplication (false) or not (true)
#endif

//Flag to disable unrolling of vectorized loops
#ifdef ETL_NO_UNROLL_VECT
constexpr const bool unroll_vectorized_loops = false;
#else
constexpr const bool unroll_vectorized_loops     = true; ///< Boolean flag indicating if vectorized loops are getting unrolled
#endif

//Flag to disable unrolling of non-vectorized loops
#ifdef ETL_NO_UNROLL_NON_VECT
constexpr const bool unroll_normal_loops = false;
#else
constexpr const bool unroll_normal_loops         = true; ///< Boolean flag indicating if normal loops are getting unrolled
#endif

/*!
 * \brief Vectorization mode
 */
enum class vector_mode_t {
    NONE,
    SSE3,
    AVX,
    AVX512
};

#ifdef __AVX512F__
constexpr const vector_mode_t vector_mode = vector_mode_t::AVX512;
#elif defined(__AVX__)
constexpr const vector_mode_t vector_mode = vector_mode_t::AVX;
#elif defined(__SSE3__)
constexpr const vector_mode_t vector_mode = vector_mode_t::SSE3;
#else
constexpr const vector_mode_t vector_mode = vector_mode_t::NONE; ///< The vector mode in use
#endif

#ifdef __AVX512F__
constexpr const bool avx512_enabled = true;
#else
constexpr const bool avx512_enabled = false;
#endif

#ifdef __AVX__
constexpr const bool avx_enabled = true;
#else
constexpr const bool avx_enabled = false;
#endif

#ifdef __SSE3__
constexpr const bool sse3_enabled = true;
#else
constexpr const bool sse3_enabled = false;
#endif

#ifdef __INTEL_COMPILER
constexpr const bool intel_compiler = true;
#else
constexpr const bool intel_compiler = false; ///< Indicates if the project is compiled with intel
#endif

} //end of namespace etl
<|endoftext|>


<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <sstream>
// StdAir
#include <stdair/bom/BomKeyManager.hpp>
#include <stdair/bom/BookingClassKey.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/bom/FareOptionStruct.hpp>
#include <stdair/service/Logger.hpp>
// TravelCCM
#include <travelccm/bom/PriceOrientedModel.hpp>

namespace TRAVELCCM {

  // ////////////////////////////////////////////////////////////////////
  const stdair::TravelSolutionStruct* PriceOrientedModel::
  chooseTravelSolution (stdair::TravelSolutionList_T& ioTSList,
                        const stdair::BookingRequestStruct& iBookingRequest) {
    stdair::TravelSolutionStruct* oChosenTS_ptr = NULL;

    // Retrieve the number of passengers
    const stdair::NbOfSeats_T& lPartySize = iBookingRequest.getPartySize();

    // Retrieve the Willingness-to-Pay (WTP) of the customer
    const stdair::WTP_T& lWTP = iBookingRequest.getWTP();

    // Browse the travel solution list and choose the cheapest one
    stdair::Fare_T lLowestFare = std::numeric_limits<stdair::Fare_T>::max();
    for (stdair::TravelSolutionList_T::iterator itTS = ioTSList.begin();
         itTS != ioTSList.end(); ++itTS) {
      stdair::TravelSolutionStruct& lTS = *itTS;

      // Browse the fare options
      const stdair::FareOptionList_T& lFOList = lTS.getFareOptionList();
      for (stdair::FareOptionList_T::const_iterator itFO = lFOList.begin();
           itFO != lFOList.end(); ++itFO) {
        const stdair::FareOptionStruct& lFO = *itFO;

        // Choose the current fare option and the current solution
        // if the current fare is lower than the current lowest fare.
        const stdair::Fare_T& lCurrentFare = lFO.getFare();
        const stdair::Availability_T& lCurrentAvl = lFO.getAvailability();
        if (lCurrentFare < lLowestFare && lCurrentAvl >= lPartySize
            && lCurrentFare <= lWTP) {
          lLowestFare = lCurrentFare;
          oChosenTS_ptr = &lTS;
          oChosenTS_ptr->setChosenFareOption (lFO);
        }
      }
    }

    return oChosenTS_ptr;
  }

}
<commit_msg>[Dev] Added optional debugging when choising a travel solution.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <sstream>
// StdAir
#include <stdair/bom/BomKeyManager.hpp>
#include <stdair/bom/BookingClassKey.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/bom/FareOptionStruct.hpp>
#include <stdair/service/Logger.hpp>
// TravelCCM
#include <travelccm/bom/PriceOrientedModel.hpp>

namespace TRAVELCCM {

  // ////////////////////////////////////////////////////////////////////
  const stdair::TravelSolutionStruct* PriceOrientedModel::
  chooseTravelSolution (stdair::TravelSolutionList_T& ioTSList,
                        const stdair::BookingRequestStruct& iBookingRequest) {
    stdair::TravelSolutionStruct* oChosenTS_ptr = NULL;

    // Retrieve the number of passengers
    const stdair::NbOfSeats_T& lPartySize = iBookingRequest.getPartySize();

    // Retrieve the Willingness-to-Pay (WTP) of the customer
    const stdair::WTP_T& lWTP = iBookingRequest.getWTP();

    // Browse the travel solution list and choose the cheapest one
    stdair::Fare_T lLowestFare = std::numeric_limits<stdair::Fare_T>::max();
    for (stdair::TravelSolutionList_T::iterator itTS = ioTSList.begin();
         itTS != ioTSList.end(); ++itTS) {
      stdair::TravelSolutionStruct& lTS = *itTS;

      // Browse the fare options
      const stdair::FareOptionList_T& lFOList = lTS.getFareOptionList();
      for (stdair::FareOptionList_T::const_iterator itFO = lFOList.begin();
           itFO != lFOList.end(); ++itFO) {
        const stdair::FareOptionStruct& lFO = *itFO;

        // Choose the current fare option and the current solution
        // if the current fare is lower than the current lowest fare.
        const stdair::Fare_T& lFOFare = lFO.getFare();
        const stdair::Availability_T& lFOAvl = lFO.getAvailability();

        if (lFOFare < lLowestFare && lFOFare <= lWTP && lFOAvl >= lPartySize) {

          // DEBUG
          /*
          STDAIR_LOG_DEBUG ("The travel solution (TS) '" << lTS
                            << "' is chosen because its fare (" << lFOFare
                            << ") is lower than the lowest fare (" << lLowestFare
                            << ") and than the WTP (" << lWTP
                            << "), and because the party size (" << lPartySize
                            << ") is lower than the availability (" << lFOAvl
                            << ")");
          */

          lLowestFare = lFOFare;
          oChosenTS_ptr = &lTS;
          oChosenTS_ptr->setChosenFareOption (lFO);

        } else {
          // DEBUG
          /*
          STDAIR_LOG_DEBUG ("The travel solution (TS) '" << lTS
                            << "' is not chosen because either its fare ("
                            << lFOFare << ") is greater than the lowest fare ("
                            << lLowestFare << ") or than the WTP (" << lWTP
                            << "), or because the party size (" << lPartySize
                            << ") is greater than the availability (" << lFOAvl
                            << ")");
          */
        }
      }
    }

    return oChosenTS_ptr;
  }

}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

namespace etl {

#ifdef ETL_VECTORIZE_FULL

//VECTORIZE_FULL enables VECTORIZE_EXPR
#ifndef ETL_VECTORIZE_EXPR
#define ETL_VECTORIZE_EXPR
#endif

//VECTORIZE_FULL enables VECTORIZE_IMPL
#ifndef ETL_VECTORIZE_IMPL
#define ETL_VECTORIZE_IMPL
#endif

#endif //ETL_VECTORIZE_FULL

//Flag to enable auto-vectorization of expressions
#ifdef ETL_VECTORIZE_EXPR
constexpr const bool vectorize_expr = true;
#else
constexpr const bool vectorize_expr   = false;                               ///< Boolean flag indicating if the expression are automatically vectorized
#endif

//Flag to enable vectorized implementation of algorithms
#ifdef ETL_VECTORIZE_IMPL
constexpr const bool vectorize_impl = true;
#else
constexpr const bool vectorize_impl   = false;                               ///< Boolean flag indicating if the implementations are automatically vectorized
#endif

//Flag to allow conv_valid_multi to use FFT
#ifdef ETL_CONV_VALID_FFT
constexpr const bool conv_valid_fft = true;
#else
constexpr const bool conv_valid_fft   = false;                               ///< Boolean flag indicating if temporaries are created
#endif

//Select the number of threads
#ifdef ETL_PARALLEL_THREADS
constexpr const std::size_t threads = ETL_PARALLEL_THREADS;
#else
const std::size_t threads             = std::thread::hardware_concurrency(); ///< Number of threads
#endif

//Indicate that ETL should run in parallel
#ifdef ETL_PARALLEL
constexpr const bool is_parallel = true;
#else
constexpr const bool is_parallel = false;                               ///< Boolean flag indicating if expressions and implementations are parallelized (alpha)
#endif

#ifdef ETL_MKL_MODE

//MKL mode enables BLAS mode
#ifndef ETL_BLAS_MODE
#define ETL_BLAS_MODE
#endif

constexpr const bool is_mkl_enabled = true;
constexpr const bool has_fast_fft   = true;

#else

constexpr const bool is_mkl_enabled              = false; ///< Boolean flag indicating if MKL is enabled
constexpr const bool has_fast_fft                = false; ///< Boolean flag indicating if a fast FFT implementation is available

#endif

//Flag to enable the use of CBLAS library
#ifdef ETL_BLAS_MODE
constexpr const bool is_cblas_enabled = true;
#else
constexpr const bool is_cblas_enabled            = false; ///< Boolean flag indicating if CBLAS is available
#endif

//Flag to indicate that blas is multithreaded
#ifdef ETL_BLAS_THREADS
constexpr const bool is_blas_parallel = true;
#else
constexpr const bool is_blas_parallel            = false; ///< Boolean flag indicating if CBLAS is running parallel
#endif

#ifdef ETL_CUDA
static_assert(false, "ETL_CUDA should never be set directly");
#endif

#ifdef ETL_CUBLAS_MODE
constexpr const bool is_cublas_enabled = true;
#define ETL_CUDA
#else
constexpr const bool is_cublas_enabled           = false; ///< Boolean flag indicating if CUBLAS is available
#endif

#ifdef ETL_CUFFT_MODE
#define ETL_CUDA
constexpr const bool is_cufft_enabled = true;
#else
constexpr const bool is_cufft_enabled            = false; ///< Boolean flag indicating if CUFFT is available
#endif

#ifdef ETL_CUDNN_MODE
constexpr const bool is_cudnn_enabled = true;
#define ETL_CUDA
#else
constexpr const bool is_cudnn_enabled            = false; ///< Boolean flag indicating if CUDNN is available
#endif

//Flag to perform elementwise multiplication by default (operator*)
//instead of matrix(vector) multiplication
#ifdef ETL_ELEMENT_WISE_MULTIPLICATION
constexpr const bool is_element_wise_mul_default = true;
#else
constexpr const bool is_element_wise_mul_default = false; ///< Boolean flag indicating if multiplication of two expression means matrix multiplication (false) or element-wise multiplication (true)
#endif

//Flag to prevent division to be done by multiplication
#ifdef ETL_STRICT_DIV
constexpr const bool is_div_strict = true;
#else
constexpr const bool is_div_strict               = false; ///< Boolean flag indicating if division can be done by multiplication (false) or not (true)
#endif

// Flag to disable streaming operations
#ifdef ETL_NO_STREAMING
constexpr const bool streaming = false;
#else
constexpr const bool streaming = true;
#endif

// Flag to set the cache size
#ifdef ETL_CACHE_SIZE
constexpr const size_t cache_size = ETL_CACHE_SIZE;
#else
constexpr const size_t cache_size = 3 * 1024 * 1024;
#endif

//Flag to disable unrolling of non-vectorized loops
#ifdef ETL_NO_UNROLL_NON_VECT
constexpr const bool unroll_normal_loops = false;
#else
constexpr const bool unroll_normal_loops         = true;  ///< Boolean flag indicating if normal loops are getting unrolled
#endif

//Flag to configure the maximum workspace size for ETL
#ifdef ETL_MAX_WORKSPACE
constexpr const std::size_t max_workspace = ETL_MAX_WORKSPACE;
#else
constexpr const std::size_t max_workspace = 2UL * 1024 * 1024 * 1024; ///< The max workspace we allocate for ETL (2GiB by default)
#endif

//Flag to configure the maximum workspace size for CUDA
#ifdef ETL_CUDNN_MAX_WORKSPACE
constexpr const std::size_t cudnn_max_workspace = ETL_CUDNN_MAX_WORKSPACE;
#else
constexpr const std::size_t cudnn_max_workspace = 2UL * 1024 * 1024 * 1024; ///< The max workspace we allocate for CUDNN (2GiB by default)
#endif

/*!
 * \brief Vectorization mode
 */
enum class vector_mode_t {
    NONE,  ///< No vectorization is available
    SSE3,  ///< SSE3 is the max vectorization available
    AVX,   ///< AVX is the max vectorization available
    AVX512 ///< AVX-512F is the max vectorization available
};

#ifdef __AVX512F__
constexpr const vector_mode_t vector_mode = vector_mode_t::AVX512;
#elif defined(__AVX__)
constexpr const vector_mode_t vector_mode        = vector_mode_t::AVX;
#elif defined(__SSE3__)
constexpr const vector_mode_t vector_mode = vector_mode_t::SSE3;
#else
constexpr const vector_mode_t vector_mode = vector_mode_t::NONE; ///< The vector mode in use
#endif

#ifdef __AVX512F__
constexpr const bool avx512_enabled = true;
#else
constexpr const bool avx512_enabled              = false; ///< Indicates if AVX512F is available
#endif

#ifdef __AVX__
constexpr const bool avx_enabled = true;
#else
constexpr const bool avx_enabled                 = false; ///< Indicates if AVX is available
#endif

#ifdef __SSE3__
constexpr const bool sse3_enabled = true;
#else
constexpr const bool sse3_enabled                = false; ///< Indicates if sse3 is available
#endif

#ifdef __INTEL_COMPILER
constexpr const bool intel_compiler = true;
#else
constexpr const bool intel_compiler              = false; ///< Indicates if the project is compiled with intel
#endif

} //end of namespace etl
<commit_msg>Prepare padding support<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

namespace etl {

#ifdef ETL_VECTORIZE_FULL

//VECTORIZE_FULL enables VECTORIZE_EXPR
#ifndef ETL_VECTORIZE_EXPR
#define ETL_VECTORIZE_EXPR
#endif

//VECTORIZE_FULL enables VECTORIZE_IMPL
#ifndef ETL_VECTORIZE_IMPL
#define ETL_VECTORIZE_IMPL
#endif

#endif //ETL_VECTORIZE_FULL

//Flag to enable auto-vectorization of expressions
#ifdef ETL_VECTORIZE_EXPR
constexpr const bool vectorize_expr = true;
#else
constexpr const bool vectorize_expr   = false;                               ///< Boolean flag indicating if the expression are automatically vectorized
#endif

//Flag to enable vectorized implementation of algorithms
#ifdef ETL_VECTORIZE_IMPL
constexpr const bool vectorize_impl = true;
#else
constexpr const bool vectorize_impl   = false;                               ///< Boolean flag indicating if the implementations are automatically vectorized
#endif

//Flag to allow conv_valid_multi to use FFT
#ifdef ETL_CONV_VALID_FFT
constexpr const bool conv_valid_fft = true;
#else
constexpr const bool conv_valid_fft   = false;                               ///< Boolean flag indicating if temporaries are created
#endif

//Select the number of threads
#ifdef ETL_PARALLEL_THREADS
constexpr const std::size_t threads = ETL_PARALLEL_THREADS;
#else
const std::size_t threads             = std::thread::hardware_concurrency(); ///< Number of threads
#endif

//Indicate that ETL should run in parallel
#ifdef ETL_PARALLEL
constexpr const bool is_parallel = true;
#else
constexpr const bool is_parallel = false;                               ///< Boolean flag indicating if expressions and implementations are parallelized (alpha)
#endif

#ifdef ETL_MKL_MODE

//MKL mode enables BLAS mode
#ifndef ETL_BLAS_MODE
#define ETL_BLAS_MODE
#endif

constexpr const bool is_mkl_enabled = true;
constexpr const bool has_fast_fft   = true;

#else

constexpr const bool is_mkl_enabled              = false; ///< Boolean flag indicating if MKL is enabled
constexpr const bool has_fast_fft                = false; ///< Boolean flag indicating if a fast FFT implementation is available

#endif

//Flag to enable the use of CBLAS library
#ifdef ETL_BLAS_MODE
constexpr const bool is_cblas_enabled = true;
#else
constexpr const bool is_cblas_enabled            = false; ///< Boolean flag indicating if CBLAS is available
#endif

//Flag to indicate that blas is multithreaded
#ifdef ETL_BLAS_THREADS
constexpr const bool is_blas_parallel = true;
#else
constexpr const bool is_blas_parallel            = false; ///< Boolean flag indicating if CBLAS is running parallel
#endif

#ifdef ETL_CUDA
static_assert(false, "ETL_CUDA should never be set directly");
#endif

#ifdef ETL_CUBLAS_MODE
constexpr const bool is_cublas_enabled = true;
#define ETL_CUDA
#else
constexpr const bool is_cublas_enabled           = false; ///< Boolean flag indicating if CUBLAS is available
#endif

#ifdef ETL_CUFFT_MODE
#define ETL_CUDA
constexpr const bool is_cufft_enabled = true;
#else
constexpr const bool is_cufft_enabled            = false; ///< Boolean flag indicating if CUFFT is available
#endif

#ifdef ETL_CUDNN_MODE
constexpr const bool is_cudnn_enabled = true;
#define ETL_CUDA
#else
constexpr const bool is_cudnn_enabled            = false; ///< Boolean flag indicating if CUDNN is available
#endif

//Flag to perform elementwise multiplication by default (operator*)
//instead of matrix(vector) multiplication
#ifdef ETL_ELEMENT_WISE_MULTIPLICATION
constexpr const bool is_element_wise_mul_default = true;
#else
constexpr const bool is_element_wise_mul_default = false; ///< Boolean flag indicating if multiplication of two expression means matrix multiplication (false) or element-wise multiplication (true)
#endif

//Flag to prevent division to be done by multiplication
#ifdef ETL_STRICT_DIV
constexpr const bool is_div_strict = true;
#else
constexpr const bool is_div_strict               = false; ///< Boolean flag indicating if division can be done by multiplication (false) or not (true)
#endif

// Flag to disable streaming operations
#ifdef ETL_NO_STREAMING
constexpr const bool streaming = false;
#else
constexpr const bool streaming = true;
#endif

// Flag to disable streaming operations
#ifdef ETL_NO_PADDING
constexpr const bool padding = false;
#else
constexpr const bool padding = true;
#endif

// Flag to set the cache size
#ifdef ETL_CACHE_SIZE
constexpr const size_t cache_size = ETL_CACHE_SIZE;
#else
constexpr const size_t cache_size = 3 * 1024 * 1024;
#endif

//Flag to disable unrolling of non-vectorized loops
#ifdef ETL_NO_UNROLL_NON_VECT
constexpr const bool unroll_normal_loops = false;
#else
constexpr const bool unroll_normal_loops         = true;  ///< Boolean flag indicating if normal loops are getting unrolled
#endif

//Flag to configure the maximum workspace size for ETL
#ifdef ETL_MAX_WORKSPACE
constexpr const std::size_t max_workspace = ETL_MAX_WORKSPACE;
#else
constexpr const std::size_t max_workspace = 2UL * 1024 * 1024 * 1024; ///< The max workspace we allocate for ETL (2GiB by default)
#endif

//Flag to configure the maximum workspace size for CUDA
#ifdef ETL_CUDNN_MAX_WORKSPACE
constexpr const std::size_t cudnn_max_workspace = ETL_CUDNN_MAX_WORKSPACE;
#else
constexpr const std::size_t cudnn_max_workspace = 2UL * 1024 * 1024 * 1024; ///< The max workspace we allocate for CUDNN (2GiB by default)
#endif

/*!
 * \brief Vectorization mode
 */
enum class vector_mode_t {
    NONE,  ///< No vectorization is available
    SSE3,  ///< SSE3 is the max vectorization available
    AVX,   ///< AVX is the max vectorization available
    AVX512 ///< AVX-512F is the max vectorization available
};

#ifdef __AVX512F__
constexpr const vector_mode_t vector_mode = vector_mode_t::AVX512;
#elif defined(__AVX__)
constexpr const vector_mode_t vector_mode        = vector_mode_t::AVX;
#elif defined(__SSE3__)
constexpr const vector_mode_t vector_mode = vector_mode_t::SSE3;
#else
constexpr const vector_mode_t vector_mode = vector_mode_t::NONE; ///< The vector mode in use
#endif

#ifdef __AVX512F__
constexpr const bool avx512_enabled = true;
#else
constexpr const bool avx512_enabled              = false; ///< Indicates if AVX512F is available
#endif

#ifdef __AVX__
constexpr const bool avx_enabled = true;
#else
constexpr const bool avx_enabled                 = false; ///< Indicates if AVX is available
#endif

#ifdef __SSE3__
constexpr const bool sse3_enabled = true;
#else
constexpr const bool sse3_enabled                = false; ///< Indicates if sse3 is available
#endif

#ifdef __INTEL_COMPILER
constexpr const bool intel_compiler = true;
#else
constexpr const bool intel_compiler              = false; ///< Indicates if the project is compiled with intel
#endif

} //end of namespace etl
<|endoftext|>


<commit_before>#ifndef HORNET_JAVA_HH
#define HORNET_JAVA_HH

#include "hornet/zip.hh"

#include <jni.h>

#include <valarray>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
#include <mutex>
#include <stack>

namespace hornet {

struct method;
struct field;
struct klass;

enum class cp_tag {
    const_class,
    const_fieldref,
    const_methodref,
    const_interface_methodref,
    const_string,
    const_integer,
    const_float,
    const_long,
    const_double,
    const_name_and_type,
    const_utf8,
    const_method_handle,
    const_method_type,
    const_invoke_dynamic,
};

struct cp_info {
    cp_info(cp_tag tag) : tag(tag) { }

    virtual ~cp_info() { }

    cp_tag tag;

    union {
        uint16_t name_index;
        jint     value;
    };

    static inline
    std::shared_ptr<cp_info> const_class(int16_t name_index) {
        auto ret = std::make_shared<cp_info>(cp_tag::const_class);
        ret->name_index = name_index;
        return ret;
    }

    static inline
    std::shared_ptr<cp_info> const_integer(jint value) {
        auto ret = std::make_shared<cp_info>(cp_tag::const_integer);
        ret->value = value;
        return ret;
    }
};

struct const_utf8_info : cp_info {
    const_utf8_info() : cp_info(cp_tag::const_utf8) { }

    ~const_utf8_info() {
        delete[] bytes;
    }

    char *bytes;
};

class constant_pool {
public:
    explicit constant_pool(uint16_t size);
    ~constant_pool();

    void set(uint16_t idx, std::shared_ptr<cp_info> entry);

    cp_info *get(uint16_t idx);
    jint get_integer(uint16_t idx);
    const_utf8_info *get_utf8(uint16_t idx);

private:
    std::valarray<std::shared_ptr<cp_info>> _entries;
};

enum class attr_type {
    code,
    unknown
};

struct attr_info {
    attr_type type;

    attr_info(attr_type type) : type(type) {}
};

struct code_attr : attr_info {
    uint16_t max_locals;
    char*    code;
    uint32_t code_length;

    code_attr() : attr_info(attr_type::code) {}
};

struct unknown_attr : attr_info {
    unknown_attr() : attr_info(attr_type::unknown) {}
};

class class_file {
public:
    explicit class_file(void *data, size_t size);
    ~class_file();

    std::shared_ptr<klass> parse();
private:

    std::shared_ptr<constant_pool> read_constant_pool();
    std::shared_ptr<cp_info> read_const_class();
    void read_const_fieldref();
    void read_const_methodref();
    void read_const_interface_methodref();
    void read_const_string();
    std::shared_ptr<cp_info> read_const_integer();
    void read_const_float();
    void read_const_long();
    void read_const_double();
    void read_const_name_and_type();
    std::shared_ptr<cp_info> read_const_utf8();
    void read_const_method_handle();
    void read_const_method_type();
    void read_const_invoke_dynamic();

    std::shared_ptr<field> read_field_info(constant_pool &constant_pool);
    std::shared_ptr<method> read_method_info(klass* klass, constant_pool &constant_pool);
    std::unique_ptr<attr_info> read_attr_info(constant_pool &constant_pool);
    std::unique_ptr<code_attr> read_code_attribute(constant_pool &constant_pool);

    uint8_t  read_u1();
    uint16_t read_u2();
    uint32_t read_u4();
    uint64_t read_u8();

    size_t _offset;
    size_t _size;
    char *_data;
};

extern bool verbose_verifier;
bool verify_method(std::shared_ptr<method> method);
void verifier_stats();

class jar {
public:
    jar(std::string filename);
    ~jar();

    jar(const jar&) = delete;
    jar& operator=(const jar&) = delete;

    std::shared_ptr<klass> load_class(std::string class_name);

private:
    std::string _filename;
    hornet::zip* _zip;
};

class loader {
public:
    void register_jar(std::shared_ptr<jar> jar);
    std::shared_ptr<klass> load_class(const char *class_name);
private:
    std::shared_ptr<klass> try_to_load_class(const char *class_name);
    std::shared_ptr<klass> load_file(const char *file_name);
    std::vector<std::shared_ptr<jar>> _jars;
};

class system_loader {
public:
    static void init() {
        const char *java_home = getenv("JAVA_HOME");
        if (!java_home)
            java_home = "/usr/lib/jvm/java";

        get()->register_jar(std::make_shared<jar>(std::string(java_home) + "/jre/lib/rt.jar"));
    }
    static loader *get() {
        static loader loader;
        return &loader;
    }
};

inline loader *system_loader()
{
    return system_loader::get();
}

extern unsigned char opcode_length[];

static inline uint8_t read_opc_u1(char *p)
{
    return p[1];
}

static inline uint16_t read_opc_u2(char *p)
{
    return p[1] << 8 | p[2];
}

typedef uint64_t value_t;

struct frame {
    frame(uint16_t max_locals)
       : locals(max_locals), pc(0) {}

    std::valarray<value_t> locals;
    std::stack<value_t>    ostack;
    uint16_t               pc;
};

void interp(method* method, frame& frame);

}

#endif
<commit_msg>java: use std::vector instead of std::valarray<commit_after>#ifndef HORNET_JAVA_HH
#define HORNET_JAVA_HH

#include "hornet/zip.hh"

#include <jni.h>

#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
#include <mutex>
#include <stack>

namespace hornet {

struct method;
struct field;
struct klass;

enum class cp_tag {
    const_class,
    const_fieldref,
    const_methodref,
    const_interface_methodref,
    const_string,
    const_integer,
    const_float,
    const_long,
    const_double,
    const_name_and_type,
    const_utf8,
    const_method_handle,
    const_method_type,
    const_invoke_dynamic,
};

struct cp_info {
    cp_info(cp_tag tag) : tag(tag) { }

    virtual ~cp_info() { }

    cp_tag tag;

    union {
        uint16_t name_index;
        jint     value;
    };

    static inline
    std::shared_ptr<cp_info> const_class(int16_t name_index) {
        auto ret = std::make_shared<cp_info>(cp_tag::const_class);
        ret->name_index = name_index;
        return ret;
    }

    static inline
    std::shared_ptr<cp_info> const_integer(jint value) {
        auto ret = std::make_shared<cp_info>(cp_tag::const_integer);
        ret->value = value;
        return ret;
    }
};

struct const_utf8_info : cp_info {
    const_utf8_info() : cp_info(cp_tag::const_utf8) { }

    ~const_utf8_info() {
        delete[] bytes;
    }

    char *bytes;
};

class constant_pool {
public:
    explicit constant_pool(uint16_t size);
    ~constant_pool();

    void set(uint16_t idx, std::shared_ptr<cp_info> entry);

    cp_info *get(uint16_t idx);
    jint get_integer(uint16_t idx);
    const_utf8_info *get_utf8(uint16_t idx);

private:
    std::vector<std::shared_ptr<cp_info>> _entries;
};

enum class attr_type {
    code,
    unknown
};

struct attr_info {
    attr_type type;

    attr_info(attr_type type) : type(type) {}
};

struct code_attr : attr_info {
    uint16_t max_locals;
    char*    code;
    uint32_t code_length;

    code_attr() : attr_info(attr_type::code) {}
};

struct unknown_attr : attr_info {
    unknown_attr() : attr_info(attr_type::unknown) {}
};

class class_file {
public:
    explicit class_file(void *data, size_t size);
    ~class_file();

    std::shared_ptr<klass> parse();
private:

    std::shared_ptr<constant_pool> read_constant_pool();
    std::shared_ptr<cp_info> read_const_class();
    void read_const_fieldref();
    void read_const_methodref();
    void read_const_interface_methodref();
    void read_const_string();
    std::shared_ptr<cp_info> read_const_integer();
    void read_const_float();
    void read_const_long();
    void read_const_double();
    void read_const_name_and_type();
    std::shared_ptr<cp_info> read_const_utf8();
    void read_const_method_handle();
    void read_const_method_type();
    void read_const_invoke_dynamic();

    std::shared_ptr<field> read_field_info(constant_pool &constant_pool);
    std::shared_ptr<method> read_method_info(klass* klass, constant_pool &constant_pool);
    std::unique_ptr<attr_info> read_attr_info(constant_pool &constant_pool);
    std::unique_ptr<code_attr> read_code_attribute(constant_pool &constant_pool);

    uint8_t  read_u1();
    uint16_t read_u2();
    uint32_t read_u4();
    uint64_t read_u8();

    size_t _offset;
    size_t _size;
    char *_data;
};

extern bool verbose_verifier;
bool verify_method(std::shared_ptr<method> method);
void verifier_stats();

class jar {
public:
    jar(std::string filename);
    ~jar();

    jar(const jar&) = delete;
    jar& operator=(const jar&) = delete;

    std::shared_ptr<klass> load_class(std::string class_name);

private:
    std::string _filename;
    hornet::zip* _zip;
};

class loader {
public:
    void register_jar(std::shared_ptr<jar> jar);
    std::shared_ptr<klass> load_class(const char *class_name);
private:
    std::shared_ptr<klass> try_to_load_class(const char *class_name);
    std::shared_ptr<klass> load_file(const char *file_name);
    std::vector<std::shared_ptr<jar>> _jars;
};

class system_loader {
public:
    static void init() {
        const char *java_home = getenv("JAVA_HOME");
        if (!java_home)
            java_home = "/usr/lib/jvm/java";

        get()->register_jar(std::make_shared<jar>(std::string(java_home) + "/jre/lib/rt.jar"));
    }
    static loader *get() {
        static loader loader;
        return &loader;
    }
};

inline loader *system_loader()
{
    return system_loader::get();
}

extern unsigned char opcode_length[];

static inline uint8_t read_opc_u1(char *p)
{
    return p[1];
}

static inline uint16_t read_opc_u2(char *p)
{
    return p[1] << 8 | p[2];
}

typedef uint64_t value_t;

struct frame {
    frame(uint16_t max_locals)
       : locals(max_locals), pc(0) {}

    std::vector<value_t> locals;
    std::stack<value_t>    ostack;
    uint16_t               pc;
};

void interp(method* method, frame& frame);

}

#endif
<|endoftext|>