示例#1
0
static void
getcpuid (char *id)
{
    uint32_t ax[3],cx[3],dx[3];
    cpuid(1);
    LM(veax,ax);
    cpuid(3);
    LM(vecx,cx);
    LM(vedx,dx);
    sprintf(id,"%u%u%u%u%u%u%u%u%u",ax[0],ax[1],ax[2],cx[0],cx[1],cx[2],dx[0],dx[1],dx[2]);
}
示例#2
0
bool TCNN_opt_function::write_func_to_file(double x_begin, double x_end, unsigned steps, const char* file_name)
{
    if (x_end < x_begin)
    {
        LM(LW, "x_begin should be less than x_end");
        return false;
    }

    std::vector<std::vector<double> > function_values;

    double delta = (x_end - x_begin) / steps;

    for (double x = x_begin; x < x_end; x += delta)
    {
        std::vector<double> row;
        row.push_back(x);
        std::vector<double> tmp_data;
        tmp_data.push_back(x);
        tmp_data.push_back(x);
        row.push_back(optimized_function->fVal(tmp_data));

        function_values.push_back(row);
    }

    write_to_file(file_name, function_values);

    return true;
}
示例#3
0
  static void apply(const EncryptedArrayDerived<type>& ea, 
                    std::vector<zzX>& unpackSlotEncoding)
  {
    FHE_NTIMER_START(buildUnpackSlotEncoding);
    RBak bak; bak.save(); ea.restoreContext();  // the NTL context for mod p^r

    long nslots = ea.size(); // how many slots
    long d = ea.getDegree(); // size of each slot

    const Mat<R>& CBi=ea.getNormalBasisMatrixInverse();
    // CBi contains a description of the normal-basis inverse transformation

    std::vector<RX> LM(d);
    for (long i = 0; i < d; i++) // prepare the linear polynomial
      LM[i] = CBi[i][0];

    std::vector<RX> C; 
    ea.buildLinPolyCoeffs(C, LM); // "build" the linear polynomial

    unpackSlotEncoding.resize(d);  // encode the coefficients
    for (long j = 0; j < d; j++) {
      std::vector<RX> v(nslots, C[j]);
      ea.encode(unpackSlotEncoding[j], v);
    }
  }
示例#4
0
      // dump statistics and weighted average
      void dump(std::ostream& os, std::string msg="PRS") throw(Exception)
      {
         try {
            was.setMessage(msg);
            os << was << std::endl;

            if(ndof > 0) {
               // scale covariance
               double sig(::sqrt(APV/ndof));
               Matrix<double> Cov(was.getCov());
               for(size_t i=0; i<Cov.rows(); i++) for(size_t j=i; j<Cov.cols(); j++)
                  Cov(i,j) = Cov(j,i) = Cov(i,j)*sig;
               // print cov as labelled matrix
               Namelist NL;
               NL += "ECEF_X"; NL += "ECEF_Y"; NL += "ECEF_Z";
               LabeledMatrix LM(NL,Cov);
               LM.scientific().setprecision(3).setw(14);

               os << "Covariance: " << msg << std::endl << LM << std::endl;
               os << "APV: " << msg << std::fixed << std::setprecision(3)
                  << " sigma = " << sig << " meters with "
                  << ndof << " degrees of freedom.";
            }
            else os << " Not enough data for covariance.";
         }
         catch(Exception& e) { GPSTK_RETHROW(e); }
      }
示例#5
0
void dynLagrangianCsBound::correct(const tmp<volTensorField>& gradU)
{
    LESModel::correct(gradU);

    volSymmTensorField S(dev(symm(gradU())));

    volScalarField magS(mag(S));

    volVectorField Uf(filter_(U()));

    volSymmTensorField Sf(dev(symm(fvc::grad(Uf))));

    volScalarField magSf(mag(Sf));

    volSymmTensorField L(dev(filter_(sqr(U())) - (sqr(filter_(U())))));

    volSymmTensorField M(2.0*sqr(delta())*(filter_(magS*S) - 4.0*magSf*Sf));

    volScalarField invT
    (
        (1.0/(theta_.value()*delta()))*pow(flm_*fmm_, 1.0/8.0)
    );

    volScalarField LM(L && M);

    fvScalarMatrix flmEqn
    (
        fvm::ddt(flm_)
      + fvm::div(phi(), flm_)
     ==
        invT*LM
      - fvm::Sp(invT, flm_)
    );

    flmEqn.relax();
    flmEqn.solve();

    bound(flm_, flm0_);

    volScalarField MM(M && M);

    fvScalarMatrix fmmEqn
    (
        fvm::ddt(fmm_)
      + fvm::div(phi(), fmm_)
     ==
        invT*MM
      - fvm::Sp(invT, fmm_)
    );

    fmmEqn.relax();
    fmmEqn.solve();

    bound(fmm_, fmm0_);

    updateSubGridScaleFields(gradU);
}
示例#6
0
bool TCNN_opt_function::isInitialConditionsHasSameDimentions(std::vector<std::vector<double> > const &init_initial_conditions)
{
    if (init_initial_conditions.size() != chaos_fuctions.size())
    {
        LM(LE, "Size of vector with initial conditions are not equal to size of vector chaotic functions");
        return false;
    }

    return true;
}
void CLMBlockModel::optimise()
{
    this->run(); //Full recompute of all the 0-states, which will never be recomputed again.
	CLMFullModel fullModelFn(this);
    CLevMar LM(fullModelFn, true, 1e-7);
    Eigen::VectorXd params = fullModelFn.init();
    cout << params.transpose() << endl;
    LM.minimise(params, 5);
    cout << "Optimisation complete" << endl;
}
示例#8
0
matf TriangulateNonLinear(const matf & P1, const matf & P2, const TrackedPoint & p) {
  matf X(4,1);
  X(0,0) = p.x1;
  X(1,0) = p.y1;
  X(2,0) = p.x2;
  X(3,0) = p.y2;
  DistTriangulateNL dtnl(P1, P2);
  matf a_;
  LM(X, Triangulate(P1, P2, p), dtnl, a_);
  return a_;
}
示例#9
0
文件: ODE45.cpp 项目: Polladin/TCNN
void baseODE45::solve(std::vector<double> init_initial_conditions, double init_step_length, unsigned init_amount_steps)
{
    step_length         = init_step_length;
    amount_steps        = init_amount_steps;
    res.clear();
    res.push_back(init_initial_conditions);

//    tmp_log_ostringstream.clear();
//    tmp_log_ostringstream << "Start solve for ODE45 with configure ALL parameters step_length:" << step_length << " steps:" << amount_steps;
    LM(LI,  "Start solve for ODE45 with configure ALL parameters step_length:" << step_length << " steps:" << amount_steps);
    //LM(LI, "Start solve for ODE45 with configure ALL parameters step_length:" + std::to_string(step_length) + " steps:" + std::to_string(amount_steps));

    solve();
}
示例#10
0
文件: ODE45.cpp 项目: Polladin/TCNN
void baseODE45::solve()
{
    if (res.size() == 0)
    {
        LM(LE, "Need to set initial conditions for ODE");
        assert(false);
    }
    std::vector<double> X, C, K1, K2, K3, K4;

    X = res.back();

    for (unsigned step = 0; step < amount_steps; ++step)
    {
        solve_one_step(X, C, K1, K2, K3, K4);
    }
}
示例#11
0
/**
 * @brief Extract coefficients from ciphertext polynomial

 * @param coeffs extracted coefficients
 * @param ctxt ciphertext
 * @param n extract "n" lowest degree coefficients
 */
void extractCoeffs(EncryptedArray& ea, vector<Ctxt>& coeffs, Ctxt& ctxt, long n) {
  long d = ea.getDegree();
  if (d < n) n = d;

  coeffs.clear();

  vector<Ctxt> conj;  
  for (int coeff = 0; coeff < n; ++coeff) {
    vector<ZZX> LM(d);
    LM[coeff] = ZZX(0, 1);

    // "building" the linearized-polynomial coefficients
    vector<ZZX> C(d);
    ea.buildLinPolyCoeffs(C, LM);

    coeffs.push_back(ctxt);
    applyLinPoly1(ea, coeffs[coeff], C, conj);
  }
}
示例#12
0
void TSPsolver::init_chaotic(unsigned cities)
{
    double rand_initial_cond;
    srand (time(0));

    for(auto elem : chaos)
    {
        for(auto *sub_elem : elem)
        {
            delete sub_elem;
        }
    }
    chaos.clear();

    for (int i=0; i<100; ++i)
    {
        rand_initial_cond = 2.0 * (static_cast<double>(rand())/RAND_MAX-0.5) * 0.2;
    }

    for (unsigned i = 0; i < cities; ++i)
    {
        std::vector<baseODE45*> city_row;

        for (unsigned j = 0; j < cities; ++j)
        {
            rand_initial_cond = 2.0 * (static_cast<double>(rand())/RAND_MAX-0.5) * 0.2;

            LM(LI, "rand initial cond: " << rand_initial_cond)

            std::vector<double> X;
            X.push_back(0);
            X.push_back(rand_initial_cond);
            X.push_back(0);
            X.push_back(0);

            city_row.push_back(new Chaotic1);
            city_row.back()->solve_init(X, step_length);
        }

        chaos.push_back(city_row);
        city_row.clear();
    }
}
int main(int argc, char* argv[])
{	
	//Load the AEM system specification files for the Skytem moments
	//only do this once
	//LM = Low moment pulse and 
	cTDEmSystem LM("..\\..\\examples\\bhmar-skytem\\stmfiles\\Skytem-LM.stm");
	//HM = high moment pulse	
	cTDEmSystem HM("..\\..\\examples\\bhmar-skytem\\stmfiles\\Skytem-HM.stm");

	//Load the system geometry (same for both moments)
	//This changes every fiducial/station
	cTDEmGeometry G;	
	G.tx_height = 30;
	G.tx_roll = 0;       G.tx_pitch = 0; G.tx_yaw = 0;
	G.txrx_dx = -12.62;  G.txrx_dy  = 0;  G.txrx_dz = +2.16;
	G.rx_roll = 0;       G.rx_pitch = 0; G.rx_yaw = 0;

	//Create the earth structure
	//This changes every fiducial/station
	cEarth1D E(3);	
	E.conductivity[0] = 0.010;
	E.conductivity[1] = 0.100;
	E.conductivity[2] = 0.001;
	E.thickness[0] = 20;
	E.thickness[1] = 40;
	//bottom layer is infinite thickness and not set
	
	//Create a response object for each moment (they have different numbers of windwos)
	cTDEmResponse LMR;
	cTDEmResponse HMR;

	//Run the forward model for each moment
	LM.forwardmodel(G, E, LMR);		
	HM.forwardmodel(G, E, HMR);

	//Merge the secondary field vertical (Z) components data into one data vector
	std::vector<double> data = concaternate(LMR.SZ, HMR.SZ);
	
	for (size_t i = 0; i < data.size(); i++){
		printf("%d %g\n", i, data[i]);
	}
}
示例#14
0
IGL_INLINE void igl::min_quad_dense_precompute(
  const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& A,
  const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& Aeq,    
  const bool use_lu_decomposition,
  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& S)
{
  typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> Mat;
        // This threshold seems to matter a lot but I'm not sure how to
        // set it
  const T treshold = igl::FLOAT_EPS;
  //const T treshold = igl::DOUBLE_EPS;

  const int n = A.rows();
  assert(A.cols() == n);
  const int m = Aeq.rows();
  assert(Aeq.cols() == n);

  // Lagrange multipliers method:
  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> LM(n + m, n + m);
  LM.block(0, 0, n, n) = A;
  LM.block(0, n, n, m) = Aeq.transpose();
  LM.block(n, 0, m, n) = Aeq;
  LM.block(n, n, m, m).setZero();

  Mat LMpinv;
  if(use_lu_decomposition)
  {
    // if LM is close to singular, use at your own risk :)
    LMpinv = LM.inverse();
  }else
  {
    // use SVD
    typedef Eigen::Matrix<T, Eigen::Dynamic, 1> Vec; 
    Vec singValues;
    Eigen::JacobiSVD<Mat> svd;
    svd.compute(LM, Eigen::ComputeFullU | Eigen::ComputeFullV );
    const Mat& u = svd.matrixU();
    const Mat& v = svd.matrixV();
    const Vec& singVals = svd.singularValues();

    Vec pi_singVals(n + m);
    int zeroed = 0;
    for (int i=0; i<n + m; i++)
    {
      T sv = singVals(i, 0);
      assert(sv >= 0);      
                 // printf("sv: %lg ? %lg\n",(double) sv,(double)treshold);
      if (sv > treshold) pi_singVals(i, 0) = T(1) / sv;
      else 
      {
        pi_singVals(i, 0) = T(0);
        zeroed++;
      }
    }

    printf("min_quad_dense_precompute: %i singular values zeroed (threshold = %e)\n", zeroed, treshold);
    Eigen::DiagonalMatrix<T, Eigen::Dynamic> pi_diag(pi_singVals);

    LMpinv = v * pi_diag * u.transpose();
  }
  S = LMpinv.block(0, 0, n, n + m);

  //// debug:
  //mlinit(&g_pEngine);
  //
  //mlsetmatrix(&g_pEngine, "A", A);
  //mlsetmatrix(&g_pEngine, "Aeq", Aeq);
  //mlsetmatrix(&g_pEngine, "LM", LM);
  //mlsetmatrix(&g_pEngine, "u", u);
  //mlsetmatrix(&g_pEngine, "v", v);
  //MatrixXd svMat = singVals;
  //mlsetmatrix(&g_pEngine, "singVals", svMat);
  //mlsetmatrix(&g_pEngine, "LMpinv", LMpinv);
  //mlsetmatrix(&g_pEngine, "S", S);

  //int hu = 1;
}
示例#15
0
文件: kbobj.c 项目: boberg/buchla700
  KA, KA, KA, KA,		/* 1 *//* Z *//* B */
  KB, KB, KB, KC,
  KB, KB, KB, KC,
  KD, KD, KB, KC,

  KD, KD, KA, KA,		/* 2 *//* A0 */
  KD, KD, KB, KC,
  KB, KB, KB, KC,
  KB, KB, KB, KC,

  KA, KA, KA, KA,		/* 3 *//* Bottom border */
  KD, KD, KD, KD,

  /* New Data label */

  LM (0x0000), LM (0x0000), LM (0x0000), LM (0x0000),
  LM (0x00F0), LM (0xFF0F), LM (0x0F0F), LM (0x0F00),
  LM (0x0FF0), LM (0x0F0F), LM (0x0F00), LM (0x0F00),
  LM (0xF0F0), LM (0xFF0F), LM (0x0F00), LM (0x0F0F),
  LM (0x00F0), LM (0x0F0F), LM (0xFF00), LM (0x0FF0),
  LM (0x00F0), LM (0xFF0F), LM (0x0F0F), LM (0x0F00),
  LM (0x0000), LM (0x0000), LM (0x0000), LM (0x0000),
  LM (0x0000), LM (0x0000), LM (0x0000), LM (0x0000),
  LM (0x0FF0), LM (0xFF00), LM (0xFFF0), LM (0x0FF0),
  LM (0xF0F0), LM (0x00F0), LM (0x0F0F), LM (0xF00F),
  LM (0xF0F0), LM (0xFFF0), LM (0x0F0F), LM (0xFFFF),
  LM (0xF0F0), LM (0x00F0), LM (0x0F0F), LM (0xF00F),
  LM (0x0FF0), LM (0x00F0), LM (0x0F0F), LM (0xF00F),
  LM (0x0000), LM (0x0000), LM (0x0000), LM (0x0000)
};
示例#16
0
void dynamicLagrangian<BasicTurbulenceModel>::correct()
{
    if (!this->turbulence_)
    {
        return;
    }

    // Local references
    const surfaceScalarField& phi = this->phi_;
    const volVectorField& U = this->U_;

    LESeddyViscosity<BasicTurbulenceModel>::correct();

    tmp<volTensorField> tgradU(fvc::grad(U));
    const volTensorField& gradU = tgradU();

    volSymmTensorField S(dev(symm(gradU)));
    volScalarField magS(mag(S));

    volVectorField Uf(filter_(U));
    volSymmTensorField Sf(dev(symm(fvc::grad(Uf))));
    volScalarField magSf(mag(Sf));

    volSymmTensorField L(dev(filter_(sqr(U)) - (sqr(filter_(U)))));
    volSymmTensorField M
    (
        2.0*sqr(this->delta())*(filter_(magS*S) - 4.0*magSf*Sf)
    );

    volScalarField invT
    (
        (1.0/(theta_.value()*this->delta()))*pow(flm_*fmm_, 1.0/8.0)
    );

    volScalarField LM(L && M);

    fvScalarMatrix flmEqn
    (
        fvm::ddt(flm_)
      + fvm::div(phi, flm_)
     ==
        invT*LM
      - fvm::Sp(invT, flm_)
    );

    flmEqn.relax();
    flmEqn.solve();

    bound(flm_, flm0_);

    volScalarField MM(M && M);

    fvScalarMatrix fmmEqn
    (
        fvm::ddt(fmm_)
      + fvm::div(phi, fmm_)
     ==
        invT*MM
      - fvm::Sp(invT, fmm_)
    );

    fmmEqn.relax();
    fmmEqn.solve();

    bound(fmm_, fmm0_);

    correctNut(gradU);
}
示例#17
0
/*!
    This function decodes some data into image changes.

    Returns the number of bytes consumed.
*/
int QGIFFormat::decode(QImage *image, const uchar *buffer, int length,
                       int *nextFrameDelay, int *loopCount, QSize *nextSize)
{
    // We are required to state that
    //    "The Graphics Interchange Format(c) is the Copyright property of
    //    CompuServe Incorporated. GIF(sm) is a Service Mark property of
    //    CompuServe Incorporated."

#define LM(l, m) (((m)<<8)|l)
    digress = false;
    int initial = length;
    while (!digress && length) {
        length--;
        unsigned char ch=*buffer++;
        switch (state) {
          case Header:
            hold[count++]=ch;
            if (count==6) {
                // Header
                gif89=(hold[3]!='8' || hold[4]!='7');
                state=LogicalScreenDescriptor;
                count=0;
            }
            break;
          case LogicalScreenDescriptor:
            hold[count++]=ch;
            if (count==7) {
                // Logical Screen Descriptor
                swidth=LM(hold[0], hold[1]);
                sheight=LM(hold[2], hold[3]);
                gcmap=!!(hold[4]&0x80);
                //UNUSED: bpchan=(((hold[4]&0x70)>>3)+1);
                //UNUSED: gcmsortflag=!!(hold[4]&0x08);
                gncols=2<<(hold[4]&0x7);
                bgcol=(gcmap) ? hold[5] : -1;
                //aspect=hold[6] ? double(hold[6]+15)/64.0 : 1.0;

                trans_index = -1;
                count=0;
                ncols=gncols;
                if (gcmap) {
                    ccount=0;
                    state=GlobalColorMap;
                    globalcmap = new QRgb[gncols+1]; // +1 for trans_index
                    globalcmap[gncols] = Q_TRANSPARENT;
                } else {
                    state=Introducer;
                }
            }
            break;
          case GlobalColorMap: case LocalColorMap:
            hold[count++]=ch;
            if (count==3) {
                QRgb rgb = qRgb(hold[0], hold[1], hold[2]);
                if (state == LocalColorMap) {
                    if (ccount < lncols)
                        localcmap[ccount] =  rgb;
                } else {
                    globalcmap[ccount] = rgb;
                }
                if (++ccount >= ncols) {
                    if (state == LocalColorMap)
                        state=TableImageLZWSize;
                    else
                        state=Introducer;
                }
                count=0;
            }
            break;
          case Introducer:
            hold[count++]=ch;
            switch (ch) {
              case ',':
                state=ImageDescriptor;
                break;
              case '!':
                state=ExtensionLabel;
                break;
              case ';':
                  // ### Changed: QRect(0, 0, swidth, sheight)
                state=Done;
                break;
              default:
                digress=true;
                // Unexpected Introducer - ignore block
                state=Error;
            }
            break;
          case ImageDescriptor:
            hold[count++]=ch;
            if (count==10) {
                int newleft=LM(hold[1], hold[2]);
                int newtop=LM(hold[3], hold[4]);
                int newwidth=LM(hold[5], hold[6]);
                int newheight=LM(hold[7], hold[8]);

                // disbelieve ridiculous logical screen sizes,
                // unless the image frames are also large.
                if (swidth/10 > qMax(newwidth,200))
                    swidth = -1;
                if (sheight/10 > qMax(newheight,200))
                    sheight = -1;

                if (swidth <= 0)
                    swidth = newleft + newwidth;
                if (sheight <= 0)
                    sheight = newtop + newheight;

                QImage::Format format = trans_index >= 0 ? QImage::Format_ARGB32 : QImage::Format_RGB32;
                if (image->isNull() || (image->size() != QSize(swidth, sheight)) || image->format() != format) {
                    (*image) = QImage(swidth, sheight, format);
                    memset(image->bits(), 0, image->numBytes());

                    // ### size of the upcoming frame, should rather
                    // be known before decoding it.
                    *nextSize = QSize(swidth, sheight);
                }

                disposePrevious(image);
                disposed = false;

                left = newleft;
                top = newtop;
                width = newwidth;
                height = newheight;

                right=qMax(0, qMin(left+width, swidth)-1);
                bottom=qMax(0, qMin(top+height, sheight)-1);
                lcmap=!!(hold[9]&0x80);
                interlace=!!(hold[9]&0x40);
                //bool lcmsortflag=!!(hold[9]&0x20);
                lncols=lcmap ? (2<<(hold[9]&0x7)) : 0;
                if (lncols) {
                    if (localcmap)
                        delete [] localcmap;
                    localcmap = new QRgb[lncols+1];
                    localcmap[lncols] = Q_TRANSPARENT;
                    ncols = lncols;
                } else {
                    ncols = gncols;
                }
                frame++;
                if (frame == 0) {
                    if (left || top || width<swidth || height<sheight) {
                        // Not full-size image - erase with bg or transparent
                        if (trans_index >= 0) {
                            fillRect(image, 0, 0, swidth, sheight, color(trans_index));
                            // ### Changed: QRect(0, 0, swidth, sheight)
                        } else if (bgcol>=0) {
                            fillRect(image, 0, 0, swidth, sheight, color(bgcol));
                            // ### Changed: QRect(0, 0, swidth, sheight)
                        }
                    }
                }

                if (disposal == RestoreImage) {
                    int l = qMin(swidth-1,left);
                    int r = qMin(swidth-1,right);
                    int t = qMin(sheight-1,top);
                    int b = qMin(sheight-1,bottom);
                    int w = r-l+1;
                    int h = b-t+1;

                    if (backingstore.width() < w
                        || backingstore.height() < h) {
                        // We just use the backing store as a byte array
                        backingstore = QImage(qMax(backingstore.width(), w),
                                              qMax(backingstore.height(), h),
                                              QImage::Format_RGB32);
                        memset(image->bits(), 0, image->numBytes());
                    }
                    for (int ln=0; ln<h; ln++) {
                        memcpy(backingstore.scanLine(ln),
                               image->scanLine(t+ln)+l, w*sizeof(QRgb));
                    }
                }

                count=0;
                if (lcmap) {
                    ccount=0;
                    state=LocalColorMap;
                } else {
                    state=TableImageLZWSize;
                }
                x = left;
                y = top;
                accum = 0;
                bitcount = 0;
                sp = stack;
                firstcode = oldcode = 0;
                needfirst = true;
                out_of_bounds = left>=swidth || y>=sheight;
            }
            break;
          case TableImageLZWSize: {
            lzwsize=ch;
            if (lzwsize > max_lzw_bits) {
                state=Error;
            } else {
                code_size=lzwsize+1;
                clear_code=1<<lzwsize;
                end_code=clear_code+1;
                max_code_size=2*clear_code;
                max_code=clear_code+2;
                int i;
                for (i=0; i<clear_code; i++) {
                    table[0][i]=0;
                    table[1][i]=i;
                }
                state=ImageDataBlockSize;
            }
            count=0;
            break;
          } case ImageDataBlockSize:
            expectcount=ch;
            if (expectcount) {
                state=ImageDataBlock;
            } else {
                state=Introducer;
                digress = true;
                newFrame = true;
            }
            break;
          case ImageDataBlock:
            count++;
            accum|=(ch<<bitcount);
            bitcount+=8;
            while (bitcount>=code_size && state==ImageDataBlock) {
                int code=accum&((1<<code_size)-1);
                bitcount-=code_size;
                accum>>=code_size;

                if (code==clear_code) {
                    if (!needfirst) {
                        code_size=lzwsize+1;
                        max_code_size=2*clear_code;
                        max_code=clear_code+2;
                    }
                    needfirst=true;
                } else if (code==end_code) {
                    bitcount = -32768;
                    // Left the block end arrive
                } else {
                    if (needfirst) {
                        firstcode=oldcode=code;
                        if (!out_of_bounds && image->height() > y && firstcode!=trans_index)
                            ((QRgb*)image->scanLine(y))[x] = color(firstcode);
                        x++;
                        if (x>=swidth) out_of_bounds = true;
                        needfirst=false;
                        if (x>=left+width) {
                            x=left;
                            out_of_bounds = left>=swidth || y>=sheight;
                            nextY(image);
                        }
                    } else {
                        incode=code;
                        if (code>=max_code) {
                            *sp++=firstcode;
                            code=oldcode;
                        }
                        while (code>=clear_code+2) {
                            *sp++=table[1][code];
                            if (code==table[0][code]) {
                                state=Error;
                                break;
                            }
                            if (sp-stack>=(1<<(max_lzw_bits))*2) {
                                state=Error;
                                break;
                            }
                            code=table[0][code];
                        }
                        *sp++=firstcode=table[1][code];
                        code=max_code;
                        if (code<(1<<max_lzw_bits)) {
                            table[0][code]=oldcode;
                            table[1][code]=firstcode;
                            max_code++;
                            if ((max_code>=max_code_size)
                             && (max_code_size<(1<<max_lzw_bits)))
                            {
                                max_code_size*=2;
                                code_size++;
                            }
                        }
                        oldcode=incode;
                        const int h = image->height();
                        const QRgb *map = lcmap ? localcmap : globalcmap;
                        QRgb *line = 0;
                        if (!out_of_bounds && h > y)
                            line = (QRgb*)image->scanLine(y);
                        while (sp>stack) {
                            const uchar index = *(--sp);
                            if (!out_of_bounds && h > y && index!=trans_index) {
                                if (index > ncols)
                                    line[x] = Q_TRANSPARENT;
                                else
                                    line[x] = map ? map[index] : 0;
                            }
                            x++;
                            if (x>=swidth) out_of_bounds = true;
                            if (x>=left+width) {
                                x=left;
                                out_of_bounds = left>=swidth || y>=sheight;
                                nextY(image);
                                if (!out_of_bounds && h > y)
                                    line = (QRgb*)image->scanLine(y);
                            }
                        }
                    }
                }
            }
            partialNewFrame = true;
            if (count==expectcount) {
                count=0;
                state=ImageDataBlockSize;
            }
            break;
          case ExtensionLabel:
            switch (ch) {
            case 0xf9:
                state=GraphicControlExtension;
                break;
            case 0xff:
                state=ApplicationExtension;
                break;
#if 0
            case 0xfe:
                state=CommentExtension;
                break;
            case 0x01:
                break;
#endif
            default:
                state=SkipBlockSize;
            }
            count=0;
            break;
          case ApplicationExtension:
            if (count<11) hold[count]=ch;
            count++;
            if (count==hold[0]+1) {
                if (qstrncmp((char*)(hold+1), "NETSCAPE", 8)==0) {
                    // Looping extension
                    state=NetscapeExtensionBlockSize;
                } else {
                    state=SkipBlockSize;
                }
                count=0;
            }
            break;
          case NetscapeExtensionBlockSize:
            expectcount=ch;
            count=0;
            if (expectcount) state=NetscapeExtensionBlock;
            else state=Introducer;
            break;
          case NetscapeExtensionBlock:
            if (count<3) hold[count]=ch;
            count++;
            if (count==expectcount) {
                *loopCount = hold[1]+hold[2]*256;
                state=SkipBlockSize; // Ignore further blocks
            }
            break;
          case GraphicControlExtension:
            if (count<5) hold[count]=ch;
            count++;
            if (count==hold[0]+1) {
                disposePrevious(image);
                disposal=Disposal((hold[1]>>2)&0x7);
                //UNUSED: waitforuser=!!((hold[1]>>1)&0x1);
                int delay=count>3 ? LM(hold[2], hold[3]) : 1;
                // IE and mozilla use a minimum delay of 10. With the minimum delay of 10
                // we are compatible to them and avoid huge loads on the app and xserver.
                *nextFrameDelay = (delay < 2 ? 10 : delay) * 10;

                bool havetrans=hold[1]&0x1;
                trans_index = havetrans ? hold[4] : -1;

                count=0;
                state=SkipBlockSize;
            }
            break;
          case SkipBlockSize:
            expectcount=ch;
            count=0;
            if (expectcount) state=SkipBlock;
            else state=Introducer;
            break;
          case SkipBlock:
            count++;
            if (count==expectcount) state=SkipBlockSize;
            break;
          case Done:
            digress=true;
            /* Netscape ignores the junk, so we do too.
            length++; // Unget
            state=Error; // More calls to this is an error
            */
            break;
          case Error:
            return -1; // Called again after done.
        }
    }
/*!
    This function decodes some data into image changes.

    Returns the number of bytes consumed.
*/
int QGIFFormat::decode(QImage& img, QImageConsumer* consumer,
	const uchar* buffer, int length)
{
    // We are required to state that
    //    "The Graphics Interchange Format(c) is the Copyright property of
    //    CompuServe Incorporated. GIF(sm) is a Service Mark property of
    //    CompuServe Incorporated."

#define LM(l, m) (((m)<<8)|l)
    digress = FALSE;
    int initial = length;
    QRgb** line = (QRgb **)img.jumpTable();
    while (!digress && length) {
	length--;
	unsigned char ch=*buffer++;
	switch (state) {
	  case Header:
	    hold[count++]=ch;
	    if (count==6) {
		// Header
		gif89=(hold[3]!='8' || hold[4]!='7');
		state=LogicalScreenDescriptor;
		count=0;
	    }
	    break;
	  case LogicalScreenDescriptor:
	    hold[count++]=ch;
	    if (count==7) {
		// Logical Screen Descriptor
		swidth=LM(hold[0], hold[1]);
		sheight=LM(hold[2], hold[3]);
		gcmap=!!(hold[4]&0x80);
		//UNUSED: bpchan=(((hold[4]&0x70)>>3)+1);
		//UNUSED: gcmsortflag=!!(hold[4]&0x08);
		gncols=2<<(hold[4]&0x7);
		bgcol=(gcmap) ? hold[5] : -1;
		//aspect=hold[6] ? double(hold[6]+15)/64.0 : 1.0;

		trans_index = -1;
		count=0;
		ncols=gncols;
		if (gcmap) {
		    ccount=0;
		    state=GlobalColorMap;
		    globalcmap = new QRgb[gncols+1]; // +1 for trans_index
		    globalcmap[gncols] = Q_TRANSPARENT;
		} else {
		    state=Introducer;
		}
	    }
	    break;
	  case GlobalColorMap: case LocalColorMap:
	    hold[count++]=ch;
	    if (count==3) {
		QRgb rgb = qRgb(hold[0], hold[1], hold[2]);
		if ( state == LocalColorMap ) {
		    if ( ccount < lncols )
			localcmap[ccount] =  rgb;
		} else {
		    globalcmap[ccount] = rgb;
		}
		if (++ccount >= ncols) {
		    if ( state == LocalColorMap )
			state=TableImageLZWSize;
		    else
			state=Introducer;
		}
		count=0;
	    }
	    break;
	  case Introducer:
	    hold[count++]=ch;
	    switch (ch) {
	      case ',':
		state=ImageDescriptor;
		break;
	      case '!':
		state=ExtensionLabel;
		break;
	      case ';':
		if (consumer) {
		    if ( out_of_bounds ) // flush anything that survived
			consumer->changed(QRect(0,0,swidth,sheight));
		    consumer->end();
		}
		state=Done;
		break;
	      default:
		digress=TRUE;
		// Unexpected Introducer - ignore block
		state=Error;
	    }
	    break;
	  case ImageDescriptor:
	    hold[count++]=ch;
	    if (count==10) {
		int newleft=LM(hold[1], hold[2]);
		int newtop=LM(hold[3], hold[4]);
		int width=LM(hold[5], hold[6]);
		int height=LM(hold[7], hold[8]);

		// disbelieve ridiculous logical screen sizes,
		// unless the image frames are also large.
		if ( swidth/10 > QMAX(width,200) )
		    swidth = -1;
		if ( sheight/10 > QMAX(height,200) )
		    sheight = -1;

		if ( swidth <= 0 )
		    swidth = newleft + width;
		if ( sheight <= 0 )
		    sheight = newtop + height;

		if (img.isNull()) {
		    img.create(swidth, sheight, 32);
		    memset( img.bits(), 0, img.numBytes() );
		    if (consumer) consumer->setSize(swidth, sheight);
		}
		img.setAlphaBuffer(trans_index >= 0);
		line = (QRgb **)img.jumpTable();

		disposePrevious( img, consumer );
		disposed = FALSE;

		left = newleft;
		top = newtop;

		// Sanity check frame size - must fit on "screen".
		if (left >= swidth) left=QMAX(0, swidth-1);
		if (top >= sheight) top=QMAX(0, sheight-1);
		if (left+width >= swidth) {
		    if ( width <= swidth )
			left=swidth-width;
		    else
			width=swidth-left;
		}
		if (top+height >= sheight) {
		    if ( height <= sheight )
			top=sheight-height;
		    else
			height=sheight-top;
		}

		right=QMAX( 0, left+width-1);
		bottom=QMAX(0, top+height-1);
		lcmap=!!(hold[9]&0x80);
		interlace=!!(hold[9]&0x40);
		//bool lcmsortflag=!!(hold[9]&0x20);
		lncols=lcmap ? (2<<(hold[9]&0x7)) : 0;
		if (lncols) {
		    if ( localcmap )
			delete [] localcmap;
		    localcmap = new QRgb[lncols+1];
		    localcmap[lncols] = Q_TRANSPARENT;
		    ncols = lncols;
		} else {
		    ncols = gncols;
		}
		frame++;
		if ( frame == 0 ) {
		    if ( left || top || width!=swidth || height!=sheight ) {
			// Not full-size image - erase with bg or transparent
			if ( trans_index >= 0 ) {
			    fillRect(img, 0, 0, swidth, sheight, color(trans_index));
			    if (consumer) consumer->changed(QRect(0,0,swidth,sheight));
			} else if ( bgcol>=0 ) {
			    fillRect(img, 0, 0, swidth, sheight, color(bgcol));
			    if (consumer) consumer->changed(QRect(0,0,swidth,sheight));
			}
		    }
		}

		if ( disposal == RestoreImage ) {
		    int l = QMIN(swidth-1,left);
		    int r = QMIN(swidth-1,right);
		    int t = QMIN(sheight-1,top);
		    int b = QMIN(sheight-1,bottom);
		    int w = r-l+1;
		    int h = b-t+1;

		    if (backingstore.width() < w
			|| backingstore.height() < h) {
			// We just use the backing store as a byte array
			backingstore.create( QMAX(backingstore.width(), w),
					     QMAX(backingstore.height(), h),
					     32);
			memset( img.bits(), 0, img.numBytes() );
		    }
		    for (int ln=0; ln<h; ln++) {
			memcpy(backingstore.scanLine(ln),
			       line[t+ln]+l, w*sizeof(QRgb));
		    }
		}

		count=0;
		if (lcmap) {
		    ccount=0;
		    state=LocalColorMap;
		} else {
		    state=TableImageLZWSize;
		}
		x = left;
		y = top;
		accum = 0;
		bitcount = 0;
		sp = stack;
		needfirst = FALSE;
		out_of_bounds = FALSE;
	    }
	    break;
	  case TableImageLZWSize: {
	    lzwsize=ch;
	    if ( lzwsize > max_lzw_bits ) {
		state=Error;
	    } else {
		code_size=lzwsize+1;
		clear_code=1<<lzwsize;
		end_code=clear_code+1;
		max_code_size=2*clear_code;
		max_code=clear_code+2;
		int i;
		for (i=0; i<clear_code && i<(1<<max_lzw_bits); i++) {
		    table[0][i]=0;
		    table[1][i]=i;
		}
		for (i=clear_code; i<(1<<max_lzw_bits); i++) {
		    table[0][i]=table[1][i]=0;
		}
		state=ImageDataBlockSize;
	    }
	    count=0;
	    break;
	  } case ImageDataBlockSize:
	    expectcount=ch;
	    if (expectcount) {
		state=ImageDataBlock;
	    } else {
		if (consumer) {
		    consumer->frameDone();
		    digress = TRUE;
		}

		state=Introducer;
	    }
	    break;
	  case ImageDataBlock:
	    count++;
	    accum|=(ch<<bitcount);
	    bitcount+=8;
	    while (bitcount>=code_size && state==ImageDataBlock) {
		int code=accum&((1<<code_size)-1);
		bitcount-=code_size;
		accum>>=code_size;

		if (code==clear_code) {
		    if (!needfirst) {
			int i;
			code_size=lzwsize+1;
			max_code_size=2*clear_code;
			max_code=clear_code+2;
			for (i=0; i<clear_code; i++) {
			    table[0][i]=0;
			    table[1][i]=i;
			}
			for (i=clear_code; i<(1<<max_lzw_bits); i++) {
			    table[0][i]=table[1][i]=0;
			}
		    }
		    needfirst=TRUE;
		} else if (code==end_code) {
		    bitcount = -32768;
		    // Left the block end arrive
		} else {
		    if (needfirst) {
			firstcode=oldcode=code;
			if (!out_of_bounds && line && firstcode!=trans_index)
			    line[y][x] = color(firstcode);
			x++;
			if (x>=swidth) out_of_bounds = TRUE;
			needfirst=FALSE;
			if (x>right) {
			    x=left;
			    if (out_of_bounds)
				out_of_bounds = left>=swidth || y>=sheight;
			    nextY(img,consumer);
			}
		    } else {
			incode=code;
			if (code>=max_code) {
			    *sp++=firstcode;
			    code=oldcode;
			}
			while (code>=clear_code) {
			    *sp++=table[1][code];
			    if (code==table[0][code]) {
				state=Error;
				break;
			    }
			    if (sp-stack>=(1<<(max_lzw_bits))*2) {
				state=Error;
				break;
			    }
			    code=table[0][code];
			}
			*sp++=firstcode=table[1][code];
			code=max_code;
			if (code<(1<<max_lzw_bits)) {
			    table[0][code]=oldcode;
			    table[1][code]=firstcode;
			    max_code++;
			    if ((max_code>=max_code_size)
			     && (max_code_size<(1<<max_lzw_bits)))
			    {
				max_code_size*=2;
				code_size++;
			    }
			}
			oldcode=incode;
			while (sp>stack) {
			    --sp;
			    if (!out_of_bounds && *sp!=trans_index)
				line[y][x] = color(*sp);
			    x++;
			    if (x>=swidth) out_of_bounds = TRUE;
			    if (x>right) {
				x=left;
				if (out_of_bounds)
				    out_of_bounds = left>=swidth || y>=sheight;
				nextY(img,consumer);
			    }
			}
		    }
		}
	    }
	    if (count==expectcount) {
		count=0;
		state=ImageDataBlockSize;
	    }
	    break;
	  case ExtensionLabel:
	    switch (ch) {
	    case 0xf9:
		state=GraphicControlExtension;
		break;
	    case 0xff:
		state=ApplicationExtension;
		break;
#if 0
	    case 0xfe:
		state=CommentExtension;
		break;
	    case 0x01:
		break;
#endif
	    default:
		state=SkipBlockSize;
	    }
	    count=0;
	    break;
	  case ApplicationExtension:
	    if (count<11) hold[count]=ch;
	    count++;
	    if (count==hold[0]+1) {
		if (qstrncmp((char*)(hold+1), "NETSCAPE", 8)==0) {
		    // Looping extension
		    state=NetscapeExtensionBlockSize;
		} else {
		    state=SkipBlockSize;
		}
		count=0;
	    }
	    break;
	  case NetscapeExtensionBlockSize:
	    expectcount=ch;
	    count=0;
	    if (expectcount) state=NetscapeExtensionBlock;
	    else state=Introducer;
	    break;
	  case NetscapeExtensionBlock:
	    if (count<3) hold[count]=ch;
	    count++;
	    if (count==expectcount) {
		int loop = hold[0]+hold[1]*256;
		if (consumer) consumer->setLooping(loop);
		state=SkipBlockSize; // Ignore further blocks
	    }
	    break;
	  case GraphicControlExtension:
	    if (count<5) hold[count]=ch;
	    count++;
	    if (count==hold[0]+1) {
		disposePrevious( img, consumer );
		disposal=Disposal((hold[1]>>2)&0x7);
		//UNUSED: waitforuser=!!((hold[1]>>1)&0x1);
		int delay=count>3 ? LM(hold[2], hold[3]) : 1;
		// IE and mozilla use a minimum delay of 10. With the minumum delay of 10
		// we are compatible to them and avoid huge loads on the app and xserver.
		if ( delay < 10 )
		    delay = 10;

		bool havetrans=hold[1]&0x1;
 		trans_index = havetrans ? hold[4] : -1;

		if (consumer) consumer->setFramePeriod(delay*10);
		count=0;
		state=SkipBlockSize;
	    }
	    break;
	  case SkipBlockSize:
	    expectcount=ch;
	    count=0;
	    if (expectcount) state=SkipBlock;
	    else state=Introducer;
	    break;
	  case SkipBlock:
	    count++;
	    if (count==expectcount) state=SkipBlockSize;
	    break;
	  case Done:
	    digress=TRUE;
	    /* Netscape ignores the junk, so we do too.
	    length++; // Unget
	    state=Error; // More calls to this is an error
	    */
	    break;
	  case Error:
	    return -1; // Called again after done.
	}
    }
示例#19
-2
文件: Test_LP.cpp 项目: 2080/HElib
void  TestIt(long R, long p, long r, long d, long c, long k, long w, 
               long L, long m)
{
  cerr << "\n\n******** TestIt: R=" << R 
       << ", p=" << p
       << ", r=" << r
       << ", d=" << d
       << ", c=" << c
       << ", k=" << k
       << ", w=" << w
       << ", L=" << L
       << ", m=" << m
       << endl;

  FHEcontext context(m, p, r);
  buildModChain(context, L, c);

  // context.lazy = false;

  if (context.lazy)
    cerr << "LAZY REDUCTIONS\n";
  else
    cerr << "NON-LAZY REDUCTIONS\n";

  context.zMStar.printout();
  cerr << endl;
#ifdef DEBUG
  cerr << context << endl;
#endif

  FHESecKey secretKey(context);
  const FHEPubKey& publicKey = secretKey;
  secretKey.GenSecKey(w); // A Hamming-weight-w secret key


  ZZX G;

  if (d == 0) {
    G = context.alMod.getFactorsOverZZ()[0];
    d = deg(G);
  }
  else
    G = makeIrredPoly(p, d); 

  cerr << "G = " << G << "\n";
  cerr << "generating key-switching matrices... ";
  addSome1DMatrices(secretKey); // compute key-switching matrices that we need
  addFrbMatrices(secretKey); // compute key-switching matrices that we need
  cerr << "done\n";


  cerr << "computing masks and tables for rotation...";
  EncryptedArray ea(context, G);
  cerr << "done\n";


  long nslots = ea.size();


  // L selects even coefficients
  vector<ZZX> LM(d);
  for (long j = 0; j < d; j++) 
    if (j % 2 == 0) LM[j] = ZZX(j, 1);

  vector<ZZX> C;
  ea.buildLinPolyCoeffs(C, LM);

  PlaintextArray p0(ea);
  p0.random();
  
  Ctxt c0(publicKey);
  ea.encrypt(c0, publicKey, p0);

  Ctxt res(c0);

  applyLinPoly1(ea, res, C);

  PlaintextArray pp0(ea);
  ea.decrypt(res, secretKey, pp0);

  p0.print(cout); cout << "\n";
  pp0.print(cout); cout << "\n";

}