void UniformHelmholtzGreens ( ElementalMatrix<Complex<Real>>& A, Int n, Real lambda ) { EL_DEBUG_CSE typedef Complex<Real> C; const Real pi = 4*Atan( Real(1) ); const Real k0 = 2*pi/lambda; const Grid& g = A.Grid(); // Generate a list of n uniform samples from the 3D unit ball DistMatrix<Real,STAR,VR> X_STAR_VR(3,n,g); for( Int jLoc=0; jLoc<X_STAR_VR.LocalWidth(); ++jLoc ) { Real x0, x1, x2; // Sample uniformly from [-1,+1]^3 until a point is drawn from the ball while( true ) { x0 = SampleUniform( Real(-1), Real(1) ); x1 = SampleUniform( Real(-1), Real(1) ); x2 = SampleUniform( Real(-1), Real(1) ); const Real radiusSq = x0*x0 + x1*x1 + x2*x2; if( radiusSq > 0 && radiusSq <= 1 ) break; } X_STAR_VR.SetLocal( 0, jLoc, x0 ); X_STAR_VR.SetLocal( 1, jLoc, x1 ); X_STAR_VR.SetLocal( 2, jLoc, x2 ); } DistMatrix<Real,STAR,STAR> X_STAR_STAR( X_STAR_VR ); A.Resize( n, n ); for( Int jLoc=0; jLoc<A.LocalWidth(); ++jLoc ) { const Int j = A.GlobalCol(jLoc); const Real xj0 = X_STAR_STAR.GetLocal(0,j); const Real xj1 = X_STAR_STAR.GetLocal(1,j); const Real xj2 = X_STAR_STAR.GetLocal(2,j); for( Int iLoc=0; iLoc<A.LocalHeight(); ++iLoc ) { const Int i = A.GlobalRow(iLoc); if( i == j ) { A.SetLocal( iLoc, jLoc, 0 ); } else { const Real d0 = X_STAR_STAR.GetLocal(0,i)-xj0; const Real d1 = X_STAR_STAR.GetLocal(1,i)-xj1; const Real d2 = X_STAR_STAR.GetLocal(2,i)-xj2; const Real gamma = k0*Sqrt(d0*d0+d1*d1+d2*d2); const Real realPart = Cos(gamma)/gamma; const Real imagPart = Sin(gamma)/gamma; A.SetLocal( iLoc, jLoc, C(realPart,imagPart) ); } } } }
void UniformHelmholtzGreens( Matrix<Complex<Real>>& A, Int n, Real lambda ) { EL_DEBUG_CSE typedef Complex<Real> C; const Real pi = 4*Atan( Real(1) ); const Real k0 = 2*pi/lambda; // Generate a list of n uniform samples from the 3D unit ball Matrix<Real> X(3,n); for( Int j=0; j<n; ++j ) { Real x0, x1, x2; // Sample uniformly from [-1,+1]^3 until a point is drawn from the ball while( true ) { x0 = SampleUniform( Real(-1), Real(1) ); x1 = SampleUniform( Real(-1), Real(1) ); x2 = SampleUniform( Real(-1), Real(1) ); const Real radiusSq = x0*x0 + x1*x1 + x2*x2; if( radiusSq > 0 && radiusSq <= 1 ) break; } X(0,j) = x0; X(1,j) = x1; X(2,j) = x2; } A.Resize( n, n ); for( Int j=0; j<n; ++j ) { const Real xj0 = X(0,j); const Real xj1 = X(1,j); const Real xj2 = X(2,j); for( Int i=0; i<n; ++i ) { if( i == j ) { A(i,j) = 0; } else { const Real d0 = X(0,i)-xj0; const Real d1 = X(1,i)-xj1; const Real d2 = X(2,i)-xj2; const Real gamma = k0*Sqrt(d0*d0+d1*d1+d2*d2); const Real realPart = Cos(gamma)/gamma; const Real imagPart = Sin(gamma)/gamma; A(i,j) = C(realPart,imagPart); } } } }
glm::vec4 BRDF::sampleColor(FastStack<Ray> & rays, const Ray ray, const Intersection & result, Scene * scene) { glm::vec4 position = result.surface->worldTransform * result.surface->samplePosition(result.index, result.coord); glm::vec4 normal = glm::normalize( result.surface->worldTransformIT * result.surface->sampleNormal(result.index, result.coord)); float p = SampleUniform(); glm::vec4 totalColor(0.f, 0.f, 0.f, 0.f); if (p < emissiveProbability) { totalColor = emissiveIntensity * emissiveColor / emissiveProbability; } else if (ray.depth < maxDepth) { glm::vec4 strength = ray.strength * diffuseColor; glm::vec4 outgoing = SampleHemi(normal); Ray reflected(ray.depth + 1, position, outgoing, strength, PAC_EPSILON); rays.push(reflected); } else { totalColor.a = 1.f; } return totalColor * ray.strength; }
void BayesUnfoldingExample641() { #ifdef __CINT__ // Avoid CINT badness Printf("Please compile this script (root BayesUnfoldingExample641.C+) " "or use ROOT 6."); gSystem->Exit(0); #endif if (!gROOT->IsBatch()) { Printf("Several canvases coming...adding -b flag."); gROOT->SetBatch(); } gStyle->SetOptStat(0); gStyle->SetPaintTextFormat(".2f"); if (gSystem->Getenv("TMPDIR")) gSystem->SetBuildDir(gSystem->Getenv("TMPDIR")); TRandom3 ran; TStopwatch watch; // Watch starts here. A call to Start() would reset it. TObjArray *cList = new TObjArray(); // List of drawn canvases --> PDF file // Set up the problem double bins[Nt+1] = {0}; for (int j=0; j<=Nt; j++) bins[j] = 500*TMath::Exp(0.15*j); TestProblem testprob = AtlasDiJetMass(Nt, Nr, bins, bins, apar, bpar, nevts, evtWeight); TH2D *hM = testprob.Response; TH1D *hT = testprob.xTruth; TH1D *hTmc = testprob.xTruthEst; TH1D *hMt = testprob.xIni; TH1D *hD = testprob.bNoisy; TH1D *heff = testprob.eff; SetHistProps(hT,kRed+2,kNone,kRed+2); SetHistProps(hTmc,kRed,kNone,kRed); SetHistProps(hD,kBlack,kNone,kBlack,kFullCircle,1.5); TMatrixD M = MatrixUtils::Hist2Matrix(hM); TVectorD T = MatrixUtils::Hist2Vec(hT); // \hat{T} TVectorD Tmc = MatrixUtils::Hist2Vec(hTmc); // \tilde{T} TVectorD D = MatrixUtils::Hist2Vec(hD); TVectorD eff = MatrixUtils::Hist2Vec(heff); TVectorD Pt = MatrixUtils::ElemDiv(MatrixUtils::Hist2Vec(hMt), eff); // P(t) TMatrixD Prt = MatrixUtils::DivRowsByVector(M, Pt); // P(r|t) // Compute initial sampling volume and do MCMC sampling TGraphAsymmErrors *box = HyperBox(hTmc); SetGraphProps(box, kGreen+2, kNone, kSpring, kFullSquare, 1.0); // Likelihood functor LogPoissonLikeFn llfunc(Prt, D); // Curvature regularization. // Note that this is not directly penalizing curvature of the solution. // Instead it smooths the solution divided by the trial spectrum. std::vector<double> regpars; regpars.push_back(alpha); // Regularization strength for (int i=0; i<box->GetN(); i++) regpars.push_back(box->GetY()[i]); CurvatureRegFn regfunc(regpars); TTree *tmcmc = SampleMH(nMcmcSamples, 1e4, 0.01, box, llfunc, regfunc); // Create marginal prob. distributions from MCMC std::cout << Form("Marginalizing parameters from Markov chain...") << std::flush; TH1D *hMCMC[Nt]; for (int t=0; t<Nt; t++) { double tlo = box->GetY()[t] - box->GetEYlow()[t]; double thi = box->GetY()[t] + box->GetEYhigh()[t]; hMCMC[t] = new TH1D(Form("hMCMC%d",t),"",nMcmcBins, tlo, thi); hMCMC[t]->SetTitle(Form("MCMC - point %d;" "entries;" "Marginal posterior probability",t)); // Marginalize with unit weight when using MCMC, weight by // likelihood if sampling was uniform. tmcmc->Draw(Form("T%d >> hMCMC%d",t,t), "", "goff"); hMCMC[t]->Scale(1./hMCMC[t]->Integral(1, nMcmcBins)); SetHistProps(hMCMC[t], kBlack, kYellow, kBlack, kFullCircle, 1.0); hMCMC[t]->GetYaxis()->SetTitleOffset(1.5); } Printf("Done marginalizing MCMC."); // Now compute reduced sampling volume, and do uniform sampling TGraphAsymmErrors *rbox = ReducedSamplingVolume(hMCMC, box); SetGraphProps(rbox, kBlack, kNone, kNone, kFullSquare, 1.0); TH1D *hFlat[Nt]; if (doUniformSampling) { TTree *tflat = SampleUniform(nFlatSamples, D, Prt, rbox); std::cout << Form("Marginalizing parameters from uniform volume...") << std::flush; for (int t=0; t<Nt; t++) { double tlo = rbox->GetY()[t] - rbox->GetEYlow()[t]; double thi = rbox->GetY()[t] + rbox->GetEYhigh()[t]; hFlat[t] = new TH1D(Form("hFlat%d",t),"",nFlatBins, tlo, thi); hFlat[t]->SetTitle(Form("Uniform sampling - point %d;" "dijet mass (GeV/c^{2});" "Marginal posterior probability",t)); tflat->Draw(Form("T%d >> hFlat%d",t,t), "L", "goff"); hFlat[t]->Scale(1./hFlat[t]->Integral(1,nFlatBins)); SetHistProps(hFlat[t], kBlack, kOrange, kBlack, kFullCircle, 1.0); } Printf("Done marginalizing uniform volume."); } // Unfolded spectrum from MCMC TGraphErrors *unf1 = new TGraphErrors(); SetGraphProps(unf1, kBlue, kNone, kBlue, kOpenSquare, 1.5); unf1->SetLineWidth(2); for (int t=0; t<Nt; t++) { MaxDensityInterval mdi = GetMDI(hMCMC[t], 0.68); unf1->SetPoint(t, hD->GetBinCenter(t+1), mdi.u); unf1->SetPointError(t, 0.48*hD->GetBinWidth(t+1), mdi.du); } // Unfolded spectrum from uniform sampling after volume reduction TGraphErrors *unf2 = 0; if (doUniformSampling) { unf2 = new TGraphErrors(); SetGraphProps(unf2, kRed, kNone, kRed, kOpenSquare, 1.5); unf2->SetLineWidth(2); for (int t=0; t<Nt; t++) { MaxDensityInterval mdi = GetMDI(hFlat[t], 0.68); unf2->SetPoint(t, hD->GetBinCenter(t+1), mdi.u); unf2->SetPointError(t, 0.47*hD->GetBinWidth(t+1), mdi.du); } } Printf("Drawing results..."); DrawObject(hM, "colz", "matrix", cList, 550, 500); gPad->SetLogx(); gPad->SetLogy(); gPad->SetLogz(); gPad->SetRightMargin(0.15); DrawObject(heff, "", "efficiency", cList); // Draw marginal dists. from MCMC for (int t=0; t<Nt; t++) { DrawObject(hMCMC[t], "", Form("post_%d", t), cList); gPad->SetLeftMargin(0.15); if (doUniformSampling) { hFlat[t]->Scale(1./hFlat[t]->Integral(1, nFlatBins,"width")); hFlat[t]->Draw("same"); } double ymin = hMCMC[t]->GetMinimum(); double ymax = hMCMC[t]->GetMaximum(); double yDraw = 0.25*(ymax-ymin); DataPoint(hD, hMCMC[t], t, 0.75*yDraw)->Draw("ep same"); TruePoint(hT, hMCMC[t], t, yDraw)->Draw("p same"); MD68Point(hMCMC[t], yDraw)->Draw("ep same"); } // Result! hT->GetYaxis()->SetRangeUser(0.002, 101*nevts*evtWeight); DrawObject(hT, "ep", "result", cList); gPad->SetLogy(); box->Draw("e5 same"); if (doUniformSampling || drawReducedVolume) rbox->Draw("e5 same"); hT->Draw("same"); hD->Draw("ep same"); unf1->Draw("ep same"); if (unf2) unf2->Draw("ep same"); if (printPDFs) { PrintPDFs(cList, "pdfs"); // Print individuals into ./pdfs dir PrintPDF(cList, "pdfs/mcmc_unfold_example"); // Multipage PDF } Printf("All done."); watch.Stop(); watch.Print(); return; }
inline BigInt FindFactor ( const BigInt& n, DynamicSieve<SieveUnsigned>& sieve, const PollardPMinusOneCtrl<SieveUnsigned>& ctrl ) { const double twoLog = Log( 2. ); const double nLog = double( Log( BigFloat(n) ) ); const BigInt zero(0), one(1); // Keep all of the generated primes sieve.SetStorage( true ); SieveUnsigned smooth1 = ctrl.smooth1; SieveUnsigned smooth2 = ctrl.smooth2; SieveUnsigned smooth1Bound = Max( Pow(10ULL,9ULL), 8ULL*smooth1 ); SieveUnsigned smooth2Bound = Max( Pow(10ULL,10ULL), 8ULL*smooth2 ); // Ensure that we do not have a GCD of n appear too many times despite // separately checking the powers of two bool separateOdd=false; Int maxGCDFailures=10; Int numGCDFailures=0; BigInt smallPrime, gcd, tmp, diffPower; while( true ) { // Ensure that we have sieved at least up until smooth1 bool neededStage1Sieving = ( sieve.oddPrimes.back() < smooth1 ); if( ctrl.progress && neededStage1Sieving ) Output ("Updating sieve from ",sieve.oddPrimes.back()," to ",smooth1); sieve.Generate( smooth1 ); if( ctrl.progress && neededStage1Sieving ) Output("Done sieving for stage 1"); // Uniformly select a in (Z/(n))* // (alternatively, we could set a=2) BigInt a = SampleUniform( zero, n ); while( GCD( a, n ) != one ) { a = SampleUniform( zero, n ); } if( !separateOdd ) { // Handle 2 separately unsigned smallPrimeExponent = unsigned(nLog/twoLog); for( Int i=0; i<smallPrimeExponent; ++i ) { // a = a^2 (mod n) a *= a; a %= n; } } auto smooth1End = std::upper_bound ( sieve.oddPrimes.begin(), sieve.oddPrimes.end(), smooth1 ); for( auto iter=sieve.oddPrimes.begin(); iter<smooth1End; ++iter ) { auto smallPrime = *iter; double smallPrimeLog = double(Log(double(smallPrime))); unsigned smallPrimeExponent = unsigned(nLog/smallPrimeLog); for( Int i=0; i<smallPrimeExponent; ++i ) { // a = a^smallPrime (mod n) PowMod( a, smallPrime, n, a ); } } // gcd := GCD( a-1, n ) tmp = a; tmp -= 1; GCD( tmp, n, gcd ); if( gcd > one && gcd < n ) { if( ctrl.progress ) Output("Found stage-1 factor of ",gcd); return gcd; } if( separateOdd ) { unsigned twoExponent = unsigned(nLog/twoLog); for( Int i=0; i<twoExponent; ++i ) { // a = a*a (mod n) a *= a; a %= n; //gcd = GCD( a-1, n ); tmp = a; tmp -= 1; GCD( tmp, n, gcd ); if( gcd > one && gcd < n ) { if( ctrl.progress ) Output("Found separate stage-1 factor of ",gcd); return gcd; } } } if( gcd == n ) { if( separateOdd ) { ++numGCDFailures; if( numGCDFailures >= maxGCDFailures ) RuntimeError ("Too many GCD failures despite separately checking " "powers of two"); } else { ++numGCDFailures; separateOdd = true; if( ctrl.progress ) Output("GCD was n; will separately check powers of two"); } continue; } else // gcd == one { if( ctrl.progress ) Output("Proceeding to stage-2"); } // Run stage-2 // ----------- // Store all powers of a^{d_i}, where d_i is the difference between // primes p_{i+1} and p_i, where smooth1 < p_{i+1} <= smooth2 bool neededStage2Sieving = ( sieve.oddPrimes.back() < smooth2 ); if( ctrl.progress && neededStage2Sieving ) Output ("Updating sieve from ",sieve.oddPrimes.back()," to ",smooth2); sieve.Generate( smooth2 ); if( ctrl.progress && neededStage2Sieving ) Output("Done sieving for stage 2"); // NOTE: stage1End has potentially been invalidated due to reallocation auto stage2Beg = std::lower_bound ( sieve.oddPrimes.begin(), sieve.oddPrimes.end(), smooth1 ); auto stage2End = std::upper_bound ( stage2Beg, sieve.oddPrimes.end(), smooth2 ); std::map<SieveUnsigned,BigInt> diffPowers; for( auto iter=stage2Beg; iter<stage2End; ++iter ) { SieveUnsigned diff = *iter - *(iter-1); auto search = diffPowers.find( diff ); const size_t whichPrime = (iter-sieve.oddPrimes.begin())+1; Output(" ",whichPrime,": ",*iter," - ",*(iter-1)," = ",diff); if( search == diffPowers.end() ) { PowMod( a, diff, n, diffPower ); diffPowers.insert( std::make_pair(diff,diffPower) ); Output(" Stored ",a,"^",diff,"=",diffPower); } else Output(" diff=",diff," was redundant"); } // Test each stage two candidate for( auto iter=stage2Beg; iter<stage2End; ++iter ) { SieveUnsigned diff = *iter - *(iter-1); a *= diffPowers[diff]; a %= n; //gcd = GCD( a-1, n ); tmp = a; tmp -= 1; GCD( tmp, n, gcd ); if( gcd > one && gcd < n ) { if( ctrl.progress ) Output("Found stage-2 factor of ",gcd); return gcd; } } if( gcd == n ) { if( separateOdd ) { if( ctrl.progress ) Output("GCD failure ",numGCDFailures); ++numGCDFailures; if( numGCDFailures >= maxGCDFailures ) RuntimeError ("Too many GCD failures despite separately checking " "powers of two"); } else { ++numGCDFailures; separateOdd = true; if( ctrl.progress ) Output("GCD was n; will separately check powers of two"); } continue; } else // gcd == one { if( smooth1 >= smooth1Bound ) { RuntimeError ("Stage-1 smoothness bound of ",smooth1Bound," exceeded"); } if( smooth2 >= smooth2Bound ) { RuntimeError ("Stage-2 smoothness bound of ",smooth2Bound," exceeded"); } smooth1 *= 2; smooth2 *= 2; if( ctrl.progress ) Output ("Increased stage-1 smoothness to ",smooth1," and stage-2 " "smoothness to ",smooth2); } } }