Exemplo n.º 1
0
double spatial_Bspline03_integralf(double alpha)
{
    XX(global_aux) = XX(global_r) + alpha * XX(global_u);
    YY(global_aux) = YY(global_r) + alpha * YY(global_u);
    ZZ(global_aux) = ZZ(global_r) + alpha * ZZ(global_u);
    return spatial_Bspline03LUT(global_aux);
}
Exemplo n.º 2
0
static long ZZ_remove(struct ZZ &dest, const struct ZZ &src, const struct ZZ &f)
{
    // Based on the code for mpz_remove
    ZZ fpow[40];            // inexaustible...until year 2020 or so
    ZZ x, rem;
    long pwr;
    int p;

    if (compare(f, 1) <= 0 && compare(f, -1) >= 0)
        Error("Division by zero");

    if (compare(src, 0) == 0)
    {
        if (src != dest)
           dest = src;
        return 0;
    }

    if (compare(f, 2) == 0)
    {
        dest = src;
        return MakeOdd(dest);
    }

    /* We could perhaps compute mpz_scan1(src,0)/mpz_scan1(f,0).  It is an
     upper bound of the result we're seeking.  We could also shift down the
     operands so that they become odd, to make intermediate values smaller.  */

    pwr = 0;
    fpow[0] = ZZ(f);
    dest = src;
    rem = ZZ();
    x = ZZ();

    /* Divide by f, f^2, ..., f^(2^k) until we get a remainder for f^(2^k).  */
    for (p = 0;;p++)
    {
        DivRem(x, rem, dest, fpow[p]);
        if (compare(rem, 0) != 0)
            break;
        fpow[p+1] = ZZ();
        NTL::mul(fpow[p+1], fpow[p], fpow[p]);
        dest = x;
    }

    pwr = (1 << p) - 1;

    /* Divide by f^(2^(k-1)), f^(2^(k-2)), ..., f for all divisors that give a
       zero remainder.  */
    while (--p >= 0)
    {
        DivRem(x, rem, dest, fpow[p]);
        if (compare(rem, 0) == 0)
        {
            pwr += 1 << p;
            dest = x;
        }
    }
    return pwr;
}
Exemplo n.º 3
0
// Remove wedge ------------------------------------------------------------
void MissingWedge::removeWedge(MultidimArray<double> &V) const
{
    Matrix2D<double> Epos, Eneg;
    Euler_angles2matrix(rotPos,tiltPos,0,Epos);
    Euler_angles2matrix(rotNeg,tiltNeg,0,Eneg);
    
    Matrix1D<double> freq(3), freqPos, freqNeg;
    Matrix1D<int> idx(3);

    FourierTransformer transformer;
    MultidimArray< std::complex<double> > Vfft;
    transformer.FourierTransform(V,Vfft,false);

    FOR_ALL_ELEMENTS_IN_ARRAY3D(Vfft)
    {
        // Frequency in the coordinate system of the volume
        VECTOR_R3(idx,j,i,k);
        FFT_idx2digfreq(V,idx,freq);

        // Frequency in the coordinate system of the plane
        freqPos=Epos*freq;
        freqNeg=Eneg*freq;
        if (ZZ(freqPos)<0 || ZZ(freqNeg)>0)
            Vfft(k,i,j)=0;
    }
    transformer.inverseFourierTransform();
}
Exemplo n.º 4
0
// Computes sum of the values of a unitary blob on grid points. The blob is
// supposed to be at the origin of the absolute coordinate system
double sum_blob_SimpleGrid(const struct blobtype &blob, const SimpleGrid &grid,
                           const Matrix2D<double> *D)
{
    SPEED_UP_temps012;
    Matrix1D<double> gr(3), ur(3), corner1(3), corner2(3);
    double         actual_radius;
    int          i, j, k;
    double        sum = 0.0;

    // Compute the limits of the blob in the grid coordinate system
    grid.universe2grid(vectorR3(-blob.radius, -blob.radius, -blob.radius), corner1);
    grid.universe2grid(vectorR3(blob.radius, blob.radius, blob.radius), corner2);
    if (D != NULL)
        box_enclosing(corner1, corner2, *D, corner1, corner2);

    // Compute the sum in the points inside the grid
    // The integer part of the vectors is taken for not picking points
    // just in the border of the blob, which we know they are 0.
    for (i = (int)XX(corner1); i <= (int)XX(corner2); i++)
        for (j = (int)YY(corner1); j <= (int)YY(corner2); j++)
            for (k = (int)ZZ(corner1); k <= (int)ZZ(corner2); k++)
            {
                VECTOR_R3(gr, i, j, k);
                grid.grid2universe(gr, ur);
                if (D != NULL)
                    M3x3_BY_V3x1(ur, *D, ur);
                actual_radius = ur.module();
                if (actual_radius < blob.radius)
                    sum += kaiser_value(actual_radius,
                                        blob.radius, blob.alpha, blob.order);
            }
    return sum;
}
Exemplo n.º 5
0
// Sets the prime defining the field for the curve and stores certain values
void Icart::setPrime(ZZ* p)
{
    //ZZ_p::init(*p);
    // Icart hash function uses 1/3 root, which is equivalent to (2p-1)/3
    exp = MulMod( SubMod( MulMod(ZZ(2), *p, *p), ZZ(1), *p), InvMod(ZZ(3),*p), *p);
    // Store inverse values to be used later
    ts = inv(ZZ_p(27));
    th = inv(ZZ_p(3));
}
Exemplo n.º 6
0
int main()
{
   setbuf(stdout, NULL);

   for (long l = 256; l <= 16384; l *= 2) {
      // for (long n = 256; n <= 16384; n *= 2) {
      for (long idx = 0; idx < 13; idx ++) {
         long n  = 256*(1L << idx/2);
         if (idx & 1) n += n/2;
           SetSeed((ZZ(l) << 64) + ZZ(n));

	   ZZX a, b, c;

           a.SetLength(n);
           for (long i = 0; i < n; i++) RandomBits(a[i], l);
           a.normalize();

           b.SetLength(n);
           for (long i = 0; i < n; i++) RandomBits(b[i], l);
           b.normalize();


	   double t;

	   mul(c, a, b);

	   long iter = 1;
	   do {
	      t = GetTime();
	      for (long i = 0; i < iter; i++) mul(c, a, b);
	      t = GetTime() - t;
	      iter *= 2;
	   } while (t < 3);
	   iter /= 2;

	   t = GetTime();
	   for (long i = 0; i < iter; i++) mul(c, a, b);
	   t = GetTime()-t;
	   double NTLTime = t;


	   FlintZZX f_a(a), f_b(b), f_c(c);


	   fmpz_poly_mul(f_c.value, f_a.value, f_b.value);
	   t = GetTime();
	   for (long i = 0; i < iter; i++) fmpz_poly_mul(f_c.value, f_a.value, f_b.value);
	   t = GetTime()-t;
	   double FlintTime = t;

           printf("%8.2f", FlintTime/NTLTime);
      }

      printf("\n");
   }
}
Exemplo n.º 7
0
// Apply transformation ---------------------------------------------------
void applyTransformation(const MultidimArray<double> &V2,
                         MultidimArray<double> &Vaux,
                         double *p)
{
    Matrix1D<double> r(3);
    Matrix2D<double> A, Aaux;

    double greyScale = p[0];
    double greyShift = p[1];
    double rot       = p[2];
    double tilt      = p[3];
    double psi       = p[4];
    double scale     = p[5];
    ZZ(r)            = p[6];
    YY(r)            = p[7];
    XX(r)            = p[8];

    Euler_angles2matrix(rot, tilt, psi, A, true);
    translation3DMatrix(r,Aaux);
    A = A * Aaux;
    scale3DMatrix(vectorR3(scale, scale, scale),Aaux);
    A = A * Aaux;

    applyGeometry(LINEAR, Vaux, V2, A, IS_NOT_INV, WRAP);
    if (greyScale!=1 || greyShift!=0)
        FOR_ALL_DIRECT_ELEMENTS_IN_MULTIDIMARRAY(Vaux)
        DIRECT_MULTIDIM_ELEM(Vaux,n)=DIRECT_MULTIDIM_ELEM(Vaux,n)*greyScale+greyShift;
}
Exemplo n.º 8
0
static int bloch_jacobian(long int N, realtype t,
        N_Vector M, N_Vector fM, DlsMat J, void *user_data,
        N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)
{
    struct bloch_sim *bs = (struct bloch_sim*)user_data;

    int i;
    for (i=0; i < bs->num_cells; ++i)
    {
        realtype dw = bs->cell_frequencies[i] - bs->w_avg;
        realtype w_1 = bs->rf_on ? bs->w_1 : 0.0;

        XX(J,i) = -1 / bs->T_2;
        XY(J,i) = dw;
        XZ(J,i) = 0.0;
        YX(J,i) = -dw;
        YY(J,i) = -1 / bs->T_2;
        YZ(J,i) = w_1;
        ZX(J,i) = 0.0;
        ZY(J,i) = -w_1;
        ZZ(J,i) = -1 / bs->T_1;
    }

    return 0;
}
Exemplo n.º 9
0
 static pair<ZZ,int> factModExp(int n) {
         if (n == 0) return MP(1, 0);
         int e = n / MOD;
         pair<ZZ,int> pr = factModExp(e);
         if (e % 2) {
                 return MP(ZZ(0) - pr.first * fact(n % MOD), pr.second + e);
         } else {
                 return MP(pr.first * fact(n % MOD), pr.second + e);
         }
 }
Exemplo n.º 10
0
int main(int argc, char *argv[]) 
{
  ArgMapping amap;

  long p=2;
  long r=1;
  long c=3;
  long L=600;
  long N=0;
  long t=0;
  long nthreads=1;

  long seed=0;
  long useCache=1;

  amap.arg("p", p, "plaintext base");

  amap.arg("r", r,  "exponent");
  amap.note("p^r is the plaintext-space modulus");

  amap.arg("c", c, "number of columns in the key-switching matrices");
  amap.arg("L", L, "# of levels in the modulus chain");
  amap.arg("N", N, "lower-bound on phi(m)");
  amap.arg("t", t, "Hamming weight of recryption secret key", "heuristic");
  amap.arg("dry", dry, "dry=1 for a dry-run");
  amap.arg("nthreads", nthreads, "number of threads");
  amap.arg("seed", seed, "random number seed");
  amap.arg("noPrint", noPrint, "suppress printouts");
  amap.arg("useCache", useCache, "0: zzX cache, 1: DCRT cache");

  amap.arg("force_bsgs", fhe_test_force_bsgs);
  amap.arg("force_hoist", fhe_test_force_hoist);

  //  amap.arg("disable_intFactor", fhe_disable_intFactor);
  amap.arg("chen_han", fhe_force_chen_han);

  amap.arg("debug", debug, "generate debugging output");
  amap.arg("scale", scale, "scale parameter");


  amap.parse(argc, argv);

  if (seed) 
    SetSeed(ZZ(seed));

  SetNumThreads(nthreads);

  for (long i=0; i<(long)num_mValues; i++)
    if (mValues[i][0]==p && mValues[i][1]>=N) {
      TestIt(i,p,r,L,c,t,useCache);
      break;
    }

  return 0;
}
Exemplo n.º 11
0
std::string Ioss::Sym_Tensor_31::label(int which, const char) const
{
  assert(which > 0 && which <= component_count());
  switch(which) {
  case 1:  return XX();
  case 2:  return YY();
  case 3:  return ZZ();
  case 4:  return XY();
  default:  return "";
  }
}
Exemplo n.º 12
0
/* Sum spline on a grid ---------------------------------------------------- */
double sum_spatial_Bspline03_SimpleGrid(const SimpleGrid &grid)
{
    Matrix1D<double> gr(3), ur(3), corner1(3), corner2(3);
    int          i, j, k;
    double        sum = 0.0;

// Compute the limits of the spline in the grid coordinate system
    grid.universe2grid(vectorR3(-2.0, -2.0, -2.0), corner1);
    grid.universe2grid(vectorR3(2.0, 2.0, 2.0), corner2);

// Compute the sum in the points inside the grid
// The integer part of the vectors is taken for not picking points
// just in the border of the spline, which we know they are 0.
    for (i = (int)XX(corner1); i <= (int)XX(corner2); i++)
        for (j = (int)YY(corner1); j <= (int)YY(corner2); j++)
            for (k = (int)ZZ(corner1); k <= (int)ZZ(corner2); k++)
            {
                VECTOR_R3(gr, i, j, k);
                grid.grid2universe(gr, ur);
                sum += spatial_Bspline03(ur);
            }
    return sum;
}
Exemplo n.º 13
0
// Draw wedge --------------------------------------------------------------
void drawWedge(double rotPos, double tiltPos, double rotNeg, double tiltNeg,
               const MultidimArray<double> *V,
               const MultidimArray<double> *Vmag, MultidimArray<double> *Vdraw)
{
    Matrix2D<double> Epos, Eneg;
    Euler_angles2matrix(rotPos,tiltPos,0,Epos);
    Euler_angles2matrix(rotNeg,tiltNeg,0,Eneg);

    Matrix1D<double> freq(3), freqPos, freqNeg;
    Matrix1D<int> idx(3);
    Vdraw->initZeros(*Vmag);
    FOR_ALL_ELEMENTS_IN_ARRAY3D(*Vdraw)
    {
        // Frequency in the coordinate system of the volume
        VECTOR_R3(idx,j,i,k);
        FFT_idx2digfreq(*V,idx,freq);

        // Frequency in the coordinate system of the plane
        freqPos=Epos*freq;
        freqNeg=Eneg*freq;
        if (ZZ(freqPos)<0 || ZZ(freqNeg)>0)
            (*Vdraw)(k,i,j)+=1;
    }
}
 ISOIEC_DSS(const DSSDomainParameters<EC_Dscr> & DomainParameters,
            generateRandomValueCallback & PRNG)
     : _DomainParameters(DomainParameters),
       _Curve(_DomainParameters.EC),
       _PCurve(_DomainParameters.EC),
       _privateKey(ZZ()),
       _publicKey(_PCurve.create()),
       _isPrivateKeyLoaded(false),
       _isPublicKeyLoaded(false),
       _Ln(L(_DomainParameters.EC.getOrder())),
       _Lcm(L(_DomainParameters.EC.getModulus())),
       _BasePoint(_PCurve.getBasePoint()),
       _PRNG(PRNG)
     {
         /* TODO: Input policy sanity checks */
     }
Exemplo n.º 15
0
std::string Ioss::Matrix_33::label(int which, const char) const
{
  assert(which > 0 && which <= component_count());
  switch(which) {
  case 1:  return XX();
  case 2:  return XY();
  case 3:  return XZ();
  case 4:  return YX();
  case 5:  return YY();
  case 6:  return YZ();
  case 7:  return ZX();
  case 8:  return ZY();
  case 9:  return ZZ();
  default: return "";
  }
}
Exemplo n.º 16
0
// Icart's hash function
EPoint Icart::hash(ZZ_p u)
{
    // 0 maps to the point at infinity
    if (IsZero(u))
    {
        return EPoint(ZZ_p(0), ZZ_p(0), true);
    }

    // v = (3a - u^4) / 6u
    ZZ_p v = ((ZZ_p(3) * a) - power(u, 4)) * inv(ZZ_p(6) * u);
    // x = (v^2 - b - u^6/27)^(1/3) + u^2/3
    ZZ_p x = power( sqr(v) - b - (power(u, ZZ(6)) * ts), exp) + (sqr(u) * th);
    // y = ux + v
    ZZ_p y = (u * x) + v;

    return EPoint(x, y, false);
}
Exemplo n.º 17
0
// Write PDB format
void Assembly::writePDB(std::string filename)
{
    FILE *file;
    file = fopen(filename.c_str(), "w");
    if (file==NULL)
        REPORT_ERROR("Error writing file: " + filename);

    fprintf(file, "%s\n", "REMARK Created by DsigNA");
    long int atomnum = 0;
    for (int imol = 0; imol < molecules.size(); imol++)
    {
        for (int ires = 0; ires < molecules[imol].residues.size(); ires++)
        {
            for (int iatom = 0; iatom < molecules[imol].residues[ires].atoms.size(); iatom++, atomnum++)
            {
                // If more than 100,000 atoms: just start counting at one again.
                if (atomnum > 99999)
                    atomnum -= 99999;
                char chainID = molecules[imol].name[0];
                fprintf(file, "ATOM  %5d %-4s %3s %1c%4d    %8.3f%8.3f%8.3f%6.2f%6.2f      %4s\n",
                                                  atomnum, molecules[imol].residues[ires].atoms[iatom].name.c_str(), molecules[imol].residues[ires].name.c_str(),
                                                  chainID, molecules[imol].residues[ires].number,
                                                  XX(molecules[imol].residues[ires].atoms[iatom].coords),
                                                  YY(molecules[imol].residues[ires].atoms[iatom].coords),
                                                  ZZ(molecules[imol].residues[ires].atoms[iatom].coords),
                                                  molecules[imol].residues[ires].atoms[iatom].occupancy,
                                                  molecules[imol].residues[ires].atoms[iatom].bfactor,
                                                  molecules[imol].name.c_str());
            }
        }
        if (imol + 1 < molecules.size())
            fprintf(file, "%s\n", "TER");
    }

    fprintf(file, "%s\n", "END");
    fclose(file);
}
Exemplo n.º 18
0
void Coordinates::update(void)
{
   Matrix M1, M2;
   
   selfTest();
   
   M1.loadIdentity(); M1.translate(On);
   M2.newUVN(Xn,Yn,Zn);
   mO2N = M1 * M2;//Old->New
  
   Vector XX(1,0,0),YY(0,1,0),ZZ(0,0,1);
   fPoint o(0,0,0);
   o = o * mO2N; 
   M1.loadIdentity(); M1.translate(o);
   XX = XX * mO2N; YY = YY * mO2N; ZZ = ZZ * mO2N;
     /*
     printf("\n------On------\n");o.outputs();
     printf("\n------XXn------\n");XX.outputs();
     printf("\n------YYn------\n");YY.outputs();
     printf("\n------ZZn------\n");ZZ.outputs();
     */
   M2.newUVN(XX,YY,ZZ);
   mN2O = M1 * M2;//New -> Old
}
Exemplo n.º 19
0
void ProgAngularProjectLibrary::project_angle_vector (int my_init, int my_end, bool verbose)
{
    Projection P;
    FileName fn_proj;
    double rot,tilt,psi;
    int mySize;
    int numberStepsPsi = 1;

    mySize=my_end-my_init+1;
    if (psi_sampling < 360)
    {
        numberStepsPsi = (int) (359.99999/psi_sampling);
        mySize *= numberStepsPsi;
    }

    if (verbose)
        init_progress_bar(mySize);
    int myCounter=0;


    for (double mypsi=0;mypsi<360;mypsi += psi_sampling)
        for (int i=0;i<my_init;i++)
            myCounter++;

//    if (shears && XSIZE(inputVol())!=0 && VShears==NULL)
//        VShears=new RealShearsInfo(inputVol());
    if (projType == SHEARS && XSIZE(inputVol())!=0 && Vshears==NULL)
        Vshears=new RealShearsInfo(inputVol());
    if (projType == FOURIER && XSIZE(inputVol())!=0 && Vfourier==NULL)
        Vfourier=new FourierProjector(inputVol(),
        		                      paddFactor,
        		                      maxFrequency,
        		                      BSplineDeg);

    for (double mypsi=0;mypsi<360;mypsi += psi_sampling)
    {
        for (int i=my_init;i<=my_end;i++)
        {
            if (verbose)
                progress_bar(i-my_init);
            psi= mypsi+ZZ(mysampling.no_redundant_sampling_points_angles[i]);
            tilt=      YY(mysampling.no_redundant_sampling_points_angles[i]);
            rot=       XX(mysampling.no_redundant_sampling_points_angles[i]);

//            if (shears)
//                projectVolume(*VShears, P, Ydim, Xdim, rot,tilt,psi);
//            else
//                projectVolume(inputVol(), P, Ydim, Xdim, rot,tilt,psi);
            if (projType == SHEARS)
                projectVolume(*Vshears, P, Ydim, Xdim,   rot, tilt, psi);
            else if (projType == FOURIER)
                projectVolume(*Vfourier, P, Ydim, Xdim,  rot, tilt, psi);
            else if (projType == REALSPACE)
                projectVolume(inputVol(), P, Ydim, Xdim, rot, tilt, psi);


            P.setEulerAngles(rot,tilt,psi);
            P.setDataMode(_DATA_ALL);
            P.write(output_file,(size_t) (numberStepsPsi * i + mypsi +1),true,WRITE_REPLACE);
        }
    }
    if (verbose)
        progress_bar(mySize);
}
Exemplo n.º 20
0
NTL_CLIENT



//namespace NTL { extern double ip_time; }

int main(int argc, char **argv)
{
   ArgMapping amap;

   long n = 1024;
   amap.arg("n", n, "degree bound");

   long l = 1024;
   amap.arg("l", l, "coeff bound");

   long nt = 1;
   amap.arg("nt", nt, "num threads");

   amap.parse(argc, argv);

   cerr << "\n\n=============================\n\n";

   cerr << "n=" << n << "\n";
   cerr << "l=" << l << "\n";
   cerr << "nt=" << nt << "\n";

   SetSeed(ZZ(0));

   SetNumThreads(nt);

   ZZ p;

   RandomPrime(p, l);
   ZZ_p::init(p);


   ZZ_pX f;

   random(f, n);
   SetCoeff(f, n);

   Vec< Pair<ZZ_pX, long> > fac;


   double t;

   ZZ_pXFileThresh = 1e9;



   FILE *fp;
   unsigned long A[4], B[4];
   int loadavg;

   fp = fopen("/proc/stat","r");
   fscanf(fp,"cpu %lu %lu %lu %lu",&A[0],&A[1],&A[2],&A[3]);
   fclose(fp);
   
   
   t = GetTime();
   CanZass(fac, f, 1);
   t = GetTime()-t;
   double NTLTime = t;

   fp = fopen("/proc/stat","r");
   fscanf(fp,"cpu %lu %lu %lu %lu",&B[0],&B[1],&B[2],&B[3]);
   fclose(fp);
   
   // we multiply by 20 -- that's the total number of cores
   loadavg = int(100.0*20.0*double((B[0]+B[1]+B[2]) - (A[0]+A[1]+A[2])) / 
      double((B[0]+B[1]+B[2]+B[3]) - (A[0]+A[1]+A[2]+A[3])));
   fprintf(stderr, "CPU utilization: %d\%\n",loadavg);

   struct rusage rusage;
   getrusage( RUSAGE_SELF, &rusage );

   cerr << "MAX_RSS="<<rusage.ru_maxrss <<  "KB" << endl;
   cerr << "Fac: " << t << "\n";

   //cerr << "ip_time: " << ip_time << "\n";

   delete NTLThreadPool;
   NTLThreadPool = 0;


}
Exemplo n.º 21
0
void * blobs2voxels_SimpleGrid( void * data )
{
    ThreadBlobsToVoxels * thread_data = (ThreadBlobsToVoxels *) data;

    const MultidimArray<double> *vol_blobs = thread_data->vol_blobs;
    const SimpleGrid *grid = thread_data->grid;
    const struct blobtype *blob = thread_data->blob;
    MultidimArray<double> *vol_voxels = thread_data->vol_voxels;
    const Matrix2D<double> *D = thread_data->D;
    int istep = thread_data->istep;
    MultidimArray<double> *vol_corr = thread_data->vol_corr;
    const MultidimArray<double> *vol_mask = thread_data->vol_mask;
    ;
    bool FORW = thread_data->FORW;
    int eq_mode = thread_data->eq_mode;

    int min_separation = thread_data->min_separation;

    int z_planes = (int)(ZZ(grid->highest) - ZZ(grid->lowest) + 1);

    Matrix2D<double> Dinv;                   // Inverse of D
    Matrix1D<double> act_coord(3);           // Coord: Actual position inside
    // the voxel volume without deforming
    Matrix1D<double> real_position(3);       // Coord: actual position after
    // applying the V transformation
    Matrix1D<double> beginZ(3);              // Coord: Voxel coordinates of the
    // blob at the 3D point
    // (z0,YY(lowest),XX(lowest))
    Matrix1D<double> beginY(3);              // Coord: Voxel coordinates of the
    // blob at the 3D point
    // (z0,y0,XX(lowest))
    Matrix1D<double> corner2(3), corner1(3); // Coord: Corners of the
    // blob in the voxel volume
    Matrix1D<double> gcurrent(3);            // Position in g of current point
    MultidimArray<double> blob_table;             // Something like a blobprint
    // but with the values of the
    // blob in space
    double         d;                        // Distance between the center
    // of the blob and a voxel position
    int           id;                        // index inside the blob value
    // table for tha blob value at
    // a distance d
    double         intx, inty, intz;         // Nearest integer voxel
    int           i, j, k;                   // Index within the blob volume
    int           process;                   // True if this blob has to be
    // processed
    double         vol_correction=0;         // Correction to apply to the
    // volume when "projecting" back
    SPEED_UP_temps012;

    // Some aliases
#define x0 STARTINGX(*vol_voxels)
#define xF FINISHINGX(*vol_voxels)
#define y0 STARTINGY(*vol_voxels)
#define yF FINISHINGY(*vol_voxels)
#define z0 STARTINGZ(*vol_voxels)
#define zF FINISHINGZ(*vol_voxels)

#ifdef DEBUG

    bool condition = !FORW;
    if (condition)
    {
        (*vol_voxels)().printShape();
        std::cout << std::endl;
        std::cout << "x0= " << x0 << " xF= " << xF << std::endl;
        std::cout << "y0= " << y0 << " yF= " << yF << std::endl;
        std::cout << "z0= " << z0 << " zF= " << zF << std::endl;
        std::cout << grid;
    }
#endif

    // Invert deformation matrix ............................................
    if (D != NULL)
        Dinv = D->inv();

    // Compute a blob value table ...........................................
    blob_table.resize((int)(blob->radius*istep + 1));
    for (size_t i = 0; i < blob_table.xdim; i++)
    {
        A1D_ELEM(blob_table, i) = kaiser_value((double)i/istep, blob->radius, blob->alpha, blob->order);

#ifdef DEBUG_MORE

        if (condition)
            std::cout << "Blob (" << i << ") r=" << (double)i / istep <<
            " val= " << A1D_ELEM(blob_table, i) << std::endl;
#endif

    }

    int assigned_slice;

    do
    {
        assigned_slice = -1;
        do
        {
            pthread_mutex_lock(&blobs_conv_mutex);
            if( slices_processed == z_planes )
            {
                pthread_mutex_unlock(&blobs_conv_mutex);
                return (void*)NULL;
            }

            for(int w = 0 ; w < z_planes ; w++ )
            {
                if( slices_status[w]==0 )
                {
                    slices_status[w] = -1;
                    assigned_slice = w;
                    slices_processed++;

                    for( int in = (w-min_separation+1) ; in <= (w+min_separation-1 ) ; in ++ )
                    {
                        if( in != w )
                        {
                            if( ( in >= 0 ) && ( in < z_planes ))
                            {
                                if( slices_status[in] != -1 )
                                    slices_status[in]++;
                            }
                        }
                    }
                    break;
                }
            }

            pthread_mutex_unlock(&blobs_conv_mutex);
        }
        while( assigned_slice == -1);

        // Convert the whole grid ...............................................
        // Corner of the plane defined by Z. These coordinates are in the
        // universal coord. system
        Matrix1D<double> aux( grid->lowest );
        k = (int)(assigned_slice + ZZ( grid->lowest ));
        ZZ(aux) = k;
        grid->grid2universe(aux, beginZ);

        Matrix1D<double> grid_index(3);

        // Corner of the row defined by Y
        beginY = beginZ;
        for (i = (int) YY(grid->lowest); i <= (int) YY(grid->highest); i++)
        {
            // First point in the row
            act_coord = beginY;
            for (j = (int) XX(grid->lowest); j <= (int) XX(grid->highest); j++)
            {
                VECTOR_R3(grid_index, j, i, k);
#ifdef DEBUG

                if (condition)
                {
                    printf("Dealing blob at (%d,%d,%d) = %f\n", j, i, k, A3D_ELEM(*vol_blobs, k, i, j));
                    std::cout << "Center of the blob      "
                    << act_coord.transpose() << std::endl;
                }
#endif

                // Place act_coord in its right place
                if (D != NULL)
                {
                    M3x3_BY_V3x1(real_position, *D, act_coord);
#ifdef DEBUG

                    if (condition)
                        std::cout << "Center of the blob moved to "
                        //ROB, the "moved" coordinates are in
                        // real_position not in act_coord
                        << act_coord.transpose() << std::endl;
                    << real_position.transpose() << std::endl;
#endif
                    // ROB This is OK if blob.radius is in Cartesian space as I
                    // think is the case
                }
                else
                    real_position = act_coord;

                // These two corners are also real valued
                process = true;
                //ROB
                //This is OK if blob.radius is in Cartesian space as I think is the case
                V3_PLUS_CT(corner1, real_position, -blob->radius);
                V3_PLUS_CT(corner2, real_position, blob->radius);
#ifdef DEFORM_BLOB_WHEN_IN_CRYSTAL
                //ROB
                //we do not need this, it is already in Cartesian space
                //if (D!=NULL)
                //   box_enclosing(corner1,corner2, *D, corner1, corner2);
#endif

                if (XX(corner1) >= xF)
                    process = false;
                if (YY(corner1) >= yF)
                    process = false;
                if (ZZ(corner1) >= zF)
                    process = false;
                if (XX(corner2) <= x0)
                    process = false;
                if (YY(corner2) <= y0)
                    process = false;
                if (ZZ(corner2) <= z0)
                    process = false;
#ifdef DEBUG

                if (!process && condition)
                    std::cout << "   It is outside output volume\n";
#endif

                if (!grid->is_interesting(real_position))
                {
#ifdef DEBUG
                    if (process && condition)
                        std::cout << "   It is not interesting\n";
#endif

                    process = false;
                }

#ifdef DEBUG
                if (condition)
                {
                    std::cout << "Corner 1 for this point " << corner1.transpose() << std::endl;
                    std::cout << "Corner 2 for this point " << corner2.transpose() << std::endl;
                }
#endif

                if (process)
                {
                    // Clip the corners to the volume borders
                    XX(corner1) = ROUND(CLIP(XX(corner1), x0, xF));
                    YY(corner1) = ROUND(CLIP(YY(corner1), y0, yF));
                    ZZ(corner1) = ROUND(CLIP(ZZ(corner1), z0, zF));
                    XX(corner2) = ROUND(CLIP(XX(corner2), x0, xF));
                    YY(corner2) = ROUND(CLIP(YY(corner2), y0, yF));
                    ZZ(corner2) = ROUND(CLIP(ZZ(corner2), z0, zF));
#ifdef DEBUG

                    if (condition)
                    {
                        std::cout << "Clipped and rounded Corner 1 " << corner1.transpose() << std::endl;
                        std::cout << "Clipped and rounded Corner 2 " << corner2.transpose() << std::endl;
                    }
#endif

                    if (!FORW)
                        switch (eq_mode)
                        {
                        case VARTK:
                            vol_correction = 0;
                            break;
                        case VMAXARTK:
                            vol_correction = -1e38;
                            break;
                        }

                    // Effectively convert
                    long N_eq;
                    N_eq = 0;
                    for (intz = ZZ(corner1); intz <= ZZ(corner2); intz++)
                        for (inty = YY(corner1); inty <= YY(corner2); inty++)
                            for (intx = XX(corner1); intx <= XX(corner2); intx++)
                            {
                                int iz = (int)intz, iy = (int)inty, ix = (int)intx;
                                if (vol_mask != NULL)
                                    if (!A3D_ELEM(*vol_mask, iz, iy, ix))
                                        continue;

                                // Compute distance to the center of the blob
                                VECTOR_R3(gcurrent, intx, inty, intz);
#ifdef DEFORM_BLOB_WHEN_IN_CRYSTAL
                                // ROB
                                //if (D!=NULL)
                                //   M3x3_BY_V3x1(gcurrent,Dinv,gcurrent);
#endif

                                V3_MINUS_V3(gcurrent, real_position, gcurrent);
                                d = sqrt(XX(gcurrent) * XX(gcurrent) +
                                         YY(gcurrent) * YY(gcurrent) +
                                         ZZ(gcurrent) * ZZ(gcurrent));
                                if (d > blob->radius)
                                    continue;
                                id = (int)(d * istep);
#ifdef DEBUG_MORE

                                if (condition)
                                {
                                    std::cout << "At (" << intx << ","
                                    << inty << "," << intz << ") distance=" << d;
                                    std::cout.flush();
                                }
#endif

                                // Add at that position the corresponding blob value

                                if (FORW)
                                {
                                    A3D_ELEM(*vol_voxels, iz, iy, ix) +=
                                        A3D_ELEM(*vol_blobs, k, i, j) *
                                        A1D_ELEM(blob_table, id);
#ifdef DEBUG_MORE

                                    if (condition)
                                    {
                                        std::cout << " adding " << A3D_ELEM(*vol_blobs, k, i, j)
                                        << " * " << A1D_ELEM(blob_table, id) << " = "
                                        << A3D_ELEM(*vol_blobs, k, i, j)*
                                        A1D_ELEM(blob_table, id) << std::endl;
                                        std::cout.flush();
                                    }
#endif
                                    if (vol_corr != NULL)
                                        A3D_ELEM(*vol_corr, iz, iy, ix) +=
                                            A1D_ELEM(blob_table, id) * A1D_ELEM(blob_table, id);
                                }
                                else
                                {
                                    double contrib = A3D_ELEM(*vol_corr, iz, iy, ix) *
                                                     A1D_ELEM(blob_table, id);
                                    switch (eq_mode)
                                    {
                                    case VARTK:
                                        vol_correction += contrib;
                                        N_eq++;
                                        break;
                                    case VMAXARTK:
                                        if (contrib > vol_correction)
                                            vol_correction = contrib;
                                        break;

                                    }
#ifdef DEBUG_MORE
                                    if (condition)
                                    {
                                        std::cout << " adding " << A3D_ELEM(*vol_corr, iz, iy, ix)
                                        << " * " << A1D_ELEM(blob_table, id) << " = "
                                        << contrib << std::endl;
                                        std::cout.flush();
                                    }
#endif

                                }
                            }
                    if (N_eq == 0)
                        N_eq = 1;
                    if (!FORW)
                    {
                        A3D_ELEM(*vol_blobs, k, i, j) += vol_correction / N_eq;
#ifdef DEBUG_MORE

                        std::cout << " correction= " << vol_correction << std::endl
                        << " Number of eqs= " << N_eq << std::endl
                        << " Blob after correction= "
                        << A3D_ELEM(*vol_blobs, k, i, j) << std::endl;
#endif

                    }
                }

                // Prepare for next iteration
                XX(act_coord) = XX(act_coord) + grid->relative_size * (grid->basis)( 0, 0);
                YY(act_coord) = YY(act_coord) + grid->relative_size * (grid->basis)( 1, 0);
                ZZ(act_coord) = ZZ(act_coord) + grid->relative_size * (grid->basis)( 2, 0);
            }
Exemplo n.º 22
0
int main()
{

#ifdef NTL_LONG_LONG


   if (sizeof(NTL_LL_TYPE) < 2*sizeof(long)) {
      printf("999999999999999 ");
      print_flag();
      return 0;
   }

#endif

   SetSeed(ZZ(0));

   long i, k;

   
   k = 10*NTL_ZZ_NBITS;

   for (i = 0; i < 10000; i++) {
      ZZ a, b, c, d;
      long da = RandomBnd(k);
      long db = RandomBnd(k);
      long dc = RandomBnd(k);
      long dd = RandomBnd(k);
      RandomLen(a, da);  RandomLen(b, db);  RandomLen(c, dc);  RandomLen(d, dd);

      if ((a + b)*(c + d) != c*a + d*a + c*b + d*b) {
	 printf("999999999999999 ");
	 print_flag();
	 return 0;
      }
   }

   

   for (i = 0; i < 10000; i++) {
      ZZ a, b, c;
      
      long da = RandomBnd(k);
      long db = RandomBnd(k);
      long dc = RandomBnd(k) + 2;
      
      RandomLen(a, da);  RandomLen(b, db);  RandomLen(c, dc); 

      if ( ( a * b ) % c != ((a % c) * (b % c)) % c ) {
	 printf("999999999999999 ");
	 print_flag();
	 return 0;
      }
   }

   k = 1024;

   ZZ x1, x2, x3;
   double t;
   long j;

   RandomLen(x1, k);
   RandomLen(x2, k);
   

   long iter;

   mul(x3, x1, x2);

   iter = 1;

   do {
     t = GetTime();
     for (i = 0; i < iter; i++) {
        for (j = 0; j < 500; j++) mul(x3, x1, x2);
      }
     t = GetTime() - t;
     iter = 2*iter;
   } while(t < 1);


   iter = iter/2;
   iter = long((3/t)*iter) + 1;

   double tvec[5];
   long w;

   for (w = 0; w < 5; w++) {
     t = GetTime();
     for (i = 0; i < iter; i++) {
        for (j = 0; j < 500; j++) mul(x3, x1, x2);
      }
     t = GetTime() - t;
     tvec[w] = t;
   }

   t = clean_data(tvec);

   t = floor((t/iter)*1e14);

   if (t < 0 || t >= 1e15)
      printf("999999999999999 ");
   else
      printf("%015.0f ", t);

   printf(" [%ld] ", iter);

   print_flag();

   return 0;
}
Exemplo n.º 23
0
                        << " Number of eqs= " << N_eq << std::endl
                        << " Blob after correction= "
                        << A3D_ELEM(*vol_blobs, k, i, j) << std::endl;
#endif

                    }
                }

                // Prepare for next iteration
                XX(act_coord) = XX(act_coord) + grid->relative_size * (grid->basis)( 0, 0);
                YY(act_coord) = YY(act_coord) + grid->relative_size * (grid->basis)( 1, 0);
                ZZ(act_coord) = ZZ(act_coord) + grid->relative_size * (grid->basis)( 2, 0);
            }
            XX(beginY) = XX(beginY) + grid->relative_size * (grid->basis)( 0, 1);
            YY(beginY) = YY(beginY) + grid->relative_size * (grid->basis)( 1, 1);
            ZZ(beginY) = ZZ(beginY) + grid->relative_size * (grid->basis)( 2, 1);
        }

        pthread_mutex_lock(&blobs_conv_mutex);

        for( int in = (assigned_slice-min_separation+1) ; in <= (assigned_slice+min_separation-1); in ++ )
        {
            if( in != assigned_slice )
            {
                if( ( in >= 0 ) && ( in < z_planes))
                {
                    if( slices_status[in] != -1 )
                        slices_status[in]--;
                }
            }
        }
Exemplo n.º 24
0
int main(int argc, char *argv[]) 
{

  // Commandline setup

  ArgMapping amap;

  long m=16;
  long r=8;
  long L=0;
  double epsilon=0.01; // Accepted accuracy
  long R=1;
  long seed=0;
  bool debug = false;

  amap.arg("m", m, "Cyclotomic index");
  amap.note("e.g., m=1024, m=2047");
  amap.arg("r", r, "Bits of precision");
  amap.arg("R", R, "number of rounds");
  amap.arg("L", L, "Number of bits in modulus", "heuristic");
  amap.arg("ep", epsilon, "Accepted accuracy");
  amap.arg("seed", seed, "PRG seed");
  amap.arg("verbose", verbose, "more printouts");
  amap.arg("debug", debug, "for debugging");

  amap.parse(argc, argv);

  if (seed)
    NTL::SetSeed(ZZ(seed));

  if (R<=0) R=1;
  if (R<=2)
    L = 100*R;
  else
    L = 220*(R-1);

  if (verbose) {
    cout << "** m="<<m<<", #rounds="<<R<<", |q|="<<L
         << ", epsilon="<<epsilon<<endl;
  }
  epsilon /= R;
  try{

    // FHE setup keys, context, SKMs, etc

    FHEcontext context(m, /*p=*/-1, r);
    context.scale=4;
    buildModChain(context, L, /*c=*/2);

    FHESecKey secretKey(context);
    secretKey.GenSecKey(); // A +-1/0 secret key
    addSome1DMatrices(secretKey); // compute key-switching matrices

    const FHEPubKey publicKey = secretKey;
    const EncryptedArrayCx& ea = context.ea->getCx();

    if (verbose) {
      ea.getPAlgebra().printout();
      cout << "r = " << context.alMod.getR() << endl;
      cout << "ctxtPrimes="<<context.ctxtPrimes
           << ", specialPrimes="<<context.specialPrimes<<endl<<endl;
    }
    if (debug) {
        dbgKey = & secretKey;
        dbgEa = (EncryptedArray*) context.ea;
    }

    // Run the tests.
    testBasicArith(publicKey, secretKey, ea, epsilon);
    testComplexArith(publicKey, secretKey, ea, epsilon);
    testRotsNShifts(publicKey, secretKey, ea, epsilon);
    testGeneralOps(publicKey, secretKey, ea, epsilon*R, R);
  } 
  catch (exception& e) {
    cerr << e.what() << endl;
    cerr << "***Major FAIL***" << endl;  
  }

  return 0;
}
Exemplo n.º 25
0
void ProgValidationTiltPairs::run()
{
	MetaData MD_tilted, MD_untilted, DF1sorted, DF2sorted, DFweights;

	MD_tilted.read(fntiltimage_In);
	MD_untilted.read(fnuntiltimage_In);

	DF1sorted.sort(MD_tilted,MDL_ITEM_ID,true);
	DF2sorted.sort(MD_untilted,MDL_ITEM_ID,true);

	MDIterator iter1(DF1sorted), iter2(DF2sorted);
	std::vector< Matrix1D<double> > ang1, ang2;
	Matrix1D<double> rotTiltPsi(3), z(3);
	size_t currentId;
	bool anotherImageIn2=iter2.hasNext();
	size_t id1, id2;
	bool mirror;
	Matrix2D<double> Eu, Et, R;
	double alpha, beta;
	while (anotherImageIn2)
	{
		ang1.clear();
		ang2.clear();

		// Take current id
		DF2sorted.getValue(MDL_ITEM_ID,currentId,iter2.objId);

		// Grab all the angles in DF2 associated to this id
		bool anotherIteration=false;
		do
		{
			DF2sorted.getValue(MDL_ITEM_ID,id2,iter2.objId);
			anotherIteration=false;
			if (id2==currentId)
			{
				DF2sorted.getValue(MDL_ANGLE_ROT,XX(rotTiltPsi),iter2.objId);
				DF2sorted.getValue(MDL_ANGLE_TILT,YY(rotTiltPsi),iter2.objId);
				DF2sorted.getValue(MDL_ANGLE_PSI,ZZ(rotTiltPsi),iter2.objId);
				DF2sorted.getValue(MDL_FLIP,mirror,iter2.objId);
				std::cout << "From DF2:" << XX(rotTiltPsi) << " " << YY(rotTiltPsi) << " " << ZZ(rotTiltPsi) << " " << mirror << std::endl;
				//LINEA ANTERIOR ORIGINAL
				if (mirror)
				{
					double rotp, tiltp, psip;
					Euler_mirrorX(XX(rotTiltPsi),YY(rotTiltPsi),ZZ(rotTiltPsi), rotp, tiltp, psip);
					XX(rotTiltPsi)=rotp;
					YY(rotTiltPsi)=tiltp;
					ZZ(rotTiltPsi)=psip;
				}
				ang2.push_back(rotTiltPsi);
				iter2.moveNext();
				if (iter2.hasNext())
					anotherIteration=true;
			}
		} while (anotherIteration);

		// Advance Iter 1 to catch Iter 2
		double N=0, cumulatedDistance=0;
		size_t newObjId=0;
		if (iter1.objId>0)
		{
			DF1sorted.getValue(MDL_ITEM_ID,id1,iter1.objId);
			while (id1<currentId && iter1.hasNext())
			{
				iter1.moveNext();
				DF1sorted.getValue(MDL_ITEM_ID,id1,iter1.objId);
			}

			// If we are at the end of DF1, then we did not find id1 such that id1==currentId
			if (!iter1.hasNext())
				break;

			// Grab all the angles in DF1 associated to this id
			anotherIteration=false;
			do
			{
				DF1sorted.getValue(MDL_ITEM_ID,id1,iter1.objId);
				anotherIteration=false;
				if (id1==currentId)
				{
					DF1sorted.getValue(MDL_ANGLE_ROT,XX(rotTiltPsi),iter1.objId);
					DF1sorted.getValue(MDL_ANGLE_TILT,YY(rotTiltPsi),iter1.objId);
					DF1sorted.getValue(MDL_ANGLE_PSI,ZZ(rotTiltPsi),iter1.objId);
					DF1sorted.getValue(MDL_FLIP,mirror,iter1.objId);
					std::cout << "From DF1:" << XX(rotTiltPsi) << " " << YY(rotTiltPsi) << " " << ZZ(rotTiltPsi) << " " << mirror << std::endl;
					//LINEA ANTERIOR ORIGINAL
					if (mirror)
					{
						double rotp, tiltp, psip;
						Euler_mirrorX(XX(rotTiltPsi),YY(rotTiltPsi),ZZ(rotTiltPsi), rotp, tiltp, psip);
						XX(rotTiltPsi)=rotp;
						YY(rotTiltPsi)=tiltp;
						ZZ(rotTiltPsi)=psip;
					}
					ang1.push_back(rotTiltPsi);
					iter1.moveNext();
					if (iter1.hasNext())
						anotherIteration=true;
				}
			} while (anotherIteration);

			// Process both sets of angles
			for (size_t i=0; i<ang2.size(); ++i)
			{
				const Matrix1D<double> &anglesi=ang2[i];
				double rotu=XX(anglesi);
				double tiltu=YY(anglesi);
				double psiu=ZZ(anglesi);
				Euler_angles2matrix(rotu,tiltu,psiu,Eu,false);
				/*std::cout << "------UNTILTED MATRIX------" << std::endl;
				std::cout << Eu << std::endl;
				std::cout << "vector" << std::endl;
				std::cout << Eu(2,0) << "  " << Eu(2,1) << "  " << Eu(2,2) << std::endl;*/


				for (size_t j=0; j<ang1.size(); ++j)
				{
					const Matrix1D<double> &anglesj=ang1[j];
					double rott=XX(anglesj);
					double tiltt=YY(anglesj);
					double psit=ZZ(anglesj);
					double alpha_x, alpha_y;
					Euler_angles2matrix(rott,tiltt,psit,Et,false);
					//////////////////////////////////////////////////////////////////
					double untilt_angles[3]={rotu, tiltu, psiu}, tilt_angles[3]={rott, tiltt, psit};
					angles2tranformation(untilt_angles, tilt_angles, alpha_x, alpha_y);
					//std::cout << "alpha = " << (alpha_x*alpha_x+alpha_y*alpha_y) << std::endl;
					//////////////////////////////////////////////////////////////////
					/*std::cout << "------TILTED MATRIX------" << std::endl;
					std::cout << Et << std::endl;
					std::cout << "vector" << std::endl;
					std::cout << Et(2,0) << "  " << Et(2,1) << "  " << Et(2,2) << std::endl;
					std::cout << "---------------------------" << std::endl;
					std::cout << "---------------------------" << std::endl;*/
					R=Eu*Et.transpose();
					double rotTransf, tiltTransf, psiTransf;
					Euler_matrix2angles(R, rotTransf, tiltTransf, psiTransf);
					std::cout << "Rot_and_Tilt " << rotTransf << " " << tiltTransf << std::endl;
					//LINEA ANTERIOR ORIGINAL

				XX(z) = Eu(2,0) - Et(2,0);
				YY(z) = Eu(2,1) - Et(2,1);
				ZZ(z) = Eu(2,2) - Et(2,2);

				alpha = atan2(YY(z), XX(z));        //Expressed in rad
				beta = atan2(XX(z)/cos(alpha), ZZ(z));   //Expressed in rad
				std::cout << "alpha = " << alpha*180/PI << std::endl;
				std::cout << "beta = " << beta*180/PI << std::endl;
				}
			}
		}
		else
			N=0;

		if (N>0)
		{
			double meanDistance=cumulatedDistance/ang2.size();
			DFweights.setValue(MDL_ANGLE_DIFF,meanDistance,newObjId);
		}
		else
			if (newObjId>0)
				DFweights.setValue(MDL_ANGLE_DIFF,-1.0,newObjId);
		anotherImageIn2=iter2.hasNext();
	}

	std::complex<double> qu[4], qt[4], M[4], Inv_qu[4], test[4], P1[4], P2[4], Inv_quu[4];
	double rotu=34*PI/180, tiltu=10*PI/180, psiu=5*PI/180;
	double rott=25*PI/180, tiltt=15*PI/180, psit=40*PI/180;


    quaternion2Paulibasis(rotu, tiltu, psiu, qu);
    /*std::cout << "quaternion2Pauli" << std::endl;
    std::cout << "Untilted " << qu[0] << " " << qu[1] << " " << qu[2] << " " << qu[3] << std::endl;
    std::cout << "      " << std::endl;*/

    Paulibasis2matrix(qu,M);
    /*std::cout << "Pauli2matrix" << std::endl;
    std::cout << "Matriz   " << M[0] << " " << M[1] << " " << M[2] << " " << M[3] << std::endl;
    std::cout << "      " << std::endl;*/

    inverse_matrixSU2(M, Inv_qu);
    /*std::cout << "inverse_matrixSU(2)" << std::endl;
    std::cout << "Inversa  " << Inv_qu[0] << " " << Inv_qu[1] << " " << Inv_qu[2] << " " << Inv_qu[3] << std::endl;
    std::cout << "      " << std::endl;*/

    quaternion2Paulibasis(rott, tiltt, psit, qt);
    /*std::cout << "quaternion2Pauli" << std::endl;
    std::cout << "Tilted " << qt[0] << " " << qt[1] << " " << qt[2] << " " << qt[3] << std::endl;
    std::cout << "      " << std::endl;*/

    InversefromPaulibasis(qu,Inv_quu);

    Pauliproduct(qt, Inv_qu, P1);
    /*std::cout << "Pauliproduct" << std::endl;
    std::cout << "quaternion qt  " << P1[0] << " " << P1[1] << " " << P1[2] << " " << P1[3] << std::endl;
    std::cout << "      " << std::endl;
    std::cout << "-----------------------------------" << std::endl;*/

    //double alpha_x, alpha_y;
    //extrarotationangles(P1, alpha_x, alpha_y);
    //std::cout << "alpha_x = " << alpha_x << " " << "alpha_y = " << alpha_y << std::endl;
}
   void
   computeConsistentRotations_Linf(double const sigma, int const nIterations, int const nViews,
                                   std::vector<Matrix3x3d> const& relativeRotations,
                                   std::vector<std::pair<int, int> > const& viewPairs,
                                   std::vector<Matrix3x3d>& rotations, std::vector<double>& zs)
   {
      double const gamma = 1.0;

      int const nRelPoses = relativeRotations.size();

      rotations.resize(nViews);

      Matrix3x3d zero3x3d;
      makeZeroMatrix(zero3x3d);

      Matrix4x4d zeroQuat;
      makeZeroMatrix(zeroQuat); zeroQuat[0][0] = 1;

      double const denomT = 1.0 / (1.0 + nRelPoses);

      vector<double> denomQ(nViews, 1.0); // from the psd constraint
      for (int k = 0; k < nRelPoses; ++k)
      {
         int const i = viewPairs[k].first;
         int const j = viewPairs[k].second;
         denomQ[i] += 1;
         denomQ[j] += 1;
      }
      for (int i = 0; i < nViews; ++i) denomQ[i] = 1.0 / denomQ[i];

      double T = 0.0;
      vector<double> T1(nRelPoses);
      vector<double> ZT1(nRelPoses, 0.0);
      double T2;
      double ZT2 = 0;

      vector<Matrix4x4d> Q(nViews, zeroQuat);
      vector<Matrix4x4d> Q1(nViews, zeroQuat);
      vector<Matrix4x4d> ZQ1(nViews, zeroQuat);
      vector<Matrix4x4d> Q2i(nRelPoses, zeroQuat);
      vector<Matrix4x4d> Q2j(nRelPoses, zeroQuat);
      vector<Matrix4x4d> ZQ2i(nRelPoses, zeroQuat);
      vector<Matrix4x4d> ZQ2j(nRelPoses, zeroQuat);

      vector<Matrix3x3d> A(nRelPoses, zero3x3d);
      vector<Matrix3x3d> A1(nRelPoses, zero3x3d);
      vector<Matrix3x3d> A2(nRelPoses, zero3x3d);
      vector<Matrix3x3d> ZA1(nRelPoses, zero3x3d);
      vector<Matrix3x3d> ZA2(nRelPoses, zero3x3d);

      for (int iter = 0; iter < nIterations; ++iter)
      {
         // Convex hull of rotation matrices
         for (int i = 0; i < nViews; ++i)
         {
            Matrix4x4d q = Q[i] + ZQ1[i];
            if (i > 0)
               projectConvHull_SO3(q);
            else
            {
               makeZeroMatrix(q);
               q[0][0] = 1;
            }
            Q1[i] = q;
            addMatricesIP(Q[i] - q, ZQ1[i]);
         } // end for (i)

         // Shrinkage of T (we want to minimize T)
         T2 = std::max(0.0, T + ZT2 - gamma);
         ZT2 += T - T2;

         // Cone constraint
         for (int k = 0; k < nRelPoses; ++k)
         {
            double t = T + ZT1[k];
            Matrix3x3d a = A[k] + ZA1[k];

            proxDataResidual_Frobenius(sigma, t, a);

            T1[k] = t;
            ZT1[k] += T - t;
            A1[k] = a;
            addMatricesIP(A[k] - a, ZA1[k]);
         } // end for (k)

         // Enforce linear consistency
         for (int k = 0; k < nRelPoses; ++k)
         {
            int const i = viewPairs[k].first;
            int const j = viewPairs[k].second;

            Matrix4x4d qi = Q[i] + ZQ2i[k];
            Matrix4x4d qj = Q[j] + ZQ2j[k];
            Matrix3x3d a = A[k] + ZA2[k];

            proxConsistency(relativeRotations[k], qi, qj, a);

            Q2i[k] = qi;
            Q2j[k] = qj;
            A2[k] = a;
            addMatricesIP(Q[i] - qi, ZQ2i[k]);
            addMatricesIP(Q[j] - qj, ZQ2j[k]);
            addMatricesIP(A[k] - a, ZA2[k]);
         } // end for (k)

         // Averaging of the solutions
         for (int i = 0; i < nViews; ++i) Q[i] = Q1[i] - ZQ1[i];

         T = T2 - ZT2;
         for (int k = 0; k < nRelPoses; ++k) T += T1[k] - ZT1[k];
         T *= denomT;
         T = std::max(0.0, T);

         for (int k = 0; k < nRelPoses; ++k) A[k] = A1[k] - ZA1[k];

         for (int k = 0; k < nRelPoses; ++k)
         {
            int const i = viewPairs[k].first;
            int const j = viewPairs[k].second;

            addMatricesIP(Q2i[k] - ZQ2i[k], Q[i]);
            addMatricesIP(Q2j[k] - ZQ2j[k], Q[j]);
            addMatricesIP(A2[k] - ZA2[k], A[k]);
         } // end for (k)

         for (int i = 0; i < nViews; ++i) scaleMatrixIP(denomQ[i], Q[i]);
         for (int k = 0; k < nRelPoses; ++k) scaleMatrixIP(0.5, A[k]);

         if ((iter % 500) == 0)
         {
            cout << "iter: " << iter << " t = " << T << endl;
            cout << "T1 = "; displayVector(T1);
            cout << "ZT1 = "; displayVector(ZT1);
            cout << "T2 = " << T2 << " ZT2 = " << ZT2 << endl;

            Matrix<double> ZZ(4, 4);
            for (int i = 0; i < nViews; ++i)
            {
               copyMatrix(Q[i], ZZ);
               SVD<double> svd(ZZ);
               cout << "Q = "; displayMatrix(ZZ);
               cout << "SV = "; displayVector(svd.getSingularValues());
               //Matrix3x3d R = getRotationFromQuat(Q[i]);
               //cout << "R = "; displayMatrix(R);
            } // end for (i)
         }
      } // end for (iter)

      rotations.resize(nViews);
      for (int i = 0; i < nViews; ++i)
         rotations[i] = getRotationFromQuat(Q[i]);

      zs = ZT1;
   } // end computeConsistentRotations_Linf()
Exemplo n.º 27
0
int main()
{
   setbuf(stdout, NULL);
   SetSeed(ZZ(0));

   for (long l = 256; l <= 16384; l *= 2) {
      // for (long n = 256; n <= 16384; n *= 2) {
      for (long idx = 0; idx < 13; idx ++) {
         long n  = 256*(1L << idx/2);
         if (idx & 1) n += n/2;

         SetSeed((ZZ(l) << 64) + ZZ(n));

         ZZ p;
      
         RandomLen(p, l);
         if (!IsOdd(p)) p++;
         ZZ_p::init(p);
      
      
         ZZ_pX a, c, f;
      
         random(a, n);
         random(f, n);
         SetCoeff(f, n);
      
         ZZ_pXModulus F(f);
      
      
         double t;
      
         SqrMod(c, a, F);
      
         long iter = 1;
         do {
            t = GetTime();
            for (long i = 0; i < iter; i++) SqrMod(c, a, F);
            t = GetTime() - t;
            iter *= 2;
         } while (t < 3);
         iter /= 2;
      
         t = GetTime();
         for (long i = 0; i < iter; i++) SqrMod(c, a, F);
         t = GetTime()-t;
         double NTLTime = t;
      
      
         FlintZZ_pX f_a(a), f_c, f_f(f), f_finv;
         fmpz_mod_poly_reverse(f_finv.value, f_f.value, f_f.value->length); 
         fmpz_mod_poly_inv_series_newton(f_finv.value, f_finv.value, f_f.value->length);
      
         fmpz_mod_poly_mulmod_preinv(f_c.value, f_a.value, f_a.value, f_f.value, f_finv.value);
      
      
         t = GetTime();
         for (long i = 0; i < iter; i++) 
            fmpz_mod_poly_mulmod_preinv(f_c.value, f_a.value, f_a.value, f_f.value, f_finv.value);
         t = GetTime()-t;
         double FlintTime = t;

         printf("%8.2f", FlintTime/NTLTime);
      }

      printf("\n");
   }
}
Exemplo n.º 28
0
//#define DEBUG
void spatial_Bspline032voxels(const GridVolume &vol_splines,
                              MultidimArray<double> *vol_voxels, int Zdim, int Ydim, int Xdim)
{
    // Resize and set starting corner .......................................
    if (Zdim == 0 || Ydim == 0 || Xdim == 0)
    {
        Matrix1D<double> size = vol_splines.grid(0).highest -
                                vol_splines.grid(0).lowest;
        Matrix1D<double> corner = vol_splines.grid(0).lowest;
        (*vol_voxels).initZeros(CEIL(ZZ(size)), CEIL(YY(size)), CEIL(XX(size)));
        STARTINGX(*vol_voxels) = FLOOR(XX(corner));
        STARTINGY(*vol_voxels) = FLOOR(YY(corner));
        STARTINGZ(*vol_voxels) = FLOOR(ZZ(corner));
    }
    else
    {
        (*vol_voxels).initZeros(Zdim, Ydim, Xdim);
        (*vol_voxels).setXmippOrigin();
    }

    // Convert each subvolume ...............................................
    for (size_t i = 0; i < vol_splines.VolumesNo(); i++)
    {
        spatial_Bspline032voxels_SimpleGrid(vol_splines(i)(), vol_splines.grid(i),
                                            vol_voxels);
#ifdef DEBUG
        std::cout << "Spline grid no " << i << " stats: ";
        vol_splines(i)().printStats();
        std::cout << std::endl;
        std::cout << "So far vol stats: ";
        (*vol_voxels).printStats();
        std::cout << std::endl;
        VolumeXmipp save;
        save() = *vol_voxels;
        save.write((std::string)"PPPvoxels" + integerToString(i));
#endif
    }

    // Now normalise the resulting volume ..................................
    double inorm = 1.0 / sum_spatial_Bspline03_Grid(vol_splines.grid());
    FOR_ALL_ELEMENTS_IN_ARRAY3D(*vol_voxels)
    A3D_ELEM(*vol_voxels, k, i, j) *= inorm;

    // Set voxels outside interest region to minimum value .................
    double R = vol_splines.grid(0).get_interest_radius();
    if (R != -1)
    {
        double R2 = (R - 6) * (R - 6);

        // Compute minimum value within sphere
        double min_val = A3D_ELEM(*vol_voxels, 0, 0, 0);
        FOR_ALL_ELEMENTS_IN_ARRAY3D(*vol_voxels)
        if (j*j + i*i + k*k <= R2 - 4)
            min_val = XMIPP_MIN(min_val, A3D_ELEM(*vol_voxels, k, i, j));

        // Substitute minimum value
        R2 = (R - 2) * (R - 2);
        FOR_ALL_ELEMENTS_IN_ARRAY3D(*vol_voxels)
        if (j*j + i*i + k*k >= R2)
            A3D_ELEM(*vol_voxels, k, i, j) = min_val;
    }
Exemplo n.º 29
0
/* Splines -> Voxels for a SimpleGrid -------------------------------------- */
void spatial_Bspline032voxels_SimpleGrid(const MultidimArray<double> &vol_splines,
        const SimpleGrid &grid,
        MultidimArray<double> *vol_voxels,
        const MultidimArray<double> *vol_mask = NULL)
{
    Matrix1D<double> act_coord(3);           // Coord: Actual position inside
    // the voxel volume without deforming
    Matrix1D<double> beginZ(3);              // Coord: Voxel coordinates of the
    // blob at the 3D point
    // (z0,YY(lowest),XX(lowest))
    Matrix1D<double> beginY(3);              // Coord: Voxel coordinates of the
    // blob at the 3D point
    // (z0,y0,XX(lowest))
    Matrix1D<double> corner2(3), corner1(3); // Coord: Corners of the
    // blob in the voxel volume
    Matrix1D<double> gcurrent(3);            // Position in g of current point
    double        intx, inty, intz;          // Nearest integer voxel
    int           i, j, k;                   // Index within the blob volume
    bool          process;                   // True if this blob has to be
    // processed
    double spline_radius = 2 * sqrt(3.0);

    // Some aliases
#define x0 STARTINGX(*vol_voxels)
#define xF FINISHINGX(*vol_voxels)
#define y0 STARTINGY(*vol_voxels)
#define yF FINISHINGY(*vol_voxels)
#define z0 STARTINGZ(*vol_voxels)
#define zF FINISHINGZ(*vol_voxels)

#ifdef DEBUG
    bool condition = true;
    (*vol_voxels)().printShape();
    std::cout << std::endl;
    std::cout << "x0= " << x0 << " xF= " << xF << std::endl;
    std::cout << "y0= " << y0 << " yF= " << yF << std::endl;
    std::cout << "z0= " << z0 << " zF= " << zF << std::endl;
    std::cout << grid;
#endif

    // Convert the whole grid ...............................................
    // Corner of the plane defined by Z. These coordinates are in the
    // universal coord. system
    grid.grid2universe(grid.lowest, beginZ);

    Matrix1D<double> grid_index(3);
    for (k = (int) ZZ(grid.lowest); k <= (int) ZZ(grid.highest); k++)
    {
        // Corner of the row defined by Y
        beginY = beginZ;
        for (i = (int) YY(grid.lowest); i <= (int) YY(grid.highest); i++)
        {
            // First point in the row
            act_coord = beginY;
            for (j = (int) XX(grid.lowest); j <= (int) XX(grid.highest); j++)
            {
                VECTOR_R3(grid_index, j, i, k);
#ifdef DEBUG
                if (condition)
                {
                    printf("Dealing spline at (%d,%d,%d) = %f\n", j, i, k, A3D_ELEM(vol_splines, k, i, j));
                    std::cout << "Center of the blob      "
                    << act_coord.transpose() << std::endl;
                }
#endif

                // These two corners are also real valued
                process = true;
                if (XX(act_coord) >= xF) process = false;
                if (YY(act_coord) >= yF) process = false;
                if (ZZ(act_coord) >= zF) process = false;
                if (XX(act_coord) <= x0) process = false;
                if (YY(act_coord) <= y0) process = false;
                if (ZZ(act_coord) <= z0) process = false;
#ifdef DEBUG
                if (!process && condition) std::cout << "   It is outside output volume\n";
#endif
                if (!grid.is_interesting(act_coord))
                {
#ifdef DEBUG
                    if (process && condition) std::cout << "   It is not interesting\n";
#endif
                    process = false;
                }

                if (process)
                {
                    V3_PLUS_CT(corner1, act_coord, -spline_radius);
                    V3_PLUS_CT(corner2, act_coord, spline_radius);
#ifdef DEBUG
                    if (condition)
                    {
                        std::cout << "Corner 1 for this point " << corner1.transpose() << std::endl;
                        std::cout << "Corner 2 for this point " << corner2.transpose() << std::endl;
                    }
#endif

                    // Clip the corners to the volume borders
                    XX(corner1) = ROUND(CLIP(XX(corner1), x0, xF));
                    YY(corner1) = ROUND(CLIP(YY(corner1), y0, yF));
                    ZZ(corner1) = ROUND(CLIP(ZZ(corner1), z0, zF));
                    XX(corner2) = ROUND(CLIP(XX(corner2), x0, xF));
                    YY(corner2) = ROUND(CLIP(YY(corner2), y0, yF));
                    ZZ(corner2) = ROUND(CLIP(ZZ(corner2), z0, zF));
#ifdef DEBUG
                    if (condition)
                    {
                        std::cout << "Clipped and rounded Corner 1 " << corner1.transpose() << std::endl;
                        std::cout << "Clipped and rounded Corner 2 " << corner2.transpose() << std::endl;
                    }
#endif

                    // Effectively convert
                    for (intz = ZZ(corner1); intz <= ZZ(corner2); intz++)
                        for (inty = YY(corner1); inty <= YY(corner2); inty++)
                            for (intx = XX(corner1); intx <= XX(corner2); intx++)
                            {
                                int iz = (int)intz, iy = (int)inty, ix = (int)intx;
                                if (vol_mask != NULL)
                                    if (!A3D_ELEM(*vol_mask, iz, iy, ix)) continue;

                                // Compute the spline value at this point
                                VECTOR_R3(gcurrent, intx, inty, intz);
                                V3_MINUS_V3(gcurrent, act_coord, gcurrent);
                                double spline_value = spatial_Bspline03(gcurrent);
#ifdef DEBUG_MORE
                                if (condition)
                                {
                                    std::cout << "At (" << intx << ","
                                    << inty << "," << intz << ") value="
                                    << spline_value;
                                    std::cout.flush();
                                }
#endif

                                // Add at that position the corresponding spline value
                                A3D_ELEM(*vol_voxels, iz, iy, ix) +=
                                    A3D_ELEM(vol_splines, k, i, j) * spline_value;
#ifdef DEBUG_MORE
                                if (condition)
                                {
                                    std::cout << " adding " << A3D_ELEM(vol_splines, k, i, j)
                                    << " * " << value_spline << " = "
                                    << A3D_ELEM(vol_splines, k, i, j)*
                                    value_spline << std::endl;
                                    std::cout.flush();
                                }
#endif
                            }
                }

                // Prepare for next iteration
                XX(act_coord) = XX(act_coord) + grid.relative_size * grid.basis(0, 0);
                YY(act_coord) = YY(act_coord) + grid.relative_size * grid.basis(1, 0);
                ZZ(act_coord) = ZZ(act_coord) + grid.relative_size * grid.basis(2, 0);
            }
            XX(beginY) = XX(beginY) + grid.relative_size * grid.basis(0, 1);
            YY(beginY) = YY(beginY) + grid.relative_size * grid.basis(1, 1);
            ZZ(beginY) = ZZ(beginY) + grid.relative_size * grid.basis(2, 1);
        }
        XX(beginZ) = XX(beginZ) + grid.relative_size * grid.basis(0, 2);
        YY(beginZ) = YY(beginZ) + grid.relative_size * grid.basis(1, 2);
        ZZ(beginZ) = ZZ(beginZ) + grid.relative_size * grid.basis(2, 2);
    }
}
Exemplo n.º 30
0
//#define DEBUG
double spatial_Bspline03_proj(
    const Matrix1D<double> &r, const Matrix1D<double> &u)
{
    // Avoids divisions by zero and allows orthogonal rays computation
    static Matrix1D<double> ur(3);
    if (XX(u) == 0) XX(ur) = XMIPP_EQUAL_ACCURACY;
    else XX(ur) = XX(u);
    if (YY(u) == 0) YY(ur) = XMIPP_EQUAL_ACCURACY;
    else YY(ur) = YY(u);
    if (ZZ(u) == 0) ZZ(ur) = XMIPP_EQUAL_ACCURACY;
    else ZZ(ur) = ZZ(u);

    // Some precalculated variables
    double x_sign = SGN(XX(ur));
    double y_sign = SGN(YY(ur));
    double z_sign = SGN(ZZ(ur));

    // Compute the minimum and maximum alpha for the ray
    double alpha_xmin = (-2 - XX(r)) / XX(ur);
    double alpha_xmax = (2 - XX(r)) / XX(ur);
    double alpha_ymin = (-2 - YY(r)) / YY(ur);
    double alpha_ymax = (2 - YY(r)) / YY(ur);
    double alpha_zmin = (-2 - ZZ(r)) / ZZ(ur);
    double alpha_zmax = (2 - ZZ(r)) / ZZ(ur);

    double alpha_min = XMIPP_MAX(XMIPP_MIN(alpha_xmin, alpha_xmax),
                           XMIPP_MIN(alpha_ymin, alpha_ymax));
    alpha_min = XMIPP_MAX(alpha_min, XMIPP_MIN(alpha_zmin, alpha_zmax));
    double alpha_max = XMIPP_MIN(XMIPP_MAX(alpha_xmin, alpha_xmax),
                           XMIPP_MAX(alpha_ymin, alpha_ymax));
    alpha_max = XMIPP_MIN(alpha_max, XMIPP_MAX(alpha_zmin, alpha_zmax));
    if (alpha_max - alpha_min < XMIPP_EQUAL_ACCURACY) return 0.0;

#ifdef DEBUG
    std::cout << "Pixel:  " << r.transpose() << std::endl
    << "Dir:    " << ur.transpose() << std::endl
    << "Alpha x:" << alpha_xmin << " " << alpha_xmax << std::endl
    << "        " << (r + alpha_xmin*ur).transpose() << std::endl
    << "        " << (r + alpha_xmax*ur).transpose() << std::endl
    << "Alpha y:" << alpha_ymin << " " << alpha_ymax << std::endl
    << "        " << (r + alpha_ymin*ur).transpose() << std::endl
    << "        " << (r + alpha_ymax*ur).transpose() << std::endl
    << "Alpha z:" << alpha_zmin << " " << alpha_zmax << std::endl
    << "        " << (r + alpha_zmin*ur).transpose() << std::endl
    << "        " << (r + alpha_zmax*ur).transpose() << std::endl
    << "alpha  :" << alpha_min  << " " << alpha_max  << std::endl
    << std::endl;
#endif

    // Compute the first point in the volume intersecting the ray
    static Matrix1D<double> v(3);
    V3_BY_CT(v, ur, alpha_min);
    V3_PLUS_V3(v, r, v);

#ifdef DEBUG
    std::cout << "First entry point: " << v.transpose() << std::endl;
    std::cout << "   Alpha_min: " << alpha_min << std::endl;
#endif

    // Follow the ray
    double alpha = alpha_min;
    double ray_sum = 0;
    do
    {
        double alpha_x = (XX(v) + x_sign - XX(r)) / XX(ur);
        double alpha_y = (YY(v) + y_sign - YY(r)) / YY(ur);
        double alpha_z = (ZZ(v) + z_sign - ZZ(r)) / ZZ(ur);

        // Which dimension will ray move next step into?, it isn't neccesary to be only
        // one.
        double diffx = ABS(alpha - alpha_x);
        double diffy = ABS(alpha - alpha_y);
        double diffz = ABS(alpha - alpha_z);
        double diff_alpha = XMIPP_MIN(XMIPP_MIN(diffx, diffy), diffz);
        ray_sum += spatial_Bspline03_integral(r, ur, alpha, alpha + diff_alpha);

        // Update alpha and the next entry point
        if (ABS(diff_alpha - diffx) <= XMIPP_EQUAL_ACCURACY) alpha = alpha_x;
        if (ABS(diff_alpha - diffy) <= XMIPP_EQUAL_ACCURACY) alpha = alpha_y;
        if (ABS(diff_alpha - diffz) <= XMIPP_EQUAL_ACCURACY) alpha = alpha_z;
        XX(v) += diff_alpha * XX(ur);
        YY(v) += diff_alpha * YY(ur);
        ZZ(v) += diff_alpha * ZZ(ur);

#ifdef DEBUG
        std::cout << "Alpha x,y,z: " << alpha_x << " " << alpha_y
        << " " << alpha_z << " ---> " << alpha << std::endl;

        std::cout << "    Next entry point: " << v.transpose() << std::endl
        << "    diff_alpha: " << diff_alpha << std::endl
        << "    ray_sum: " << ray_sum << std::endl
        << "    Alfa tot: " << alpha << "alpha_max: " << alpha_max <<
        std::endl;

#endif
    }
    while ((alpha_max - alpha) > XMIPP_EQUAL_ACCURACY);
    return ray_sum;
}