diff --git a/GeometryService/src/KinKalGeomMaker.cc b/GeometryService/src/KinKalGeomMaker.cc index 8b1c62c741..400a55a6a8 100644 --- a/GeometryService/src/KinKalGeomMaker.cc +++ b/GeometryService/src/KinKalGeomMaker.cc @@ -23,6 +23,8 @@ #include "Offline/DetectorSolenoidGeom/inc/DetectorSolenoid.hh" #include "CLHEP/Vector/ThreeVector.h" #include "CLHEP/Vector/TwoVector.h" +#include "CLHEP/Vector/Rotation.h" +#include "Offline/GeneralUtilities/inc/OrientationResolver.hh" #include "art/Framework/Services/Registry/ServiceHandle.h" #include "cetlib_except/exception.h" #include @@ -30,6 +32,7 @@ #include #include #include +#include namespace mu2e { using KinKal::VEC3; @@ -338,28 +341,28 @@ namespace mu2e { // DS cryostat + thermal-shield END WALLS (z-normal annuli). Tracks bound for the upstream/ // downstream CRV sectors (CRV-U / CRV-D) leave the solenoid through its z-faces and cross the // cryostat and shield end walls; the radial shells above only catch tracks that exit radially. - // Geometry from DetectorSolenoid: (shield_)endWallHalfLength(). + // Each annulus carries the full wall thickness and spans the gap between the inner and outer shells (constructDS). { double const dsz = ds->position().z(); auto addEndWall = [this,&toDetectorZ](SurfaceId const& sid, double zmu2e, double rin, - double rout, double halfThick, std::string const& material) { + double rout, double thick, std::string const& material) { auto annulus = std::make_shared(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0), VEC3(0.0,0.0,toDetectorZ(zmu2e)),rin,rout); - kkg_->passiveMaterialPlanes_.emplace_back(sid,annulus,material,halfThick); + kkg_->passiveMaterialPlanes_.emplace_back(sid,annulus,material,thick); kkg_->map_.emplace(std::make_pair(sid,std::static_pointer_cast(annulus))); }; double const cOff = ds->halfLength() - ds->endWallHalfLength(); // cryo wall center inset double const sOff = ds->shield_halfLength() - ds->shield_endWallHalfLength(); // shield wall center inset // cryostat end walls (StainlessSteel) - addEndWall(SurfaceId(SurfaceIdEnum::DS_Front,1), dsz-cOff, ds->rIn1(), ds->rOut2(), - ds->endWallHalfLength(), ds->material()); - addEndWall(SurfaceId(SurfaceIdEnum::DS_Back,1), dsz+cOff, ds->rIn1(), ds->rOut2(), - ds->endWallHalfLength(), ds->material()); + addEndWall(SurfaceId(SurfaceIdEnum::DS_Front,1), dsz-cOff, ds->rIn2(), ds->rOut1(), + 2.0*ds->endWallHalfLength(), ds->material()); + addEndWall(SurfaceId(SurfaceIdEnum::DS_Back,1), dsz+cOff, ds->rIn2(), ds->rOut1(), + 2.0*ds->endWallHalfLength(), ds->material()); // thermal-shield end walls (aluminium; see dsShieldMaterial above) - addEndWall(SurfaceId(SurfaceIdEnum::DS_Front,2), dsz-sOff, ds->shield_rIn1(), ds->shield_rOut2(), - ds->shield_endWallHalfLength(), dsShieldMaterial); - addEndWall(SurfaceId(SurfaceIdEnum::DS_Back,2), dsz+sOff, ds->shield_rIn1(), ds->shield_rOut2(), - ds->shield_endWallHalfLength(), dsShieldMaterial); + addEndWall(SurfaceId(SurfaceIdEnum::DS_Front,2), dsz-sOff, ds->shield_rIn2(), ds->shield_rOut1(), + 2.0*ds->shield_endWallHalfLength(), dsShieldMaterial); + addEndWall(SurfaceId(SurfaceIdEnum::DS_Back,2), dsz+sOff, ds->shield_rIn2(), ds->shield_rOut1(), + 2.0*ds->shield_endWallHalfLength(), dsShieldMaterial); } // hard-coded for now @@ -414,16 +417,6 @@ namespace mu2e { GeomHandle det; auto const& shields = CRS->getCRSScintillatorShields(); std::vector sectors; - // Strongback (aluminium support plate) thickness from the CRV geometry - double strongBackThickness = 0.0; - for(auto const& shield : shields){ - int const td = shield.getFirstBar().getBarDetail().getThicknessDirection(); - for(int im = 0; im < shield.nModules(); ++im){ - auto const& mod = shield.getModule(im); - if(mod.nAluminumSheets() > 0){ strongBackThickness = 2.0*mod.getAluminumSheet(0).getHalfLengths().at(td); break; } - } - if(strongBackThickness != 0.0) break; - } // loop over the shields (= sectors) for (auto const& shield : shields) { // @@ -508,17 +501,39 @@ namespace mu2e { sector.sname_ = shield.getName(); sector.sector_ = std::make_shared(wdir,udir,midpoint,uhw,vhw); sector.whw_ = whw; - // Each CRV module carries a ~12.7 mm aluminium strongback (support plate) on the tracker-facing side - // of the scintillator stack. Thickness (strongBackThickness, above) and material now come from the - // CRV geometry rather than crs.strongBackThickness / crs.aluminumSheetMaterialName. - // KinKal DetMaterial name for the strongback (aluminium). The CRV geometry's aluminium-sheet - // material is the G4 name "G4_Al"; we use a CRV-specific MatEnv material so the plane self-documents. - std::string const strongBackMaterial = "CRVStrongbackAl"; - auto const sbcenter = midpoint - (whw + 0.5*strongBackThickness)*wdir; - auto const sbplane = std::make_shared(wdir,udir,sbcenter,uhw,vhw); - SurfaceId sbsid(SurfaceIdEnum::CRV_StrongBack, static_cast(kkg_->passiveMaterialPlanes_.size())); - kkg_->passiveMaterialPlanes_.emplace_back(sbsid, sbplane, strongBackMaterial, 0.5*strongBackThickness); - kkg_->map_.emplace(std::make_pair(sbsid, std::static_pointer_cast(sbplane))); + // each layer's bar spans across the bars, one per module, so the material of a crossing can follow the layer stagger + auto const svdir = sector.sector_->vDirection(); // the axis layerFraction uses + for(int il = 0; il < nlay; ++il){ + mu2e::KKGeom::KKCRVLayer layer; + layer.w_ = (VEC3(det->toDetector(firstmod.getLayer(il).getPosition())) - midpoint).Dot(sector.sector_->normal()); + for(int im = 0; im < shield.nModules(); ++im){ + auto const& lay = shield.getModule(im).getLayer(il); + double const va = (VEC3(det->toDetector(lay.getBar(0).getPosition())) - midpoint).Dot(svdir); + double const vb = (VEC3(det->toDetector(lay.getBar(lay.nBars()-1).getPosition())) - midpoint).Dot(svdir); + layer.v_.emplace_back(std::min(va,vb) - firstbar.getHalfWidth(), std::max(va,vb) + firstbar.getHalfWidth()); + } + sector.layers_.push_back(layer); + } + // Strongback: one plane over aluminium sheet 0 (layer 0) of all the sector's modules, with the full sheet thickness + if(firstmod.nAluminumSheets() > 0){ + int const td = bardet.getThicknessDirection(); + int const ld = bardet.getLengthDirection(); + int const wd = bardet.getWidthDirection(); + CLHEP::Hep3Vector lo(1.0e30,1.0e30,1.0e30), hi(-1.0e30,-1.0e30,-1.0e30); + for(int im = 0; im < shield.nModules(); ++im){ + auto const& sheet = shield.getModule(im).getAluminumSheet(0); + for(int k = 0; k < 3; ++k){ + lo[k] = std::min(lo[k], sheet.getPosition()[k] - sheet.getHalfLengths().at(k)); + hi[k] = std::max(hi[k], sheet.getPosition()[k] + sheet.getHalfLengths().at(k)); + } + } + std::string const strongBackMaterial = "CRVStrongbackAl"; + auto const sbcenter = VEC3(det->toDetector(0.5*(lo+hi))); + auto const sbplane = std::make_shared(wdir,udir,sbcenter,0.5*(hi[ld]-lo[ld]),0.5*(hi[wd]-lo[wd])); + SurfaceId sbsid(SurfaceIdEnum::CRV_StrongBack, static_cast(kkg_->passiveMaterialPlanes_.size())); + kkg_->passiveMaterialPlanes_.emplace_back(sbsid, sbplane, strongBackMaterial, hi[td]-lo[td]); + kkg_->map_.emplace(std::make_pair(sbsid, std::static_pointer_cast(sbplane))); + } sectors.push_back(sector); } // sort the sectors according to their transverse distance (largest first), to optimize searching for downward going tracks. @@ -581,303 +596,166 @@ namespace mu2e { } } + namespace { + // axis-aligned box in Mu2e coordinates + struct MuBox { + CLHEP::Hep3Vector lo{1.0e30,1.0e30,1.0e30}, hi{-1.0e30,-1.0e30,-1.0e30}; + bool empty() const { return lo.x() > hi.x(); } + void extend(MuBox const& b) { for(int k = 0; k < 3; ++k){ lo[k] = std::min(lo[k],b.lo[k]); hi[k] = std::max(hi[k],b.hi[k]); } } + CLHEP::Hep3Vector center() const { return 0.5*(lo+hi); } + double half(int k) const { return 0.5*(hi[k]-lo[k]); } + }; + // Mu2e box of a block-local box, placed as in constructExternalShielding (local point p goes to center + R^-1 p) + MuBox placeBox(double u0, double u1, double v0, double v1, double w0, double w1, + CLHEP::Hep3Vector const& center, CLHEP::HepRotation const& rinv) { + MuBox box; + for(int icorner = 0; icorner < 8; ++icorner){ + CLHEP::Hep3Vector const global = center + rinv*CLHEP::Hep3Vector((icorner&1) ? u1 : u0, (icorner&2) ? v1 : v0, (icorner&4) ? w1 : w0); + for(int k = 0; k < 3; ++k){ box.lo[k] = std::min(box.lo[k],global[k]); box.hi[k] = std::max(box.hi[k],global[k]); } + } + return box; + } + CLHEP::HepRotation inverseRotation(std::string const& orientation) { + CLHEP::HepRotation rot(CLHEP::HepRotation::IDENTITY); + OrientationResolver().getRotationFromOrientation(rot,orientation); + return rot.inverse(); + } + // Mu2e cuboids of a block: its U-V outline cut into U strips, extruded along W (no notches, holes or tolerances) + std::vector blockCuboids(std::vector> const& outline, double halfLength, + CLHEP::Hep3Vector const& center, std::string const& orientation) { + std::vector boxes; + size_t const nv = outline.size(); + if(nv < 3) return boxes; + auto const rinv = inverseRotation(orientation); + std::vector ucuts; + for(auto const& uv : outline) ucuts.push_back(uv[0]); + std::sort(ucuts.begin(),ucuts.end()); + ucuts.erase(std::unique(ucuts.begin(),ucuts.end(),[](double a, double b){ return std::fabs(a-b) < 1.0e-6; }),ucuts.end()); + for(size_t is = 0; is+1 < ucuts.size(); ++is){ + double const um = 0.5*(ucuts[is]+ucuts[is+1]); + std::vector vcross; // outline crossings of the line U = um + for(size_t iv = 0; iv < nv; ++iv){ + auto const& a = outline[iv]; + auto const& b = outline[(iv+1)%nv]; + if((a[0]-um)*(b[0]-um) < 0.0) vcross.push_back(a[1] + (b[1]-a[1])*(um-a[0])/(b[0]-a[0])); + } + std::sort(vcross.begin(),vcross.end()); + for(size_t ic = 0; ic+1 < vcross.size(); ic += 2) + boxes.push_back(placeBox(ucuts[is],ucuts[is+1],vcross[ic],vcross[ic+1],-halfLength,halfLength,center,rinv)); + } + return boxes; + } + // Mu2e envelope of a block, grown by its G4 tolerances (du, dv, dw) + MuBox blockEnvelope(std::vector> const& outline, double halfLength, std::vector const& tol, + CLHEP::Hep3Vector const& center, std::string const& orientation) { + if(outline.empty()) return MuBox(); + double u0 = 1.0e30, u1 = -1.0e30, v0 = 1.0e30, v1 = -1.0e30; + for(auto const& uv : outline){ u0 = std::min(u0,uv[0]); u1 = std::max(u1,uv[0]); v0 = std::min(v0,uv[1]); v1 = std::max(v1,uv[1]); } + double const du = tol.size() > 0 ? tol[0] : 0.0, dv = tol.size() > 1 ? tol[1] : 0.0, dw = tol.size() > 2 ? tol[2] : 0.0; + return placeBox(u0-du,u1+du,v0-dv,v1+dv,-halfLength-dw,halfLength+dw,center,inverseRotation(orientation)); + } + } + void KinKalGeomMaker::makePassiveMaterials() { GeomHandle det; - // External shielding (concrete) geometry now comes from the ExtShieldDownstream GeometryService object + // External shielding (concrete) geometry comes from the ExtShieldDownstream GeometryService object art::ServiceHandle geomService; if(!geomService->hasElement()) return; GeomHandle esd; if(esd->getNumberOfBoxTypes() <= 0) return; - // Group block indices by their 1-based type number. The type identity is what SimpleConfig - // supplied and what outline/material/orientation alone cannot recover (several types share - // identical geometry); getBoxTypes() restores it. Vectors below are parallel per block. + // Decode every block (vectors parallel per block; getBoxTypes() gives the 1-based type, lengths are halves) auto const& esdTypes = esd->getBoxTypes(); - auto const& esdOutlines = esd->getOutlines(); // per block: list of {u,v} vertices (mm) - auto const& esdLengths = esd->getLengths(); // per block: HALF length along W (mm) + auto const& esdOutlines = esd->getOutlines(); + auto const& esdLengths = esd->getLengths(); auto const& esdMats = esd->getMaterialNames(); auto const& esdCenters = esd->getCentersOfBoxes(); - std::map> boxesByType; - for(std::size_t i = 0; i < esdTypes.size(); ++i) boxesByType[esdTypes[i]].push_back(i); - auto firstBox = [&](int t)->long { - auto it = boxesByType.find(t); - return (it == boxesByType.end() || it->second.empty()) ? -1L : static_cast(it->second.front()); - }; - auto nBoxOf = [&](int t){ auto it = boxesByType.find(t); return it == boxesByType.end() ? 0 : static_cast(it->second.size()); }; - auto materialOf = [&](int t){ long const b = firstBox(t); return b >= 0 ? esdMats[b] : std::string(); }; - // Mu2e-frame center {x,y,z} of the ibox-th (1-based) block of a type (mirrors centerType{t}Box{ibox}). - auto centerOf = [&](int t, int ibox)->std::vector { - auto const& c = esdCenters[boxesByType[t][ibox-1]]; - return { c.x(), c.y(), c.z() }; - }; - // --- ExtShieldDownstream box dimensions. A box "type" is an extruded U-V outline of half-length - // esdLengths; the helpers return its half-extents. The {U,V,W=length} -> {x,y,z} orientation per - // region is not carried here, so it stays explicit at the call sites (as before). - // Helpers return 0 for absent types so an optional region is simply skipped (its nBox guard fires). - auto vertsOf = [&](int t, bool uaxis){ - std::vector v; long const b = firstBox(t); - if(b >= 0) for(auto const& uv : esdOutlines[b]) v.push_back(uaxis ? uv[0] : uv[1]); - return v; + auto const& esdOrients = esd->getOrientations(); + auto const& esdTols = esd->getTolerances(); + struct Block { int type; std::string const* material; std::vector cuboids; MuBox envelope; }; + std::vector blocks; + for(size_t ib = 0; ib < esdTypes.size(); ++ib){ + Block block{esdTypes[ib],&esdMats[ib],blockCuboids(esdOutlines[ib],esdLengths[ib],esdCenters[ib],esdOrients[ib]), + blockEnvelope(esdOutlines[ib],esdLengths[ib],esdTols[ib],esdCenters[ib],esdOrients[ib])}; + if(!block.envelope.empty()) blocks.push_back(std::move(block)); + } + auto hasType = [](std::vector const& types, int t){ return std::find(types.begin(),types.end(),t) != types.end(); }; + // Envelope of the blocks of the given types (and material) passing the selection + auto envelope = [&](std::vector const& types, std::string const& material, std::function const& select){ + MuBox env; + for(auto const& block : blocks) + if(hasType(types,block.type) && *block.material == material && (!select || select(block))) env.extend(block.envelope); + return env; }; - auto maxAbs = [](std::vector const& v){ double m=0.0; for(double x : v) m=std::max(m,std::fabs(x)); return m; }; - auto spanHalf= [](std::vector const& v){ if(v.empty()) return 0.0; auto e=std::minmax_element(v.begin(),v.end()); return 0.5*(*e.second - *e.first); }; - auto uHalf = [&](int t){ return maxAbs(vertsOf(t,true)); }; // outline U half-width (max |U|) - auto vHalf = [&](int t){ return maxAbs(vertsOf(t,false)); }; // outline V half-height (max |V|) - auto vSpanH = [&](int t){ return spanHalf(vertsOf(t,false)); }; // V half-extent (handles 0-based outlines) - auto lenHalf = [&](int t){ long const b = firstBox(t); return b >= 0 ? esdLengths[b] : 0.0; }; // already half - // V-weighted mean half-thickness of a T cross-section along its U (thin) axis: used where a - // T-block is collapsed to a single slab whose normal is U (the side walls), giving the - // energy-loss-correct mean depth without per-component Gauss planes. Reproduces the run-2 449.7. - auto tMeanUHalf = [&](int t){ - auto uV=vertsOf(t,true), vV=vertsOf(t,false); - if(uV.empty() || vV.empty()) return 0.0; - double const uo=maxAbs(uV); double ui=uo; - for(double u : uV) if(u > 0.0 && u < uo-1.0) ui=std::min(ui,u); // inner (stem) U half-width - auto const ve=std::minmax_element(vV.begin(),vV.end()); - double const vmin=*ve.first, vmax=*ve.second; double vsh=0.5*(vmin+vmax); - for(double v : vV) if(v > vmin+1.0 && v < vmax-1.0){ vsh=v; break; } // shoulder V - double const cb=vsh-vmin, st=vmax-vsh, span=vmax-vmin; // crossbar / stem V extents - return span>0.0 ? (uo*cb + ui*st)/span : uo; + auto materials = [&](std::vector const& types){ + std::vector mats; + for(auto const& block : blocks) + if(hasType(types,block.type) && std::find(mats.begin(),mats.end(),*block.material) == mats.end()) mats.push_back(*block.material); + return mats; }; - - // Model the ExtShieldDownstream Type 2 regular concrete roof T-blocks. - // These blocks sit between the DS outer cryostat (y~1328 mm) and the CRV top sectors T1/T2 (y~2653 mm). - // With orientations "010"/"012" (both map U->z, V->y, W->x): - // U (±uhw_outer mm) -> ±z footprint of the wide crossbar per block - // V range [vmin, vmax] -> y; vshoulder separates crossbar from stem - // W (length/2 = xhw mm) -> x (transverse, same for both components) - // - // The T cross-section is decomposed into two non-overlapping rectangles: - // Crossbar: V in [vmin, vshoulder], U in [-uhw_outer, +uhw_outer] - // Stem : V in [vshoulder, vmax], U in [-uhw_inner, +uhw_inner] - // Each is modelled with two Gauss-point planes so tracks through the crossbar- - // only region (the ~2/3 of z-width outside the stem) correctly see half the - // concrete compared to tracks through the full T height. - // Wrapped in an IIFE so a degenerate Type-2 (no boxes / empty outline) skips only this block - // via `return`, without abandoning the side walls / roof / endcap / hatch handled below. - [&]{ - int const nType2 = nBoxOf(2); - if(nType2 <= 0) return; - double const invSqrt3 = 1.0/std::sqrt(3.0); - std::vector uVerts = vertsOf(2,true), vVerts = vertsOf(2,false); - if(uVerts.empty() || vVerts.empty()) return; - - auto const uExt = std::minmax_element(uVerts.begin(), uVerts.end()); - auto const vExt = std::minmax_element(vVerts.begin(), vVerts.end()); - double const xhw = lenHalf(2); - auto const material = materialOf(2); - - double const vmin_t = *vExt.first; // = -452.2 mm (bottom of crossbar) - double const vmax_t = *vExt.second; // = +452.2 mm (top of stem) - double const uhw_outer = *uExt.second; // = 680.8 mm (crossbar z half-width per block) - - // Inner U half-width (stem): smallest positive U vertex that differs from uhw_outer - double uhw_inner = uhw_outer; - for(double u : uVerts) - if(u > 0 && u < uhw_outer - 1.0) uhw_inner = std::min(uhw_inner, u); - - // Shoulder V (where T width steps inward): V value strictly between vmin and vmax - double vshoulder = 0.0; - for(double v : vVerts) - if(v > vmin_t + 1.0 && v < vmax_t - 1.0) { vshoulder = v; break; } - - // Crossbar component: V in [vmin_t, vshoulder] - double const yhalf_cb = 0.5*(vshoulder - vmin_t); // = 223.6 mm - double const vcenter_cb = 0.5*(vmin_t + vshoulder); // = -228.6 mm (local V offset) - - // Stem component: V in [vshoulder, vmax_t] - double const yhalf_stem = 0.5*(vmax_t - vshoulder); // = 228.6 mm - double const vcenter_stem = 0.5*(vshoulder + vmax_t); // = +223.6 mm (local V offset) - - // Accumulate x/y center (common to both components) and z bounding boxes - // (different per component because stem is narrower in z than crossbar). - double xcenter = 0.0, ycenter = 0.0; - double zmin_cb = 1.0e9, zmax_cb = -1.0e9; - double zmin_st = 1.0e9, zmax_st = -1.0e9; - int nfound = 0; - for(int ibox = 1; ibox <= nType2; ++ibox) { - std::vector ctr = centerOf(2, ibox); - xcenter += ctr[0]; - ycenter += ctr[1]; - zmin_cb = std::min(zmin_cb, ctr[2] - uhw_outer); - zmax_cb = std::max(zmax_cb, ctr[2] + uhw_outer); - zmin_st = std::min(zmin_st, ctr[2] - uhw_inner); - zmax_st = std::max(zmax_st, ctr[2] + uhw_inner); - ++nfound; - } - if(nfound == 0) return; - xcenter /= nfound; - ycenter /= nfound; - - // Global Mu2e Y centers for each T component (ycenter = mean box center = 2006.1 mm) - double const ycenter_cb = ycenter + vcenter_cb; // ≈ 1777.5 mm - double const ycenter_stem = ycenter + vcenter_stem; // ≈ 2229.7 mm - - double const zcenters[2] = { 0.5*(zmin_cb + zmax_cb), 0.5*(zmin_st + zmax_st) }; - double const zhws[2] = { 0.5*(zmax_cb - zmin_cb), 0.5*(zmax_st - zmin_st) }; - double const yctrs[2] = { ycenter_cb, ycenter_stem }; - double const yhalfs[2] = { yhalf_cb, yhalf_stem }; - - // Four planes total: two Gauss-point planes for each T component. - for(int icomp = 0; icomp < 2; ++icomp) { - for(int iplane = 0; iplane < 2; ++iplane) { - double const ysign = iplane == 0 ? -1.0 : 1.0; - auto const center = VEC3(det->toDetector( - CLHEP::Hep3Vector(xcenter, yctrs[icomp] + ysign*yhalfs[icomp]*invSqrt3, zcenters[icomp]))); - auto const plane = std::make_shared( - VEC3(0.0,1.0,0.0), VEC3(1.0,0.0,0.0), center, xhw, zhws[icomp]); - SurfaceId sid(SurfaceIdEnum::DS_HatchConcrete, - static_cast(kkg_->passiveMaterialPlanes_.size())); - kkg_->passiveMaterialPlanes_.emplace_back(sid, plane, material, yhalfs[icomp]); - kkg_->map_.emplace(std::make_pair(sid, std::static_pointer_cast(plane))); - } - } - }(); - - // Collapse all type- ExtShieldDownstream concrete boxes of a region into one - // averaged plane. 'normalAxis' is the slab normal (0=x,1=y,2=z); the in-plane - // half-extents are (center span)/2 + the block half-size along each in-plane - // axis; 'halfThickness' is supplied by the caller (block depth along normal). - // Boxes whose center lies far from the region cluster (different sub-region, - // e.g. the type-1 north vs south wall) are separated by an explicit center cut. - auto buildAveragedRegion = [&](int boxType, int normalAxis, - double halfU_block, double halfV_block, double halfThickness, - std::function const&)> select) { - int const nbox = nBoxOf(boxType); - if(nbox <= 0) return; - auto const material = materialOf(boxType); - // axis indices orthogonal to the normal, in increasing order - int a1 = (normalAxis == 0) ? 1 : 0; - int a2 = (normalAxis == 2) ? 1 : 2; - double nsum = 0.0; // accumulate the normal-axis center (slab position) - double min1 = 1e9, max1 = -1e9; // in-plane axis 1 center range - double min2 = 1e9, max2 = -1e9; // in-plane axis 2 center range - int nfound = 0; - for(int ibox = 1; ibox <= nbox; ++ibox) { - std::vector ctr = centerOf(boxType, ibox); - if(select && !select(ctr)) continue; - nsum += ctr[normalAxis]; - min1 = std::min(min1, ctr[a1]); max1 = std::max(max1, ctr[a1]); - min2 = std::min(min2, ctr[a2]); max2 = std::max(max2, ctr[a2]); - ++nfound; - } - if(nfound == 0) return; - // assemble the center from the per-axis values (normal axis = mean slab - // position; in-plane axes = midpoint of the center bounding box) - double cc[3] = {0.0,0.0,0.0}; - cc[normalAxis] = nsum / nfound; - cc[a1] = 0.5*(min1 + max1); - cc[a2] = 0.5*(min2 + max2); - CLHEP::Hep3Vector center(cc[0],cc[1],cc[2]); - double const hw1 = 0.5*(max1 - min1) + halfU_block; - double const hw2 = 0.5*(max2 - min2) + halfV_block; - this->addConcretePlane(*det, normalAxis, center, hw1, hw2, halfThickness, material); + // One slab (a Gauss-plane pair) filling a box, normal along 'normalAxis'; in-plane half widths in addConcretePlane order + auto addSlab = [&](int normalAxis, MuBox const& box, std::string const& material){ + if(box.empty()) return; + int const a1 = (normalAxis == 0) ? 1 : 0; + int const a2 = (normalAxis == 2) ? 1 : 2; + addConcretePlane(*det, normalAxis, box.center(), box.half(a1), box.half(a2), box.half(normalAxis), material); }; - - // --- Side walls. Type 1 regular-concrete wall T-blocks. Geometry from - // ExtShieldDownstream (outlineType1 U/V verts + lengthType1): the T cross-section - // lies in the U-V plane, extruded over lengthType1; for the walls the orientation - // maps U->x (wall thickness), V->z (footprint), length->y (vertical extent). - // U verts +/-680.8 / +/-223.6 -> crossbar 1361.6 mm thick, stem 447.2 mm thick - // V verts +/-452.2 (span 904.4); crossbar occupies V in [-452.2,-5] = 447.2 mm, - // stem occupies V in [-5, 452.2] = 457.2 mm - // The wall is one x-normal slab per side whose x half-thickness is the z-weighted - // mean of the T thickness, so the mean crossed concrete (energy loss) is exact - // without four Gauss planes per wall: - // 2*xHalf = (1361.6*447.2 + 447.2*457.2)/904.4 = 899.3 mm -> xHalfThick = 449.7 - // Box centers split into the north wall (x ~ -1897) and south wall (x ~ -5911) - // about the DS axis (x = -3904); each is emitted as a single slab. - { - double const yHalfBlock = lenHalf(1); // length (W) -> y vertical half-height - double const zHalfBlock = vSpanH(1); // V outline -> z footprint (452.2 in run-2) - double const xHalfThick = tMeanUHalf(1); // U-outline T-mean -> x half-thickness (449.7 in run-2) - // Separate the two symmetric side walls at the DS axis = the mean x of the type-1 box - // centers (-3904 in run-2), derived from config so it tracks the geometry instead of a literal. - double splitX = 0.0; int nWall = 0; - int const nBox1 = nBoxOf(1); - for(int ibox = 1; ibox <= nBox1; ++ibox) { - std::vector c = centerOf(1, ibox); - splitX += c[0]; ++nWall; - } - if(nWall > 0) { - splitX /= nWall; - buildAveragedRegion(1, 0, yHalfBlock, zHalfBlock, xHalfThick, - [splitX](std::vector const& c){ return c[0] > splitX; }); // north - buildAveragedRegion(1, 0, yHalfBlock, zHalfBlock, xHalfThick, - [splitX](std::vector const& c){ return c[0] < splitX; }); // south - } + // Each row of interlocking blocks is one slab filling the envelope of its blocks. + // Roof, y-normal: main roof (types 2, 10, 23 over the DS, 29, 30 over the endcap) and upstream row (types 4, 9). + std::vector const mainRoof = {2,10,23,29,30}; + std::vector const upstreamRoof = {4,9}; + double roofBottom = 1.0e30; + for(auto const& mat : materials(mainRoof)){ + auto const env = envelope(mainRoof,mat,nullptr); + addSlab(1,env,mat); + if(!env.empty()) roofBottom = std::min(roofBottom,env.lo.y()); } - - // --- Other roof concrete types (same y-normal plane family as Type-2). These - // sit at y ~ 2006 between the DS and the top CRV. We add - // them as averaged y-normal slabs using the roof T half-height (the V outline - // ~452.2 mm maps to the vertical thickness for the roof). Types: 4 (barite roof - // T, 6 boxes), 9 (barite roof L, 2), 10 (concrete roof filler, 1), 23 (barite - // roof T around ST, 2), 29 (endcap top-back, 1), 30 (endcap top-front, 1). - // For these the wide U crossbar (680.8) and the W length (4918 for the long - // roof types) span x and z; we use the conservative full-width block half-sizes - // so the averaged footprint covers the tiled blocks. y half-thickness = 452.2. - { - double const roofYhalfThick = vHalf(2); // V outline half -> roof vertical depth (452.2) - double const roofXhalfBlock = lenHalf(2); // length/2 spans x (~2459) - double const roofZhalfBlock = uHalf(2); // U crossbar half spans z (680.8) - // These slabs borrow Type-2's dimensions; if Type-2 is zeroed but these types aren't, skip - // rather than emit zero-thickness planes (a partial config the run-1 nBoxOf(2)<=0 path misses). - if(roofYhalfThick > 0.0) { - // type 4: barite roof T blocks (upstream) - buildAveragedRegion(4, 1, roofXhalfBlock, roofZhalfBlock, roofYhalfThick, nullptr); - // type 23: barite roof T blocks around the stopping target - buildAveragedRegion(23, 1, roofXhalfBlock, roofZhalfBlock, roofYhalfThick, nullptr); - // type 9: barite roof L blocks on the ends of the upstream roof - buildAveragedRegion(9, 1, roofXhalfBlock, roofZhalfBlock, roofYhalfThick, nullptr); - // type 10: concrete roof filler block - buildAveragedRegion(10, 1, roofXhalfBlock, roofZhalfBlock, roofYhalfThick, nullptr); - // types 29/30: new-endcap top back / front roof pieces. y-normal slabs; their own wide U - // outline spans x and their short length spans z, modelled at the roof slab depth. - buildAveragedRegion(29, 1, uHalf(29), lenHalf(29), roofYhalfThick, nullptr); - buildAveragedRegion(30, 1, uHalf(30), lenHalf(30), roofYhalfThick, nullptr); + for(auto const& mat : materials(upstreamRoof)) addSlab(1,envelope(upstreamRoof,mat,nullptr),mat); + // Side walls (type 1), x-normal, one per side of the DS axis (the mean x of the wall blocks) + std::vector const walls = {1}; + std::vector wallEnvelopes; + double xsum = 0.0; int nwall = 0; + for(auto const& block : blocks) if(block.type == 1){ xsum += block.envelope.center().x(); ++nwall; } + if(nwall > 0){ + double const xsplit = xsum/nwall; + for(auto const& mat : materials(walls)){ + wallEnvelopes.push_back(envelope(walls,mat,[xsplit](Block const& b){ return b.envelope.center().x() > xsplit; })); + wallEnvelopes.push_back(envelope(walls,mat,[xsplit](Block const& b){ return b.envelope.center().x() < xsplit; })); + for(auto it = wallEnvelopes.end()-2; it != wallEnvelopes.end(); ++it) addSlab(0,*it,mat); } } - - // --- Downstream endcap concrete (z-normal). Types 27 (3 boxes) and 28 (1 box) - // form the wall closing the DS<->CRV gap at z ~ 18542, beyond the DS, at the - // CRV-D sectors. They have large x/y outlines (U up to 2463.8, V up to 3246.2, - // the V outline runs 0..3246.2 so the per-block V half-extent is ~1623 mm) and - // a short z length (~1117 / ~907 mm), i.e. a slab normal to z. We emit one - // averaged z-normal plane per type, with x half from the U outline, y half from - // the centers' bounding box plus the block V half, and z half-thickness from - // length/2. NOTE: the asymmetric (0-based) V outline means the precise y - // placement of the face would need the per-box "300" rotation to be decoded; - // here we cover the whole stacked x-y face conservatively, which is adequate for - // the broad energy-loss correction this region needs for CRV-D-bound tracks. - { - // Endcap face (z-normal): the type-27 U outline -> x, its V outline span -> y; the slab - // z half-thickness is each type's own length/2. (Type 28 shares the type-27 x-y face, as before.) - double const ecXhalf = uHalf(27); // U outline -> x half (2463.8) - double const ecYhalf = vSpanH(27); // V outline span -> y half (~1623) - // Both endcap types use Type-27's x-y face; skip if Type-27 is zeroed so Type-28 doesn't - // emit a zero-area plane. - if(ecXhalf > 0.0 && ecYhalf > 0.0) { - // type 27: 3 stacked endcap blocks (cover most of the x-y face) - buildAveragedRegion(27, 2, ecXhalf, ecYhalf, lenHalf(27), nullptr); - // type 28: endcap bottom block - buildAveragedRegion(28, 2, ecXhalf, ecYhalf, lenHalf(28), nullptr); + // Downstream endcap (types 27, 28 stacked in y), z-normal: one slab per outline strip, under the main roof and + // beyond the side walls (whose last blocks are half thick where the side columns start) + std::vector const endcap = {27,28}; + for(auto const& mat : materials(endcap)){ + std::vector strips; + for(auto const& block : blocks){ + if(!hasType(endcap,block.type) || *block.material != mat) continue; + for(auto const& cub : block.cuboids){ + auto same = [&cub](MuBox const& s){ for(int k : {0,2}) if(std::fabs(s.lo[k]-cub.lo[k]) > 1.0 || std::fabs(s.hi[k]-cub.hi[k]) > 1.0) return false; return true; }; + auto it = std::find_if(strips.begin(),strips.end(),same); + if(it == strips.end()) strips.push_back(cub); else it->extend(cub); + } + } + for(auto& strip : strips){ + strip.hi[1] = std::min(strip.hi[1],roofBottom); + for(auto const& wall : wallEnvelopes) + if(!wall.empty() && strip.lo.x() < wall.hi.x() && wall.lo.x() < strip.hi.x() && strip.lo.y() < wall.hi.y() && wall.lo.y() < strip.hi.y()) + strip.lo[2] = std::max(strip.lo[2],wall.hi.z()); + if(strip.hi[1] > strip.lo[1] && strip.hi[2] > strip.lo[2]) addSlab(2,strip,mat); } } // Run-1 geometries zero the ExtShieldDownstream concrete T-blocks but retain the building // dsAreaHatchBlock concrete (CONCRETE_MARS) between tracker and CRV-T. Extracted geometries // have no ExtShieldDownstream object and returned above. Reaching here means the shield is - // declared (numberOfBoxTypes>0); the run-1 fallback fires when its roof T-blocks are zeroed. - if(nBoxOf(2) <= 0) { + // declared (numberOfBoxTypes>0); the run-1 fallback fires when its roof T-blocks are absent. + if(std::none_of(blocks.begin(),blocks.end(),[](Block const& b){ return b.type == 2; })) { addBuildingHatchConcrete(*det); } } void KinKalGeomMaker::addBuildingHatchConcrete(DetectorSystem const& det) { - // The dsAreaHatchBlock concrete is a building ExtrudedSolid served by Mu2eHall, replacing the - // former building.dsArea.hatchblock.* / yOfFloorSurface SimpleConfig reads. The solid's offset - // already folds the floor-surface Y into its Mu2e-origin offset. The 2D outline lies in the - // (x, z) plane: vertex x -> Mu2e x, vertex y -> Mu2e z; the slab normal is y (a roof plane). + // dsAreaHatchBlock(E): Mu2eHall building solids; the hall rotation (constructHall) maps vertex x to Mu2e z, y to x GeomHandle hall; auto const& solids = hall->getBldgSolids(); auto spanHalf = [](std::vector const& v, bool xaxis) { @@ -897,8 +775,8 @@ namespace mu2e { auto const& verts = solid.getVertices(); if(verts.empty()) return; auto const& off = solid.getOffsetFromMu2eOrigin(); - CLHEP::Hep3Vector center(off.x() + mid(verts,true), off.y(), off.z() + mid(verts,false)); - addConcretePlane(det, 1, center, spanHalf(verts,true), spanHalf(verts,false), + CLHEP::Hep3Vector center(off.x() + mid(verts,false), off.y(), off.z() + mid(verts,true)); + addConcretePlane(det, 1, center, spanHalf(verts,false), spanHalf(verts,true), solid.getYhalfThickness(), solid.getMaterial()); }; addSlab("dsAreaHatchBlock"); diff --git a/KinKalGeom/CMakeLists.txt b/KinKalGeom/CMakeLists.txt index 5aa3e52cb8..6292de8c8b 100644 --- a/KinKalGeom/CMakeLists.txt +++ b/KinKalGeom/CMakeLists.txt @@ -8,6 +8,7 @@ cet_make_library( src/KKStrawMaterial.cc LIBRARIES PUBLIC Offline::ConfigTools + Offline::DataProducts KinKal::MatEnv KinKal::Geometry KinKal::Trajectory @@ -15,6 +16,14 @@ cet_make_library( Offline::GeneralUtilities ) +cet_build_plugin(KinKalGeomCheck art::module + REG_SOURCE src/KinKalGeomCheck_module.cc + LIBRARIES REG + Offline::KinKalGeom + Offline::GeometryService + ROOT::Geom +) + install_source(SUBDIRS src) install_headers(USE_PROJECT_NAME SUBDIRS inc) install_fhicl(SUBDIRS fcl SUBDIRNAME Offline/KinKalGeom/fcl) diff --git a/KinKalGeom/fcl/kinkalGeomCheck.fcl b/KinKalGeom/fcl/kinkalGeomCheck.fcl new file mode 100644 index 0000000000..84e1b2be1c --- /dev/null +++ b/KinKalGeom/fcl/kinkalGeomCheck.fcl @@ -0,0 +1,20 @@ +# Consistency check of the KinKalGeom passive material (module KinKalGeomCheck) for the default geometry. The job fails +# on overlapping elements or coplanar same-material planes. kinkalGeomCheckG4.fcl adds the comparison with G4. +#include "Offline/fcl/standardServices.fcl" + +process_name : KinKalGeomCheck + +source : { + module_type : EmptyEvent + maxEvents : 1 +} + +services : @local::Services.Core + +physics : { + analyzers : { + KinKalGeomCheck : { module_type : KinKalGeomCheck } + } + checkPath : [ KinKalGeomCheck ] + end_paths : [ checkPath ] +} diff --git a/KinKalGeom/fcl/kinkalGeomCheckG4.fcl b/KinKalGeom/fcl/kinkalGeomCheckG4.fcl new file mode 100644 index 0000000000..7866b7a4fe --- /dev/null +++ b/KinKalGeom/fcl/kinkalGeomCheckG4.fcl @@ -0,0 +1,4 @@ +# KinKalGeomCheck including the comparison with the G4 geometry, read from the GDML file that +# "mu2e -c Offline/Mu2eG4/fcl/gdmldump.fcl" writes for the same geometry (mu2e_common.gdml in the current directory). +#include "Offline/KinKalGeom/fcl/kinkalGeomCheck.fcl" +physics.analyzers.KinKalGeomCheck.gdmlFile : "mu2e_common.gdml" diff --git a/KinKalGeom/fcl/kinkalGeomCheck_run2.fcl b/KinKalGeom/fcl/kinkalGeomCheck_run2.fcl new file mode 100644 index 0000000000..669f32f9a5 --- /dev/null +++ b/KinKalGeom/fcl/kinkalGeomCheck_run2.fcl @@ -0,0 +1,3 @@ +# KinKalGeomCheck for the Run 2 geometry +#include "Offline/KinKalGeom/fcl/kinkalGeomCheck.fcl" +services.GeometryService.inputFile : "Offline/Mu2eG4/geom/geom_run2.txt" diff --git a/KinKalGeom/inc/CRV.hh b/KinKalGeom/inc/CRV.hh index 0778c25e61..eef7ac5533 100644 --- a/KinKalGeom/inc/CRV.hh +++ b/KinKalGeom/inc/CRV.hh @@ -5,16 +5,42 @@ #ifndef KinKalGeom_CRV_hh #define KinKalGeom_CRV_hh #include "KinKal/Geometry/Rectangle.hh" +#include "KinKal/General/Vectors.hh" +#include +#include +#include #include #include namespace mu2e { namespace KKGeom { using RecPtr = std::shared_ptr; + // one scintillator layer of a sector: its offset from the sector midplane and the spans its bars cover across the bars + struct KKCRVLayer { + double w_ = 0.0; // layer center along the sector normal, relative to the sector midplane (mm) + std::vector> v_; // [low,high] along the sector vDirection, relative to the sector center (mm), one per module + }; struct KKCRVSector { std::string sname_; - RecPtr sector_; + RecPtr sector_; // midplane, spanning every layer: adjacent sectors overlap where their staggered layers interleave double whw_; + std::vector layers_; + // fraction of the layers that a straight line through pos (on the midplane) along dir crosses; 1 if no layers are given + double layerFraction(KinKal::VEC3 const& pos, KinKal::VEC3 const& dir) const; }; + inline double KKCRVSector::layerFraction(KinKal::VEC3 const& pos, KinKal::VEC3 const& dir) const { + if(layers_.empty()) return 1.0; + double const dw = dir.Dot(sector_->normal()); + double const slope = std::fabs(dw) > 1.0e-6 ? dir.Dot(sector_->vDirection())/dw : 0.0; // dv/dw along the line + double const v0 = (pos - sector_->center()).Dot(sector_->vDirection()); + unsigned ncross = 0; + for(auto const& layer : layers_){ + double const v = v0 + slope*layer.w_; + for(auto const& span : layer.v_){ + if(v >= span.first && v <= span.second){ ++ncross; break; } + } + } + return ncross/double(layers_.size()); + } class CRV { public: // construct with rectangles representing the midplane of CRV sectors (shields) diff --git a/KinKalGeom/src/KinKalGeomCheck_module.cc b/KinKalGeom/src/KinKalGeomCheck_module.cc new file mode 100644 index 0000000000..ec968b7396 --- /dev/null +++ b/KinKalGeom/src/KinKalGeomCheck_module.cc @@ -0,0 +1,637 @@ +// +// Check the KinKalGeom passive material: (1) no two solid elements (DS shells, passive planes, CRV sectors) share a +// volume and no two passive planes are coplanar, of the same material and thickness, with overlapping or touching +// footprints, and no line crosses a layer of two CRV sectors; (2) given a GDML file of the G4 geometry, points sampled +// inside each element lie in G4 volumes of a matching material, the CRV layer spans match the G4 scintillator, and the +// column density along straight lines from the tracker to the CRV sectors, outside the DS bore, agrees between +// KinKalGeom and G4. G4 material crossed by those lines outside every KinKalGeom element is +// tallied per G4 volume. The job fails (throws at beginRun) on (1), and on (2) if failOnG4Mismatch is set. +// +#include "art/Framework/Core/EDAnalyzer.h" +#include "art/Framework/Core/ModuleMacros.h" +#include "art/Framework/Principal/Run.h" +#include "cetlib_except/exception.h" +#include "fhiclcpp/types/Atom.h" +#include "fhiclcpp/types/Sequence.h" +#include "Offline/GeometryService/inc/GeomHandle.hh" +#include "Offline/GeometryService/inc/DetectorSystem.hh" +#include "Offline/KinKalGeom/inc/KinKalGeom.hh" +#include "Offline/KinKalGeom/inc/KKMaterial.hh" +#include "Offline/KinKalGeom/inc/Tracker.hh" +#include "Offline/KinKalGeom/inc/DetectorSolenoid.hh" +#include "Offline/KinKalGeom/inc/CRV.hh" +#include "KinKal/General/Vectors.hh" +#include "KinKal/Geometry/Rectangle.hh" +#include "KinKal/Geometry/Annulus.hh" +#include "KinKal/MatEnv/DetMaterial.hh" +#include "TGeoManager.h" +#include "TGeoNode.h" +#include "TGeoVolume.h" +#include "TGeoMaterial.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace mu2e { + // Geometry helpers for the check, local to this plugin: the solid elements of the KinKalGeom passive material (DS + // shells, passive planes, CRV sectors), their pairwise overlaps, coplanar same-material planes, and straight-line + // path lengths through them. All positions in detector coordinates. + namespace KKGeomCheck { + namespace { + using KinKal::VEC3; + // A solid element: an oriented box or a tube about wdir; a Gauss-plane pair is merged back into its slab + struct Element { + enum Shape { box, tube }; + enum Kind { dsCylinder, passivePlane, crvSector }; + std::string name; + std::string material; // KinKal material name; the CRV material for sectors + Kind kind; + Shape shape; + VEC3 center, udir, vdir, wdir; // wdir is the box normal or the tube axis + double uhalf = 0, vhalf = 0, whalf = 0; // box half lengths + double rin = 0, rout = 0; // tube radii (whalf is the tube half length) + std::vector planes; // passiveMaterialPlanes indices this element came from + int sector = -1; // CRV sector index for a crvSector element + bool inside(VEC3 const& point) const; + VEC3 sample(std::mt19937& rng) const; // uniform in the volume + double volume() const; + // length of the segment start + s*dir, s in [smin,smax] (dir a unit vector), inside the element + double pathLength(VEC3 const& start, VEC3 const& dir, double smin, double smax) const; + void bounds(VEC3& lo, VEC3& hi) const; // axis-aligned bounding box + }; + using Elements = std::vector; + struct Overlap { size_t first, second; double volume; }; + struct SectorPair { size_t first, second; double minsum, maxsum; unsigned nlines; }; + struct Coplanar { size_t first, second; double uoverlap, voverlap; }; + + // intersect [a0,a1] with [b0,b1] in place; false if empty + bool clip(double& a0, double& a1, double b0, double b1) { a0 = std::max(a0,b0); a1 = std::min(a1,b1); return a1 > a0; } + // interval where |c + s*d| < h along one axis + bool slabInterval(double c, double d, double h, double& s0, double& s1) { + if(std::fabs(d) < 1.0e-12) return std::fabs(c) < h; + double t0 = (-h-c)/d, t1 = (h-c)/d; + if(t0 > t1) std::swap(t0,t1); + return clip(s0,s1,t0,t1); + } + // interval where the radial distance from the axis is below r + bool radialInterval(VEC3 const& q, VEC3 const& dq, double r, double& s0, double& s1) { + double const a = dq.Mag2(), b = q.Dot(dq), c = q.Mag2() - r*r; + if(a < 1.0e-12) return c < 0.0; + double const disc = b*b - a*c; + if(disc <= 0.0) return false; + double const sq = std::sqrt(disc); + return clip(s0,s1,(-b-sq)/a,(-b+sq)/a); + } + + bool Element::inside(VEC3 const& point) const { + VEC3 const d = point - center; + double const w = d.Dot(wdir); + if(std::fabs(w) > whalf) return false; + if(shape == box) return std::fabs(d.Dot(udir)) <= uhalf && std::fabs(d.Dot(vdir)) <= vhalf; + double const r = (d - w*wdir).R(); + return r >= rin && r <= rout; + } + + VEC3 Element::sample(std::mt19937& rng) const { + std::uniform_real_distribution flat(-1.0,1.0); + if(shape == box) return center + (uhalf*flat(rng))*udir + (vhalf*flat(rng))*vdir + (whalf*flat(rng))*wdir; + double const r = std::sqrt(rin*rin + 0.5*(1.0+flat(rng))*(rout*rout-rin*rin)); + double const phi = M_PI*flat(rng); + return center + (r*std::cos(phi))*udir + (r*std::sin(phi))*vdir + (whalf*flat(rng))*wdir; + } + + double Element::volume() const { + return shape == box ? 8.0*uhalf*vhalf*whalf : 2.0*M_PI*(rout*rout-rin*rin)*whalf; + } + + void Element::bounds(VEC3& lo, VEC3& hi) const { + VEC3 ext; + if(shape == box){ + ext = VEC3(uhalf*std::fabs(udir.X()) + vhalf*std::fabs(vdir.X()) + whalf*std::fabs(wdir.X()), + uhalf*std::fabs(udir.Y()) + vhalf*std::fabs(vdir.Y()) + whalf*std::fabs(wdir.Y()), + uhalf*std::fabs(udir.Z()) + vhalf*std::fabs(vdir.Z()) + whalf*std::fabs(wdir.Z())); + } else { + auto rad = [this](double a){ return rout*std::sqrt(std::max(0.0,1.0-a*a)) + whalf*std::fabs(a); }; + ext = VEC3(rad(wdir.X()),rad(wdir.Y()),rad(wdir.Z())); + } + lo = center - ext; hi = center + ext; + } + + // interval of s in [smin,smax] where start + s*dir is inside a finite cylinder (axis through 'center'); false if none + bool cylinderInterval(VEC3 const& center, VEC3 const& axis, double radius, double halflen, + VEC3 const& start, VEC3 const& dir, double smin, double smax, double& s0, double& s1) { + s0 = smin; s1 = smax; + VEC3 const d = start - center; + double const z = d.Dot(axis), dz = dir.Dot(axis); + if(!slabInterval(z,dz,halflen,s0,s1)) return false; + return radialInterval(d - z*axis, dir - dz*axis, radius, s0, s1); + } + + double Element::pathLength(VEC3 const& start, VEC3 const& dir, double smin, double smax) const { + VEC3 const d = start - center; + double s0 = smin, s1 = smax; + if(shape == box){ + if(!slabInterval(d.Dot(udir),dir.Dot(udir),uhalf,s0,s1)) return 0.0; + if(!slabInterval(d.Dot(vdir),dir.Dot(vdir),vhalf,s0,s1)) return 0.0; + if(!slabInterval(d.Dot(wdir),dir.Dot(wdir),whalf,s0,s1)) return 0.0; + return s1 - s0; + } + double const z = d.Dot(wdir), dz = dir.Dot(wdir); + if(!slabInterval(z,dz,whalf,s0,s1)) return 0.0; + VEC3 const q = d - z*wdir, dq = dir - dz*wdir; + double o0 = s0, o1 = s1; + if(!radialInterval(q,dq,rout,o0,o1)) return 0.0; + double len = o1 - o0; + double i0 = o0, i1 = o1; + if(rin > 0.0 && radialInterval(q,dq,rin,i0,i1)) len -= i1 - i0; + return len; + } + + // DS material cylinders, passive planes and CRV sectors of a KinKalGeom + Elements elements(KinKalGeom const& kkg) { + Elements elems; + if(kkg.DS()){ + for(auto const& cyl : kkg.DS()->materialCylinders()){ + Element el; + el.name = cyl.sid_.name(); + el.material = cyl.material_; + el.kind = Element::dsCylinder; + el.shape = Element::tube; + el.center = cyl.surface_->center(); + el.wdir = cyl.surface_->axis().Unit(); + el.udir = (std::fabs(el.wdir.X()) < 0.9 ? VEC3(1.0,0.0,0.0) : VEC3(0.0,1.0,0.0)).Cross(el.wdir).Unit(); + el.vdir = el.wdir.Cross(el.udir); + el.whalf = cyl.surface_->halfLength(); + el.rin = cyl.surface_->radius() - 0.5*cyl.thickness_; + el.rout = cyl.surface_->radius() + 0.5*cyl.thickness_; + elems.push_back(el); + } + } + auto const& planes = kkg.passiveMaterialPlanes(); + for(size_t ip = 0; ip < planes.size(); ++ip){ + auto const& plane = planes[ip]; + Element el; + el.name = plane.sid_.name() + "_" + std::to_string(plane.sid_.index()); + el.material = plane.material_; + el.kind = Element::passivePlane; + el.center = plane.surface_->center(); + el.udir = plane.surface_->uDirection(); + el.vdir = plane.surface_->vDirection(); + el.wdir = plane.surface_->normal(); + el.whalf = 0.5*plane.thickness_; + el.planes.push_back(ip); + if(auto rect = std::dynamic_pointer_cast(plane.surface_)){ + el.shape = Element::box; + el.uhalf = rect->uHalfLength(); + el.vhalf = rect->vHalfLength(); + // merge with the next plane if it is the second Gauss plane of the same slab (offset 2t/sqrt(3) along the normal) + if(ip+1 < planes.size()){ + auto const& next = planes[ip+1]; + auto nrect = std::dynamic_pointer_cast(next.surface_); + VEC3 const sep = next.surface_->center() - el.center; + double const gauss = 2.0*plane.thickness_/std::sqrt(3.0); + if(nrect && next.material_ == plane.material_ && std::fabs(next.thickness_-plane.thickness_) < 1.0e-6 + && std::fabs(std::fabs(next.surface_->normal().Dot(el.wdir))-1.0) < 1.0e-9 + && std::fabs(nrect->uHalfLength()-el.uhalf) < 1.0e-6 && std::fabs(nrect->vHalfLength()-el.vhalf) < 1.0e-6 + && (sep - sep.Dot(el.wdir)*el.wdir).R() < 1.0e-6 && std::fabs(std::fabs(sep.Dot(el.wdir))-gauss) < 1.0e-6){ + el.center += 0.5*sep; + el.whalf = plane.thickness_; + el.planes.push_back(++ip); + } + } + } else if(auto ann = std::dynamic_pointer_cast(plane.surface_)){ + el.shape = Element::tube; + el.rin = ann->innerRadius(); + el.rout = ann->outerRadius(); + } else { + continue; + } + elems.push_back(el); + } + if(kkg.CRV()){ + for(size_t isect = 0; isect < kkg.CRV()->sectors().size(); ++isect){ + auto const& sector = kkg.CRV()->sectors()[isect]; + Element el; + el.name = sector.sname_; + el.sector = int(isect); + el.kind = Element::crvSector; + el.shape = Element::box; + el.center = sector.sector_->center(); + el.udir = sector.sector_->uDirection(); + el.vdir = sector.sector_->vDirection(); + el.wdir = sector.sector_->normal(); + el.uhalf = sector.sector_->uHalfLength(); + el.vhalf = sector.sector_->vHalfLength(); + el.whalf = sector.whw_; + elems.push_back(el); + } + } + return elems; + } + + // pairs of elements sharing a volume above 'minVolume' (mm^3), estimated from 'nsample' points per element + std::vector overlaps(Elements const& elems, unsigned nsample, unsigned seed, double minVolume, bool skipSectorPairs) { + std::vector found; + std::vector lo(elems.size()), hi(elems.size()); + for(size_t ie = 0; ie < elems.size(); ++ie) elems[ie].bounds(lo[ie],hi[ie]); + std::mt19937 rng(seed); + for(size_t ie = 0; ie < elems.size(); ++ie){ + for(size_t je = ie+1; je < elems.size(); ++je){ + if(skipSectorPairs && elems[ie].kind == Element::crvSector && elems[je].kind == Element::crvSector) continue; + if(lo[ie].X() >= hi[je].X() || lo[je].X() >= hi[ie].X() || lo[ie].Y() >= hi[je].Y() || lo[je].Y() >= hi[ie].Y() + || lo[ie].Z() >= hi[je].Z() || lo[je].Z() >= hi[ie].Z()) continue; + // sample the smaller element + auto const& a = elems[ie].volume() < elems[je].volume() ? elems[ie] : elems[je]; + auto const& b = &a == &elems[ie] ? elems[je] : elems[ie]; + unsigned nin = 0; + for(unsigned is = 0; is < nsample; ++is) if(b.inside(a.sample(rng))) ++nin; + double const vol = a.volume()*nin/double(nsample); + if(nin > 0 && vol > minVolume) found.push_back(Overlap{ie,je,vol}); + } + } + return found; + } + + // coplanar CRV sectors with overlapping envelopes: extreme summed layer fractions of lines through the shared area + std::vector sectorLayerSums(KinKalGeom const& kkg, double tol, double step) { + std::vector found; + if(!kkg.CRV()) return found; + auto const& sectors = kkg.CRV()->sectors(); + for(size_t is = 0; is < sectors.size(); ++is){ + auto const& r1 = *sectors[is].sector_; + for(size_t js = is+1; js < sectors.size(); ++js){ + auto const& r2 = *sectors[js].sector_; + if(std::fabs(std::fabs(r1.normal().Dot(r2.normal()))-1.0) > 1.0e-9) continue; + VEC3 const sep = r2.center() - r1.center(); + if(std::fabs(sep.Dot(r1.normal())) > tol) continue; + // shared area in the axes of r1 + auto range = [&](VEC3 const& axis, double half1, double& lo, double& hi){ + double const half2 = r2.uHalfLength()*std::fabs(r2.uDirection().Dot(axis)) + r2.vHalfLength()*std::fabs(r2.vDirection().Dot(axis)); + lo = std::max(-half1,sep.Dot(axis)-half2); hi = std::min(half1,sep.Dot(axis)+half2); + return hi > lo; + }; + double ulo, uhi, vlo, vhi; + if(!range(r1.uDirection(),r1.uHalfLength(),ulo,uhi) || !range(r1.vDirection(),r1.vHalfLength(),vlo,vhi)) continue; + SectorPair pair{is,js,2.0,0.0,0}; + // lines along the normal and tilted by 45 degrees either way across the bars, every 'step' across the shared band + for(double slope : {0.0,1.0,-1.0}){ + VEC3 const dir = (r1.normal() + slope*r1.vDirection()).Unit(); + for(double v = vlo + 0.5*step; v < vhi; v += step){ + VEC3 const pos = r1.center() + 0.5*(ulo+uhi)*r1.uDirection() + v*r1.vDirection(); + double const sum = sectors[is].layerFraction(pos,dir) + sectors[js].layerFraction(pos,dir); + pair.minsum = std::min(pair.minsum,sum); + pair.maxsum = std::max(pair.maxsum,sum); + ++pair.nlines; + } + } + if(pair.nlines > 0) found.push_back(pair); + } + } + return found; + } + + // coplanar (within tol) passive rectangles of the same material and thickness whose footprints overlap or touch + std::vector coplanarPlanes(KinKalGeom const& kkg, double tol) { + std::vector found; + auto const& planes = kkg.passiveMaterialPlanes(); + for(size_t ip = 0; ip < planes.size(); ++ip){ + auto r1 = std::dynamic_pointer_cast(planes[ip].surface_); + if(!r1) continue; + for(size_t jp = ip+1; jp < planes.size(); ++jp){ + auto r2 = std::dynamic_pointer_cast(planes[jp].surface_); + if(!r2 || planes[jp].material_ != planes[ip].material_ || std::fabs(planes[jp].thickness_-planes[ip].thickness_) > 1.0e-6) continue; + if(std::fabs(std::fabs(r1->normal().Dot(r2->normal()))-1.0) > 1.0e-9) continue; + VEC3 const sep = r2->center() - r1->center(); + if(std::fabs(sep.Dot(r1->normal())) > tol) continue; + // in-plane extents of r2 along the axes of r1 + auto overlap1d = [&](VEC3 const& axis, double half1){ + double const half2 = r2->uHalfLength()*std::fabs(r2->uDirection().Dot(axis)) + r2->vHalfLength()*std::fabs(r2->vDirection().Dot(axis)); + double const c2 = sep.Dot(axis); + return std::min(half1,c2+half2) - std::max(-half1,c2-half2); + }; + double const uo = overlap1d(r1->uDirection(),r1->uHalfLength()); + double const vo = overlap1d(r1->vDirection(),r1->vHalfLength()); + if(uo > -tol && vo > -tol) found.push_back(Coplanar{ip,jp,uo,vo}); + } + } + return found; + } + } + } + + class KinKalGeomCheck : public art::EDAnalyzer { + public: + using Name = fhicl::Name; + using Comment = fhicl::Comment; + struct Config { + fhicl::Atom debug{Name("debug"), Comment("1: list the elements, 2: also every bad ray"), 0}; + fhicl::Atom seed{Name("seed"), Comment("random seed"), 12345}; + fhicl::Atom nOverlapSample{Name("nOverlapSample"), Comment("points per element for the overlap test"), 20000}; + fhicl::Atom minOverlapVolume{Name("minOverlapVolume"), Comment("overlap volume (mm^3) above which a pair is reported"), 1000.0}; + fhicl::Atom coplanarTolerance{Name("coplanarTolerance"), Comment("distance (mm) under which planes are coplanar, and footprint gap under which they touch"), 0.1}; + fhicl::Atom allowCRVSectorOverlaps{Name("allowCRVSectorOverlaps"), Comment("skip CRV sector pairs in the volume test: their staggered layers interleave, and their layer fractions are checked instead"), true}; + fhicl::Atom layerSumStep{Name("layerSumStep"), Comment("step (mm) across the shared band of overlapping CRV sectors for the layer-fraction test"), 1.0}; + fhicl::Atom crvScintillator{Name("crvScintillator"), Comment("G4 material of the CRV scintillator bars"), "G4_POLYSTYRENE"}; + fhicl::Atom minLayerAgreement{Name("minLayerAgreement"), Comment("fraction of points on CRV layer center planes where KinKal and G4 agree on scintillator"), 0.95}; + fhicl::Atom failOnOverlaps{Name("failOnOverlaps"), Comment("throw on overlaps or coplanar planes"), true}; + fhicl::Atom gdmlFile{Name("gdmlFile"), Comment("GDML file of the G4 geometry; empty skips the G4 comparison"), ""}; + fhicl::Sequence gdmlOffset{Name("gdmlOffset"), Comment("Mu2e origin in the GDML world frame (mm)"), std::array{0.0,0.0,0.0}}; + fhicl::Sequence materialAliases{Name("materialAliases"), Comment("'KinKalName=G4Name' pairs of matching materials"), + std::vector{"CRVStrongbackAl=G4_Al","DSShieldAl=G4_Al","DSCoilMix=DS1CoilMix","DSCoilMix=DS2CoilMix"}}; + fhicl::Atom nMaterialSample{Name("nMaterialSample"), Comment("points per element for the material test"), 2000}; + fhicl::Atom minMaterialFraction{Name("minMaterialFraction"), Comment("fraction of an element's points that must be in matching G4 material"), 0.8}; + fhicl::Atom nRays{Name("nRays"), Comment("tracker-to-CRV lines"), 5000}; + fhicl::Atom minDensity{Name("minDensity"), Comment("G4 materials below this density (g/cm^3) are ignored"), 0.01}; + fhicl::Atom coverageStep{Name("coverageStep"), Comment("step (mm) of the coverage sampling along G4 steps"), 5.0}; + fhicl::Atom rayAbsTolerance{Name("rayAbsTolerance"), Comment("column density difference (g/cm^2) always accepted"), 2.0}; + fhicl::Atom rayRelTolerance{Name("rayRelTolerance"), Comment("relative column density difference accepted"), 0.1}; + fhicl::Atom maxBadRayFraction{Name("maxBadRayFraction"), Comment("fraction of lines allowed outside the tolerance"), 0.05}; + fhicl::Atom failOnG4Mismatch{Name("failOnG4Mismatch"), Comment("throw when the G4 comparison fails"), false}; + }; + using Parameters = art::EDAnalyzer::Table; + explicit KinKalGeomCheck(Parameters const& config); + void beginRun(art::Run const& run) override; + void analyze(art::Event const&) override {} + private: + using VEC3 = KinKal::VEC3; + bool checkInternal(KinKalGeom const& kkg, KKGeomCheck::Elements const& elems) const; + bool checkG4(KinKalGeom const& kkg, KKGeomCheck::Elements const& elems) const; + std::string g4Material(VEC3 const& detpos, std::string* volname = nullptr) const; + VEC3 toGDML(VEC3 const& detpos) const; // detector coordinates (mm) -> GDML world (cm) + Config config_; + std::multimap aliases_; + }; + + KinKalGeomCheck::KinKalGeomCheck(Parameters const& config) : art::EDAnalyzer(config), config_(config()) { + for(auto const& alias : config_.materialAliases()){ + auto const eq = alias.find('='); + if(eq == std::string::npos) throw cet::exception("CONFIG") << "KinKalGeomCheck: material alias '" << alias << "' is not 'KinKalName=G4Name'\n"; + aliases_.emplace(alias.substr(0,eq),alias.substr(eq+1)); + } + } + + void KinKalGeomCheck::beginRun(art::Run const&) { + GeomHandle kkg_h; + auto const elems = KKGeomCheck::elements(*kkg_h); + GeomHandle det; + if(config_.debug() > 0){ + std::cout << "KinKalGeomCheck: " << elems.size() << " elements (Mu2e coordinates, mm)" << std::endl; + for(auto const& el : elems){ + auto const c = det->toMu2e(CLHEP::Hep3Vector(el.center.X(),el.center.Y(),el.center.Z())); + std::cout << " " << std::setw(22) << std::left << el.name << std::right << " " << std::setw(16) << el.material + << " center (" << c.x() << "," << c.y() << "," << c.z() << ") w " << el.wdir; + if(el.shape == KKGeomCheck::Element::box) std::cout << " halves u " << el.uhalf << " v " << el.vhalf << " w " << el.whalf << " udir " << el.udir; + else std::cout << " r " << el.rin << "-" << el.rout << " half length " << el.whalf; + std::cout << std::endl; + } + } + bool const internalOK = checkInternal(*kkg_h,elems); + bool const g4OK = config_.gdmlFile().empty() ? true : checkG4(*kkg_h,elems); + std::cout << "KinKalGeomCheck: internal " << (internalOK ? "PASS" : "FAIL") + << ", G4 " << (config_.gdmlFile().empty() ? "not run" : (g4OK ? "PASS" : "FAIL")) << std::endl; + if((!internalOK && config_.failOnOverlaps()) || (!g4OK && config_.failOnG4Mismatch())) + throw cet::exception("KINKALGEOM") << "KinKalGeomCheck failed\n"; + } + + bool KinKalGeomCheck::checkInternal(KinKalGeom const& kkg, KKGeomCheck::Elements const& elems) const { + auto const ovls = KKGeomCheck::overlaps(elems,config_.nOverlapSample(),config_.seed(),config_.minOverlapVolume(),config_.allowCRVSectorOverlaps()); + std::cout << "KinKalGeomCheck: " << ovls.size() << " overlapping element pairs" << std::endl; + for(auto const& ovl : ovls) + std::cout << " OVERLAP " << elems[ovl.first].name << " / " << elems[ovl.second].name << " volume " << ovl.volume/1000.0 << " cm^3" << std::endl; + auto const copl = KKGeomCheck::coplanarPlanes(kkg,config_.coplanarTolerance()); + auto const& planes = kkg.passiveMaterialPlanes(); + std::cout << "KinKalGeomCheck: " << copl.size() << " coplanar same-material plane pairs" << std::endl; + for(auto const& cp : copl) + std::cout << " COPLANAR " << planes[cp.first].sid_ << " / " << planes[cp.second].sid_ << " " << planes[cp.first].material_ + << " in-plane overlaps " << cp.uoverlap << ", " << cp.voverlap << " mm" << std::endl; + // a line through the band where two sectors' staggered layers interleave crosses each layer in only one of them + auto const sums = KKGeomCheck::sectorLayerSums(kkg,config_.coplanarTolerance(),config_.layerSumStep()); + unsigned nbadsum = 0; + std::cout << "KinKalGeomCheck: " << sums.size() << " CRV sector pairs with overlapping envelopes (summed layer fraction, min and max)" << std::endl; + for(auto const& sp : sums){ + bool const bad = sp.maxsum > 1.0 + 1.0e-9; + if(bad) ++nbadsum; + std::cout << (bad ? " BAD " : " ") << kkg.CRV()->sectorName(sp.first) << " / " << kkg.CRV()->sectorName(sp.second) + << " " << sp.minsum << " " << sp.maxsum << " (" << sp.nlines << " lines)" << std::endl; + } + return ovls.empty() && copl.empty() && nbadsum == 0; + } + + KinKal::VEC3 KinKalGeomCheck::toGDML(VEC3 const& detpos) const { + GeomHandle det; + auto const m = det->toMu2e(CLHEP::Hep3Vector(detpos.X(),detpos.Y(),detpos.Z())); + auto const& off = config_.gdmlOffset(); + return VEC3(0.1*(m.x()+off[0]),0.1*(m.y()+off[1]),0.1*(m.z()+off[2])); + } + + std::string KinKalGeomCheck::g4Material(VEC3 const& detpos, std::string* volname) const { + auto const g = toGDML(detpos); + TGeoNode* node = gGeoManager->FindNode(g.X(),g.Y(),g.Z()); + if(!node) return ""; + if(volname) *volname = node->GetVolume()->GetName(); + std::string name = node->GetVolume()->GetMaterial()->GetName(); + return name.substr(0,name.find("0x")); + } + + bool KinKalGeomCheck::checkG4(KinKalGeom const& kkg, KKGeomCheck::Elements const& elems) const { + TGeoManager::SetVerboseLevel(0); + if(!TGeoManager::Import(config_.gdmlFile().c_str()) || !gGeoManager) + throw cet::exception("KINKALGEOM") << "KinKalGeomCheck: cannot import " << config_.gdmlFile() << "\n"; + GeomHandle kkmat; + // KinKal densities (DetMaterial: g/mm^3) in g/cm^3, per element + std::vector rho(elems.size(),0.0); + for(size_t ie = 0; ie < elems.size(); ++ie){ + auto const mat = elems[ie].kind == KKGeomCheck::Element::crvSector ? kkmat->CRVMaterial() : kkmat->material(elems[ie].material); + if(!mat) throw cet::exception("KINKALGEOM") << "KinKalGeomCheck: no KinKal material '" << elems[ie].material << "'\n"; + rho[ie] = 1000.0*mat->density(); + } + auto isCRV = [](std::string const& vol){ return vol.compare(0,3,"CRS") == 0; }; + // CRV mother volumes (CRSmother, CRSmotherLayer, CRSscintLayer) are air: count only the solid parts of the CRV + auto isCRVSolid = [&isCRV](std::string const& vol, std::string const& mat){ return isCRV(vol) && mat != "G4_AIR"; }; + auto isCRVElement = [](KKGeomCheck::Element const& el){ + return el.kind == KKGeomCheck::Element::crvSector || el.name.compare(0,14,"CRV_StrongBack") == 0; }; + std::mt19937 rng(config_.seed()); + bool ok = true; + + // (a) material at points inside each element + std::cout << "KinKalGeomCheck: G4 material at points inside each element (KinKal density, matching fraction, most common G4 materials)" << std::endl; + unsigned nbadel = 0; + for(size_t ie = 0; ie < elems.size(); ++ie){ + auto const& el = elems[ie]; + std::map counts; + unsigned nmatch = 0; + for(unsigned is = 0; is < config_.nMaterialSample(); ++is){ + std::string vol; + auto const mat = g4Material(el.sample(rng),&vol); + bool match = false; + if(el.kind == KKGeomCheck::Element::crvSector) match = isCRVSolid(vol,mat); + else if(mat == el.material) match = true; + else { auto range = aliases_.equal_range(el.material); for(auto it = range.first; it != range.second; ++it) if(it->second == mat) match = true; } + if(match) ++nmatch; + ++counts[el.kind == KKGeomCheck::Element::crvSector && match ? std::string("CRS*") : mat]; + } + double const frac = nmatch/double(config_.nMaterialSample()); + bool const good = frac >= config_.minMaterialFraction(); + if(!good) ++nbadel; + std::vector> top; + for(auto const& [m,n] : counts) top.emplace_back(n,m); + std::sort(top.rbegin(),top.rend()); + std::cout << (good ? " " : " BAD ") << std::setw(22) << std::left << el.name << std::right << " " << std::setw(16) << el.material + << " rho " << std::setprecision(4) << rho[ie] << " match " << std::setprecision(3) << frac << " :"; + for(size_t it = 0; it < std::min(3,top.size()); ++it) std::cout << " " << top[it].second << " " << top[it].first/double(config_.nMaterialSample()); + std::cout << std::endl; + } + if(nbadel > 0) ok = false; + + // (b) scintillator on each CRV layer's center plane: KinKal layer spans against G4 + if(kkg.CRV()){ + std::uniform_real_distribution unit(-1.0,1.0); + // a point is in KinKal scintillator if any sector has a layer there: neighbouring sectors' layers share the overlap bands + auto inLayer = [&kkg](VEC3 const& p){ + for(auto const& sect : kkg.CRV()->sectors()){ + auto const& r = *sect.sector_; + VEC3 const rel = p - r.center(); + if(std::fabs(rel.Dot(r.uDirection())) > r.uHalfLength()) continue; + double const w = rel.Dot(r.normal()), v = rel.Dot(r.vDirection()); + for(auto const& layer : sect.layers_){ + if(std::fabs(w - layer.w_) > 1.0) continue; + for(auto const& span : layer.v_) if(v >= span.first && v <= span.second) return true; + } + } + return false; + }; + std::cout << "KinKalGeomCheck: CRV layer spans against G4 on each layer center plane (fraction of points that agree)" << std::endl; + unsigned nbadsect = 0; + for(auto const& sector : kkg.CRV()->sectors()){ + auto const& rect = *sector.sector_; + unsigned nagree = 0, ntot = 0; + for(auto const& layer : sector.layers_){ + for(unsigned is = 0; is < config_.nMaterialSample(); ++is){ + VEC3 const p = rect.center() + 0.98*rect.uHalfLength()*unit(rng)*rect.uDirection() + rect.vHalfLength()*unit(rng)*rect.vDirection() + + layer.w_*rect.normal(); + bool const kk = inLayer(p); + if(kk == (g4Material(p) == config_.crvScintillator())) ++nagree; + ++ntot; + } + } + if(ntot == 0) continue; + double const frac = nagree/double(ntot); + bool const good = frac >= config_.minLayerAgreement(); + if(!good) ++nbadsect; + std::cout << (good ? " " : " BAD ") << std::setw(8) << std::left << sector.sname_ << std::right << " layers " << sector.layers_.size() + << " agree " << std::setprecision(4) << frac << std::endl; + } + if(nbadsect > 0) ok = false; + } + + // (c) column density along lines from the tracker to the CRV sectors, outside the DS bore + if(!kkg.CRV() || kkg.CRV()->sectors().empty() || !kkg.DS() || !kkg.tracker()) return ok; + auto const& sectors = kkg.CRV()->sectors(); + auto const& trk = kkg.tracker()->outer(); + auto const& bore = kkg.DS()->inner(); + std::uniform_real_distribution flat(-1.0,1.0); + std::uniform_int_distribution pick(0,sectors.size()-1); + struct SectorSum { unsigned n = 0, nbad = 0; double g4p = 0, kkp = 0, g4c = 0, kkc = 0; }; + std::map bysector; + std::map uncovered; // G4 column (g/cm^2) outside every KinKal element, per G4 volume + unsigned nbad = 0; + double const coverStep = config_.coverageStep(); + for(unsigned iray = 0; iray < config_.nRays(); ++iray){ + // start: uniform in the tracker volume; end: the far face of a random point of a random sector + double const r = trk.radius()*std::sqrt(0.5*(1.0+flat(rng))), phi = M_PI*flat(rng); + VEC3 const start = trk.center() + VEC3(r*std::cos(phi),r*std::sin(phi),trk.halfLength()*flat(rng)); + auto const& sector = sectors[pick(rng)]; + auto const& rect = *sector.sector_; + VEC3 const end = rect.center() + (rect.uHalfLength()*flat(rng))*rect.uDirection() + (rect.vHalfLength()*flat(rng))*rect.vDirection() + + sector.whw_*rect.normal(); + double const send = (end-start).R(); + VEC3 const dir = (end-start).Unit(); + // allowed segments: [0,send] outside the bore + std::vector> allowed; + double b0, b1; + if(KKGeomCheck::cylinderInterval(bore.center(),bore.axis(),bore.radius(),bore.halfLength(),start,dir,0.0,send,b0,b1)){ + if(b0 > 0.0) allowed.emplace_back(0.0,b0); + if(b1 < send) allowed.emplace_back(b1,send); + } else allowed.emplace_back(0.0,send); + // KinKal column + double kkp = 0.0, kkc = 0.0; + for(size_t ie = 0; ie < elems.size(); ++ie){ + double len = 0.0; + for(auto const& seg : allowed) len += elems[ie].pathLength(start,dir,seg.first,seg.second); + // a CRV sector adds the fraction of its layers this line crosses, as the extrapolation does + if(len > 0.0 && elems[ie].sector >= 0){ + auto const& sect = sectors[elems[ie].sector]; + double const dn = dir.Dot(sect.sector_->normal()); + if(std::fabs(dn) > 1.0e-9) len *= sect.layerFraction(start + ((sect.sector_->center()-start).Dot(sect.sector_->normal())/dn)*dir,dir); + } + (isCRVElement(elems[ie]) ? kkc : kkp) += 0.1*len*rho[ie]; + } + // G4 column: walk the GDML geometry along the line + double g4p = 0.0, g4c = 0.0; + auto const g0 = toGDML(start); + gGeoManager->InitTrack(g0.X(),g0.Y(),g0.Z(),dir.X(),dir.Y(),dir.Z()); + double s = 0.0; + for(unsigned istep = 0; istep < 100000 && s < send; ++istep){ + TGeoNode* node = gGeoManager->GetCurrentNode(); + if(!node || gGeoManager->IsOutside()) break; + double const density = node->GetVolume()->GetMaterial()->GetDensity(); + std::string const vol = node->GetVolume()->GetName(); + gGeoManager->FindNextBoundaryAndStep(0.1*(send-s)+1.0e-4); + double const step = std::max(10.0*gGeoManager->GetStep(),1.0e-6); + if(density >= config_.minDensity()){ + for(auto const& seg : allowed){ + double const a = std::max(s,seg.first), b = std::min(std::min(s+step,send),seg.second); + if(b <= a) continue; + (isCRV(vol) ? g4c : g4p) += 0.1*(b-a)*density; + // coverage: sample the step and tally the part outside every KinKal element + unsigned const npt = std::max(1u,unsigned(std::ceil((b-a)/coverStep))); + unsigned nout = 0; + for(unsigned ip = 0; ip < npt; ++ip){ + VEC3 const p = start + (a + (ip+0.5)*(b-a)/npt)*dir; + if(std::none_of(elems.begin(),elems.end(),[&p](auto const& el){ return el.inside(p); })) ++nout; + } + if(nout > 0) uncovered[vol.substr(0,vol.find("0x"))] += 0.1*(b-a)*density*nout/npt; + } + } + s += step; + } + double const g4 = g4p + g4c, kk = kkp + kkc; + bool const bad = std::fabs(kk-g4) > std::max(config_.rayAbsTolerance(),config_.rayRelTolerance()*g4); + auto& sum = bysector[sector.sname_]; + ++sum.n; sum.g4p += g4p; sum.kkp += kkp; sum.g4c += g4c; sum.kkc += kkc; + if(bad){ + ++nbad; ++sum.nbad; + if(config_.debug() > 1){ + GeomHandle det; + auto const m = det->toMu2e(CLHEP::Hep3Vector(start.X(),start.Y(),start.Z())); + std::cout << " BAD ray to " << sector.sname_ << " start (" << m.x() << "," << m.y() << "," << m.z() << ") dir " << dir + << " G4 " << g4p << "+" << g4c << " KinKal " << kkp << "+" << kkc << " g/cm^2" << std::endl; + } + } + } + std::cout << "KinKalGeomCheck: tracker-to-CRV column density outside the DS bore, mean g/cm^2 (passive + CRV)" << std::endl; + for(auto const& [name,sum] : bysector){ + std::cout << " " << std::setw(8) << std::left << name << std::right << " rays " << std::setw(5) << sum.n + << " G4 " << std::setw(7) << sum.g4p/sum.n << " + " << std::setw(7) << sum.g4c/sum.n + << " KinKal " << std::setw(7) << sum.kkp/sum.n << " + " << std::setw(7) << sum.kkc/sum.n + << " bad " << sum.nbad/double(sum.n) << std::endl; + } + double const badfrac = nbad/double(std::max(1u,config_.nRays())); + std::cout << "KinKalGeomCheck: " << nbad << " of " << config_.nRays() << " lines outside tolerance (fraction " << badfrac << ")" << std::endl; + if(badfrac > config_.maxBadRayFraction()) ok = false; + std::vector> unc; + for(auto const& [vol,col] : uncovered) unc.emplace_back(col/config_.nRays(),vol); + std::sort(unc.rbegin(),unc.rend()); + std::cout << "KinKalGeomCheck: G4 volumes crossed outside every KinKalGeom element (mean g/cm^2 per line)" << std::endl; + for(size_t iu = 0; iu < std::min(25,unc.size()); ++iu) std::cout << " " << std::setw(40) << std::left << unc[iu].second << std::right << " " << unc[iu].first << std::endl; + return ok; + } +} + +DEFINE_ART_MODULE(mu2e::KinKalGeomCheck) diff --git a/KinKalGeom/src/SConscript b/KinKalGeom/src/SConscript index eea1886bbb..51a4e6804b 100644 --- a/KinKalGeom/src/SConscript +++ b/KinKalGeom/src/SConscript @@ -15,6 +15,7 @@ helper = mu2e_helper(env) mainlib = helper.make_mainlib([ 'mu2e_ConfigTools', + 'mu2e_DataProducts', 'KinKal_MatEnv', 'KinKal_Geometry', 'KinKal_Trajectory', @@ -32,6 +33,32 @@ mainlib = helper.make_mainlib([ rootlibs ]) +helper.make_plugins([ + mainlib, + 'mu2e_GeometryService', + 'mu2e_DataProducts', + 'art_Framework_Core', + 'art_Framework_Principal', + 'art_Framework_Services_Registry', + 'art_Persistency_Provenance', + 'art_Utilities', + 'canvas', + 'MF_MessageLogger', + 'fhiclcpp', + 'fhiclcpp_types', + 'cetlib', + 'cetlib_except', + 'KinKal_MatEnv', + 'KinKal_Geometry', + 'KinKal_Trajectory', + 'KinKal_General', + 'GenVector', + 'MathCore', + 'CLHEP', + 'Geom', + rootlibs +]) + # This tells emacs to view this file in python mode. # Local Variables: diff --git a/Mu2eKinKal/inc/ExtrapolateSweep.hh b/Mu2eKinKal/inc/ExtrapolateSweep.hh index ca66b63739..eba667c8e7 100644 --- a/Mu2eKinKal/inc/ExtrapolateSweep.hh +++ b/Mu2eKinKal/inc/ExtrapolateSweep.hh @@ -40,6 +40,7 @@ namespace mu2e { namespace KKGeom { class CaloFrontPanelPipes; class CaloInnerSupport; + struct KKCRVSector; } // one surface the sweep can cross struct SweepTarget { @@ -60,6 +61,7 @@ namespace mu2e { double thick_ = 0.0; // material thickness (mm) KKGeom::CaloFrontPanelPipes const* pipes_ = nullptr; // calopanel: the thickness depends on where the pipe plane is crossed KKGeom::CaloInnerSupport const* support_ = nullptr; // calosupport: the support and the part this target finds + KKGeom::KKCRVSector const* crvsector_ = nullptr; // crvsector: the material is the fraction of the sector's layers the track crosses SupportPart part_ = casefront; unsigned maxcross_ = 1; // crossings kept per sweep, 0 for no limit int group_ = -1; // targets in a group keep only the first crossing of any of them diff --git a/Mu2eKinKal/inc/KKExtrap.hh b/Mu2eKinKal/inc/KKExtrap.hh index 9ae5ffe4f8..db70ad6451 100644 --- a/Mu2eKinKal/inc/KKExtrap.hh +++ b/Mu2eKinKal/inc/KKExtrap.hh @@ -261,6 +261,7 @@ namespace mu2e { tg.rect_ = sector.sector_; tg.mat_ = &*kkmat_h->CRVMaterial(); tg.thick_ = 2*sector.whw_; + tg.crvsector_ = §or; plane(tg,*sector.sector_); tgts.push_back(tg); } @@ -444,7 +445,9 @@ namespace mu2e { return true; } double thick = tg.pipes_ ? tg.pipes_->wallDepth(inter.pos_) : tg.thick_; + if(tg.crvsector_) thick *= tg.crvsector_->layerFraction(inter.pos_,inter.pdir_); // near a seam, the staggered layers are shared with the next sector if(tg.effect_ == SweepTarget::calopanel && thick <= 0.0) return true; // the pipe plane between the pipes + if(tg.effect_ == SweepTarget::crvsector && thick <= 0.0){ ktrk.addIntersection(tg.sid_,inter); return true; } // inside the envelope but between layers // KinKal records why a fit became unusable (e.g. a failed domain walk); the direction just ends if(!ktrk.fitStatus().usable()) return false; auto const& ftraj = ktrk.fitTraj(); @@ -480,7 +483,7 @@ namespace mu2e { return true; } case SweepTarget::crvsector: { - auto shell = std::make_shared>(tg.rect_,tg.sid_,*tg.mat_,inter,reftrajptr,tg.thick_,intertol_); + auto shell = std::make_shared>(tg.rect_,tg.sid_,*tg.mat_,inter,reftrajptr,thick,intertol_); if(rangesOut(*shell,tdir)) return rangeOut(ktrk,tg,inter); ktrk.addCRVXing(shell,tdir); return true;