// This method is called to reset the texmap back to its default values. void Planet::Init() { // Reset the XYZGen or allocate a new one if (xyzGen) xyzGen->Reset(); else ReplaceReference(0, GetNewDefaultXYZGen()); // ReplaceReference(1, CreateParameterBlock(pbdesc, // PB_LENGTH, PLANET_PB_VERSION)); // if (paramDlg) // paramDlg->pmap->SetParamBlock(pblock); // Set the inital parameters // {10,20,80},{10,30,80},{10,40,90},{10,100,12}, // {100,80,12},{80,20,8},{100,80,50},{100,100,100} SetColor(0, Color(0.04f, 0.08f, 0.31f), TimeValue(0)); SetColor(1, Color(0.04f, 0.12f, 0.31f), TimeValue(0)); SetColor(2, Color(0.04f, 0.16f, 0.31f), TimeValue(0)); SetColor(3, Color(0.04f, 0.39f, 0.05f), TimeValue(0)); SetColor(4, Color(0.39f, 0.31f, 0.05f), TimeValue(0)); SetColor(5, Color(0.31f, 0.08f, 0.03f), TimeValue(0)); SetColor(6, Color(0.39f, 0.31f, 0.20f), TimeValue(0)); SetColor(7, Color(0.39f, 0.39f, 0.39f), TimeValue(0)); SetSize(40.0f, TimeValue(0)); SetIsland(0.5f, TimeValue(0)); SetPercent(60.0f, TimeValue(0)); SetSeed(12345, TimeValue(0)); blend = 1; // Set the validity interval of the texture to empty texValidity.SetEmpty(); }
// This is the inititialization routine. This has to be called first! CALMAPI::CALMAPI( void ) { // store stream defaults, since we will be manipulating width and precision GetStreamDefaults(); // initialize the random number generator for the E-node activation SetSeed( GetSeed() ); // store the current working directory getcwd( mCALMCurDir, FILENAME_MAX ); strcpy( mCALMLogDir, mCALMCurDir ); // init log dir to same dir // Initialize and set the global network specifications data mNetwork = new CALMNetwork; mInput = NULL; mInputLen = 0; mNumRuns = 1; mNumEpochs = 50; mNumIterations = 100; mOrder = kPermuted; mVerbosity = O_WINNER; mConvstop = false; mFBOn = false; strcpy( mBasename, "calm" ); strcpy( mDirname, "." ); mLogFile = NULL; mCALMLog = &cout; }
//~~~~~~~~~~~~~~~FUNCTII PENTRU CRIPTARE/DECRIPTARE~~~~~~~~~~~~~~ void gen_p_q_n_phi_n() { SetSeed(to_ZZ(6)); GenGermainPrime(p,512); q=p; while(p==q) { GenGermainPrime(q,512); SetSeed(to_ZZ(10)); } n=p*q; phi_n=(p-1)*(q-1); }
NoiseBase::NoiseBase(unsigned int seed) : m_scale(0.05f) { SetSeed(seed); // Fill permutations with initial values std::iota(m_permutations.begin(), m_permutations.begin() + 256, 0); }
CMultiplePrimeRandom::CMultiplePrimeRandom(ULONG32 seed) { m_rand_m = RAND_M_INIT; m_rand_ia = RAND_IA_INIT; m_rand_ib = RAND_IB_INIT; m_rand_irand = RAND_IRAND_INIT; SetSeed(seed); }
CMultiplePrimeRandom::CMultiplePrimeRandom() { m_rand_m = RAND_M_INIT; m_rand_ia = RAND_IA_INIT; m_rand_ib = RAND_IB_INIT; m_rand_irand = RAND_IRAND_INIT; SetSeed(HX_GET_TICKCOUNT()); }
// --- Methods inherited from Tex3D --- void Planet::ReadSXPData(TCHAR *name, void *sxpdata) { PlanetState *state = (PlanetState*)sxpdata; if (state != NULL && (state->version == PLANET_SXP_VERSION)) { SetSize(state->size, TimeValue(0)); SetPercent(state->percent, TimeValue(0)); SetIsland(state->island, TimeValue(0)); SetSeed(state->seed, TimeValue(0)); } }
void InitNewBattle() { //播撒随机数种子 SetSeed(); //清扫之前的战场 pBattlefield->SweepBattlefield(true,true,true,true); }
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"); } }
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; }
/* Usage: Test_EvalMap_x.exe [ name=value ]... * p plaintext base [ default=2 ] * r lifting [ default=1 ] * c number of columns in the key-switching matrices [ default=2 ] * k security parameter [ default=80 ] * L # of levels in the modulus chain [ default=6 ] * s minimum number of slots [ default=0 ] * seed PRG seed [ default=0 ] * mvec use specified factorization of m * e.g., mvec='[5 3 187]' * gens use specified vector of generators * e.g., gens='[562 1871 751]' * ords use specified vector of orders * e.g., ords='[4 2 -4]', negative means 'bad' */ int main(int argc, char *argv[]) { ArgMapping amap; long p=2; amap.arg("p", p, "plaintext base"); long r=1; amap.arg("r", r, "lifting"); long c=2; amap.arg("c", c, "number of columns in the key-switching matrices"); long k=80; amap.arg("k", k, "security parameter"); long L=6; amap.arg("L", L, "# of levels in the modulus chain"); long s=0; amap.arg("s", s, "minimum number of slots"); long seed=0; amap.arg("seed", seed, "PRG seed"); Vec<long> mvec; amap.arg("mvec", mvec, "use specified factorization of m", NULL); amap.note("e.g., mvec='[7 3 221]'"); Vec<long> gens; amap.arg("gens", gens, "use specified vector of generators", NULL); amap.note("e.g., gens='[3979 3095 3760]'"); Vec<long> ords; amap.arg("ords", ords, "use specified vector of orders", NULL); amap.note("e.g., ords='[6 2 -8]', negative means 'bad'"); amap.arg("dry", dry, "a dry-run flag to check the noise"); long nthreads=1; amap.arg("nthreads", nthreads, "number of threads"); amap.arg("noPrint", noPrint, "suppress printouts"); long useCache=0; amap.arg("useCache", useCache, "0: zzX cache, 2: DCRT cache"); amap.parse(argc, argv); SetNumThreads(nthreads); SetSeed(conv<ZZ>(seed)); TestIt(p, r, c, k, /*Key Hamming weight=*/64, L, mvec, gens, ords, useCache); }
/* function initField : Initialize the field GF2E with irreducible polynomial. * param t : degree of the irreducible polynomial * param randomNum : seed for the random calculations. */ void initField(jint t, jint randomNum){ //Create an irreducible polynomial. GF2X irredPoly = BuildSparseIrred_GF2X(t); //init the field with the newly generated polynomial. GF2E::init(irredPoly); //Sets the seed to the random calculations. ZZ seed; seed = (int) randomNum; SetSeed(seed); }
int main(void) { int n=400, noisy=0, i,j; int nr=10, ir, TimeSquare=10, algorithm; /* TimeSquare should be larger for large t */ double t=5, *Q, *pi, *space, s; char timestr[96], *AlgStr[2]={"repeated squaring", "eigensolution"}; if((Q=(double*)malloc(n*n*5*sizeof(double))) ==NULL) error2("oom"); pi=Q+n*n; space=pi+n; for(algorithm=0; algorithm<2; algorithm++) { starttime(); SetSeed(1234567); for (i=0; i<n; i++) pi[i]=rndu(); s=sum(pi,n); for (i=0; i<n; i++) pi[i]/=s; for(ir=0; ir<nr; ir++) { printf("Replicate %d/%d ", ir+1,nr); for (i=0; i<n; i++) for (j=0,Q[i*n+i]=0; j<i; j++) Q[i*n+j]=Q[j*n+i] = square(rndu()); for (i=0; i<n; i++) for (j=0; j<n; j++) Q[i*n+j] *= pi[j]; for(i=0,s=0; i<n; i++) { /* rescaling Q so that average rate is 1 */ Q[i*n+i]=0; Q[i*n+i]=-sum(Q+i*n, n); s-=pi[i]*Q[i*n+i]; } if(noisy) { matout(stdout, pi, 1, n); matout(stdout, Q, n, n); } if(algorithm==0) matexp(Q, 1, n, TimeSquare, space); else PMatQRev(Q, pi, 1, n, space); printf("%s, time: %s\n", AlgStr[algorithm], printtime(timestr)); if(noisy) matout(stdout, Q, n, n); } } return (0); }
template <typename T> vec_ZZ RandomPoint(LatticeBasis<T>& B,int seed,int dim=0) { //Generate uniformly random point in the box \prod[-b*i/2,b*i/2] B.updateGSBasis(); vec_ZZ ret; ZZ det = LatticeVolumeZZ(B); if (dim==0) dim = B.dim; ret.SetLength(dim); SetSeed(to_ZZ(seed)); for (int i=0;i<dim;i++) { ret[i] = RandomBnd(det); } ret = NearestPlane(ret,B); return ret; }
// This is the inititialization routine. This has to be called first! SequenceAPI::SequenceAPI( void ) { // store stream defaults, since we will be manipulating width and precision GetStreamDefaults(); // initialize the random number generator for noise SetSeed( GetSeed() ); // store the current working directory getcwd( mSequenceCurDir, FILENAME_MAX ); strcpy( mSequenceLogDir, mSequenceCurDir ); // init log dir to same dir mPatterns = new Patterns(); // this just sets an empty pattern class // set defaults for the network specifications strcpy( mBasename, "seq" ); strcpy( mDirname, "." ); mNumFiles = 1; mFileIndex = 0; mRuns = 1; mEpochs = 1000; mIterations = 10; mRecallLen = 100; mNumLayers = 8; mLayerSize = 16; mContextSize = 16; mOrder = kPermutedOrder; mType = O_INF; mVerbosity = O_ERROR; mErrCrit = 0.1; mAlphaCrit = 0.01; mRecallCrit = 0.05; mTermNoise = 0.05; mError = -1.0; mOldInput = NULL; mNewInput = NULL; mInContext = NULL; mTextDisplay = NULL; mNetwork = NULL; mNoise = NULL; mSequenceLog = &cout; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int ndims, len, i; int *dims; double *indata, *outdata; long ix,iy,iz; if((nlhs > 1) || (nrhs > 1)) mexErrMsgTxt("Usage: seed = randomseed; (or) randomseed(new_seed);"); if(nrhs > 0) { /* prhs[0] is first argument. * mxGetPr returns double* (data, col-major) */ ndims = mxGetNumberOfDimensions(prhs[0]); dims = (int*)mxGetDimensions(prhs[0]); indata = mxGetPr(prhs[0]); len = mxGetNumberOfElements(prhs[0]); if(mxIsSparse(prhs[0])) mexErrMsgTxt("Cannot handle sparse matrices. Sorry."); if(len == 1 && *indata == 0.0) { ResetSeed(); } else if(len != 3) { mexErrMsgTxt("seed must be 0 or a vector of 3 numbers."); } else { SetSeed((long)indata[0],(long)indata[1],(long)indata[2]); } } ndims = 1; dims = (int*)mxMalloc(sizeof(int)); dims[0] = 3; /* plhs[0] is first output */ plhs[0] = mxCreateNumericArray(ndims, dims, mxDOUBLE_CLASS, mxREAL); outdata = mxGetPr(plhs[0]); GetSeed(&ix,&iy,&iz); outdata[0] = (double)ix; outdata[1] = (double)iy; outdata[2] = (double)iz; }
template <typename T> mat_ZZ RandomPoints(LatticeBasis<T>& B,int seed,int numrows,int dim=0) { B.updateGSBasis(); vec_ZZ r; ZZ det = LatticeVolumeZZ(B); if (dim==0) dim = B.dim; r.SetLength(dim); mat_ZZ ret; ret.SetDims(numrows,dim); SetSeed(to_ZZ(seed)); for (int k=0;k<numrows;k++) { for (int i=0;i<dim;i++) { r[i] = RandomBnd(det); } ret[k] = NearestPlane(r,B); } return ret; }
/////////////////////////////////////////// // Create a random example /////////////////////////////////////////// void CRSAFactorHintDlg::OnRandom() { UpdateData(); int m_bitsOfP=GetDlgItemInt(IDC_EDITBITSOFP); if (m_bitsOfN<=10){ CString tmp, myTitle; tmp.LoadString(IDS_RSA_FH_WRONGN); this->GetWindowText(myTitle); MessageBox(tmp,myTitle); } else if(m_bitsOfP<=5 || m_bitsOfP>=m_bitsOfN){ CString tmp, myTitle; tmp.LoadString(IDS_RSA_FH_WRONGP); this->GetWindowText(myTitle); MessageBox(tmp,myTitle); } else{ BeginWaitCursor(); int bitsOfQ=(m_bitsOfN-m_bitsOfP); SetSeed(to_ZZ(GetTime()*10000)); m_p = GenPrime_ZZ(m_bitsOfP); // generate N, p and q ZZ q = GenPrime_ZZ(bitsOfQ); m_N=m_p*q; int newbase=2; // check which representation to use if(m_base==0) newbase=10; if(m_base==1) newbase=16; // m_N=toString(N,newbase,newbase*newbase*2); // m_P=toString(m_p,newbase,newbase*newbase*2); UpdateData(false); updateP(); updateDim(); EndWaitCursor(); } }
static void seed(void) { int fd; unsigned char randbuf[RANDBYTES]; if ( (fd = open("/dev/urandom", O_RDONLY, 0)) < 0) { cerr << "Error: Can't open /dev/urandom." << endl; exit(1); } if (read(fd, randbuf, RANDBYTES) != RANDBYTES) { cerr << "Error: Can't read from /dev/urandom." << endl; exit(1); } if (close(fd) < 0) { cerr << "Error: Can't close /dev/urandom." << endl; exit(1); } SetSeed(ZZFromBytes(randbuf, RANDBYTES)); }
RTPRandomRand48::RTPRandomRand48(uint32_t seed) { SetSeed(seed); }
Random::Random(UInt32 seed) { SetSeed(seed); }
// Constructor: it is assumed that zms is already set with m>1 // If q == 0, then the current context is used Cmodulus::Cmodulus(const PAlgebra &zms, long qq, long rt) { assert(zms.getM()>1); bool explicitModulus = true; if (qq == 0) { q = zz_p::modulus(); explicitModulus = false; } else q = qq; zMStar = &zms; root = rt; long mm; mm = zms.getM(); m_inv = InvMod(mm, q); zz_pBak bak; if (zms.getPow2()) { // special case when m is a power of 2 assert( explicitModulus ); bak.save(); RandomState state; SetSeed(conv<ZZ>("84547180875373941534287406458029")); // DIRT: this ensures the roots are deterministically generated // inside the zz_pContext constructor context = zz_pContext(INIT_USER_FFT, q); state.restore(); context.restore(); powers.set_ptr(new zz_pX); ipowers.set_ptr(new zz_pX); long k = zms.getPow2(); long phim = 1L << (k-1); assert(k <= zz_pInfo->MaxRoot); // rootTables get initialized 0..zz_pInfo->Maxroot #ifdef FHE_OPENCL altFFTInfo = MakeSmart<AltFFTPrimeInfo>(); InitAltFFTPrimeInfo(*altFFTInfo, *zz_pInfo->p_info, k-1); #endif long w0 = zz_pInfo->p_info->RootTable[0][k]; long w1 = zz_pInfo->p_info->RootTable[1][k]; powers->rep.SetLength(phim); powers_aux.SetLength(phim); for (long i = 0, w = 1; i < phim; i++) { powers->rep[i] = w; powers_aux[i] = PrepMulModPrecon(w, q); w = MulMod(w, w0, q); } ipowers->rep.SetLength(phim); ipowers_aux.SetLength(phim); for (long i = 0, w = 1; i < phim; i++) { ipowers->rep[i] = w; ipowers_aux[i] = PrepMulModPrecon(w, q); w = MulMod(w, w1, q); } return; } if (explicitModulus) { bak.save(); // backup the current modulus context = BuildContext(q, NextPowerOfTwo(zms.getM()) + 1); context.restore(); // set NTL's current modulus to q } else context.save(); if (root==0) { // Find a 2m-th root of unity modulo q, if not given zz_p rtp; long e = 2*zms.getM(); FindPrimitiveRoot(rtp,e); // NTL routine, relative to current modulus if (rtp==0) // sanity check Error("Cmod::compRoots(): no 2m'th roots of unity mod q"); root = rep(rtp); } rInv = InvMod(root,q); // set rInv = root^{-1} mod q // Allocate memory (relative to current modulus that was defined above). // These objects will be initialized when anyone calls FFT/iFFT. zz_pX phimx_poly; conv(phimx_poly, zms.getPhimX()); powers.set_ptr(new zz_pX); Rb.set_ptr(new fftRep); ipowers.set_ptr(new zz_pX); iRb.set_ptr(new fftRep); phimx.set_ptr(new zz_pXModulus1(zms.getM(), phimx_poly)); BluesteinInit(mm, conv<zz_p>(root), *powers, powers_aux, *Rb); BluesteinInit(mm, conv<zz_p>(rInv), *ipowers, ipowers_aux, *iRb); }
NzWorley2D::NzWorley2D(unsigned int seed) : NzWorley2D() { SetSeed(seed); Shuffle(); }
int main (int argc, char*argv[]) { char *MCctlf=NULL, outf[512]="evolver.out", treefile[512]="mcmc.txt", mastertreefile[512]="\0"; int i, option=-1, ntree=1,rooted, BD=0, gotoption=0, pick1tree=-1; double bfactor=1, birth=-1,death=-1,sample=-1,mut=-1, *space; FILE *fout=gfopen(outf,"w"); printf("EVOLVER in %s\n", pamlVerStr); com.alpha=0; com.cleandata=1; com.model=0; com.NSsites=0; if(argc>1) { gotoption=1; sscanf(argv[1], "%d", &option); } if(argc==1) printf("Results for options 1-4 & 8 go into %s\n",outf); else if(option!=5 && option!=6 && option!=7 && option!=9) { puts("Usage: \n\tevolver \n\tevolver option# MyDataFile"); exit(-1); } if(option>=4 && option<=6) MCctlf = argv[2]; else if(option==9) { strcpy(treefile, argv[2]); if(argc>3) strcpy(mastertreefile, argv[3]); if(argc>4) sscanf(argv[4], "%d", &pick1tree); } #if defined (CodonNSbranches) option=6; com.model=1; MCctlf = (argc==3 ? argv[2] : "MCcodonNSbranches.dat"); gotoption = 1; #elif defined (CodonNSsites) option=6; com.NSsites=3; MCctlf = (argc==3 ? argv[2] : "MCcodonNSsites.dat"); gotoption = 1; #elif defined (CodonNSbranchsites) option=6; com.model=1; com.NSsites=3; MCctlf = (argc==3 ? argv[2] : "MCcodonNSbranchsites.dat"); gotoption = 1; #endif if(!gotoption) { for(; ;) { fflush(fout); printf("\n\t(1) Get random UNROOTED trees?\n"); printf("\t(2) Get random ROOTED trees?\n"); printf("\t(3) List all UNROOTED trees?\n"); printf("\t(4) List all ROOTED trees?\n"); printf("\t(5) Simulate nucleotide data sets (use %s)?\n",MCctlf0[0]); printf("\t(6) Simulate codon data sets (use %s)?\n",MCctlf0[1]); printf("\t(7) Simulate amino acid data sets (use %s)?\n",MCctlf0[2]); printf("\t(8) Calculate identical bi-partitions between trees?\n"); printf("\t(9) Calculate clade support values (evolver 9 treefile mastertreefile <pick1tree>)?\n"); printf("\t(11) Label clades?\n"); printf("\t(0) Quit?\n"); option = 9; scanf("%d", &option); if(option==0) exit(0); if(option>=5 && option<=7) break; if(option<5) { printf ("No. of species: "); scanf ("%d", &com.ns); } if(com.ns>NS) error2 ("Too many species. Raise NS."); if((space=(double*)malloc(10000*sizeof(double)))==NULL) error2("oom"); rooted = !(option%2); if(option<3) { printf("\nnumber of trees & random number seed? "); scanf("%d%d", &ntree, &i); SetSeed(i, 1); printf ("Want branch lengths from the birth-death process (0/1)? "); scanf ("%d", &BD); } if(option<=4) { if(com.ns<3) error2("no need to do this?"); i = (com.ns*2-1)*sizeof(struct TREEN); if((nodes=(struct TREEN*)malloc(i)) == NULL) error2("oom"); } switch (option) { case(1): /* random UNROOTED trees */ case(2): /* random ROOTED trees */ /* default names */ if(com.ns<=52) for(i=0; i<com.ns; i++) sprintf(com.spname[i], "%c", (i<26 ? 'A'+i : 'a'+i-26)); else for(i=0; i<com.ns; i++) sprintf(com.spname[i], "S%d", i+1); if(BD) { printf ("\nbirth rate, death rate, sampling fraction, and "); printf ("mutation rate (tree height)?\n"); scanf ("%lf%lf%lf%lf", &birth, &death, &sample, &mut); } for(i=0;i<ntree;i++) { RandomLHistory (rooted, space); if(BD) BranchLengthBD (1, birth, death, sample, mut); if(com.ns<20&&ntree<10) { OutTreeN(F0, 0, BD); puts("\n"); } OutTreeN(fout, 1, BD); FPN(fout); } /* for (i=0; i<com.ns-2-!rooted; i++) Ib[i] = (int)((3.+i)*rndu()); MakeTreeIb (com.ns, Ib, rooted); */ break; case(3): case(4): ListTrees(fout, com.ns, rooted); break; case(8): TreeDistances(fout); break; case(9): printf("tree file names? "); scanf("%s%s", treefile, mastertreefile); break; case(10): between_f_and_x(); break; case(11): LabelClades(fout); break; default: exit(0); } } } if(option>=5 && option<=7) { com.seqtype = option-5; /* 0, 1, 2 for bases, codons, & amino acids */ Simulate(MCctlf ? MCctlf : MCctlf0[option-5]); } else if(option==9) { CladeSupport(fout, treefile, mastertreefile, pick1tree); /* CladeMrBayesProbabilities("/papers/BPPJC3sB/Karol.trees"); */ } return(0); }
int main() { RR::SetPrecision(150); long n, b, size; cerr << "n: "; cin >> n; cerr << "b: "; cin >> b; cerr << "size: "; cin >> size; cerr << "prune: "; long prune; cin >> prune; ZZ seed; cerr << "seed: "; cin >> seed; if (seed != 0) SetSeed(seed); char alg; cerr << "alg [fqQxr]: "; cin >> alg; double TotalTime = 0; long TotalSucc = 0; long iter; for (iter = 1; iter <= 20; iter++) { vec_ZZ a; a.SetLength(n); ZZ bound; LeftShift(bound, to_ZZ(1), b); long i; for (i = 1; i <= n; i++) { RandomBnd(a(i), bound); a(i) += 1; } ZZ S; do { RandomLen(S, n+1); } while (weight(S) != n/2+1); ZZ s; clear(s); for (i = 1; i <= n; i++) if (bit(S, i-1)) s += a(i); mat_ZZ B(INIT_SIZE, n+1, n+3); for (i = 1; i <= n; i++) { B(i, i) = 2; B(i, n+1) = a(i) * n; B(i, n+3) = n; } for (i = 1; i <= n; i++) B(n+1, i) = 1; B(n+1, n+1) = s * n; B(n+1, n+2) = 1; B(n+1, n+3) = n; B(n+1, n+3) *= n/2; swap(B(1), B(n+1)); for (i = 2; i <= n; i++) { long j = RandomBnd(n-i+2) + i; swap(B(i), B(j)); } double t; LLLStatusInterval = 10; t = GetTime(); switch (alg) { case 'f': BKZ_FP(B, 0.99, size, prune, SubsetSumSolution); break; case 'q': BKZ_QP(B, 0.99, size, prune, SubsetSumSolution); break; case 'Q': BKZ_QP1(B, 0.99, size, prune, SubsetSumSolution); break; case 'x': BKZ_XD(B, 0.99, size, prune, SubsetSumSolution); break; case 'r': BKZ_RR(B, 0.99, size, prune, SubsetSumSolution); break; default: Error("invalid algorithm"); } t = GetTime()-t; long succ = 0; for (i = 1; i <= n+1; i++) if (SubsetSumSolution(B(i))) succ = 1; TotalTime += t; TotalSucc += succ; if (succ) cerr << "+"; else cerr << "-"; } cerr << "\n"; cerr << "number of success: " << TotalSucc << "\n"; cerr << "average time: " << TotalTime/20 << "\n"; return 0; }
void SobolGenerator::ResetDimensionality(unsigned long NewDimensionality) { RandomBase::ResetDimensionality(NewDimensionality); SetSeed(InitialSeed); }
void SobolGenerator::Reset() { SetSeed(InitialSeed); }
RTPRandomRand48::RTPRandomRand48() { SetSeed(PickSeed()); }
// Takes as arguments a ciphertext-part p relative to s' and a key-switching // matrix W = W[s'->s], uses W to switch p relative to (1,s), and adds the // result to *this. // It is assumed that the part p does not include any of the special primes, // and that if *this is not an empty ciphertext then its primeSet is // p.getIndexSet() \union context.specialPrimes void Ctxt::keySwitchPart(const CtxtPart& p, const KeySwitch& W) { FHE_TIMER_START; // no special primes in the input part assert(context.specialPrimes.disjointFrom(p.getIndexSet())); // For parts p that point to 1 or s, only scale and add if (p.skHandle.isOne() || p.skHandle.isBase(W.toKeyID)) { CtxtPart pp = p; pp.addPrimesAndScale(context.specialPrimes); addPart(pp, /*matchPrimeSet=*/true); return; } // some sanity checks assert(W.fromKey == p.skHandle); // the handles must match // Compute the number of digits that we need and the esitmated added noise // from switching this ciphertext part. long pSpace = W.ptxtSpace; long nDigits = 0; xdouble addedNoise = to_xdouble(0.0); double sizeLeft = context.logOfProduct(p.getIndexSet()); for (size_t i=0; i<context.digits.size() && sizeLeft>0.0; i++) { nDigits++; double digitSize = context.logOfProduct(context.digits[i]); if (sizeLeft<digitSize) digitSize=sizeLeft; // need only part of this digit // Added noise due to this digit is phi(m) * sigma^2 * pSpace^2 * |Di|^2/4, // where |Di| is the magnitude of the digit // WARNING: the following line is written just so to prevent overflow addedNoise += to_xdouble(context.zMStar.getPhiM()) * pSpace*pSpace * xexp(2*digitSize) * context.stdev*context.stdev / 4.0; sizeLeft -= digitSize; } // Sanity-check: make sure that the added noise is not more than the special // primes can handle: After dividing the added noise by the product of all // the special primes, it should be smaller than the added noise term due // to modulus switching, i.e., keyWeight * phi(m) * pSpace^2 / 12 long keyWeight = pubKey.getSKeyWeight(p.skHandle.getSecretKeyID()); double phim = context.zMStar.getPhiM(); double logModSwitchNoise = log((double)keyWeight) +2*log((double)pSpace) +log(phim) -log(12.0); double logKeySwitchNoise = log(addedNoise) -2*context.logOfProduct(context.specialPrimes); assert(logKeySwitchNoise < logModSwitchNoise); // Break the ciphertext part into digits, if needed, and scale up these // digits using the special primes. This is the most expensive operation // during homormophic evaluation, so it should be thoroughly optimized. vector<DoubleCRT> polyDigits; p.breakIntoDigits(polyDigits, nDigits); // Finally we multiply the vector of digits by the key-switching matrix // An object to hold the pseudorandom ai's, note that it must be defined // with the maximum number of levels, else the PRG will go out of synch. // FIXME: This is a bug waiting to happen. DoubleCRT ai(context); // Set the first ai using the seed, subsequent ai's (if any) will // use the evolving RNG state (NOTE: this is not thread-safe) RandomState state; SetSeed(W.prgSeed); // Add the columns in, one by one DoubleCRT tmp(context, IndexSet::emptySet()); for (unsigned long i=0; i<polyDigits.size(); i++) { ai.randomize(); tmp = polyDigits[i]; // The operations below all use the IndexSet of tmp // add part*a[i] with a handle pointing to base of W.toKeyID tmp.Mul(ai, /*matchIndexSet=*/false); addPart(tmp, SKHandle(1,1,W.toKeyID), /*matchPrimeSet=*/true); // add part*b[i] with a handle pointing to one polyDigits[i].Mul(W.b[i], /*matchIndexSet=*/false); addPart(polyDigits[i], SKHandle(), /*matchPrimeSet=*/true); } noiseVar += addedNoise; } // restore random state upon destruction of the RandomState, see NumbTh.h
//---------------------------------------------------------------------------- void medOpFlipNormals::OnEvent(mafEventBase *maf_event) //---------------------------------------------------------------------------- { if (mafEvent *e = mafEvent::SafeDownCast(maf_event)) { switch(e->GetId()) { case ID_OK: m_Dialog->EndModal(wxID_OK); break; case ID_CANCEL: m_Dialog->EndModal(wxID_CANCEL); break; case ID_UNSELECT: m_CellFilter->UndoMarks(); m_Rwi->m_RenderWindow->Render(); break; case ID_FIT: { vtkPolyData *polydata = vtkPolyData::SafeDownCast(((mafVME *)m_Input)->GetOutput()->GetVTKData()); double bounds[6] = {0,0,0,0,0,0}; polydata->GetBounds(bounds); m_Rwi->m_RenFront->ResetCamera(polydata->GetBounds()); m_Rwi->m_RenFront->ResetCameraClippingRange(bounds); m_Rwi->m_RenderWindow->Render(); } break; case VME_PICKED: { double pos[3]; vtkPoints *pts = NULL; pts = (vtkPoints *)e->GetVtkObj(); pts->GetPoint(0,pos); // get the picked cell and mark it as selected int cellID = e->GetArg(); if (cellID == m_CellSeed) { return; } SetSeed(cellID); // select circle region by pick MarkCellsInRadius(m_Diameter/2); m_Rwi->m_RenderWindow->Render(); } break; case ID_DELETE: { } break ; case ID_FLIP: { FlipNormals(); m_CellFilter->UndoMarks(); m_Rwi->m_RenderWindow->Render(); } break ; case ID_RESET: { m_ResultPolydata->DeepCopy(m_OriginalPolydata); m_ResultPolydata->Update(); m_Rwi->m_RenderWindow->Render(); } break ; case ID_ALL_NORMAL: { ModifyAllNormal(); m_Rwi->m_RenderWindow->Render(); } break ; default: mafEventMacro(*e); break; } } }