<commit_before>/*
    SWARM

    Copyright (C) 2012-2020 Torbjorn Rognes and Frederic Mahe

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
    Department of Informatics, University of Oslo,
    PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/

#include "swarm.h"

struct bucket
{
  uint64_t hash;
  unsigned int seqno_first;
  unsigned int seqno_last;
  uint64_t mass;
  unsigned int size;
  unsigned int singletons;
};

int derep_compare(const void * a, const void * b);

int derep_compare(const void * a, const void * b)
{
  const auto * x = static_cast<const struct bucket *>(a);
  const auto * y = static_cast<const struct bucket *>(b);
  auto status {0};

  /* highest abundance first, otherwise keep order */

  if (x->mass < y->mass) {
    status = +1;
  }
  else if (x->mass > y->mass) {
    status = -1;
  }
  else {
    if (x->seqno_first < y->seqno_first) {
      status = -1;
    }
    else if (x->seqno_first > y->seqno_first) {
      status = +1;
    }
    else {
      status = 0;
    }
  }

  return status;
}

void dereplicate()
{
  /* adjust size of hash table for 2/3 fill rate */
  uint64_t dbsequencecount = db_getsequencecount();
  uint64_t hashtablesize = 1;
  while (100 * dbsequencecount > 70 * hashtablesize) {
    hashtablesize <<= 1;
  }
  uint64_t derep_hash_mask = hashtablesize - 1;

  auto * hashtable =
    static_cast<struct bucket *>(xmalloc(sizeof(bucket) * hashtablesize));

  memset(hashtable, 0, sizeof(bucket) * hashtablesize);

  uint64_t swarmcount = 0;
  uint64_t maxmass = 0;
  unsigned int maxsize = 0;

  /* alloc and init table of links to other sequences in cluster */
  auto * nextseqtab = static_cast<unsigned int *>
    (xmalloc(sizeof(unsigned int) * dbsequencecount));
  memset(nextseqtab, 0, sizeof(unsigned int) * dbsequencecount);

  progress_init("Dereplicating:    ", dbsequencecount);

  for(auto i = 0U; i < dbsequencecount; i++)
    {
      unsigned int seqlen = db_getsequencelen(i);
      char * seq = db_getsequence(i);

      /*
        Find free bucket or bucket for identical sequence.
        Make sure sequences are exactly identical
        in case of any hash collision.
        With 64-bit hashes, there is about 50% chance of a
        collision when the number of sequences is about 5e9.
      */

      uint64_t hash = zobrist_hash(reinterpret_cast<unsigned char *>(seq),
                                   seqlen);

      uint64_t j = hash & derep_hash_mask;
      struct bucket * bp = hashtable + j;

      while ((bp->mass) &&
             ((bp->hash != hash) ||
              (seqlen != db_getsequencelen(bp->seqno_first)) ||
              (memcmp(seq,
                      db_getsequence(bp->seqno_first),
                      nt_bytelength(seqlen)))))
        {
          bp++;
          j++;
          if (bp >= hashtable + hashtablesize)
            {
              bp = hashtable;
              j = 0;
            }
        }

      uint64_t ab = db_getabundance(i);

      if (bp->mass)
        {
          /* at least one identical sequence already */
          nextseqtab[bp->seqno_last] = i;
        }
      else
        {
          /* no identical sequences yet, start a new cluster */
          swarmcount++;
          bp->hash = hash;
          bp->seqno_first = i;
          bp->size = 0;
          bp->singletons = 0;
        }

      bp->size++;
      bp->seqno_last = i;
      bp->mass += ab;

      if (ab == 1) {
        bp->singletons++;
      }

      if (bp->mass > maxmass) {
        maxmass = bp->mass;
      }

      if (bp->size > maxsize) {
        maxsize = bp->size;
      }

      progress_update(i);
    }
  progress_done();

  progress_init("Sorting:          ", 1);
  qsort(hashtable, hashtablesize, sizeof(bucket), derep_compare);
  progress_done();

  /* dump swarms */

  progress_init("Writing swarms:   ", swarmcount);

  if (opt_mothur) {
    fprintf(outfile, "swarm_%" PRId64 "\t%" PRIu64, opt_differences, swarmcount);
  }

  for(auto i = 0U; i < swarmcount; i++)
    {
      unsigned int seed = hashtable[i].seqno_first;
      if (opt_mothur) {
        fputc('\t', outfile);
      }
      fprint_id(outfile, seed);
      unsigned int a = nextseqtab[seed];

      while (a)
        {
          if (opt_mothur) {
            fputc(',', outfile);
          }
          else {
            fputc(sepchar, outfile);
          }
          fprint_id(outfile, a);
          a = nextseqtab[a];
        }

      if (!opt_mothur) {
        fputc('\n', outfile);
      }

      progress_update(i+1);
    }

  if (opt_mothur) {
    fputc('\n', outfile);
  }

  progress_done();

  /* dump seeds in fasta format with sum of abundances */

  if (opt_seeds)
    {
      progress_init("Writing seeds:    ", swarmcount);
      for(auto i = 0U; i < swarmcount; i++)
        {
          unsigned int seed = hashtable[i].seqno_first;
          fprintf(fp_seeds, ">");
          fprint_id_with_new_abundance(fp_seeds, seed, hashtable[i].mass);
          fprintf(fp_seeds, "\n");
          db_fprintseq(fp_seeds, seed, 0);
          progress_update(i+1);
        }
      progress_done();
    }

  /* output swarm in uclust format */

  if (uclustfile)
    {
      progress_init("Writing UCLUST:   ", swarmcount);

      for(auto swarmid = 0U; swarmid < swarmcount; swarmid++)
        {
          struct bucket * bp = hashtable + swarmid;

          unsigned int seed = bp->seqno_first;

          fprintf(uclustfile, "C\t%u\t%u\t*\t*\t*\t*\t*\t",
                  swarmid,
                  bp->size);
          fprint_id(uclustfile, seed);
          fprintf(uclustfile, "\t*\n");

          fprintf(uclustfile, "S\t%u\t%u\t*\t*\t*\t*\t*\t",
                  swarmid,
                  db_getsequencelen(seed));
          fprint_id(uclustfile, seed);
          fprintf(uclustfile, "\t*\n");

          unsigned int a = nextseqtab[seed];

          while (a)
            {
              fprintf(uclustfile,
                      "H\t%u\t%u\t%.1f\t+\t0\t0\t%s\t",
                      swarmid,
                      db_getsequencelen(a),
                      100.0,
                      "=");
              fprint_id(uclustfile, a);
              fprintf(uclustfile, "\t");
              fprint_id(uclustfile, seed);
              fprintf(uclustfile, "\n");
              a = nextseqtab[a];
            }

          progress_update(swarmid+1);
        }
      progress_done();
    }

  /* output internal structure to file */

  if (opt_internal_structure)
    {
      progress_init("Writing structure:", swarmcount);

      for(auto i = 0UL; i < swarmcount; i++)
        {
          struct bucket * sp = hashtable + i;
          uint64_t seed = sp->seqno_first;
          unsigned int a = nextseqtab[seed];
          while (a)
            {
              fprint_id_noabundance(internal_structure_file, seed);
              fprintf(internal_structure_file, "\t");
              fprint_id_noabundance(internal_structure_file, a);
              fprintf(internal_structure_file, "\t%d\t%" PRIu64 "\t%d\n", 0, i+1, 0);
              a = nextseqtab[a];
            }
          progress_update(i);
        }
      progress_done();
    }

  /* output statistics to file */

  if (statsfile)
    {
      progress_init("Writing stats:    ", swarmcount);
      for(auto i = 0ULL; i < swarmcount; i++)
        {
          struct bucket * sp = hashtable + i;
          fprintf(statsfile, "%u\t%" PRIu64 "\t", sp->size, sp->mass);
          fprint_id_noabundance(statsfile, sp->seqno_first);
          fprintf(statsfile, "\t%" PRIu64 "\t%u\t%u\t%u\n",
                  db_getabundance(sp->seqno_first),
                  sp->singletons, 0U, 0U);
          progress_update(i);
        }
      progress_done();
    }

  fprintf(logfile, "\n");
  fprintf(logfile, "Number of swarms:  %" PRIu64 "\n", swarmcount);
  fprintf(logfile, "Largest swarm:     %u\n", maxsize);
  fprintf(logfile, "Heaviest swarm:    %" PRIu64 "\n", maxmass);

  xfree(nextseqtab);
  xfree(hashtable);
}
<commit_msg>function 'memcmp' is called without explicitly comparing result<commit_after>/*
    SWARM

    Copyright (C) 2012-2020 Torbjorn Rognes and Frederic Mahe

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
    Department of Informatics, University of Oslo,
    PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/

#include "swarm.h"

struct bucket
{
  uint64_t hash;
  unsigned int seqno_first;
  unsigned int seqno_last;
  uint64_t mass;
  unsigned int size;
  unsigned int singletons;
};

int derep_compare(const void * a, const void * b);

int derep_compare(const void * a, const void * b)
{
  const auto * x = static_cast<const struct bucket *>(a);
  const auto * y = static_cast<const struct bucket *>(b);
  auto status {0};

  /* highest abundance first, otherwise keep order */

  if (x->mass < y->mass) {
    status = +1;
  }
  else if (x->mass > y->mass) {
    status = -1;
  }
  else {
    if (x->seqno_first < y->seqno_first) {
      status = -1;
    }
    else if (x->seqno_first > y->seqno_first) {
      status = +1;
    }
    else {
      status = 0;
    }
  }

  return status;
}

void dereplicate()
{
  /* adjust size of hash table for 2/3 fill rate */
  uint64_t dbsequencecount = db_getsequencecount();
  uint64_t hashtablesize = 1;
  while (100 * dbsequencecount > 70 * hashtablesize) {
    hashtablesize <<= 1;
  }
  uint64_t derep_hash_mask = hashtablesize - 1;

  auto * hashtable =
    static_cast<struct bucket *>(xmalloc(sizeof(bucket) * hashtablesize));

  memset(hashtable, 0, sizeof(bucket) * hashtablesize);

  uint64_t swarmcount = 0;
  uint64_t maxmass = 0;
  unsigned int maxsize = 0;

  /* alloc and init table of links to other sequences in cluster */
  auto * nextseqtab = static_cast<unsigned int *>
    (xmalloc(sizeof(unsigned int) * dbsequencecount));
  memset(nextseqtab, 0, sizeof(unsigned int) * dbsequencecount);

  progress_init("Dereplicating:    ", dbsequencecount);

  for(auto i = 0U; i < dbsequencecount; i++)
    {
      unsigned int seqlen = db_getsequencelen(i);
      char * seq = db_getsequence(i);

      /*
        Find free bucket or bucket for identical sequence.
        Make sure sequences are exactly identical
        in case of any hash collision.
        With 64-bit hashes, there is about 50% chance of a
        collision when the number of sequences is about 5e9.
      */

      uint64_t hash = zobrist_hash(reinterpret_cast<unsigned char *>(seq),
                                   seqlen);

      uint64_t j = hash & derep_hash_mask;
      struct bucket * bp = hashtable + j;

      while ((bp->mass) &&
             ((bp->hash != hash) ||
              (seqlen != db_getsequencelen(bp->seqno_first)) ||
              (memcmp(seq,
                      db_getsequence(bp->seqno_first),
                      nt_bytelength(seqlen)) != 0)))
        {
          bp++;
          j++;
          if (bp >= hashtable + hashtablesize)
            {
              bp = hashtable;
              j = 0;
            }
        }

      uint64_t ab = db_getabundance(i);

      if (bp->mass)
        {
          /* at least one identical sequence already */
          nextseqtab[bp->seqno_last] = i;
        }
      else
        {
          /* no identical sequences yet, start a new cluster */
          swarmcount++;
          bp->hash = hash;
          bp->seqno_first = i;
          bp->size = 0;
          bp->singletons = 0;
        }

      bp->size++;
      bp->seqno_last = i;
      bp->mass += ab;

      if (ab == 1) {
        bp->singletons++;
      }

      if (bp->mass > maxmass) {
        maxmass = bp->mass;
      }

      if (bp->size > maxsize) {
        maxsize = bp->size;
      }

      progress_update(i);
    }
  progress_done();

  progress_init("Sorting:          ", 1);
  qsort(hashtable, hashtablesize, sizeof(bucket), derep_compare);
  progress_done();

  /* dump swarms */

  progress_init("Writing swarms:   ", swarmcount);

  if (opt_mothur) {
    fprintf(outfile, "swarm_%" PRId64 "\t%" PRIu64, opt_differences, swarmcount);
  }

  for(auto i = 0U; i < swarmcount; i++)
    {
      unsigned int seed = hashtable[i].seqno_first;
      if (opt_mothur) {
        fputc('\t', outfile);
      }
      fprint_id(outfile, seed);
      unsigned int a = nextseqtab[seed];

      while (a)
        {
          if (opt_mothur) {
            fputc(',', outfile);
          }
          else {
            fputc(sepchar, outfile);
          }
          fprint_id(outfile, a);
          a = nextseqtab[a];
        }

      if (!opt_mothur) {
        fputc('\n', outfile);
      }

      progress_update(i+1);
    }

  if (opt_mothur) {
    fputc('\n', outfile);
  }

  progress_done();

  /* dump seeds in fasta format with sum of abundances */

  if (opt_seeds)
    {
      progress_init("Writing seeds:    ", swarmcount);
      for(auto i = 0U; i < swarmcount; i++)
        {
          unsigned int seed = hashtable[i].seqno_first;
          fprintf(fp_seeds, ">");
          fprint_id_with_new_abundance(fp_seeds, seed, hashtable[i].mass);
          fprintf(fp_seeds, "\n");
          db_fprintseq(fp_seeds, seed, 0);
          progress_update(i+1);
        }
      progress_done();
    }

  /* output swarm in uclust format */

  if (uclustfile)
    {
      progress_init("Writing UCLUST:   ", swarmcount);

      for(auto swarmid = 0U; swarmid < swarmcount; swarmid++)
        {
          struct bucket * bp = hashtable + swarmid;

          unsigned int seed = bp->seqno_first;

          fprintf(uclustfile, "C\t%u\t%u\t*\t*\t*\t*\t*\t",
                  swarmid,
                  bp->size);
          fprint_id(uclustfile, seed);
          fprintf(uclustfile, "\t*\n");

          fprintf(uclustfile, "S\t%u\t%u\t*\t*\t*\t*\t*\t",
                  swarmid,
                  db_getsequencelen(seed));
          fprint_id(uclustfile, seed);
          fprintf(uclustfile, "\t*\n");

          unsigned int a = nextseqtab[seed];

          while (a)
            {
              fprintf(uclustfile,
                      "H\t%u\t%u\t%.1f\t+\t0\t0\t%s\t",
                      swarmid,
                      db_getsequencelen(a),
                      100.0,
                      "=");
              fprint_id(uclustfile, a);
              fprintf(uclustfile, "\t");
              fprint_id(uclustfile, seed);
              fprintf(uclustfile, "\n");
              a = nextseqtab[a];
            }

          progress_update(swarmid+1);
        }
      progress_done();
    }

  /* output internal structure to file */

  if (opt_internal_structure)
    {
      progress_init("Writing structure:", swarmcount);

      for(auto i = 0UL; i < swarmcount; i++)
        {
          struct bucket * sp = hashtable + i;
          uint64_t seed = sp->seqno_first;
          unsigned int a = nextseqtab[seed];
          while (a)
            {
              fprint_id_noabundance(internal_structure_file, seed);
              fprintf(internal_structure_file, "\t");
              fprint_id_noabundance(internal_structure_file, a);
              fprintf(internal_structure_file, "\t%d\t%" PRIu64 "\t%d\n", 0, i+1, 0);
              a = nextseqtab[a];
            }
          progress_update(i);
        }
      progress_done();
    }

  /* output statistics to file */

  if (statsfile)
    {
      progress_init("Writing stats:    ", swarmcount);
      for(auto i = 0ULL; i < swarmcount; i++)
        {
          struct bucket * sp = hashtable + i;
          fprintf(statsfile, "%u\t%" PRIu64 "\t", sp->size, sp->mass);
          fprint_id_noabundance(statsfile, sp->seqno_first);
          fprintf(statsfile, "\t%" PRIu64 "\t%u\t%u\t%u\n",
                  db_getabundance(sp->seqno_first),
                  sp->singletons, 0U, 0U);
          progress_update(i);
        }
      progress_done();
    }

  fprintf(logfile, "\n");
  fprintf(logfile, "Number of swarms:  %" PRIu64 "\n", swarmcount);
  fprintf(logfile, "Largest swarm:     %u\n", maxsize);
  fprintf(logfile, "Heaviest swarm:    %" PRIu64 "\n", maxmass);

  xfree(nextseqtab);
  xfree(hashtable);
}
<|endoftext|>


<commit_before>#include "FluidProperties3EqnMaterial.h"
#include "SinglePhaseFluidProperties.h"
#include "Numerics.h"

template <>
InputParameters
validParams<FluidProperties3EqnMaterial>()
{
  InputParameters params = validParams<Material>();

  params.addRequiredCoupledVar("area", "Cross-sectional area");
  params.addRequiredCoupledVar("rhoA", "Conserved density");
  params.addRequiredCoupledVar("rhouA", "Conserved momentum");
  params.addRequiredCoupledVar("rhoEA", "Conserved total energy");

  params.addRequiredParam<UserObjectName>("fp", "The name of the user object for fluid properties");

  return params;
}

FluidProperties3EqnMaterial::FluidProperties3EqnMaterial(const InputParameters & parameters)
  : DerivativeMaterialInterfaceRelap<Material>(parameters),
    _area(coupledValue("area")),
    _rhoA(coupledValue("rhoA")),
    _rhouA(coupledValue("rhouA")),
    _rhoEA(coupledValue("rhoEA")),

    _rho(declareProperty<Real>("rho")),
    _drho_drhoA(declarePropertyDerivativeRelap<Real>("rho", "rhoA")),

    _v(declareProperty<Real>("specific_volume")),
    _dv_drhoA(declarePropertyDerivativeRelap<Real>("specific_volume", "rhoA")),

    _vel(declareProperty<Real>("vel")),
    _dvel_drhoA(declarePropertyDerivativeRelap<Real>("vel", "rhoA")),
    _dvel_drhouA(declarePropertyDerivativeRelap<Real>("vel", "rhouA")),

    _e(declareProperty<Real>("specific_internal_energy")),
    _de_drhoA(declarePropertyDerivativeRelap<Real>("specific_internal_energy", "rhoA")),
    _de_drhouA(declarePropertyDerivativeRelap<Real>("specific_internal_energy", "rhouA")),
    _de_drhoEA(declarePropertyDerivativeRelap<Real>("specific_internal_energy", "rhoEA")),

    _p(declareProperty<Real>("pressure")),
    _dp_drhoA(declarePropertyDerivativeRelap<Real>("pressure", "rhoA")),
    _dp_drhouA(declarePropertyDerivativeRelap<Real>("pressure", "rhouA")),
    _dp_drhoEA(declarePropertyDerivativeRelap<Real>("pressure", "rhoEA")),

    _T(declareProperty<Real>("temperature")),
    _dT_drhoA(declarePropertyDerivativeRelap<Real>("temperature", "rhoA")),
    _dT_drhouA(declarePropertyDerivativeRelap<Real>("temperature", "rhouA")),
    _dT_drhoEA(declarePropertyDerivativeRelap<Real>("temperature", "rhoEA")),

    _c(declareProperty<Real>("c")),

    _cp(declareProperty<Real>("cp")),

    _cv(declareProperty<Real>("cv")),

    _mu(declareProperty<Real>("mu")),

    _k(declareProperty<Real>("k")),

    _fp(getUserObject<SinglePhaseFluidProperties>("fp"))
{
}

void
FluidProperties3EqnMaterial::computeQpProperties()
{
  _rho[_qp] = _rhoA[_qp] / _area[_qp];
  _drho_drhoA[_qp] = 1.0 / _area[_qp];

  _v[_qp] = 1.0 / _rho[_qp];
  _dv_drhoA[_qp] = dv_darhoA(_area[_qp], _rhoA[_qp]);

  _vel[_qp] = _rhouA[_qp] / _rhoA[_qp];
  _dvel_drhoA[_qp] = -_rhouA[_qp] / (_rhoA[_qp] * _rhoA[_qp]);
  _dvel_drhouA[_qp] = 1.0 / _rhoA[_qp];

  _e[_qp] = (_rhoEA[_qp] - 0.5 * _rhouA[_qp] * _rhouA[_qp] / _rhoA[_qp]) / _rhoA[_qp];
  _de_drhoA[_qp] = de_darhoA(_rhoA[_qp], _rhouA[_qp], _rhoEA[_qp]);
  _de_drhouA[_qp] = de_darhouA(_rhoA[_qp], _rhouA[_qp]);
  _de_drhoEA[_qp] = de_darhoEA(_rhoA[_qp]);

  _p[_qp] = _fp.pressure(_v[_qp], _e[_qp]);
  _T[_qp] = _fp.temperature(_v[_qp], _e[_qp]);

  Real dp_dv, dp_de;
  Real dT_dv, dT_de;
  _fp.dp_duv(_v[_qp], _e[_qp], dp_dv, dp_de, dT_dv, dT_de);

  _dp_drhoA[_qp] = dp_dv * _dv_drhoA[_qp] + dp_de * _de_drhoA[_qp];
  _dp_drhouA[_qp] = dp_de * _de_drhouA[_qp];

  _dT_drhoA[_qp] = dT_dv * _dv_drhoA[_qp] + dT_de * _de_drhoA[_qp];
  _dT_drhouA[_qp] = dT_de * _de_drhouA[_qp];

  _dp_drhoEA[_qp] = dp_de * _de_drhoEA[_qp];
  _dT_drhoEA[_qp] = dT_de * _de_drhoEA[_qp];

  _c[_qp] = _fp.c(_v[_qp], _e[_qp]);
  _cp[_qp] = _fp.cp(_v[_qp], _e[_qp]);
  _cv[_qp] = _fp.cv(_v[_qp], _e[_qp]);
  _mu[_qp] = _fp.mu(_v[_qp], _e[_qp]);
  _k[_qp] = _fp.k(_v[_qp], _e[_qp]);
}
<commit_msg>Applied naming conventions to pressure<commit_after>#include "FluidProperties3EqnMaterial.h"
#include "SinglePhaseFluidProperties.h"
#include "Numerics.h"

template <>
InputParameters
validParams<FluidProperties3EqnMaterial>()
{
  InputParameters params = validParams<Material>();

  params.addRequiredCoupledVar("area", "Cross-sectional area");
  params.addRequiredCoupledVar("rhoA", "Conserved density");
  params.addRequiredCoupledVar("rhouA", "Conserved momentum");
  params.addRequiredCoupledVar("rhoEA", "Conserved total energy");

  params.addRequiredParam<UserObjectName>("fp", "The name of the user object for fluid properties");

  return params;
}

FluidProperties3EqnMaterial::FluidProperties3EqnMaterial(const InputParameters & parameters)
  : DerivativeMaterialInterfaceRelap<Material>(parameters),
    _area(coupledValue("area")),
    _rhoA(coupledValue("rhoA")),
    _rhouA(coupledValue("rhouA")),
    _rhoEA(coupledValue("rhoEA")),

    _rho(declareProperty<Real>("rho")),
    _drho_drhoA(declarePropertyDerivativeRelap<Real>("rho", "rhoA")),

    _v(declareProperty<Real>("v")),
    _dv_drhoA(declarePropertyDerivativeRelap<Real>("v", "rhoA")),

    _vel(declareProperty<Real>("vel")),
    _dvel_drhoA(declarePropertyDerivativeRelap<Real>("vel", "rhoA")),
    _dvel_drhouA(declarePropertyDerivativeRelap<Real>("vel", "rhouA")),

    _e(declareProperty<Real>("e")),
    _de_drhoA(declarePropertyDerivativeRelap<Real>("e", "rhoA")),
    _de_drhouA(declarePropertyDerivativeRelap<Real>("e", "rhouA")),
    _de_drhoEA(declarePropertyDerivativeRelap<Real>("e", "rhoEA")),

    _p(declareProperty<Real>("p")),
    _dp_drhoA(declarePropertyDerivativeRelap<Real>("p", "rhoA")),
    _dp_drhouA(declarePropertyDerivativeRelap<Real>("p", "rhouA")),
    _dp_drhoEA(declarePropertyDerivativeRelap<Real>("p", "rhoEA")),

    _T(declareProperty<Real>("temperature")),
    _dT_drhoA(declarePropertyDerivativeRelap<Real>("temperature", "rhoA")),
    _dT_drhouA(declarePropertyDerivativeRelap<Real>("temperature", "rhouA")),
    _dT_drhoEA(declarePropertyDerivativeRelap<Real>("temperature", "rhoEA")),

    _c(declareProperty<Real>("c")),

    _cp(declareProperty<Real>("cp")),

    _cv(declareProperty<Real>("cv")),

    _mu(declareProperty<Real>("mu")),

    _k(declareProperty<Real>("k")),

    _fp(getUserObject<SinglePhaseFluidProperties>("fp"))
{
}

void
FluidProperties3EqnMaterial::computeQpProperties()
{
  _rho[_qp] = _rhoA[_qp] / _area[_qp];
  _drho_drhoA[_qp] = 1.0 / _area[_qp];

  _v[_qp] = 1.0 / _rho[_qp];
  _dv_drhoA[_qp] = dv_darhoA(_area[_qp], _rhoA[_qp]);

  _vel[_qp] = _rhouA[_qp] / _rhoA[_qp];
  _dvel_drhoA[_qp] = -_rhouA[_qp] / (_rhoA[_qp] * _rhoA[_qp]);
  _dvel_drhouA[_qp] = 1.0 / _rhoA[_qp];

  _e[_qp] = (_rhoEA[_qp] - 0.5 * _rhouA[_qp] * _rhouA[_qp] / _rhoA[_qp]) / _rhoA[_qp];
  _de_drhoA[_qp] = de_darhoA(_rhoA[_qp], _rhouA[_qp], _rhoEA[_qp]);
  _de_drhouA[_qp] = de_darhouA(_rhoA[_qp], _rhouA[_qp]);
  _de_drhoEA[_qp] = de_darhoEA(_rhoA[_qp]);

  _p[_qp] = _fp.pressure(_v[_qp], _e[_qp]);
  _T[_qp] = _fp.temperature(_v[_qp], _e[_qp]);

  Real dp_dv, dp_de;
  Real dT_dv, dT_de;
  _fp.dp_duv(_v[_qp], _e[_qp], dp_dv, dp_de, dT_dv, dT_de);

  _dp_drhoA[_qp] = dp_dv * _dv_drhoA[_qp] + dp_de * _de_drhoA[_qp];
  _dp_drhouA[_qp] = dp_de * _de_drhouA[_qp];

  _dT_drhoA[_qp] = dT_dv * _dv_drhoA[_qp] + dT_de * _de_drhoA[_qp];
  _dT_drhouA[_qp] = dT_de * _de_drhouA[_qp];

  _dp_drhoEA[_qp] = dp_de * _de_drhoEA[_qp];
  _dT_drhoEA[_qp] = dT_de * _de_drhoEA[_qp];

  _c[_qp] = _fp.c(_v[_qp], _e[_qp]);
  _cp[_qp] = _fp.cp(_v[_qp], _e[_qp]);
  _cv[_qp] = _fp.cv(_v[_qp], _e[_qp]);
  _mu[_qp] = _fp.mu(_v[_qp], _e[_qp]);
  _k[_qp] = _fp.k(_v[_qp], _e[_qp]);
}
<|endoftext|>


<commit_before>#include "draw.hpp"

#include <algorithm>
#include <iostream>
#include <sstream>

#include "args.hpp"
#include "config.hpp"
#include "task.hpp"
#include "todolist.hpp"
#include "win.hpp"

using std::string;
using std::stringstream;

// ===================|
// internal functions |
// ===================|
void drawText(string text, int x, int y);

WINDOW* createWindow(int startX, int startY, int width, int height);
void setCurrentWindow(WINDOW *curWin);

std::string buildTitle(TodoList *list);

void drawTitle(TodoList* list);
void drawControls();
void drawTasks(TodoList* list, unsigned selected);

void inverseOn();
void inverseOff();
void colorOn(int pair);
void colorOff(int pair);
void colorMarkOn(string mark);
void colorMarkOff(string mark);

// ===================|
// internal variables |
// ===================|
WINDOW *taskWindow;
WINDOW *inputWindow;
WINDOW *controlWindow;
WINDOW *titleWindow;
WINDOW *taskWindowBorder;
WINDOW *inputWindowBorder;
WINDOW *controlWindowBorder;
WINDOW *currentWindow;

Win *titleWin;

int startX;
int startY;
int width;
int height;

unsigned xpos;
unsigned ypos;
unsigned startTask = 0;
unsigned endTask = 0;
unsigned int listOff = 0;

bool colors = false;

/////////////////////////////////////////
// start curses mode and create windows
void Draw::init()
{
    std::cout << "\033]0;" << "todo" << "\7" << std::flush;
    initscr();
    raw();

    use_default_colors();
    if (useColors() && has_colors()){
        start_color();
        init_pair(TITLE_COLOR_PAIR, TITLE_FOREGROUND, TITLE_BACKGROUND);
        init_pair(GUTTER_COLOR_PAIR, GUTTER_FOREGROUND, GUTTER_BACKGROUND);
        init_pair(SELECT_COLOR_PAIR, SELECT_FOREGROUND, SELECT_BACKGROUND);
        init_pair(BORDER_COLOR_PAIR, BORDER_FOREGROUND, BORDER_BACKGROUND);
        init_pair(MARK_COLOR_PAIR, MARK_FOREGROUND, MARK_BACKGROUND);
        init_pair(MARK_COLOR_PAIR_DONE, MARK_FOREGROUND_DONE,
                  MARK_BACKGROUND_DONE);
        colors = true;
    }
    Win::setColors(colors);

    mouseinterval(0);
    keypad(stdscr, true);
    noecho();

    clear();
    refresh();

    curs_set(0);

    startX = listStartX;
    startY = listStartY;
    width = COLS - startX - 2;
    height = LINES * listHeight;
    taskWindowBorder = createWindow(startX, startY, width, height);
    taskWindow = createWindow(startX + 1, startY + 1,
                              width - 2, height - 2);

    int inHeight = inputHeight * LINES;
    inHeight = std::max(inHeight, 4);
    inputWindowBorder = createWindow(inputStartX, inputStartY,
                                     COLS - inputStartX - 2, inHeight);
    inputWindow = createWindow(inputStartX + 1, inputStartY + 1,
                               COLS - inputStartX - 4, inHeight - 2);

    controlWindowBorder = createWindow(inputStartX, inputStartY,
                                       COLS - inputStartX - 2, inHeight);
    controlWindow = createWindow(inputStartX + 1, inputStartY + 1,
                                 COLS - inputStartX - 4, inHeight - 2);

    titleWindow = createWindow(0, 0, COLS, titleHeight);

    setCurrentWindow(taskWindow);

    titleWin = new Win(0, 0, COLS, titleHeight, false);
}

//////////////////////
// main draw function
void Draw::draw(TodoList *list, unsigned selected)
{
    werase(inputWindow);
    werase(inputWindowBorder);

    drawTitle(list);
    drawControls();
    drawTasks(list, selected);
}

////////////////////////
// act on mouse events
void Draw::mouse(MEVENT event, TodoList *list,
                 unsigned &selected, bool button)
{
    int x = event.x;
    int y = event.y;
    if (wmouse_trafo(taskWindow, &y, &x, false)){
        unsigned pos = listOff + y - 1;
        if (pos < list->size()){
            if (!button){
                selected = pos;
            } else{
                list->at(pos).toggleComplete();
            }
        }
    }
}

///////////////////////////////////////
// get an input string for a new task
string Draw::getInput()
{
    echo();

    werase(controlWindow);
    werase(controlWindowBorder);

    setCurrentWindow(inputWindowBorder);
    if (colors){
        colorOn(BORDER_COLOR_PAIR);
    }
    box(inputWindowBorder, 0, 0);

    inverseOn();
    drawText("[New task]", 0, 0);
    inverseOff();

    if (colors){
        colorOff(BORDER_COLOR_PAIR);
    }

    setCurrentWindow(inputWindow);
    wrefresh(inputWindowBorder);
    wrefresh(inputWindow);
    curs_set(1);

    char tmp[charBufferSize];
    mvwgetnstr(inputWindow, 0, 0, tmp, charBufferSize);

    setCurrentWindow(taskWindow);
    box(inputWindowBorder, ' ', ' ');
    werase(inputWindow);
    werase(inputWindowBorder);
    curs_set(0);
    noecho();

    return std::string(tmp);
}

void drawTitle(TodoList* list)
{
    titleWin->clear();
    titleWin->inverse();
    titleWin->color(TITLE_COLOR_PAIR);
    titleWin->print(buildTitle(list), 0, 0);
    titleWin->colorOff(TITLE_COLOR_PAIR);
    titleWin->inverseOff();
    titleWin->color(BORDER_COLOR_PAIR, true);
    titleWin->draw();
}

// draw the control panel
void drawControls()
{
    setCurrentWindow(controlWindow);
    wmove(controlWindow, 0, 0);

    stringstream line;

    line << "[" << ((char) EXIT_KEY) << "]";
    wprintw(controlWindow, line.str().c_str());
    wprintw(controlWindow, " quit          ");
    line.str("");

    line << "[Space]";
    wprintw(controlWindow, line.str().c_str());
    wprintw(controlWindow, " new task          ");
    line.str("");

    line << "[" << ((char) MOVE_UP_KEY) << "]";
    wprintw(controlWindow, line.str().c_str());
    wprintw(controlWindow, " move task up  ");
    line.str("");

    wmove(controlWindow, 1, 0);

    line << "[" << ((char) REMOVE_KEY) << "]";
    wprintw(controlWindow, line.str().c_str());
    wprintw(controlWindow, " delete task   ");
    line.str("");

    line << "[Return]";
    wprintw(controlWindow, line.str().c_str());
    wprintw(controlWindow, " mark task done   ");
    line.str("");

    line << "[" << ((char) MOVE_DOWN_KEY) << "]";
    wprintw(controlWindow, line.str().c_str());
    wprintw(controlWindow, " move task down  ");
    line.str("");

    setCurrentWindow(controlWindowBorder);
    if (colors){
        colorOn(BORDER_COLOR_PAIR);
    }
    box(controlWindowBorder, 0, 0);

    inverseOn();
    drawText("[Controls]", 0, 0);
    inverseOff();

    if (colors){
        colorOff(BORDER_COLOR_PAIR);
    }

    wrefresh(controlWindowBorder);
    wrefresh(controlWindow);
}

void drawTasks(TodoList* list, unsigned selected)
{
    auto tasks = list->tasks();

    setCurrentWindow(taskWindowBorder);
    if (colors){
        colorOn(BORDER_COLOR_PAIR);
    }
    box(taskWindowBorder, 0, 0);

    inverseOn();
    drawText("[Tasks]", 0, 0);
    inverseOff();

    if (colors){
        colorOff(BORDER_COLOR_PAIR);
    }

    setCurrentWindow(taskWindow);
    werase(taskWindow);

    if (tasks && tasks->size() != 0){
        xpos = 1;
        ypos = 1;

        unsigned numTasks = height - 2;
        endTask = tasks->size();
        if (endTask > numTasks){
            endTask = numTasks;
        }

        if (numTasks <= tasks->size()){
            while (selected > endTask + listOff - 2 && selected != 0){
                listOff++;
            }
            while (selected < startTask + listOff && selected != list->size() - 1){
                listOff--;
            }
        } else{
            listOff = 0;
        }

        for (unsigned i = startTask + listOff; i < endTask + listOff; i++){
            if (showNumbers){
                inverseOn();
                if (colors){
                    colorOn(GUTTER_COLOR_PAIR);
                }
                std::string number = std::to_string(i);
                if (!zeroIndexNumbers){
                    number = std::to_string(i + 1);
                }
                if (number.size() < 2){
                    number = "0"+number;
                }
                drawText(number + ")", xpos, ypos);
                if (colors){
                    colorOff(GUTTER_COLOR_PAIR);
                }
                inverseOff();
                xpos += 5;
            }
            if (i == selected){
                inverseOn();
                std::string tmp = tasks->at(i).task();
                std::string line = tmp;
                if (highlightWholeLine){
                    for (int k = tmp.size() + xpos; k < width - 2; k++){
                        line += " ";
                    }
                }
                std::string mark = line.substr(0, STRING_COMPLETE.size());
                line = line.substr(mark.size());

                colorMarkOn(mark);
                drawText(mark, xpos, ypos);
                colorMarkOff(mark);

                if (colors){
                    colorOn(SELECT_COLOR_PAIR);
                }
                drawText(line, xpos + mark.size(), ypos);
                if (colors){
                    colorOff(SELECT_COLOR_PAIR);
                }
                inverseOff();
            } else{
                std::string tmp = tasks->at(i).task();
                std::string text = tmp;
                std::string mark = text.substr(0, STRING_COMPLETE.size());
                text = text.substr(mark.size());

                colorMarkOn(mark);
                drawText(mark, xpos, ypos);
                colorMarkOff(mark);

                drawText(text, xpos + mark.size(), ypos);
            }
            ypos++;
            if (ypos > numTasks || i >= tasks->size() - 1){
                break;
            }
            if (showNumbers){
                xpos -= 5;
            }
        }
    }
    wrefresh(taskWindowBorder);
    wrefresh(taskWindow);
}

// draw text to the current window
void drawText(std::string text, int x, int y)
{
    mvwprintw(currentWindow, y, x, text.c_str());
}

// create a new window
WINDOW* createWindow(int startX, int startY, int width, int height)
{
    WINDOW *win;
    win = newwin(height, width, startY, startX);
    return win;
}

// set the current window
void setCurrentWindow(WINDOW* curWin)
{
    currentWindow = curWin;
}

// draw text in inverse
void inverseOn()
{
    wattron(currentWindow, A_STANDOUT);
}

// draw text normally
void inverseOff()
{
    wattroff(currentWindow, A_STANDOUT);
}

// turn on a color pair
void colorOn(int pair)
{
    wattron(currentWindow, COLOR_PAIR(pair));
}

// turn off a color pair
void colorOff(int pair)
{
    wattroff(currentWindow, COLOR_PAIR(pair));
}

///////////////////////////////////
// stop curses and delete windows
void Draw::stop()
{
    delwin(taskWindow);
    delwin(inputWindow);
    delwin(titleWindow);
    delwin(taskWindowBorder);
    delwin(inputWindowBorder);

    delete titleWin;

    endwin();

    curs_set(1);
}

// create the title string
std::string buildTitle(TodoList *list)
{
    std::string title = "[todo version "+vn+"]";

    unsigned cent = (COLS - list->name.size() - 2) / 2;

    for (unsigned i = title.size(); i < cent; i++){
        title += division;
    }

    title += "[";
    title += list->name;
    title += "]";

    std::string stats = "[";
    stats += std::to_string(list->completed());
    stats += "/";
    stats += std::to_string(list->size());
    stats += " -> ";
    if (list->size() == 0){
        stats += "NaN";
    } else{
        stats += std::to_string((int) ((float) list->completed() / (float) list->size() * 100));
        stats += "%";
    }
    stats += "]";

    for (unsigned i = title.size() + stats.size(); i < (unsigned)COLS; i++){
        title += division;
    }

    title += stats;
    return title;
}

void colorMarkOn(std::string mark)
{
    if (colors){
        if (mark == STRING_COMPLETE){
            colorOn(MARK_COLOR_PAIR_DONE);
        } else{
            colorOn(MARK_COLOR_PAIR);
        }
    }
}

void colorMarkOff(std::string mark)
{
    if (colors){
        if (mark == STRING_COMPLETE){
            colorOff(MARK_COLOR_PAIR_DONE);
        } else{
            colorOff(MARK_COLOR_PAIR);
        }
    }
}
<commit_msg>removed code for old title<commit_after>#include "draw.hpp"

#include <algorithm>
#include <iostream>
#include <sstream>

#include "args.hpp"
#include "config.hpp"
#include "task.hpp"
#include "todolist.hpp"
#include "win.hpp"

using std::string;
using std::stringstream;

// ===================|
// internal functions |
// ===================|
void drawText(string text, int x, int y);

WINDOW* createWindow(int startX, int startY, int width, int height);
void setCurrentWindow(WINDOW *curWin);

std::string buildTitle(TodoList *list);

void drawTitle(TodoList* list);
void drawControls();
void drawTasks(TodoList* list, unsigned selected);

void inverseOn();
void inverseOff();
void colorOn(int pair);
void colorOff(int pair);
void colorMarkOn(string mark);
void colorMarkOff(string mark);

// ===================|
// internal variables |
// ===================|
WINDOW *taskWindow;
WINDOW *inputWindow;
WINDOW *controlWindow;
WINDOW *taskWindowBorder;
WINDOW *inputWindowBorder;
WINDOW *controlWindowBorder;
WINDOW *currentWindow;

Win *titleWin;

int startX;
int startY;
int width;
int height;

unsigned xpos;
unsigned ypos;
unsigned startTask = 0;
unsigned endTask = 0;
unsigned int listOff = 0;

bool colors = false;

/////////////////////////////////////////
// start curses mode and create windows
void Draw::init()
{
    std::cout << "\033]0;" << "todo" << "\7" << std::flush;
    initscr();
    raw();

    use_default_colors();
    if (useColors() && has_colors()){
        start_color();
        init_pair(TITLE_COLOR_PAIR, TITLE_FOREGROUND, TITLE_BACKGROUND);
        init_pair(GUTTER_COLOR_PAIR, GUTTER_FOREGROUND, GUTTER_BACKGROUND);
        init_pair(SELECT_COLOR_PAIR, SELECT_FOREGROUND, SELECT_BACKGROUND);
        init_pair(BORDER_COLOR_PAIR, BORDER_FOREGROUND, BORDER_BACKGROUND);
        init_pair(MARK_COLOR_PAIR, MARK_FOREGROUND, MARK_BACKGROUND);
        init_pair(MARK_COLOR_PAIR_DONE, MARK_FOREGROUND_DONE,
                  MARK_BACKGROUND_DONE);
        colors = true;
    }
    Win::setColors(colors);

    mouseinterval(0);
    keypad(stdscr, true);
    noecho();

    clear();
    refresh();

    curs_set(0);

    startX = listStartX;
    startY = listStartY;
    width = COLS - startX - 2;
    height = LINES * listHeight;
    taskWindowBorder = createWindow(startX, startY, width, height);
    taskWindow = createWindow(startX + 1, startY + 1,
                              width - 2, height - 2);

    int inHeight = inputHeight * LINES;
    inHeight = std::max(inHeight, 4);
    inputWindowBorder = createWindow(inputStartX, inputStartY,
                                     COLS - inputStartX - 2, inHeight);
    inputWindow = createWindow(inputStartX + 1, inputStartY + 1,
                               COLS - inputStartX - 4, inHeight - 2);

    controlWindowBorder = createWindow(inputStartX, inputStartY,
                                       COLS - inputStartX - 2, inHeight);
    controlWindow = createWindow(inputStartX + 1, inputStartY + 1,
                                 COLS - inputStartX - 4, inHeight - 2);

    setCurrentWindow(taskWindow);

    titleWin = new Win(0, 0, COLS, titleHeight, false);
}

//////////////////////
// main draw function
void Draw::draw(TodoList *list, unsigned selected)
{
    werase(inputWindow);
    werase(inputWindowBorder);

    drawTitle(list);
    drawControls();
    drawTasks(list, selected);
}

////////////////////////
// act on mouse events
void Draw::mouse(MEVENT event, TodoList *list,
                 unsigned &selected, bool button)
{
    int x = event.x;
    int y = event.y;
    if (wmouse_trafo(taskWindow, &y, &x, false)){
        unsigned pos = listOff + y - 1;
        if (pos < list->size()){
            if (!button){
                selected = pos;
            } else{
                list->at(pos).toggleComplete();
            }
        }
    }
}

///////////////////////////////////////
// get an input string for a new task
string Draw::getInput()
{
    echo();

    werase(controlWindow);
    werase(controlWindowBorder);

    setCurrentWindow(inputWindowBorder);
    if (colors){
        colorOn(BORDER_COLOR_PAIR);
    }
    box(inputWindowBorder, 0, 0);

    inverseOn();
    drawText("[New task]", 0, 0);
    inverseOff();

    if (colors){
        colorOff(BORDER_COLOR_PAIR);
    }

    setCurrentWindow(inputWindow);
    wrefresh(inputWindowBorder);
    wrefresh(inputWindow);
    curs_set(1);

    char tmp[charBufferSize];
    mvwgetnstr(inputWindow, 0, 0, tmp, charBufferSize);

    setCurrentWindow(taskWindow);
    box(inputWindowBorder, ' ', ' ');
    werase(inputWindow);
    werase(inputWindowBorder);
    curs_set(0);
    noecho();

    return std::string(tmp);
}

////////////////////
//  draw the title
void drawTitle(TodoList* list)
{
    titleWin->clear();
    titleWin->inverse();
    titleWin->color(TITLE_COLOR_PAIR);
    titleWin->print(buildTitle(list), 0, 0);
    titleWin->colorOff(TITLE_COLOR_PAIR);
    titleWin->inverseOff();
    titleWin->color(BORDER_COLOR_PAIR, true);
    titleWin->draw();
}

// draw the control panel
void drawControls()
{
    setCurrentWindow(controlWindow);
    wmove(controlWindow, 0, 0);

    stringstream line;

    line << "[" << ((char) EXIT_KEY) << "]";
    wprintw(controlWindow, line.str().c_str());
    wprintw(controlWindow, " quit          ");
    line.str("");

    line << "[Space]";
    wprintw(controlWindow, line.str().c_str());
    wprintw(controlWindow, " new task          ");
    line.str("");

    line << "[" << ((char) MOVE_UP_KEY) << "]";
    wprintw(controlWindow, line.str().c_str());
    wprintw(controlWindow, " move task up  ");
    line.str("");

    wmove(controlWindow, 1, 0);

    line << "[" << ((char) REMOVE_KEY) << "]";
    wprintw(controlWindow, line.str().c_str());
    wprintw(controlWindow, " delete task   ");
    line.str("");

    line << "[Return]";
    wprintw(controlWindow, line.str().c_str());
    wprintw(controlWindow, " mark task done   ");
    line.str("");

    line << "[" << ((char) MOVE_DOWN_KEY) << "]";
    wprintw(controlWindow, line.str().c_str());
    wprintw(controlWindow, " move task down  ");
    line.str("");

    setCurrentWindow(controlWindowBorder);
    if (colors){
        colorOn(BORDER_COLOR_PAIR);
    }
    box(controlWindowBorder, 0, 0);

    inverseOn();
    drawText("[Controls]", 0, 0);
    inverseOff();

    if (colors){
        colorOff(BORDER_COLOR_PAIR);
    }

    wrefresh(controlWindowBorder);
    wrefresh(controlWindow);
}

void drawTasks(TodoList* list, unsigned selected)
{
    auto tasks = list->tasks();

    setCurrentWindow(taskWindowBorder);
    if (colors){
        colorOn(BORDER_COLOR_PAIR);
    }
    box(taskWindowBorder, 0, 0);

    inverseOn();
    drawText("[Tasks]", 0, 0);
    inverseOff();

    if (colors){
        colorOff(BORDER_COLOR_PAIR);
    }

    setCurrentWindow(taskWindow);
    werase(taskWindow);

    if (tasks && tasks->size() != 0){
        xpos = 1;
        ypos = 1;

        unsigned numTasks = height - 2;
        endTask = tasks->size();
        if (endTask > numTasks){
            endTask = numTasks;
        }

        if (numTasks <= tasks->size()){
            while (selected > endTask + listOff - 2 && selected != 0){
                listOff++;
            }
            while (selected < startTask + listOff && selected != list->size() - 1){
                listOff--;
            }
        } else{
            listOff = 0;
        }

        for (unsigned i = startTask + listOff; i < endTask + listOff; i++){
            if (showNumbers){
                inverseOn();
                if (colors){
                    colorOn(GUTTER_COLOR_PAIR);
                }
                std::string number = std::to_string(i);
                if (!zeroIndexNumbers){
                    number = std::to_string(i + 1);
                }
                if (number.size() < 2){
                    number = "0"+number;
                }
                drawText(number + ")", xpos, ypos);
                if (colors){
                    colorOff(GUTTER_COLOR_PAIR);
                }
                inverseOff();
                xpos += 5;
            }
            if (i == selected){
                inverseOn();
                std::string tmp = tasks->at(i).task();
                std::string line = tmp;
                if (highlightWholeLine){
                    for (int k = tmp.size() + xpos; k < width - 2; k++){
                        line += " ";
                    }
                }
                std::string mark = line.substr(0, STRING_COMPLETE.size());
                line = line.substr(mark.size());

                colorMarkOn(mark);
                drawText(mark, xpos, ypos);
                colorMarkOff(mark);

                if (colors){
                    colorOn(SELECT_COLOR_PAIR);
                }
                drawText(line, xpos + mark.size(), ypos);
                if (colors){
                    colorOff(SELECT_COLOR_PAIR);
                }
                inverseOff();
            } else{
                std::string tmp = tasks->at(i).task();
                std::string text = tmp;
                std::string mark = text.substr(0, STRING_COMPLETE.size());
                text = text.substr(mark.size());

                colorMarkOn(mark);
                drawText(mark, xpos, ypos);
                colorMarkOff(mark);

                drawText(text, xpos + mark.size(), ypos);
            }
            ypos++;
            if (ypos > numTasks || i >= tasks->size() - 1){
                break;
            }
            if (showNumbers){
                xpos -= 5;
            }
        }
    }
    wrefresh(taskWindowBorder);
    wrefresh(taskWindow);
}

// draw text to the current window
void drawText(std::string text, int x, int y)
{
    mvwprintw(currentWindow, y, x, text.c_str());
}

// create a new window
WINDOW* createWindow(int startX, int startY, int width, int height)
{
    WINDOW *win;
    win = newwin(height, width, startY, startX);
    return win;
}

// set the current window
void setCurrentWindow(WINDOW* curWin)
{
    currentWindow = curWin;
}

// draw text in inverse
void inverseOn()
{
    wattron(currentWindow, A_STANDOUT);
}

// draw text normally
void inverseOff()
{
    wattroff(currentWindow, A_STANDOUT);
}

// turn on a color pair
void colorOn(int pair)
{
    wattron(currentWindow, COLOR_PAIR(pair));
}

// turn off a color pair
void colorOff(int pair)
{
    wattroff(currentWindow, COLOR_PAIR(pair));
}

///////////////////////////////////
// stop curses and delete windows
void Draw::stop()
{
    delwin(taskWindow);
    delwin(inputWindow);
    delwin(taskWindowBorder);
    delwin(inputWindowBorder);

    delete titleWin;

    endwin();

    curs_set(1);
}

// create the title string
std::string buildTitle(TodoList *list)
{
    std::string title = "[todo version "+vn+"]";

    unsigned cent = (COLS - list->name.size() - 2) / 2;

    for (unsigned i = title.size(); i < cent; i++){
        title += division;
    }

    title += "[";
    title += list->name;
    title += "]";

    std::string stats = "[";
    stats += std::to_string(list->completed());
    stats += "/";
    stats += std::to_string(list->size());
    stats += " -> ";
    if (list->size() == 0){
        stats += "NaN";
    } else{
        stats += std::to_string((int) ((float) list->completed() / (float) list->size() * 100));
        stats += "%";
    }
    stats += "]";

    for (unsigned i = title.size() + stats.size(); i < (unsigned)COLS; i++){
        title += division;
    }

    title += stats;
    return title;
}

void colorMarkOn(std::string mark)
{
    if (colors){
        if (mark == STRING_COMPLETE){
            colorOn(MARK_COLOR_PAIR_DONE);
        } else{
            colorOn(MARK_COLOR_PAIR);
        }
    }
}

void colorMarkOff(std::string mark)
{
    if (colors){
        if (mark == STRING_COMPLETE){
            colorOff(MARK_COLOR_PAIR_DONE);
        } else{
            colorOff(MARK_COLOR_PAIR);
        }
    }
}
<|endoftext|>


<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow_lite_support/cc/task/processor/image_preprocessor.h"

#include <fstream>
#include <memory>

#include "absl/status/status.h"
#include "tensorflow/lite/core/shims/cc/shims_test_util.h"
#include "tensorflow_lite_support/cc/port/gmock.h"
#include "tensorflow_lite_support/cc/port/gtest.h"
#include "tensorflow_lite_support/cc/port/status_matchers.h"
#include "tensorflow_lite_support/cc/task/core/task_utils.h"
#include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_common_utils.h"
#include "tensorflow_lite_support/cc/test/test_utils.h"
#include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils.h"

namespace tflite {
namespace task {
namespace processor {
namespace {

using ::testing::HasSubstr;
using ::tflite::support::StatusOr;
using ::tflite::task::JoinPath;
using ::tflite::task::core::TfLiteEngine;
using ::tflite::task::vision::DecodeImageFromFile;
using ::tflite::task::vision::FrameBuffer;
using ::tflite::task::vision::ImageData;

constexpr char kTestDataDirectory[] =
    "tensorflow_lite_support/cc/test/testdata/task/vision/";

constexpr char kDilatedConvolutionModelWithMetaData[] = "dilated_conv.tflite";

StatusOr<ImageData> LoadImage(std::string image_name) {
  return DecodeImageFromFile(
      JoinPath("./" /*test src dir*/, kTestDataDirectory, image_name));
}

class DynamicInputTest : public tflite_shims::testing::Test {
 public:
  void SetUp() {
    engine_ = absl::make_unique<TfLiteEngine>();
    engine_->BuildModelFromFile(JoinPath("./", kTestDataDirectory,
                                         kDilatedConvolutionModelWithMetaData));
    engine_->InitInterpreter();

    SUPPORT_ASSERT_OK_AND_ASSIGN(preprocessor_,
                                 ImagePreprocessor::Create(engine_.get(), {0}));

    SUPPORT_ASSERT_OK_AND_ASSIGN(ImageData image, LoadImage("burger.jpg"));
    frame_buffer_ = CreateFromRgbRawBuffer(
        image.pixel_data, FrameBuffer::Dimension{image.width, image.height});

    preprocessor_->Preprocess(*frame_buffer_);
  }

 protected:
  std::unique_ptr<TfLiteEngine> engine_ = nullptr;
  std::unique_ptr<FrameBuffer> frame_buffer_ = nullptr;
  std::unique_ptr<ImagePreprocessor> preprocessor_ = nullptr;
};

// See if output tensor has been re-dimmed as per the input
// tensor. Expected shape: (1, input_height, input_width, 16).
TEST_F(DynamicInputTest, OutputDimensionCheck) {
  EXPECT_TRUE(engine_->interpreter_wrapper()->InvokeWithoutFallback().ok());
  EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[0], 1);
  EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[1],
            engine_->GetInputs()[0]->dims->data[1]);
  EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[2],
            engine_->GetInputs()[0]->dims->data[2]);
  EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[3], 16);
}

// Compare pre-processed input with an already pre-processed
// golden image.
TEST_F(DynamicInputTest, GoldenImageComparison) {
  // Get the processed input image.
  float* processed_input_data =
      tflite::task::core::AssertAndReturnTypedTensor<float>(
          engine_->GetInputs()[0]);

  bool is_equal = true;

  const uint8* image_data = frame_buffer_->plane(0).buffer;
  const size_t input_byte_size =
      frame_buffer_->plane(0).stride.row_stride_bytes *
      frame_buffer_->dimension().height;

  for (size_t i = 0; i < input_byte_size / sizeof(uint8);
       ++i, ++image_data, ++processed_input_data)
    is_equal &=
        std::fabs(static_cast<float>(*image_data) - *processed_input_data) <=
        std::numeric_limits<float>::epsilon();

  EXPECT_TRUE(is_equal);
}

// Modifying batch/depth to invalid size after Init()
// call should throw error.
TEST_F(DynamicInputTest, InvalidBatchOrDepthResize) {
  // Resized input tensor to invalid batch and depth size.
  engine_->interpreter()->ResizeInputTensor(
      0, {50, frame_buffer_->dimension().height,
          frame_buffer_->dimension().width, 100});
  auto process_status = preprocessor_->Preprocess(*frame_buffer_);
  EXPECT_EQ(process_status.code(), absl::StatusCode::kInvalidArgument);
  EXPECT_THAT(process_status.message(),
              HasSubstr("The input tensor should have dimensions 1 x height x "
                        "width x 3. Got"));
}

}  // namespace
}  // namespace processor
}  // namespace task
}  // namespace tflite
<commit_msg>EXPECT_NEAR<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow_lite_support/cc/task/processor/image_preprocessor.h"

#include <fstream>
#include <memory>

#include "absl/status/status.h"
#include "tensorflow/lite/core/shims/cc/shims_test_util.h"
#include "tensorflow_lite_support/cc/port/gmock.h"
#include "tensorflow_lite_support/cc/port/gtest.h"
#include "tensorflow_lite_support/cc/port/status_matchers.h"
#include "tensorflow_lite_support/cc/task/core/task_utils.h"
#include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_common_utils.h"
#include "tensorflow_lite_support/cc/test/test_utils.h"
#include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils.h"

namespace tflite {
namespace task {
namespace processor {
namespace {

using ::testing::HasSubstr;
using ::tflite::support::StatusOr;
using ::tflite::task::JoinPath;
using ::tflite::task::core::TfLiteEngine;
using ::tflite::task::vision::DecodeImageFromFile;
using ::tflite::task::vision::FrameBuffer;
using ::tflite::task::vision::ImageData;

constexpr char kTestDataDirectory[] =
    "tensorflow_lite_support/cc/test/testdata/task/vision/";

constexpr char kDilatedConvolutionModelWithMetaData[] = "dilated_conv.tflite";

StatusOr<ImageData> LoadImage(std::string image_name) {
  return DecodeImageFromFile(
      JoinPath("./" /*test src dir*/, kTestDataDirectory, image_name));
}

class DynamicInputTest : public tflite_shims::testing::Test {
 public:
  void SetUp() {
    engine_ = absl::make_unique<TfLiteEngine>();
    engine_->BuildModelFromFile(JoinPath("./", kTestDataDirectory,
                                         kDilatedConvolutionModelWithMetaData));
    engine_->InitInterpreter();

    SUPPORT_ASSERT_OK_AND_ASSIGN(preprocessor_,
                                 ImagePreprocessor::Create(engine_.get(), {0}));

    SUPPORT_ASSERT_OK_AND_ASSIGN(ImageData image, LoadImage("burger.jpg"));
    frame_buffer_ = CreateFromRgbRawBuffer(
        image.pixel_data, FrameBuffer::Dimension{image.width, image.height});

    preprocessor_->Preprocess(*frame_buffer_);
  }

 protected:
  std::unique_ptr<TfLiteEngine> engine_ = nullptr;
  std::unique_ptr<FrameBuffer> frame_buffer_ = nullptr;
  std::unique_ptr<ImagePreprocessor> preprocessor_ = nullptr;
};

// See if output tensor has been re-dimmed as per the input
// tensor. Expected shape: (1, input_height, input_width, 16).
TEST_F(DynamicInputTest, OutputDimensionCheck) {
  EXPECT_TRUE(engine_->interpreter_wrapper()->InvokeWithoutFallback().ok());
  EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[0], 1);
  EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[1],
            engine_->GetInputs()[0]->dims->data[1]);
  EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[2],
            engine_->GetInputs()[0]->dims->data[2]);
  EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[3], 16);
}

// Compare pre-processed input with an already pre-processed
// golden image.
TEST_F(DynamicInputTest, GoldenImageComparison) {
  // Get the processed input image.
  float* processed_input_data =
      tflite::task::core::AssertAndReturnTypedTensor<float>(
          engine_->GetInputs()[0]);

  const uint8* image_data = frame_buffer_->plane(0).buffer;
  const size_t input_byte_size =
      frame_buffer_->plane(0).stride.row_stride_bytes *
      frame_buffer_->dimension().height;

  for (size_t i = 0; i < input_byte_size / sizeof(uint8);
       ++i, ++image_data, ++processed_input_data)
    EXPECT_NEAR(static_cast<float>(*image_data), *processed_input_data,
                std::numeric_limits<float>::epsilon());
}

// Modifying batch/depth to invalid size after Init()
// call should throw error.
TEST_F(DynamicInputTest, InvalidBatchOrDepthResize) {
  // Resized input tensor to invalid batch and depth size.
  engine_->interpreter()->ResizeInputTensor(
      0, {50, frame_buffer_->dimension().height,
          frame_buffer_->dimension().width, 100});
  auto process_status = preprocessor_->Preprocess(*frame_buffer_);
  EXPECT_EQ(process_status.code(), absl::StatusCode::kInvalidArgument);
  EXPECT_THAT(process_status.message(),
              HasSubstr("The input tensor should have dimensions 1 x height x "
                        "width x 3. Got"));
}

}  // namespace
}  // namespace processor
}  // namespace task
}  // namespace tflite
<|endoftext|>


<commit_before>/*
   DDS, a bridge double dummy solver.

   Copyright (C) 2006-2014 by Bo Haglund /
   2014-2018 by Bo Haglund & Soren Hein.

   See LICENSE and README.
*/

#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>

#include "dds.h"
#include "TransTable.h"
#include "Moves.h"
#include "Memory.h"
#include "dump.h"

#define DDS_POS_LINES 5
// #define DDS_HAND_LINES 12
#define DDS_NODE_LINES 4
// #define DDS_FULL_LINE 80
#define DDS_HAND_OFFSET 16
#define DDS_HAND_OFFSET2 12
#define DDS_DIAG_WIDTH 34

string PrintSuit(const unsigned short suitCode);

void PrintDeal(
  ofstream& fout,
  const unsigned short ranks[][DDS_SUITS],
  const unsigned spacing);

void RankToDiagrams(
  unsigned short rankInSuit[DDS_HANDS][DDS_SUITS],
  nodeCardsType * np,
  char text[DDS_HAND_LINES][DDS_FULL_LINE]);

string WinnersToText(const unsigned short winRanks[]);

string NodeToText(nodeCardsType const * np);

string FullNodeToText(nodeCardsType const * np);

void PosToText(
  pos const * posPoint,
  const int target,
  const int depth,
  string& text);

string PrintSuit(const unsigned short suitCode)
{
  if (! suitCode)
    return "--";

  string st;
  for (int r = 14; r >= 2; r--)
    if ((suitCode & bitMapRank[r]))
      st += cardRank[r];
  return st;
}

void PrintDeal(
  ofstream& fout,
  const unsigned short ranks[][DDS_SUITS],
  const unsigned spacing)
{
  for (int s = 0; s < DDS_SUITS; s++)
  {
    fout << setw(spacing) << "" <<
      cardSuit[s] << " " <<
      PrintSuit(ranks[0][s]) << "\n";
  }

  for (int s = 0; s < DDS_SUITS; s++)
  {
    fout << cardSuit[s] << " " <<
      setw(2*spacing - 2) << left << PrintSuit(ranks[3][s]) <<
      cardSuit[s] << " " <<
      PrintSuit(ranks[1][s]) << "\n";
  }

  for (int s = 0; s < DDS_SUITS; s++)
  {
    fout << setw(spacing) << "" <<
      cardSuit[s] << " " <<
      PrintSuit(ranks[2][s]) << "\n";
  }

  fout << "\n";
  return;
}

void RankToDiagrams(
  const unsigned short rankInSuit[DDS_HANDS][DDS_SUITS],
  nodeCardsType const * np,
  char text[DDS_HAND_LINES][DDS_FULL_LINE])
{
  int c, h, s, r;

  for (int l = 0; l < DDS_HAND_LINES; l++)
  {
    memset(text[l], ' ', DDS_FULL_LINE);
    text[l][DDS_FULL_LINE - 1] = '\0';
    text[l][DDS_DIAG_WIDTH ] = '|';
  }

  strncpy(text[0], "Sought", 6);
  strncpy(&text[0][DDS_DIAG_WIDTH + 5], "Found", 5);

  for (h = 0; h < DDS_HANDS; h++)
  {
    int offset, line;
    if (h == 0)
    {
      offset = DDS_HAND_OFFSET2;
      line = 0;
    }
    else if (h == 1)
    {
      offset = 2 * DDS_HAND_OFFSET2;
      line = 4;
    }
    else if (h == 2)
    {
      offset = DDS_HAND_OFFSET2;
      line = 8;
    }
    else
    {
      offset = 0;
      line = 4;
    }

    for (s = 0; s < DDS_SUITS; s++)
    {
      c = offset;
      for (r = 14; r >= 2; r--)
      {
        if (rankInSuit[h][s] & bitMapRank[r])
        {
          text[line + s][c] = static_cast<char>(cardRank[r]);
          text[line + s][c + DDS_DIAG_WIDTH + 5] =
            (r >= 15 - np->leastWin[s] ?
             static_cast<char>(cardRank[r]) : 'x');
          c++;
        }
      }

      if (c == offset)
      {
        text[line + s][c] = '-';
        text[line + s][c + DDS_DIAG_WIDTH + 5] = '-';
        c++;
      }

      if (h != 3)
        text[line + s][c + DDS_DIAG_WIDTH + 5] = '\0';
    }
  }
}

string WinnersToText(const unsigned short ourWinRanks[])
{
  stringstream ss;
  for (int s = 0; s < DDS_SUITS; s++)
    ss << cardSuit[s] << " " << PrintSuit(ourWinRanks[s]) << "\n";

  return ss.str();
}

string NodeToText(nodeCardsType const * np)
{
  stringstream ss;
  ss << setw(16) << left << "Address" <<
    static_cast<void const *>(np) << "\n";

  ss << setw(16) << left << "Bounds" <<
    static_cast<int>(np->lbound) << " to " <<
    static_cast<int>(np->ubound) << " tricks\n";

  ss << setw(16) << left << "Best move" <<
    cardSuit[ static_cast<int>(np->bestMoveSuit) ] <<
    cardRank[ static_cast<int>(np->bestMoveRank) ] << "\n";

  return ss.str();
}

string FullNodeToText(nodeCardsType const * np)

{
  stringstream ss;
  vector<int> v(DDS_SUITS);
  for (unsigned i = 0; i < DDS_SUITS; i++)
    v[i] = 15 - static_cast<int>(np->leastWin[i]);

  ss << setw(16) << left << "Lowest used" <<
    cardSuit[0] << cardRank[v[0]] << ", " <<
    cardSuit[1] << cardRank[v[1]] << ", " <<
    cardSuit[2] << cardRank[v[2]] << ", " <<
    cardSuit[3] << cardRank[v[3]] << "\n";

  return NodeToText(np) + ss.str();
}

void PosToText(
  pos const * posPoint,
  const int target,
  const int depth,
  string& text)
{
  stringstream ss;
  ss << setw(16) << left << "Target" << target << "\n";
  ss << setw(16) << "Depth" << depth << "\n";
  ss << setw(16) << "tricksMAX" << posPoint->tricksMAX << "\n";
  ss << setw(16) << "First hand" <<
    cardHand[ posPoint->first[depth] ] << "\n";
  ss << setw(16) << "Next first" <<
    cardHand[ posPoint->first[depth - 1] ] << "\n";
  text = ss.str();
}

int DumpInput(
  const int errCode,
  const deal& dl,
  const int target,
  const int solutions,
  const int mode)
{
  ofstream fout;
  fout.open("dump.txt");

  fout << "Error code=" << errCode << "\n\n";
  fout << "Deal data:\n";
  fout << "trump=";

  if (dl.trump == DDS_NOTRUMP)
    fout << "N\n";
  else
    fout << cardSuit[dl.trump] << "\n";
  fout << "first=" << cardHand[dl.first] << "\n";

  unsigned short ranks[4][4];

  for (int k = 0; k <= 2; k++)
    if (dl.currentTrickRank[k] != 0)
    {
      fout << "index=" << k <<
        " currentTrickSuit=" << cardSuit[dl.currentTrickSuit[k]] <<
        " currentTrickRank= " << cardRank[dl.currentTrickRank[k]] << "\n";
    }

  for (int h = 0; h < DDS_HANDS; h++)
    for (int s = 0; s < DDS_SUITS; s++)
    {
      fout << "index1=" << h << " index2=" << s <<
        " remainCards=" << dl.remainCards[h][s] << "\n";
      ranks[h][s] = static_cast<unsigned short>
                    (dl.remainCards[h][s] >> 2);
    }

  fout << "\ntarget=" << target << "\n";
  fout << "solutions=" << solutions << "\n";
  fout << "mode=" << mode << "\n\n\n";
  PrintDeal(fout, ranks, 8);
  fout.close();
  return 0;
}

void DumpRetrieved(
  const string& fname,
  pos const * posPoint,
  nodeCardsType const * np,
  const int target,
  const int depth)
{
  ofstream fout;
  fout.open(fname, ofstream::out | ofstream::app);

  // Big enough for all uses.
  char text[DDS_HAND_LINES][DDS_FULL_LINE];

  fout << "Retrieved entry\n";
  fout << string(15, '-') << "\n";

  string stext;
  PosToText(posPoint, target, depth, stext);
  fout << stext << "\n";

  fout << FullNodeToText(np) << "\n";

  RankToDiagrams(posPoint->rankInSuit, np, text);
  for (int i = 0; i < DDS_HAND_LINES; i++)
    fout << string(text[i]) << "\n";
  fout << "\n";

  fout.close();
}

void DumpStored(
  const string& fname,
  pos const * posPoint,
  Moves const * moves,
  nodeCardsType const * np,
  const int target,
  const int depth)
{
  ofstream fout;
  fout.open(fname, ofstream::out | ofstream::app);

  // Big enough for all uses.
  char text[DDS_HAND_LINES][DDS_FULL_LINE];

  fout << "Stored entry\n";
  fout << string(12, '-') << "\n";

  string stext;
  PosToText(posPoint, target, depth, stext);
  fout << stext << "\n";

  fout << NodeToText(np);

  moves->TrickToText((depth >> 2) + 1, text[0]);
  fout << string(text[0]) << "\n";

  PrintDeal(fout, posPoint->rankInSuit, 16);

  fout.close();
}

void DumpTopLevel(
  ThreadData const * thrp,
  const int tricks,
  const int lower,
  const int upper,
  const int printMode)
{
  ofstream fout;
  fout.open(thrp->fnTopLevel, ofstream::out | ofstream::app);

  char text[DDS_HAND_LINES][DDS_FULL_LINE];
  pos const * posPoint = &thrp->lookAheadPos;

  if (printMode == 0)
  {
    // Trying just one target.
    sprintf(text[0], "Single target %d, %s\n",
            tricks,
            "achieved");
  }
  else if (printMode == 1)
  {
    // Looking for best score.
    if (thrp->val)
    {
      sprintf(text[0],
              "Loop target %d, bounds %d .. %d, achieved with move %c%c\n",
              tricks,
              lower,
              upper,
              cardSuit[ thrp->bestMove[thrp->iniDepth].suit ],
              cardRank[ thrp->bestMove[thrp->iniDepth].rank ]);
    }
    else
    {
      sprintf(text[0],
              "Loop target %d, bounds %d .. %d, failed\n",
              tricks,
              lower,
              upper);
    }
  }
  else if (printMode == 2)
  {
    // Looking for other moves with best score.
    if (thrp->val)
    {
      sprintf(text[0],
              "Loop for cards with score %d, achieved with move %c%c\n",
              tricks,
              cardSuit[ thrp->bestMove[thrp->iniDepth].suit ],
              cardRank[ thrp->bestMove[thrp->iniDepth].rank ]);
    }
    else
    {
      sprintf(text[0],
              "Loop for cards with score %d, failed\n",
              tricks);
    }
  }

  size_t l = strlen(text[0]) - 1;

  memset(text[1], '-', l);
  text[1][l] = '\0';
  fout << string(text[0]) << string(text[1]) << "\n\n";

  PrintDeal(fout, posPoint->rankInSuit, 16);

  fout << WinnersToText(posPoint->winRanks[ thrp->iniDepth ]) << "\n";

  fout << thrp->nodes << " AB nodes, " <<
    thrp->trickNodes << " trick nodes\n\n";

  fout.close();
}

<commit_msg>More refactoring<commit_after>/*
   DDS, a bridge double dummy solver.

   Copyright (C) 2006-2014 by Bo Haglund /
   2014-2018 by Bo Haglund & Soren Hein.

   See LICENSE and README.
*/

#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>

#include "dds.h"
#include "TransTable.h"
#include "Moves.h"
#include "Memory.h"
#include "dump.h"

#define DDS_POS_LINES 5
// #define DDS_HAND_LINES 12
#define DDS_NODE_LINES 4
// #define DDS_FULL_LINE 80
#define DDS_HAND_OFFSET 16
#define DDS_HAND_OFFSET2 12
#define DDS_DIAG_WIDTH 34

string PrintSuit(const unsigned short suitCode);

void PrintDeal(
  ofstream& fout,
  const unsigned short ranks[][DDS_SUITS],
  const unsigned spacing);

void RankToDiagrams(
  unsigned short rankInSuit[DDS_HANDS][DDS_SUITS],
  nodeCardsType * np,
  char text[DDS_HAND_LINES][DDS_FULL_LINE]);

string WinnersToText(const unsigned short winRanks[]);

string NodeToText(nodeCardsType const * np);

string FullNodeToText(nodeCardsType const * np);

string PosToText(
  pos const * posPoint,
  const int target,
  const int depth);

string TopMove(
  const bool val,
  const moveType& bestMove);

string PrintSuit(const unsigned short suitCode)
{
  if (! suitCode)
    return "--";

  string st;
  for (int r = 14; r >= 2; r--)
    if ((suitCode & bitMapRank[r]))
      st += cardRank[r];
  return st;
}

void PrintDeal(
  ofstream& fout,
  const unsigned short ranks[][DDS_SUITS],
  const unsigned spacing)
{
  for (int s = 0; s < DDS_SUITS; s++)
  {
    fout << setw(spacing) << "" <<
      cardSuit[s] << " " <<
      PrintSuit(ranks[0][s]) << "\n";
  }

  for (int s = 0; s < DDS_SUITS; s++)
  {
    fout << cardSuit[s] << " " <<
      setw(2*spacing - 2) << left << PrintSuit(ranks[3][s]) <<
      cardSuit[s] << " " <<
      PrintSuit(ranks[1][s]) << "\n";
  }

  for (int s = 0; s < DDS_SUITS; s++)
  {
    fout << setw(spacing) << "" <<
      cardSuit[s] << " " <<
      PrintSuit(ranks[2][s]) << "\n";
  }

  fout << "\n";
  return;
}

void RankToDiagrams(
  const unsigned short rankInSuit[DDS_HANDS][DDS_SUITS],
  nodeCardsType const * np,
  char text[DDS_HAND_LINES][DDS_FULL_LINE])
{
  int c, h, s, r;

  for (int l = 0; l < DDS_HAND_LINES; l++)
  {
    memset(text[l], ' ', DDS_FULL_LINE);
    text[l][DDS_FULL_LINE - 1] = '\0';
    text[l][DDS_DIAG_WIDTH ] = '|';
  }

  strncpy(text[0], "Sought", 6);
  strncpy(&text[0][DDS_DIAG_WIDTH + 5], "Found", 5);

  for (h = 0; h < DDS_HANDS; h++)
  {
    int offset, line;
    if (h == 0)
    {
      offset = DDS_HAND_OFFSET2;
      line = 0;
    }
    else if (h == 1)
    {
      offset = 2 * DDS_HAND_OFFSET2;
      line = 4;
    }
    else if (h == 2)
    {
      offset = DDS_HAND_OFFSET2;
      line = 8;
    }
    else
    {
      offset = 0;
      line = 4;
    }

    for (s = 0; s < DDS_SUITS; s++)
    {
      c = offset;
      for (r = 14; r >= 2; r--)
      {
        if (rankInSuit[h][s] & bitMapRank[r])
        {
          text[line + s][c] = static_cast<char>(cardRank[r]);
          text[line + s][c + DDS_DIAG_WIDTH + 5] =
            (r >= 15 - np->leastWin[s] ?
             static_cast<char>(cardRank[r]) : 'x');
          c++;
        }
      }

      if (c == offset)
      {
        text[line + s][c] = '-';
        text[line + s][c + DDS_DIAG_WIDTH + 5] = '-';
        c++;
      }

      if (h != 3)
        text[line + s][c + DDS_DIAG_WIDTH + 5] = '\0';
    }
  }
}

string WinnersToText(const unsigned short ourWinRanks[])
{
  stringstream ss;
  for (int s = 0; s < DDS_SUITS; s++)
    ss << cardSuit[s] << " " << PrintSuit(ourWinRanks[s]) << "\n";

  return ss.str();
}

string NodeToText(nodeCardsType const * np)
{
  stringstream ss;
  ss << setw(16) << left << "Address" <<
    static_cast<void const *>(np) << "\n";

  ss << setw(16) << left << "Bounds" <<
    static_cast<int>(np->lbound) << " to " <<
    static_cast<int>(np->ubound) << " tricks\n";

  ss << setw(16) << left << "Best move" <<
    cardSuit[ static_cast<int>(np->bestMoveSuit) ] <<
    cardRank[ static_cast<int>(np->bestMoveRank) ] << "\n";

  return ss.str();
}

string FullNodeToText(nodeCardsType const * np)

{
  stringstream ss;
  vector<int> v(DDS_SUITS);
  for (unsigned i = 0; i < DDS_SUITS; i++)
    v[i] = 15 - static_cast<int>(np->leastWin[i]);

  ss << setw(16) << left << "Lowest used" <<
    cardSuit[0] << cardRank[v[0]] << ", " <<
    cardSuit[1] << cardRank[v[1]] << ", " <<
    cardSuit[2] << cardRank[v[2]] << ", " <<
    cardSuit[3] << cardRank[v[3]] << "\n";

  return NodeToText(np) + ss.str();
}

string PosToText(
  pos const * posPoint,
  const int target,
  const int depth)
{
  stringstream ss;
  ss << setw(16) << left << "Target" << target << "\n";
  ss << setw(16) << "Depth" << depth << "\n";
  ss << setw(16) << "tricksMAX" << posPoint->tricksMAX << "\n";
  ss << setw(16) << "First hand" <<
    cardHand[ posPoint->first[depth] ] << "\n";
  ss << setw(16) << "Next first" <<
    cardHand[ posPoint->first[depth - 1] ] << "\n";
  return ss.str();
}

int DumpInput(
  const int errCode,
  const deal& dl,
  const int target,
  const int solutions,
  const int mode)
{
  ofstream fout;
  fout.open("dump.txt");

  fout << "Error code=" << errCode << "\n\n";
  fout << "Deal data:\n";
  fout << "trump=";

  if (dl.trump == DDS_NOTRUMP)
    fout << "N\n";
  else
    fout << cardSuit[dl.trump] << "\n";
  fout << "first=" << cardHand[dl.first] << "\n";

  unsigned short ranks[4][4];

  for (int k = 0; k <= 2; k++)
    if (dl.currentTrickRank[k] != 0)
    {
      fout << "index=" << k <<
        " currentTrickSuit=" << cardSuit[dl.currentTrickSuit[k]] <<
        " currentTrickRank= " << cardRank[dl.currentTrickRank[k]] << "\n";
    }

  for (int h = 0; h < DDS_HANDS; h++)
    for (int s = 0; s < DDS_SUITS; s++)
    {
      fout << "index1=" << h << " index2=" << s <<
        " remainCards=" << dl.remainCards[h][s] << "\n";
      ranks[h][s] = static_cast<unsigned short>
                    (dl.remainCards[h][s] >> 2);
    }

  fout << "\ntarget=" << target << "\n";
  fout << "solutions=" << solutions << "\n";
  fout << "mode=" << mode << "\n\n\n";
  PrintDeal(fout, ranks, 8);
  fout.close();
  return 0;
}

void DumpRetrieved(
  const string& fname,
  pos const * posPoint,
  nodeCardsType const * np,
  const int target,
  const int depth)
{
  ofstream fout;
  fout.open(fname, ofstream::out | ofstream::app);

  // Big enough for all uses.
  char text[DDS_HAND_LINES][DDS_FULL_LINE];

  fout << "Retrieved entry\n";
  fout << string(15, '-') << "\n";
  fout << PosToText(posPoint, target, depth) << "\n";
  fout << FullNodeToText(np) << "\n";

  RankToDiagrams(posPoint->rankInSuit, np, text);
  for (int i = 0; i < DDS_HAND_LINES; i++)
    fout << string(text[i]) << "\n";
  fout << "\n";

  fout.close();
}

void DumpStored(
  const string& fname,
  pos const * posPoint,
  Moves const * moves,
  nodeCardsType const * np,
  const int target,
  const int depth)
{
  ofstream fout;
  fout.open(fname, ofstream::out | ofstream::app);

  // Big enough for all uses.
  char text[DDS_HAND_LINES][DDS_FULL_LINE];

  fout << "Stored entry\n";
  fout << string(12, '-') << "\n";
  fout << PosToText(posPoint, target, depth) << "\n";
  fout << NodeToText(np);

  moves->TrickToText((depth >> 2) + 1, text[0]);
  fout << string(text[0]) << "\n";

  PrintDeal(fout, posPoint->rankInSuit, 16);

  fout.close();
}

string TopMove(
  const bool val,
  const moveType& bestMove)
{
  if (val)
  {
    stringstream ss;
    ss << "achieved with move " <<
      cardSuit[ bestMove.suit ] <<
      cardRank[ bestMove.rank ];
    return ss.str();
  }
  else
    return "failed";
}

void DumpTopLevel(
  ThreadData const * thrp,
  const int tricks,
  const int lower,
  const int upper,
  const int printMode)
{
  ofstream fout;
  fout.open(thrp->fnTopLevel, ofstream::out | ofstream::app);

  pos const * posPoint = &thrp->lookAheadPos;

  string stext;
  if (printMode == 0)
  {
    // Trying just one target.
    stext = "Single target " + to_string(tricks) + ", " + "achieved";
  }
  else if (printMode == 1)
  {
    // Looking for best score.
    stext = "Loop target " + to_string(tricks) + ", " +
      "bounds " + to_string(lower) + " .. " + to_string(upper) + ", " +
      TopMove(thrp->val, thrp->bestMove[thrp->iniDepth]) + "";
  }
  else if (printMode == 2)
  {
    // Looking for other moves with best score.
    stext = "Loop for cards with score " + to_string(tricks) + ", " +
      TopMove(thrp->val, thrp->bestMove[thrp->iniDepth]);
  }

  fout << stext << "\n" << string(stext.size(), '-') << "\n\n";

  PrintDeal(fout, posPoint->rankInSuit, 16);

  fout << WinnersToText(posPoint->winRanks[ thrp->iniDepth ]) << "\n";

  fout << thrp->nodes << " AB nodes, " <<
    thrp->trickNodes << " trick nodes\n\n";

  fout.close();
}

<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright RTK Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "rtkConjugateGradientConeBeamReconstructionFilter.h"

namespace rtk
{

template<>
ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
::ConjugateGradientConeBeamReconstructionFilter()
{
  this->SetNumberOfRequiredInputs(3);

  // Set the default values of member parameters
  m_NumberOfIterations=3;
  m_MeasureExecutionTimes=false;
//  m_IterationCosts=false;

  m_Gamma = 0;
  m_Regularized = false;
  m_CudaConjugateGradient = true;
  m_DisableDisplacedDetectorFilter = false;

  // Create the filters
#ifdef RTK_USE_CUDA
  m_DisplacedDetectorFilter = rtk::CudaDisplacedDetectorImageFilter::New();
  m_ConstantVolumeSource     = rtk::CudaConstantVolumeSource::New();
#else
  m_DisplacedDetectorFilter = DisplacedDetectorFilterType::New();
  m_ConstantVolumeSource     = ConstantImageSourceType::New();
#endif
  m_CGOperator = CGOperatorFilterType::New();

  m_MultiplyVolumeFilter = MultiplyFilterType::New();
  m_MatrixVectorMultiplyFilter = MatrixVectorMultiplyFilterType::New();
  m_MultiplyOutputFilter = MultiplyFilterType::New();

  // Set permanent parameters
  m_ConstantVolumeSource->SetConstant(0);
  m_DisplacedDetectorFilter->SetPadOnTruncatedSide(false);
}

//template<>
//void
//ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
//::SetSupportMask(const itk::Image<float, 3> *SupportMask)
//{
//  this->SetInput("SupportMask", const_cast<itk::Image<float, 3>*>(SupportMask));
//}

//template<>
//typename itk::Image<float, 3>::ConstPointer
//ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
//::GetSupportMask()
//{
//  return static_cast< const itk::Image<float, 3> * >
//          ( this->itk::ProcessObject::GetInput("SupportMask") );
//}

template<>
void
ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
::GenerateOutputInformation()
{
  // Choose between cuda or non-cuda conjugate gradient filter
  m_ConjugateGradientFilter = ConjugateGradientFilterType::New();
#ifdef RTK_USE_CUDA
  if (m_CudaConjugateGradient)
    m_ConjugateGradientFilter = rtk::CudaConjugateGradientImageFilter_3f::New();
#endif
  m_ConjugateGradientFilter->SetA(m_CGOperator.GetPointer());
  m_ConjugateGradientFilter->SetTargetSumOfSquaresBetweenConsecutiveIterates(m_TargetSumOfSquaresBetweenConsecutiveIterates);
//  m_ConjugateGradientFilter->SetIterationCosts(m_IterationCosts);

  // Set runtime connections
  m_ConstantVolumeSource->SetInformationFromImage(this->GetInput(0));
  m_CGOperator->SetInput(1, this->GetInput(1));
  m_CGOperator->SetSupportMask(this->GetSupportMask());
  m_ConjugateGradientFilter->SetX(this->GetInput(0));
  m_DisplacedDetectorFilter->SetDisable(m_DisableDisplacedDetectorFilter);
  m_DisplacedDetectorFilter->SetInput(this->GetInput(2));

  // Links with the m_BackProjectionFilter should be set here and not
  // in the constructor, as m_BackProjectionFilter is set at runtime
  m_BackProjectionFilterForB->SetInput(0, m_ConstantVolumeSource->GetOutput());
  m_ConjugateGradientFilter->SetB(m_BackProjectionFilterForB->GetOutput());

  // Set the matrix vector multiply filter's inputs for multiplication
  // by the inverse covariance matrix (for GLS minimization)
  m_MatrixVectorMultiplyFilter->SetInput1(this->GetInput(1));
  m_MatrixVectorMultiplyFilter->SetInput2(m_DisplacedDetectorFilter->GetOutput());
  m_CGOperator->SetInput(2, m_DisplacedDetectorFilter->GetOutput());
  m_BackProjectionFilterForB->SetInput(1, m_MatrixVectorMultiplyFilter->GetOutput());

  // If a support mask is used, it serves as preconditioning weights
  if (this->GetSupportMask().IsNotNull())
    {
    // Multiply the volume by support mask, and pass it to the conjugate gradient operator
    m_MultiplyVolumeFilter->SetInput1(m_BackProjectionFilterForB->GetOutput());
    m_MultiplyVolumeFilter->SetInput2(this->GetSupportMask());
    m_CGOperator->SetSupportMask(this->GetSupportMask());
    m_ConjugateGradientFilter->SetB(m_MultiplyVolumeFilter->GetOutput());

    // Multiply the output by the support mask
    m_MultiplyOutputFilter->SetInput1(m_ConjugateGradientFilter->GetOutput());
    m_MultiplyOutputFilter->SetInput2(this->GetSupportMask());
    }

  // For the same reason, set geometry now
  m_CGOperator->SetGeometry(this->m_Geometry);
  m_BackProjectionFilterForB->SetGeometry(this->m_Geometry.GetPointer());
  m_DisplacedDetectorFilter->SetGeometry(this->m_Geometry);

  // Set runtime parameters
  m_ConjugateGradientFilter->SetNumberOfIterations(this->m_NumberOfIterations);
  m_CGOperator->SetGamma(m_Gamma);
  m_CGOperator->SetTikhonov(m_Tikhonov);

  // Set memory management parameters
  m_MatrixVectorMultiplyFilter->ReleaseDataFlagOn();
  m_BackProjectionFilterForB->ReleaseDataFlagOn();
  if (this->GetSupportMask().IsNotNull())
    {
    m_MultiplyVolumeFilter->ReleaseDataFlagOn();
    m_MultiplyOutputFilter->ReleaseDataFlagOn();
    }

  // Have the last filter calculate its output information
  m_ConjugateGradientFilter->UpdateOutputInformation();

  // Copy it as the output information of the composite filter
  this->GetOutput()->CopyInformation( m_ConjugateGradientFilter->GetOutput() );
}

template<>
void
ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
::GenerateData()
{
  itk::TimeProbe ConjugateGradientTimeProbe;
//  typename StatisticsImageFilterType::Pointer StatisticsImageFilterForC = StatisticsImageFilterType::New();
//  typename MultiplyFilterType::Pointer MultiplyFilterForC = MultiplyFilterType::New();

//  if (m_IterationCosts)
//    {
//    MultiplyFilterForC->SetInput(0,this->GetInput(1));
//    MultiplyFilterForC->SetInput(1,this->GetInput(2));
//    MultiplyFilterForC->Update();
//    MultiplyFilterForC->SetInput(1,MultiplyFilterForC->GetOutput());
//    MultiplyFilterForC->Update();
//    StatisticsImageFilterForC->SetInput(MultiplyFilterForC->GetOutput());
//    StatisticsImageFilterForC->Update();
//    m_ConjugateGradientFilter->SetC(0.5*StatisticsImageFilterForC->GetSum());
//    }

  if(m_MeasureExecutionTimes)
    {
    std::cout << "Starting ConjugateGradient" << std::endl;
    ConjugateGradientTimeProbe.Start();
    }

  m_ConjugateGradientFilter->Update();

  if (this->GetSupportMask())
    {
    m_MultiplyOutputFilter->Update();
    }

  if(m_MeasureExecutionTimes)
    {
    ConjugateGradientTimeProbe.Stop();
    std::cout << "ConjugateGradient took " << ConjugateGradientTimeProbe.GetTotal() << ' ' << ConjugateGradientTimeProbe.GetUnit() << std::endl;
    }

  if (this->GetSupportMask())
    {
    this->GraftOutput( m_MultiplyOutputFilter->GetOutput() );
    }
    else
    {
    this->GraftOutput( m_ConjugateGradientFilter->GetOutput() );
    }
}

} // end namespace rtk
<commit_msg>Fixed uninitialized variable<commit_after>/*=========================================================================
 *
 *  Copyright RTK Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "rtkConjugateGradientConeBeamReconstructionFilter.h"

namespace rtk
{

template<>
ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
::ConjugateGradientConeBeamReconstructionFilter()
{
  this->SetNumberOfRequiredInputs(3);

  // Set the default values of member parameters
  m_NumberOfIterations=3;
  m_MeasureExecutionTimes=false;
//  m_IterationCosts=false;

  m_Gamma = 0;
  m_Tikhonov = 0;
  m_Regularized = false;
  m_CudaConjugateGradient = true;
  m_DisableDisplacedDetectorFilter = false;
  m_TargetSumOfSquaresBetweenConsecutiveIterates = 0;

  // Create the filters
#ifdef RTK_USE_CUDA
  m_DisplacedDetectorFilter = rtk::CudaDisplacedDetectorImageFilter::New();
  m_ConstantVolumeSource     = rtk::CudaConstantVolumeSource::New();
#else
  m_DisplacedDetectorFilter = DisplacedDetectorFilterType::New();
  m_ConstantVolumeSource     = ConstantImageSourceType::New();
#endif
  m_CGOperator = CGOperatorFilterType::New();

  m_MultiplyVolumeFilter = MultiplyFilterType::New();
  m_MatrixVectorMultiplyFilter = MatrixVectorMultiplyFilterType::New();
  m_MultiplyOutputFilter = MultiplyFilterType::New();

  // Set permanent parameters
  m_ConstantVolumeSource->SetConstant(0);
  m_DisplacedDetectorFilter->SetPadOnTruncatedSide(false);
}

//template<>
//void
//ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
//::SetSupportMask(const itk::Image<float, 3> *SupportMask)
//{
//  this->SetInput("SupportMask", const_cast<itk::Image<float, 3>*>(SupportMask));
//}

//template<>
//typename itk::Image<float, 3>::ConstPointer
//ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
//::GetSupportMask()
//{
//  return static_cast< const itk::Image<float, 3> * >
//          ( this->itk::ProcessObject::GetInput("SupportMask") );
//}

template<>
void
ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
::GenerateOutputInformation()
{
  // Choose between cuda or non-cuda conjugate gradient filter
  m_ConjugateGradientFilter = ConjugateGradientFilterType::New();
#ifdef RTK_USE_CUDA
  if (m_CudaConjugateGradient)
    m_ConjugateGradientFilter = rtk::CudaConjugateGradientImageFilter_3f::New();
#endif
  m_ConjugateGradientFilter->SetA(m_CGOperator.GetPointer());
  m_ConjugateGradientFilter->SetTargetSumOfSquaresBetweenConsecutiveIterates(m_TargetSumOfSquaresBetweenConsecutiveIterates);
//  m_ConjugateGradientFilter->SetIterationCosts(m_IterationCosts);

  // Set runtime connections
  m_ConstantVolumeSource->SetInformationFromImage(this->GetInput(0));
  m_CGOperator->SetInput(1, this->GetInput(1));
  m_CGOperator->SetSupportMask(this->GetSupportMask());
  m_ConjugateGradientFilter->SetX(this->GetInput(0));
  m_DisplacedDetectorFilter->SetDisable(m_DisableDisplacedDetectorFilter);
  m_DisplacedDetectorFilter->SetInput(this->GetInput(2));

  // Links with the m_BackProjectionFilter should be set here and not
  // in the constructor, as m_BackProjectionFilter is set at runtime
  m_BackProjectionFilterForB->SetInput(0, m_ConstantVolumeSource->GetOutput());
  m_ConjugateGradientFilter->SetB(m_BackProjectionFilterForB->GetOutput());

  // Set the matrix vector multiply filter's inputs for multiplication
  // by the inverse covariance matrix (for GLS minimization)
  m_MatrixVectorMultiplyFilter->SetInput1(this->GetInput(1));
  m_MatrixVectorMultiplyFilter->SetInput2(m_DisplacedDetectorFilter->GetOutput());
  m_CGOperator->SetInput(2, m_DisplacedDetectorFilter->GetOutput());
  m_BackProjectionFilterForB->SetInput(1, m_MatrixVectorMultiplyFilter->GetOutput());

  // If a support mask is used, it serves as preconditioning weights
  if (this->GetSupportMask().IsNotNull())
    {
    // Multiply the volume by support mask, and pass it to the conjugate gradient operator
    m_MultiplyVolumeFilter->SetInput1(m_BackProjectionFilterForB->GetOutput());
    m_MultiplyVolumeFilter->SetInput2(this->GetSupportMask());
    m_CGOperator->SetSupportMask(this->GetSupportMask());
    m_ConjugateGradientFilter->SetB(m_MultiplyVolumeFilter->GetOutput());

    // Multiply the output by the support mask
    m_MultiplyOutputFilter->SetInput1(m_ConjugateGradientFilter->GetOutput());
    m_MultiplyOutputFilter->SetInput2(this->GetSupportMask());
    }

  // For the same reason, set geometry now
  m_CGOperator->SetGeometry(this->m_Geometry);
  m_BackProjectionFilterForB->SetGeometry(this->m_Geometry.GetPointer());
  m_DisplacedDetectorFilter->SetGeometry(this->m_Geometry);

  // Set runtime parameters
  m_ConjugateGradientFilter->SetNumberOfIterations(this->m_NumberOfIterations);
  m_CGOperator->SetGamma(m_Gamma);
  m_CGOperator->SetTikhonov(m_Tikhonov);

  // Set memory management parameters
  m_MatrixVectorMultiplyFilter->ReleaseDataFlagOn();
  m_BackProjectionFilterForB->ReleaseDataFlagOn();
  if (this->GetSupportMask().IsNotNull())
    {
    m_MultiplyVolumeFilter->ReleaseDataFlagOn();
    m_MultiplyOutputFilter->ReleaseDataFlagOn();
    }

  // Have the last filter calculate its output information
  m_ConjugateGradientFilter->UpdateOutputInformation();

  // Copy it as the output information of the composite filter
  this->GetOutput()->CopyInformation( m_ConjugateGradientFilter->GetOutput() );
}

template<>
void
ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
::GenerateData()
{
  itk::TimeProbe ConjugateGradientTimeProbe;
//  typename StatisticsImageFilterType::Pointer StatisticsImageFilterForC = StatisticsImageFilterType::New();
//  typename MultiplyFilterType::Pointer MultiplyFilterForC = MultiplyFilterType::New();

//  if (m_IterationCosts)
//    {
//    MultiplyFilterForC->SetInput(0,this->GetInput(1));
//    MultiplyFilterForC->SetInput(1,this->GetInput(2));
//    MultiplyFilterForC->Update();
//    MultiplyFilterForC->SetInput(1,MultiplyFilterForC->GetOutput());
//    MultiplyFilterForC->Update();
//    StatisticsImageFilterForC->SetInput(MultiplyFilterForC->GetOutput());
//    StatisticsImageFilterForC->Update();
//    m_ConjugateGradientFilter->SetC(0.5*StatisticsImageFilterForC->GetSum());
//    }

  if(m_MeasureExecutionTimes)
    {
    std::cout << "Starting ConjugateGradient" << std::endl;
    ConjugateGradientTimeProbe.Start();
    }

  m_ConjugateGradientFilter->Update();

  if (this->GetSupportMask())
    {
    m_MultiplyOutputFilter->Update();
    }

  if(m_MeasureExecutionTimes)
    {
    ConjugateGradientTimeProbe.Stop();
    std::cout << "ConjugateGradient took " << ConjugateGradientTimeProbe.GetTotal() << ' ' << ConjugateGradientTimeProbe.GetUnit() << std::endl;
    }

  if (this->GetSupportMask())
    {
    this->GraftOutput( m_MultiplyOutputFilter->GetOutput() );
    }
    else
    {
    this->GraftOutput( m_ConjugateGradientFilter->GetOutput() );
    }
}

} // end namespace rtk
<|endoftext|>


<commit_before><commit_msg>coverity#1078582 Dereference after null check<commit_after><|endoftext|>