#include <NTL/LLL.h>
#include <NTL/fileio.h>

#include <NTL/new.h>

NTL_START_IMPL

static void RowTransform(vec_ZZ& A, vec_ZZ& B, const ZZ& MU1)
// x = x - y*MU
{
   static ZZ T, MU;
   long k;

   long n = A.length();
   long i;

   MU = MU1;

   if (MU == 1) {
      for (i = 1; i <= n; i++)
         sub(A(i), A(i), B(i));

      return;
   }

   if (MU == -1) {
      for (i = 1; i <= n; i++)
         add(A(i), A(i), B(i));

      return;
   }

   if (MU == 0) return;

   if (NumTwos(MU) >= NTL_ZZ_NBITS)
      k = MakeOdd(MU);
   else
      k = 0;

   if (MU.WideSinglePrecision()) {
      long mu1;
      conv(mu1, MU);

      for (i = 1; i <= n; i++) {
         mul(T, B(i), mu1);
         if (k > 0) LeftShift(T, T, k);
         sub(A(i), A(i), T);
      }
   }
   else {
      for (i = 1; i <= n; i++) {
         mul(T, B(i), MU);
         if (k > 0) LeftShift(T, T, k);
         sub(A(i), A(i), T);
      }
   }
}

static void RowTransform2(vec_ZZ& A, vec_ZZ& B, const ZZ& MU1)
// x = x + y*MU
{
   static ZZ T, MU;
   long k;

   long n = A.length();
   long i;

   MU = MU1;

   if (MU == 1) {
      for (i = 1; i <= n; i++)
         add(A(i), A(i), B(i));

      return;
   }

   if (MU == -1) {
      for (i = 1; i <= n; i++)
         sub(A(i), A(i), B(i));

      return;
   }

   if (MU == 0) return;

   if (NumTwos(MU) >= NTL_ZZ_NBITS)
      k = MakeOdd(MU);
   else
      k = 0;

   if (MU.WideSinglePrecision()) {
      long mu1;
      conv(mu1, MU);

      for (i = 1; i <= n; i++) {
         mul(T, B(i), mu1);
         if (k > 0) LeftShift(T, T, k);
         add(A(i), A(i), T);
      }
   }
   else {
      for (i = 1; i <= n; i++) {
         mul(T, B(i), MU);
         if (k > 0) LeftShift(T, T, k);
         add(A(i), A(i), T);
      }
   }
}

class GivensCache_RR {
public:
   GivensCache_RR(long m, long n);
   ~GivensCache_RR();

   void flush();
   void selective_flush(long l);
   void swap(long l);
   void swap();
   void touch();
   void incr();

   long sz;

   mat_RR buf;

   long *bl;
   long *bv;
   long bp;
};

GivensCache_RR::GivensCache_RR(long m, long n)
{
   sz = min(m, n)/10;
   if (sz < 2)
      sz = 2;
   else if (sz > 20)
      sz = 20;

   typedef double *doubleptr;

   long i;

   buf.SetDims(sz, n);

   bl = NTL_NEW_OP long[sz];
   if (!bl) Error("out of memory");
   for (i = 0; i < sz; i++) bl[0] = 0;

   bv = NTL_NEW_OP long[sz];
   if (!bv) Error("out of memory");
   for (i = 0; i < sz; i++) bv[0] = 0;

   bp = 0;
}

GivensCache_RR::~GivensCache_RR()
{
   delete [] bl;
   delete [] bv;
}

void GivensCache_RR::flush()
{
   long i;
   for (i = 0; i < sz; i++) bl[i] = 0;
}

void GivensCache_RR::selective_flush(long l)
{
   long i;

   for (i = 0; i < sz; i++)
      if (bl[i] && bv[i] >= l)
         bl[i] = 0;
}

void GivensCache_RR::swap(long l)
{
   long k = bl[bp];
   long i;

   i = 0;
   while (i < sz && bl[i] != l)
      i++;

   if (i < sz) {
      bl[bp] = l;
      bl[i] = k;
   }
   else
      bl[bp] = l;

   selective_flush(l);
}

void GivensCache_RR::swap()
{
   swap(bl[bp] - 1);
}

void GivensCache_RR::touch()
{
   long k = bl[bp];
   bl[bp] = 0;
   selective_flush(k);
}

void GivensCache_RR::incr()
{
   long k = bl[bp];
   long k1 = k+1;
   long i;

   i = 0;
   while (i < sz && bl[i] != k1)
      i++;

   if (i < sz) {
      bp = i;
      return;
   }

   i = 0;
   while (i < sz && bl[i] != 0)
      i++;

   if (i < sz) {
      bp = i;
      return;
   }

   long max_val = 0;
   long max_index = 0;
   for (i = 0; i < sz; i++) {
      long t = labs(bl[i]-k1);
      if (t > max_val) {
         max_val = t;
         max_index = i;
      }
   }

   bp = max_index;
   bl[max_index] = 0;
}

static
void GivensComputeGS(mat_RR& B1, mat_RR& mu, mat_RR& aux, long k, long n,
                     GivensCache_RR& cache)
{
   long i, j;

   RR c, s, a, b, t;
   RR T1, T2;

   vec_RR& p = mu(k);

   vec_RR& pp = cache.buf[cache.bp];

   if (!cache.bl[cache.bp]) {
      for (j = 1; j <= n; j++)
         pp(j) = B1(k,j);

      long backoff;
      backoff = k/4;
      if (backoff < 2)
         backoff = 2;
      else if (backoff > cache.sz + 2)
         backoff = cache.sz + 2;

      long ub = k-(backoff-1);

      for (i = 1; i < ub; i++) {
         vec_RR& cptr = mu(i);
         vec_RR& sptr = aux(i);

         for (j = n; j > i; j--) {
            c = cptr(j);
            s = sptr(j);

            // a = c*pp(j-1) - s*pp(j);
            mul(T1, c, pp(j-1));
            mul(T2, s, pp(j));
            sub(a, T1, T2);

            // b = s*pp(j-1) + c*pp(j);
            mul(T1, s, pp(j-1));
            mul(T2, c, pp(j));
            add(b, T1, T2);

            pp(j-1) = a;
            pp(j) = b;
         }

         div(pp(i), pp(i), mu(i,i));
      }

      cache.bl[cache.bp] = k;
      cache.bv[cache.bp] = k-backoff;
   }

   for (j = 1; j <= n; j++)
      p(j) = pp(j);

   for (i = max(cache.bv[cache.bp]+1, 1); i < k; i++) {
      vec_RR& cptr = mu(i);
      vec_RR& sptr = aux(i);

      for (j = n; j > i; j--) {
         c = cptr(j);
         s = sptr(j);

         // a = c*p(j-1) - s*p(j);
         mul(T1, c, p(j-1));
         mul(T2, s, p(j));
         sub(a, T1, T2);

         // b = s*p(j-1) + c*p(j);
         mul(T1, s, p(j-1));
         mul(T2, c, p(j));
         add(b, T1, T2);

         p(j-1) = a;
         p(j) = b;
      }

      div(p(i), p(i), mu(i,i));
   }

   for (j = n; j > k; j--) {
      a = p(j-1);
      b = p(j);

      if (b == 0) {
         c = 1;
         s = 0;
      }
      else {
         abs(T1, b);
         abs(T2, a);

         if (T1 > T2) {
            // t = -a/b;
            div(T1, a, b);
            negate(t, T1);

            // s = 1/sqrt(1 + t*t);
            sqr(T1, t);
            add(T1, T1, 1);
            SqrRoot(T1, T1);
            inv(s, T1);

            // c = s*t;
            mul(c, s, t);
         }
         else {
            // t = -b/a;
            div(T1, b, a);
            negate(t, T1);

            // c = 1/sqrt(1 + t*t);
            sqr(T1, t);
            add(T1, T1, 1);
            SqrRoot(T1, T1);
            inv(c, T1);

            // s = c*t;
            mul(s, c, t);
         }
      }

      // p(j-1) = c*a - s*b;
      mul(T1, c, a);
      mul(T2, s, b);
      sub(p(j-1), T1, T2);

      p(j) = c;
      aux(k,j) = s;
   }

   if (k > n+1) Error("G_LLL_RR: internal error");
   if (k > n) p(k) = 0;

}

static RR red_fudge;
static long log_red = 0;

static void init_red_fudge()
{
   log_red = long(0.50*RR::precision());

   power2(red_fudge, -log_red);
}

static void inc_red_fudge()
{

   mul(red_fudge, red_fudge, 2);
   log_red--;

   cerr << "G_LLL_RR: warning--relaxing reduction (" << log_red << ")\n";

   if (log_red < 4)
      Error("G_LLL_RR: can not continue...sorry");
}

static long verbose = 0;

static unsigned long NumSwaps = 0;
static double StartTime = 0;
static double LastTime = 0;

static void G_LLLStatus(long max_k, double t, long m, const mat_ZZ& B)
{
   cerr << "---- G_LLL_RR status ----\n";
   cerr << "elapsed time: ";
   PrintTime(cerr, t-StartTime);
   cerr << ", stage: " << max_k;
   cerr << ", rank: " << m;
   cerr << ", swaps: " << NumSwaps << "\n";

   ZZ t1;
   long i;
   double prodlen = 0;

   for (i = 1; i <= m; i++) {
      InnerProduct(t1, B(i), B(i));
      if (!IsZero(t1))
         prodlen += log(t1);
   }

   cerr << "log of prod of lengths: " << prodlen/(2.0*log(2.0)) << "\n";

   if (LLLDumpFile) {
      cerr << "dumping to " << LLLDumpFile << "...";

      ofstream f;
      OpenWrite(f, LLLDumpFile);

      f << "[";
      for (i = 1; i <= m; i++) {
         f << B(i) << "\n";
      }
      f << "]\n";

      f.close();

      cerr << "\n";
   }

   LastTime = t;

}

static
long ll_G_LLL_RR(mat_ZZ& B, mat_ZZ* U, const RR& delta, long deep,
           LLLCheckFct check, mat_RR& B1, mat_RR& mu,
           mat_RR& aux, long m, long init_k, long &quit,
           GivensCache_RR& cache)
{
   long n = B.NumCols();

   long i, j, k, Fc1;
   ZZ MU;
   RR mu1, t1, t2, cc;
   ZZ T1;

   quit = 0;
   k = init_k;

   long counter;

   long trigger_index;
   long small_trigger;
   long cnt;

   RR half;
   conv(half,  0.5);
   RR half_plus_fudge;
   add(half_plus_fudge, half, red_fudge);

   long max_k = 0;
   double tt;

   cache.flush();

   while (k <= m) {

      if (k > max_k) {
         max_k = k;
      }

      if (verbose) {
         tt = GetTime();

         if (tt > LastTime + LLLStatusInterval)
            G_LLLStatus(max_k, tt, m, B);
      }

      GivensComputeGS(B1, mu, aux, k, n, cache);

      counter = 0;
      trigger_index = k;
      small_trigger = 0;
      cnt = 0;

      do {
         // size reduction

         counter++;
         if (counter > 10000) {
            cerr << "G_LLL_XD: warning--possible infinite loop\n";
            counter = 0;
         }

         Fc1 = 0;

         for (j = k-1; j >= 1; j--) {
            abs(t1, mu(k,j));
            if (t1 > half_plus_fudge) {

               if (!Fc1) {
                  if (j > trigger_index ||
                      (j == trigger_index && small_trigger)) {

                     cnt++;

                     if (cnt > 10) {
                        inc_red_fudge();
                        add(half_plus_fudge, half, red_fudge);
                        cnt = 0;
                     }
                  }

                  trigger_index = j;
                  small_trigger = (t1 < 4);
               }

               Fc1 = 1;

               mu1 = mu(k,j);
               if (sign(mu1) >= 0) {
                  sub(mu1, mu1, half);
                  ceil(mu1, mu1);
               }
               else {
                  add(mu1, mu1, half);
                  floor(mu1, mu1);
               }

               if (mu1 == 1) {
                  for (i = 1; i <= j-1; i++)
                     sub(mu(k,i), mu(k,i), mu(j,i));
               }
               else if (mu1 == -1) {
                  for (i = 1; i <= j-1; i++)
                     add(mu(k,i), mu(k,i), mu(j,i));
               }
               else {
                  for (i = 1; i <= j-1; i++) {
                     mul(t2, mu1, mu(j,i));
                     sub(mu(k,i), mu(k,i), t2);
                  }
               }

               conv(MU, mu1);

               sub(mu(k,j), mu(k,j), mu1);

               RowTransform(B(k), B(j), MU);
               if (U) RowTransform((*U)(k), (*U)(j), MU);
            }
         }

         if (Fc1) {
            for (i = 1; i <= n; i++)
               conv(B1(k, i), B(k, i));
            cache.touch();
            GivensComputeGS(B1, mu, aux, k, n, cache);
         }
      } while (Fc1);

      if (check && (*check)(B(k)))
         quit = 1;

      if (IsZero(B(k))) {
         for (i = k; i < m; i++) {
            // swap i, i+1
            swap(B(i), B(i+1));
            swap(B1(i), B1(i+1));
            if (U) swap((*U)(i), (*U)(i+1));
         }

         cache.flush();

         m--;
         if (quit) break;
         continue;
      }

      if (quit) break;

      if (deep > 0) {
         // deep insertions

         Error("sorry...deep insertions not implemented");

      } // end deep insertions

      // test G_LLL reduction condition

      if (k <= 1) {
         cache.incr();
         k++;
      }
      else {
         sqr(t1, mu(k,k-1));
         sub(t1, delta, t1);
         sqr(t2, mu(k-1,k-1));
         mul(t1, t1, t2);
         sqr(t2, mu(k, k));
         if (t1 > t2) {
            // swap rows k, k-1
            swap(B(k), B(k-1));
            swap(B1(k), B1(k-1));
            if (U) swap((*U)(k), (*U)(k-1));

            cache.swap();

            k--;
            NumSwaps++;
         }
         else {
            cache.incr();
            k++;
         }
      }
   }

   if (verbose) {
      G_LLLStatus(m+1, GetTime(), m, B);
   }

   return m;
}

static
long G_LLL_RR(mat_ZZ& B, mat_ZZ* U, const RR& delta, long deep,
           LLLCheckFct check)
{
   long m = B.NumRows();
   long n = B.NumCols();

   long i, j;
   long new_m, dep, quit;
   RR s;
   ZZ MU;
   RR mu1;

   RR t1;
   ZZ T1;

   init_red_fudge();

   if (U) ident(*U, m);

   mat_RR B1;  // approximates B
   B1.SetDims(m, n);

   mat_RR mu;
   mu.SetDims(m, n+1);

   mat_RR aux;
   aux.SetDims(m, n);

   for (i = 1; i <=m; i++)
      for (j = 1; j <= n; j++)
         conv(B1(i, j), B(i, j));

   GivensCache_RR cache(m, n);

   new_m = ll_G_LLL_RR(B, U, delta, deep, check, B1, mu, aux, m, 1, quit, cache);

   dep = m - new_m;
   m = new_m;

   if (dep > 0) {
      // for consistency, we move all of the zero rows to the front

      for (i = 0; i < m; i++) {
         swap(B(m+dep-i), B(m-i));
         if (U) swap((*U)(m+dep-i), (*U)(m-i));
      }
   }

   return m;
}

long G_LLL_RR(mat_ZZ& B, double delta, long deep,
            LLLCheckFct check, long verb)
{
   verbose = verb;
   NumSwaps = 0;
   if (verbose) {
      StartTime = GetTime();
      LastTime = StartTime;
   }

   if (delta < 0.50 || delta >= 1) Error("G_LLL_RR: bad delta");
   if (deep < 0) Error("G_LLL_RR: bad deep");
   RR Delta;
   conv(Delta, delta);
   return G_LLL_RR(B, 0, Delta, deep, check);
}

long G_LLL_RR(mat_ZZ& B, mat_ZZ& U, double delta, long deep,
           LLLCheckFct check, long verb)
{
   verbose = verb;
   NumSwaps = 0;
   if (verbose) {
      StartTime = GetTime();
      LastTime = StartTime;
   }

   if (delta < 0.50 || delta >= 1) Error("G_LLL_RR: bad delta");
   if (deep < 0) Error("G_LLL_RR: bad deep");
   RR Delta;
   conv(Delta, delta);
   return G_LLL_RR(B, &U, Delta, deep, check);
}

static vec_RR G_BKZConstant;

static
void ComputeG_BKZConstant(long beta, long p)
{
   RR c_PI;
   ComputePi(c_PI);

   RR LogPI = log(c_PI);

   G_BKZConstant.SetLength(beta-1);

   vec_RR Log;
   Log.SetLength(beta);

   long i, j, k;
   RR x, y;

   for (j = 1; j <= beta; j++)
      Log(j) = log(to_RR(j));

   for (i = 1; i <= beta-1; i++) {
      // First, we compute x = gamma(i/2)^{2/i}

      k = i/2;

      if ((i & 1) == 0) { // i even
         x = 0;
         for (j = 1; j <= k; j++)
            x += Log(j);

         x = exp(x/k);

      }
      else { // i odd
         x = 0;
         for (j = k + 2; j <= 2*k + 2; j++)
            x += Log(j);

         x += 0.5*LogPI - 2*(k+1)*Log(2);

         x = exp(2*x/i);
      }

      // Second, we compute y = 2^{2*p/i}

      y = exp(-(2*p/to_RR(i))*Log(2));

      G_BKZConstant(i) = x*y/c_PI;
   }

}

static vec_RR G_BKZThresh;

static
void ComputeG_BKZThresh(RR *c, long beta)
{
   G_BKZThresh.SetLength(beta-1);

   long i;
   RR x;
   RR t1;

   x = 0;

   for (i = 1; i <= beta-1; i++) {
      log(t1, c[i-1]);
      add(x, x, t1);
      div(t1, x, i);
      exp(t1, t1);
      mul(G_BKZThresh(i), t1, G_BKZConstant(i));
   }
}

static
void G_BKZStatus(double tt, double enum_time, unsigned long NumIterations,
               unsigned long NumTrivial, unsigned long NumNonTrivial,
               unsigned long NumNoOps, long m,
               const mat_ZZ& B)
{
   cerr << "---- G_BKZ_RR status ----\n";
   cerr << "elapsed time: ";
   PrintTime(cerr, tt-StartTime);
   cerr << ", enum time: ";
   PrintTime(cerr, enum_time);
   cerr << ", iter: " << NumIterations << "\n";
   cerr << "triv: " << NumTrivial;
   cerr << ", nontriv: " << NumNonTrivial;
   cerr << ", no ops: " << NumNoOps;
   cerr << ", rank: " << m;
   cerr << ", swaps: " << NumSwaps << "\n";

   ZZ t1;
   long i;
   double prodlen = 0;

   for (i = 1; i <= m; i++) {
      InnerProduct(t1, B(i), B(i));
      if (!IsZero(t1))
         prodlen += log(t1);
   }

   cerr << "log of prod of lengths: " << prodlen/(2.0*log(2.0)) << "\n";

   if (LLLDumpFile) {
      cerr << "dumping to " << LLLDumpFile << "...";

      ofstream f;
      OpenWrite(f, LLLDumpFile);

      f << "[";
      for (i = 1; i <= m; i++) {
         f << B(i) << "\n";
      }
      f << "]\n";

      f.close();

      cerr << "\n";
   }

   LastTime = tt;

}

static
long G_BKZ_RR(mat_ZZ& BB, mat_ZZ* UU, const RR& delta,
         long beta, long prune, LLLCheckFct check)
{
   long m = BB.NumRows();
   long n = BB.NumCols();
   long m_orig = m;

   long i, j;
   ZZ MU;

   RR t1, t2;
   ZZ T1;

   init_red_fudge();

   mat_ZZ B;
   B = BB;

   B.SetDims(m+1, n);

   mat_RR B1;
   B1.SetDims(m+1, n);

   mat_RR mu;
   mu.SetDims(m+1, n+1);

   mat_RR aux;
   aux.SetDims(m+1, n);

   vec_RR c;
   c.SetLength(m+1);

   RR cbar;

   vec_RR ctilda;
   ctilda.SetLength(m+1);

   vec_RR vvec;
   vvec.SetLength(m+1);

   vec_RR yvec;
   yvec.SetLength(m+1);

   vec_RR uvec;
   uvec.SetLength(m+1);

   vec_RR utildavec;
   utildavec.SetLength(m+1);

   vec_long Deltavec;
   Deltavec.SetLength(m+1);

   vec_long deltavec;
   deltavec.SetLength(m+1);

   mat_ZZ Ulocal;
   mat_ZZ *U;

   if (UU) {
      Ulocal.SetDims(m+1, m);
      for (i = 1; i <= m; i++)
         conv(Ulocal(i, i), 1);
      U = &Ulocal;
   }
   else
      U = 0;

   long quit;
   long new_m;
   long z, jj, kk;
   long s, t;
   long h;

   for (i = 1; i <=m; i++)
      for (j = 1; j <= n; j++)
         conv(B1(i, j), B(i, j));

   // cerr << "\n";
   // cerr << "first G_LLL\n";

   GivensCache_RR cache(m, n);

   m = ll_G_LLL_RR(B, U, delta, 0, check, B1, mu, aux, m, 1, quit, cache);

   double tt;

   double enum_time = 0;
   unsigned long NumIterations = 0;
   unsigned long NumTrivial = 0;
   unsigned long NumNonTrivial = 0;
   unsigned long NumNoOps = 0;

   long verb = verbose;

   verbose = 0;

   if (m < m_orig) {
      for (i = m_orig+1; i >= m+2; i--) {
         // swap i, i-1

         swap(B(i), B(i-1));
         if (U) swap((*U)(i), (*U)(i-1));
      }
   }

   long clean = 1;

   if (!quit && m > 1) {
      // cerr << "continuing\n";

      if (beta > m) beta = m;

      if (prune > 0)
         ComputeG_BKZConstant(beta, prune);

      z = 0;
      jj = 0;

      while (z < m-1) {
         jj++;
         kk = min(jj+beta-1, m);

         if (jj == m) {
            jj = 1;
            kk = beta;
            clean = 1;
         }

         if (verb) {
            tt = GetTime();
            if (tt > LastTime + LLLStatusInterval)
               G_BKZStatus(tt, enum_time, NumIterations, NumTrivial,
                         NumNonTrivial, NumNoOps, m, B);
         }

         // ENUM

         double tt1;

         if (verb) {
            tt1 = GetTime();
         }

         for (i = jj; i <= kk; i++)
            sqr(c(i), mu(i,i));

         if (prune > 0)
            ComputeG_BKZThresh(&c(jj), kk-jj+1);

         cbar = c(jj);
         conv(utildavec(jj), 1);
         conv(uvec(jj), 1);

         conv(yvec(jj), 0);
         conv(vvec(jj), 0);
         Deltavec(jj) = 0;

         s = t = jj;
         deltavec(jj) = 1;

         for (i = jj+1; i <= kk+1; i++) {
            conv(ctilda(i), 0);
            conv(uvec(i), 0);
            conv(utildavec(i), 0);
            conv(yvec(i), 0);
            Deltavec(i) = 0;
            conv(vvec(i), 0);
            deltavec(i) = 1;
         }

         long enum_cnt = 0;

         while (t <= kk) {
            if (verb) {
               enum_cnt++;
               if (enum_cnt > 100000) {
                  enum_cnt = 0;
                  tt = GetTime();
                  if (tt > LastTime + LLLStatusInterval) {
                     enum_time += tt - tt1;
                     tt1 = tt;
                     G_BKZStatus(tt, enum_time, NumIterations, NumTrivial,
                               NumNonTrivial, NumNoOps, m, B);
                  }
               }
            }

            add(t1, yvec(t), utildavec(t));
            sqr(t1, t1);
            mul(t1, t1, c(t));
            add(ctilda(t), ctilda(t+1), t1);

            if (prune > 0 && t > jj)
               sub(t1, cbar, G_BKZThresh(t-jj));
            else
               t1 = cbar;

            if (ctilda(t) <t1) {
               if (t > jj) {
                  t--;
                  clear(t1);
                  for (i = t+1; i <= s; i++) {
                     mul(t2, utildavec(i), mu(i,t));
                     add(t1, t1, t2);
                  }

                  yvec(t) = t1;
                  negate(t1, t1);
                  if (sign(t1) >= 0) {
                     sub(t1, t1, 0.5);
                     ceil(t1, t1);
                  }
                  else {
                     add(t1, t1, 0.5);
                     floor(t1, t1);
                  }

                  utildavec(t) = t1;
                  vvec(t) = t1;
                  Deltavec(t) = 0;

                  negate(t1, t1);

                  if (t1 < yvec(t))
                     deltavec(t) = -1;
                  else
                     deltavec(t) = 1;
               }
               else {
                  cbar = ctilda(jj);
                  for (i = jj; i <= kk; i++) {
                     uvec(i) = utildavec(i);
                  }
               }
            }
            else {
               t++;
               s = max(s, t);
               if (t < s) Deltavec(t) = -Deltavec(t);
               if (Deltavec(t)*deltavec(t) >= 0) Deltavec(t) += deltavec(t);
               add(utildavec(t), vvec(t), Deltavec(t));
            }
         }

         if (verb) {
            tt1 = GetTime() - tt1;
            enum_time += tt1;
         }

         NumIterations++;

         h = min(kk+1, m);

         mul(t1, red_fudge, -8);
         add(t1, t1, delta);
         mul(t1, t1, c(jj));

         if (t1 > cbar) {

            clean = 0;

            // we treat the case that the new vector is b_s (jj < s <= kk)
            // as a special case that appears to occur most of the time.

            s = 0;
            for (i = jj+1; i <= kk; i++) {
               if (uvec(i) != 0) {
                  if (s == 0)
                     s = i;
                  else
                     s = -1;
               }
            }

            if (s == 0) Error("G_BKZ_RR: internal error");

            if (s > 0) {
               // special case
               // cerr << "special case\n";

               NumTrivial++;

               for (i = s; i > jj; i--) {
                  // swap i, i-1
                  swap(B(i-1), B(i));
                  swap(B1(i-1), B1(i));
                  if (U) swap((*U)(i-1), (*U)(i));
               }

               new_m = ll_G_LLL_RR(B, U, delta, 0, check,
                                B1, mu, aux, h, jj, quit, cache);
               if (new_m != h) Error("G_BKZ_RR: internal error");
               if (quit) break;
            }
            else {
               // the general case

               NumNonTrivial++;

               for (i = 1; i <= n; i++) conv(B(m+1, i), 0);

               if (U) {
                  for (i = 1; i <= m_orig; i++)
                     conv((*U)(m+1, i), 0);
               }

               for (i = jj; i <= kk; i++) {
                  if (uvec(i) == 0) continue;
                  conv(MU, uvec(i));
                  RowTransform2(B(m+1), B(i), MU);
                  if (U) RowTransform2((*U)(m+1), (*U)(i), MU);
               }

               for (i = m+1; i >= jj+1; i--) {
                  // swap i, i-1
                  swap(B(i-1), B(i));
                  swap(B1(i-1), B1(i));
                  if (U) swap((*U)(i-1), (*U)(i));
               }

               for (i = 1; i <= n; i++)
                  conv(B1(jj, i), B(jj, i));

               if (IsZero(B(jj))) Error("G_BKZ_RR: internal error");

               // remove linear dependencies

               // cerr << "general case\n";
               new_m = ll_G_LLL_RR(B, U, delta, 0, 0, B1, mu, aux,
                                  kk+1, jj, quit, cache);

               if (new_m != kk) Error("G_BKZ_RR: internal error");

               // remove zero vector

               for (i = kk+2; i <= m+1; i++) {
                  // swap i, i-1
                  swap(B(i-1), B(i));
                  swap(B1(i-1), B1(i));
                  if (U) swap((*U)(i-1), (*U)(i));
               }

               quit = 0;
               if (check) {
                  for (i = 1; i <= kk; i++)
                     if ((*check)(B(i))) {
                        quit = 1;
                        break;
                     }
               }

               if (quit) break;

               if (h > kk) {
                  // extend reduced basis

                  new_m = ll_G_LLL_RR(B, U, delta, 0, check,
                                   B1, mu, aux, h, h, quit, cache);

                  if (new_m != h) Error("G_BKZ_RR: internal error");
                  if (quit) break;
               }
            }

            z = 0;
         }
         else {
            // G_LLL_RR
            // cerr << "progress\n";

            NumNoOps++;

            if (!clean) {
               new_m = ll_G_LLL_RR(B, U, delta, 0, check, B1, mu, aux,
                                   h, h, quit, cache);
               if (new_m != h) Error("G_BKZ_RR: internal error");
               if (quit) break;
            }

            z++;
         }
      }
   }

   if (verb) {
      G_BKZStatus(GetTime(), enum_time, NumIterations, NumTrivial, NumNonTrivial,
                NumNoOps, m, B);
   }

   // clean up

   if (m_orig > m) {
      // for consistency, we move zero vectors to the front

      for (i = m+1; i <= m_orig; i++) {
         swap(B(i), B(i+1));
         if (U) swap((*U)(i), (*U)(i+1));
      }

      for (i = 0; i < m; i++) {
         swap(B(m_orig-i), B(m-i));
         if (U) swap((*U)(m_orig-i), (*U)(m-i));
      }
   }

   B.SetDims(m_orig, n);
   BB = B;

   if (U) {
      U->SetDims(m_orig, m_orig);
      *UU = *U;
   }

   return m;
}

long G_BKZ_RR(mat_ZZ& BB, mat_ZZ& UU, double delta,
         long beta, long prune, LLLCheckFct check, long verb)
{
   verbose = verb;
   NumSwaps = 0;
   if (verbose) {
      StartTime = GetTime();
      LastTime = StartTime;
   }

   if (delta < 0.50 || delta >= 1) Error("G_BKZ_RR: bad delta");
   if (beta < 2) Error("G_BKZ_RR: bad block size");

   RR Delta;
   conv(Delta, delta);

   return G_BKZ_RR(BB, &UU, Delta, beta, prune, check);
}

long G_BKZ_RR(mat_ZZ& BB, double delta,
         long beta, long prune, LLLCheckFct check, long verb)
{
   verbose = verb;
   NumSwaps = 0;
   if (verbose) {
      StartTime = GetTime();
      LastTime = StartTime;
   }

   if (delta < 0.50 || delta >= 1) Error("G_BKZ_RR: bad delta");
   if (beta < 2) Error("G_BKZ_RR: bad block size");

   RR Delta;
   conv(Delta, delta);

   return G_BKZ_RR(BB, 0, Delta, beta, prune, check);
}

NTL_END_IMPL


#include <module_Preprocessing/Preprocessor.h>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <math.h>

using namespace cv;
using namespace boost::numeric::ublas;
using namespace std;

Preprocessor::Preprocessor()
{
}

Mat Preprocessor::doPreprocessing(cv::Mat img){

    Mat rgbImg = img.clone();
    Mat ycbcrImg;

    // Convert original image to YCbCr color space
    cvtColor(rgbImg, ycbcrImg, CV_RGB2YCrCb);

    // Parameters of the skin-color modell
    double c11 = 0.0479;
    double c12 = 0.0259;
    double c21 = 0.0259;
    double c22 = 0.0212;

    double k1 = 0.0;
    double k2 = 0.0;
    double x1, x2;
    double m1 = 113.9454;
    double m2 = 157.5052;
    double f1, f2;

    Mat thresholded(ycbcrImg.size(), CV_8UC1);
    thresholded.setTo(Scalar(0));

    //Segmenting the hand
    double p = 0;

    for (int i = 0; i < ycbcrImg.rows; ++i){
        for (int j = 0; j < ycbcrImg.cols; ++j){

            x1 = (int)ycbcrImg.at<Vec3b>(i, j)[1];
            x2 = (int)ycbcrImg.at<Vec3b>(i, j)[2];

                f1 = -0.5*(x1 - m1);
                f2 = -0.5*(x2 - m2);
                k1 = f1*c11 + f2*c21;
                k2 = f1*c12 + f2*c22;

                // Probability of the pixel that belongs to a skin region
                p = exp(k1*(x1 - m1) + k2*(x2 - m2));

                if (p > 0.15){
                    thresholded.at<uchar>(i, j) = 255;
                }
        }
    }

    return thresholded;
}

Preprocessor::~Preprocessor()
{
}


#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE ToTConverterTest

#include <boost/test/unit_test.hpp>
#include "JPetLoggerInclude.h"
#include "../ToTConverter.h"
using namespace jpet_common_tools;

/// Returns Time-over-threshold for given deposited energy
/// the current parametrization is par1 + par2 * eDep
/// Returned value in ps, and eDep is given in keV.
double getToT1(double eDep, double  par1 = -91958, double par2 = 19341)
{
  if (eDep < 0 ) return 0;
  double value = par1 + eDep * par2;
  return value;
}

BOOST_AUTO_TEST_SUITE(ToTConverterTestSuite)

BOOST_AUTO_TEST_CASE(getTot_standardFunc)
{
  JPetCachedFunctionParams params("pol1", {-91958, 19341});
  ToTConverter conv(params, Range(10000, 0., 100.));
  BOOST_CHECK_CLOSE(conv(0), getToT1(0), 0.1);
  BOOST_CHECK_CLOSE(conv(1), getToT1(1), 0.1);
  BOOST_CHECK_CLOSE(conv(10), getToT1(10), 0.1);
  BOOST_CHECK_CLOSE(conv(59.5), getToT1(59.5), 0.1);
  BOOST_CHECK_CLOSE(conv(99.9), getToT1(99.9), 0.1);
}

BOOST_AUTO_TEST_SUITE_END()


#include <cstdlib>
#include <iostream>
#include <complex>
#define BOOST_UBLAS_NO_ELEMENT_PROXIES
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/bindings/ublas/matrix.hpp>
#include <boost/numeric/bindings/blas/level3.hpp>
#include <boost/numeric/bindings/lower.hpp>
#include <boost/numeric/bindings/upper.hpp>
#include <boost/numeric/bindings/unit_lower.hpp>
#include <boost/numeric/bindings/unit_upper.hpp>
#include <boost/numeric/bindings/left.hpp>
#include <boost/numeric/bindings/right.hpp>
#include <boost/numeric/bindings/trans.hpp>
#include <boost/numeric/bindings/conj.hpp>
#include "print.hpp"
#include "random.hpp"

namespace ublas=boost::numeric::ublas;
namespace blas=boost::numeric::bindings::blas;

int main(int argc, char *argv[]) {
  {
    typedef std::complex<double> complex;
    typedef ublas::matrix<complex, ublas::column_major> matrix;
    typedef typename matrix::size_type size_type;
    rand_normal<complex>::reset();
    size_type n=8, m=2;
    matrix A_l(n, n);
    matrix A_u(n, n);
    for (size_type j=0; j<n; ++j) {
      for (size_type i=0; i<j; ++i) {
    	A_u(i, j)=rand_normal<complex>::get();
	A_l(j, i)=rand_normal<complex>::get();
      }
      A_u(j, j)=rand_normal<complex>::get();
      A_l(j, j)=rand_normal<complex>::get();
      for (size_type i=j+1; i<n; ++i) {
    	A_u(i, j)=0;
	A_l(j, i)=0;
      }
    }
    matrix B(n, m);
    for (size_type j=0; j<m; ++j)
      for (size_type i=0; i<n; ++i)
	B(i, j)=rand_normal<complex>::get();
    complex alpha=rand_normal<complex>::get();
    {
      matrix B1(B);
      for (size_type j=0; j<m; ++j) {
	ublas::matrix_column<matrix> b(B1, j);
	ublas::inplace_solve(A_l, b, ublas::lower_tag());
	b*=alpha;
      }
      matrix B2(B);
      blas::trsm(blas::left(), alpha, blas::lower(A_l), B2);
      std::cout << "testing boost::ublas containers\n"
    		<< "using ublas (left, lower):\n" << print_mat(B1) << '\n'
    		<< "using blas  (left, lower):\n" << print_mat(B2) << '\n'
     		<< '\n';
    }
    {
      matrix B1(B);
      for (size_type j=0; j<m; ++j) {
	ublas::matrix_column<matrix> b(B1, j);
	ublas::inplace_solve(A_u, b, ublas::upper_tag());
	b*=alpha;
      }
      matrix B2(B);
      blas::trsm(blas::left(), alpha, blas::upper(A_u), B2);
      std::cout << "testing boost::ublas containers\n"
    		<< "using ublas (left, upper):\n" << print_mat(B1) << '\n'
    		<< "using blas  (left, upper):\n" << print_mat(B2) << '\n'
     		<< '\n';
    }
  }
  return EXIT_SUCCESS;
}


//!
//! Contains the implementation for creating grids.
//!
//! \file world/grid.cpp
//! \author Alistair Reid
//! \author Darren Shen
//! \date 2014
//! \license Affero General Public License version 3 or later
//! \copyright (c) 2014, NICTA
//!

#include "world/grid.hpp"

#include <Eigen/Dense>
#include <Eigen/Core>

namespace obsidian
{
  namespace world
  {
    Eigen::MatrixXd sensorGrid(const WorldSpec& worldSpec, uint resx, uint resy, double sensorZ)
    {
        Eigen::MatrixXd xyLocations = world::internalGrid2D(worldSpec.xBounds, worldSpec.yBounds, resx, resy);
        Eigen::MatrixXd xyzLocations = Eigen::MatrixXd(xyLocations.rows(), 3);
        xyzLocations.leftCols<2>() = xyLocations;
        xyzLocations.col(2).fill(sensorZ);
        return xyzLocations;
    }

    Eigen::MatrixXd internalGrid2D(std::pair<double,double> xMinMax, std::pair<double,double> yMinMax, uint resx, uint resy)
    {
      double xmin = xMinMax.first;
      double xmax = xMinMax.second;
      double ymin = yMinMax.first;
      double ymax = yMinMax.second;
      double deltax = xmax - xmin;
      double deltay = ymax - ymin;
      Eigen::MatrixXd xyLocations(resx*resy, 2);
      uint c = 0;
      for (uint j = 0; j < resy; j++)
      {
        for (uint i = 0; i < resx; i++)
        {
          double xLoc = xmin + deltax * ((double)i + 0.5) / (double)resx;
          double yLoc = ymin + deltay * ((double)j + 0.5) / (double)resy;
          xyLocations(c,0) = xLoc;
          xyLocations(c,1) = yLoc;
          c++;
        }
      }

      return xyLocations;
    }

    Eigen::MatrixXd internalGrid2DX(std::pair<double,double> xMinMax, std::pair<double,double> yMinMax, uint resx, uint resy)
    {
      double xmin = xMinMax.first;
      double xmax = xMinMax.second;
      double ymin = yMinMax.first;
      double ymax = yMinMax.second;
      double deltax = xmax - xmin;
      double deltay = ymax - ymin;
      Eigen::MatrixXd xyLocations(resx*resy, 2);
      uint c = 0;

      for (uint i = 0; i < resx; i++)
      {
        for (uint j = 0; j < resy; j++)
        {
          double xLoc = xmin + deltax * ((double)i + 0.5) / (double)resx;
          double yLoc = ymin + deltay * ((double)j + 0.5) / (double)resy;
          xyLocations(c,0) = xLoc;
          xyLocations(c,1) = yLoc;
          c++;
        }
      }

      return xyLocations;
    }

    Eigen::MatrixXd edgeGrid2D(std::pair<double, double> xMinMax, std::pair<double, double> yMinMax,
        uint resx, uint resy)
    {
      double xmin = xMinMax.first;
      double xmax = xMinMax.second;
      double ymin = yMinMax.first;
      double ymax = yMinMax.second;
      double deltax = xmax - xmin;
      double deltay = ymax - ymin;
      Eigen::MatrixXd xyLocations(resx*resy, 2);
      uint c = 0;
      for (uint j = 0; j < resy; j++)
      {
        for (uint i = 0; i < resx; i++)
        {
          double xLoc = xmin + deltax * (double)i/(double)(resx-1);
          double yLoc = ymin + deltay * (double)j/(double)(resy-1);
          xyLocations(c,0) = xLoc;
          xyLocations(c,1) = yLoc;
          c++;
        }
      }

      return xyLocations;
    }

    Eigen::MatrixXd sensorGrid3d(const WorldSpec& worldSpec, uint resx, uint resy, uint resz)
    {
      double xmin = worldSpec.xBounds.first;
      double xmax = worldSpec.xBounds.second;
      double ymin = worldSpec.yBounds.first;
      double ymax = worldSpec.yBounds.second;
      double zmin = worldSpec.zBounds.first;
      double zmax = worldSpec.zBounds.second;
      double deltax = xmax - xmin;
      double deltay = ymax - ymin;
      double deltaz = zmax - zmin;

      Eigen::MatrixXd xyzLocations(resx*resy*resz, 3);
      uint c = 0;
      for (uint i = 0; i < resx; i++)
      {
        for (uint j = 0; j < resy; j++)
        {
          for (uint k = 0; k < resz; k++)
          {
            double xLoc = xmin + deltax * ((double)i + 0.5) / (double)resx;
            double yLoc = ymin + deltay * ((double)j + 0.5) / (double)resy;
            double zLoc = zmin + deltaz * ((double)k + 0.5) / (double)resz;
            xyzLocations(c,0) = xLoc;
            xyzLocations(c,1) = yLoc;
            xyzLocations(c,2) = zLoc;
            c++;
          }
        }
      }

      return xyzLocations;
    }

    double length(const Eigen::Vector2d &pt)
    {
      return pt(1) - pt(0);
    }

    Eigen::VectorXd linrange(double from, double to, double step)
    {
      int size = std::floor((to - from) / step) + 1;
      Eigen::VectorXd result(size);
      for (int i = 0; i < result.rows(); i++)
        result(i) = from + (i * step);
      return result;
    }

    std::pair<Eigen::MatrixXd, Eigen::MatrixXd> meshgrid(const Eigen::VectorXd &x, const Eigen::VectorXd &y)
    {
      // Courtesy of: http://forum.kde.org/viewtopic.php?f=74&t=90876
      return std::pair<Eigen::MatrixXd, Eigen::MatrixXd>(x.transpose().replicate(y.rows(), 1), y.replicate(1, x.rows()));
    }

    Eigen::VectorXd flatten(const Eigen::MatrixXd& matrix)
    {
      Eigen::MatrixXd res(matrix);
      res.resize(matrix.rows() * matrix.cols(), 1);
      return res;
    }

    Eigen::VectorXi flatten(const Eigen::MatrixXi &matrix)
    {
      Eigen::MatrixXi res(matrix);
      res.resize(matrix.rows() * matrix.cols(), 1);
      return res;
    }

    std::pair<Eigen::MatrixXd, std::pair<Eigen::MatrixXd, Eigen::MatrixXd>>
    makeGrid(const Eigen::Vector2d &boundaryStart, const Eigen::Vector2d &boundaryEnd,
      const Eigen::Vector2i &resolution, int padding)
    {
      padding = 0;

      // assert(spacing.min() > 0)
      Eigen::Vector2d spacing = (boundaryEnd - boundaryStart).array() /
        (resolution.array() - 1 - 2 * padding).cast<double>();

      // Handle 1 control point using the midpoint of the boundaries
      Eigen::VectorXd linX = resolution(0) == 1 ?
        Eigen::VectorXd::Ones(1) * ((boundaryStart(0) + boundaryEnd(0)) / 2) :
        linrange(boundaryStart(0) - spacing(0) * padding, boundaryEnd(0) + spacing(0) * padding,
          spacing(0));

      Eigen::VectorXd linY = resolution(1) == 1 ?
        Eigen::VectorXd::Ones(1) * ((boundaryStart(1) + boundaryEnd(1)) / 2) :
        linrange(boundaryStart(1) - spacing(1) * padding, boundaryEnd(1) + spacing(1) * padding,
          spacing(1));

      // Get the mesh grid
      auto mesh = meshgrid(linX, linY);

      // We return the mesh as a N*2 matrix, where the first column contains
      // the values of the flattened X coordinates and second column contains
      // the flattened Y coordinates.
      Eigen::MatrixXd flattenedMesh(linX.rows() * linY.rows(), 2);
      flattenedMesh.col(0) << flatten(mesh.first);
      flattenedMesh.col(1) << flatten(mesh.second);

      return std::make_pair(flattenedMesh, std::make_pair(linX, linY));
    }
  }
}


#include "Epetra_ConfigDefs.h"
#ifdef HAVE_MPI
#include "mpi.h"
#include "Epetra_MpiComm.h"
#else
#include "Epetra_SerialComm.h"
#endif

#include "Teuchos_CommandLineProcessor.hpp"
#include "Teuchos_StandardCatchMacros.hpp"
#include "Teuchos_ParameterList.hpp"
#include "Teuchos_XMLParameterListCoreHelpers.hpp"

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/math/special_functions/erf.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/math/special_functions/gamma.hpp>
#include <boost/math/special_functions/beta.hpp>

int main(int argc, char *argv[]){

    std::string    xmlInFileName = "";
    std::string    extraXmlFile = "";
    std::string    xmlOutFileName = "paramList.out";

    Teuchos::CommandLineProcessor  clp(false);
    clp.setOption("xml-in-file",&xmlInFileName,"The XML file to read into a parameter list");
    clp.setDocString("TO DO.");

    Teuchos::CommandLineProcessor::EParseCommandLineReturn
    parse_return = clp.parse(argc,argv);
    if( parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL ) {
        std::cout << "\nEnd Result: TEST FAILED" << std::endl;
        return parse_return;
    }

#ifdef HAVE_MPI
    MPI_Init(&argc, &argv);
    Epetra_MpiComm Comm(MPI_COMM_WORLD);
#else
    Epetra_SerialComm Comm;
#endif

    Teuchos::RCP<Teuchos::ParameterList> paramList = Teuchos::rcp(new Teuchos::ParameterList);
    if(xmlInFileName.length()) {
        Teuchos::updateParametersFromXmlFile(xmlInFileName, inoutArg(*paramList));
        if (Comm.MyPID()==0){
            paramList->print(std::cout,2,true,true);
        }
    }

    double a = -6.0;
    double b = 6.0;
    int n = 10;
    double v;

    double alpha = 1.0/(0.1*0.1);
    double beta  = 1771.0*0.1*0.1;
    for (int i=0; i<n; ++i){
       v = a + (b-a)*double(i)/double(n-1);
       double erfx = boost::math::erf<double>(v/std::sqrt(2.0));
       double y = (1.0/2.0)*(1.0 + erfx);
       double yinv = boost::math::gamma_p_inv<double,double>(alpha,y);
       double g = yinv*beta;

       std::cout << v << std::setw(15) << g << "\n";
    }

    /*double mean = 0.0;
    double stan = 1.0;
    boost::random::normal_distribution<> w(mean,stan);
    boost::random::mt19937 rng;
    rng.seed(std::time(0));
    for (unsigned int i=0; i<10; ++i){
        double x = w(rng);
        double erfarg = (x-mean)/(stan*std::sqrt(2.0));
        double erfx = boost::math::erf<double>(erfarg);
        double y = (1.0/2.0)*(1.0 + erfx);
        double yinv = boost::math::gamma_p_inv<double,double>(1.0/(0.1*0.1),y);
        double z = yinv*10.0*0.1*0.1;
        double z2 = boost::math::ibeta_inv<double,double,double>(5.0,4.0,y);
        std::cout << x << std::setw(20) << y << std::setw(20) << z << std::setw(20) << z2 << "\n";
    }*/

#ifdef HAVE_MPI
    MPI_Finalize();
#endif
return 0;

}


// -------------------------------------------------------------------------------------------------
//                              Copyright 2016 - NumScale SAS
//
//                   Distributed under the Boost Software License, Version 1.0.
//                        See accompanying file LICENSE.txt or copy at
//                            http://www.boost.org/LICENSE_1_0.txt
// -------------------------------------------------------------------------------------------------

/// bench for functor is_not_less_equal in simd mode for float type with no decorator (regular call).
#include <simd_bench.hpp>
#include <boost/simd/function/is_not_less_equal.hpp>

namespace nsb = ns::bench;
namespace bs =  boost::simd;

DEFINE_BENCH_MAIN()
{
  using T = bs::pack<float>;
  run<T>(bs::is_not_less_equal, nsbg::rand<T>(-10, 10), nsbg::rand<T>(-10, 10));
}


//
//  parameters.cpp
//
//  Created by Anton Leuski on 2/17/12.
//  Copyright (c) 2015 Anton Leuski & ICT/USC. All rights reserved.
//
//  This file is part of Jerome.
//
//  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 <sstream>
#include <random>

#include <jerome/type/random.hpp>
#include <jerome/math/parameters/parameterized.hpp>
#include <boost/range/algorithm/copy.hpp>

namespace jerome {
namespace math {
namespace parameters {

	std::ostream& operator << (std::ostream& outs, const RangeDomain& value) {
		return (outs << "[" << value.minimum() << ", " << value.maximum() << "]");
	}

}}}

namespace jerome {
namespace math {
namespace parameters {

	value_vector	parseVector(const String& inString)
	{
		std::stringstream	s(inString);
		std::vector<double> tmp( (std::istream_iterator<double>(s)), std::istream_iterator<double>());
		value_vector		result(tmp.size());
		boost::copy(tmp, result.begin());
		return result;
	}

	List<RangeDomain::value_type> mean(const range_vector& ranges)
	{
		List<RangeDomain::value_type> result;
		for(const auto& r : ranges) {
			result.push_back((r.minimum()+r.maximum()) * 0.5);
		}
		return result;
	}

  List<RangeDomain::value_type>
  clumpToMean(const List<RangeDomain::value_type>& value,
              const range_vector& ranges)
  {
    List<RangeDomain::value_type> result;
    for(List<RangeDomain::value_type>::size_type i = 0, n = value.size();
        i < n; ++i)
    {
      const auto& r = ranges[i];
      const auto& v = value[i];
      if (v >= r.minimum() && v <= r.maximum()) {
        result.push_back(v);
      } else {
        result.push_back((r.minimum()+r.maximum()) * 0.5);
      }
    }
    return result;
  }

  List<RangeDomain::value_type> random(const range_vector& ranges)
	{
		List<RangeDomain::value_type> result;
    static jerome::random<RangeDomain::value_type> random_gen(0, 1);

		for(const auto& r : ranges) {
			result.push_back(r.minimum() + (r.minimum()+r.maximum()) * random_gen());
		}
		return result;
	}

}}}


/*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#include <boost/hana/range.hpp>

#include <boost/hana/core/datatype.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/tuple.hpp>

#include <laws/base.hpp>
#include <laws/foldable.hpp>

#include <test/cnumeric.hpp>

#include <type_traits>
using namespace boost::hana;

int main() {
    //////////////////////////////////////////////////////////////////////////
    // Setup for the laws below
    //////////////////////////////////////////////////////////////////////////
    auto ranges = make<Tuple>(
          range(int_<0>, int_<0>)
        , range(int_<0>, int_<1>)
        , range(int_<0>, int_<2>)
        , range(int_<1>, int_<1>)
        , range(int_<1>, int_<2>)
        , range(int_<1>, int_<3>)
        , range(int_<50>, int_<60>)

        , range(int_<50>, long_<60>)
        , range(long_<50>, int_<60>)
    );

    //////////////////////////////////////////////////////////////////////////
    // Foldable
    //////////////////////////////////////////////////////////////////////////
    {
        test::_injection<0> f{};

        // unpack
        {
            BOOST_HANA_CONSTANT_CHECK(equal(
                unpack(range(int_<0>, int_<0>), f),
                f()
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                unpack(range(int_<0>, int_<1>), f),
                f(int_<0>)
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                unpack(range(int_<0>, int_<2>), f),
                f(int_<0>, int_<1>)
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                unpack(range(int_<0>, int_<3>), f),
                f(int_<0>, int_<1>, int_<2>)
            ));

            // Previously, we would only unpack with `std::size_t`s. Make
            // sure this does not happen.
            unpack(range(int_<0>, int_<1>), [](auto x) {
                using T = datatype_t<decltype(x)>;
                static_assert(std::is_same<typename T::value_type, int>{}, "");
            });
        }

        // length
        {
            BOOST_HANA_CONSTANT_CHECK(equal(
                length(range(int_<0>, int_<0>)), size_t<0>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                length(range(int_<0>, int_<1>)), size_t<1>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                length(range(int_<0>, int_<2>)), size_t<2>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                length(range(int_<4>, int_<4>)), size_t<0>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                length(range(int_<4>, int_<10>)), size_t<6>
            ));
        }

        // minimum
        {
            BOOST_HANA_CONSTANT_CHECK(equal(
                minimum(range(int_<3>, int_<4>)), int_<3>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                minimum(range(int_<3>, int_<5>)), int_<3>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                minimum(range(int_<-1>, int_<5>)), int_<-1>
            ));
        }

        // maximum
        {
            BOOST_HANA_CONSTANT_CHECK(equal(
                maximum(range(int_<3>, int_<4>)), int_<3>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                maximum(range(int_<3>, int_<5>)), int_<4>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                maximum(range(int_<-1>, int_<6>)), int_<5>
            ));
        }

        // sum
        {
            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<-3>, int_<-3>)), int_<0>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<-3>, int_<-2>)), int_<-3>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<-3>, int_<-1>)), int_<-3 + -2>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<-3>, int_<0>)), int_<-3 + -2 + -1>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<-3>, int_<1>)), int_<-3 + -2 + -1 + 0>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<-3>, int_<2>)), int_<-3 + -2 + -1 + 0 + 1>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<-3>, int_<3>)), int_<-3 + -2 + -1 + 0 + 1 + 2>
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<0>, int_<0>)), int_<0>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<0>, int_<1>)), int_<0>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<0>, int_<2>)), int_<0 + 1>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<0>, int_<3>)), int_<0 + 1 + 2>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<0>, int_<4>)), int_<0 + 1 + 2 + 3>
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<3>, int_<3>)), int_<0>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<3>, int_<4>)), int_<3>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<3>, int_<5>)), int_<3 + 4>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<3>, int_<6>)), int_<3 + 4 + 5>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                sum(range(int_<3>, int_<7>)), int_<3 + 4 + 5 + 6>
            ));
        }

        // product
        {
            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<-3>, int_<-3>)), int_<1>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<-3>, int_<-2>)), int_<-3>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<-3>, int_<-1>)), int_<-3 * -2>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<-3>, int_<0>)), int_<-3 * -2 * -1>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<-3>, int_<1>)), int_<-3 * -2 * -1 * 0>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<-3>, int_<2>)), int_<-3 * -2 * -1 * 0 * 1>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<-3>, int_<3>)), int_<-3 * -2 * -1 * 0 * 1 * 2>
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<1>, int_<1>)), int_<1>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<1>, int_<2>)), int_<1>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<1>, int_<3>)), int_<1 * 2>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<1>, int_<4>)), int_<1 * 2 * 3>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<1>, int_<5>)), int_<1 * 2 * 3 * 4>
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<3>, int_<3>)), int_<1>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<3>, int_<4>)), int_<3>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<3>, int_<5>)), int_<3 * 4>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<3>, int_<6>)), int_<3 * 4 * 5>
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                product(range(int_<3>, int_<7>)), int_<3 * 4 * 5 * 6>
            ));
        }

        // laws
        test::TestFoldable<Range>{ranges};
    }
}


//---------------------------------------------------------------------------//
// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://boostorg.github.com/compute for more information.
//---------------------------------------------------------------------------//

#include <iostream>

#include <Eigen/Core>
#include <Eigen/LU>

#include <boost/compute/function.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/algorithm/transform.hpp>
#include <boost/compute/container/vector.hpp>
#include <boost/compute/types/fundamental.hpp>

namespace compute = boost::compute;

// this example shows how to compute the determinant of many 4x4 matrices
// using a determinant function and the transform() algorithm. in OpenCL the
// float16 type can be used to store a 4x4 matrix and the components are laid
// out in the following order:
//
// M = [ s0 s4 s8 sc ]
//     [ s1 s5 s9 sd ]
//     [ s2 s6 sa se ]
//     [ s3 s7 sb sf ]
//
// the input matrices are created using eigen's random matrix and then
// used again at the end to verify the results of the determinant function.
int main()
{
    // get default device and setup context
    compute::device gpu = compute::system::default_device();
    compute::context context(gpu);
    compute::command_queue queue(context, gpu);
    std::cout << "device: " << gpu.name() << std::endl;

    size_t n = 1000;

    // create random 4x4 matrices on the host
    std::vector<Eigen::Matrix4f, mi_stl_allocator<Eigen::Matrix4f>> matrices(n);
    for (size_t i = 0; i < n; i++)
    {
        matrices[i] = Eigen::Matrix4f::Random();
    }

    // copy matrices to the device
    using compute::float16_;
    compute::vector<float16_> input(n, context);
    compute::copy(
        matrices.begin(), matrices.end(), input.begin(), queue);

    // function returning the determinant of a 4x4 matrix.
    BOOST_COMPUTE_FUNCTION(float, determinant4x4, (const float16_ m),
                           {
                               return m.s0 * m.s5 * m.sa * m.sf + m.s0 * m.s6 * m.sb * m.sd + m.s0 * m.s7 * m.s9 * m.se +
                                      m.s1 * m.s4 * m.sb * m.se + m.s1 * m.s6 * m.s8 * m.sf + m.s1 * m.s7 * m.sa * m.sc +
                                      m.s2 * m.s4 * m.s9 * m.sf + m.s2 * m.s5 * m.sb * m.sc + m.s2 * m.s7 * m.s8 * m.sd +
                                      m.s3 * m.s4 * m.sa * m.sd + m.s3 * m.s5 * m.s8 * m.se + m.s3 * m.s6 * m.s9 * m.sc -
                                      m.s0 * m.s5 * m.sb * m.se - m.s0 * m.s6 * m.s9 * m.sf - m.s0 * m.s7 * m.sa * m.sd -
                                      m.s1 * m.s4 * m.sa * m.sf - m.s1 * m.s6 * m.sb * m.sc - m.s1 * m.s7 * m.s8 * m.se -
                                      m.s2 * m.s4 * m.sb * m.sd - m.s2 * m.s5 * m.s8 * m.sf - m.s2 * m.s7 * m.s9 * m.sc -
                                      m.s3 * m.s4 * m.s9 * m.se - m.s3 * m.s5 * m.sa * m.sc - m.s3 * m.s6 * m.s8 * m.sd;
                           });

    // calculate determinants on the gpu
    compute::vector<float> determinants(n, context);
    compute::transform(
        input.begin(), input.end(), determinants.begin(), determinant4x4, queue);

    // check determinants
    std::vector<float, mi_stl_allocator<float>> host_determinants(n);
    compute::copy(
        determinants.begin(), determinants.end(), host_determinants.begin(), queue);

    for (size_t i = 0; i < n; i++)
    {
        float det = matrices[i].determinant();

        if (std::abs(det - host_determinants[i]) > 1e-6)
        {
            std::cerr << "error: wrong determinant at " << i << " ("
                      << host_determinants[i] << " != " << det << ")"
                      << std::endl;
            return -1;
        }
    }

    return 0;
}


#include <Eigen/Dense>
#include <iostream>

using namespace Eigen;
using namespace std;

int main(int, char**)
{
  cout.precision(3);
  Matrix3d m = 10000 * Matrix3d::Identity();
m(0,2) = 1;
cout << "Here's the matrix m:" << endl << m << endl;
cout << "m.isDiagonal() returns: " << m.isDiagonal() << endl;
cout << "m.isDiagonal(1e-3) returns: " << m.isDiagonal(1e-3) << endl;

  return 0;
}


/**
 *
 * Copyright (c) 2010 Matthias Walter (xammy@xammy.homelinux.net)
 *
 * Authors: Matthias Walter
 *
 * Distributed under the Boost Software License, Version 1.0. (See
 * accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 */

#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/bipartite.hpp>

using namespace boost;

/// Example to test for bipartiteness and print the certificates.

template < typename Graph > void print_bipartite(const Graph& g)
{
    typedef graph_traits< Graph > traits;
    typename traits::vertex_iterator vertex_iter, vertex_end;

    /// Most simple interface just tests for bipartiteness.

    bool bipartite = is_bipartite(g);

    if (bipartite)
    {
        typedef std::vector< default_color_type > partition_t;
        typedef
            typename property_map< Graph, vertex_index_t >::type index_map_t;
        typedef iterator_property_map< partition_t::iterator, index_map_t >
            partition_map_t;

        partition_t partition(num_vertices(g));
        partition_map_t partition_map(partition.begin(), get(vertex_index, g));

        /// A second interface yields a bipartition in a color map, if the graph
        /// is bipartite.

        is_bipartite(g, get(vertex_index, g), partition_map);

        for (boost::tie(vertex_iter, vertex_end) = vertices(g);
             vertex_iter != vertex_end; ++vertex_iter)
        {
            std::cout
                << "Vertex " << *vertex_iter << " has color "
                << (get(partition_map, *vertex_iter)
                               == color_traits< default_color_type >::white()
                           ? "white"
                           : "black")
                << std::endl;
        }
    }
    else
    {
        typedef std::vector< typename traits::vertex_descriptor >
            vertex_vector_t;
        vertex_vector_t odd_cycle;

        /// A third interface yields an odd-cycle if the graph is not bipartite.

        find_odd_cycle(g, get(vertex_index, g), std::back_inserter(odd_cycle));

        std::cout << "Odd cycle consists of the vertices:";
        for (size_t i = 0; i < odd_cycle.size(); ++i)
        {
            std::cout << " " << odd_cycle[i];
        }
        std::cout << std::endl;
    }
}

int main(int argc, char** argv)
{
    typedef adjacency_list< vecS, vecS, undirectedS > vector_graph_t;
    typedef std::pair< int, int > E;

    /**
     * Create the graph drawn below.
     *
     *       0 - 1 - 2
     *       |       |
     *   3 - 4 - 5 - 6
     *  /      \   /
     *  |        7
     *  |        |
     *  8 - 9 - 10
     **/

    E bipartite_edges[]
        = { E(0, 1), E(0, 4), E(1, 2), E(2, 6), E(3, 4), E(3, 8), E(4, 5),
              E(4, 7), E(5, 6), E(6, 7), E(7, 10), E(8, 9), E(9, 10) };
    vector_graph_t bipartite_vector_graph(&bipartite_edges[0],
        &bipartite_edges[0] + sizeof(bipartite_edges) / sizeof(E), 11);

    /**
     * Create the graph drawn below.
     *
     *       2 - 1 - 0
     *       |       |
     *   3 - 6 - 5 - 4
     *  /      \   /
     *  |        7
     *  |       /
     *  8 ---- 9
     *
     **/

    E non_bipartite_edges[] = { E(0, 1), E(0, 4), E(1, 2), E(2, 6), E(3, 6),
        E(3, 8), E(4, 5), E(4, 7), E(5, 6), E(6, 7), E(7, 9), E(8, 9) };
    vector_graph_t non_bipartite_vector_graph(&non_bipartite_edges[0],
        &non_bipartite_edges[0] + sizeof(non_bipartite_edges) / sizeof(E), 10);

    /// Call test routine for a bipartite and a non-bipartite graph.

    print_bipartite(bipartite_vector_graph);

    print_bipartite(non_bipartite_vector_graph);

    return 0;
}


#ifndef HYPSYS1D_DG_RATE_OF_CHANGE_HPP
#define HYPSYS1D_DG_RATE_OF_CHANGE_HPP

#include <memory>
#include <Eigen/Dense>
#include <iostream>

#include <ancse/grid.hpp>
#include <ancse/model.hpp>
#include <ancse/rate_of_change.hpp>
#include <ancse/simulation_time.hpp>

#include <ancse/polynomial_basis.hpp>
#include <ancse/dg_handler.hpp>

/// Compute the rate of change due to DG method.
/** The semidiscrete approximation of a PDE using DG is
 *      du_i/dt = - (<F_{i+0.5},\phi^{-}> - <F_{i-0.5},\phi^{+}>)
 *                + \int_K <F, d/dx {\phi}>
 *  This computes the right hand side of the ODE.
 *
 * @tparam NumericalFlux see e.g. `CentralFlux`.
 */
template <class NumericalFlux>
class DGRateOfChange : public RateOfChange {
  public:

    DGRateOfChange (const Grid &grid,
                    const std::shared_ptr<Model> &model,
                    const NumericalFlux &numerical_flux,
                    const PolynomialBasis &poly_basis,
                    const DGHandler &dg_handler)
        : grid (grid),
          model (model),
          numerical_flux (numerical_flux),
          poly_basis (poly_basis),
          dg_handler (dg_handler)
    {
        std::tie(quad_points, quad_weights) = dg_handler.get_quadrature();
    }

    virtual void operator() (Eigen::MatrixXd &dudt,
                             const Eigen::MatrixXd &u0) const override {
        dudt.setZero();
        eval_numerical_flux(dudt, u0);
        eval_volume_integral(dudt, u0);
    }

    void eval_numerical_flux (Eigen::MatrixXd &dudt,
                              const Eigen::MatrixXd &u0) const;

    void eval_volume_integral (Eigen::MatrixXd &dudt,
                               const Eigen::MatrixXd &u0) const;

  private:
    Grid grid;
    std::shared_ptr<Model> model;
    NumericalFlux numerical_flux;
    PolynomialBasis poly_basis;
    DGHandler dg_handler;

    mutable Eigen::VectorXd quad_points, quad_weights;
};

std::shared_ptr<RateOfChange>
make_dg_rate_of_change(const nlohmann::json &config,
                       const Grid &grid,
                       const std::shared_ptr<Model> &model,
                       const PolynomialBasis &poly_basis,
                       const DGHandler &dg_handler,
                       const std::shared_ptr<SimulationTime> &simulation_time);

#endif // HYPSYS1D_DG_RATE_OF_CHANGE_HPP


#include <cctbx/boost_python/flex_fwd.h>

#include <cctbx/uctbx.h>
#include <cctbx/sgtbx/change_of_basis_op.h>
#include <boost/python/tuple.hpp>
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <boost/python/class.hpp>
#include <boost/python/args.hpp>
#include <boost/python/return_value_policy.hpp>
#include <boost/python/copy_const_reference.hpp>
#include <boost/python/return_by_value.hpp>
#include <boost/python/return_internal_reference.hpp>
#include <scitbx/vec3.h>
#include <scitbx/array_family/versa.h>

namespace cctbx { namespace uctbx { namespace boost_python {

  void wrap_fast_minimum_reduction();

namespace {

  struct unit_cell_wrappers : boost::python::pickle_suite
  {
    typedef unit_cell w_t;
    typedef cartesian<> cart_t;
    typedef fractional<> frac_t;
    typedef miller::index<> mix_t;
    typedef scitbx::vec3<double> frac_mix_t;
    typedef af::const_ref<mix_t> cr_mix_t;
    typedef af::shared<double> sh_dbl_t;

    static boost::python::tuple
    getinitargs(w_t const& ucell)
    {
      return boost::python::make_tuple(ucell.parameters());
    }

    typedef af::versa<double, af::mat_grid> matrix_t;

    static matrix_t u_star_to_u_cart_linear_map(w_t const &self) {
      matrix_t result(af::mat_grid(6, 6));
      std::copy(self.u_star_to_u_cart_linear_map().begin(),
                self.u_star_to_u_cart_linear_map().end(),
                result.begin());
      return result;
    }

    static matrix_t d_metrical_matrix_d_params(w_t const &self) {
      matrix_t result(af::mat_grid(6, 6));
      std::copy(self.d_metrical_matrix_d_params().begin(),
                self.d_metrical_matrix_d_params().end(),
                result.begin());
      return result;
    }

    static void
    wrap()
    {
      using namespace boost::python;
      typedef return_value_policy<copy_const_reference> ccr;
      typedef return_internal_reference<> rir;
      class_<w_t>("unit_cell", no_init)
        .def(init<scitbx::mat3<double> const&>((
          arg("orthogonalization_matrix"))))
        .def(init<scitbx::sym_mat3<double> const&>((
          arg("metrical_matrix"))))
        .def(init<af::small<double, 6> const&>((
          arg("parameters"))))
        .def("parameters", &w_t::parameters, ccr())
        .def("reciprocal_parameters", &w_t::reciprocal_parameters, ccr())
        .def("metrical_matrix", &w_t::metrical_matrix, ccr())
        .def("reciprocal_metrical_matrix",
          &w_t::reciprocal_metrical_matrix, ccr())
        .def("volume", &w_t::volume)
        .def("d_volume_d_params",
          &w_t::d_volume_d_params, ccr())
        .def("reciprocal", &w_t::reciprocal)
        .def("longest_vector_sq", &w_t::longest_vector_sq)
        .def("shortest_vector_sq", &w_t::shortest_vector_sq)
        .def("is_degenerate",
          &w_t::is_degenerate, (
            arg("min_min_length_over_max_length")=1e-10,
            arg("min_volume_over_min_length")=1e-5))
        .def("is_similar_to",
          &w_t::is_similar_to, (
            arg("other"),
            arg("relative_length_tolerance")=0.01,
            arg("absolute_angle_tolerance")=1.,
            arg("absolute_length_tolerance")=-9999.))
        .def("similarity_transformations",
          &w_t::similarity_transformations, (
            arg("other"),
            arg("relative_length_tolerance")=0.02,
            arg("absolute_angle_tolerance")=2,
            arg("unimodular_generator_range")=1))
        .def("fractionalization_matrix", &w_t::fractionalization_matrix, ccr())
        .def("orthogonalization_matrix", &w_t::orthogonalization_matrix, ccr())
        .def("grid_index_as_site_cart_matrix",
          (uc_mat3 (w_t::*)(scitbx::vec3<int> const&) const)
            &w_t::grid_index_as_site_cart_matrix,
              (arg("gridding")))
        .def("fractionalize",
          (scitbx::vec3<double>(w_t::*)(scitbx::vec3<double> const&) const)
          &w_t::fractionalize, (
            arg("site_cart")))
        .def("orthogonalize",
          (scitbx::vec3<double>(w_t::*)(scitbx::vec3<double> const&) const)
          &w_t::orthogonalize, (
            arg("site_frac")))
        .def("fractionalize",
          (af::shared<scitbx::vec3<double> >(w_t::*)(
            af::const_ref<scitbx::vec3<double> > const&) const)
              &w_t::fractionalize, (
                arg("sites_cart")))
        .def("orthogonalize",
          (af::shared<scitbx::vec3<double> >(w_t::*)(
            af::const_ref<scitbx::vec3<double> > const&) const)
              &w_t::orthogonalize, (
                arg("sites_frac")))
        .def("fractionalize_gradient",
          (scitbx::vec3<double>(w_t::*)(scitbx::vec3<double> const&) const)
          &w_t::fractionalize_gradient, (
            arg("site_cart")))
        .def("u_star_to_u_iso_linear_form",
             &w_t::u_star_to_u_iso_linear_form, ccr())
        .def("u_star_to_u_cif_linear_map",
             &w_t::u_star_to_u_cif_linear_map, ccr())
        .def("u_star_to_u_cart_linear_map",
             u_star_to_u_cart_linear_map)
        .def("d_metrical_matrix_d_params",
             d_metrical_matrix_d_params)
        .def("length",
          (double(w_t::*)(frac_t const&) const)
          &w_t::length, (
            arg("site_frac")))
        .def("distance",
          (double(w_t::*)(frac_t const&, frac_t const&) const)
          &w_t::distance, (
            arg("site_frac_1"), arg("site_frac_2")))
        .def("angle",
          (boost::optional<double>(w_t::*)(
            frac_t const&, frac_t const&, frac_t const&) const)
          &w_t::angle, (
            arg("site_frac_1"), arg("site_frac_2"), arg("site_frac_3")))
        .def("dihedral",
          (boost::optional<double>(w_t::*)(
            frac_t const&, frac_t const&, frac_t const&, frac_t const&) const)
          &w_t::dihedral, (
            arg("site_frac_1"), arg("site_frac_2"),
            arg("site_frac_3"), arg("site_frac_4")))
        .def("mod_short_length",
          (double(w_t::*)(frac_t const&) const)
          &w_t::mod_short_length, (
            arg("site_frac")))
        .def("mod_short_distance",
          (double(w_t::*)(frac_t const&, frac_t const&) const)
          &w_t::mod_short_distance, (
            arg("site_frac_1"), arg("site_frac_2")))
        .def("min_mod_short_distance",
          (double(w_t::*)
            (af::const_ref<scitbx::vec3<double> > const&,
             frac_t const&) const)
          &w_t::min_mod_short_distance, (
            arg("site_frac_1"), arg("site_frac_2")))
        .def("matrix_cart",
          (uc_mat3(w_t::*)(sgtbx::rot_mx const&) const)
            &w_t::matrix_cart, (
              arg("rot_mx")))
        .def("change_basis",
          (w_t(w_t::*)(uc_mat3 const&, double) const)
            &w_t::change_basis, (
              arg("c_inv_r"), arg("r_den")=1.))
        .def("change_basis",
          (w_t(w_t::*)(sgtbx::change_of_basis_op const&) const)
            &w_t::change_basis, (
              arg("cb_op")))
        .def("max_miller_indices",
          (mix_t(w_t::*)(double, double) const)
            &w_t::max_miller_indices, (
              arg("d_min"), arg("tolerance")=1e-4))
        .def("d_star_sq",
          (double(w_t::*)(mix_t const&) const)
          &w_t::d_star_sq, (
            arg("miller_index")))
        .def("d_star_sq",
          (sh_dbl_t(w_t::*)(cr_mix_t const&) const)
          &w_t::d_star_sq, (
            arg("miller_indices")))
        .def("max_d_star_sq",
          (double(w_t::*)(cr_mix_t const&) const)
          &w_t::max_d_star_sq, (
            arg("miller_indices")))
        .def("min_max_d_star_sq",
          (af::double2(w_t::*)(cr_mix_t const&) const)
          &w_t::min_max_d_star_sq, (
            arg("miller_indices")))
        .def("stol_sq",
          (double(w_t::*)(mix_t  const&) const)
          &w_t::stol_sq, (
            arg("miller_index")))
        .def("stol_sq",
          (sh_dbl_t(w_t::*)(cr_mix_t const&) const)
          &w_t::stol_sq, (
            arg("miller_indices")))
        .def("two_stol",
          (double(w_t::*)(mix_t const&) const)
          &w_t::two_stol, (
            arg("miller_index")))
        .def("two_stol",
          (sh_dbl_t(w_t::*)(cr_mix_t const&) const)
          &w_t::two_stol, (
            arg("miller_indices")))
        .def("stol",
          (double(w_t::*)(mix_t const&) const)
          &w_t::stol, (
            arg("miller_index")))
        .def("stol",
          (sh_dbl_t(w_t::*)(cr_mix_t const&) const)
          &w_t::stol, (
            arg("miller_indices")))
        .def("d",
          (double(w_t::*)(mix_t const&) const)
          &w_t::d, (
            arg("miller_index")))
        .def("d_frac",
          (double(w_t::*)(frac_mix_t const&) const)
          &w_t::d_frac, (
            arg("miller_index")))
        .def("d",
          (sh_dbl_t(w_t::*)(cr_mix_t const&) const)
          &w_t::d, (
            arg("miller_indices")))
        .def("two_theta",
          (double(w_t::*)(mix_t const&, double, bool) const)
            &w_t::two_theta, (
              arg("miller_index"), arg("wavelength"), arg("deg")=false))
        .def("two_theta",
          (sh_dbl_t(w_t::*)(cr_mix_t const&, double, bool) const)
            &w_t::two_theta, (
              arg("miller_indices"), arg("wavelength"), arg("deg")=false))
        .def("sin_sq_two_theta",
          (double(w_t::*)(mix_t const&, double) const)
            &w_t::sin_sq_two_theta, (
              arg("miller_index"), arg("wavelength")))
        .def("sin_sq_two_theta",
          (sh_dbl_t(w_t::*)(cr_mix_t const&, double) const)
            &w_t::sin_sq_two_theta, (
              arg("miller_indices"), arg("wavelength")))
        .def("sin_two_theta",
          (double(w_t::*)(mix_t const&, double) const)
            &w_t::sin_two_theta, (
              arg("miller_index"), arg("wavelength")))
        .def("sin_two_theta",
          (sh_dbl_t(w_t::*)(cr_mix_t const&, double) const)
            &w_t::sin_two_theta, (
              arg("miller_indices"), arg("wavelength")))
        .def("reciprocal_space_vector",
          (scitbx::vec3<double>(w_t::*)(mix_t const&) const)
            &w_t::reciprocal_space_vector, (
              arg("miller_index")))
        .def("reciprocal_space_vector",
          (af::shared<scitbx::vec3<double> >(w_t::*)(cr_mix_t const&) const)
            &w_t::reciprocal_space_vector, (
              arg("miller_indices")))
        .def("bases_mean_square_difference",
          &w_t::bases_mean_square_difference,
            (arg("other")))
        .def("compare_orthorhombic", &w_t::compare_orthorhombic,
          (arg("other")))
        .def("compare_monoclinic", &w_t::compare_monoclinic,
          (arg("other"), arg("unique_axis"), arg("angular_tolerance")))
        .def("change_of_basis_op_for_best_monoclinic_beta",
          &w_t::change_of_basis_op_for_best_monoclinic_beta, rir())
        .def_pickle(unit_cell_wrappers())
      ;
    }
  };

  inline
  scitbx::vec3<int>
  fractional_unit_shifts_d(fractional<> const& distance_frac)
  {
    return distance_frac.unit_shifts();
  }

  inline
  scitbx::vec3<int>
  fractional_unit_shifts_s_s(
    fractional<> const& site_frac_1,
    fractional<> const& site_frac_2)
  {
    return fractional<>(site_frac_1-site_frac_2).unit_shifts();
  }

  struct distance_mod_1_wrappers
  {
    typedef distance_mod_1 w_t;

    static void
    wrap()
    {
      using namespace boost::python;
      typedef return_value_policy<return_by_value> rbv;
      class_<w_t>("distance_mod_1", no_init)
        .def(init<
          unit_cell const&,
          fractional<> const&,
          fractional<> const&>((
            arg("unit_cell"),
            arg("site_frac_1"),
            arg("site_frac_2"))))
        .add_property("diff_raw", make_getter(&w_t::diff_raw, rbv()))
        .add_property("diff_mod", make_getter(&w_t::diff_mod, rbv()))
        .def_readonly("dist_sq", &w_t::dist_sq)
        .def("unit_shifts", &w_t::unit_shifts)
      ;
    }
  };

  void init_module()
  {
    using namespace boost::python;
    //! Forward conversions
    def("d_star_sq_as_stol_sq", (
      double(*)(double)) d_star_sq_as_stol_sq, (arg("d_star_sq")));
    def("d_star_sq_as_stol_sq", (
      af::shared<double>(*)(af::const_ref<double> const &))
      d_star_sq_as_stol_sq, (arg("d_star_sq")));
    def("d_star_sq_as_two_stol", (
      double(*)(double)) d_star_sq_as_two_stol, (arg("d_star_sq")));
    def("d_star_sq_as_two_stol", (
      af::shared<double>(*)(af::const_ref<double> const &))
      d_star_sq_as_two_stol, (arg("d_star_sq")));
    def("d_star_sq_as_stol", (
      double(*)(double)) d_star_sq_as_stol, (arg("d_star_sq")));
    def("d_star_sq_as_stol", (
      af::shared<double>(*)(af::const_ref<double> const &))
      d_star_sq_as_stol, (arg("d_star_sq")));
    def("d_star_sq_as_d", (
      double(*)(double)) d_star_sq_as_d, (arg("d_star_sq")));
    def("d_star_sq_as_d", (
      af::shared<double>(*)(af::const_ref<double> const &))
      d_star_sq_as_d, (arg("d_star_sq")));
    def("d_star_sq_as_two_theta", (
      double(*)(double, double, bool)) d_star_sq_as_two_theta,
      (arg("d_star_sq"), arg("wavelength"), arg("deg")=false));
    def("d_star_sq_as_two_theta", (
      af::shared<double>(*)(af::const_ref<double> const &, double, bool))
      d_star_sq_as_two_theta,
      (arg("d_star_sq"), arg("wavelength"), arg("deg")=false));
    //! Reverse conversions
    def("stol_sq_as_d_star_sq", (
      double(*)(double)) stol_sq_as_d_star_sq, (arg("stol_sq")));
    def("stol_sq_as_d_star_sq", (
      af::shared<double>(*)(af::const_ref<double> const &))
      stol_sq_as_d_star_sq, (arg("stol_sq")));
    def("two_stol_as_d_star_sq", (
      double(*)(double)) two_stol_as_d_star_sq, (arg("two_stol")));
    def("two_stol_as_d_star_sq", (
      af::shared<double>(*)(af::const_ref<double> const &))
      two_stol_as_d_star_sq, (arg("two_stol")));
    def("stol_as_d_star_sq", (
      double(*)(double)) stol_as_d_star_sq, (arg("stol")));
    def("stol_as_d_star_sq", (
      af::shared<double>(*)(af::const_ref<double> const &))
      stol_as_d_star_sq, (arg("stol")));
    def("d_as_d_star_sq", (
      double(*)(double)) d_as_d_star_sq, (arg("d")));
    def("d_as_d_star_sq", (
      af::shared<double>(*)(af::const_ref<double> const &))
      d_as_d_star_sq, (arg("d")));
    def("two_theta_as_d_star_sq", (
      double(*)(double, double, bool)) two_theta_as_d_star_sq,
      (arg("two_theta"), arg("wavelength"), arg("deg")=false));
    def("two_theta_as_d_star_sq", (
      af::shared<double>(*)(af::const_ref<double> const &, double, bool))
      two_theta_as_d_star_sq,
      (arg("two_theta"), arg("wavelength"), arg("deg")=false));
    def("two_theta_as_d", (
      double(*)(double, double, bool)) two_theta_as_d,
      (arg("two_theta"), arg("wavelength"), arg("deg")=false));
    def("two_theta_as_d", (
      af::shared<double>(*)(af::const_ref<double> const &, double, bool))
      two_theta_as_d,
      (arg("two_theta"), arg("wavelength"), arg("deg")=false));

    def("unit_cell_angles_are_feasible", unit_cell_angles_are_feasible, (
      arg("values_deg"), arg("tolerance")=1e-6));

    unit_cell_wrappers::wrap();
    wrap_fast_minimum_reduction();

    def("fractional_unit_shifts", fractional_unit_shifts_d, (
      arg("distance_frac")));
    def("fractional_unit_shifts", fractional_unit_shifts_s_s, (
      arg("site_frac_1"), arg("site_frac_2")));

    distance_mod_1_wrappers::wrap();
  }

} // namespace <anonymous>
}}} // namespace cctbx::uctbx::boost_python

BOOST_PYTHON_MODULE(cctbx_uctbx_ext)
{
  cctbx::uctbx::boost_python::init_module();
}


#include <tiny.h>
#include <convex.h>

#define BOOST_AUTO_TEST_MAIN
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_tools.hpp>

BOOST_AUTO_TEST_SUITE(convex_reduce_edge);

BOOST_AUTO_TEST_CASE(case_by_case_test)
{
  typedef tiny::MathTypes<double>        math_types;
  typedef math_types::vector3_type      vector3_type;

  typedef convex::Simplex<vector3_type>    simplex_type;

  // First we create a simplex that represents an edge
  vector3_type const a = vector3_type::make(1.0, 0.0, 0.0);
  vector3_type const b = vector3_type::make(0.0, 0.0, 0.0);

  // First we use a test point that does not lie on the line

  // Front side of A voronoi plane
  {
    simplex_type S;

    convex::add_point_to_simplex( a, a, a, S);
    convex::add_point_to_simplex( b, b, b, S);

    vector3_type const p = vector3_type::make( 1.5, 1.0,  1.0);

    convex::reduce_edge( p, S );

    BOOST_CHECK( convex::dimension( S ) == 1u );

    int bit_A    = 0;
    size_t idx_A = 0;
    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );

    BOOST_CHECK(S.m_bitmask == bit_A );
    BOOST_CHECK(S.m_v[idx_A] == a);
    BOOST_CHECK(S.m_a[idx_A] == a);
    BOOST_CHECK(S.m_b[idx_A] == a);
    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);

  }
  // Back side of A voronoi plane
  {
    simplex_type S;

    convex::add_point_to_simplex( a, a, a, S);
    convex::add_point_to_simplex( b, b, b, S);

    vector3_type const p = vector3_type::make( 0.5, 1.0,  1.0);

    convex::reduce_edge( p, S );

    BOOST_CHECK( convex::dimension( S ) == 2u );

    int bit_A    = 0;
    size_t idx_A = 0;
    int bit_B    = 0;
    size_t idx_B = 0;
    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );

    BOOST_CHECK( S.m_bitmask == (bit_A | bit_B));

    BOOST_CHECK(S.m_v[idx_A] == a);
    BOOST_CHECK(S.m_a[idx_A] == a);
    BOOST_CHECK(S.m_b[idx_A] == a);
    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);

    BOOST_CHECK(S.m_v[idx_B] == b);
    BOOST_CHECK(S.m_a[idx_B] == b);
    BOOST_CHECK(S.m_b[idx_B] == b);
    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);
  }
  // In A voronoi plane
  {
    simplex_type S;

    convex::add_point_to_simplex( a, a, a, S);
    convex::add_point_to_simplex( b, b, b, S);

    vector3_type const p = vector3_type::make( 1.0, 1.0,  1.0);

    convex::reduce_edge( p, S );

    BOOST_CHECK( convex::dimension( S ) == 1u );

    int bit_A    = 0;
    size_t idx_A = 0;
    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );

    BOOST_CHECK(S.m_bitmask == bit_A );
    BOOST_CHECK(S.m_v[idx_A] == a);
    BOOST_CHECK(S.m_a[idx_A] == a);
    BOOST_CHECK(S.m_b[idx_A] == a);
    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);
  }

  // Front side of B voronoi plane
  {
    simplex_type S;

    convex::add_point_to_simplex( a, a, a, S);
    convex::add_point_to_simplex( b, b, b, S);

    vector3_type const p = vector3_type::make( -0.5, 1.0,  1.0);

    convex::reduce_edge( p, S );

    BOOST_CHECK( convex::dimension( S ) == 1u );

    int bit_A    = 0;
    size_t idx_A = 0;
    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );

    BOOST_CHECK(S.m_bitmask == bit_A );
    BOOST_CHECK(S.m_v[idx_A] == b);
    BOOST_CHECK(S.m_a[idx_A] == b);
    BOOST_CHECK(S.m_b[idx_A] == b);
    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);
  }
  // Back side of B voronoi plane
  {
    simplex_type S;

    convex::add_point_to_simplex( a, a, a, S);
    convex::add_point_to_simplex( b, b, b, S);

    vector3_type const p = vector3_type::make( 0.5, 1.0,  1.0);

    convex::reduce_edge( p, S );

    BOOST_CHECK( convex::dimension( S ) == 2u );

    int bit_A    = 0;
    size_t idx_A = 0;
    int bit_B    = 0;
    size_t idx_B = 0;
    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );

    BOOST_CHECK( S.m_bitmask == (bit_A | bit_B));

    BOOST_CHECK(S.m_v[idx_A] == a);
    BOOST_CHECK(S.m_a[idx_A] == a);
    BOOST_CHECK(S.m_b[idx_A] == a);
    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);

    BOOST_CHECK(S.m_v[idx_B] == b);
    BOOST_CHECK(S.m_a[idx_B] == b);
    BOOST_CHECK(S.m_b[idx_B] == b);
    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);
  }
  // In B voronoi plane
  {
    simplex_type S;

    convex::add_point_to_simplex( a, a, a, S);
    convex::add_point_to_simplex( b, b, b, S);

    vector3_type const p = vector3_type::make( 0.0, 1.0,  1.0);

    convex::reduce_edge( p, S );

    BOOST_CHECK( convex::dimension( S ) == 1u );

    int bit_A    = 0;
    size_t idx_A = 0;
    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );

    BOOST_CHECK(S.m_bitmask == bit_A );
    BOOST_CHECK(S.m_v[idx_A] == b);
    BOOST_CHECK(S.m_a[idx_A] == b);
    BOOST_CHECK(S.m_b[idx_A] == b);
    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);
  }

  // Second we use a test point that lies on the line

  // Front side of A voronoi plane
  {
    simplex_type S;

    convex::add_point_to_simplex( a, a, a, S);
    convex::add_point_to_simplex( b, b, b, S);

    vector3_type const p = vector3_type::make( 1.5, 0.0,  0.0);

    convex::reduce_edge( p, S );

    BOOST_CHECK( convex::dimension( S ) == 1u );

    int bit_A    = 0;
    size_t idx_A = 0;
    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );

    BOOST_CHECK(S.m_bitmask == bit_A );
    BOOST_CHECK(S.m_v[idx_A] == a);
    BOOST_CHECK(S.m_a[idx_A] == a);
    BOOST_CHECK(S.m_b[idx_A] == a);
    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);
  }
  // Back side of A voronoi plane
  {
    simplex_type S;

    convex::add_point_to_simplex( a, a, a, S);
    convex::add_point_to_simplex( b, b, b, S);

    vector3_type const p = vector3_type::make( 0.5, 0.0,  0.0);

    convex::reduce_edge( p, S );

    BOOST_CHECK( convex::dimension( S ) == 2u );

    int bit_A    = 0;
    size_t idx_A = 0;
    int bit_B    = 0;
    size_t idx_B = 0;
    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );

    BOOST_CHECK( S.m_bitmask == (bit_A | bit_B));

    BOOST_CHECK(S.m_v[idx_A] == a);
    BOOST_CHECK(S.m_a[idx_A] == a);
    BOOST_CHECK(S.m_b[idx_A] == a);
    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);

    BOOST_CHECK(S.m_v[idx_B] == b);
    BOOST_CHECK(S.m_a[idx_B] == b);
    BOOST_CHECK(S.m_b[idx_B] == b);
    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);
  }
  // In A voronoi plane
  {
    simplex_type S;

    convex::add_point_to_simplex( a, a, a, S);
    convex::add_point_to_simplex( b, b, b, S);

    vector3_type const p = vector3_type::make( 1.0, 0.0,  0.0);

    convex::reduce_edge( p, S );

    BOOST_CHECK( convex::dimension( S ) == 1u );

    int bit_A    = 0;
    size_t idx_A = 0;
    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );

    BOOST_CHECK(S.m_bitmask == bit_A );
    BOOST_CHECK(S.m_v[idx_A] == a);
    BOOST_CHECK(S.m_a[idx_A] == a);
    BOOST_CHECK(S.m_b[idx_A] == a);
    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);
  }

  // Front side of B voronoi plane
  {
    simplex_type S;

    convex::add_point_to_simplex( a, a, a, S);
    convex::add_point_to_simplex( b, b, b, S);

    vector3_type const p = vector3_type::make( -0.5, 0.0,  0.0);

    convex::reduce_edge( p, S );

    BOOST_CHECK( convex::dimension( S ) == 1u );

    int bit_A    = 0;
    size_t idx_A = 0;
    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );

    BOOST_CHECK(S.m_bitmask == bit_A );
    BOOST_CHECK(S.m_v[idx_A] == b);
    BOOST_CHECK(S.m_a[idx_A] == b);
    BOOST_CHECK(S.m_b[idx_A] == b);
    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);
  }
  // Back side of B voronoi plane
  {
    simplex_type S;

    convex::add_point_to_simplex( a, a, a, S);
    convex::add_point_to_simplex( b, b, b, S);

    vector3_type const p = vector3_type::make( 0.5, 0.0,  0.0);

    convex::reduce_edge( p, S );

    BOOST_CHECK( convex::dimension( S ) == 2u );

    int bit_A    = 0;
    size_t idx_A = 0;
    int bit_B    = 0;
    size_t idx_B = 0;
    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );

    BOOST_CHECK( S.m_bitmask == (bit_A | bit_B));

    BOOST_CHECK(S.m_v[idx_A] == a);
    BOOST_CHECK(S.m_a[idx_A] == a);
    BOOST_CHECK(S.m_b[idx_A] == a);
    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);

    BOOST_CHECK(S.m_v[idx_B] == b);
    BOOST_CHECK(S.m_a[idx_B] == b);
    BOOST_CHECK(S.m_b[idx_B] == b);
    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);
  }
  // In B voronoi plane
  {
    simplex_type S;

    convex::add_point_to_simplex( a, a, a, S);
    convex::add_point_to_simplex( b, b, b, S);

    vector3_type const p = vector3_type::make( 0.0, 0.0,  0.0);

    convex::reduce_edge( p, S );

    BOOST_CHECK( convex::dimension( S ) == 1u );

    int bit_A    = 0;
    size_t idx_A = 0;
    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );

    BOOST_CHECK(S.m_bitmask == bit_A );
    BOOST_CHECK(S.m_v[idx_A] == b);
    BOOST_CHECK(S.m_a[idx_A] == b);
    BOOST_CHECK(S.m_b[idx_A] == b);
    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);
  }

  // Assymetric test case when simplex is AB
  {
    simplex_type S;

    convex::add_point_to_simplex( a, a, a, S);
    convex::add_point_to_simplex( b, b, b, S);

    vector3_type const p = (2.0*a + 3.0*b)/5.0;

    convex::reduce_edge( p, S );

    BOOST_CHECK( convex::dimension( S ) == 2u );

    int bit_A    = 0;
    size_t idx_A = 0;
    int bit_B    = 0;
    size_t idx_B = 0;
    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );

    BOOST_CHECK( S.m_bitmask == (bit_A | bit_B));

    BOOST_CHECK(S.m_v[idx_A] == a);
    BOOST_CHECK(S.m_a[idx_A] == a);
    BOOST_CHECK(S.m_b[idx_A] == a);
    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.4, 0.01);

    BOOST_CHECK(S.m_v[idx_B] == b);
    BOOST_CHECK(S.m_a[idx_B] == b);
    BOOST_CHECK(S.m_b[idx_B] == b);
    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.6, 0.01);
  }
}

BOOST_AUTO_TEST_SUITE_END();