diff --git a/doc/LaTex/DD4hep-AIDA-logo.png b/doc/LaTex/DD4hep-AIDA-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..71e94b458cf33650a870c5b440909081d641aa05 Binary files /dev/null and b/doc/LaTex/DD4hep-AIDA-logo.png differ diff --git a/doc/LaTex/DD4hep-Lumical-detailed.png b/doc/LaTex/DD4hep-Lumical-detailed.png new file mode 100644 index 0000000000000000000000000000000000000000..1150e0ce5c8a35b9aa9dab424e4b29a32263b6a5 Binary files /dev/null and b/doc/LaTex/DD4hep-Lumical-detailed.png differ diff --git a/doc/LaTex/DD4hep-Lumical.png b/doc/LaTex/DD4hep-Lumical.png new file mode 100644 index 0000000000000000000000000000000000000000..4885685a952ab75368f8fdebe759fc571b178caf Binary files /dev/null and b/doc/LaTex/DD4hep-Lumical.png differ diff --git a/doc/LaTex/DD4hep-Overview.tex b/doc/LaTex/DD4hep-Overview.tex new file mode 100644 index 0000000000000000000000000000000000000000..2c8cc8b2dfa01d64b2a69179be53541255055045 --- /dev/null +++ b/doc/LaTex/DD4hep-Overview.tex @@ -0,0 +1,418 @@ +%============================================================================= +\section{Introduction and General Overview} +%============================================================================= +\label{sec:introduction} +\noindent +The development of a coherent set of software tools for the description of +High Energy Physics detectors from a single source of information has been +on the agenda of many experiments for decades. +Providing appropriate and consistent detector views to simulation, +reconstruction and analysis applications from a single information source +is crucial for the success of the experiments. +Detector description in general includes not only the geometry and the +materials used in the apparatus, but all parameters describing e.g. the +detection techniques, constants required by alignment and calibration, +description of the readout structures, conditions data, etc. + +\noindent +The design of the DD4hep toolkit\cite{bib:DD4hep} +is shaped on the experience of detector description +systems, which were implemented for the LHC experiments, in particular +the LHCb experiment~\cite{bib:LHCb,bib:LHCb-geometry}, +as well as the lessons learnt from other +implementations of geometry description tools developed for +the Linear Collider community~\cite{bib:ILD,bib:SiD}. +Designing a coherent set of tools, with most of the basic components +already existing in one form or another, is an opportunity for getting +the best of all existing solutions. +DD4hep aims to widely reuse used existing software components, in particular +the ROOT geometry package~\cite{bib:ROOT-tgeo}, part of the +ROOT project\cite{bib:ROOT}, a tool for +building, browsing, navigating and visualizing detector geometries. The +code is designed to optimize particle transport through complex +structures and works standalone with respect to any Monte-Carlo +simulation engine. The ROOT geometry package provides +sophisticated 3D visualization functionality, which is ideal for building +detector and event displays. The second component is +the Geant4 simulation toolkit~\cite{bib:geant4}, which is used to +simulate the detector response from particle collisions in complex designs. +In DD4hep the geometrical +representation provided by ROOT is the main source of information. +In addition DD4hep provides the automatic conversions to other geometrical +representations, such as Geant4, and the convenient usage of these +components without the reinvention of the existing functionality. + +\noindent +In Section~\ref{sec:architectural-concepts} the scope and the high-level +requirements of the DD4hep toolkit are elaborated (in the following +also called "the toolkit"). This is basically the high level vision +of the provided functionality to the experimental communities. +In Section~\ref{sec:toolkit-design} the high-level or architectural design +of the toolkit is presented, and in subsequent subsections design +aspects of the various functional components and their interfaces will be +introduced. + +%============================================================================= +\subsection{Project Scope and Requirements} +%============================================================================= +\label{sec:architectural-concepts} +\noindent +The detector description should fully describe and qualify +the detection apparatus and must expose access to all information +required to interpret event data recorded from particle collisions. +Experience from the LHC experiments has shown that a generalized +view, not limited only to geometry, is very beneficial in order to obtain +a coherent set of tools for the interpretation of collision data. +This is particularly important in later stages of the experiment's life cycle, +when a valid set of detector data must be used to analyze real or simulated +detector response from particle collisions. An example would be an alignment +application, where time dependent precise detector positions are matched +with the detector geometry. + +\noindent +The following main requirements influenced the design of the toolkit: +\begin{itemize} +\item {\bf{Full Detector Description.}} The toolkit should be able to + manage the data describing the detector geometry, the materials used + when building the structures, + visualization attributes, detector readout information, alignment, + calibration and environmental parameters - all that is + necessary to interpret event data recorded from particle collisions. +\item {\bf{The Full Experiment Life Cycle}} should be supported. + The toolkit should support the development of the detector concepts, + detector optimizations, + construction and later operation of the detector. + The transition from one phase to the next should be simple and not require + new developments. The initial phases are characterized by very $ideal$ + detector descriptions, i.e. only very few parameters are sufficient + to describe new + detector designs. Once operational, the detector will be different + from the ideal detector, and each part of the detector will have + to have its own specific parameters and conditions, + which are exposed by the toolkit. +\item {\bf{One single source of detector information}} must be sufficient + to perform all data processing applications such as simulation, + reconstruction, online trigger and data analysis. + This ensures that all applications see a coherent description. + In the past attempts by experiments to re-synchronize parallel + detector descriptions were always problematic. + Consequently, the detector description is the union of the information + needed by all applications, though the level of detail may be selectable. +\item {\bf{Ease of Use}} influenced both + the design and the im\-ple\-men\-tation. The definition of sub\-detectors, + their geometrical description and the access to con\-ditions and alignment + data should follow a minimalistic, simple and intuitive interface. + Hence, the of the developer using the toolkit is focused on specifics of + the detector design and not on technicalities handled transparently by + the toolkit. +\end{itemize} + +%============================================================================= +\begin{figure}[h] + \begin{center} + \includegraphics[height=80mm] {DD4hep_big_picture.png} + \caption{The components of the DD4hep detector geometry toolkit.} + \label{fig:dd4hep-big-picture} + \end{center} + \vspace{-0.4cm} +\end{figure} + +%============================================================================= +\subsection{Toolkit Design} +\label{sec:toolkit-design} +%============================================================================= +\noindent +Figure~\ref{fig:dd4hep-big-picture} shows the architecture +of the main components of the toolkit and their interfaces +to the end-user applications, namely the simulation, reconstruction, +alignment and visualization. +The central element of the toolkit is the so-called generic detector +description model. This is an in-memory model, i.e., a set of C++ objects +holding the data describing the geometry and other information of +the detector. The rest of the toolkit consists of tools and interfaces +to input or output information from this generic detector model. +The model and its components will be described in subsequence sections. + +%============================================================================= +\subsubsection{The Compact Detector Description} +\label{sec:problem_analysis} +%============================================================================= +\noindent +Inspired from the work of the linear collider detector +simulation~\cite{bib:LCDD,bib:lcsim}, the compact detector description is used +to define an ideal detector as typically used during +the conceptual design phase of an experiment. +The compact description in its minimalistic form is probably not going to +be adequate later in the detector life cycle and +is likely to be replaced or refined when a more realistic detector +with deviations from the ideal would be needed by the experiment. + +\noindent +In the compact description the detector is parametrized in minimalistic terms +with user provided parameters in XML. +XML is an open format, the DD4hep parsers do not validate against a fix schema +and hence allow to easily introduce new elements and attributes to describe +detectors. This feature minimizes the burden on the end-user while still +supporting flexibility. +%Figure~\ref{fig:fig-vxd-xml} shows a partial example of how to describe an ideal +%silicon-based vertex detector with regular disposition of ladders +%in 2 layers in total. +Such a compact detector descriptions cannot be interpreted in a +general manner, therefore so called $Detector$ $Constructors$ are needed. + +%============================================================================= +%\begin{figure}[h] +% \begin{center} +% \includegraphics[width=16cm] {DD4hep_compact_xml.png} +% \caption{An example sniplett of the compact detector description. The +% example shows the description of a 2 layered silicon vertex +% detector.} +% \label{fig:fig-vxd-xml} +% \end{center} +% \vspace{-0.6cm} +%\end{figure} +%============================================================================= + +%============================================================================= +\subsubsection{Detector Constructors} +\label{sec:detector-constructors} +%============================================================================= +\noindent +Detector Constructors are relatively small code fragments that get +as input an XML element from the compact description that represents +a single detector instance. The code interprets the data and expands +its geometry model in memory using the elements from the generic detector +description model described in section~\ref{subsec:generic-model}. +The toolkit invokes these code fragments in a data driven way +using naming conventions during the initialization phase of the +application. Users focus on one +single detector type at the time, but the toolkit supports them to still +construct complex and large detector setups. +Two implementations are currently supported: One is based on +C++, which performs better and is able to detect errors at +compiler time, but the code is slightly more technical. +The other is based on Python fragments, the code is more readable and +compact but errors are only detected at execution time. + +\noindent +The compact description together with the detector constructors are sufficient +to build the detector model and to visualize it. If during the lifetime of the +experiment the detector model changes, the corresponding constructors will +need to be adapted accordingly. +DD4hep provides already a palette of basic pre-implemented geometrical detector +concepts to design experiments. In view of usage of DD4hep as a detector +description toolkit, this library may in the future also adopt +generic designs of detector components created by end users e.g. during the design +phase of future experiments. +%============================================================================= +\begin{figure}[t] + \begin{center} + \includegraphics[height=110mm] {DD4hep_classes.png} + \caption{Class diagram with the main classes and their relations + for the Generic Detector Description Model. The implementing + ROOT classes are shown in brackets.} + \label{fig:dd4hep-detector-model} + \end{center} +\end{figure} +%============================================================================= +\subsection{Generic Detector Description Model} +\label{subsec:generic-model} +%============================================================================= + +\noindent +This is the heart of the DD4hep detector description toolkit. Its purpose is +to build in memory a model of the detector including its geometrical aspects +as well as structural and functional aspects. The design reuses the elements +from the ROOT geometry package and extends them in case required functionality +is not available. Figure~\ref{fig:dd4hep-detector-model} illustrates the main +players and their relationships. +Any detector is modeled as a tree of $Detector$ $Elements$, the entity +central to this design, which is represented in the implementation by +the $DetElement$ class~\cite{bib:LHCb-geometry}. It offers all +applications a natural entry point to any detector part of the experiment +and represents a complete sub-detector (e.g. TPC), a part of a +sub-detector (e.g. TPC-Endcap), a detector module or any other convenient +detector device. +The main purpose is to give access to the data associated +to the detector device. For example, if the user writes some TPC reconstruction +code, accessing the TPC detector element from this code will provide access +the all TPC geometrical dimensions, the alignment and calibration constants +and other slow varying conditions such as the gas pressure, end-plate +temperatures etc. The $Detector$ $Element$ acts as a data concentrator. +Applications may access the full experiment geometry and all connected data +through a singleton object called $LCDD$, which provides +management, bookkeeping and ownership to the model instances. + +\noindent +The geometry is implemented using the ROOT geometry classes, which are used +directly without unnecessary interfaces to isolate the end-user from the +actual ROOT based implementation. There is one exception: +The constructors are wrapped to facilitate a very compact and readable +notation to end-users building custom $Detector$ $Constructors$. + +%============================================================================= +\subsubsection{Detector Element Tree versus the Geometry Hierarchy} +\label{subsect:detelement-hierarchy} +%============================================================================= +\noindent +The geometry part of the detector description is delegated to the ROOT classes. +$Logical$ $Volumes$ are the basic objects used in building the geometrical hierarchy. +A $Logical$ $Volume$ is a shape with its dimensions and consist of a given material. +They represent unpositioned objects which store all information about +the placement of possibly embedded volumes. The same +volume can be replicated several times in the geometry. The $Logical$ $Volume$ also +represents a system of reference with respect to its containing volumes. +The reuse of instances of $Logical$ $Volumes$ for different placements +optimizes the memory consumption and detailed geometries for complex setups +consisting of millions of volumes may be realized with reasonable amount of memory. +The difficulty is to identify a given positioned volume +in space and e.g. applying misalignment to one of these volumes. +The relationship between the Detector Element and the placements +is not defined by a single reference to the placement, but the full path +from the top of the detector geometry model to resolve existing +ambiguities due to the reuse of $Logical$ $Volumes$. +Hence, individual volumes must be identified by their full path from mother +to daughter starting from the top-level volume. + +%============================================================================= +\begin{figure}[t] + \begin{center} + \includegraphics[height=85mm] {DD4hep_detelement_tree.png} + \caption{The object diagram of a hypothetical TPC detector showing in + parallel the $Detector$ $Element$ and the $Geometry$ hierarchy and the + relationships between the objects.} + \label{fig:dd4hep-hierarchies} + \end{center} +\end{figure} +%============================================================================= + +\noindent +The tree structure of +Detector Elements is a parallel structure to the geometrical hierarchy. +This structure will probably not be as deep as the geometrical one since +there would not need to associate detector information at very fine-grain +level - it is unlikely that every little metallic screw +needs associated detector information such as alignment, conditions, etc. +Though this screw and many other replicas must be described in the geometry +description since it may be important e.g. for its material contribution +in the simulation application. Thus, the tree of Detector Elements is +fully degenerate and each detector element object will be placed only +once in the detector element tree as illustrated for a hypothetical +TPC detector in Figure~\ref{fig:dd4hep-hierarchies}. + +%============================================================================= +\subsubsection{Extensions and Views} +\label{subsect:extesions-and-views} +%============================================================================= + +\noindent +As depicted in Figure~\ref{fig:dd4hep-big-picture} the reconstruction +application will require special functionality extending the basics +offered by the common detector element. This functionality may be +implemented by a set of specialized classes that will extend the +detector element. These extensions will be in charge +of providing specific answers to the questions formulated by the +reconstruction algorithms such as pattern recognition, tracking, vertexing, +particle identification, etc. One example could be to transform a calorimeter +cell identifier into a 3D space position in the global coordinate system. +A generic detector description toolkit would be unable +to answer this concrete question, however it provides a convenient +environment for the developer to slot-in code fragments, which implement the +additional functionality using parameters stored +in the XML compact description. + +\noindent +Depending on the functionality these specialized component must be able to +either store additional data, expose additional behavior or both. Additional +behavior may easily be added overloading the $DetElement$ class using its +internal data. The internal data is public and addressed by reference, hence +any number of views extending the $DetElement$ behavior may be constructed +with very small overhead. Additional data may be added by any user at any time +to any instance of the $DetElement$ class using a simple aggregation +mechanism shown in Figure~\ref{fig:dd4hep-extensions}. Data extensions must +differ by their type. The freedom to attach virtually +any data item allows for optimized attachments depending on the +application type, such as special attachments for reconstruction, +simulation, tracking, etc. +%============================================================================= +\begin{figure}[t] + \begin{center} + \includegraphics[width=115mm] {DD4hep-extensions.png} + \caption{Extensions may be attached to common Detector Elements which + extend the functionality of the common DetElement + class and support e.g. caching of precomputed values.} + \label{fig:dd4hep-extensions} + \end{center} +\end{figure} +%============================================================================= +This design allows to build views addressing the following use-cases: +\begin{itemize} +\item{{\bf{Convenience Views}}} provide higher level abstractions + and internally group complex calculations. Such views simplify + the life of the end-users. +\item{{\bf{Optimization Views}}} allows end-users extend the data of + the common detector detector element and store precomputed + results, which would be expensive to obtain repeatedly. +\item{{\bf{Compatibility Views}}} help to ensure smooth periods of + software redesign. During the life-time of the experiment + often various software constructs are for functional reasons + re-designed and re-engineered. + Compatibility Views either adapt new data designs to existing application + code or expose new behavior based on existing data. +\end{itemize} + +%============================================================================= +\subsection{Simulation Support} +\label{subsect:simulation-support} +%============================================================================= +\noindent +Detector-simulation depends strongly on the use of an underlying simulation toolkit, +the most prominent candidate nowadays being Geant4~\cite{bib:geant4}. +DD4hep supports simulation activities with Geant4 providing +an automatic translation mechanism between geometry representations. +The simulation response in the active elements of the detector +is not implemented by the toolkit, since it is strongly influenced by the technical +choices and precise simulations depends on the very specific detection techniques. +In Geant4 this response is computed in software constructs called $Sensitive$ +$Detectors$. + +\noindent +Ideally DD4hep aims to provide a generic simulation application. +Similar to the palette of pre-implemented geometrical detector +concepts to design experiments, it provides a palette of $Sensitive$ +$Detectors$ to simulate the detector response in form of a component library. +Detector designers may base the simulation of a planned experiment +on these predefined components for initial design and optimization +studies. In a similar way easy access +and configuration of other user actions of Geant4 is provided. + +%============================================================================= +\subsection{Detector Alignment Support} +\label{subsect:alignment-support} +%============================================================================= +\noindent +The support for alignment operations is crucial to the usefulness of the +toolkit. In the linear collider community this support is basically missing +in all the currently used geometry description systems. +The possibility to apply into the detector description alignment $deltas$ +(differences with respect the ideal or measured position) and read them +from an external source is mandatory to exploit the toolkit. A typical +alignment application would consist of calculating a new set of $deltas$ +from a given starting point, which could then be loaded and applied again +in order to validate the alignment by recalculating some alignment residuals. +The ROOT geometry package supports to apply an [mis]-alignment to +$touchable$ objects in the geometry. $Touchable$ objects are identified +by the path of positioned volumes starting with the top node +(e.g. path=$/TOP/A_1/B_4/C_3$). Contrary to ordinary multiple placements +of $Logical$ $Volumes$, $touchable$ objects are degenerate and only +valid for one single volume~\cite{bib:ROOT-tgeo}. +To simplify the usage for the end user, +the identification of a positioned volume will be connected +to the Detector Element, where only the relative path with respect +to the Detector Element will have to be specified +rather the full path from the top volume. +The $delta$-values will have to be read from various data sources. +The initial implementation will be based on simple XML files, later +a connection to other sources such as the detector conditions database +is envisaged. + diff --git a/doc/LaTex/DD4hep-abstract.tex b/doc/LaTex/DD4hep-abstract.tex new file mode 100644 index 0000000000000000000000000000000000000000..d737ff65cdccd6e83aec8b686583d47f94f4c526 --- /dev/null +++ b/doc/LaTex/DD4hep-abstract.tex @@ -0,0 +1,17 @@ +%============================================================================= +\noindent +The detector description is an essential component that is used to analyze data +resulting from particle collisions in high energy physics experiments. +We will present a generic detector description toolkit +and describe the guiding requirements and the architectural design for +such a toolkit, as well as the main implementation choices. +The design is strongly driven by easy of use; +developers of detector descriptions and applications using +them should provide minimal information and minimal specific +code to achieve the desired result. +The toolkit will be built reusing already existing components +from the ROOT geometry package and provides missing functional +elements and interfaces to offer a complete and coherent +detector description solution. A natural integration to +Geant4, the detector simulation program used in high energy physics, +is provided. diff --git a/doc/LaTex/DD4hep-bibliography.tex b/doc/LaTex/DD4hep-bibliography.tex new file mode 100644 index 0000000000000000000000000000000000000000..1985339d46de241644ebab97c221be18183b0b87 --- /dev/null +++ b/doc/LaTex/DD4hep-bibliography.tex @@ -0,0 +1,46 @@ +\bibitem{bib:DD4hep} DD4Hep web page, http://aidasoft.web.cern.ch/DD4hep. + +\bibitem{bib:LHCb} LHCb Collaboration, + "LHCb, the Large Hadron Collider beauty experiment, reoptimised detector + design and performance", CERN/LHCC 2003-030 + +\bibitem{bib:LHCb-geometry} S. Ponce et al., + "Detector Description Framework in LHCb", + International Conference on Computing in High Energy and Nuclear Physics (CHEP 2003), + La Jolla, CA, 2003, proceedings. + +\bibitem{bib:ILD} The ILD Concept Group, + "The International Large Detector: Letter of Intent",\\ + ISBN 978-3-935702-42-3, 2009. + +\bibitem{bib:SiD} H. Aihara, P. Burrows, M. Oreglia (Editors), + "SiD Letter of Intent", + arXiv:0911.0006, 2009. + +\bibitem{bib:ROOT-tgeo} R.Brun, A.Gheata, M.Gheata, "The ROOT geometry package",\\ + Nuclear Instruments and Methods {\bf{A}} 502 (2003) 676-680. + +\bibitem{bib:ROOT} R.Brun et al., + "Root - An object oriented data analysis framework",\\ + Nuclear Instruments and Methods {\bf{A}} 389 (1997) 81-86. + +\bibitem{bib:geant4} S. Agostinelli et al., + "Geant4 - A Simulation Toolkit", \\ + Nuclear Instruments and Methods {\bf{A}} 506 (2003) 250-303. + +\bibitem{bib:LCDD} T.Johnson et al., + "LCGO - geometry description for ILC detectors", + International Conference on Computing in High Energy and Nuclear Physics (CHEP 2007), + Victoria, BC, Canada, 2012, Proceedings. + +\bibitem{bib:lcsim} N.Graf et al., + "lcsim: An integrated detector simulation, + reconstruction and analysis environment", + International Conference on Computing in High Energy and Nuclear Physics (CHEP 2012), + New York, 2012, Proceedings. + +\bibitem{bib:GDML} R. Chytracek et al., + "Geometry Description Markup Language for Physics Simulation and Analysis + Applications", + IEEE Trans. Nucl. Sci., Vol. 53, Issue: 5, Part 2, 2892-2896, + http://gdml.web.cern.ch. diff --git a/doc/LaTex/DD4hep-detelement-drawing.png b/doc/LaTex/DD4hep-detelement-drawing.png new file mode 100644 index 0000000000000000000000000000000000000000..9642d68c30b850860248b068340a3e29cf07398b Binary files /dev/null and b/doc/LaTex/DD4hep-detelement-drawing.png differ diff --git a/doc/LaTex/DD4hep-extensions.png b/doc/LaTex/DD4hep-extensions.png new file mode 100644 index 0000000000000000000000000000000000000000..ea81d439068c115099872e00ebc72bf5582c473c Binary files /dev/null and b/doc/LaTex/DD4hep-extensions.png differ diff --git a/doc/LaTex/DD4hep-materials.png b/doc/LaTex/DD4hep-materials.png new file mode 100644 index 0000000000000000000000000000000000000000..f76d5e5bad37320aed9904bc5a64d852a9e80e65 Binary files /dev/null and b/doc/LaTex/DD4hep-materials.png differ diff --git a/doc/LaTex/DD4hep-readout.png b/doc/LaTex/DD4hep-readout.png new file mode 100644 index 0000000000000000000000000000000000000000..412fcf2714a4f691ddd10af912f83c83006060b8 Binary files /dev/null and b/doc/LaTex/DD4hep-readout.png differ diff --git a/doc/LaTex/DD4hep-sensitive-detectors.png b/doc/LaTex/DD4hep-sensitive-detectors.png new file mode 100644 index 0000000000000000000000000000000000000000..5f1c8758f1a4a1299c6f1c8b6ee5c587d54019ca Binary files /dev/null and b/doc/LaTex/DD4hep-sensitive-detectors.png differ diff --git a/doc/LaTex/DD4hep-setup.tex b/doc/LaTex/DD4hep-setup.tex new file mode 100644 index 0000000000000000000000000000000000000000..19a5a5d796058ebe84d919f3f0485d6274bb6b01 --- /dev/null +++ b/doc/LaTex/DD4hep-setup.tex @@ -0,0 +1,114 @@ +% +% +\usepackage{graphicx} +\usepackage{hyperref} +\usepackage{verbatim} +\usepackage{fix-cm} +\usepackage{lineno} +\usepackage{fancyhdr} +% +% +\oddsidemargin 0.1 in +\evensidemargin 0.1 in +% +% +\newlength{\backindent}\setlength{\backindent}{2cm} +\textwidth 5.375 in % Width of text line. +\advance\textheight by1.4cm +\advance\voffset by-1.4cm +\advance\textwidth by\backindent +% +% +% === Fancy headers setup =============================== +% +\setlength{\headheight}{15.2pt} +\pagestyle{fancyplain} { +\fancyhead[L]{\includegraphics[height=10mm]{DD4hep-AIDA-logo.png}\vspace{-0.3cm}} +\fancyhead[C]{} +\fancyhead[R]{\sffamily{\underline{\hspace{6cm}Advanced European Infrastructures for Detectors at Accelerators}}} +\fancyfoot[L]{} +\fancyfoot[C]{\sffamily{User Manual}} +\fancyfoot[R]{\sffamily{\thepage}} +} +% +% +\newcommand{\tw}[1]{${\tt{#1}}$} +\newcommand{\tts}[1]{{\tt\small{#1}}} +\newcommand{\bold}[1]{{\bf{#1}}} +% +% +\newcommand{\DDE}{{$\tt{DDEve}$\space}} +\newcommand{\DDhep}{{$\tt{DD4hep}$\space}} +\newcommand{\DDG}{{\tt{DDG4}\space}} +\newcommand{\DDA}{{\tt{DDAlign}\space}} +% +% +\newcommand{\docline}[2]{\vspace{0.1cm}{\bf{#1}} & \parbox{14.5cm}{#2}\\} +% +% === Specialization of the lineno package +% +\renewcommand{\linenumberfont} {\normalfont\small\sffamily} +\renewcommand{\makeLineNumber} {\makeLineNumberLeft} +\renewcommand{\linenumbersep} {2pt} +% +% === Set font to code section with line numbers +% +\newenvironment{code}{\par\vspace{0.01cm}\small\linenumbers\verbatim\setcounter{linenumber}{1}}{\endverbatim\nolinenumbers\vspace{-0.02cm}}% +% +% === Set font to code section with line numbers +% +\newenvironment{unnumberedcode}{\par\vspace{-0.1cm}\small\verbatim\setcounter{linenumber}{1}}% +{\endverbatim\vspace{-0.2cm}} +% +% === Command to insert http links to the DD4hep geomtery package +% +\newcommand{\detdesc}[2] +{ + \href{http://www.cern.ch/frankm/DD4hep/doc/#1}{#2} +} +% +% === Command to insert http links to the ROOT geomtery package +% +\newcommand{\tgeo}[2] +{ + \href{http://root.cern.ch/root/html/#1.html}{#2} +} +% +% === Compactify the item list ========================= +% +\newcommand{\itemcompact}{\setlength{\itemsep}{1pt}\setlength{\parskip}{0pt}\setlength{\parsep}{0pt}} +% +% +% === Title page command =============================== +% +\newcommand{\mytitle}[2]{ +\begin{titlepage} +% +\pagestyle{empty} +% +\includegraphics[height=25mm] {DD4hep-AIDA-logo.png} + +\vspace{0.02cm} + +{\sffamily{\underline{\hspace{6cm}Advanced European Infrastructures for Detectors at Accelerators}}} + +\vspace{2cm} + +\begin{center} +{\fontsize{72}{32}\selectfont{\bfseries{#1}}} + +\vspace{3cm} +{\Huge\bf{#2}} + +\vspace{5cm} +M.Frank%\textsuperscript{1}, +%F.Gaede\textsuperscript{2}, +%C.Grefe\textsuperscript{1}, +%P.Mato\textsuperscript{1} + +%{\textsuperscript{1} +{CERN, 1211 Geneva 23, Switzerland} +%{\textsuperscript{2} Desy, 22607 Hamburg, Germany} +\end{center} +\end{titlepage} +} diff --git a/doc/LaTex/DD4hep-solids.png b/doc/LaTex/DD4hep-solids.png new file mode 100644 index 0000000000000000000000000000000000000000..7c99a688b55e444e77df9f38674bfdd10c081eb3 Binary files /dev/null and b/doc/LaTex/DD4hep-solids.png differ diff --git a/doc/LaTex/DD4hep-volmgr.png b/doc/LaTex/DD4hep-volmgr.png new file mode 100644 index 0000000000000000000000000000000000000000..33bc334d196d65aeddb547bf519c627ba49546d7 Binary files /dev/null and b/doc/LaTex/DD4hep-volmgr.png differ diff --git a/doc/LaTex/DD4hep-volume-code.png b/doc/LaTex/DD4hep-volume-code.png new file mode 100644 index 0000000000000000000000000000000000000000..3406b27df7e90b5804008464b9a29946991fdade Binary files /dev/null and b/doc/LaTex/DD4hep-volume-code.png differ diff --git a/doc/LaTex/DD4hep-xml-code-snippet.png b/doc/LaTex/DD4hep-xml-code-snippet.png new file mode 100644 index 0000000000000000000000000000000000000000..4050b847003323c93533ac9d23bda239d9df89c6 Binary files /dev/null and b/doc/LaTex/DD4hep-xml-code-snippet.png differ diff --git a/doc/LaTex/DD4hep-xml-data-snippet.png b/doc/LaTex/DD4hep-xml-data-snippet.png new file mode 100644 index 0000000000000000000000000000000000000000..f37c3941b7c05ee61877d24c34871f18b15256ef Binary files /dev/null and b/doc/LaTex/DD4hep-xml-data-snippet.png differ diff --git a/doc/LaTex/DD4hep-xml-data-structure.png b/doc/LaTex/DD4hep-xml-data-structure.png new file mode 100644 index 0000000000000000000000000000000000000000..8962cfe1957eaa3c4afbd19a58b7d1e372b4f9f4 Binary files /dev/null and b/doc/LaTex/DD4hep-xml-data-structure.png differ diff --git a/doc/LaTex/DD4hepManual.0.tex b/doc/LaTex/DD4hepManual.0.tex new file mode 100644 index 0000000000000000000000000000000000000000..8b2f98a0e68e8901c0f302d0573629e05a15744f --- /dev/null +++ b/doc/LaTex/DD4hepManual.0.tex @@ -0,0 +1,1831 @@ +%============================================================================= +\documentclass[10pt,a4paper]{article} +% +\input{DD4hep-setup.tex} +% +\pagestyle{fancyplain}{\fancyfoot[C]{\sffamily{DD4hep User Manual}}} +% +% +\begin{document} +% +\mytitle{ +DD4hep +}{ +A Detector Description Toolkit\\ +for High Energy Physics\\ +\vspace{0.3cm} +Experiments +} +% +% +%== Abstract =============================================================== +\pagestyle{plain} +\pagenumbering{Roman} +\setcounter{page}{1} + +\begin{abstract} +\normalsize +\input{DD4hep-abstract.tex} +\end{abstract} + +\vspace{8cm} + +\begin{center} +{\large{\bf{ +\begin{tabular} {| l | l | l |} +\hline +\multicolumn{3}{| c |}{} \\[0.2cm] +\multicolumn{3}{| c |}{Document History} \\[0.2cm] +\multicolumn{3}{| c |}{} \\[0.2cm] +\hline + & & \\ +Document & & \\ +version & Date & Author \\[0.2cm] \hline + & & \\ +1.0 & 19/11/2013 & Markus Frank CERN/LHCb \\ + & & \\ \hline +\end{tabular} +}}} +\end{center} + +\clearpage +% +% +%== TOC ==================================================================== +\tableofcontents +\clearpage +% +% +%== Introduction =========================================================== +\pagenumbering{arabic} +\setcounter{page}{1} +\input{DD4hep-Overview.tex} +% +\newpage +%============================================================================= +% Manual +%============================================================================= +\section{User Manual} +\label{sec:dd4hep-user-manual} +%============================================================================= +\noindent +This chapter describes how supply a physics application developed with all the +information related to the detector which is necessary to process data from +particle collisions and to qualify the detecting apparatus in order to +interpret these event data. + +\noindent +The clients of the detector description are the algorithms residing in the +event processing framework that need this information in order to perform +their job (reconstruction, simulation, etc.). +The detector description provided by \DDhep is a framework for developers +to provide the specific detector information to algorithms. + +\noindent +In the following sections an overview is given over the various independent +elements of DD4hep followed by the discussion of an example which leads to +the description of a detector when combining these elements. +This includes a discussion of the features of the \DDhep detector description +and of its structure. + +%============================================================================= +\subsection{Building DD4hep} +\label{sec:dd4hep-user-manual-building} +%============================================================================= + +\noindent +The \DDhep source code is freely available. See the +\detdesc{doc/LICENSE}{licence conditions}. +Please read the \detdesc{doc/release.notes}{Release Notes} +before downloading or using this release. + +\noindent +The \DDhep project consists of several packages. The idea +has been to separate the common parts of +the detector description toolkit from concrete detector examples. + +\noindent +The package {\tw{DDCore}} contains the definition of the basic classes +of the toolkit: \tw{Handle}, \tw{DetElement}, \tw{Volume}, \tw{PlacedVolume}, +\tw{Shapes}, \tw{Material}, etc. Most of these classes are \tw{handles} +to ROOT's TGeom classes. + +%============================================================================= +\subsubsection{Supported Platforms} +\label{sec:dd4hep-user-manual-platforms} +%============================================================================= +\noindent +Supported platforms for DD4hep are the CERN Linux operating systems: +\begin{itemize} +\item \tw{Scientic} \tw{Linux} \tw{CERN} \tw{6} +\item \tw{Scientic} \tw{Linux} \tw{CERN} \tw{ 7} - once approved. +\end{itemize} +Support for any other platform will well be taken into account, but can only +be actively supported by users who submit the necessary patches. + +%============================================================================= +\subsubsection{Prerequisites} +\label{sec:dd4hep-user-manual-prerequisites} +%============================================================================= +\noindent +DD4hep depends on a number of external packages. +The user will need to install these in his/her +system before building and running the examples +\begin{itemize}\itemcompact +\item Mandatory are recent \tw{CMake} (version 2.8 or higher) and +\item \tw{ROOT} (version 5.34 or higher) installations. +\item If the \tw{Xerces-C} is used to parse compact descriptions and + installation of {Xerces-C} will be required. +\item To build \DDG it is useful to have an installation of the Boost + header files. +\item To build and run the simulation examples \tw{Geant4} will be required. +\end{itemize} + +\newpage +%============================================================================= +\subsubsection{CMake Build Options for DD4hep} +\label{sec:dd4hep-user-manual-building} +%============================================================================= +\noindent +The package provides the basic mechanisms for constructing the +{\it{Generic Detector Description Model}} in memory from XML compact detector +definition files. Two methods are currently supported: one based +on the C++ \tw{Xerces}-C parser, and another one based on Python and using the +\tw{PyROOT} bindings to ROOT~\footnote{I will not continue +the support using PyROOT. \\ +If there is a desire that it stays alive +someone else should take care -- M.Frank}. +\tw{PyROOT} may be enabled using the switch: + +\begin{unnumberedcode} + -DD4HEP_USE_PYROOT:BOOL +\end{unnumberedcode} + +\noindent +The XML parsing method is enabled by default using the \tw{TiXML} parser. Optionally +instead of \tw{TiXML} the \tw{Xerces}-C parser may be chosen by setting the +two configuration options appropriately: + +\begin{unnumberedcode} + -DD4HEP_USE_XERCESC:BOOL + -DXERCESC_ROOT_DIR=<path to Xerces-C-installation-directory> +\end{unnumberedcode} + +\noindent +{\bf{DDG4}} is the package that contains the conversion of \DDhep geometry +into Geant4 geometry to be used for simulation. +The option \tw{DD4HEP\_WITH\_GEANT4:BOOL} controls the building or not of +this package that has the dependency to Geant4. The Geant4 installation +needs to be located using the variable: + +\begin{unnumberedcode} + -DDD4HEP_WITH_GEANT4=on -D + -DGeant4_DIR=<path to Geant4Config.cmake> +\end{unnumberedcode} + +\noindent +To properly handle component properties using \tw{boost::spirit}, +access to the Boost header files must be provided. +\vspace{0.3cm} +\begin{unnumberedcode} + -DDD4HEP_USE_BOOST=ON + -DBOOST_INCLUDE_DIR=<path to the boost include directory> +\end{unnumberedcode} + +\noindent +Other useful build options: +\begin{itemize} +\item build doxygen documentation ( after 'install' open ./doc/html/index.html) +\begin{unnumberedcode} + -D INSTALL_DOC=on +\end{unnumberedcode} + +\item {\bf{note:}} you might have to update your environment beforehand to have all needed + libraries in the shared lib search path (this will vary with OS, shell, etc.) e.g +\begin{unnumberedcode} + . /data/ilcsoft/geant4/9.5/bin/geant4.sh + export CLHEP_BASE_DIR="/data/ilcsoft/HEAD/CLHEP/2.1.0.1" + export CLHEP_INCLUDE_DIR="$CLHEP_BASE_DIR/include" + export PATH="$CLHEP_BASE_DIR/bin:$PATH" + export LD_LIBRARY_PATH="$CLHEP_BASE_DIR/lib:$LD_LIBRARY_PATH" +\end{unnumberedcode} +\end{itemize} + +%============================================================================= +\subsubsection{Build From Source} +\label{sec:dd4hep-user-manual-building-from-source} +%============================================================================= +\noindent +The following steps are necessary to build \DDhep: +\begin{itemize} +\item Set the environment, at least ROOT needs to be initialized, e.g. + \begin{unnumberedcode} + source /data/ilcsoft/root/5.34.03/bin/thisroot.sh + \end{unnumberedcode} + \vspace{-0.6cm} + (the bare minimum is: \tw{export ROOTSYS=<path to root installation>}). + +\item First checkout code from the repository: + \begin{unnumberedcode} + svn co https://svnsrv.desy.de/public/aidasoft/DD4hep/trunk DD4hep + \end{unnumberedcode} + \vspace{-0.6cm} + +\item We refer to the directory \DDhep as the source directory. The +next step is to create a directory in which to configure and run the build +and store the build products. This directory should not be the same as, or +inside, the source directory. In this guide, we create this build directory +alongside our source directory: + \begin{unnumberedcode} + mkdir build + cd build + cmake -DCMAKE_INSTALL_PREFIX=<dd4hep-install-pasth> <CMake-options> ../DD4hep + make -j 4 + make install + \end{unnumberedcode} +\end{itemize} +The CMake Variable \tw{CMAKE\_INSTALL\_PREFIX} is used to set the install directory, +the directory under which the \DDhep libraries, headers and support files +will be installed. + +%============================================================================= +\subsubsection{Tutorial} +\label{sec:dd4hep-user-manual-tutorial} +%============================================================================= +\noindent +In January 2013 an introductory tutorial was given at CERN to members of the +linear collider community. The slides to the tutorial can be found +\detdesc{doc/DD4hep_Tutorial.pdf}{here}. +The tutorial is not entirely up to date. Please take the content with a +grain of salt. + +%============================================================================= +\subsubsection{Doxygen Code Documentation} +\label{sec:dd4hep-user-manual-doxygen} +%============================================================================= +\noindent +The \DDhep source code is instrumented with tags understood by doxygen. +The generated code documentation can be found +\detdesc{html/index.html}{here}. + +%============================================================================= +\subsubsection{Remarks} +\label{sec:dd4hep-user-manual-remarks} +%============================================================================= +\noindent +The main reference is the doxygen information of \DDhep and the ROOT documentation. +Please refer to these sources for a detailed view of the capabilities of +each component and/or its handle. +For coherence reasons, the description of the +interfaces is limited to examples which illustrate the usage of the basic +components. + +%============================================================================= +\subsubsection{Caveat} +\label{sec:dd4hep-user-manual-caveat} +%============================================================================= +\noindent +The atomic units in of Geant4 are (millimeter, nanosecond and MeV and radians). +The atomic units of ROOT-TGeo are (centimeter, seconds, GeV and degrees). +Unfortunately the authors could not agree on a common system of units +and mixing the two can easily result in a chaos. +Users must be aware of this fact. + + +\newpage +%============================================================================= +\subsection{DD4hep Handles} +\label{sec:dd4hep-user-manual-handles} +%============================================================================= +\noindent +Handles are the means of clients accessing \DDhep detector description data. +The data itself is not held by the handle itself, the handle only allows the +access to the data typically held by a pointer. The template handle class +(see for details the \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_handle.html}{header file}). +allows type safe assignment of other unrelated handles and supports standard +data conversions to the underlying object in form of the raw pointer, +a reference etc. The template handle class: + +\begin{code} +template <typename T> struct Handle { + typedef T Implementation; + typedef Handle<Implementation> handle_t; + T* m_element; + Handle() : m_element(0) { } + Handle(T* e) : m_element(e) { } + Handle(const Handle<T>& e) : m_element(e.m_element) { } + template<typename Q> Handle(Q* e) + : m_element((T*)e) { verifyObject(); } + template<typename Q> Handle(const Handle<Q>& e) + : m_element((T*)e.m_element) { verifyObject(); } + Handle<T>& operator=(const Handle<T>& e) { m_element=e.m_element; return *this;} + bool isValid() const { return 0 != m_element; } + bool operator!() const { return 0 == m_element; } + void clear() { m_element = 0; } + T* operator->() const { return m_element; } + operator T& () const { return *m_element; } + T& operator*() const { return *m_element; } + T* ptr() const { return m_element; } + template <typename Q> Q* _ptr() const { return (Q*)m_element; } + template <typename Q> Q* data() const { return (Q*)m_element; } + template <typename Q> Q& object() const { return *(Q*)m_element; } + const char* name() const; +}; +\end{code} + +\noindent +effectively works like a pointer with additional object validation during assignment +and construction. Handles support direct access to the held object: either by using +the + +\begin{verbatim} + operator->() (See line 16 above) +\end{verbatim} + +\noindent +or the automatic type conversions: + +\begin{verbatim} + operator T& () const (See line 17-18 above) + T& operator*() const. +\end{verbatim} + +\noindent +All entities of the \DDhep detector description are exposed as handles - +raw pointers should not occur in the code. +The handles to these objects serve two purposes: +\begin{itemize}\itemcompact +\item Hold a pointer to the object and extend the functionality of a raw + pointer. +\item Enable the creation of new objects using specialized constructors + within sub-classes. To ensure memory integrity and avoid resource + leaks these created objects should always be stored in the + detector description data hub $LCDD$ described in + section~\ref{sec:dd4hep-user-manual-LCDD-hub}. +\end{itemize} + +\newpage +%============================================================================= +\subsection{The Data Extension Mechanism} +\label{sec:dd4hep-user-manual-data-extensions} +%============================================================================= +\noindent +Data extensions are client defined C++ objects aggregated to basic \DDhep objects. +The need to introduce such data extensions results from the simple fact that +no data structure can be defined without the iterative need in the long term +to extend it leading to implementations, which can only satisfy a subset of +possible clients. To accomplish for this fact a mechanism was put in place +which allows any user to attach any supplementary information provided +the information is embedded in a polymorph object with an accessible destructor. +There is one limitation though: object extension must differ by their +interface type. +There may not be two objects attached with the identical interface type. +The actual implemented sub-type of the extension is not relevant. +Separating the interface type from the implementation type keeps client +code still functional even if the implementation of the extension changes +or is a plug-able component. + +\noindent +The following code snippet shows the extension interface: + +\begin{code} + /// Extend the object with an arbitrary structure accessible by the type + template <typename IFACE, typename CONCRETE> IFACE* addExtension(CONCRETE* c); + /// Access extension element by the type + template <class T> T* extension() const; +\end{code} + +Assuming a client class of the following structure: +\begin{code} + class ExtensionInterface { + virtual ~ExtensionInterface(); + virtual void foo() = 0; + }; + + class ExtensionImplementation : public ExtensionInterface { + ExtensionImplementation(); + virtual ~ExtensionImplementation(); + virtual void foo(); + }; +\end{code} +is then attached to an extensible object as follows: +\begin{code} + ExtensionImplementation* ptr = new ExtensionImplementation(); + ... fill the ExtensionImplementation instance with data ... + module.addExtension<ExtensionInterface>(ptr); +\end{code} +The data extension may then be retrieved whenever the instance of the +extensible object "module" is accessible: +\begin{code} + ExtensionInterface* ptr = module.extension<ExtensionInterface>(); +\end{code} +The lookup mechanism is rather efficient. Though it is advisable to +cache the pointer withing the client code if the usage is very frequent. + + +\noindent +There are currently three object types present which support this mechanism: +\begin{itemize}\itemcompact +\item the central object of \DDhep, the \tw{LCDD} class discussed in + section~\ref{sec:dd4hep-user-manual-LCDD-hub}. +\item the object describing subdetectors or parts thereof, the + \tw{DetElement} class discussed in + section~\ref{sec:dd4hep-user-manual-detector-elements}. + Detector element extensions in addition require the presence + of a copy constructor to support e.g. reflection operations. + Without a copy mechanism detector element hierarchies could + cloned. +\item the object describing sensitive detectors, + the \tw{SensitiveDetector} class discussed in + section~\ref{sec:dd4hep-user-manual-sensitive-detectors}. +\end{itemize} + + +\newpage +%============================================================================= +\subsection{XML Tools and Interfaces} +\label{sec:dd4hep-user-manual-xml-tools} +%============================================================================= +\noindent +Using native tools to interpret XML structures is rather tedious and lengthy. +To easy the access to XML data considerable effort was put in place to easy +the life of clients as much as possible using predefined constructs to +access XML attributes, elements or element collections. + +\noindent +The functionality of the XML tools is perhaps best shown with a small example. +Imagine to extract the data from an XML snippet like the following: +\begin{code} + <detector name="Sometthing"> + <tubs rmin="BP_radius - BP_thickness" rmax="BP_radius" zhalf="Endcap_zmax/2.0"/> + <position x="0" y="0" z="Endcap_zmax/2.0" /> + <rotation x="0.0" y="CrossingAngle/2.0" z="0.0" /> + <layer id="1" inner_r="Barrel_r1" + outer_r="Barrel_r1 + 0.02*cm" inner_z="Barrel_zmax + 0.1*cm"> + <slice material = "G10" thickness ="0.5*cm"/> + </layer> + <layer id="2" inner_r="Barrel_r2" + outer_r="Barrel_r2 + 0.02*cm" inner_z="Barrel_zmax + 0.1*cm"> + <slice material = "G10" thickness ="0.5*cm"/> + </layer> + .... + </detector> +\end{code} + +The variable names used in the XML snippet are evaluated when interpreted. +Unless the attributes are accessed as strings, the client never sees the +strings, but only the evaluated numbers. +The anatomy of the C++ code snippets to interpret such a data section +looks very similar: +\begin{code} + static void some_xml_handler(xml_h e) { + xml_det_t x_det (e); + xml_comp_t x_tube = x_det.tubs(); + xml_dim_t pos = x_det.position(); + xml_dim_t rot = x_det.rotation(); + string name = x_det.nameStr(); + + for(xml_coll_t i(x_det,_U(layer)); i; ++i) { + xml_comp_t x_layer = i; + double zmin = x_layer.inner_z(); + double rmin = x_layer.inner_r(); + double rmax = x_layer.outer_r(); + double layerWidh = 0; + + for(xml_coll_t j(x_layer,_U(slice)); j; ++j) { + double thickness = xml_comp_t(j).thickness(); + layerWidth += thickness; + } + } + } +\end{code} +In the above code snippet an XML (sub-)tree is passed to the executing +function as a handle to an XML element ({\tt{xml\_h}}). Such handles may seamlessly be +assigned to any supporting helper class inheriting from the +class {\tt{XML::Element}}, which encapsulates the functionality required to +interpret the XML structures. +Effectively the various XML attributes and child nodes +are accessed using functions with the same +name from a convenience handle. +In lines 3-5 child nodes are extracted, lines 10-12,16 access element attributes. +Element collections with the same tag names \tw{layer} and \tw{slice} are exposed +to the client code using an iteration mechanism. + +\noindent +Note the macros $\tt{\_U(layer)}$ and $\tt{\_U(slice)}$: +When using Xerces-C as an XML parser, +it will expand to the reference to an object containing the unicode value +of the string "layer". The full list of predefined tag names can be found in the +include file \detdesc{html/_unicode_values_8h.html}{DD4hep/UnicodeValues.h}. +If a user tag is not part in the precompiled tag list, the corresponding Unicode +string may be created with the macro \tw{\_Unicode(layer)} or the function +\tw{Unicode("layer")}. + +\noindent +The convenience handles actually implement +these functions to ease life. There is no magic - newly created attributes +with new names obviously cannot be accessed with convenience mechanism. +Hence, either you know what you are doing and you create your own +convenience handlers or you restrict yourself a bit in the creativity +of defining new attribute names. + +\noindent +There exist several utility classes to extract data from predefined XML tags: +\begin{itemize}\itemcompact +\item Any XML element is described by an XML handle + \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_handle.html}{\tt{XML::Handle\_t}} + ({\tt{xml\_t}}). Handles are the basic structure for the support + of higher level interfaces described above. The assignment of a handle + to any of the interfaces below is possible. +\item The class \detdesc{html/struct_d_d4hep_1_1_x_m_l_1_1_element.html}{\tt{XML::Element}} + ({\tt{xml\_elt\_t}}) + supports in a simple way the navigation through the hierarchy of the + XML tree accessing child nodes and attributes. Attributes at this + level are named entities and the tag name must be supplied. +\item The class \detdesc{html/struct_d_d4hep_1_1_x_m_l_1_1_dimension.html}{\tt{XML::Dimension}} + with the type definition {\tt{xml\_dim\_t}}, + supports numerous access functions named identical to the + XML attribute names. Such helper classes simplify the tedious + string handling required by the +\item The class \detdesc{html/struct_d_d4hep_1_1_x_m_l_1_1_component.html}{\tt{XML::Component}} + ({\tt{xml\_comp\_t}}) and \\ + the class \detdesc{html/struct_d_d4hep_1_1_x_m_l_1_1_det_element.html}{\tt{XML::Detector}} + ({\tt{xml\_det\_t}}) resolving other issues useful to construct detectors. +\item Sequences of XML elements with an identical tag name may be handled + as iterations as shown in the Figure above using the class + \detdesc{html/struct_d_d4hep_1_1_x_m_l_1_1_collection__t.html}{\tt{XML::Collection\_t}}. +\item Convenience classes, which allow easy access to element attributes + may easily be constructed using the methods of the {\tt{XML::Element}} + class. This allows to construct very flexible thou non-intrusive + extensions to \DDhep. Hence there is a priori no need to modify + these helpers for the benefit of only one single client. + In the presence of multiple requests such extensions may though be adopted. +\end{itemize} +It is clearly the responsibility of the client to only request attributes +from an XML element, which exist. If an attribute, a child node etc. is not +found within the element an exception is thrown. + +\noindent +The basic interface of the \tw{XML::Element} class allows to access tags +and child nodes not exposed by the convenience wrappers: +\begin{code} + /// Access the tag name of this DOM element + std::string tag() const; + /// Access the tag name of this DOM element + const XmlChar* tagName() const; + + /// Check for the existence of a named attribute + bool hasAttr(const XmlChar* name) const; + /// Retrieve a collection of all attributes of this DOM element + std::vector<Attribute> attributes() const; + /// Access single attribute by it's name + Attribute getAttr(const XmlChar* name) const; + /// Access attribute with implicit return type conversion + template <class T> T attr(const XmlChar* tag) const; + /// Access attribute name (throws exception if not present) + const XmlChar* attr_name(const Attribute attr) const; + /// Access attribute value by the attribute (throws exception if not present) + const XmlChar* attr_value(const Attribute attr) const; + + /// Check the existence of a child with a given tag name + bool hasChild(const XmlChar* tag) const; + /// Access child by tag name. Thow an exception if required in case the child is not present + Handle_t child(const Strng_t& tag, bool except = true) const; + /// Add a new child to the DOM node + Handle_t addChild(const XmlChar* tag) const; + /// Check if a child with the required tag exists - if not create it and add it to the current node + Handle_t setChild(const XmlChar* tag) const; +\end{code} + +%============================================================================= +\subsection{The Detector Description Data Hub: LCDD} +\label{sec:dd4hep-user-manual-LCDD-hub} +%============================================================================= +\noindent +As shown in Figure~\ref{fig:dd4hep-detector-model}, any access to the detector +description data is done using a standardized interface called \tw{LCDD}. +During the configuration phase of the detector the interface is used to populate +the internal data structures. +Data structures present in the memory layout of the detector description +may be retrieved by clients at any time using the +\detdesc{html/struct_d_d4hep_1_1_geometry_1_1_l_c_d_d.html}{\tw{LCDD} interface class}. +This includes of course, the access during the actual detector construction. +The following code listing shows the accessor method to retrieve +detector description entities from the interface. Not shown are access methods +for groups of these entities and the methods to add objects: + +\begin{code} +struct LCDD { + + ///+++ Shortcuts to access often used quantities + + /// Return handle to material describing air + virtual Material air() const = 0; + /// Return handle to material describing vacuum + virtual Material vacuum() const = 0; + /// Return handle to "invisible" visualization attributes + virtual VisAttr invisible() const = 0; + + ///+++ Access to the top level detector elements and the corresponding volumes + + /// Return reference to the top-most (world) detector element + virtual DetElement world() const = 0; + /// Return reference to detector element with all tracker devices. + virtual DetElement trackers() const = 0; + + /// Return handle to the world volume containing everything + virtual Volume worldVolume() const = 0; + /// Return handle to the volume containing the tracking devices + virtual Volume trackingVolume() const = 0; + + ///+++ Access to geometry and detector description objects + + /// Retrieve a constant by it's name from the detector description + virtual Constant constant(const std::string& name) const = 0; + /// Retrieve a matrial by it's name from the detector description + virtual Material material(const std::string& name) const = 0; + /// Retrieve a field component by it's name from the detector description + virtual DetElement detector(const std::string& name) const = 0; + /// Retrieve a sensitive detector by it's name from the detector description + virtual SensitiveDetector sensitiveDetector(const std::string& name) const = 0; + /// Retrieve a readout object by it's name from the detector description + virtual Readout readout(const std::string& name) const = 0; + /// Retrieve a id descriptor by it's name from the detector description + virtual IDDescriptor idSpecification(const std::string& name) const = 0; + /// Retrieve a subdetector element by it's name from the detector description + virtual CartesianFieldfield(const std::string& name) const = 0; + + ///+++ Access to visualisation attributes and Geant4 processing hints + + /// Retrieve a visualization attribute by it's name from the detector description + virtual VisAttr visAttributes(const std::string& name) const = 0; + + /// Retrieve a region object by it's name from the detector description + virtual Region region(const std::string& name) const = 0; + /// Retrieve a limitset by it's name from the detector description + virtual LimitSet limitSet(const std::string& name) const = 0; + /// Retrieve an alignment entry by it's name from the detector description + virtual AlignmentEntryalignment(const std::string& path) const = 0; + ... + + ///+++ Extension mechanism: + + /// Extend the sensitive detector element with an arbitrary structure accessible by the type + template <typename IFACE, typename CONCRETE> IFACE* addExtension(CONCRETE* c); + /// Access extension element by the type + template <class T> T* extension() const; +}; +\end{code} + +\noindent +As shown in the above listing, the \tw{LCDD} interface is the main access point to access +a whole set +\begin{itemize}\itemcompact +\item often used predefined values such as the material "air" or "vacuum" (line 5-10). +\item the top level objects "world", "trackers" and the corresponding volumes (line 14-22). +\item items in the constants table containing named definitions also used during the + interpretation of the XML content after parsing (line 27) +\item named items in the the material table (line 29) +\item named subdetectors after construction and the corresponding (line 31) +\item named sensitive detectors with their (line 33) +\item named readout structure definition using a (line 35) +\item named readout identifier descriptions (line 37) +\item named descriptors of electric and/or magnetic fields (line 39). +\end{itemize} +Additional support for specialized applications is provided by the interface: +\begin{itemize}\itemcompact +\item Geant4: named region settings (line 47) +\item Geant4: named limits settings (line 49) +\item Visualization: named visualization attributes (line 44) +\item Alignment: named alignment entries to correct displaced volumes (line 51) +\item User defined extensions (line 56-59) are supported with the extension mechanism + described in section~\ref{sec:dd4hep-user-manual-data-extensions}. +\end{itemize} +All the values are populated either directly from XML or from +\tw{detector-constructors} (see section~\ref{sec:detector-constructors}). The interface +also allows to load XML configuration files of any kind provided an appropriate +interpretation plugin is present. In the next section we describe the functionality +of the "lccdd" plugin used to interpret the compact detector description. +This mechanism can easily be extended using ROOT plugins, where the +plugin name must corrspond to the XML root element of the document to +be interpreted. + +\newpage +%============================================================================= +\subsection{Detector Description Persistency in XML} +\label{sec:compact-xml-structure} +%============================================================================= +\noindent +As explained in a previous section, the mechanism involved in the data loading +allow an application to be fairly independent of the technology used to populate +the transient detector representation. However, if one wants to use a given tech- +nology, she/he has to get/provide the corresponding conversion mechanism. +Though \DDhep also supports the population of the detector description using +python constructs, we want to focus here on the XML based population. +The choice of XML was driven mainly by its easiness of use and the number +of tools provided for its manipulation and parsing. Moreover, XML data +can be easily translated into many other format using tools like \tw{XSLT} +processors. +The grammar used for the XML data is pretty simple and straight forward, +actually very similar to other geometry description languages based +on XML. For example the material description is nearly identical +to the material description in \tw{GDML}~\cite{bib:GDML}. +The syntactic structure of the compact XML description was taken from +the SiD detector description~\cite{bib:LCDD}. +The following listing shows the basic layout of any +the compact detector description file with its different sections: + +\begin{code} +<lccdd> + <info> ... </info> Auxiliary detector model information + <includes> ... </includes> Section defining GDML files to be included + <define> ... </define> Dictionary of constant expressions and varables + <materials> ... </materials> Additional material definitions + <display> ... </display> Definition of visualization attributes + <detectors> ... </detectors> Section with sub-detector definitions + <readouts> ... </readouts> Section with readout structure definitions + <limits> ... </limits> Definition of limit sets for Geant4 + <fields> ... </fields> Field definitions +</lccdd> +\end{code} + +\noindent +The root tag of the XML tree is {\tw{lccdd}}. This name is fixed. +In the following the content of the various sections is discussed. +The XML sections are filled with the following information: +\begin{itemize} +\item {\bf{The \tw{<info>} sub-tree}} contains auxiliary information about + the detector model: + +\begin{code} +<info name="clic_sid_cdr" + title="CLIC Silicon Detector CDR" + author="Christian Grefe" + url="https://twiki.cern.ch/twiki/bin/view/CLIC/ClicSidCdr" + status="development" + version="$Id: compact.xml 665 2013-07-02 18:49:26Z markus.frank $"> + <comment>The compact format for the CLIC Silicon Detector used + for the conceptual design report</comment> +</info> +\end{code} + +\item {\bf{The \tw{<includes>} section}} allows to include GDML sub-trees containing + material descriptions. These files are processed {\it{before}} the + detector constructors are called: + +\begin{code} +<includes> + <gdmlFile ref="elements.xml"/> + <gdmlFile ref="materials.xml"/> + ... +</includes> +\end{code} + +\item {\bf{The \tw{<define>} section}} contains all variable definitions + defined by the client to simplify the definition of subdetectors. + These name-value pairs are fed to the expression evaluator + and MUST evaluate to a number. String constants are not allowed. + These variables can be combined to formulas e.g. to automatically + re-dimension subdetectors if boundaries are changed: + +\begin{code} +<define> + <constant name="world_side" value="30000"/> + <constant name="world_x" value="world_side"/> + <constant name="world_y" value="world_side"/> + <constant name="world_z" value="world_side"/> + .... +</define> +\end{code} + +\item {\bf{The $\tt<materials>$ sub-tree}} contains additional materials, which + are not contained in the default materials tables. The snippet below shows + an example to extend the table of known materials. For more details please see + section~\ref{sec:compact-material-description}. + +\begin{code} +<materials> + <!-- The description of an atomic element or isotope --> + <element Z="30" formula="Zn" name="Zn" > + <atom type="A" unit="g/mol" value="65.3955" /> + </element> + ... + <!-- The description of a new material --> + <material name="CarbonFiber_15percent"> + ... + </material> + ... +</materials> +\end{code} + +\item {\bf{The visualization attributes}} are defined in the $\tt<display>$ section. + Clients access visualization settings by name. The possible attributes are shown + below and essentially contain the RGB color values, the visibility and the drawing style: + +\begin{code} +<display> + <vis name="InvisibleNoDaughters" showDaughters="false" visible="false"/> + <vis name="SiVertexBarrelModuleVis" + alpha="1.0" r="1" g="1" b="0.6" + drawingStyle="solid" + showDaughters="true" + visible="true"/> + .... +</display> +\end{code} + +\item {\bf{Limisets}} contain parameters passed to Geant4: + +\begin{code} +<limits> + <limitset name="cal_limits"> + <limit name="step_length_max" particles="*" value="5.0" unit="mm" /> + </limitset> +</limits> +\end{code} + +\item {\bf{The $\tt<detectors>$}} section contains subtrees of the type $\tt<detector>$ + which contain all parameters used by the $detector constructors$ + to actually expand the geometrical structure. Each subdetector has a name and a type, + where the type is used to call the proper constructor plugin. If the subdetector + element is sensitive, a forward reference to the corresponding readout structure + is mandatory. The remaining parameters are user defined: + +\begin{code} +<detectors> + <detector id="4" name="SiTrackerEndcap" type="SiTrackerEndcap" readout="SiTrackerEndcapHits"> + <comment>Outer Tracker Endcaps</comment> + <module name="Module1" vis="SiTrackerEndcapModuleVis"> + <trd x1="36.112" x2="46.635" z="100.114/2" /> + <module_component thickness="0.00052*cm" material="Copper" /> + <module_component thickness="0.03*cm" material="Silicon" sensitive="true" /> + ... + </module> + ... + <layer id="1"> + <ring r="256.716" zstart="787.105+1.75" nmodules="24" dz="1.75" module="Module1"/> + <ring r="353.991" zstart="778.776+1.75" nmodules="32" dz="1.75" module="Module1"/> + <ring r="449.180" zstart="770.544+1.75" nmodules="40" dz="1.75" module="Module1"/> + </layer> + ... + </detector> +</detectors> +\end{code} + +\item {\bf{The $\tt<readouts>$ section}} defined the encoding of sensitive volumes + to so-called cell-ids, which are in \DDhep 64-bit integer numbers. The encoding + is subdetector dependent with one exception: to uniquely identity each subdetector, + the width of the system field must be the same. The usage of these data is + discussed in section~\ref{dd4hep-sensitive-detectors}. +\begin{code} +<readouts> + <readout name="SiTrackerEndcapHits"> + <id>system:8,barrel:3,layer:4,module:14,sensor:2,side:32:-2,strip:20</id> + </readout> + ... +</readouts> +\end{code} + +\item {\bf{Electromagnetic fields}} are described in the $\tt<fields>$ section. + There may be several fields present. In \DDhep the resulting field vectors + may be both electric and magnetic. The strength of the overall field is calculated + as the superposition of the individual components: +\begin{code} +<fields> + <field name="GlobalSolenoid" type="solenoid" + inner_field="5.0*tesla" + outer_field="-1.5*tesla" + zmax="SolenoidCoilOuterZ" + outer_radius="SolenoidalFieldRadius"> + </field> + ... +</fields> +\end{code} +\end{itemize} + + + +\newpage +%============================================================================= +\subsection{Material Description} +\label{sec:compact-material-description} +%============================================================================= +\noindent +Materials are needed by logical volumes. They are defined as isotopes, +elements or mixtures. +Elements can optionally be composed of isotopes. Composition is always done +by specifying the fraction of the mass. Mixtures can be composed of elements +or other mixtures. For a mixture the user can specify composition either by +number of atoms or by fraction of mass. The materials sub-tree +in section~\ref{sec:compact-xml-structure} +shows the representation of an element, a simple material and a +composite material in the XML format identical to GDML~\cite{bib:GDML}. +The snippet below shows how to define new material instances: +\begin{code} +<materials> + ... + <!-- (1) The description of an atomic element or isotope --> + <element Z="30" formula="Zn" name="Zn" > + <atom type="A" unit="g/mol" value="65.3955" /> + </element> + <!-- (2) A composite material --> + <material name="Kapton"> + <D value="1.43" unit="g/cm3" /> + <composite n="22" ref="C"/> + <composite n="10" ref="H" /> + <composite n="2" ref="N" /> + <composite n="5" ref="O" /> + </material> + <!-- (3) A material mixture --> + <material name="PyrexGlass"> + <D type="density" value="2.23" unit="g/cm3"/> + <fraction n="0.806" ref="SiliconOxide"/> + <fraction n="0.130" ref="BoronOxide"/> + <fraction n="0.040" ref="SodiumOxide"/> + <fraction n="0.023" ref="AluminumOxide"/> + </material> + ... +</materials> +\end{code} +The $\tt<materials>$ sub-tree contains additional materials, which +are not contained in the default materials tables. The snippet above shows +different kinds of materials: +\begin{description} +\item{(1)} Atomic elements as they are in the periodic table. The number of elements + is finite. It is unlikely any client will have to extend the known elements. +\item{(2)} Composite materials, which consists of one or several elements + forming a molecule. These materials have a certain density under normal + conditions described in the child element \tw{D}. + For each \tw{composite} the attribute \tw{ref} denotes the element type by name, + the attribute \tw{n} denotes the atomic multiplicity. + Typically each of the elements in (1) also forms such a material representing + objects which consist of pure material like e.g. iron magnet yokes or copper wires. +\item{(3)} Last there are mixtures of composite materials to describe + for example alloys, solutions or other mixtures of solid materials. + This is the type of material used to actually create mechanical structures + forming the assembly of an experiment. Depending on the maufactering + these materials have a certain density (\tw{D}) and are composed + of numerous molecules contributing to the resulting material with a given + \tw{fraction}. The sum of all fractions (attribute \tw{n}) is 1.0. +\end{description} +"Real" materials i.e. those you can actually touch are described in TGeo +by the class \tgeo{TGeoMedium}{\tt{TGeoMedium}} +\footnote{Typical beginner's mistake: Do not mix up the +two classes \tw{TGeoMaterial} and \tw{TGeoMedium}! +The material to define volumes is of type \tw{TGeoMedium}, which also includes the +description of the material's finish.}. +Materials are not constructed by any client. Materials and elements are +either already present in the the corresponding tables of the ROOT geometry +package or they are added during the interpretation of the XML input. +Clients access the description of material using the \tw{LCDD} interface. + + +\newpage +\begin{figure}[t] + \begin{center} + \includegraphics[width=160mm] {DD4hep-solids.png} + \caption{Extensions may be attached to common Detector Elements which + extend the functionality of the common DetElement + class and support e.g. caching of precomputed values.} + \label{fig:dd4hep-solids} + \end{center} + \vspace{-0.6cm} +\end{figure} +%============================================================================= +\subsection{Shapes} +\label{dd4hep-basic-shapes} +%============================================================================= +\noindent +Shapes are abstract objects with a bounding surface and fixed dimensions. +There are primitive, atomic shapes +and complex boolean shapes as shown in Figure~\ref{fig:dd4hep-solids}. +TGeo and similarly Geant4 offer a whole palette of +primitive shapes, which can be used to construct more complex shapes: +\begin{itemize}\itemcompact +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_box.html}{Box} shape + represented by the \tgeo{TGeoBBox}{\tt TGeoBBox} class. To create a new box + object call one of the following constructors: +\begin{code} +/// Constructor to be used when creating an anonymous new box object +Box(double x, double y, double z); +/// Constructor to be used when creating an anonymous new box object +template<typename X, typename Y, typename Z> Box(const X& x, const Y& y, const Z& z); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_sphere.html}{Sphere} shape + represented by the \tgeo{TGeoSphere}{\tt TGeoSphere} class. To create a new sphere + object call one of the following constructors: +\begin{code} +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_cone.html}{Cone} shape + represented by the \tgeo{TGeoCone}{\tt TGeoCone} class. To create a new cone + object call one of the following constructors: +\begin{code} +/// Constructor to create a new anonymous object with attribute initialization +Cone(double z,double rmin1,double rmax1,double rmin2,double rmax2); +template<typename Z, typename RMIN1, typename RMAX1, typename RMIN2, typename RMAX2> +Cone(const Z& z, const RMIN1& rmin1, const RMAX1& rmax1, const RMIN2& rmin2, const RMAX2& rmax2); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_cone_segment.html}{Cone segment} shape + represented by the \tgeo{TGeoConeSeg}{\tt TGeoConeSeg} class. To create a new cone segment + object call one of the following constructors: +\begin{code} +/// Constructor to create a new ConeSegment +ConeSegment(double dz, double rmin1, double rmax1, double rmin2, double rmax2, + double phi1=0.0, double phi2=2.0*M_PI); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_polycone.html}{Polycone} shape + represented by the \tgeo{TGeoPcon}{\tt TGeoPcon} class. To create a new polycone + object call one of the following constructors: +\begin{code} +/// Constructor to create a new polycone object +Polycone(double start, double delta); +followed by a call to: +void addZPlanes(const std::vector<double>& rmin, + const std::vector<double>& rmax, + const std::vector<double>& z); +/// Constructor to create a new polycone object. Add at the same time all Z planes +Polycone(double start, double delta, + const std::vector<double>& rmin, + const std::vector<double>& rmax, + const std::vector<double>& z); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_tube.html}{Tube segment} shape + represented by the \tgeo{TGeoTubeSeg}{\tt TGeoTubeSeg} class. To create a new tube segment + object call one of the following constructors: +\begin{code} +Tube(double rmin, double rmax, double z, double deltaPhi=2*M_PI) +Tube(double rmin, double rmax, double z, double startPhi, double deltaPhi) + +template<typename RMIN, typename RMAX, typename Z, typename DELTAPHI> +Tube(const RMIN& rmin, const RMAX& rmax, const Z& z, const DELTAPHI& deltaPhi) + +template<typename RMIN, typename RMAX, typename Z, typename STARTPHI, typename DELTAPHI> +Tube(const std::string& name, const RMIN& rmin, const RMAX& rmax, const Z& z, + const STARTPHI& startPhi, const DELTAPHI& deltaPhi) +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_trapezoid.html}{Trapezoid} shape + represented by the \tgeo{TGeoTrd2}{\tt TGeoTrd} class. To create a new trapezoid + object call one of the following constructors: +\begin{code} +/// Constructor to create a new anonymous object with attribute initialization +Trapezoid(double x1, double x2, double y1, double y2, double z); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_trap.html}{Trap} shape + represented by the \tgeo{TGeoTrap}{\tt TGeoTrap} class. To create a new trap + object call one of the following constructors: +\begin{code} +/// Constructor to create a new anonymous object with attribute initialization +Trap(double z,double theta,double phi, + double y1,double x1,double x2,double alpha1, + double y2,double x3,double x4,double alpha2); +/// Constructor to create a new anonymous object for right angular wedge from STEP (Se G4 manual for details) +Trap( double pz, double py, double px, double pLTX); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_torus.html}{Torus} shape + represented by the \tgeo{TGeoTorus}{\tt TGeoTorus} class. To create a new torus + object call one of the following constructors: +\begin{code} +/// Constructor to create a new anonymous object with attribute initialization +Torus(double r, double rmin, double rmax, double phi=M_PI, double delta_phi=2.*M_PI); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_paraboloid.html}{Paraboloid} shape + represented by the \tgeo{TGeoParaboloid}{\tt TGeoParaboloid} class. To create a new paraboloid + object call one of the following constructors: +\begin{code} +/// Constructor to create a new anonymous object with attribute initialization +Paraboloid(double r_low, double r_high, double delta_z); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_polyhedra_regular.html}{Regular Polyhedron} shape + represented by the \tgeo{TGeoPgon}{\tt TGeoPgon} class. To create a new polyhedron + object call one of the following constructors: +\begin{code} +/// Constructor to create a new object. Phi(start)=0, deltaPhi=2PI, Z-planes at +-zlen/2 +PolyhedraRegular(int nsides, double rmin, double rmax, double zlen); +/// Constructor to create a new object. Phi(start)=0, deltaPhi=2PI, Z-planes at zplanes[0],[1] +PolyhedraRegular(int nsides, double rmin, double rmax, double zplanes[2]); +/// Constructor to create a new object with phi_start, deltaPhi=2PI, Z-planes at +-zlen/2 +PolyhedraRegular(int nsides, double phi_start, double rmin, double rmax, double zlen); +\end{code} +\end{itemize} + +\noindent +Besides the primitive shapes three types of boolean shapes (described in TGeo by the +\tgeo{TGeoCompositeShape}{{\tt{TGeoCompositeShape}}} class) +are supported: + +\begin{itemize}\itemcompact +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_union_solid.html}{\tt UnionSolid} objects representing the union, +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_intersection_solid.html}{\tt IntersectionSolid} objects representing the intersection, +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_subtraction_solid.html}{\tt SubtractionSolid} objects representing the subtraction, +\end{itemize} + +\noindent +of two other primitive or complex shapes. To build a boolean shape, the +second shape is transformed in 3-dimensional space before the boolean +operation is applied. The 3D transformations are described by objects from the +ROOT::Math library and are supplied at construction time. +Such a transformation as shown in the code snippet below may be + +\begin{itemize}\itemcompact +\item The identity transformation. Then no transformation object needs to be provided (see line 2). + +\item A translation only described by a \tw{Position} object (see line 4) + +\item A 3-fold rotation first around the Z-axis, then around the Y-axis and finally around the X-axis. + For transformation operations of this kind a \tw{RotationZYX} object must be supplied (see line 6). + +\item A generic 3D rotation matrix should be applied to the second shape. Then a \tw{Rotation3D} + object must be supplied (see line 8). + +\item Finally a generic 3D transformation (translation+rotation) may be applied using a + \tw{Transform3D} object (see line 10). +\end{itemize} + +\noindent +All three boolean shapes +have constructors as shown here for the UnionSolid: +\begin{code} + /// Constructor to create a new object. Position is identity, Rotation is identity-rotation! + UnionSolid(const Solid& shape1, const Solid& shape2); + /// Constructor to create a new object. Placement by position, Rotation is identity-rotation! + UnionSolid(const Solid& shape1, const Solid& shape2, const Position& pos); + /// Constructor to create a new object. Placement by a RotationZYX within the mother + UnionSolid(const Solid& shape1, const Solid& shape2, const RotationZYX& rot); + /// Constructor to create a new object. Placement by a generic rotoation within the mother + UnionSolid(const Solid& shape1, const Solid& shape2, const Rotation3D& rot); + /// Constructor to create a new object. Placement by a generic transformation within the mother + UnionSolid(const Solid& shape1, const Solid& shape2, const Transform3D& pos); +\end{code} + + +\newpage +%============================================================================= +\subsection{Volumes and Placements} +%============================================================================= +\noindent +The detector geometry is described by a hierarchy of volumes and their +corresponding placements. Both, the TGeo package and Geant4~\cite{bib:geant4} +are following effectively the same ideas ensuring an easy conversion from +TGeo to Geant4 objects for the simulation application. +\noindent +A volume is an unplaced solid de\-scribed in terms of a primitive +shape or a boolean operation of solids, a material and a number of +placed sub-volumes (placed volumes) inside. The class diagram showing the +relationships between volumes and placements, solids and materials is shown +in Figure~\ref{fig:dd4hep-detector-model}. +\noindent +It is worth noting, that any volume has children, but no parent or "mother" +volume. This is a direct consequence of the requirement to re-use volumes +and place the same volume arbitrarily often. Only the act of placing a volume +defines the relationship to the next level parent volume. +The resulting geometry tree is very effective, simple and convenient to +describe the detector geometry hierarchy starting from the top level volume +representing e.g. the experiment cavern down to the very detail of the detector +e.g. the small screw in the calorimeter. The top level volume is the very only +volume without a placement. All geometry calculations, computations are always +performed within the local coordinate system of the volume. +The following example code shows how to create +a volume which consists of a given material and with a shape. The created volume +is then placed inside the mother-volume using the local coordinate system of the +mother volume: + +\begin{code} + Volume mother = ....ampercent + + Material mat (lcdd.material("Iron")); + Tube tub (rmin, rmax, zhalf); + Volume vol (name, tub, mat); + Transform3D tr (RotationZYX(rotz,roty,rotx),Position(x,y,z)); + PlacedVolume phv = mother.placeVolume(vol,tr); +\end{code} + +\noindent +The volume has the shape of a tube and consists of iron. +Before being placed, the daughter volume is transformed within +the mother coordinate system according to the requested transformation. +The example also illustrates how to access $Material$ objects from the +$LCDD$ interface. + +\noindent +The {\tt{Volume}} class provides several possibilities to declare +the required space transformation necessary to place a daughter volume +within the mother: +\begin{itemize}\itemcompact +\item to place a daughter volume unrotated at the origin of the mother, the +transformation is the identity. Use the following call to place the daughter: +\begin{unnumberedcode} +PlacedVolume placeVolume(const Volume& vol) const; +\end{unnumberedcode} +\item If the positioning is described by a simple translation, use: +\begin{unnumberedcode} +PlacedVolume placeVolume(const Volume& vol, const Position& pos) coampercentnst; +\end{unnumberedcode} +\item In case the daughter should be rotated first around the Z-axis, + then around the Y-axis and finally around the X-axis place the daughter + using this call: +\begin{unnumberedcode} +PlacedVolume placeVolume(const Volume& vol, const RotationZYX& rot) const; +\end{unnumberedcode} +\item If the full 3-dimensional rotation matrix is known use: +\begin{unnumberedcode} +PlacedVolume placeVolume(const Volume& vol, const Rotation3D& rot) const; +\end{unnumberedcode} +\item for an entirely unconstrained placement place the daughter providing + a Transform3D object: +\begin{unnumberedcode} +PlacedVolume placeVolume(const Volume& volume, const Transform3D& tr) const; +\end{unnumberedcode} +\end{itemize} + +\noindent +For more details of the \tw{Volume} and the \tw{PlacedVolume} classes please see the +\detdesc{html/_volumes_8h.html}{header file}. + +\noindent +One volume like construct is special: the assembly constructs. +Assemblies are volumes without shapes. The "assembly" shape does not +own a own surface by itself, but rather defines it's surface and +bounding box from the contained children. +In this corner also the implementation concepts between TGeo and Geant4 diverge. +Whereas TGeo handles assemblies very similar to real volumes, in Geant4 +assemblies are purely artificial and disappear at the very moment volumes +are placed. + +\newpage +%============================================================================= +\subsection{Detector Elements} +\label{sec:dd4hep-user-manual-detector-elements} +%============================================================================= +\begin{figure}[b] + \begin{center} + \includegraphics[width=160mm] {DD4hep-detelement-drawing.png} + \caption{The basic layout of the \tw{DetElement} class aggregating + all data entities necessary to process data.} + \label{fig:dd4hep-user-manual-detelement-drawing} + \end{center} + \vspace{-0.6cm} +\end{figure} + +\noindent +Detector elements (class \tw{DetElement}) are entities which represent +subdetectors or sizable parts of a subdetector. +As shown in Figure~\ref{fig:dd4hep-user-manual-detelement-drawing}, +a \tw{DetElement} instance has the means to provide to clients information about + +\begin{itemize}\itemcompact +\item generic properties like the detector type or the path within the \tw{DetElement}s + hierarchy: +\begin{code} + /// Access detector type (structure, tracker, calorimeter, etc.). + std::string type() const; + /// Path of the detector element (not necessarily identical to placement path!) + std::string path() const; +\end{code} + +\item the detector hierarchy by exposing its children. The hierarchy may be + accessed with the following API: +\begin{code} + /// Add new child to the detector structure + DetElement& add(DetElement sub_element); + /// Access to the list of children + const Children& children() const; + /// Access to individual children by name + DetElement child(const std::string& name) const; + /// Access to the detector elements's parent + DetElement parent() const; +\end{code} + +\item its placement within the overall experiment if it represents an + entire subdetector or its placement with respect to its parent + if the \tw{DetElement} represents a part of a subdetector. + The placement path is the fully qualified path of placed volumes + from the top level volume to the placed detector element and may + serve as a shortcut for the alignment implementation: +\begin{code} + /// Access to the full path to the placed object + std::string placementPath() const; + /// Access to the physical volume of this detector element + PlacedVolume placement() const; + /// Access to the logical volume of the daughter placement + Volume volume() const; +\end{code} + +\item information about the environmental conditions etc. (\tw{conditons}): +\begin{code} + /// Access to the conditions information + Conditions conditions() const; +\end{code} + +\item alignment information: +\begin{code} + /// Access to the alignment information + Alignment alignment() const; +\end{code} + +\item convenience information such as cached transformations + to/from the top level volume, to/from the parent \tw{DetElement} + and to/from another \tw{DetElement} in the hierarchy above: +\begin{code} + /// Transformation from local coordinates of the placed volume to the world system + bool localToWorld(const Position& local, Position& global) const; + /// Transformation from world coordinates of the local placed volume coordinates + bool worldToLocal(const Position& global, Position& local) const; + + /// Transformation from local coordinates of the placed volume to the parent system + bool localToParent(const Position& local, Position& parent) const; + /// Transformation from world coordinates of the local placed volume coordinates + bool parentToLocal(const Position& parent, Position& local) const; + + /// Transformation from local coordinates of the placed volume to arbitrary parent system set as reference + bool localToReference(const Position& local, Position& reference) const; + /// Transformation from world coordinates of the local placed volume coordinates + bool referenceToLocal(const Position& reference, Position& local) const; + + /// Set detector element for reference transformations. + /// Will delete existing reference transformation. + DetElement& setReference(DetElement reference); +\end{code} + +\item User extension information as described in section~\ref{sec:dd4hep-user-manual-data-extensions}: +\begin{code} + /// Extend the detector element with an arbitrary structure accessible by the type + template <typename IFACE, typename CONCRETE> IFACE* addExtension(CONCRETE* c); + /// Access extension element by the type + template <class T> T* extension() const; +\end{code} + +\end{itemize} + + +\newpage +%============================================================================= +\subsection{Sensitive Detectors} +\label{sec:dd4hep-user-manual-sensitive-detectors} +%============================================================================= + +\noindent +Though the concept of sensitive detectors comes from Geant4 and simulation +activities, in DD4hep the sensitive detectors are the client interface to +access the readout description (class \tw{Readout}) with its +segmentation of sensitive elements (class \tw{Segmentation}) and +the description of hit decoders (class \tw{IDDescriptors}). +As shown in Figure~\ref{fig:dd4hep-sensitive-detectors}, these object +instances are required when reconstructing data from particle collisions. + +\noindent +Besides the access to data necessary for reconstruction the sensitive detector +also hosts Region setting (class \tw{Region} and sets of cut limits +(class \tw{LimitSets}) used to configure the Geant4 simulation toolkit. +The following code snippet shows the accessors of the +\tw{SensitiveDetector} class to obtain the corresponding +information~\footnote{The methods to set the data are not shown here.}: + + +\vspace{0.3cm} +\begin{code} + struct SensitiveDetector: public Ref_t { + /// Access the hits collection name + const std::string& hitsCollection() const; + /// Access readout structure of the sensitive detector + Readout readout() const; + /// Access to the region setting of the sensitive detector (not mandatory) + Region region() const; + /// Access to the limit set of the sensitive detector (not mandatory). + LimitSet limits() const; + + /// Extend the sensitive detector element with an arbitrary structure accessible by the type + template <typename IFACE, typename CONCRETE> IFACE* addExtension(CONCRETE* c); + /// Access extension element by the type + template <class T> T* extension() const; + }; +\end{code} + +\begin{figure}[h] + \begin{center} + \includegraphics[width=140mm] {DD4hep-sensitive-detectors.png} + \caption{The structure of DD4hep sensitive detectors.} + \label{fig:dd4hep-sensitive-detectors} + \end{center} + \vspace{-0.6cm} +\end{figure} + + +\noindent +Sensitive detector objects are automatically creating using the information +of the \tw{<readout>} section of the XML file if a subdetector is sensitive +and references a valid readout entry. +In the detector constructor (or any time later) clients +may add additional information to a sensitive detector object using +an extension mechanism similar to the extension mechanism for +detector elements mentioned earlier. + + +\noindent +Volumes may be shared and reused in several placements. In the parallel +hierarchy of detector elements as shown in Figure~\ref{fig:dd4hep-hierarchies}, +the detector elements may reference unambiguously the volumes of their +respective placements, but not the reverse. +However, the sensitive detector setup is a single instance per subdetector. +Hence it may be referenced by all sensitive Volumes of one subdetector. +In the following chapters the access to the readout structure is described. + +%============================================================================= +\subsection{Description of the Readout Structure} +\label{sec:dd4hep-manual-readout-description} +%============================================================================= +\noindent +The \tw{Readout} class describes the detailed structure of a sensitve volume. +The for example may be the layout of strips or pixels in a silicon detector +i.e. the description of entities which would not be modeled using individual +volumes and placements though this would theoretically feasible. +Each sensitive element is segmented according to the \tw{Segmentation} object +and hits resulting from energy depositions in the sensitive volume are +encoded using the \tw{IDDescriptor} object. + +\begin{figure}[h] + \begin{center} + \includegraphics[width=100mm] {DD4hep-readout.png} + \caption{The basic components to describe the \tw{Readout} structure + of a subdetector. } + \label{fig:dd4hep-sensitive-detectors} + \end{center} + \vspace{-0.6cm} +\end{figure} + +%============================================================================= +\subsubsection{CellID Descriptors} +\label{sec:dd4hep-manual-readout-iddescriptors} +%============================================================================= +\noindent +\tw{IDDescriptor}s define the encoding of sensitive volumes to uniquely identify +the location of the detector response. The encoding defines a bit-field with +the length of 64 bits. The first field is mandatory called \tw{system} and +identifies the subdetector. All other fields define the other volumes in the +hierarchy. The high bits are not necessarily mapped to small daughter volumes, +but may simply identify a logical segmentation such as the \tw{strip} \tw{number} +within a wafer of a vertex detector as shown in the following XML snippet: +\begin{code} +<readouts> + <readout name="SiVertexEndcapHits"> + <id>system:8,barrel:3,layer:4,module:14,sensor:2,side:32:-2,strip:24</id> + </readout> +<readouts> +\end{code} +These identifiers are the data input to +\tw{segmentation classes}~\ref{sec:dd4hep-manual-readout-segmentations}, +which define a user friendly API to en/decode the detector response. + +%============================================================================= +\subsubsection{Segmentations} +\label{sec:dd4hep-manual-readout-segmentations} +%============================================================================= +\noindent +Segementations define the user API to the low level interpretation of +the energy deposits in a subdetector. For technical reasons and partial +religious reasons are the segmentation implementation not part of the \DDhep +toolkit, but an independent package call +\tw{DDSegmentation}~\cite{bib:DDSegmentations}. Though the usage is an +integral part of DD4hep. + +\newpage +%============================================================================= +\subsection{Detector Constructors} +\label{sec:dd4hep-manual-detector-constructors} +%============================================================================= +\noindent +The creation of appropriate detector constructors is the main work of a client +defining his own detector. The detector constructor is a fragment of code in the +form of a routine, which return a handle to the created subdetector +\tw{DetElement} object. + +\noindent +Knowing that detector constructors are the main work items of clients significant +effort was put in place to ease and simplify this procedure as much as possible +in order to obtain readable, still compact code hopefully easy to maintain. +The interfaces to all objects, XML accessors, shapes, volumes etc. which were +discussed above were optimized to support this intention. + +\noindent +To illustrate the anatomy of such a constructor the following code originating +from an existing SiD detector concept will be analyzed. The example starts +with the XML input data. Further down this section the code is shown +with a detailed description of every relevant line. The object to be build is +a subdetector representing a layered calorimeter, +where each layer consists of a number of slices as shown in the XML snippet. +These layers are then repeated a number of times. + +\vspace{0.1cm} +\noindent +The XML snippet describing the subdetector properties: +\begin{code} + <detector id="13" name="LumiCal" reflect="true" type="CylindricalEndcapCalorimeter" + readout="LumiCalHits" vis="LumiCalVis" calorimeterType="LUMI"> + <comment>Luminosity Calorimeter</comment> + <dimensions inner_r = "LumiCal_rmin" inner_z = "LumiCal_zmin" outer_r = "LumiCal_rmax" /> + <layer repeat="20" > + <slice material = "TungstenDens24" thickness = "0.271*cm" /> + <slice material = "Silicon" thickness = "0.032*cm" sensitive = "yes" /> + <slice material = "Copper" thickness = "0.005*cm" /> + <slice material = "Kapton" thickness = "0.030*cm" /> + <slice material = "Air" thickness = "0.033*cm" /> + </layer> + <layer repeat="15" > + <slice material = "TungstenDens24" thickness = "0.543*cm" /> + <slice material = "Silicon" thickness = "0.032*cm" sensitive = "yes" /> + <slice material = "Copper" thickness = "0.005*cm" /> + <slice material = "Kapton" thickness = "0.030*cm" /> + <slice material = "Air" thickness = "0.033*cm" /> + </layer> + </detector> +\end{code} + +\vspace{0.1cm} +\noindent +The C++ code snippet interpreting the XML data and expanding the geometry: +\vspace{0.1cm} +\begin{code} +#include "DD4hep/DetFactoryHelper.h" +#include "XML/Layering.h" + +using namespace std; +using namespace DD4hep; +using namespace DD4hep::Geometry; + +static Ref_t create_detector(LCDD& lcdd, xml_h e, SensitiveDetector sens) { + xml_det_t x_det = e; + string det_name = x_det.nameStr(); + bool reflect = x_det.reflect(); + xml_dim_t dim = x_det.dimensions(); + double zmin = dim.inner_z(); + double rmin = dim.inner_r(); + double rmax = dim.outer_r(); + double totWidth = Layering(x_det).totalThickness(); + double z = zmin; + Material air = lcdd.air(); + Tube envelope (rmin,rmax,totWidth,0,2*M_PI); + Volume envelopeVol(det_name+"_envelope",envelope,air); + int layer_num = 1; + PlacedVolume pv; + + // Set attributes of slice + for(xml_coll_t c(x_det,_U(layer)); c; ++c) { + xml_comp_t x_layer = c; + double layerWidth = 0; + for(xml_coll_t l(x_layer,_U(slice)); l; ++l) + layerWidth += xml_comp_t(l).thickness(); + + for(int i=0, m=0, repeat=x_layer.repeat(); i<repeat; ++i, m=0) { + double zlayer = z; + string layer_name = det_name + _toString(layer_num,"_layer%d"); + Volume layer_vol(layer_name,Tube(rmin,rmax,layerWidth),air); + + for(xml_coll_t l(x_layer,_U(slice)); l; ++l, ++m) { + xml_comp_t x_slice = l; + double w = x_slice.thickness(); + string slice_name = layer_name + _toString(m+1,"slice%d"); + Material slice_mat = lcdd.material(x_slice.materialStr()); + Volume slice_vol (slice_name,Tube(rmin,rmax,w),slice_mat); + + if ( x_slice.isSensitive() ) { + sens.setType("calorimeter"); + slice_vol.setSensitiveDetector(sens); + } + slice_vol.setAttributes(lcdd,x_slice.regionStr(),x_slice.limitsStr(),x_slice.visStr()); + pv = layer_vol.placeVolume(slice_vol,Position(0,0,z-zlayer-layerWidth/2+w/2)); + pv.addPhysVolID("slice",m+1); + z += w; + } + layer_vol.setVisAttributes(lcdd,x_layer.visStr()); + Position layer_pos(0,0,zlayer-zmin-totWidth/2+layerWidth/2); + pv = envelopeVol.placeVolume(layer_vol,layer_pos); + pv.addPhysVolID("layer",layer_num); + ++layer_num; + } + } + // Set attributes of slice + envelopeVol.setAttributes(lcdd,x_det.regionStr(),x_det.limitsStr(),x_det.visStr()); + + DetElement sdet(det_name,x_det.id()); + Volume motherVol = lcdd.pickMotherVolume(sdet); + PlacedVolume phv = motherVol.placeVolume(envelopeVol,Position(0,0,zmin+totWidth/2)); + phv.addPhysVolID("system",sdet.id()) + .addPhysVolID("barrel",1); + sdet.setPlacement(phv); + if ( reflect ) { + phv=motherVol.placeVolume(envelopeVol,Transform3D(RotationZ(M_PI),Position(0,0,-zmin-totWidth/2))); + phv.addPhysVolID("system",sdet.id()) + .addPhysVolID("barrel",2); + } + return sdet; +} + +DECLARE_DETELEMENT(CylindricalEndcapCalorimeter,create_detector); +\end{code} + +\newpage +\noindent +\begin{tabular} {l||p{0cm}} +\docline{Line}{} +\docline{1}{The include file DetFactoryHelper.h includes all + utilities to extract XML information together with the appropriate type + definition.} +\docline{4-6}{Convenience shortcut to save ourself a lot of typing.} +\docline{8}{The entry point to the detector constructor. This routine shall + be called by the plugin mechanism.} +\docline{9}{The functionality of the raw XML handle \tw{xml\_h} is rather + limited. A simple assignment to a XML detector object gives us all the + functionality we need.} +\docline{10,11}{Extracting the sub-detector name and properties from the xml handle.} +\docline{12-17}{Access the $dimension$ child-element from the XML subtree, access the element's + attributes and precompute values used later.} +\docline{18}{Retrieve a reference to the "air" material from LCDD.} +\docline{19-20}{Construct the envelope volume shaped as a tube made out of air.} +\docline{25}{Now the detector can be built: We loop over all layers types and over + each layer type as often as necessary (attribute: repeat). + The XML collection object will return all child elements of \tw{x\_det} + with a tag-name "layer". } +\docline{25}{Note the macro $\tt{\_U(layer)}$: When using Xerces-C as an XML parser, + it will expand to the reference to an object containing the unicode value + of the string "layer". The full list of predefined tag names can be found in the + include file \detdesc{html/_unicode_values_8h.html}{DD4hep/UnicodeValues.h}. + If a user tag is not part in the precompiled tag list, the corresponding Unicode + string may be created with the macro \tw{\_Unicode(layer)} or \tw{Unicode("layer")}. + } +\docline{26}{Convenience assignment to extract attributes of the layer element.} +\docline{27-29}{Compute total layer width.} +\docline{31}{Create \tw{repeat} number of layers of the same type.} +\docline{32-34}{Create the named envelope volume with a tube shape + containing all slices of this layer.} +\docline{36-51}{Create the different layer-slices with a tube shape and the + corresponding material as indicated in the XML data.} +\docline{43-46}{If the slice is sensitive i.e. is instrumented and supposed to + deliver signals from particle passing, the sensitive detector component of this + detector needs to be attached to the slice.} +\docline{47}{Set visualization and geant4 attributes to the slice volume. + If the attributes are not present, they will be ignored.} +\docline{48}{Now the created slice volume will be placed inside the mother, + the layer envelope at the correct position. This operation results + in the creation of a \tw{PlacedVolume}.} +\docline{49}{It identify uniquely every slice within the layer an identifier + (here the number of the created slice) is attached. This identifier + must be present in the + bitmap defined by the \tw{IDDescriptor} of this subdetector.} +\docline{52-55}{Same as 47-49, but now the created layer volume is placed + in the envelope of the entire subdetector.} +\docline{60}{Set envelope attributes.} +\docline{62}{Construct the main detector element of this subdetector. + This will be the unique entry point to access any information of the subdetector.\\ + {\bf{Note:}} the subdetector my consist of a hierarchy of detector elements. + For example each layer could be described by it's own \tw{DetElement} and all + layer-\tw{DetElement} instances being children of the subdetector instance. + } +\docline{63-64}{Place the subdetector envelope into its mother + (typically the top level (world) volume).} +\docline{65-66}{Add the missing \tw{IDDescriptor} identifiers to complete the bitmap.} +\docline{67}{Store the placement in the subdetector detector + element in order to make it availible to later clients of this \tw{DetElement}.} +\end{tabular} +\newpage +\begin{tabular} {l||p{0cm}} +\docline{Line}{} +\docline{68-72}{Endcap calorimeters typically are symmetric i.e. an + endcap is located on each side of the barrel. To easy such + reflections the entire endcap structure + can be copied and placed again. } +\docline{73}{All done. Return the created subdetector element to the caller for registration.} +\docline{76}{{\bf Very important:}Without the registration of the construction + function to the framework, the corresponding plugin will not be found. + The macro has two arguments: firstly the plugin name which is identical to the + detector type in the XML snippet and secondly the function to be called + at construction time.} +\end{tabular} + +%============================================================================= +\subsection{Tools} +\subsubsection{Volume Manager} +%============================================================================= +\noindent +The \tw{VolumeManager} is a tool to seek a lookup table of placements of +sensitive volumes and their corresponding unique volume identifier, the +\tw{cellID}. The volume manager analyzes - once the geometry is closed - +the hierarchical tree and stores the various placements in the hierarchy +with respect to their identifiers. In other words the the tree is +reused volumes shown e.g. in Figure~\ref{fig:dd4hep-hierarchies} is +degenerated according to the full pathes of the various volumes. This +use case is very common to reconstruction and analysis applications +whenever a given raw-data (aka "hit") element must be related to its +geometrical location. + +\noindent +Figure~\ref{fig:dd4hep-user-manual-volmgr} shows the design diagram of this component: +\begin{figure}[h] + \begin{center} + \includegraphics[width=170mm] {DD4hep-volmgr.png} + \caption{Extensions may be attached to common Detector Elements which + extend the functionality of the common DetElement + class and support e.g. caching of precomputed values.} + \label{fig:dd4hep-user-manual-volmgr} + \end{center} +\end{figure} + +\noindent +To optimize the access of complex subdetector structures, is the volume-identifier +map split and the volumes of each each subdetector is stored in a separate map. +This optimization however is transparent to clients. The following code extract +from the header files lists the main client routines to extract volume information +given a known cellID: +\begin{code} + /// Lookup the context, which belongs to a registered physical volume. + Context* lookupContext(VolumeID volume_id) const; + /// Lookup a physical (placed) volume identified by its 64 bit hit ID + PlacedVolume lookupPlacement(VolumeID volume_id) const; + /// Lookup a top level subdetector detector element + /// according to a contained 64 bit hit ID + DetElement lookupDetector(VolumeID volume_id) const; + /// Lookup the closest subdetector detector element in the hierarchy + /// according to a contained 64 bit hit ID + DetElement lookupDetElement(VolumeID volume_id) const; + /// Access the transformation of a physical volume to the world coordinate system + const TGeoMatrix& worldTransformation(VolumeID volume_id) const; +\end{code} + +%============================================================================= +\subsubsection{Geometry Visualization} +\label{sec:dd4hep-manual-geometry-visualization} +%============================================================================= +\noindent +Visualizing the geometry is an important tool to debug and validate +the constructed detector. +Since \DDhep uses the \tw{ROOT} geometry package, all visualization tools +from ROOT are automatically supported. This is in the first place the +OpenGL canvas of \tw{ROOT} and all elaborated derivatives thereof such as +event displays etc. Figure~\ref{fig:dd4hep-user-manual-visualization-subdetector} +shows as an example the subdetector example from the \tw{SiD} detector design +discussed in section~\ref{sec:dd4hep-manual-detector-constructors}. +\begin{figure}[h] + \begin{center} + \begin{tabular}{l r} + \includegraphics[width=80mm] {DD4hep-Lumical.png} & + \includegraphics[width=80mm] {DD4hep-Lumical-detailed.png} \\ + \end{tabular} + \caption{Geometry visualization using the ROOT OpenGL plugin. + To the left the entire luminosity calorimeter is shown, + at the right the detailed zoomed view with clipping to + access the internal layer and slice structure.} + \label{fig:dd4hep-user-manual-visualization-subdetector} + \end{center} +\end{figure} + +\noindent +The command to create the display is part of the DD4hep release: +\begin{code} +$> geoDisplay -compact <path to the XML file containing the detector description> + + +geoDisplay -opt [-opt] + -compact <file> Specify the compact geometry file + [REQUIRED] At least one compact geo file is required! + -load_only [OPTIONAL] Dry-run to only load geometry without + starting the dispay. +\end{code} + +%============================================================================= +\subsubsection{Geometry Conversion} +\label{sec:dd4hep-manual-geometry-conversion} +%============================================================================= +\noindent +\tw{ROOT} \tw{TGeo} is only one representation of a detector geometry. +Other applications may require other representation. In particular two other +are worth mentioning: +\begin{itemize}\itemcompact +\item \tw{LCDD}~\cite{bib:LCDD} the geometry representation used to + simulate the ILC detector design with the \tw{slic} application. +\item \tw{GDML}~\cite{bib:GDML} a geometry markup language understood + by Geant4 and \tw{ROOT}. +\end{itemize} +Both conversions are supported in \DDhep with the geoConverter application: +\begin{code} + geoConverter -opt [-opt] + Action flags: Usage is exclusive, 1 required! + -compact2lcdd Convert compact xml geometry to lcdd. + -compact2gdml Convert compact xml geometry to gdml. + -compact2vis Convert compact xml to visualisation attrs + + -input <file> [REQUIRED] Specify input file. + -output <file> [OPTIONAL] Specify output file. + if no output file is specified, the output + device is stdout. + -ascii [OPTIONAL] Dump visualisation attrs in csv format. + [Only valid for -compact2vis] +\end{code} + +%============================================================================= +\newpage +\begin{thebibliography}{9} +\input{DD4hep-bibliography.tex} +\bibitem{bib:DDSegmentations} C.Grefe et al., + "The DDSegmentation package", + Non existing documentation to be written. +\end{thebibliography} +%============================================================================= +\end{document} diff --git a/doc/LaTex/DD4hepManual.tex b/doc/LaTex/DD4hepManual.tex new file mode 100644 index 0000000000000000000000000000000000000000..55ba58a60388bf110217018dcb4587af732811a8 --- /dev/null +++ b/doc/LaTex/DD4hepManual.tex @@ -0,0 +1,1831 @@ +%============================================================================= +\documentclass[10pt,a4paper]{article} +% +\input{DD4hep-setup.tex} +% +\pagestyle{fancyplain}{\fancyfoot[C]{\sffamily{DD4hep User Manual}}} +% +% +\begin{document} +% +\mytitle{ +DD4hep +}{ +A Detector Description Toolkit\\ +for High Energy Physics\\ +\vspace{0.3cm} +Experiments +} +% +% +%== Abstract =============================================================== +\pagestyle{plain} +\pagenumbering{Roman} +\setcounter{page}{1} + +\begin{abstract} +\normalsize +\input{DD4hep-abstract.tex} +\end{abstract} + +\vspace{8cm} + +\begin{center} +{\large{\bf{ +\begin{tabular} {| l | l | l |} +\hline +\multicolumn{3}{| c |}{} \\[0.2cm] +\multicolumn{3}{| c |}{Document History} \\[0.2cm] +\multicolumn{3}{| c |}{} \\[0.2cm] +\hline + & & \\ +Document & & \\ +version & Date & Author \\[0.2cm] \hline + & & \\ +1.0 & 19/11/2013 & Markus Frank CERN/LHCb \\ + & & \\ \hline +\end{tabular} +}}} +\end{center} + +\clearpage +% +% +%== TOC ==================================================================== +\tableofcontents +\clearpage +% +% +%== Introduction =========================================================== +\pagenumbering{arabic} +\setcounter{page}{1} +\input{DD4hep-Overview.tex} +% +\newpage +%============================================================================= +% Manual +%============================================================================= +\section{User Manual} +\label{sec:dd4hep-user-manual} +%============================================================================= +\noindent +This chapter describes how supply a physics application developed with all the +information related to the detector which is necessary to process data from +particle collisions and to qualify the detecting apparatus in order to +interpret these event data. + +\noindent +The clients of the detector description are the algorithms residing in the +event processing framework that need this information in order to perform +their job (reconstruction, simulation, etc.). +The detector description provided by \DDhep is a framework for developers +to provide the specific detector information to algorithms. + +\noindent +In the following sections an overview is given over the various independent +elements of DD4hep followed by the discussion of an example which leads to +the description of a detector when combining these elements. +This includes a discussion of the features of the \DDhep detector description +and of its structure. + +%============================================================================= +\subsection{Building DD4hep} +\label{sec:dd4hep-user-manual-building} +%============================================================================= + +\noindent +The \DDhep source code is freely available. See the +\detdesc{doc/LICENSE}{licence conditions}. +Please read the \detdesc{doc/release.notes}{Release Notes} +before downloading or using this release. + +\noindent +The \DDhep project consists of several packages. The idea +has been to separate the common parts of +the detector description toolkit from concrete detector examples. + +\noindent +The package {\tw{DDCore}} contains the definition of the basic classes +of the toolkit: \tw{Handle}, \tw{DetElement}, \tw{Volume}, \tw{PlacedVolume}, +\tw{Shapes}, \tw{Material}, etc. Most of these classes are \tw{handles} +to ROOT's TGeom classes. + +%============================================================================= +\subsubsection{Supported Platforms} +\label{sec:dd4hep-user-manual-platforms} +%============================================================================= +\noindent +Supported platforms for DD4hep are the CERN Linux operating systems: +\begin{itemize} +\item \tw{Scientic Linux CERN 6} +\item \tw{Scientic Linux CERN 7} - once approved. +\end{itemize} +Support for any other platform will well be taken into account, but can only +be actively supported by users who submit the necessary patches. + +%============================================================================= +\subsubsection{Prerequisites} +\label{sec:dd4hep-user-manual-prerequisites} +%============================================================================= +\noindent +DD4hep depends on a number of ‘external’ packages. +The user will need to install these in his/her +system before building and running the examples +\begin{itemize}\itemcompact +\item Mandatory are recent \tw{CMake} (version 2.8 or higher) and +\item \tw{ROOT} (version 5.34 or higher) installations. +\item If the \tw{Xerces-C} is used to parse compact descriptions and + installation of {Xerces-C} will be required. +\item To build \DDG it is useful to have an installation of the Boost + header files. +\item To build and run the simulation examples \tw{Geant4} will be required. +\end{itemize} + +\newpage +%============================================================================= +\subsubsection{CMake Build Options for DD4hep} +\label{sec:dd4hep-user-manual-building} +%============================================================================= +\noindent +The package provides the basic mechanisms for constructing the +{\it{Generic Detector Description Model}} in memory from XML compact detector +definition files. Two methods are currently supported: one based +on the C++ \tw{Xerces}-C parser, and another one based on Python and using the +\tw{PyROOT} bindings to ROOT~\footnote{I will not continue +the support using PyROOT. \\ +If there is a desire that it stays alive +someone else should take care -- M.Frank}. +\tw{PyROOT} may be enabled using the switch: + +\begin{unnumberedcode} + -DD4HEP_USE_PYROOT:BOOL +\end{unnumberedcode} + +\noindent +The XML parsing method is enabled by default using the \tw{TiXML} parser. Optionally +instead of \tw{TiXML} the \tw{Xerces}-C parser may be chosen by setting the +two configuration options appropriately: + +\begin{unnumberedcode} + -DD4HEP_USE_XERCESC:BOOL + -DXERCESC_ROOT_DIR=<path to Xerces-C-installation-directory> +\end{unnumberedcode} + +\noindent +{\bf{DDG4}} is the package that contains the conversion of \DDhep geometry +into Geant4 geometry to be used for simulation. +The option \tw{DD4HEP\_WITH\_GEANT4:BOOL} controls the building or not of +this package that has the dependency to Geant4. The Geant4 installation +needs to be located using the variable: + +\begin{unnumberedcode} + -DDD4HEP_WITH_GEANT4=on -D + -DGeant4_DIR=<path to Geant4Config.cmake> +\end{unnumberedcode} + +\noindent +To properly handle component properties using \tw{boost::spirit}, +access to the Boost header files must be provided. +\vspace{0.3cm} +\begin{unnumberedcode} + -DDD4HEP_USE_BOOST=ON + -DBOOST_INCLUDE_DIR=<path to the boost include directory> +\end{unnumberedcode} + +\noindent +Other useful build options: +\begin{itemize} +\item build doxygen documentation ( after 'install' open ./doc/html/index.html) +\begin{unnumberedcode} + -D INSTALL_DOC=on +\end{unnumberedcode} + +\item {\bf{note:}} you might have to update your environment beforehand to have all needed + libraries in the shared lib search path (this will vary with OS, shell, etc.) e.g +\begin{unnumberedcode} + . /data/ilcsoft/geant4/9.5/bin/geant4.sh + export CLHEP_BASE_DIR="/data/ilcsoft/HEAD/CLHEP/2.1.0.1" + export CLHEP_INCLUDE_DIR="$CLHEP_BASE_DIR/include" + export PATH="$CLHEP_BASE_DIR/bin:$PATH" + export LD_LIBRARY_PATH="$CLHEP_BASE_DIR/lib:$LD_LIBRARY_PATH" +\end{unnumberedcode} +\end{itemize} + +%============================================================================= +\subsubsection{Build From Source} +\label{sec:dd4hep-user-manual-building-from-source} +%============================================================================= +\noindent +The following steps are necessary to build \DDhep: +\begin{itemize} +\item Set the environment, at least ROOT needs to be initialized, e.g. + \begin{unnumberedcode} + source /data/ilcsoft/root/5.34.03/bin/thisroot.sh + \end{unnumberedcode} + \vspace{-0.6cm} + (the bare minimum is: \tw{export ROOTSYS=<path to root installation>}). + +\item First checkout code from the repository: + \begin{unnumberedcode} + svn co https://svnsrv.desy.de/public/aidasoft/DD4hep/trunk DD4hep + \end{unnumberedcode} + \vspace{-0.6cm} + +\item We refer to the directory \DDhep as the source directory. The +next step is to create a directory in which to configure and run the build +and store the build products. This directory should not be the same as, or +inside, the source directory. In this guide, we create this build directory +alongside our source directory: + \begin{unnumberedcode} + mkdir build + cd build + cmake -DCMAKE_INSTALL_PREFIX=<dd4hep-install-pasth> <CMake-options> ../DD4hep + make -j 4 + make install + \end{unnumberedcode} +\end{itemize} +The CMake Variable \tw{CMAKE\_INSTALL\_PREFIX} is used to set the install directory, +the directory under which the \DDhep libraries, headers and support files +will be installed. + +%============================================================================= +\subsubsection{Tutorial} +\label{sec:dd4hep-user-manual-tutorial} +%============================================================================= +\noindent +In January 2013 an introductory tutorial was given at CERN to members of the +linear collider community. The slides to the tutorial can be found +\detdesc{doc/DD4hep_Tutorial.pdf}{here}. +The tutorial is not entirely up to date. Please take the content with a +grain of salt. + +%============================================================================= +\subsubsection{Doxygen Code Documentation} +\label{sec:dd4hep-user-manual-doxygen} +%============================================================================= +\noindent +The \DDhep source code is instrumented with tags understood by doxygen. +The generated code documentation can be found +\detdesc{html/index.html}{here}. + +%============================================================================= +\subsubsection{Remarks} +\label{sec:dd4hep-user-manual-remarks} +%============================================================================= +\noindent +The main reference is the doxygen information of \DDhep and the ROOT documentation. +Please refer to these sources for a detailed view of the capabilities of +each component and/or its handle. +For coherence reasons, the description of the +interfaces is limited to examples which illustrate the usage of the basic +components. + +%============================================================================= +\subsubsection{Caveat} +\label{sec:dd4hep-user-manual-caveat} +%============================================================================= +\noindent +The atomic units in of Geant4 are (millimeter, nanosecond and MeV and radians). +The atomic units of ROOT-TGeo are (centimeter, seconds, GeV and degrees). +Unfortunately the authors could not agree on a common system of units +and mixing the two can easily result in a chaos. +Users must be aware of this fact. + + +\newpage +%============================================================================= +\subsection{DD4hep Handles} +\label{sec:dd4hep-user-manual-handles} +%============================================================================= +\noindent +Handles are the means of clients accessing \DDhep detector description data. +The data itself is not held by the handle itself, the handle only allows the +access to the data typically held by a pointer. The template handle class +(see for details the \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_handle.html}{header file}). +allows type safe assignment of other unrelated handles and supports standard +data conversions to the underlying object in form of the raw pointer, +a reference etc. The template handle class: + +\begin{code} +template <typename T> struct Handle { + typedef T Implementation; + typedef Handle<Implementation> handle_t; + T* m_element; + Handle() : m_element(0) { } + Handle(T* e) : m_element(e) { } + Handle(const Handle<T>& e) : m_element(e.m_element) { } + template<typename Q> Handle(Q* e) + : m_element((T*)e) { verifyObject(); } + template<typename Q> Handle(const Handle<Q>& e) + : m_element((T*)e.m_element) { verifyObject(); } + Handle<T>& operator=(const Handle<T>& e) { m_element=e.m_element; return *this;} + bool isValid() const { return 0 != m_element; } + bool operator!() const { return 0 == m_element; } + void clear() { m_element = 0; } + T* operator->() const { return m_element; } + operator T& () const { return *m_element; } + T& operator*() const { return *m_element; } + T* ptr() const { return m_element; } + template <typename Q> Q* _ptr() const { return (Q*)m_element; } + template <typename Q> Q* data() const { return (Q*)m_element; } + template <typename Q> Q& object() const { return *(Q*)m_element; } + const char* name() const; +}; +\end{code} + +\noindent +effectively works like a pointer with additional object validation during assignment +and construction. Handles support direct access to the held object: either by using +the + +\begin{verbatim} + operator->() (See line 16 above) +\end{verbatim} + +\noindent +or the automatic type conversions: + +\begin{verbatim} + operator T& () const (See line 17-18 above) + T& operator*() const. +\end{verbatim} + +\noindent +All entities of the \DDhep detector description are exposed as handles - +raw pointers should not occur in the code. +The handles to these objects serve two purposes: +\begin{itemize}\itemcompact +\item Hold a pointer to the object and extend the functionality of a raw + pointer. +\item Enable the creation of new objects using specialized constructors + within sub-classes. To ensure memory integrity and avoid resource + leaks these created objects should always be stored in the + detector description data hub $LCDD$ described in + section~\ref{sec:dd4hep-user-manual-LCDD-hub}. +\end{itemize} + +\newpage +%============================================================================= +\subsection{The Data Extension Mechanism} +\label{sec:dd4hep-user-manual-data-extensions} +%============================================================================= +\noindent +Data extensions are client defined C++ objects aggregated to basic \DDhep objects. +The need to introduce such data extensions results from the simple fact that +no data structure can be defined without the iterative need in the long term +to extend it leading to implementations, which can only satisfy a subset of +possible clients. To accomplish for this fact a mechanism was put in place +which allows any user to attach any supplementary information provided +the information is embedded in a polymorph object with an accessible destructor. +There is one limitation though: object extension must differ by their +interface type. +There may not be two objects attached with the identical interface type. +The actual implemented sub-type of the extension is not relevant. +Separating the interface type from the implementation type keeps client +code still functional even if the implementation of the extension changes +or is a plug-able component. + +\noindent +The following code snippet shows the extension interface: + +\begin{code} + /// Extend the object with an arbitrary structure accessible by the type + template <typename IFACE, typename CONCRETE> IFACE* addExtension(CONCRETE* c); + /// Access extension element by the type + template <class T> T* extension() const; +\end{code} + +Assuming a client class of the following structure: +\begin{code} + class ExtensionInterface { + virtual ~ExtensionInterface(); + virtual void foo() = 0; + }; + + class ExtensionImplementation : public ExtensionInterface { + ExtensionImplementation(); + virtual ~ExtensionImplementation(); + virtual void foo(); + }; +\end{code} +is then attached to an extensible object as follows: +\begin{code} + ExtensionImplementation* ptr = new ExtensionImplementation(); + ... fill the ExtensionImplementation instance with data ... + module.addExtension<ExtensionInterface>(ptr); +\end{code} +The data extension may then be retrieved whenever the instance of the +extensible object "module" is accessible: +\begin{code} + ExtensionInterface* ptr = module.extension<ExtensionInterface>(); +\end{code} +The lookup mechanism is rather efficient. Though it is advisable to +cache the pointer withing the client code if the usage is very frequent. + + +\noindent +There are currently three object types present which support this mechanism: +\begin{itemize}\itemcompact +\item the central object of \DDhep, the \tw{LCDD} class discussed in + section~\ref{sec:dd4hep-user-manual-LCDD-hub}. +\item the object describing subdetectors or parts thereof, the + \tw{DetElement} class discussed in + section~\ref{sec:dd4hep-user-manual-detector-elements}. + Detector element extensions in addition require the presence + of a copy constructor to support e.g. reflection operations. + Without a copy mechanism detector element hierarchies could + cloned. +\item the object describing sensitive detectors, + the \tw{SensitiveDetector} class discussed in + section~\ref{sec:dd4hep-user-manual-sensitive-detectors}. +\end{itemize} + + +\newpage +%============================================================================= +\subsection{XML Tools and Interfaces} +\label{sec:dd4hep-user-manual-xml-tools} +%============================================================================= +\noindent +Using native tools to interpret XML structures is rather tedious and lengthy. +To easy the access to XML data considerable effort was put in place to easy +the life of clients as much as possible using predefined constructs to +access XML attributes, elements or element collections. + +\noindent +The functionality of the XML tools is perhaps best shown with a small example. +Imagine to extract the data from an XML snippet like the following: +\begin{code} + <detector name="Sometthing"> + <tubs rmin="BP_radius - BP_thickness" rmax="BP_radius" zhalf="Endcap_zmax/2.0"/> + <position x="0" y="0" z="Endcap_zmax/2.0" /> + <rotation x="0.0" y="CrossingAngle/2.0" z="0.0" /> + <layer id="1" inner_r="Barrel_r1" + outer_r="Barrel_r1 + 0.02*cm" inner_z="Barrel_zmax + 0.1*cm"> + <slice material = "G10" thickness ="0.5*cm"/> + </layer> + <layer id="2" inner_r="Barrel_r2" + outer_r="Barrel_r2 + 0.02*cm" inner_z="Barrel_zmax + 0.1*cm"> + <slice material = "G10" thickness ="0.5*cm"/> + </layer> + .... + </detector> +\end{code} + +The variable names used in the XML snippet are evaluated when interpreted. +Unless the attributes are accessed as strings, the client never sees the +strings, but only the evaluated numbers. +The anatomy of the C++ code snippets to interpret such a data section +looks very similar: +\begin{code} + static void some_xml_handler(xml_h e) { + xml_det_t x_det (e); + xml_comp_t x_tube = x_det.tubs(); + xml_dim_t pos = x_det.position(); + xml_dim_t rot = x_det.rotation(); + string name = x_det.nameStr(); + + for(xml_coll_t i(x_det,_U(layer)); i; ++i) { + xml_comp_t x_layer = i; + double zmin = x_layer.inner_z(); + double rmin = x_layer.inner_r(); + double rmax = x_layer.outer_r(); + double layerWidh = 0; + + for(xml_coll_t j(x_layer,_U(slice)); j; ++j) { + double thickness = xml_comp_t(j).thickness(); + layerWidth += thickness; + } + } + } +\end{code} +In the above code snippet an XML (sub-)tree is passed to the executing +function as a handle to an XML element ({\tt{xml\_h}}). Such handles may seamlessly be +assigned to any supporting helper class inheriting from the +class {\tt{XML::Element}}, which encapsulates the functionality required to +interpret the XML structures. +Effectively the various XML attributes and child nodes +are accessed using functions with the same +name from a convenience handle. +In lines 3-5 child nodes are extracted, lines 10-12,16 access element attributes. +Element collections with the same tag names \tw{layer} and \tw{slice} are exposed +to the client code using an iteration mechanism. + +\noindent +Note the macros $\tt{\_U(layer)}$ and $\tt{\_U(slice)}$: +When using Xerces-C as an XML parser, +it will expand to the reference to an object containing the unicode value +of the string "layer". The full list of predefined tag names can be found in the +include file \detdesc{html/_unicode_values_8h.html}{DD4hep/UnicodeValues.h}. +If a user tag is not part in the precompiled tag list, the corresponding Unicode +string may be created with the macro \tw{\_Unicode(layer)} or the function +\tw{Unicode("layer")}. + +\noindent +The convenience handles actually implement +these functions to ease life. There is no magic - newly created attributes +with new names obviously cannot be accessed with convenience mechanism. +Hence, either you know what you are doing and you create your own +convenience handlers or you restrict yourself a bit in the creativity +of defining new attribute names. + +\noindent +There exist several utility classes to extract data from predefined XML tags: +\begin{itemize}\itemcompact +\item Any XML element is described by an XML handle + \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_handle.html}{\tt{XML::Handle\_t}} + ({\tt{xml\_t}}). Handles are the basic structure for the support + of higher level interfaces described above. The assignment of a handle + to any of the interfaces below is possible. +\item The class \detdesc{html/struct_d_d4hep_1_1_x_m_l_1_1_element.html}{\tt{XML::Element}} + ({\tt{xml\_elt\_t}}) + supports in a simple way the navigation through the hierarchy of the + XML tree accessing child nodes and attributes. Attributes at this + level are named entities and the tag name must be supplied. +\item The class \detdesc{html/struct_d_d4hep_1_1_x_m_l_1_1_dimension.html}{\tt{XML::Dimension}} + with the type definition {\tt{xml\_dim\_t}}, + supports numerous access functions named identical to the + XML attribute names. Such helper classes simplify the tedious + string handling required by the +\item The class \detdesc{html/struct_d_d4hep_1_1_x_m_l_1_1_component.html}{\tt{XML::Component}} + ({\tt{xml\_comp\_t}}) and \\ + the class \detdesc{html/struct_d_d4hep_1_1_x_m_l_1_1_det_element.html}{\tt{XML::Detector}} + ({\tt{xml\_det\_t}}) resolving other issues useful to construct detectors. +\item Sequences of XML elements with an identical tag name may be handled + as iterations as shown in the Figure above using the class + \detdesc{html/struct_d_d4hep_1_1_x_m_l_1_1_collection__t.html}{\tt{XML::Collection\_t}}. +\item Convenience classes, which allow easy access to element attributes + may easily be constructed using the methods of the {\tt{XML::Element}} + class. This allows to construct very flexible thou non-intrusive + extensions to \DDhep. Hence there is a priori no need to modify + these helpers for the benefit of only one single client. + In the presence of multiple requests such extensions may though be adopted. +\end{itemize} +It is clearly the responsibility of the client to only request attributes +from an XML element, which exist. If an attribute, a child node etc. is not +found within the element an exception is thrown. + +\noindent +The basic interface of the \tw{XML::Element} class allows to access tags +and child nodes not exposed by the convenience wrappers: +\begin{code} + /// Access the tag name of this DOM element + std::string tag() const; + /// Access the tag name of this DOM element + const XmlChar* tagName() const; + + /// Check for the existence of a named attribute + bool hasAttr(const XmlChar* name) const; + /// Retrieve a collection of all attributes of this DOM element + std::vector<Attribute> attributes() const; + /// Access single attribute by it's name + Attribute getAttr(const XmlChar* name) const; + /// Access attribute with implicit return type conversion + template <class T> T attr(const XmlChar* tag) const; + /// Access attribute name (throws exception if not present) + const XmlChar* attr_name(const Attribute attr) const; + /// Access attribute value by the attribute (throws exception if not present) + const XmlChar* attr_value(const Attribute attr) const; + + /// Check the existence of a child with a given tag name + bool hasChild(const XmlChar* tag) const; + /// Access child by tag name. Thow an exception if required in case the child is not present + Handle_t child(const Strng_t& tag, bool except = true) const; + /// Add a new child to the DOM node + Handle_t addChild(const XmlChar* tag) const; + /// Check if a child with the required tag exists - if not create it and add it to the current node + Handle_t setChild(const XmlChar* tag) const; +\end{code} + +%============================================================================= +\subsection{The Detector Description Data Hub: LCDD} +\label{sec:dd4hep-user-manual-LCDD-hub} +%============================================================================= +\noindent +As shown in Figure~\ref{fig:dd4hep-detector-model}, any access to the detector +description data is done using a standardized interface called \tw{LCDD}. +During the configuration phase of the detector the interface is used to populate +the internal data structures. +Data structures present in the memory layout of the detector description +may be retrieved by clients at any time using the +\detdesc{html/struct_d_d4hep_1_1_geometry_1_1_l_c_d_d.html}{\tw{LCDD} interface class}. +This includes of course, the access during the actual detector construction. +The following code listing shows the accessor method to retrieve +detector description entities from the interface. Not shown are access methods +for groups of these entities and the methods to add objects: + +\begin{code} +struct LCDD { + + ///+++ Shortcuts to access often used quantities + + /// Return handle to material describing air + virtual Material air() const = 0; + /// Return handle to material describing vacuum + virtual Material vacuum() const = 0; + /// Return handle to "invisible" visualization attributes + virtual VisAttr invisible() const = 0; + + ///+++ Access to the top level detector elements and the corresponding volumes + + /// Return reference to the top-most (world) detector element + virtual DetElement world() const = 0; + /// Return reference to detector element with all tracker devices. + virtual DetElement trackers() const = 0; + + /// Return handle to the world volume containing everything + virtual Volume worldVolume() const = 0; + /// Return handle to the volume containing the tracking devices + virtual Volume trackingVolume() const = 0; + + ///+++ Access to geometry and detector description objects + + /// Retrieve a constant by it's name from the detector description + virtual Constant constant(const std::string& name) const = 0; + /// Retrieve a matrial by it's name from the detector description + virtual Material material(const std::string& name) const = 0; + /// Retrieve a field component by it's name from the detector description + virtual DetElement detector(const std::string& name) const = 0; + /// Retrieve a sensitive detector by it's name from the detector description + virtual SensitiveDetector sensitiveDetector(const std::string& name) const = 0; + /// Retrieve a readout object by it's name from the detector description + virtual Readout readout(const std::string& name) const = 0; + /// Retrieve a id descriptor by it's name from the detector description + virtual IDDescriptor idSpecification(const std::string& name) const = 0; + /// Retrieve a subdetector element by it's name from the detector description + virtual CartesianFieldfield(const std::string& name) const = 0; + + ///+++ Access to visualisation attributes and Geant4 processing hints + + /// Retrieve a visualization attribute by it's name from the detector description + virtual VisAttr visAttributes(const std::string& name) const = 0; + + /// Retrieve a region object by it's name from the detector description + virtual Region region(const std::string& name) const = 0; + /// Retrieve a limitset by it's name from the detector description + virtual LimitSet limitSet(const std::string& name) const = 0; + /// Retrieve an alignment entry by it's name from the detector description + virtual AlignmentEntryalignment(const std::string& path) const = 0; + ... + + ///+++ Extension mechanism: + + /// Extend the sensitive detector element with an arbitrary structure accessible by the type + template <typename IFACE, typename CONCRETE> IFACE* addExtension(CONCRETE* c); + /// Access extension element by the type + template <class T> T* extension() const; +}; +\end{code} + +\noindent +As shown in the above listing, the \tw{LCDD} interface is the main access point to access +a whole set +\begin{itemize}\itemcompact +\item often used predefined values such as the material "air" or "vacuum" (line 5-10). +\item the top level objects "world", "trackers" and the corresponding volumes (line 14-22). +\item items in the constants table containing named definitions also used during the + interpretation of the XML content after parsing (line 27) +\item named items in the the material table (line 29) +\item named subdetectors after construction and the corresponding (line 31) +\item named sensitive detectors with their (line 33) +\item named readout structure definition using a (line 35) +\item named readout identifier descriptions (line 37) +\item named descriptors of electric and/or magnetic fields (line 39). +\end{itemize} +Additional support for specialized applications is provided by the interface: +\begin{itemize}\itemcompact +\item Geant4: named region settings (line 47) +\item Geant4: named limits settings (line 49) +\item Visualization: named visualization attributes (line 44) +\item Alignment: named alignment entries to correct displaced volumes (line 51) +\item User defined extensions (line 56-59) are supported with the extension mechanism + described in section~\ref{sec:dd4hep-user-manual-data-extensions}. +\end{itemize} +All the values are populated either directly from XML or from +\tw{detector-constructors} (see section~\ref{sec:detector-constructors}). The interface +also allows to load XML configuration files of any kind provided an appropriate +interpretation plugin is present. In the next section we describe the functionality +of the "lccdd" plugin used to interpret the compact detector description. +This mechanism can easily be extended using ROOT plugins, where the +plugin name must corrspond to the XML root element of the document to +be interpreted. + +\newpage +%============================================================================= +\subsection{Detector Description Persistency in XML} +\label{sec:compact-xml-structure} +%============================================================================= +\noindent +As explained in a previous section, the mechanism involved in the data loading +allow an application to be fairly independent of the technology used to populate +the transient detector representation. However, if one wants to use a given tech- +nology, she/he has to get/provide the corresponding conversion mechanism. +Though \DDhep also supports the population of the detector description using +python constructs, we want to focus here on the XML based population. +The choice of XML was driven mainly by its easiness of use and the number +of tools provided for its manipulation and parsing. Moreover, XML data +can be easily translated into many other format using tools like \tw{XSLT} +processors. +The grammar used for the XML data is pretty simple and straight forward, +actually very similar to other geometry description languages based +on XML. For example the material description is nearly identical +to the material description in \tw{GDML}~\cite{bib:GDML}. +The syntactic structure of the compact XML description was taken from +the SiD detector description~\cite{bib:LCDD}. +The following listing shows the basic layout of any +the compact detector description file with its different sections: + +\begin{code} +<lccdd> + <info> ... </info> Auxiliary detector model information + <includes> ... </includes> Section defining GDML files to be included + <define> ... </define> Dictionary of constant expressions and varables + <materials> ... </materials> Additional material definitions + <display> ... </display> Definition of visualization attributes + <detectors> ... </detectors> Section with sub-detector definitions + <readouts> ... </readouts> Section with readout structure definitions + <limits> ... </limits> Definition of limit sets for Geant4 + <fields> ... </fields> Field definitions +</lccdd> +\end{code} + +\noindent +The root tag of the XML tree is {\tw{lccdd}}. This name is fixed. +In the following the content of the various sections is discussed. +The XML sections are filled with the following information: +\begin{itemize} +\item {\bf{The \tw{<info>} sub-tree}} contains auxiliary information about + the detector model: + +\begin{code} +<info name="clic_sid_cdr" + title="CLIC Silicon Detector CDR" + author="Christian Grefe" + url="https://twiki.cern.ch/twiki/bin/view/CLIC/ClicSidCdr" + status="development" + version="$Id: compact.xml 665 2013-07-02 18:49:26Z markus.frank $"> + <comment>The compact format for the CLIC Silicon Detector used + for the conceptual design report</comment> +</info> +\end{code} + +\item {\bf{The \tw{<includes>} section}} allows to include GDML sub-trees containing + material descriptions. These files are processed {\it{before}} the + detector constructors are called: + +\begin{code} +<includes> + <gdmlFile ref="elements.xml"/> + <gdmlFile ref="materials.xml"/> + ... +</includes> +\end{code} + +\item {\bf{The \tw{<define>} section}} contains all variable definitions + defined by the client to simplify the definition of subdetectors. + These name-value pairs are fed to the expression evaluator + and MUST evaluate to a number. String constants are not allowed. + These variables can be combined to formulas e.g. to automatically + re-dimension subdetectors if boundaries are changed: + +\begin{code} +<define> + <constant name="world_side" value="30000"/> + <constant name="world_x" value="world_side"/> + <constant name="world_y" value="world_side"/> + <constant name="world_z" value="world_side"/> + .... +</define> +\end{code} + +\item {\bf{The $\tt<materials>$ sub-tree}} contains additional materials, which + are not contained in the default materials tables. The snippet below shows + an example to extend the table of known materials. For more details please see + section~\ref{sec:compact-material-description}. + +\begin{code} +<materials> + <!-- The description of an atomic element or isotope --> + <element Z="30" formula="Zn" name="Zn" > + <atom type="A" unit="g/mol" value="65.3955" /> + </element> + ... + <!-- The description of a new material --> + <material name="CarbonFiber_15percent"> + ... + </material> + ... +</materials> +\end{code} + +\item {\bf{The visualization attributes}} are defined in the $\tt<display>$ section. + Clients access visualization settings by name. The possible attributes are shown + below and essentially contain the RGB color values, the visibility and the drawing style: + +\begin{code} +<display> + <vis name="InvisibleNoDaughters" showDaughters="false" visible="false"/> + <vis name="SiVertexBarrelModuleVis" + alpha="1.0" r="1" g="1" b="0.6" + drawingStyle="solid" + showDaughters="true" + visible="true"/> + .... +</display> +\end{code} + +\item {\bf{Limisets}} contain parameters passed to Geant4: + +\begin{code} +<limits> + <limitset name="cal_limits"> + <limit name="step_length_max" particles="*" value="5.0" unit="mm" /> + </limitset> +</limits> +\end{code} + +\item {\bf{The $\tt<detectors>$}} section contains subtrees of the type $\tt<detector>$ + which contain all parameters used by the $detector constructors$ + to actually expand the geometrical structure. Each subdetector has a name and a type, + where the type is used to call the proper constructor plugin. If the subdetector + element is sensitive, a forward reference to the corresponding readout structure + is mandatory. The remaining parameters are user defined: + +\begin{code} +<detectors> + <detector id="4" name="SiTrackerEndcap" type="SiTrackerEndcap" readout="SiTrackerEndcapHits"> + <comment>Outer Tracker Endcaps</comment> + <module name="Module1" vis="SiTrackerEndcapModuleVis"> + <trd x1="36.112" x2="46.635" z="100.114/2" /> + <module_component thickness="0.00052*cm" material="Copper" /> + <module_component thickness="0.03*cm" material="Silicon" sensitive="true" /> + ... + </module> + ... + <layer id="1"> + <ring r="256.716" zstart="787.105+1.75" nmodules="24" dz="1.75" module="Module1"/> + <ring r="353.991" zstart="778.776+1.75" nmodules="32" dz="1.75" module="Module1"/> + <ring r="449.180" zstart="770.544+1.75" nmodules="40" dz="1.75" module="Module1"/> + </layer> + ... + </detector> +</detectors> +\end{code} + +\item {\bf{The $\tt<readouts>$ section}} defined the encoding of sensitive volumes + to so-called cell-ids, which are in \DDhep 64-bit integer numbers. The encoding + is subdetector dependent with one exception: to uniquely identity each subdetector, + the width of the system field must be the same. The usage of these data is + discussed in section~\ref{dd4hep-sensitive-detectors}. +\begin{code} +<readouts> + <readout name="SiTrackerEndcapHits"> + <id>system:8,barrel:3,layer:4,module:14,sensor:2,side:32:-2,strip:20</id> + </readout> + ... +</readouts> +\end{code} + +\item {\bf{Electromagnetic fields}} are described in the $\tt<fields>$ section. + There may be several fields present. In \DDhep the resulting field vectors + may be both electric and magnetic. The strength of the overall field is calculated + as the superposition of the individual components: +\begin{code} +<fields> + <field name="GlobalSolenoid" type="solenoid" + inner_field="5.0*tesla" + outer_field="-1.5*tesla" + zmax="SolenoidCoilOuterZ" + outer_radius="SolenoidalFieldRadius"> + </field> + ... +</fields> +\end{code} +\end{itemize} + + + +\newpage +%============================================================================= +\subsection{Material Description} +\label{sec:compact-material-description} +%============================================================================= +\noindent +Materials are needed by logical volumes. They are defined as isotopes, +elements or mixtures. +Elements can optionally be composed of isotopes. Composition is always done +by specifying the fraction of the mass. Mixtures can be composed of elements +or other mixtures. For a mixture the user can specify composition either by +number of atoms or by fraction of mass. The materials sub-tree +in section~\ref{sec:compact-xml-structure} +shows the representation of an element, a simple material and a +composite material in the XML format identical to GDML~\cite{bib:GDML}. +The snippet below shows how to define new material instances: +\begin{code} +<materials> + ... + <!-- (1) The description of an atomic element or isotope --> + <element Z="30" formula="Zn" name="Zn" > + <atom type="A" unit="g/mol" value="65.3955" /> + </element> + <!-- (2) A composite material --> + <material name="Kapton"> + <D value="1.43" unit="g/cm3" /> + <composite n="22" ref="C"/> + <composite n="10" ref="H" /> + <composite n="2" ref="N" /> + <composite n="5" ref="O" /> + </material> + <!-- (3) A material mixture --> + <material name="PyrexGlass"> + <D type="density" value="2.23" unit="g/cm3"/> + <fraction n="0.806" ref="SiliconOxide"/> + <fraction n="0.130" ref="BoronOxide"/> + <fraction n="0.040" ref="SodiumOxide"/> + <fraction n="0.023" ref="AluminumOxide"/> + </material> + ... +</materials> +\end{code} +The $\tt<materials>$ sub-tree contains additional materials, which +are not contained in the default materials tables. The snippet above shows +different kinds of materials: +\begin{description} +\item{(1)} Atomic elements as they are in the periodic table. The number of elements + is finite. It is unlikely any client will have to extend the known elements. +\item{(2)} Composite materials, which consists of one or several elements + forming a molecule. These materials have a certain density under normal + conditions described in the child element \tw{D}. + For each \tw{composite} the attribute \tw{ref} denotes the element type by name, + the attribute \tw{n} denotes the atomic multiplicity. + Typically each of the elements in (1) also forms such a material representing + objects which consist of pure material like e.g. iron magnet yokes or copper wires. +\item{(3)} Last there are mixtures of composite materials to describe + for example alloys, solutions or other mixtures of solid materials. + This is the type of material used to actually create mechanical structures + forming the assembly of an experiment. Depending on the maufactering + these materials have a certain density (\tw{D}) and are composed + of numerous molecules contributing to the resulting material with a given + \tw{fraction}. The sum of all fractions (attribute \tw{n}) is 1.0. +\end{description} +"Real" materials i.e. those you can actually touch are described in TGeo +by the class \tgeo{TGeoMedium}{\tt{TGeoMedium}} +\footnote{Typical beginner's mistake: Do not mix up the +two classes \tw{TGeoMaterial} and \tw{TGeoMedium}! +The material to define volumes is of type \tw{TGeoMedium}, which also includes the +description of the material's finish.}. +Materials are not constructed by any client. Materials and elements are +either already present in the the corresponding tables of the ROOT geometry +package or they are added during the interpretation of the XML input. +Clients access the description of material using the \tw{LCDD} interface. + + +\newpage +\begin{figure}[t] + \begin{center} + \includegraphics[width=160mm] {DD4hep-solids.png} + \caption{Extensions may be attached to common Detector Elements which + extend the functionality of the common DetElement + class and support e.g. caching of precomputed values.} + \label{fig:dd4hep-solids} + \end{center} + \vspace{-0.6cm} +\end{figure} +%============================================================================= +\subsection{Shapes} +\label{dd4hep-basic-shapes} +%============================================================================= +\noindent +Shapes are abstract objects with a bounding surface and fixed dimensions. +There are primitive, atomic shapes +and complex boolean shapes as shown in Figure~\ref{fig:dd4hep-solids}. +TGeo and similarly Geant4 offer a whole palette of +primitive shapes, which can be used to construct more complex shapes: +\begin{itemize}\itemcompact +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_box.html}{Box} shape + represented by the \tgeo{TGeoBBox}{\tt TGeoBBox} class. To create a new box + object call one of the following constructors: +\begin{code} +/// Constructor to be used when creating an anonymous new box object +Box(double x, double y, double z); +/// Constructor to be used when creating an anonymous new box object +template<typename X, typename Y, typename Z> Box(const X& x, const Y& y, const Z& z); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_sphere.html}{Sphere} shape + represented by the \tgeo{TGeoSphere}{\tt TGeoSphere} class. To create a new sphere + object call one of the following constructors: +\begin{code} +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_cone.html}{Cone} shape + represented by the \tgeo{TGeoCone}{\tt TGeoCone} class. To create a new cone + object call one of the following constructors: +\begin{code} +/// Constructor to create a new anonymous object with attribute initialization +Cone(double z,double rmin1,double rmax1,double rmin2,double rmax2); +template<typename Z, typename RMIN1, typename RMAX1, typename RMIN2, typename RMAX2> +Cone(const Z& z, const RMIN1& rmin1, const RMAX1& rmax1, const RMIN2& rmin2, const RMAX2& rmax2); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_cone_segment.html}{Cone segment} shape + represented by the \tgeo{TGeoConeSeg}{\tt TGeoConeSeg} class. To create a new cone segment + object call one of the following constructors: +\begin{code} +/// Constructor to create a new ConeSegment +ConeSegment(double dz, double rmin1, double rmax1, double rmin2, double rmax2, + double phi1=0.0, double phi2=2.0*M_PI); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_polycone.html}{Polycone} shape + represented by the \tgeo{TGeoPcon}{\tt TGeoPcon} class. To create a new polycone + object call one of the following constructors: +\begin{code} +/// Constructor to create a new polycone object +Polycone(double start, double delta); +followed by a call to: +void addZPlanes(const std::vector<double>& rmin, + const std::vector<double>& rmax, + const std::vector<double>& z); +/// Constructor to create a new polycone object. Add at the same time all Z planes +Polycone(double start, double delta, + const std::vector<double>& rmin, + const std::vector<double>& rmax, + const std::vector<double>& z); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_tube.html}{Tube segment} shape + represented by the \tgeo{TGeoTubeSeg}{\tt TGeoTubeSeg} class. To create a new tube segment + object call one of the following constructors: +\begin{code} +Tube(double rmin, double rmax, double z, double deltaPhi=2*M_PI) +Tube(double rmin, double rmax, double z, double startPhi, double deltaPhi) + +template<typename RMIN, typename RMAX, typename Z, typename DELTAPHI> +Tube(const RMIN& rmin, const RMAX& rmax, const Z& z, const DELTAPHI& deltaPhi) + +template<typename RMIN, typename RMAX, typename Z, typename STARTPHI, typename DELTAPHI> +Tube(const std::string& name, const RMIN& rmin, const RMAX& rmax, const Z& z, + const STARTPHI& startPhi, const DELTAPHI& deltaPhi) +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_trapezoid.html}{Trapezoid} shape + represented by the \tgeo{TGeoTrd2}{\tt TGeoTrd} class. To create a new trapezoid + object call one of the following constructors: +\begin{code} +/// Constructor to create a new anonymous object with attribute initialization +Trapezoid(double x1, double x2, double y1, double y2, double z); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_trap.html}{Trap} shape + represented by the \tgeo{TGeoTrap}{\tt TGeoTrap} class. To create a new trap + object call one of the following constructors: +\begin{code} +/// Constructor to create a new anonymous object with attribute initialization +Trap(double z,double theta,double phi, + double y1,double x1,double x2,double alpha1, + double y2,double x3,double x4,double alpha2); +/// Constructor to create a new anonymous object for right angular wedge from STEP (Se G4 manual for details) +Trap( double pz, double py, double px, double pLTX); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_torus.html}{Torus} shape + represented by the \tgeo{TGeoTorus}{\tt TGeoTorus} class. To create a new torus + object call one of the following constructors: +\begin{code} +/// Constructor to create a new anonymous object with attribute initialization +Torus(double r, double rmin, double rmax, double phi=M_PI, double delta_phi=2.*M_PI); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_paraboloid.html}{Paraboloid} shape + represented by the \tgeo{TGeoParaboloid}{\tt TGeoParaboloid} class. To create a new paraboloid + object call one of the following constructors: +\begin{code} +/// Constructor to create a new anonymous object with attribute initialization +Paraboloid(double r_low, double r_high, double delta_z); +\end{code} +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_polyhedra_regular.html}{Regular Polyhedron} shape + represented by the \tgeo{TGeoPgon}{\tt TGeoPgon} class. To create a new polyhedron + object call one of the following constructors: +\begin{code} +/// Constructor to create a new object. Phi(start)=0, deltaPhi=2PI, Z-planes at +-zlen/2 +PolyhedraRegular(int nsides, double rmin, double rmax, double zlen); +/// Constructor to create a new object. Phi(start)=0, deltaPhi=2PI, Z-planes at zplanes[0],[1] +PolyhedraRegular(int nsides, double rmin, double rmax, double zplanes[2]); +/// Constructor to create a new object with phi_start, deltaPhi=2PI, Z-planes at +-zlen/2 +PolyhedraRegular(int nsides, double phi_start, double rmin, double rmax, double zlen); +\end{code} +\end{itemize} + +\noindent +Besides the primitive shapes three types of boolean shapes (described in TGeo by the +\tgeo{TGeoCompositeShape}{{\tt{TGeoCompositeShape}}} class) +are supported: + +\begin{itemize}\itemcompact +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_union_solid.html}{\tt UnionSolid} objects representing the union, +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_intersection_solid.html}{\tt IntersectionSolid} objects representing the intersection, +\item \detdesc{html/struct_d_d4hep_1_1_geometry_1_1_subtraction_solid.html}{\tt SubtractionSolid} objects representing the subtraction, +\end{itemize} + +\noindent +of two other primitive or complex shapes. To build a boolean shape, the +second shape is transformed in 3-dimensional space before the boolean +operation is applied. The 3D transformations are described by objects from the +ROOT::Math library and are supplied at construction time. +Such a transformation as shown in the code snippet below may be + +\begin{itemize}\itemcompact +\item The identity transformation. Then no transformation object needs to be provided (see line 2). + +\item A translation only described by a \tw{Position} object (see line 4) + +\item A 3-fold rotation first around the Z-axis, then around the Y-axis and finally around the X-axis. + For transformation operations of this kind a \tw{RotationZYX} object must be supplied (see line 6). + +\item A generic 3D rotation matrix should be applied to the second shape. Then a \tw{Rotation3D} + object must be supplied (see line 8). + +\item Finally a generic 3D transformation (translation+rotation) may be applied using a + \tw{Transform3D} object (see line 10). +\end{itemize} + +\noindent +All three boolean shapes +have constructors as shown here for the UnionSolid: +\begin{code} + /// Constructor to create a new object. Position is identity, Rotation is identity-rotation! + UnionSolid(const Solid& shape1, const Solid& shape2); + /// Constructor to create a new object. Placement by position, Rotation is identity-rotation! + UnionSolid(const Solid& shape1, const Solid& shape2, const Position& pos); + /// Constructor to create a new object. Placement by a RotationZYX within the mother + UnionSolid(const Solid& shape1, const Solid& shape2, const RotationZYX& rot); + /// Constructor to create a new object. Placement by a generic rotoation within the mother + UnionSolid(const Solid& shape1, const Solid& shape2, const Rotation3D& rot); + /// Constructor to create a new object. Placement by a generic transformation within the mother + UnionSolid(const Solid& shape1, const Solid& shape2, const Transform3D& pos); +\end{code} + + +\newpage +%============================================================================= +\subsection{Volumes and Placements} +%============================================================================= +\noindent +The detector geometry is described by a hierarchy of volumes and their +corresponding placements. Both, the TGeo package and Geant4~\cite{bib:geant4} +are following effectively the same ideas ensuring an easy conversion from +TGeo to Geant4 objects for the simulation application. +\noindent +A volume is an unplaced solid de\-scribed in terms of a primitive +shape or a boolean operation of solids, a material and a number of +placed sub-volumes (placed volumes) inside. The class diagram showing the +relationships between volumes and placements, solids and materials is shown +in Figure~\ref{fig:dd4hep-detector-model}. +\noindent +It is worth noting, that any volume has children, but no parent or "mother" +volume. This is a direct consequence of the requirement to re-use volumes +and place the same volume arbitrarily often. Only the act of placing a volume +defines the relationship to the next level parent volume. +The resulting geometry tree is very effective, simple and convenient to +describe the detector geometry hierarchy starting from the top level volume +representing e.g. the experiment cavern down to the very detail of the detector +e.g. the small screw in the calorimeter. The top level volume is the very only +volume without a placement. All geometry calculations, computations are always +performed within the local coordinate system of the volume. +The following example code shows how to create +a volume which consists of a given material and with a shape. The created volume +is then placed inside the mother-volume using the local coordinate system of the +mother volume: + +\begin{code} + Volume mother = ....ampercent + + Material mat (lcdd.material("Iron")); + Tube tub (rmin, rmax, zhalf); + Volume vol (name, tub, mat); + Transform3D tr (RotationZYX(rotz,roty,rotx),Position(x,y,z)); + PlacedVolume phv = mother.placeVolume(vol,tr); +\end{code} + +\noindent +The volume has the shape of a tube and consists of iron. +Before being placed, the daughter volume is transformed within +the mother coordinate system according to the requested transformation. +The example also illustrates how to access $Material$ objects from the +$LCDD$ interface. + +\noindent +The {\tt{Volume}} class provides several possibilities to declare +the required space transformation necessary to place a daughter volume +within the mother: +\begin{itemize}\itemcompact +\item to place a daughter volume unrotated at the origin of the mother, the +transformation is the identity. Use the following call to place the daughter: +\begin{unnumberedcode} +PlacedVolume placeVolume(const Volume& vol) const; +\end{unnumberedcode} +\item If the positioning is described by a simple translation, use: +\begin{unnumberedcode} +PlacedVolume placeVolume(const Volume& vol, const Position& pos) coampercentnst; +\end{unnumberedcode} +\item In case the daughter should be rotated first around the Z-axis, + then around the Y-axis and finally around the X-axis place the daughter + using this call: +\begin{unnumberedcode} +PlacedVolume placeVolume(const Volume& vol, const RotationZYX& rot) const; +\end{unnumberedcode} +\item If the full 3-dimensional rotation matrix is known use: +\begin{unnumberedcode} +PlacedVolume placeVolume(const Volume& vol, const Rotation3D& rot) const; +\end{unnumberedcode} +\item for an entirely unconstrained placement place the daughter providing + a Transform3D object: +\begin{unnumberedcode} +PlacedVolume placeVolume(const Volume& volume, const Transform3D& tr) const; +\end{unnumberedcode} +\end{itemize} + +\noindent +For more details of the \tw{Volume} and the \tw{PlacedVolume} classes please see the +\detdesc{html/_volumes_8h.html}{header file}. + +\noindent +One volume like construct is special: the assembly constructs. +Assemblies are volumes without shapes. The "assembly" shape does not +own a own surface by itself, but rather defines it's surface and +bounding box from the contained children. +In this corner also the implementation concepts between TGeo and Geant4 diverge. +Whereas TGeo handles assemblies very similar to real volumes, in Geant4 +assemblies are purely artificial and disappear at the very moment volumes +are placed. + +\newpage +%============================================================================= +\subsection{Detector Elements} +\label{sec:dd4hep-user-manual-detector-elements} +%============================================================================= +\begin{figure}[b] + \begin{center} + \includegraphics[width=160mm] {DD4hep-detelement-drawing.png} + \caption{The basic layout of the \tw{DetElement} class aggregating + all data entities necessary to process data.} + \label{fig:dd4hep-user-manual-detelement-drawing} + \end{center} + \vspace{-0.6cm} +\end{figure} + +\noindent +Detector elements (class \tw{DetElement}) are entities which represent +subdetectors or sizable parts of a subdetector. +As shown in Figure~\ref{fig:dd4hep-user-manual-detelement-drawing}, +a \tw{DetElement} instance has the means to provide to clients information about + +\begin{itemize}\itemcompact +\item generic properties like the detector type or the path within the \tw{DetElement}s + hierarchy: +\begin{code} + /// Access detector type (structure, tracker, calorimeter, etc.). + std::string type() const; + /// Path of the detector element (not necessarily identical to placement path!) + std::string path() const; +\end{code} + +\item the detector hierarchy by exposing its children. The hierarchy may be + accessed with the following API: +\begin{code} + /// Add new child to the detector structure + DetElement& add(DetElement sub_element); + /// Access to the list of children + const Children& children() const; + /// Access to individual children by name + DetElement child(const std::string& name) const; + /// Access to the detector elements's parent + DetElement parent() const; +\end{code} + +\item its placement within the overall experiment if it represents an + entire subdetector or its placement with respect to its parent + if the \tw{DetElement} represents a part of a subdetector. + The placement path is the fully qualified path of placed volumes + from the top level volume to the placed detector element and may + serve as a shortcut for the alignment implementation: +\begin{code} + /// Access to the full path to the placed object + std::string placementPath() const; + /// Access to the physical volume of this detector element + PlacedVolume placement() const; + /// Access to the logical volume of the daughter placement + Volume volume() const; +\end{code} + +\item information about the environmental conditions etc. (\tw{conditons}): +\begin{code} + /// Access to the conditions information + Conditions conditions() const; +\end{code} + +\item alignment information: +\begin{code} + /// Access to the alignment information + Alignment alignment() const; +\end{code} + +\item convenience information such as cached transformations + to/from the top level volume, to/from the parent \tw{DetElement} + and to/from another \tw{DetElement} in the hierarchy above: +\begin{code} + /// Transformation from local coordinates of the placed volume to the world system + bool localToWorld(const Position& local, Position& global) const; + /// Transformation from world coordinates of the local placed volume coordinates + bool worldToLocal(const Position& global, Position& local) const; + + /// Transformation from local coordinates of the placed volume to the parent system + bool localToParent(const Position& local, Position& parent) const; + /// Transformation from world coordinates of the local placed volume coordinates + bool parentToLocal(const Position& parent, Position& local) const; + + /// Transformation from local coordinates of the placed volume to arbitrary parent system set as reference + bool localToReference(const Position& local, Position& reference) const; + /// Transformation from world coordinates of the local placed volume coordinates + bool referenceToLocal(const Position& reference, Position& local) const; + + /// Set detector element for reference transformations. + /// Will delete existing reference transformation. + DetElement& setReference(DetElement reference); +\end{code} + +\item User extension information as described in section~\ref{sec:dd4hep-user-manual-data-extensions}: +\begin{code} + /// Extend the detector element with an arbitrary structure accessible by the type + template <typename IFACE, typename CONCRETE> IFACE* addExtension(CONCRETE* c); + /// Access extension element by the type + template <class T> T* extension() const; +\end{code} + +\end{itemize} + + +\newpage +%============================================================================= +\subsection{Sensitive Detectors} +\label{sec:dd4hep-user-manual-sensitive-detectors} +%============================================================================= + +\noindent +Though the concept of sensitive detectors comes from Geant4 and simulation +activities, in DD4hep the sensitive detectors are the client interface to +access the readout description (class \tw{Readout}) with its +segmentation of sensitive elements (class \tw{Segmentation}) and +the description of hit decoders (class \tw{IDDescriptors}). +As shown in Figure~\ref{fig:dd4hep-sensitive-detectors}, these object +instances are required when reconstructing data from particle collisions. + +\noindent +Besides the access to data necessary for reconstruction the sensitive detector +also hosts Region setting (class \tw{Region} and sets of cut limits +(class \tw{LimitSets}) used to configure the Geant4 simulation toolkit. +The following code snippet shows the accessors of the +\tw{SensitiveDetector} class to obtain the corresponding +information~\footnote{The methods to set the data are not shown here.}: + + +\vspace{0.3cm} +\begin{code} + struct SensitiveDetector: public Ref_t { + /// Access the hits collection name + const std::string& hitsCollection() const; + /// Access readout structure of the sensitive detector + Readout readout() const; + /// Access to the region setting of the sensitive detector (not mandatory) + Region region() const; + /// Access to the limit set of the sensitive detector (not mandatory). + LimitSet limits() const; + + /// Extend the sensitive detector element with an arbitrary structure accessible by the type + template <typename IFACE, typename CONCRETE> IFACE* addExtension(CONCRETE* c); + /// Access extension element by the type + template <class T> T* extension() const; + }; +\end{code} + +\begin{figure}[h] + \begin{center} + \includegraphics[width=140mm] {DD4hep-sensitive-detectors.png} + \caption{The structure of DD4hep sensitive detectors.} + \label{fig:dd4hep-sensitive-detectors} + \end{center} + \vspace{-0.6cm} +\end{figure} + + +\noindent +Sensitive detector objects are automatically creating using the information +of the \tw{<readout>} section of the XML file if a subdetector is sensitive +and references a valid readout entry. +In the detector constructor (or any time later) clients +may add additional information to a sensitive detector object using +an extension mechanism similar to the extension mechanism for +detector elements mentioned earlier. + + +\noindent +Volumes may be shared and reused in several placements. In the parallel +hierarchy of detector elements as shown in Figure~\ref{fig:dd4hep-hierarchies}, +the detector elements may reference unambiguously the volumes of their +respective placements, but not the reverse. +However, the sensitive detector setup is a single instance per subdetector. +Hence it may be referenced by all sensitive Volumes of one subdetector. +In the following chapters the access to the readout structure is described. + +%============================================================================= +\subsection{Description of the Readout Structure} +\label{sec:dd4hep-manual-readout-description} +%============================================================================= +\noindent +The \tw{Readout} class describes the detailed structure of a sensitve volume. +The for example may be the layout of strips or pixels in a silicon detector +i.e. the description of entities which would not be modeled using individual +volumes and placements though this would theoretically feasible. +Each sensitive element is segmented according to the \tw{Segmentation} object +and hits resulting from energy depositions in the sensitive volume are +encoded using the \tw{IDDescriptor} object. + +\begin{figure}[h] + \begin{center} + \includegraphics[width=100mm] {DD4hep-readout.png} + \caption{The basic components to describe the \tw{Readout} structure + of a subdetector. } + \label{fig:dd4hep-sensitive-detectors} + \end{center} + \vspace{-0.6cm} +\end{figure} + +%============================================================================= +\subsubsection{CellID Descriptors} +\label{sec:dd4hep-manual-readout-iddescriptors} +%============================================================================= +\noindent +\tw{IDDescriptor}s define the encoding of sensitive volumes to uniquely identify +the location of the detector response. The encoding defines a bit-field with +the length of 64 bits. The first field is mandatory called \tw{system} and +identifies the subdetector. All other fields define the other volumes in the +hierarchy. The high bits are not necessarily mapped to small daughter volumes, +but may simply identify a logical segmentation such as the \tw{strip} \tw{number} +within a wafer of a vertex detector as shown in the following XML snippet: +\begin{code} +<readouts> + <readout name="SiVertexEndcapHits"> + <id>system:8,barrel:3,layer:4,module:14,sensor:2,side:32:-2,strip:24</id> + </readout> +<readouts> +\end{code} +These identifiers are the data input to +\tw{segmentation classes}~\ref{sec:dd4hep-manual-readout-segmentations}, +which define a user friendly API to en/decode the detector response. + +%============================================================================= +\subsubsection{Segmentations} +\label{sec:dd4hep-manual-readout-segmentations} +%============================================================================= +\noindent +Segementations define the user API to the low level interpretation of +the energy deposits in a subdetector. For technical reasons and partial +religious reasons are the segmentation implementation not part of the \DDhep +toolkit, but an independent package call +\tw{DDSegmentation}~\cite{bib:DDSegmentations}. Though the usage is an +integral part of DD4hep. + +\newpage +%============================================================================= +\subsection{Detector Constructors} +\label{sec:dd4hep-manual-detector-constructors} +%============================================================================= +\noindent +The creation of appropriate detector constructors is the main work of a client +defining his own detector. The detector constructor is a fragment of code in the +form of a routine, which return a handle to the created subdetector +\tw{DetElement} object. + +\noindent +Knowing that detector constructors are the main work items of clients significant +effort was put in place to ease and simplify this procedure as much as possible +in order to obtain readable, still compact code hopefully easy to maintain. +The interfaces to all objects, XML accessors, shapes, volumes etc. which were +discussed above were optimized to support this intention. + +\noindent +To illustrate the anatomy of such a constructor the following code originating +from an existing SiD detector concept will be analyzed. The example starts +with the XML input data. Further down this section the code is shown +with a detailed description of every relevant line. The object to be build is +a subdetector representing a layered calorimeter, +where each layer consists of a number of slices as shown in the XML snippet. +These layers are then repeated a number of times. + +\vspace{0.1cm} +\noindent +The XML snippet describing the subdetector properties: +\begin{code} + <detector id="13" name="LumiCal" reflect="true" type="CylindricalEndcapCalorimeter" + readout="LumiCalHits" vis="LumiCalVis" calorimeterType="LUMI"> + <comment>Luminosity Calorimeter</comment> + <dimensions inner_r = "LumiCal_rmin" inner_z = "LumiCal_zmin" outer_r = "LumiCal_rmax" /> + <layer repeat="20" > + <slice material = "TungstenDens24" thickness = "0.271*cm" /> + <slice material = "Silicon" thickness = "0.032*cm" sensitive = "yes" /> + <slice material = "Copper" thickness = "0.005*cm" /> + <slice material = "Kapton" thickness = "0.030*cm" /> + <slice material = "Air" thickness = "0.033*cm" /> + </layer> + <layer repeat="15" > + <slice material = "TungstenDens24" thickness = "0.543*cm" /> + <slice material = "Silicon" thickness = "0.032*cm" sensitive = "yes" /> + <slice material = "Copper" thickness = "0.005*cm" /> + <slice material = "Kapton" thickness = "0.030*cm" /> + <slice material = "Air" thickness = "0.033*cm" /> + </layer> + </detector> +\end{code} + +\vspace{0.1cm} +\noindent +The C++ code snippet interpreting the XML data and expanding the geometry: +\vspace{0.1cm} +\begin{code} +#include "DD4hep/DetFactoryHelper.h" +#include "XML/Layering.h" + +using namespace std; +using namespace DD4hep; +using namespace DD4hep::Geometry; + +static Ref_t create_detector(LCDD& lcdd, xml_h e, SensitiveDetector sens) { + xml_det_t x_det = e; + string det_name = x_det.nameStr(); + bool reflect = x_det.reflect(); + xml_dim_t dim = x_det.dimensions(); + double zmin = dim.inner_z(); + double rmin = dim.inner_r(); + double rmax = dim.outer_r(); + double totWidth = Layering(x_det).totalThickness(); + double z = zmin; + Material air = lcdd.air(); + Tube envelope (rmin,rmax,totWidth,0,2*M_PI); + Volume envelopeVol(det_name+"_envelope",envelope,air); + int layer_num = 1; + PlacedVolume pv; + + // Set attributes of slice + for(xml_coll_t c(x_det,_U(layer)); c; ++c) { + xml_comp_t x_layer = c; + double layerWidth = 0; + for(xml_coll_t l(x_layer,_U(slice)); l; ++l) + layerWidth += xml_comp_t(l).thickness(); + + for(int i=0, m=0, repeat=x_layer.repeat(); i<repeat; ++i, m=0) { + double zlayer = z; + string layer_name = det_name + _toString(layer_num,"_layer%d"); + Volume layer_vol(layer_name,Tube(rmin,rmax,layerWidth),air); + + for(xml_coll_t l(x_layer,_U(slice)); l; ++l, ++m) { + xml_comp_t x_slice = l; + double w = x_slice.thickness(); + string slice_name = layer_name + _toString(m+1,"slice%d"); + Material slice_mat = lcdd.material(x_slice.materialStr()); + Volume slice_vol (slice_name,Tube(rmin,rmax,w),slice_mat); + + if ( x_slice.isSensitive() ) { + sens.setType("calorimeter"); + slice_vol.setSensitiveDetector(sens); + } + slice_vol.setAttributes(lcdd,x_slice.regionStr(),x_slice.limitsStr(),x_slice.visStr()); + pv = layer_vol.placeVolume(slice_vol,Position(0,0,z-zlayer-layerWidth/2+w/2)); + pv.addPhysVolID("slice",m+1); + z += w; + } + layer_vol.setVisAttributes(lcdd,x_layer.visStr()); + Position layer_pos(0,0,zlayer-zmin-totWidth/2+layerWidth/2); + pv = envelopeVol.placeVolume(layer_vol,layer_pos); + pv.addPhysVolID("layer",layer_num); + ++layer_num; + } + } + // Set attributes of slice + envelopeVol.setAttributes(lcdd,x_det.regionStr(),x_det.limitsStr(),x_det.visStr()); + + DetElement sdet(det_name,x_det.id()); + Volume motherVol = lcdd.pickMotherVolume(sdet); + PlacedVolume phv = motherVol.placeVolume(envelopeVol,Position(0,0,zmin+totWidth/2)); + phv.addPhysVolID("system",sdet.id()) + .addPhysVolID("barrel",1); + sdet.setPlacement(phv); + if ( reflect ) { + phv=motherVol.placeVolume(envelopeVol,Transform3D(RotationZ(M_PI),Position(0,0,-zmin-totWidth/2))); + phv.addPhysVolID("system",sdet.id()) + .addPhysVolID("barrel",2); + } + return sdet; +} + +DECLARE_DETELEMENT(CylindricalEndcapCalorimeter,create_detector); +\end{code} + +\newpage +\noindent +\begin{tabular} {l||p{0cm}} +\docline{Line}{} +\docline{1}{The include file DetFactoryHelper.h includes all + utilities to extract XML information together with the appropriate type + definition.} +\docline{4-6}{Convenience shortcut to save ourself a lot of typing.} +\docline{8}{The entry point to the detector constructor. This routine shall + be called by the plugin mechanism.} +\docline{9}{The functionality of the raw XML handle \tw{xml\_h} is rather + limited. A simple assignment to a XML detector object gives us all the + functionality we need.} +\docline{10,11}{Extracting the sub-detector name and properties from the xml handle.} +\docline{12-17}{Access the $dimension$ child-element from the XML subtree, access the element's + attributes and precompute values used later.} +\docline{18}{Retrieve a reference to the "air" material from LCDD.} +\docline{19-20}{Construct the envelope volume shaped as a tube made out of air.} +\docline{25}{Now the detector can be built: We loop over all layers types and over + each layer type as often as necessary (attribute: repeat). + The XML collection object will return all child elements of \tw{x\_det} + with a tag-name "layer". } +\docline{25}{Note the macro $\tt{\_U(layer)}$: When using Xerces-C as an XML parser, + it will expand to the reference to an object containing the unicode value + of the string "layer". The full list of predefined tag names can be found in the + include file \detdesc{html/_unicode_values_8h.html}{DD4hep/UnicodeValues.h}. + If a user tag is not part in the precompiled tag list, the corresponding Unicode + string may be created with the macro \tw{\_Unicode(layer)} or \tw{Unicode("layer")}. + } +\docline{26}{Convenience assignment to extract attributes of the layer element.} +\docline{27-29}{Compute total layer width.} +\docline{31}{Create \tw{repeat} number of layers of the same type.} +\docline{32-34}{Create the named envelope volume with a tube shape + containing all slices of this layer.} +\docline{36-51}{Create the different layer-slices with a tube shape and the + corresponding material as indicated in the XML data.} +\docline{43-46}{If the slice is sensitive i.e. is instrumented and supposed to + deliver signals from particle passing, the sensitive detector component of this + detector needs to be attached to the slice.} +\docline{47}{Set visualization and geant4 attributes to the slice volume. + If the attributes are not present, they will be ignored.} +\docline{48}{Now the created slice volume will be placed inside the mother, + the layer envelope at the correct position. This operation results + in the creation of a \tw{PlacedVolume}.} +\docline{49}{It identify uniquely every slice within the layer an identifier + (here the number of the created slice) is attached. This identifier + must be present in the + bitmap defined by the \tw{IDDescriptor} of this subdetector.} +\docline{52-55}{Same as 47-49, but now the created layer volume is placed + in the envelope of the entire subdetector.} +\docline{60}{Set envelope attributes.} +\docline{62}{Construct the main detector element of this subdetector. + This will be the unique entry point to access any information of the subdetector.\\ + {\bf{Note:}} the subdetector my consist of a hierarchy of detector elements. + For example each layer could be described by it's own \tw{DetElement} and all + layer-\tw{DetElement} instances being children of the subdetector instance. + } +\docline{63-64}{Place the subdetector envelope into its mother + (typically the top level (world) volume).} +\docline{65-66}{Add the missing \tw{IDDescriptor} identifiers to complete the bitmap.} +\docline{67}{Store the placement in the subdetector detector + element in order to make it availible to later clients of this \tw{DetElement}.} +\end{tabular} +\newpage +\begin{tabular} {l||p{0cm}} +\docline{Line}{} +\docline{68-72}{Endcap calorimeters typically are symmetric i.e. an + endcap is located on each side of the barrel. To easy such + reflections the entire endcap structure + can be copied and placed again. } +\docline{73}{All done. Return the created subdetector element to the caller for registration.} +\docline{76}{{\bf Very important:}Without the registration of the construction + function to the framework, the corresponding plugin will not be found. + The macro has two arguments: firstly the plugin name which is identical to the + detector type in the XML snippet and secondly the function to be called + at construction time.} +\end{tabular} + +%============================================================================= +\subsection{Tools} +\subsubsection{Volume Manager} +%============================================================================= +\noindent +The \tw{VolumeManager} is a tool to seek a lookup table of placements of +sensitive volumes and their corresponding unique volume identifier, the +\tw{cellID}. The volume manager analyzes - once the geometry is closed - +the hierarchical tree and stores the various placements in the hierarchy +with respect to their identifiers. In other words the the tree is +reused volumes shown e.g. in Figure~\ref{fig:dd4hep-hierarchies} is +degenerated according to the full pathes of the various volumes. This +use case is very common to reconstruction and analysis applications +whenever a given raw-data (aka "hit") element must be related to its +geometrical location. + +\noindent +Figure~\ref{fig:dd4hep-user-manual-volmgr} shows the design diagram of this component: +\begin{figure}[h] + \begin{center} + \includegraphics[width=170mm] {DD4hep-volmgr.png} + \caption{Extensions may be attached to common Detector Elements which + extend the functionality of the common DetElement + class and support e.g. caching of precomputed values.} + \label{fig:dd4hep-user-manual-volmgr} + \end{center} +\end{figure} + +\noindent +To optimize the access of complex subdetector structures, is the volume-identifier +map split and the volumes of each each subdetector is stored in a separate map. +This optimization however is transparent to clients. The following code extract +from the header files lists the main client routines to extract volume information +given a known cellID: +\begin{code} + /// Lookup the context, which belongs to a registered physical volume. + Context* lookupContext(VolumeID volume_id) const; + /// Lookup a physical (placed) volume identified by its 64 bit hit ID + PlacedVolume lookupPlacement(VolumeID volume_id) const; + /// Lookup a top level subdetector detector element + /// according to a contained 64 bit hit ID + DetElement lookupDetector(VolumeID volume_id) const; + /// Lookup the closest subdetector detector element in the hierarchy + /// according to a contained 64 bit hit ID + DetElement lookupDetElement(VolumeID volume_id) const; + /// Access the transformation of a physical volume to the world coordinate system + const TGeoMatrix& worldTransformation(VolumeID volume_id) const; +\end{code} + +%============================================================================= +\subsubsection{Geometry Visualization} +\label{sec:dd4hep-manual-geometry-visualization} +%============================================================================= +\noindent +Visualizing the geometry is an important tool to debug and validate +the constructed detector. +Since \DDhep uses the \tw{ROOT} geometry package, all visualization tools +from ROOT are automatically supported. This is in the first place the +OpenGL canvas of \tw{ROOT} and all elaborated derivatives thereof such as +event displays etc. Figure~\ref{fig:dd4hep-user-manual-visualization-subdetector} +shows as an example the subdetector example from the \tw{SiD} detector design +discussed in section~\ref{sec:dd4hep-manual-detector-constructors}. +\begin{figure}[h] + \begin{center} + \begin{tabular}{l r} + \includegraphics[width=80mm] {DD4hep-Lumical.png} & + \includegraphics[width=80mm] {DD4hep-Lumical-detailed.png} \\ + \end{tabular} + \caption{Geometry visualization using the ROOT OpenGL plugin. + To the left the entire luminosity calorimeter is shown, + at the right the detailed zoomed view with clipping to + access the internal layer and slice structure.} + \label{fig:dd4hep-user-manual-visualization-subdetector} + \end{center} +\end{figure} + +\noindent +The command to create the display is part of the DD4hep release: +\begin{code} +$> geoDisplay -compact <path to the XML file containing the detector description> + + +geoDisplay -opt [-opt] + -compact <file> Specify the compact geometry file + [REQUIRED] At least one compact geo file is required! + -load_only [OPTIONAL] Dry-run to only load geometry without + starting the dispay. +\end{code} + +%============================================================================= +\subsubsection{Geometry Conversion} +\label{sec:dd4hep-manual-geometry-conversion} +%============================================================================= +\noindent +\tw{ROOT} \tw{TGeo} is only one representation of a detector geometry. +Other applications may require other representation. In particular two other +are worth mentioning: +\begin{itemize}\itemcompact +\item \tw{LCDD}~\cite{bib:LCDD} the geometry representation used to + simulate the ILC detector design with the \tw{slic} application. +\item \tw{GDML}~\cite{bib:GDML} a geometry markup language understood + by Geant4 and \tw{ROOT}. +\end{itemize} +Both conversions are supported in \DDhep with the geoConverter application: +\begin{code} + geoConverter -opt [-opt] + Action flags: Usage is exclusive, 1 required! + -compact2lcdd Convert compact xml geometry to lcdd. + -compact2gdml Convert compact xml geometry to gdml. + -compact2vis Convert compact xml to visualisation attrs + + -input <file> [REQUIRED] Specify input file. + -output <file> [OPTIONAL] Specify output file. + if no output file is specified, the output + device is stdout. + -ascii [OPTIONAL] Dump visualisation attrs in csv format. + [Only valid for -compact2vis] +\end{code} + +%============================================================================= +\newpage +\begin{thebibliography}{9} +\input{DD4hep-bibliography.tex} +\bibitem{bib:DDSegmentations} C.Grefe et al., + "The DDSegmentation package", + Non existing documentation to be written. +\end{thebibliography} +%============================================================================= +\end{document} diff --git a/doc/LaTex/DD4hepPaper.tex b/doc/LaTex/DD4hepPaper.tex new file mode 100644 index 0000000000000000000000000000000000000000..85462cfe2f19d16478c820acf25eab617656e561 --- /dev/null +++ b/doc/LaTex/DD4hepPaper.tex @@ -0,0 +1,34 @@ +\documentclass[a4paper]{jpconf} +\usepackage{graphicx} + +\begin{document} +\title{ +\vspace{-3cm}.\\ +DD4hep: A Detector Description Toolkit \\ +for High Energy Physics Experiments} + +\author{ +M.Frank\textsuperscript{1}, +F.Gaede\textsuperscript{2}, +C.Grefe\textsuperscript{1}, +P.Mato\textsuperscript{1} +} + +\address{\textsuperscript{1} CERN, 1211 Geneva 23, Switzerland} +\address{\textsuperscript{2} Desy, 22607 Hamburg, Germany} + +\ead{Markus.Frank@cern.ch} + +\begin{abstract} +\input{DD4hep-abstract.tex} +\end{abstract} + +\input{DD4hep-Overview.tex} + +\vspace{-0.1cm} +\section*{References} +\begin{thebibliography}{9} +\input{DD4hep-bibliography.tex} +\end{thebibliography} + +\end{document} \ No newline at end of file diff --git a/doc/LaTex/DD4hep_big_picture.png b/doc/LaTex/DD4hep_big_picture.png new file mode 100644 index 0000000000000000000000000000000000000000..3a679926594bb23b38497f7874ab1efab8eadb8d Binary files /dev/null and b/doc/LaTex/DD4hep_big_picture.png differ diff --git a/doc/LaTex/DD4hep_classes.png b/doc/LaTex/DD4hep_classes.png new file mode 100644 index 0000000000000000000000000000000000000000..0bbe6d59611387a4b2d8fe1a2813e6d238504b33 Binary files /dev/null and b/doc/LaTex/DD4hep_classes.png differ diff --git a/doc/LaTex/DD4hep_compact_xml.png b/doc/LaTex/DD4hep_compact_xml.png new file mode 100644 index 0000000000000000000000000000000000000000..0d8b9ee9767f4d552ca2cb5b5b682b4158982aab Binary files /dev/null and b/doc/LaTex/DD4hep_compact_xml.png differ diff --git a/doc/LaTex/DD4hep_detelement_tree.png b/doc/LaTex/DD4hep_detelement_tree.png new file mode 100644 index 0000000000000000000000000000000000000000..4f7b71bc339850443a9a32ad14bae9bff4d8d068 Binary files /dev/null and b/doc/LaTex/DD4hep_detelement_tree.png differ diff --git a/doc/LaTex/DDAlign-iterative-misalignment.png b/doc/LaTex/DDAlign-iterative-misalignment.png new file mode 100644 index 0000000000000000000000000000000000000000..85bedfb30959c3c12dc37fc4e22fcc76fc177922 Binary files /dev/null and b/doc/LaTex/DDAlign-iterative-misalignment.png differ diff --git a/doc/LaTex/DDAlign-misaligned-TPC.png b/doc/LaTex/DDAlign-misaligned-TPC.png new file mode 100644 index 0000000000000000000000000000000000000000..fefe093521ec5323aead12f407187d6a63ba83f0 Binary files /dev/null and b/doc/LaTex/DDAlign-misaligned-TPC.png differ diff --git a/doc/LaTex/DDAlignManual.0.tex b/doc/LaTex/DDAlignManual.0.tex new file mode 100644 index 0000000000000000000000000000000000000000..fd9cf5635649925ad5ab90e25232aa4e327d4d7e --- /dev/null +++ b/doc/LaTex/DDAlignManual.0.tex @@ -0,0 +1,743 @@ +%============================================================================= +\documentclass[10pt,a4paper]{article} +% +\input{DD4hep-setup.tex} +% +\pagestyle{fancyplain}{\fancyfoot[C]{\sffamily{DDAlign User Manual}}} +% +\begin{document} +% +\mytitle{ +DDAlign +}{ +Alignment Support for the \\ +\vspace{0.5cm} +DD4hep Geometry Description \\ +\vspace{0.5cm} +Toolkit +\vspace{2cm} +}{DDAlign User Manual} +% +% +%== Abstract =============================================================== +\pagestyle{plain} +\pagenumbering{Roman} +\setcounter{page}{1} +\begin{abstract} +%============================================================================= + +\noindent +\normalsize +Experimental setups in High Energy Physics are highly complex assemblies +consisting of various detector devices typically called {\it{subdetectors}}. +Contrary to the ideal world, where all these components are of perfect shape +and at exact positions, existing devices have imperfections both in their +shape and their relative and absolute positions.\\ +To still measure the detector response from particle collisions with the highest +possible precision, these imperfections are taken into account when converting +measured signals to space-points in the measurement devices. This procedure +is called {\it{detector alignment}}. \DDhep does not want to solve the exact +problem of the detector alignment itself, but rather support firstly algorithms +determining the imperfections and secondly support the application of the +measured imperfection to the ideal geometry for further event data processing.\\ +We will present the tools to support the detector alignment procedures using +the \DDhep detector description toolkit. +The \DDA toolkit implements a modular and flexible approach to introduce and +access the imperfections.\\ +The design is strongly driven by easy of use; +developers of detector descriptions and applications using +them should provide minimal information and minimal specific +code to achieve the desired result. + +\end{abstract} + +\vspace{8cm} + +\begin{center} +{\large{\bf{ +\begin{tabular} {| l | l | l |} +\hline +\multicolumn{3}{| c |}{} \\[0.2cm] +\multicolumn{3}{| c |}{Document History} \\[0.2cm] +\multicolumn{3}{| c |}{} \\[0.2cm] +\hline + & & \\ +Document & & \\ +version & Date & Author \\[0.2cm] \hline + & & \\ +1.0 & 1/4/2014 & Markus Frank CERN/LHCb \\ + & & \\ \hline +\end{tabular} +}}} +\end{center} + +\clearpage +% +% +%== TOC ==================================================================== +\tableofcontents +\clearpage +% +% +%============================================================================= +% Manual +%============================================================================= +\pagenumbering{arabic} +\setcounter{page}{1} + +%============================================================================= +\section{Introduction} +\label{sec:ddalign-user-manual-introduction} +%============================================================================= +\noindent +This manual should introduce to the \DDA framework. +One goal of \DDA is to easily model geometrical imperfections applied to +the ideal geometry of detection devices as they are typically used in +high energy physics experiments. + +\noindent +\DDA formalizes both the access and the application of geometrical imperfection +to the ideal geometry. In this manual we will shortly describe the model used +to describe an experiments detector description and then in more detail +document the support for alignment with its programming interfaces. + +%============================================================================= +\begin{figure}[h] + \begin{center} + \includegraphics[height=90mm] {DD4hep_classes.png} + \caption{Class diagram with the main classes and their relations + for the Generic Detector Description Model. The implementing + ROOT classes are shown in brackets.} + \label{fig:dd4hep-detector-model} + \end{center} +\end{figure} +\vspace{-0.5cm} +%============================================================================= +\subsection{Generic Detector Description Model} +\label{subsec:generic-model} +%============================================================================= + +\noindent +This is the heart of the DD4hep detector description toolkit. Its purpose is +to build in memory a model of the detector including its geometrical aspects +as well as structural and functional aspects. The design reuses the elements +from the ROOT geometry package and extends them in case required functionality +is not available. Figure~\ref{fig:dd4hep-detector-model} illustrates the main +players and their relationships. +Any detector is modeled as a tree of $Detector$ $Elements$, the entity +central to this design, which is represented in the implementation by +the $DetElement$ class~\cite{bib:LHCb-geometry}. It offers all +applications a natural entry point to any detector part of the experiment +and represents a complete sub-detector (e.g. TPC), a part of a +sub-detector (e.g. TPC-Endcap), a detector module or any other convenient +detector device. +The main purpose is to give access to the data associated +to the detector device. For example, if the user writes some TPC reconstruction +code, accessing the TPC detector element from this code will provide access +the all TPC geometrical dimensions, the alignment and calibration constants +and other slow varying conditions such as the gas pressure, end-plate +temperatures etc. The $Detector$ $Element$ acts as a data concentrator. +Applications may access the full experiment geometry and all connected data +through a singleton object called $LCDD$, which provides +management, bookkeeping and ownership to the model instances. + +\noindent +The geometry is implemented using the ROOT geometry classes, which are used +directly without unnecessary interfaces to isolate the end-user from the +actual ROOT based implementation. +\DDA allows client to access and manage imperfections or smallish changes +to this geometry. The mechanism to achieve this is described in the following. + +%============================================================================= +\begin{figure}[t] + \begin{center} + \includegraphics[height=75mm] {DD4hep_detelement_tree.png} + \caption{The object diagram of a hypothetical TPC detector showing in + parallel the $Detector$ $Element$ and the $Geometry$ hierarchy and the + relationships between the objects.} + \label{fig:dd4hep-hierarchies} + \end{center} + \vspace{-0.5cm} +\end{figure} +%============================================================================= +\subsection{Detector Element Tree and the Geometry Hierarchy} +\label{subsect:detelement-hierarchy} +%============================================================================= +\noindent +The geometry part of the detector description is delegated to the ROOT classes. +$Logical$ $Volumes$ are the basic objects used in building the geometrical hierarchy. +A $Logical$ $Volume$ is a shape with its dimensions and consist of a given material. +They represent unpositioned objects which store all information about +the placement of possibly embedded volumes. The same +volume can be replicated several times in the geometry. The $Logical$ $Volume$ also +represents a system of reference with respect to its containing volumes. +The reuse of instances of $Logical$ $Volumes$ for different placements +optimizes the memory consumption and detailed geometries for complex setups +consisting of millions of volumes may be realized with reasonable amount of memory. +The difficulty is to identify a given positioned volume +in space and e.g. applying misalignment to one of these volumes. +The relationship between the Detector Element and the placements +is not defined by a single reference to the placement, but the full path +from the top of the detector geometry model to resolve existing +ambiguities due to the reuse of $Logical$ $Volumes$. +Hence, individual volumes must be identified by their full path from mother +to daughter starting from the top-level volume. + +\noindent +The tree structure of +Detector Elements is a parallel structure to the geometrical hierarchy. +This structure will probably not be as deep as the geometrical one since +there would not need to associate detector information at very fine-grain +level - it is unlikely that every little metallic screw +needs associated detector information such as alignment, conditions, etc. +Though this screw and many other replicas must be described in the geometry +description since it may be important e.g. for its material contribution +in the simulation application. Thus, the tree of Detector Elements is +fully degenerate and each detector element object will be placed only +once in the detector element tree as illustrated for a hypothetical +Time Projection Chamber (TPC) detector in +Figure~\ref{fig:dd4hep-hierarchies} with an ideal geometry, +where no positioning corrections are applied to neither child. It is essential to +realize that the geometry tree in an ideal geometry is degenerate contrary +to the tree of detector elements. + +%============================================================================= +\begin{figure}[h] + \begin{center} + \includegraphics[width=160mm] {DDAlign_detelement_aligned_tree.png} + \caption{The object diagram of a hypothetical TPC detector showing in + parallel the $Detector$ $Element$ and the $Geometry$ hierarchy and examples + of mispositioned detector parts: (a) mispositioned entire subdetector + (translation), (b) mispositioned end-cap (tilt) and (c) mispositioned + individual sectors within one endcap.} + \label{fig:dd4hep-aligned-hierarchies} + \end{center} +\end{figure} +%============================================================================= +\subsection{Geometrical Imperfection of Detector Components} +\label{subsect:ddalign-intro-aligments} +%============================================================================= +\noindent +Imperfections never apply in the same way to {\it{all}} placements of the +same volume in this hierarchy. Hence, to (re-)align a volume in the hierarchy +means to lift a full branch of placements from the top volume down to +the element to be (re-)aligned out of this shared hierarchy and apply +a correction matrix to the last node. This procedure is illustrated in +Figure~\ref{fig:dd4hep-aligned-hierarchies}. Re-alignment of volumes may occur +at any level. In the above example of a TPC this results in the following effects: + +\noindent +\begin{itemize}\itemcompact +\item A realignment of the entire subdetector, i.e. the TPC as a whole, + would affect consequently move all contained children with respect to the + top level coordinate system. An example is shown in + Figure~\ref{fig:dd4hep-aligned-hierarchies} (a). A movement of the subdetector + would affect all transformation between local coordinates of any part of the + subdetector to the top level coordinate system. Such effects would be visible + at all stages of the data processing e.g. when translating signals from + particles into global coordinates. +\item A realignment of parts of a subdetector affects only the partial subdetector + itself and child volumes at lower levels. As in the example, where the entire + subdetector is moved, here only the sectors on one side of the TPC would be affected + as shown in Figure~\ref{fig:dd4hep-aligned-hierarchies} (b). +\item In Figure~\ref{fig:dd4hep-aligned-hierarchies} (c) within one end-cap of the TPC + individual sectors may not be positioned at the ideal location + (Figure~\ref{fig:dd4hep-aligned-hierarchies} (c) exaggerates: + ''flying sectors'' are a rather rare case in reality). + Finally also the sectors itself could be fragmented and be assemblies of other + shapes, which are not ideally placed and may need correction. +\end{itemize} +The origin of the volume misplacements may be many-fold: +\begin{itemize}\itemcompact +\item Elements may be weak and assembled parts move due to weak support structures. + This is a common problem e.g. for tracking detectors, where heavy and solid + structures dramatically influence the measurement result. + Misplaced sectors could e.g. be the consequence of a deforming end-cap frame due + to the weight of the sectors. +\item Environmental conditions such as the temperature may influence the + position or the shape of a volume. +\item Some of the measurement equipment may be moved from a parking position into + a data taking position such as the two halves of the LHCb vertex detector. + Whereas the position of the sensors on each half are known to a very high + precision, the position of the absolute position of the two halves with respect + to the full experiment may change after each movement. +\end{itemize} +All effects resulting from such causes obviously need to be corrected in order to +fully explore the capabilities of the detection devices and to minimize +measurement errors. In general any deviation from the ideal position of a volume +can be described by two elementary transformations: +\begin{itemize}\itemcompact +\item a translation +\item a rotation around a pivot point. +\end{itemize} +giving a full transformation matrix of the form: +\begin{equation} +T = L * P * R * P^{-1} +\end{equation} +where +\begin{itemize}\itemcompact +\item $T$ is the full transformation in 3D space containing the change to the +exiting placement transformation. The existing placement is the placement +transformation of the volume with respect to the mother volume. +\item $L$ is a translation specifying the position change with respect to the + mother volume. +\item $P * R * P^{-1}$ describes a rotation around a pivot point specified + int he mother volume's coordinate system. +\item $P$ is the translation vector from the mother volumes origin to the + pivot point. +\end{itemize} +Most of the changes do not require the full set of parameters. Very often +the changes only require the application of only a translation, only a rotation +or both with a pivot point in the origin. These simplifications are supported +in the user interface described in +Section~\ref{sec:ddalign-user-manual-ddalign-interface}. + +%============================================================================= +\begin{figure}[t] + \begin{center} + \includegraphics[width=160mm] {DDAlign-iterative-misalignment.png} + \caption{The iterative application of geometry imperfections as described + in Section~\ref{subsect:ddalign-intro-iterative-alignments}. + For each interval of validity ($[T_0,T_1]$, $[T_2,T_3]$, $[T_4,T_5]$, ...) + a seperate set of alignment constants is applied to the ideal geometry. + The two steps to reset the misaligned geometry back to the ideal geometry and + to re-apply a new set of alignment constants may be executed as + often as necessary when processing data from particle collisions.} + \label{fig:ddalign-aligned-iterative} + \end{center} +\end{figure} + +\newpage +%============================================================================= +\subsection{Iterative Application of Alignments} +\label{subsect:ddalign-intro-iterative-alignments} +%============================================================================= +\noindent +In the general case geometrical imperfections are not static and may very +well change with time. For this reason it is highly important to support +not only one single realignment step. +Hence, the following scenario is an important use case: +\begin{enumerate}\itemcompact +\item Create the ideal detector using an ideal geometry. +\item Apply the misalignment for a given time interval corresponding to the + time a set of particle collisions were collected in the experiment. +\item Process the set of collected particle collisions. +\item Reset the misaligned detector to the ideal. +\item Choose new event data input corresponding to another time interval + and restart at item 2. +\end{enumerate} +Graphically this use case is illustrated in +Figure~\ref{fig:ddalign-aligned-iterative}. In +Section~\ref{sec:ddalign-user-manual-ddalign-interface} the implementation +to realize this use case is described. + +\newpage +%============================================================================= +\section{The DDAlign User Interface} +\label{sec:ddalign-user-manual-ddalign-interface} +%============================================================================= + +\noindent +\DDA implements a machinery to apply and access geometrical imperfections +describing the difference between an ideal detector given by an ideal geometry +and the geometry of the actually built assembly in real life. +To ease its usage for the clients and to shield clients from the +internals when actually dealing with realigned geometries, a set of +helper classes was designed. The access to the imperfections +in read-only mode was separated from the import or export thereof. + +\noindent +As a basic concept within \DDhep any {\it{sizable}} detector component +can be realigned. {\it{Sizable}} as a rule of thumb is anything, which +is manufactured as an individual piece and which you may ''hold in your hands''. +Such objects are also described by a $detector$ $element$ of type {\tt DetElement}. +An example is e.g. a single silicon wafer of a tracking device or the entire +tracking detector itself. +The access to the geometry imperfections is possible from each {\tt DetElement} +instance as described in Section~\ref{sec:ddalign-user-manual-misalignment-access} + +\noindent +Please be aware that the extensive use of misalignments is highly memory +consuming. + +\noindent +%============================================================================= +\subsection{Access to Geometrical Imperfections from the Detector Element} +\label{sec:ddalign-user-manual-misalignment-access} +%============================================================================= + +\noindent +The $DetElement$ class as shown in Figure~\ref{fig:dd4hep-detector-model} +gives the user access to the alignment structure of type $Alignment$ as +illustrated in the following example: +\begin{code} + DetElement wafer = ... // Valid handle to a detector element + Alignment wafer_alignment = wafer.alignment(); + if ( wafer_alignment.isValid() ) { + // This wafer's placement differs from the ideal geometry and + // imperfections are present. + + // Access the misalignment transformation with respect to the parent volume: + Transform3D tr = wafer_alignment.toMotherDelta(); + } +\end{code} +The access to details of an invalid alignment object results in a runtime +exception. The full interface of the $Alignment$ structure to access detector imperfections +is as follows: +\begin{code} + /// Number of nodes in this branch (=depth of the placement hierarchy from the top level volume) + int numNodes() const; + /// Access the placement of this node + PlacedVolume placement() const; + /// Access the placement of the mother of this node + PlacedVolume motherPlacement(int level_up = 1) const; + /// Access the placement of a node in the chain of placements for this branch + PlacedVolume nodePlacement(int level=-1) const; + /// Access the currently applied alignment/placement matrix with respect to the world + Transform3D toGlobal(int level=-1) const; + /// Transform a point from local coordinates of a given level to global coordinates + Position toGlobal(const Position& localPoint, int level=-1) const; + /// Transform a point from global coordinates to local coordinates of a given level + Position globalToLocal(const Position& globalPoint, int level=-1) const; + /// Access the currently applied alignment/placement matrix with respect to mother volume + Transform3D toMother(int level=-1) const; + /// Access the currently applied alignment/placement matrix (mother to daughter) + Transform3D nominal() const; + /// Access the currently applied correction matrix (delta) (mother to daughter) + Transform3D delta() const; +\end{code} +\begin{itemize}\itemcompact +\item The calls in line 3-8 allow access to the relative position of the $nth.$ element + in the alignment stack with respect to its next level parent. + Element $numNodes()-1$ denotes the lowest level and element $0$ is the world + volume. The default argument $(-1)$ addresses the lowest placement in the hierarchy. +\item Calls in line 9-12 allow to access/execute transformations from a given level + in the placement hierarchy to coordinates in the top level volume (world). +\item The call in line 14 allows to transform a global coordinate to the local coordinate + system in a given level of the hierarchy. +\item The call $toMother$ in line 16 returns the local transformation of the node at + a given level to the mother's coordinate system. +\item The calls in line 17-20 give access to the nominal placement matrix of the realigned + node with respect to the parent volume and the changes thereof. +\end{itemize} +Besides these convenience calls the full interface to the class {\tt TGeoPhysicalNode}, +which implements in the ROOT geometry package alignment changes, is accessible +from the $Alignment$ handle using the overloaded $operator->()$. +Further documentation is available directly from the \tgeo{TGeoPhysicalNode}{ROOT site}. + +\noindent +%============================================================================= +\subsection{Manipulation of Geometrical Imperfections} +\label{sec:ddalign-user-manual-misalignment-manip} +%============================================================================= +There are multiple possibilities to apply geometry imperfections: +\begin{itemize}\itemcompact +\item The pedestrian way ''by hand'' using C++ as described in + Subsection~\ref{sec:ddalign-user-manual-misalignment-manip-cxx} +\item Loading a whole set of misalignment constants from XML, the ''poor man's'' database. + This mechanism is described in + Subsection~\ref{sec:ddalign-user-manual-misalignment-manip-xml} +\item Loading a whole set of misalignment constants from a database. + This possibility depends heavily on the database and its schema used. + A typical use case is to load misalignment constants depending on the + experiment conditions at the time the event data were collected. + \DDA does not provide an implementation. + This possibility here is only mentioned for completeness and will be subject + to further developments to support conditions in \DDhep. +\end{itemize} + +\noindent +%============================================================================= +\subsubsection{Manipulation of Geometrical Imperfections for Pedestrians using C++} +\label{sec:ddalign-user-manual-misalignment-manip-cxx} +%============================================================================= +\noindent +In this section we describe how to apply geometry imperfections to an existing +detector geometry in memory using {\tt C++}. To apply misalignment to an existing +geometry two classes are collaborating, the {\tt AlignmentCache} attached to +the geometry container {\tt LCDD} and a temporary structure the {\tt AlignmentStack}. +The {\tt AlignmentCache} allows to access all existing alignment entries +based on their subdetector. +The {\tt AlignmentStack} may exist in exactly one instance and is used to +insert a consistent set of alignment entries. Consistency is important because +changes may occur at any hierarchical level and internal transformation caches +of the ROOT geometry package must be revalidated for all branches containing +a higher level node. +{\bf For this reason it is highly advisable to apply realignment constants +for a complete subdetector.} +Note that this restriction is not imposed, in principle a consistent set +of misalignments may be applied at any level of the geometry hierarchy. + +\noindent +Though the application of alignment is much simpler using XML files, the following +description should give an insight on the mechanisms used behind the scene and +to understand the concept. + +\noindent +Any manipulations are transaction based must be embraced by the following two calls +opening and closing a transaction: +\begin{code} +// Required include file(s) +#include "DDAlign/AlignmentCache.h" + + LCDD& lcdd = ....; + AlignmentCache* cache = lcdd.extension<Geometry::AlignmentCache>(); + + // First things first: open the transaction. + cache->openTransaction(); + + // Prepare the entry containing the alignment data + AlignmentStack::StackEntry* entry = .....; + //.... and add the element to the AlignmentStack ..... + AlignmentStack::insert(entry); + + // Finally close the transaction. At this moment the changes are applied. + cache->closeTransaction(); +\end{code} +In the following we describe the mechanism to create and prepare the +{\tt StackEntry} instances of the above code snippet. The calls to open and close +the alignment transaction do not have to be in the same code fragment where also +the alignment entries are prepared. However, all changes are only applied when +the transaction is closed. The alignment entries do not necessarily have to +be prepared in the sequence of the hierarchy they should be applied, internally +the entries are re-ordered and follow the geometry hierarchy top to bottom +i.e. mother volumes are always re-aligned {\it\bf before} the daughters +are re-aligned. + +\noindent +The {\tt StackEntry} instances carry all information to apply the re-alignment +of a given volume. This information contains: +\begin{itemize}\itemcompact +\item The transformation matrix describing the positional change of the volume + with respect to its mother volume. +\item The placement path of the volume to be realigned. +\item A flag to reset the volume to its ideal position {\it\bf before} the + change is applied. +\item A flag to also reset all daughter volumes to their + ideal position {\it\bf before} the change is applied. +\item A flag to check for overlaps after the application of the change and +\item the actual precision used to perform this check. +\end{itemize} + +\noindent +The {\tt ROOT::Math} library provides several ways to construct the required +3D transformation as described in Section~\ref{subsect:ddalign-intro-aligments}: +\begin{code} +// Required include file(s) +#include "DD4hep/Objects.h" + + Position trans(x_translation, y_translation, z_translation); + RotationZYX rot (z_angle, y_angle, x_angle); + Translation3D pivot(x_pivot, y_pivot, z_pivot); + + Transform3D trafo; + /// Construct a 3D transformation for a translation and a rotation around a pivot point: + trafo = Transform3D(Translation3D(trans)*pivot*rot*(pivot.Inverse())); + + /// Construct a 3D transformation for a translation and a rotation around the origin + trafo = Transform3D(rot,pos); + + /// Construct a 3D transformation for a rotation around a pivot point + trafo = Transform3D(piv*rot*(piv.Inverse())); + + /// Construct a 3D transformation for a rotation around the origin + trafo = Transform3D(rot); + + /// Construct a 3D transformation for simple translation + trafo = Transform3D(pos); + +\end{code} + +\noindent +The following code snippet shows how to extract this information from the +{\tt DetElement} and prepare such a {\tt StackEntry} instance: +\begin{code} +// Required include file(s) +#include "DDAlign/AlignmentStack.h" + + // Prepare the entry containing the alignment data + typedef AlignmentStack::StackEntry Entry; + /// Detector element to be realigned + DetElement element = ...; + /// The transformation describing the relative change with respect to the mother volume + Transform3D trafo = ...; + /// Instantiate a new alignment entry + Entry* entry = new Entry(element); + entry->setTransformation(trafo) // Apply the transformation matrix + .applyReset(/* argument default: true */) // Set the reset flag + .applyResetChildren(/* argument default: true */) // Set the daughter reset flag + .checkOverlaps(/* argument default: true */) // Set flag to check overlaps + .overlapPrecision(0.001/mm); // With this precision in mm + + /// Now add the entry to the alignment stack: + AlignmentStack::insert(entry); +\end{code} +The constructor will automatically determine the volumes placement path +from the {\tt DetElement}. Then the transformation is applied and the flags +to reset the volume, its children and to trigger the overlap checks with +the given precision. + +\noindent +When passing the entry to the {\tt AlignmentStack} the {\tt AlignmentStack} +takes ownership and subsequently the entry is deleted after being applied to +the geometry. For further shortcuts in the calling sequence please consult the +{\tt AlignmentStack} header file. + + +\noindent +%============================================================================= +\subsubsection{Loading Geometrical Imperfections from XML} +\label{sec:ddalign-user-manual-misalignment-manip-xml} +%============================================================================= +\noindent +In this section we describe how to load geometry imperfections and to apply them +to an existing geometry. Loading the XML file is done automatically using the +standard XML loader plugin provided by \DDhep. This plugin is interfaced to +the {\tt LCDD} instance and invoked from code as follows: +\begin{code} + LCDD& lcdd = ....; + lcdd.fromXML("file:AlepTPC_alignment.xml"); +\end{code} +To fully exploit the capabilities it is important to understand the interpreted +structure of the XML file being processed. At the top level of the primary +input file (i.e. the file given to the XML processor) the following structure +is expected: +\begin{code} +<alignment> + <!-- Open the alignment transaction --> + <open_transaction/> + <subdetectors> <!-- Container with the list of subdetectors to be processed. --> + <detelement path="TPC" reset="true" reset_children="true"> + <!-- Move the entire TPC in the world volume --> + <position="" x="30" y="30" z="80"/> + + <!-- Now add daughter detector elements --> + + <!-- Twist a bit the entire endcap by rotating it around the x and the y axis --> + <detelement path="/world/TPC/TPC_SideA" check_overlaps="false"> + <position x="0" y="0" z="0"/> + <rotation x="-0.2" y="-0.2" z="0"/> + <!-- Apply corrections of type Translation*Rotation to a single sector + <detelement path="TPC_SideA_sector02" check_overlaps="true"> + <position x="0" y="0" z="0"/> + <rotation x="0.5" y="0.1" z="0.2"/> + </detelement> + </detelement> + + <!-- And the full shooting match of transformations for this sector --> + <detelement path="TPC_SideA/TPC_SideA_sector03" check_overlaps="true"> + <position x="0" y="0" z="290.0*mm"/> + <rotation x="0" y="pi/2" z="0"/> + <pivot x="0" y="0" z="100"/> + </detelement> + + .... + + <!-- Include alignment files to be processed in the context of the "TPC" DetElement + <include ref="file-name"/> + + </detElement> + </subdetectors> + + <!-- Include alignment files to be processed at the top level context --> + <include ref="file-name"/> + + <!-- Close the alignment transaction --> + <close_transaction/> +</alignment> +\end{code} +The specification of any transformation element is optional: +\begin{itemize}\itemcompact +\item The absence of a translation implies the origin (0,0,0) +\item The absence of a pivot point implies the origin (0,0,0) +\item The absence of a rotation implies the identity rotation. + Any supplied pivot point in this case is ignored. +\end{itemize} + +\noindent +The structure of the alignment file explained quickly: + +\noindent +\begin{tabular} {l||p{0cm}} +\docline{Line}{} +\docline{1}{The {\tt root} tag for the primary alignment file is {\tt <alignment/>}. + The primary tag name is mandatory and actually is used to invoke the correct interpreter.} +\docline{2,41}{Trigger the alignment transaction by specifying the transaction tags in + the main XML file.} +\docline{4}{Defintion of the set of {\tt subdetectors} to be processed. A valid alias for this + directove is {\tt detelements}.} +\docline{5}{The first subdetector: {\tt TPC}. The subdetector tag is {\tt detelement} + Each {\tt detelement} may recursively contain other {\tt detelement} tags. + as they were defined in the {\tt DetElement} hierarchy. + Internal {\tt detelement} elements are processed in the context of the outer + element i.e. pathes may be specified relative to the parent or as absolute pathes + with respect to the world (starting with a '/').} +\docline{7}{Global movement of the TPC} +\docline{12-20}{Realignment entry for the TPC endcap A named {\tt TPC\_SideA}} +\docline{16-19}{Realignment entry for sector named {\tt TPC\_SideA\_sector02} of the TPC endcap A. + Here the sector is specified directly as a daughter of the endcap. The name + of the {\tt DetElement} is relative to the parent.} +\docline{23-27}{Realignment entry for sector named {\tt TPC\_SideA\_sector03} of the TPC endcap A + containing a full transformation: $Translation * Pivot * Rotation * Pivot^{-1}$} +\docline{32}{Optionally {\tt detelement} elements may include other alignment files specifying + lower volume levels. These files are interpreted in the context of the calling + detector element. } +\docline{38}{Optionally the subdetector alignment constants may be fragmented + into several files, which can be loaded using the {\tt include} + directive. Each file could for example describe one single detector.} +\end{tabular} + +\newpage +\noindent +Included files may directly start with the {\tt root} tags {\tt subdetectors}, +{\tt detelements} or {\tt detelement} and may recursively include other +files. Except for the top level these files are processed in the calling context. + +\vspace{1cm} +\noindent +And finally, the result: +%============================================================================= +\begin{figure}[h] + \begin{center} + \includegraphics[width=160mm] {DDAlign-misaligned-TPC.png} + \caption{The ALEPH TPC after the import of the alignment file.} + \label{fig:dd4hep-aligned-hierarchies} + \end{center} +\end{figure} + + +\noindent +%============================================================================= +\subsubsection{Export Geometrical Imperfections to XML} +\label{sec:ddalign-user-misalignment-expotr-xml} +%============================================================================= +\noindent +In this section we describe how to export geometry imperfections to an XML file. +A small helper class {\tt AlignmentWriter} achieves this task as shown in +the snippet: +\begin{code} + LCDD& lcdd = ....; + DetElement top = ....; + if ( top.isValid() ) { + AlignmentWriter wr(lcdd); + return wr.write(top,output,enable\_transactions); + } +\end{code} +This code will dump all alignment constants contained in the {\tt DetElement} +hierarchy of {\tt top} to the output file {\tt output}. The optional argument +{\tt enable\_transactions} (default: true) will add the tags +{\tt <open\_transaction/>} and {\tt <close\_transaction/>} to the output +file. The output file conforms to the specifications described in +Section~\ref{sec:ddalign-user-manual-misalignment-manip-xml} and may later +be imported by another process. + +\newpage +%============================================================================= +\begin{thebibliography}{9} +\bibitem{bib:LHCb-geometry} S. Ponce et al., + "Detector Description Framework in LHCb", + International Conference on Computing in High Energy and Nuclear Physics (CHEP 2003), + La Jolla, CA, 2003, proceedings. +\end{thebibliography} +%============================================================================= +\end{document} diff --git a/doc/LaTex/DDAlignManual.tex b/doc/LaTex/DDAlignManual.tex new file mode 100644 index 0000000000000000000000000000000000000000..2e6421191a5bb60a27d13436a2e564a79476b309 --- /dev/null +++ b/doc/LaTex/DDAlignManual.tex @@ -0,0 +1,930 @@ +%============================================================================= +\documentclass[10pt,a4paper]{article} +% +\input{DD4hep-setup.tex} +% +\pagestyle{fancyplain}{\fancyfoot[C]{\sffamily{DDAlign User Manual}}} +% +\usepackage{amsmath} +\begin{document} +% +\mytitle{ +DDAlign +}{ +Alignment Support for the \\ +\vspace{0.5cm} +DD4hep Geometry Description \\ +\vspace{0.5cm} +Toolkit +\vspace{2cm} +}{DDAlign User Manual} +% +% +%== Abstract =============================================================== +\pagestyle{plain} +\pagenumbering{Roman} +\setcounter{page}{1} +\begin{abstract} +%============================================================================= + +\noindent +\normalsize +Experimental setups in High Energy Physics are highly complex assemblies +consisting of various detector devices typically called {\it{subdetectors}}. +Contrary to the ideal world, where all these components are of perfect shape +and at exact positions, existing devices have imperfections both in their +shape and their relative and absolute positions. These are described by the +alignment parameters.\\ +To still measure the detector response from particle collisions with the highest +possible precision, these imperfections are taken into account when converting +measured signals to space-points in the measurement devices. This procedure +is called {\it{detector alignment}}. \DDhep does not want to solve the exact +problem of the detector alignment itself, but rather support firstly algorithms +determining the alignment parameters and secondly support the application which +apply the measured alignment parameters and apply them to the ideal geometry +for further event data processing.\\ +We will present the tools to support the detector alignment procedures using +the \DDhep detector description toolkit. +The \DDA toolkit implements a modular and flexible approach to introduce and +access the alignment parameters.\\ +The design is strongly driven by easy of use; +developers of detector descriptions and applications using +them should provide minimal information and minimal specific +code to achieve the desired result. + +\end{abstract} + +\vspace{8cm} + +\begin{center} +{\large{\bf{ +\begin{tabular} {| l | l | l |} +\hline +\multicolumn{3}{| c |}{} \\[0.2cm] +\multicolumn{3}{| c |}{Document History} \\[0.2cm] +\multicolumn{3}{| c |}{} \\[0.2cm] +\hline + & & \\ +Document & & \\ +version & Date & Author \\[0.2cm] \hline + & & \\ +1.0 & 01/04/2014 & Markus Frank CERN/LHCb \\ +1.1 & 30/04/2014 & Markus Frank CERN/LHCb \\ + & & \\ \hline +\end{tabular} +}}} +\end{center} + +\clearpage +% +% +%== TOC ==================================================================== +\tableofcontents +\clearpage +% +% +%============================================================================= +% Manual +%============================================================================= +\pagenumbering{arabic} +\setcounter{page}{1} + +%============================================================================= +\section{Introduction} +\label{sec:ddalign-user-manual-introduction} +%============================================================================= +\noindent +This manual should introduce to the \DDA framework. +One goal of \DDA is to easily model geometrical imperfections applied to +the ideal geometry of detection devices as they are typically used in +high energy physics experiments. + +\noindent +To avoid confusion within this document, a few terms need to be defined +with respect to detector alignment: +\begin{itemize}\itemcompact +\item The {\it{ideal geometry}} describes the detector as it was designed. + Such a detector is an utopic object, which can never be realized in terms + of the placement of the individual components as such. +\item The {\it{actual geometry}} describes the real detector in the configuration at + a given time. This includes all the changes i.e. {\it{deltas}} to the + {\it{ideal}} geometry. These changes are also called the + {\it{alignment parameters}}. These parameters typically are only valid + for a defined time interval. +\item {\it{Realignment}} defines the procedure to apply a new set of + temporary {\it{misalignment parameters}} to the ideal geometry. Such a procedure + is applied, if a previously applied set of parameters is no longer valid with + respect to the event data to be processed. In short {\it{realignment}} + is necessary if the {\it{actual geometry}} of the detector is time dependent. +\end{itemize} + +\noindent +\DDA formalizes both the access and the application of alignment parameters +to the ideal geometry. The possibility to properly describe actual geometries +with respect to ideal geometries is essential to understand the detector response +to particle collisions and to connect response of geometrical independent +areas of the experiment e.g. to one single track. + +\noindent +In this manual we will shortly describe the model used +to describe an experiments detector description and then in more detail +document the support for alignment with its programming interfaces. + +%============================================================================= +\begin{figure}[h] + \begin{center} + \includegraphics[height=90mm] {DD4hep_classes.png} + \caption{Class diagram with the main classes and their relations + for the Generic Detector Description Model. The implementing + ROOT classes are shown in brackets.} + \label{fig:dd4hep-detector-model} + \end{center} +\end{figure} +\vspace{-0.1cm} +%============================================================================= +\subsection{Generic Detector Description Model} +\label{subsec:generic-model} +%============================================================================= + +\noindent +This is the heart of the DD4hep detector description toolkit. Its purpose is +to build in memory a model of the detector including its geometrical aspects +as well as structural and functional aspects. The design reuses the elements +from the ROOT geometry package and extends them in case required functionality +is not available. Figure~\ref{fig:dd4hep-detector-model} illustrates the main +players and their relationships~\cite{bib:DD4hep}. +Any detector is modeled as a tree of $Detector$ $Elements$, the entity +central to this design, which is represented in the implementation by +the $DetElement$ class~\cite{bib:LHCb-geometry}. It offers all +applications a natural entry point to any detector part of the experiment +and represents a complete sub-detector (e.g. TPC), a part of a +sub-detector (e.g. TPC-Endcap), a detector module or any other convenient +detector device. +The main purpose is to give access to the data associated +to the detector device. For example, if the user writes some TPC reconstruction +code, accessing the TPC detector element from this code will provide access +the all TPC geometrical dimensions, the alignment and calibration constants +and other slow varying conditions such as the gas pressure, end-plate +temperatures etc. The $Detector$ $Element$ acts as a data concentrator. +Applications may access the full experiment geometry and all connected data +through a singleton object called $LCDD$, which provides +management, bookkeeping and ownership to the model instances. + +\noindent +The geometry is implemented using the ROOT geometry classes, which are used +directly without unnecessary interfaces to isolate the end-user from the +actual ROOT based implementation. +\DDA allows client to access, manage and apply alignment parameters or +smallish changes to the ideal geometry. The mechanism to achieve this +is described in the following. + +%============================================================================= +\begin{figure}[h] + \begin{center} + \includegraphics[height=75mm] {DD4hep_detelement_tree.png} + \caption{The object diagram of a hypothetical TPC detector showing in + parallel the $Detector$ $Element$ and the $Geometry$ hierarchy and the + relationships between the objects.} + \label{fig:dd4hep-hierarchies} + \end{center} + \vspace{-0.5cm} +\end{figure} +%============================================================================= +\subsection{Detector Element Tree and the Geometry Hierarchy} +\label{subsect:detelement-hierarchy} +%============================================================================= +\noindent +The geometry part of the detector description is delegated to the ROOT classes. +$Logical$ $Volumes$ are the basic objects used in building the geometrical hierarchy. +A $Logical$ $Volume$ is a shape with its dimensions and consist of a given material. +They represent unpositioned objects which store all information about +the placement of possibly embedded volumes. The same +volume can be replicated several times in the geometry. The $Logical$ $Volume$ also +represents a system of reference with respect to its containing volumes. +The reuse of instances of $Logical$ $Volumes$ for different placements +optimizes the memory consumption and detailed geometries for complex setups +consisting of millions of volumes may be realized with reasonable amount of memory. +The difficulty is to identify a given positioned volume +in space and e.g. apply alignment parameters to one of these volumes. +The relationship between the Detector Element and the placements +is not defined by a single reference to the placement, but the full path +from the top of the detector geometry model to resolve existing +ambiguities due to the reuse of $Logical$ $Volumes$. +Hence, individual volumes must be identified by their full path from mother +to daughter starting from the top-level volume. + +\noindent +The tree structure of +$Detector$ $Elements$ is a parallel structure to the geometrical hierarchy. +This structure will probably not be as deep as the geometrical one since +there would not need to associate detector information at very fine-grain +level - it is unlikely that every little metallic screw +needs associated detector information such as alignment, conditions, etc. +Though this screw and many other replicas must be described in the geometry +description since it may be important e.g. for its material contribution +in the simulation application. Thus, the tree of Detector Elements is +fully degenerate and each detector element object will be placed only +once in the detector element tree as illustrated for a hypothetical +Time Projection Chamber (TPC) detector in +Figure~\ref{fig:dd4hep-hierarchies} with an ideal geometry, +where no positioning corrections are applied to neither child. It is essential to +realize that the geometry tree in an ideal geometry is degenerate contrary +to the tree of detector elements. + +\noindent +It should be noted, that alignment parameters may be applied to any volume +of the ideal geometry. The alignment only affects the actual position of +a volume it is e.g. irrelevant if the volume is sensitive or not. + +%============================================================================= +\begin{figure}[h] + \begin{center} + \includegraphics[width=160mm] {DDAlign_detelement_aligned_tree.png} + \caption{The object diagram of a hypothetical TPC detector showing in + parallel the $Detector$ $Element$ and the $Geometry$ hierarchy and examples + of mispositioned detector parts: (a) mispositioned entire subdetector + (translation), (b) mispositioned end-cap (tilt) and (c) mispositioned + individual sectors within one endcap.} + \label{fig:dd4hep-aligned-hierarchies} + \end{center} +\end{figure} +%============================================================================= +\subsection{Alignment Parameters of Detector Components} +\label{subsect:ddalign-intro-aligments} +%============================================================================= +\noindent +Alignment parameters never apply in the same way to {\it{all}} placements of the +same volume in this hierarchy. Hence, to (re-)align a volume in the hierarchy +means to lift a full branch of placements from the top volume down to +the element to be (re-)aligned out of this shared hierarchy and apply +a correction matrix to the last node. This procedure is illustrated in +Figure~\ref{fig:dd4hep-aligned-hierarchies}. Re-alignment of volumes may occur +at any level. In the above example of a TPC this results in the following effects: + +\noindent +\begin{itemize}\itemcompact +\item A realignment of the entire subdetector, i.e. the TPC as a whole, + would affect consequently move all contained children with respect to the + top level coordinate system. An example is shown in + Figure~\ref{fig:dd4hep-aligned-hierarchies} (a). A movement of the subdetector + would affect all transformation between local coordinates of any part of the + subdetector to the top level coordinate system. Such effects would be visible + at all stages of the data processing e.g. when translating signals from + particles into global coordinates. +\item A realignment of parts of a subdetector affects only the partial subdetector + itself and child volumes at lower levels. As in the example, where the entire + subdetector is moved, here only the sectors on one side of the TPC would be affected + as shown in Figure~\ref{fig:dd4hep-aligned-hierarchies} (b). +\item In Figure~\ref{fig:dd4hep-aligned-hierarchies} (c) within one end-cap of the TPC + individual sectors may not be positioned at the ideal location + (Figure~\ref{fig:dd4hep-aligned-hierarchies} (c) exaggerates: + ''flying sectors'' are a rather rare case in reality). + Finally also the sectors itself could be fragmented and be assemblies of other + shapes, which are not ideally placed and may need correction. +\end{itemize} +The origin of the volume misplacements may be many-fold: +\begin{itemize}\itemcompact +\item Elements may be weak and assembled parts move due to weak support structures. + This is a common problem e.g. for tracking detectors, where heavy and solid + structures dramatically influence the measurement result. + Misplaced sectors could e.g. be the consequence of a deforming end-cap frame due + to the weight of the sectors. +\item Environmental conditions such as the temperature may influence the + position or the shape of a volume. +\item Some of the measurement equipment may be moved from a parking position into + a data taking position such as the two halves of the LHCb vertex detector. + Whereas the position of the sensors on each half are known to a very high + precision, the position of the absolute position of the two halves with respect + to the full experiment may change after each movement. +\end{itemize} +Changes to the volume placement do not only affect sensitive material i.e. detector +components with an active readout, but also passive material. The placement +of any volume, passive or active, may be corrected using \DDA. The determination +of the alignment parameters of passive components however may be more difficult +in the absence of located signals resulting e.g. from the traversal of a track. + +\noindent +All effects resulting from such causes obviously need to be corrected in order to +fully explore the capabilities of the detection devices and to minimize +measurement errors. In general any deviation from the ideal position of a volume +can be described by two elementary transformations: +\begin{itemize}\itemcompact +\item a translation +\item a rotation around a pivot point. +\end{itemize} +giving a full transformation matrix of the form: +\begin{equation} +T = L * P * R * P^{-1} +\end{equation} +where +\begin{itemize}\itemcompact +\item $T$ is the full transformation in 3D space containing the change to the +exiting placement transformation. The existing placement is the placement +transformation of the volume with respect to the mother volume. +\item $L$ is a translation specifying the position change with respect to the + mother volume. +\item $P * R * P^{-1}$ describes a rotation around a pivot point specified + int he mother volume's coordinate system. +\item $P$ is the translation vector from the mother volumes origin to the + pivot point. The concept of a pivot point does not introduce a new set of + parameters. Pivot points only help to increase the numerical precision. +\end{itemize} +Most of the changes do not require the full set of parameters. Very often +the changes only require the application of only a translation, only a rotation +or both with a pivot point in the origin. These simplifications are supported +in the user interface described in +Section~\ref{sec:ddalign-user-manual-ddalign-interface}. + +%============================================================================= +\begin{figure}[t] + \begin{center} + \includegraphics[width=160mm] {DDAlign-iterative-misalignment.png} + \caption{The iterative application of alignment parameters as described + in Section~\ref{subsect:ddalign-intro-iterative-alignments}. + For each interval of validity ($[T_0,T_1]$, $[T_2,T_3]$, $[T_4,T_5]$, ...) + a seperate set of alignment constants is applied to the ideal geometry. + The two steps to reset the misaligned geometry back to the ideal geometry and + to re-apply a new set of alignment constants may be executed as + often as necessary when processing data from particle collisions.} + \label{fig:ddalign-aligned-iterative} + \end{center} +\end{figure} + +%============================================================================= +\subsection{Iterative Application of Alignments} +\label{subsect:ddalign-intro-iterative-alignments} +%============================================================================= +\noindent +In the general case a given set of alignment parameters is not static and +may very well change with time. For this reason it is highly important to +support not only one single realignment step. +Hence, the following scenario is an important use case: +\begin{enumerate}\itemcompact +\item Create the ideal detector using an ideal geometry. +\item Apply a set of alignment parameters for a given time + interval corresponding to the + time a set of particle collisions were collected in the experiment. +\item Process the set of collected particle collisions. +\item Reset the misaligned detector to the ideal. +\item Choose new event data input corresponding to another time interval + and restart at item 2. +\end{enumerate} +Graphically this use case is illustrated in +Figure~\ref{fig:ddalign-aligned-iterative}. In +Section~\ref{sec:ddalign-user-manual-ddalign-interface} the implementation +to realize this use case is described. + +%============================================================================= +\subsection{Procedures to Determine Alignment Parameters} +\label{subsect:ddalign-intro-determine-alignment-params} +%============================================================================= +\noindent +Typically the determination of alignment parameters requires a starting point +which is not necessarily identical to the ideal position of a +volume~\cite{bib:chris-parkes-priv-comm}. These volume positions are the result +of a survey measurement or the result of internal position measurements +of a sub-volume within a sub-detector e.g. on a measurement bench. +In the following we call these parameters {\it{survey parameters}}. +{\it{Survey parameters}} default to the ideal volume position if not supplied, +alternatively, if set, to the provided position. {\it{Survey parameters}} +are, like the alignment parameters, provided in terms of {\it{changes}} with +respect to the ideal position and hence may be treated in a similar way. + +\noindent +The survey parameters are - like alignment parameters - accessible to users +through the interface offered by the $DetElement$ objects. + + +%============================================================================= +\subsection{Simulation of Non-Ideal, Real Detector Geometries} +\label{subsect:ddalign-intro-simulate-misaligned-geometries} +%============================================================================= +\noindent +It is a standard procedure in high energy physics to at least verify +the measured detector response of a given physics process in particle +collisions with the expected simulated detector response. +For most purposes the simulation of an ideal detector is certainly is +sufficient - though not describing the full truth. Sometimes however, the +detector geometry must be simulated with a geometry as close to the +known geometry as possible. + +\noindent +The simulation of such a geometry with applied alignment parameters can +rather easily be realized using using the \DDhep, \DDA and the \DDG frameworks: +\begin{itemize}\itemcompact +\item The ideal geometry is constructed using the standard procedures + of \DDhep~\cite{bib:DD4hep}. +\item Then the alignment parameters are applied and finally +\item the corrected geometry is translated to $Geant4$~\cite{bib:geant4} + using the \DDG~\cite{bib:DDG4} package. + All particle collisions simulated with this translated geometry + correspond to the modified geometry including the geometry modifications. +\end{itemize} +There is a caveat though: The application of alignment parameters can +easily create volume overlaps, which are highly disliked by the $Geant4$ +runtime. If the above described procedure is applied, it is highly advised +to check the resulting geometry for overlaps. Both, $ROOT$~\cite{bib:ROOT-tgeo} +and $Geant4$~\cite{bib:geant4} offer tools to perform such tests. + + +\newpage +%============================================================================= +\section{The DDAlign User Interface} +\label{sec:ddalign-user-manual-ddalign-interface} +%============================================================================= + +\noindent +\DDA implements a machinery to apply and access the alignment parameters +describing the difference between an ideal detector given by an ideal geometry +and the geometry of the actually built assembly in real life. +To ease its usage for the clients and to shield clients from the +internals when actually dealing with realigned geometries, a set of +helper classes was designed. The access to the alignment parameters +in read-only mode was separated from the import or export thereof. + +\noindent +As a basic concept within \DDhep any {\it{sizable}} detector component +can be realigned. {\it{Sizable}} as a rule of thumb is anything, which +is manufactured as an individual piece and which you may ''hold in your hands''. +Such objects are also described by a $detector$ $element$ of type {\tt DetElement}. +An example is e.g. a single silicon wafer of a tracking device or the entire +tracking detector itself. +The access to the alignment parameters is possible from each {\tt DetElement} +instance as described in Section~\ref{sec:ddalign-user-manual-misalignment-access}. +The interface assumes ''planar'' alignment parameters i.e. the shape of +a given volume does not change~\footnote{This is a restriction to the +possibilities provided by the ROOT implemetation~\cite{bib:ROOT-tgeo} +based on experience~\cite{bib:chris-parkes-priv-comm}. +If at a later time the need arises the provided alignment interface may +be extended to support shape changes.}. + +\noindent +Please be aware that the extensive use of misalignments is highly memory +consuming. + +\noindent +%============================================================================= +\subsection{Access to Alignment Parameters from the Detector Element} +\label{sec:ddalign-user-manual-misalignment-access} +%============================================================================= + +\noindent +The $DetElement$ class as shown in Figure~\ref{fig:dd4hep-detector-model} +gives the user access to the alignment structure of type $Alignment$ as +illustrated in the following example: +\begin{code} + DetElement wafer = ... // Valid handle to a detector element + Alignment wafer_alignment = wafer.alignment(); + if ( wafer_alignment.isValid() ) { + // This wafer's placement differs from the ideal geometry when + // alignment parameters are present. + + // Access the misalignment transformation with respect to the parent volume: + Transform3D tr = wafer_alignment.toMotherDelta(); + } +\end{code} +The access to details of an invalid alignment object results in a runtime +exception. The following calls allow clients to access alignment information +from the $DetElement$ structure: +\begin{code} + /// Access to the actual alignment information + Alignment alignment() const; + + /// Access to the survey alignment information + Alignment surveyAlignment() const; +\end{code} +The call to $alignment()$ return the parameters $applied$ to the the existing +ideal geometry. The call $surveyAlignment()$ returns optional constants used +to perform numerical calculations as described in +section~\ref{subsect:ddalign-intro-determine-alignment-params}. + +\noindent +All functionality of the DetElement, which depends on applied alignment parameters +are automatically updated in the event of changes. These are typically the geometry +transformations with respect to the mother- and the world volume: +\begin{code} + /// Create cached matrix to transform to world coordinates + const TGeoHMatrix& worldTransformation() const; + + /// Create cached matrix to transform to parent coordinates + const TGeoHMatrix& parentTransformation() const; + + /// Transformation from local coordinates of the placed volume to the world system + bool localToWorld(const Position& local, Position& global) const; + + /// Transformation from local coordinates of the placed volume to the parent system + bool localToParent(const Position& local, Position& parent) const; + + /// Transformation from world coordinates of the local placed volume coordinates + bool worldToLocal(const Position& global, Position& local) const; + + /// Transformation from world coordinates of the local placed volume coordinates + bool parentToLocal(const Position& parent, Position& local) const; +\end{code} +it is worth noting that the update of cached information is performed by the $DetElement$ +objects, other user defined cached information is {\bf{not}} updated. To update +user caches it is mandatory to provide a user defined update callback to the $DetElement$: +\begin{code} + template <typename Q, typename T> + void callAtUpdate(unsigned int type, Q* pointer, + void (T::*pmf)(unsigned long typ, DetElement& det, void* opt_par)) const; +\end{code} + +\noindent +The interface of the $Alignment$ structure to access detector +alignment parameters is as follows (see also the corresponding header file DD4hep/Alignment.h): +\begin{code} + /// Number of nodes in this branch (=depth of the placement hierarchy from the top level volume) + int numNodes() const; + + /// Access the placement of this node + PlacedVolume placement() const; + + /// Access the placement of the mother of this node + PlacedVolume motherPlacement(int level_up = 1) const; + + /// Access the placement of a node in the chain of placements for this branch + PlacedVolume nodePlacement(int level=-1) const; + + /// Access the currently applied alignment/placement matrix with respect to the world + Transform3D toGlobal(int level=-1) const; + + /// Transform a point from local coordinates of a given level to global coordinates + Position toGlobal(const Position& localPoint, int level=-1) const; + + /// Transform a point from global coordinates to local coordinates of a given level + Position globalToLocal(const Position& globalPoint, int level=-1) const; + + /// Access the currently applied alignment/placement matrix with respect to mother volume + Transform3D toMother(int level=-1) const; + + /// Access the currently applied alignment/placement matrix (mother to daughter) + Transform3D nominal() const; + + /// Access the currently applied correction matrix (delta) (mother to daughter) + Transform3D delta() const; + + /// Access the inverse of the currently applied correction matrix (delta) (mother to daughter) + Transform3D invDelta() const; +\end{code} +\begin{itemize}\itemcompact +\item The calls in line 3-8 allow access to the relative position of the $nth.$ element + in the alignment stack with respect to its next level parent. + Element $numNodes()-1$ denotes the lowest level and element $0$ is the world + volume. The default argument $(-1)$ addresses the lowest placement in the hierarchy. +\item Calls in line 9-12 allow to access/execute transformations from a given level + in the placement hierarchy to coordinates in the top level volume (world). +\item The call in line 14 allows to transform a global coordinate to the local coordinate + system in a given level of the hierarchy. +\item The call $toMother$ in line 16 returns the local transformation of the node at + a given level to the mother's coordinate system. +\item The calls in line 17-20 give access to the nominal placement matrix of the realigned + node with respect to the parent volume and the changes thereof. +\end{itemize} +Besides these convenience calls the full interface to the class {\tt TGeoPhysicalNode}, +which implements in the ROOT geometry package alignment changes, is accessible +from the $Alignment$ handle using the overloaded $operator->()$. +Further documentation is available directly from the \tgeo{TGeoPhysicalNode}{ROOT site}. + +\noindent +%============================================================================= +\subsection{Manipulation of Alignment Parameters} +\label{sec:ddalign-user-manual-misalignment-manip} +%============================================================================= +There are multiple possibilities to apply alignment parameters: +\begin{itemize}\itemcompact +\item The pedestrian way ''by hand'' using C++ as described in + Subsection~\ref{sec:ddalign-user-manual-misalignment-manip-cxx} +\item Loading a whole set of misalignment constants from XML, the ''poor man's'' database. + This mechanism is described in + Subsection~\ref{sec:ddalign-user-manual-misalignment-manip-xml} +\item Loading a whole set of misalignment constants from a database. + This possibility depends heavily on the database and its schema used. + A typical use case is to load misalignment constants depending on the + experiment conditions at the time the event data were collected. + \DDA does not provide an implementation. + This possibility here is only mentioned for completeness and will be subject + to further developments to support conditions in \DDhep. +\end{itemize} + +\noindent +%============================================================================= +\subsubsection{Manipulation of Alignment Parameters for Pedestrians using C++} +\label{sec:ddalign-user-manual-misalignment-manip-cxx} +%============================================================================= +\noindent +In this section we describe how to apply geometry imperfections to an existing +detector geometry in memory using {\tt C++}. To apply misalignment to an existing +geometry two classes are collaborating, the {\tt AlignmentCache} attached to +the geometry container {\tt LCDD} and a temporary structure the {\tt AlignmentStack}. +The {\tt AlignmentCache} allows to access all existing alignment entries +based on their subdetector. +The {\tt AlignmentStack} may exist in exactly one instance and is used to +insert a consistent set of alignment entries. Consistency is important because +changes may occur at any hierarchical level and internal transformation caches +of the ROOT geometry package must be revalidated for all branches containing +a higher level node. +{\bf For this reason it is highly advisable to apply realignment constants +for a complete subdetector.} +Note that this restriction is not imposed, in principle a consistent set +of misalignments may be applied at any level of the geometry hierarchy. + +\noindent +Though the application of alignment is much simpler using XML files, the following +description should give an insight on the mechanisms used behind the scene and +to understand the concept. + +\noindent +Any manipulations are transaction based must be embraced by the following two calls +opening and closing a transaction: +\begin{code} +// Required include file(s) +#include "DDAlign/AlignmentCache.h" + + LCDD& lcdd = ....; + AlignmentCache* cache = lcdd.extension<Geometry::AlignmentCache>(); + + // First things first: open the transaction. + cache->openTransaction(); + + // Prepare the entry containing the alignment data + AlignmentStack::StackEntry* entry = .....; + //.... and add the element to the AlignmentStack ..... + AlignmentStack::insert(entry); + + // Finally close the transaction. At this moment the changes are applied. + cache->closeTransaction(); +\end{code} +In the following we describe the mechanism to create and prepare the +{\tt StackEntry} instances of the above code snippet. The calls to open and close +the alignment transaction do not have to be in the same code fragment where also +the alignment entries are prepared. However, all changes are only applied when +the transaction is closed. The alignment entries do not necessarily have to +be prepared in the sequence of the hierarchy they should be applied, internally +the entries are re-ordered and follow the geometry hierarchy top to bottom +i.e. mother volumes are always re-aligned {\it\bf before} the daughters +are re-aligned. + +\noindent +The {\tt StackEntry} instances carry all information to apply the re-alignment +of a given volume. This information contains: +\begin{itemize}\itemcompact +\item The transformation matrix describing the positional change of the volume + with respect to its mother volume. +\item The placement path of the volume to be realigned. +\item A flag to reset the volume to its ideal position {\it\bf before} the + change is applied. +\item A flag to also reset all daughter volumes to their + ideal position {\it\bf before} the change is applied. +\item A flag to check for overlaps after the application of the change and +\item the actual precision used to perform this check. +\end{itemize} + +\noindent +The {\tt ROOT::Math} library provides several ways to construct the required +3D transformation as described in Section~\ref{subsect:ddalign-intro-aligments}: +\begin{code} +// Required include file(s) +#include "DD4hep/Objects.h" + + Position trans(x_translation, y_translation, z_translation); + RotationZYX rot (z_angle, y_angle, x_angle); + Translation3D pivot(x_pivot, y_pivot, z_pivot); + + Transform3D trafo; + /// Construct a 3D transformation for a translation and a rotation around a pivot point: + trafo = Transform3D(Translation3D(trans)*pivot*rot*(pivot.Inverse())); + + /// Construct a 3D transformation for a translation and a rotation around the origin + trafo = Transform3D(rot,pos); + + /// Construct a 3D transformation for a rotation around a pivot point + trafo = Transform3D(piv*rot*(piv.Inverse())); + + /// Construct a 3D transformation for a rotation around the origin + trafo = Transform3D(rot); + + /// Construct a 3D transformation for simple translation + trafo = Transform3D(pos); + +\end{code} + +\noindent +The following code snippet shows how to extract this information from the +{\tt DetElement} and prepare such a {\tt StackEntry} instance: +\begin{code} +// Required include file(s) +#include "DDAlign/AlignmentStack.h" + + // Prepare the entry containing the alignment data + typedef AlignmentStack::StackEntry Entry; + /// Detector element to be realigned + DetElement element = ...; + /// The transformation describing the relative change with respect to the mother volume + Transform3D trafo = ...; + /// Instantiate a new alignment entry + Entry* entry = new Entry(element); + entry->setTransformation(trafo) // Apply the transformation matrix + .applyReset(/* argument default: true */) // Set the reset flag + .applyResetChildren(/* argument default: true */) // Set the daughter reset flag + .checkOverlaps(/* argument default: true */) // Set flag to check overlaps + .overlapPrecision(0.001/mm); // With this precision in mm + + /// Now add the entry to the alignment stack: + AlignmentStack::insert(entry); +\end{code} +The constructor will automatically determine the volumes placement path +from the {\tt DetElement}. Then the transformation is applied and the flags +to reset the volume, its children and to trigger the overlap checks with +the given precision. + +\noindent +When passing the entry to the {\tt AlignmentStack} the {\tt AlignmentStack} +takes ownership and subsequently the entry is deleted after being applied to +the geometry. For further shortcuts in the calling sequence please consult the +{\tt AlignmentStack} header file. + + +\noindent +%============================================================================= +\subsubsection{Loading Geometrical Imperfections from XML} +\label{sec:ddalign-user-manual-misalignment-manip-xml} +%============================================================================= +\noindent +In this section we describe how to load geometry imperfections and to apply them +to an existing geometry. Loading the XML file is done automatically using the +standard XML loader plugin provided by \DDhep. This plugin is interfaced to +the {\tt LCDD} instance and invoked from code as follows: +\begin{code} + LCDD& lcdd = ....; + lcdd.fromXML("file:AlepTPC_alignment.xml"); +\end{code} +To fully exploit the capabilities it is important to understand the interpreted +structure of the XML file being processed. At the top level of the primary +input file (i.e. the file given to the XML processor) the following structure +is expected: +\begin{code} +<alignment> + <!-- Open the alignment transaction --> + <open_transaction/> + <subdetectors> <!-- Container with the list of subdetectors to be processed. --> + <detelement path="TPC" reset="true" reset_children="true"> + <!-- Move the entire TPC in the world volume --> + <position="" x="30" y="30" z="80"/> + + <!-- Now add daughter detector elements --> + + <!-- Twist a bit the entire endcap by rotating it around the x and the y axis --> + <detelement path="/world/TPC/TPC_SideA" check_overlaps="false"> + <position x="0" y="0" z="0"/> + <rotation x="-0.2" y="-0.2" z="0"/> + <!-- Apply corrections of type Translation*Rotation to a single sector + <detelement path="TPC_SideA_sector02" check_overlaps="true"> + <position x="0" y="0" z="0"/> + <rotation x="0.5" y="0.1" z="0.2"/> + </detelement> + </detelement> + + <!-- And the full shooting match of transformations for this sector --> + <detelement path="TPC_SideA/TPC_SideA_sector03" check_overlaps="true"> + <position x="0" y="0" z="290.0*mm"/> + <rotation x="0" y="pi/2" z="0"/> + <pivot x="0" y="0" z="100"/> + </detelement> + + .... + + <!-- Include alignment files to be processed in the context of the "TPC" DetElement + <include ref="file-name"/> + + </detElement> + </subdetectors> + + <!-- Include alignment files to be processed at the top level context --> + <include ref="file-name"/> + + <!-- Close the alignment transaction --> + <close_transaction/> +</alignment> +\end{code} + +\noindent +The structure of the alignment file explained quickly: + +\begin{tabular} {l||p{0cm}} +\docline{Line}{} +\docline{1}{The {\tt root} tag for the primary alignment file is {\tt <alignment/>}. + The primary tag name is mandatory and actually is used to invoke the correct interpreter.} +\docline{2,41}{Trigger the alignment transaction by specifying the transaction tags in + the main XML file.} +\docline{4}{Defintion of the set of {\tt subdetectors} to be processed. A valid alias for this + directove is {\tt detelements}.} +\docline{5}{The first subdetector: {\tt TPC}. The subdetector tag is {\tt detelement} + Each {\tt detelement} may recursively contain other {\tt detelement} tags. + as they were defined in the {\tt DetElement} hierarchy. + Internal {\tt detelement} elements are processed in the context of the outer + element i.e. pathes may be specified relative to the parent or as absolute pathes + with respect to the world (starting with a '/').} +\docline{7}{Global movement of the TPC} +\docline{12-20}{Realignment entry for the TPC endcap A named {\tt TPC\_SideA}} +\docline{16-19}{Realignment entry for sector named {\tt TPC\_SideA\_sector02} of the TPC endcap A. + Here the sector is specified directly as a daughter of the endcap. The name + of the {\tt DetElement} is relative to the parent.} +\docline{23-27}{Realignment entry for sector named {\tt TPC\_SideA\_sector03} of the TPC endcap A + containing a full transformation: $Translation * Pivot * Rotation * Pivot^{-1}$} +\docline{32}{Optionally {\tt detelement} elements may include other alignment files specifying + lower volume levels. These files are interpreted in the context of the calling + detector element. } +\docline{38}{Optionally the subdetector alignment constants may be fragmented + into several files, which can be loaded using the {\tt include} + directive. Each file could for example describe one single detector.} +\end{tabular} + +\vspace{0.5cm} +\noindent +The specification of any transformation element is optional: +\begin{itemize}\itemcompact +\item The absence of a translation implies the origin (0,0,0) +\item The absence of a pivot point implies the origin (0,0,0) +\item The absence of a rotation implies the identity rotation. + Any supplied pivot point in this case is ignored. +\end{itemize} +The absence of a transformation element is absolutely legal and does not +issue any warning or error. + +\noindent +All transformations describe the change of placement with respect to the +coordinate system of the closest mother-volume in the volume hierarchy, +i.e. translations, rotations and pivot points are local to the +mother coordinate system. + +\newpage +\noindent +Included files may directly start with the {\tt root} tags {\tt subdetectors}, +{\tt detelements} or {\tt detelement} and may recursively include other +files. Except for the top level these files are processed in the calling context. + +\vspace{1cm} +\noindent +And finally, the result: +%============================================================================= +\begin{figure}[h] + \begin{center} + \includegraphics[width=160mm] {DDAlign-misaligned-TPC.png} + \caption{The ALEPH TPC after the import of the alignment file.} + \label{fig:dd4hep-aligned-hierarchies} + \end{center} +\end{figure} + + +\noindent +%============================================================================= +\subsubsection{Export Geometrical Imperfections to XML} +\label{sec:ddalign-user-misalignment-expotr-xml} +%============================================================================= +\noindent +In this section we describe how to export geometry imperfections to an XML file. +A small helper class {\tt AlignmentWriter} achieves this task as shown in +the snippet: +\begin{code} + LCDD& lcdd = ....; + DetElement top = ....; + if ( top.isValid() ) { + AlignmentWriter wr(lcdd); + return wr.write(top,output,enable\_transactions); + } +\end{code} +This code will dump all alignment constants contained in the {\tt DetElement} +hierarchy of {\tt top} to the output file {\tt output}. The optional argument +{\tt enable\_transactions} (default: true) will add the tags +{\tt <open\_transaction/>} and {\tt <close\_transaction/>} to the output +file. The output file conforms to the specifications described in +Section~\ref{sec:ddalign-user-manual-misalignment-manip-xml} and may later +be imported by another process. + +\newpage +%============================================================================= +\begin{thebibliography}{9} +\bibitem{bib:DD4hep} M. Frank et al, "DD4hep: A Detector Description Toolkit + for High Energy Physics Experiments", + International Conference on Computing in High Energy and Nuclear Physics + (CHEP 2013), \\ + Amsterdam, Netherlands, 2013, proceedings. + +\bibitem{bib:LHCb-geometry} S. Ponce et al., + "Detector Description Framework in LHCb", + International Conference on Computing in High Energy and Nuclear Physics (CHEP 2003), + La Jolla, CA, 2003, proceedings. +\bibitem{bib:chris-parkes-priv-comm} C. Parkes, private communications. +\bibitem{bib:DDG4} M.Frank, "DDG4 - A Simulation Toolkit for High Energy + Physics Experiments using Geant4 \\ + and the DD4hep Geometry Description". +\bibitem{bib:ROOT-tgeo} R.Brun, A.Gheata, M.Gheata, "The ROOT geometry package",\\ + Nuclear Instruments and Methods {\bf{A}} 502 (2003) 676-680. +\bibitem{bib:geant4} S. Agostinelli et al., + "Geant4 - A Simulation Toolkit", \\ + Nuclear Instruments and Methods {\bf{A}} 506 (2003) 250-303. + +\end{thebibliography} +%============================================================================= +\end{document} diff --git a/doc/LaTex/DDAlign_detelement_aligned_tree.png b/doc/LaTex/DDAlign_detelement_aligned_tree.png new file mode 100644 index 0000000000000000000000000000000000000000..3ab21750118e187f92328c96535332e7dc1d5d1e Binary files /dev/null and b/doc/LaTex/DDAlign_detelement_aligned_tree.png differ diff --git a/doc/LaTex/DDConditionsManual.tex b/doc/LaTex/DDConditionsManual.tex new file mode 100644 index 0000000000000000000000000000000000000000..103da1d9a72004fd3e5c9978cccae7ce306d29df --- /dev/null +++ b/doc/LaTex/DDConditionsManual.tex @@ -0,0 +1,132 @@ +%============================================================================= +\documentclass[10pt,a4paper]{article} +% +\input{DD4hep-setup.tex} +% +\pagestyle{fancyplain}{\fancyfoot[C]{\sffamily{DDAlign User Manual}}} +% +\begin{document} +% +\mytitle{ +DDCond +}{ +Conditions Support for the \\ +\vspace{0.5cm} +DD4hep Geometry Description \\ +\vspace{0.5cm} +Toolkit +\vspace{2cm} +}{DDAlign User Manual} +% +% +%== Abstract =============================================================== +\pagestyle{plain} +\pagenumbering{Roman} +\setcounter{page}{1} +\begin{abstract} +%============================================================================= + +\noindent +\normalsize +Experimental setups in High Energy Physics are highly complex assemblies +consisting of various detector devices typically called {\it{subdetectors}}. +Contrary to the ideal world, where all these components are of perfect shape +and at exact positions, existing devices have imperfections both in their +shape and their relative and absolute positions.\\ +To still measure the detector response from particle collisions with the highest +possible precision, these imperfections are taken into account when converting +measured signals to space-points in the measurement devices. This procedure +is called {\it{detector alignment}}. \DDhep does not want to solve the exact +problem of the detector alignment itself, but rather support firstly algorithms +determining the imperfections and secondly support the application of the +measured imperfection to the ideal geometry for further event data processing.\\ +We will present the tools to support the detector alignment procedures using +the \DDhep detector description toolkit. +The \DDA toolkit implements a modular and flexible approach to introduce and +access the imperfections.\\ +The design is strongly driven by easy of use; +developers of detector descriptions and applications using +them should provide minimal information and minimal specific +code to achieve the desired result. + +\end{abstract} + +\vspace{8cm} + +\begin{center} +{\large{\bf{ +\begin{tabular} {| l | l | l |} +\hline +\multicolumn{3}{| c |}{} \\[0.2cm] +\multicolumn{3}{| c |}{Document History} \\[0.2cm] +\multicolumn{3}{| c |}{} \\[0.2cm] +\hline + & & \\ +Document & & \\ +version & Date & Author \\[0.2cm] \hline + & & \\ +1.0 & 10/4/2014 & Markus Frank CERN/LHCb \\ + & & \\ \hline +\end{tabular} +}}} +\end{center} + +\clearpage +% +% +%== TOC ==================================================================== +\tableofcontents +\clearpage +% +% +%============================================================================= +% Manual +%============================================================================= +\pagenumbering{arabic} +\setcounter{page}{1} + +%============================================================================= +\section{Introduction} +\label{sec:ddalign-user-manual-introduction} +%============================================================================= +\noindent +This manual should introduce to the \DDA framework. +One goal of \DDA is to easily model geometrical imperfections applied to +the ideal geometry of detection devices as they are typically used in +high energy physics experiments. + +\noindent +\DDA formalizes both the access and the application of geometrical imperfection +to the ideal geometry. In this manual we will shortly describe the model used +to describe an experiments detector description and then in more detail +document the support for alignment with its programming interfaces. + +%============================================================================= +\begin{figure}[h] + \begin{center} + \includegraphics[height=90mm] {DD4hep_classes.png} + \caption{Class diagram with the main classes and their relations + for the Generic Detector Description Model. The implementing + ROOT classes are shown in brackets.} + \label{fig:dd4hep-detector-model} + \end{center} +\end{figure} +\vspace{-0.5cm} +%============================================================================= +\subsection{Generic Detector Description Model} +\label{subsec:generic-model} +%============================================================================= + +\noindent +This is the heart of the DD4hep detector description toolkit. Its purpose is + +\newpage +%============================================================================= +\begin{thebibliography}{9} +\bibitem{bib:LHCb-geometry} S. Ponce et al., + "Detector Description Framework in LHCb", + International Conference on Computing in High Energy and Nuclear Physics (CHEP 2003), + La Jolla, CA, 2003, proceedings. +\end{thebibliography} +%============================================================================= +\end{document} diff --git a/doc/LaTex/DDEveManual.tex b/doc/LaTex/DDEveManual.tex new file mode 100644 index 0000000000000000000000000000000000000000..034ac70f2486fa508ed10f12fb13cbb001c8b01b --- /dev/null +++ b/doc/LaTex/DDEveManual.tex @@ -0,0 +1,211 @@ +%============================================================================= +\documentclass[10pt,a4paper]{article} +% +\input{DD4hep-setup.tex} +% +\pagestyle{fancyplain}{\fancyfoot[C]{\sffamily{DRAFT -- DDEve User Manual -- DRAFT}}} +% +\begin{document} +% +\mytitle{ +DDEve +}{ +An Event Display for \\ +\vspace{0.5cm} +DD4hep Geometries \\ +\vspace{2.5cm} +-- DRAFT -- \\ +}{DDEve User Manual} +% +% +%== Abstract =============================================================== +\pagestyle{plain} +\pagenumbering{Roman} +\setcounter{page}{1} +\begin{abstract} +%============================================================================= + +\noindent +\normalsize +\DDE is a framework implementing a event display for detector geometries +implemented using DD4hep. \DDE hereby takes advantage of the TEve toolkit +naturally provided by the ROOT framework like the ROOT geometry toolkit +TGeo. +\noindent +\DDE actively uses the collaboration between TEve and TGeo as well +as the various object collaborations provided by the toolkits. +\DDE does in no way intend to hide any of the two toolkits, but +rather provides facilities to construct various detector views +in the most suitable manner using predefined configurations. +\end{abstract} + +\vspace{8cm} + +\begin{center} +{\large{\bf{ +\begin{tabular} {| l | l | l |} +\hline +\multicolumn{3}{| c |}{} \\[0.2cm] +\multicolumn{3}{| c |}{Document History} \\[0.2cm] +\multicolumn{3}{| c |}{} \\[0.2cm] +\hline + & & \\ +Document & & \\ +version & Date & Author \\[0.2cm] \hline + & & \\ +1.0 & 15/08/2014 & Markus Frank CERN/LHCb \\ + & & \\ \hline +\end{tabular} +}}} +\end{center} + +\clearpage +% +% +%== TOC ==================================================================== +\tableofcontents +\clearpage +% +% +%============================================================================= +% Manual +%============================================================================= +\pagenumbering{arabic} +\setcounter{page}{1} + +%============================================================================= +\section{Introduction} +\label{sec:ddeve-user-manual-introduction} +%============================================================================= +\noindent +Short usage description of \DDE. + +\noindent +\DDE is a purely experimental package. It was developed to +\begin{itemize} +\item visually debug developed detector geometries including partial views + using predefined displays. +\item compensate the frustration caused by the slow progress of subdetector + geometry implementers, which did not get up to speed and hence did not + require any support from me..... +\end{itemize} +Since up to now \DDE is a hobby of mine, please do not expect a great deal +of documentation and support. + +%============================================================================= +\section{Running the CLICSiD Example} +\label{sec:ddeve-user-manual-introduction} +%============================================================================= +\noindent +DDEve is started using the root executable. In the following we describe +how to start a display application of \DDE using the CLICSiD example. +\begin{unnumberedcode} +$> root.exe $DD4hepINSTALL/examples/DDEve/DDEve.C +\end{unnumberedcode} +When the command is issued the following display shows up: +\begin{figure}[h] + \begin{center} + \includegraphics[height=90mm] {DDEve_1.png} + \caption{The \DDE startup view.} + \label{fig:DDEve_1.png} + \end{center} +\end{figure} +\newpage +\noindent +Click on "Dismiss" then the file browser opens and you have to select +a \DDE configuration file: +\begin{figure}[h] + \begin{center} + \includegraphics[height=120mm] {DDEve_2.png} + \caption{The \DDE popup dialog to open the XML configuration file.} + \label{fig:DDEve_2.png} + \end{center} +\end{figure} + +\noindent +Move to the directory \tts{\$DD4hepINSTALL/examples/CLIDSid/eve} and open the +\DDE configuration file \tts{DDEve.xml}. The basic idea is that \DDE as an +application is truely generic and that all subsequent behavior + + +\newpage +\noindent +Next you should see the default pane with the instantiated CLICSiD detector: + +\begin{figure}[t] + \begin{center} + \includegraphics[height=120mm] {DDEve_3.png} + \caption{The \DDE default view showing the loaded detector.} + \label{fig:DDEve_3.png} + \end{center} +\end{figure} + +\newpage +\noindent +Then open from the \tts{"DD4hep"} menu the item \tts{"Open Event Data"}. Move again to the +directory \tts{\$DD4hepINSTALL/examples/CLIDSid/eve} and open the sample file +\tts{CLICSiD\_Events.root} containing a sample of events being the output of +a \DDG simulation step: + +\begin{figure}[h] + \begin{center} + \includegraphics[height=130mm] {DDEve_4.png} + \caption{The popup dialog to open event data files.} + \label{fig:DDEve_4.png} + \end{center} +\end{figure} +Using the \tts{"Views"} menu other predefined detector views may be used. + +\newpage +\noindent +The \tts{"Eve"} tab on the pane to the left allows to further customize the +predefined views, the \tts{Evt I/O} tab to control which event should +be displayed. + +\begin{figure}[h] + \begin{center} + \includegraphics[height=130mm] {DDEve_5.png} + \caption{An example of a customized view with sub-panes. Please proceed + to the XML configuration file how to create a predefined view.} + \label{fig:DDEve_5} + \end{center} +\end{figure} + +\newpage +\noindent +\begin{figure}[h] + \begin{center} + \includegraphics[height=130mm] {DDEve_7.png} + \caption{Calorimetr energy deposits in the ECAL (red) and the HCAL(blue).} + \label{fig:DDEve_5} + \end{center} +\end{figure} + +\newpage +\noindent +\begin{figure}[h] + \begin{center} + \includegraphics[height=130mm] {DDEve_8.png} + \caption{HCAL calorimeter deposits together with Monte-Carlo tracks.} + \label{fig:DDEve_5} + \end{center} +\end{figure} + + +%============================================================================= +\section{View Configuration} +\label{sec:ddeve-user-manual-display-configuration} +%============================================================================= +\noindent +This part of the \DDE application is not really stable. to configure displays +other than for the \tts{CLICSiD} example, you have to use the trial and error +approach. Starting from the \tts{CLICSiD} example is not too bad an approach. + + +%============================================================================= +\newpage +\begin{thebibliography}{9} +\input{DD4hep-bibliography.tex} +\end{thebibliography} +%============================================================================= +\end{document} diff --git a/doc/LaTex/DDEve_1.png b/doc/LaTex/DDEve_1.png new file mode 100644 index 0000000000000000000000000000000000000000..b44ad2456ffa021d6821301b699df35786d233a1 Binary files /dev/null and b/doc/LaTex/DDEve_1.png differ diff --git a/doc/LaTex/DDEve_2.png b/doc/LaTex/DDEve_2.png new file mode 100644 index 0000000000000000000000000000000000000000..a899f51eb78e3e3982e7d4338296f0a7382ec42b Binary files /dev/null and b/doc/LaTex/DDEve_2.png differ diff --git a/doc/LaTex/DDEve_3.png b/doc/LaTex/DDEve_3.png new file mode 100644 index 0000000000000000000000000000000000000000..70e821990dc90d36b568120ab85f967cbe3127ab Binary files /dev/null and b/doc/LaTex/DDEve_3.png differ diff --git a/doc/LaTex/DDEve_4.png b/doc/LaTex/DDEve_4.png new file mode 100644 index 0000000000000000000000000000000000000000..7a1bac123768c88730222c1a145c1355d82a7f1d Binary files /dev/null and b/doc/LaTex/DDEve_4.png differ diff --git a/doc/LaTex/DDEve_5.png b/doc/LaTex/DDEve_5.png new file mode 100644 index 0000000000000000000000000000000000000000..78f3d8008a49c53842877552be89936c8e7e10fb Binary files /dev/null and b/doc/LaTex/DDEve_5.png differ diff --git a/doc/LaTex/DDEve_6.png b/doc/LaTex/DDEve_6.png new file mode 100644 index 0000000000000000000000000000000000000000..09b3fd228308cf54ee59d7d4a9a22cf843756f0a Binary files /dev/null and b/doc/LaTex/DDEve_6.png differ diff --git a/doc/LaTex/DDEve_7.png b/doc/LaTex/DDEve_7.png new file mode 100644 index 0000000000000000000000000000000000000000..d0161707cf32a7894ac24256690f3a1e5a817ba1 Binary files /dev/null and b/doc/LaTex/DDEve_7.png differ diff --git a/doc/LaTex/DDEve_8.png b/doc/LaTex/DDEve_8.png new file mode 100644 index 0000000000000000000000000000000000000000..1aec6b65f3f850e9800498ff22bef30ecbdabb3d Binary files /dev/null and b/doc/LaTex/DDEve_8.png differ diff --git a/doc/LaTex/DDG4-G4RunManagerAnatomy.png b/doc/LaTex/DDG4-G4RunManagerAnatomy.png new file mode 100644 index 0000000000000000000000000000000000000000..9624cd2cbae4fe4eb4889b8e084f13a831b1351e Binary files /dev/null and b/doc/LaTex/DDG4-G4RunManagerAnatomy.png differ diff --git a/doc/LaTex/DDG4-Geant4Action.png b/doc/LaTex/DDG4-Geant4Action.png new file mode 100644 index 0000000000000000000000000000000000000000..b725f03034b788efa69edf808752f4434764a8e1 Binary files /dev/null and b/doc/LaTex/DDG4-Geant4Action.png differ diff --git a/doc/LaTex/DDG4-Geant4Kernel.png b/doc/LaTex/DDG4-Geant4Kernel.png new file mode 100644 index 0000000000000000000000000000000000000000..32adb857355575b6ee99f145dc82a0425c4115e9 Binary files /dev/null and b/doc/LaTex/DDG4-Geant4Kernel.png differ diff --git a/doc/LaTex/DDG4-Sensitive-detector.png b/doc/LaTex/DDG4-Sensitive-detector.png new file mode 100644 index 0000000000000000000000000000000000000000..46bfd4d1829c6d40da117af81a5036e16178f1ac Binary files /dev/null and b/doc/LaTex/DDG4-Sensitive-detector.png differ diff --git a/doc/LaTex/DDG4-TrackingAction.png b/doc/LaTex/DDG4-TrackingAction.png new file mode 100644 index 0000000000000000000000000000000000000000..93b86e85e189eb26af9a3fcd1d93761e8f5b41f0 Binary files /dev/null and b/doc/LaTex/DDG4-TrackingAction.png differ diff --git a/doc/LaTex/DDG4-UIMessenger.png b/doc/LaTex/DDG4-UIMessenger.png new file mode 100644 index 0000000000000000000000000000000000000000..2b1dc4700247b80a97b391daf83aa980010affb6 Binary files /dev/null and b/doc/LaTex/DDG4-UIMessenger.png differ diff --git a/doc/LaTex/DDG4Manual.0.tex b/doc/LaTex/DDG4Manual.0.tex new file mode 100644 index 0000000000000000000000000000000000000000..4590bbaa551c8490d172013dc2334d1680107f7c --- /dev/null +++ b/doc/LaTex/DDG4Manual.0.tex @@ -0,0 +1,1419 @@ +%============================================================================= +\documentclass[10pt,a4paper]{article} +% +\input{DD4hep-setup.tex} +% +\pagestyle{fancyplain}{\fancyfoot[C]{\sffamily{DDG4 User Manual}}} +% +\begin{document} +% +\mytitle{ +DDG4 +}{ +A Simulation Toolkit for \\ +\vspace{0.5cm} +High Energy Physics Experiments\\ +\vspace{0.5cm} +using Geant4 and the \\ +\vspace{0.5cm} +DD4hep Geometry Description +}{DDG4 User Manual} +% +% +%== Abstract =============================================================== +\pagestyle{plain} +\pagenumbering{Roman} +\setcounter{page}{1} +\begin{abstract} +%============================================================================= + +\noindent +\normalsize +Simulating the detector response is an essential tool in high energy physics +to analyze the sensitivity of an experiment to the underlying physics. +Such simulation tools require a detailed though convenient detector description as +it is provided by the \DDhep toolkit. +We will present the generic simulation toolkit \DDG using the \DDhep detector +description toolkit. +The toolkit implements a modular and flexible approach to simulation activities +using Geant4. User defined simulation applications using \DDG +can easily be configured, extended using specialzed action routines. +The design is strongly driven by easy of use; +developers of detector descriptions and applications using +them should provide minimal information and minimal specific +code to achieve the desired result. + +\end{abstract} + +\vspace{8cm} + +\begin{center} +{\large{\bf{ +\begin{tabular} {| l | l | l |} +\hline +\multicolumn{3}{| c |}{} \\[0.2cm] +\multicolumn{3}{| c |}{Document History} \\[0.2cm] +\multicolumn{3}{| c |}{} \\[0.2cm] +\hline + & & \\ +Document & & \\ +version & Date & Author \\[0.2cm] \hline + & & \\ +1.0 & 19/11/2013 & Markus Frank CERN/LHCb \\ + & & \\ \hline +\end{tabular} +}}} +\end{center} + +\clearpage +% +% +%== TOC ==================================================================== +\tableofcontents +\clearpage +% +% +%============================================================================= +% Manual +%============================================================================= +\pagenumbering{arabic} +\setcounter{page}{1} + +%============================================================================= +\section{Introduction} +\label{sec:ddg4-user-manual-introduction} +%============================================================================= +\noindent +This manual should introduce to the DDG4 framework. +One goal of \DDG is to easily configure the simulation applications +capable of simulating the physics response of detector configurations +as they are used for example in high energy physics experiments. +In such simulation programs the user normally has to define the +experimental setup in terms of its geometry and in terms of its +active elements which sample the detector response. + +\noindent +The goal of \DDG is to generalize the configuration of a simulation +application to a degree, which does not force users to write code +to test a detector design. At the same time it should of course +be feasible to supply specialized user written modules which are supposed +to seamlessly operate together with standard modules supplied by the toolkit. +Detector-simulation depends strongly on the use of an underlying simulation toolkit, +the most prominent candidate nowadays being Geant4~\cite{bib:geant4}. +\DDhep supports simulation activities with Geant4 providing +an automatic translation mechanism between geometry representations. +The simulation response in the active elements of the detector +is strongly influenced by the technical +choices and precise simulations depends on the very specific detection techniques. + +\noindent +Similar to the aim of \DDhep~\cite{bib:DD4hep}, +where with time a standard palette of detector +components developed by users should become part of the toolkit, +\DDG also hopes to provide a standard palette of components used +to support simulation activities for detector layouts +where detector designers may base the simulation of a planned experiment +on these predefined components for initial design and optimization +studies. + +\noindent +This is not a manual to Geant4 nor the basic infrastructure of \DDhep. +It is assumed that this knowledge is present and the typical glossary +is known. + +%============================================================================= +\section{The Geant4 User Interface} +\label{sec:ddg4-user-manual-geant4-interface} +%============================================================================= + +\noindent +The Geant4 simulation toolkit~\cite{bib:geant4} implements a very complex +machinery to simulate the energy deposition of particles traversing materials. +To ease its usage for the clients and to shield clients from the complex +internals when actually implementing a simulation applications for a +given detector design, it provides several user hooks +as shown in Figure~\ref{fig:ddg4-g4runmanager-anatomy}. Each of these hooks +serves a well specialized purpose, but unfortunately also leads to very +specialized applications. One aim of \DDG is to formalize these user +actions so that the invocation at the appropriate time may be purely +data driven. +\begin{figure}[h] + \begin{center} + \includegraphics[height=70mm] {DDG4-G4RunManagerAnatomy.png} + \caption{The various user hooks provided by Geant4. Not shown here + is the callback system interfacing to the active elements + of the detector design.} + \label{fig:ddg4-g4runmanager-anatomy} + \end{center} +\end{figure} + +\noindent +In detail the following object-hooks allow the client to define user provided actions: +\begin{itemize}\itemcompact +\item The \bold{User Physics List} allows the client to customize and define + the underlying physics process(es) which define the particle interactions + inside the detector defined with the geometry description. + These interactions define the detector response in terms of + energy depositions. +\item The \bold{Run Action} is called once at the start and end of a run. + i.e. a series of generated events. These two callbacks + allow clients to define run-dependent actions such as statistics + summaries etc. +\item The \bold{Primary Generator Action} is called for every event. + During the callback all particles are created which form the + microscopic kinematic action of the particle collision. + This input may either origin directly from an event generator program + or come from file. +\item The \bold{Event Action} is called once at the start and the end of each event. + It is typically used for a simple analysis of the processed event. + If the simulated data should be written to some persistent medium, + the call at the end of the event processing is the appropriate place. +\item The \bold{Tracking Action} +\item The \bold{Stepping Action} +\item The \bold{Stacking Action} +\end{itemize} +\noindent +Geant4 provides all callbacks with the necessary information in the form of +appropriate arguments. + +\noindent +Besides the callback system, Geant4 provides callbacks whenever a particle +traverses a sensitive volume. These callbacks are called +- similar to event actions - once at the start and the end of the event, +but in addition, if either the energy deposit of a particle in the +sensitive volume exceeds some threshold. The callbacks are formalized within +the base class \tts{G4VSensitiveDetector}. + +%============================================================================= +\section{DDG4 Implementation} +\label{sec:ddg4-user-manual-implementation} +%============================================================================= + +\noindent +A basic design criteria of the a \DDG simulation application was to +process any user defined hook provided by Geant4 as a series of algorithmic +procedures, which could be implemented either using inheritance or by +a callback mechanism registering functions fulfilling a given signature. +Such sequences are provided for all actions mentioned in the list in +Section~\ref{sec:ddg4-user-manual-geant4-interface} as well as for +the callbacks to sensitive detectors. + +\noindent +The callback mechanism was introduced to allow for weak coupling between +the various actions. For example could an action performing monitoring +using histograms at the event level initialize or reset its histograms +at the start/end of each run. To do so, clearly a callback at the +start/end of a run would be necessary. + +\noindent +In the following sections a flexible and extensible interface to hooks +of Geant4 is discussed starting with the description of the basic +components \tts{Geant4Kernel} and \tts{Geant4Action} followed by the +implementation of the relevant specializations. +The specializations exposed are sequences of such actions, +which also call registered objects. +In later section the configuration and the combination of these components +forming a functional simulation application is presented. + +%============================================================================= +\subsection{The Application Core Object: \tts{Geant4Kernel}} +\label{sec:ddg4-user-manual-implementation-geant4kernel} +%============================================================================= + +\noindent +The kernel object is the central context of a \DDG simulation application and +gives all clients access to the user hooks (see Figure~\ref{fig:ddg4-geant4-kernel}). +All Geant4 callback structures are exposed so that clients can easily +objects implementing the required interface or register callbacks with the +correct signature. +\begin{figure}[h] + \begin{center} + \includegraphics[height=80mm] {DDG4-Geant4Kernel.png} + \caption{The sensitive detector design.} + \label{fig:ddg4-geant4-kernel} + \end{center} +\end{figure} + +%============================================================================= +\subsection{The Base Class of DDG4 Actions: \tts{Geant4Action}} +\label{sec:ddg4-user-manual-implementation-geant4action-base} +%============================================================================= + +\noindent +The class \tts{Geant4Action} is a common component interface providing +the basic interface to the framework to +\begin{itemize}\itemcompact +\item configure the component using a property mechanism +\item provide an appropriate interface to Geant4 interactivity. The interactivity + included a generic way to change and access properties from the Geant4 UI + prompt as well as executing registered commands. +\item As shown in Figure~\ref{fig:ddg4-implementation-geant4-action}, the + base class also provides to its sub-class a reference to the \tts{Geant4Kernel} + objects through the \tts{Geant4Context}. +\end{itemize} +The \tts{Geant4Action} is a named entity and can be uniquely identified within +a sequence attached to one Geant4 user callback. +%============================================================================= +\begin{figure}[h] + \begin{center} + \includegraphics[height=30mm] {DDG4-Geant4Action.png} + \caption{The design of the common base class \tts{Geant4Action}.} + \label{fig:ddg4-implementation-geant4-action} + \end{center} +\end{figure} + +\noindent +\DDG knowns two types of actions: global actions and anonymous actions. +Global actions are accessible externally from the \tts{Geant4Kernel} instance. +Global actions are also re-usable and hence may be contribute to several +action sequences (see the following chapters for details). Global actions +are uniquely identified by their name. +Anonymous actions are known only within one sequence and normally +are not shared between sequences. + +%============================================================================= +\subsubsection{The Properties of \bold{Geant4Action} Instances} +\label{sec:ddg4-implementation-geant4-action-properties} +%============================================================================= + +\noindent +Nearly any subclass of a \tts{Geant4Action} needs a flexible configuration +in order to be reused, modified etc. The implementation of the mechanism +uses a very flexible value conversion mechanism using \tts{boost::spirit}, +which support also conversions between unrelated types provided a dictionary +is present. + +\noindent +Properties are supposed to be member variables of a given action object. +To publish a property it needs to be declared in the constructor as shown here: +\begin{unnumberedcode} + declareProperty("OutputLevel", m_outputLevel = INFO); + declareProperty("Control", m_needsControl = false); +\end{unnumberedcode} +The internal setup of the \tts{Geant4Action} objects then ensure that +all declared properties will be set after the object construction to the +values set in the setup file. + +\noindent +\bold{Note:} Because the values can only be set \bold{after} the object +was constructed, the actual values may not be used in the constructor +of any base or sub-class. + +%============================================================================= +\subsection{Geant4 Action Sequences} +\label{sec:ddg4-user-manual-implementation-geant4action-sequences} +%============================================================================= + +\noindent +The main action sequences have a fixed name. These are +\begin{itemize} + +\item The \bold{RunAction} attached to the \tts{G4UserRunAction}, implemented + by the \tts{Geant4RunActionSequence} class and is called at the start and the end of + every run (beamOn). Members of the \tts{Geant4RunActionSequence} are of type + \tts{Geant4RunAction} and receive the callbacks by overloading the two routines: +\begin{unnumberedcode} +/// begin-of-run callback +virtual void begin(const G4Run* run); +/// End-of-run callback +virtual void end(const G4Run* run); +\end{unnumberedcode} + or register a callback with the signature {\tts{void (T::*)(const G4Run*)}} + either to receive begin-of-run or end-or-calls using the methods: +\begin{unnumberedcode} +/// Register begin-of-run callback. Types Q and T must be polymorph! +template <typename Q, typename T> void callAtBegin(Q* p, void (T::*f)(const G4Run*)); +/// Register end-of-run callback. Types Q and T must be polymorph! +template <typename Q, typename T> void callAtEnd(Q* p, void (T::*f)(const G4Run*)); +\end{unnumberedcode} + of the \tts{Geant4RunActionSequence} from the \tts{Geant4Context} object. + + +\item The \bold{EventAction} attached to the \tts{G4UserEventAction}, implemented + by the \tts{EventActionSequence} class and is called at the start and the end of + every event. Members of the \tts{Geant4EventActionSequence} are of type + \tts{Geant4EventAction} and receive the callbacks by overloading the two routines: +\begin{unnumberedcode} +/// Begin-of-event callback +virtual void begin(const G4Event* event); +/// End-of-event callback +virtual void end(const G4Event* event); +\end{unnumberedcode} + or register a callback with the signature {\tts{void (T::*)(const G4Event*)}} + either to receive begin-of-run or end-or-calls using the methods: +\begin{unnumberedcode} +/// Register begin-of-event callback +template <typename Q, typename T> void callAtBegin(Q* p, void (T::*f)(const G4Event*)); +/// Register end-of-event callback +template <typename Q, typename T> void callAtEnd(Q* p, void (T::*f)(const G4Event*)); +\end{unnumberedcode} + of the \tts{Geant4EventActionSequence} from the \tts{Geant4Context} object. + + +\item The \bold{GeneratorAction} attached to the \tts{G4VUserPrimaryGeneratorAction}, implemented + by the \tts{Geant4GeneratorActionSequence} class and is called at the start of + every event and provided all initial tracks from the Monte-Carlo generator. + Members of the \tts{Geant4GeneratorActionSequence} are of type + \tts{Geant4EventAction} and receive the callbacks by overloading the member function: +\begin{unnumberedcode} +/// Callback to generate primary particles +virtual void operator()(G4Event* event); +\end{unnumberedcode} + or register a callback with the signature {\tts{void (T::*)(G4Event*)}} + to receive calls using the method: +\begin{unnumberedcode} +/// Register primary particle generation callback. +template <typename Q, typename T> void call(Q* p, void (T::*f)(G4Event*)); +\end{unnumberedcode} + of the \tts{Geant4GeneratorActionSequence} from the \tts{Geant4Context} object. + +\end{itemize} +\begin{figure}[t] + \begin{center} + \includegraphics[width=160mm] {DDG4-TrackingAction.png} + \caption{The design of the tracking action sequence. Specialized + tracking action objects inherit from the \tts{Geant4TrackingAction} + object and must be attached to the sequence.} + \label{fig:ddg4-implementation-tracking-action} + \end{center} +\end{figure} + +\begin{itemize} +\item The \bold{TrackingAction} attached to the \tts{G4UserTrackingAction}, + implemented by the \tts{Geant4-} \tts{Tracking\-Action\-Sequence} class + and is called at the start and the end of tracking one single particle + trace through the material of the detector. + Members of the \tts{Geant4\-Tracking\-ActionSequence} are of type + \tts{Geant4TrackingAction} and receive the callbacks by overloading the member function: +\begin{unnumberedcode} +/// Pre-tracking action callback +virtual void begin(const G4Track* trk); +/// Post-tracking action callback +virtual void end(const G4Track* trk); +\end{unnumberedcode} + or register a callback with the signature {\tts{void (T::*)(const G4Step*, G4SteppingManager*)}} + to receive calls using the method: +\begin{unnumberedcode} +/// Register Pre-track action callback +template <typename Q, typename T> void callAtBegin(Q* p, void (T::*f)(const G4Track*)); +/// Register Post-track action callback +template <typename Q, typename T> void callAtEnd(Q* p, void (T::*f)(const G4Track*)); +\end{unnumberedcode} + + +\item The \bold{SteppingAction} attached to the \tts{G4UserSteppingAction}, implemented + by the \tts{Geant4-} \tts{SteppingActionSequence} class and is called for each + step when tracking a particle. + Members of the \tts{Geant4SteppingActionSequence} are of type + \tts{Geant4SteppingAction} and receive the callbacks by overloading the member function: +\begin{unnumberedcode} +/// User stepping callback +virtual void operator()(const G4Step* step, G4SteppingManager* mgr); +\end{unnumberedcode} + or register a callback with the signature {\tts{void (T::*)(const G4Step*, G4SteppingManager*)}} + to receive calls using the method: +\begin{unnumberedcode} +/// Register stepping action callback. +template <typename Q, typename T> void call(Q* p, void (T::*f)(const G4Step*, + G4SteppingManager*)); +\end{unnumberedcode} + + +\item The \bold{StackingAction} attached to the + {\tts{G4UserStackingAction}}, implemented by the \tts{Geant4-}\\ + \tts{StackingActionSequence} class. + Members of the \tts{Geant4StackingActionSequence} are of type\\ + \detdesc{html/class_d_d4hep_1_1_simulation_1_1_geant4_stacking_action.html} + {\tts{Geant4StackingAction}} and receive the callbacks by overloading the member functions: +\begin{unnumberedcode} +/// New-stage callback +virtual void newStage(); +/// Preparation callback +virtual void prepare(); +\end{unnumberedcode} + or register a callback with the signature {\tts{void (T::*)()}} + to receive calls using the method: +\begin{unnumberedcode} +/// Register begin-of-event callback. Types Q and T must be polymorph! +template <typename T> void callAtNewStage(T* p, void (T::*f)()); +/// Register end-of-event callback. Types Q and T must be polymorph! +template <typename T> void callAtPrepare(T* p, void (T::*f)()); +\end{unnumberedcode} +\end{itemize} + +\noindent +All sequence types support the method \tts{void adopt(T* member\_reference)} +to add the members. Once adopted, the sequence takes ownership and manages +the member. The design of the sequences is very similar. +Figure~\ref{fig:ddg4-implementation-tracking-action} show as an example +the design of the \tts{Geant4TrackingAction}. + +\begin{figure}[h] + \begin{center} + \includegraphics[height=110mm] {DDG4-Sensitive-detector.png} + \caption{The sensitive detector design. The actual energy deposits are + collected in user defined subclasses of the \tts{Geant4Sensitive}. + Here, as an example possible actions called \tts{TrackerHitCollector}, + \tts{TrackerDetailedHitCollector} and \tts{TrackerHitMonitor} are shown.} + \label{fig:ddg4-implementation-sensitive-detector} + \end{center} +\end{figure} + +%============================================================================= +\subsection{Sensitive Detectors} +\label{sec:ddg4-user-manual-geant4sensitivedetectors} +%============================================================================= + +\noindent +Sensitive detectors are associated by the detector designers to all active +materials, which would produce a signal which can be read out. In Geant4 this concept +is realized by using a base class \tts{G4VSensitiveDetector}, which receives +a callback at the begin and the end of the event processing and at each step +inside the active material whenever an energy deposition occurred. + +\noindent +The sensitive actions do not necessarily deal only the collection of energy +deposits, but could also be used to simply monitor the performance of the +active element e.g. by producing histograms of the absolute value or the +spacial distribution of the depositions. + +\noindent +Within \DDG the concept of sensitive detectors is implemented as a +configurable action sequence of type +\detdesc{html/class_d_d4hep_1_1_simulation_1_1_geant4_sens_det_action_sequence.html} +{\tts{Geant4SensDetActionSequence}} +calling members of the type +\detdesc{html/struct_d_d4hep_1_1_simulation_1_1_geant4_sensitive.html} +{\tts{Geant4Sensitive}} as shown in +Figure~\ref{fig:ddg4-implementation-sensitive-detector}. The actual processing +part of such a sensitive action is only called if the and of a set of +required filters of type \tts{Geant4Filter} is positive (see also +section~\ref{sec:ddg4-implementation-sensitive-detector-filters}). No filter +is also positive. Possible filters are e.g. particle filters, which ignore the +sensitive detector action if the particle is a \tts{geantino} or if the +energy deposit is below a given threshold. + +\noindent +Objects of type \tts{Geant4Sensitive} receive the callbacks by overloading the +member function: +\begin{unnumberedcode} + /// Method invoked at the begining of each event. + virtual void begin(G4HCofThisEvent* hce); + /// Method invoked at the end of each event. + virtual void end(G4HCofThisEvent* hce); + /// Method for generating hit(s) using the information of G4Step object. + virtual bool process(G4Step* step, G4TouchableHistory* history); + /// Method invoked if the event was aborted. + virtual void clear(G4HCofThisEvent* hce); +\end{unnumberedcode} +or register a callback with the signature {\tts{void (T::*)(G4HCofThisEvent*)}} +respectively {\tts{void (T::*)(G4Step*, G4TouchableHistory*)}} +to receive callbacks using the methods: +\begin{unnumberedcode} + /// Register begin-of-event callback + template <typename T> void callAtBegin(T* p, void (T::*f)(G4HCofThisEvent*)); + /// Register end-of-event callback + template <typename T> void callAtEnd(T* p, void (T::*f)(G4HCofThisEvent*)); + /// Register process-hit callback + template <typename T> void callAtProcess(T* p, void (T::*f)(G4Step*, G4TouchableHistory*)); + /// Register clear callback + template <typename T> void callAtClear(T* p, void (T::*f)(G4HCofThisEvent*)); +\end{unnumberedcode} + +%============================================================================= +\subsubsection{Sensitive Detector Filters} +\label{sec:ddg4-implementation-sensitive-detector-filters} +%============================================================================= + +\noindent +Filters are called by Geant4 before the +hit processing in the sensitive detectors start. The global filters +may be shared between many sensitive detectors. Alternatively filters +may be directly attached to the sensitive detector in question. +Attributes are directly passed as properties to the filter action. + +\newpage +%============================================================================= +\subsection{The Geant4 Physics List} +\label{sec:ddg4-implementation-physics-list} +%============================================================================= +\noindent +Geant4 provides the base class \tts{G4VUserPhysicsList}. Any user defined +physics list must provide this interface. DDG4 provides such an interface +through the ROOT plugin mechanism using the class \tts{G4VModularPhysicsList}. +The flexibility of \DDG allows for several possibilities to setup the Geant4 +physics list. +\begin{itemize} +\item The \bold{physics list} may be configured as a sequence of type + \detdesc{html/class_d_d4hep_1_1_simulation_1_1_geant4_physics_list_action_sequence.html} + {\tts{Geant4PhysicsListActionSequence}}. + Members of the \detdesc{html/class_d_d4hep_1_1_simulation_1_1_geant4_physics_list_action_sequence.html} + {\tts{Geant4PhysicsListActionSequence}} are of type + \detdesc{html/class_d_d4hep_1_1_simulation_1_1_geant4_physics_list.html} + {\tts{Geant4PhysicsList}} and receive the callbacks by overloading + the member functions: +\begin{unnumberedcode} + /// Callback to construct the physics constructors + virtual void constructProcess(Geant4UserPhysics* interface); + /// constructParticle callback + virtual void constructParticles(Geant4UserPhysics* particle); + /// constructPhysics callback + virtual void constructPhysics(Geant4UserPhysics* physics); +\end{unnumberedcode} + or register a callback with the signature {\tts{void (T::*)(Geant4UserPhysics*)}} + to receive calls using the method: +\begin{unnumberedcode} + /// Register process construction callback t + template <typename Q, typename T> void constructProcess(Q* p, void (T::*f)(Geant4UserPhysics*)); + /// Register particle construction callback + template <typename Q, typename T> void constructParticle(Q* p, void (T::*f)(Geant4UserPhysics*)); +\end{unnumberedcode} + The argument of type \detdesc{html/class_d_d4hep_1_1_simulation_1_1_geant4_user_physics.html} + {\tts{Geant4UserPhysics}} provides a basic interface to the original + \tts{G4VModular}- \tts{PhysicsList}, which allows to register physics constructors etc. + +\item In most of the cases the above approach is an overkill and often even too flexible. + Hence, alternatively, the physics list may consist of a single entry of type + \detdesc{html/class_d_d4hep_1_1_simulation_1_1_geant4_physics_list.html} + {\tts{Geant4PhysicsList}}. +\end{itemize} + +\noindent +The basic implementation of the \tts{Geant4PhysicsList} supports the usage of various +\begin{itemize}\itemcompact +\item \detdesc{}{particle constructors}, such as single particle constructors like + \tts{G4Gamma} or \tts{G4Proton}, or whole particle groups like + \tts{G4BosonConstructor} or \tts{G4IonConstrutor}, +\item \detdesc{}{physics process constructors}, such as e.g. \tts{G4GammaConversion}, + \tts{G4PhotoElectricEffect} or\\ \tts{G4ComptonScattering}, +\item \detdesc{}{physics constructors} combining particles and the corresponding + interactions, such as\\ e.g. \tts{G4OpticalPhysics}, + \tts{HadronPhysicsLHEP} or \tts{G4HadronElasticPhysics} and +\item \detdesc{}{predefined Geant4 physics lists}, such as \tts{FTFP\_BERT}, + \tts{CHIPS} or \tts{QGSP\_INCLXX}. This option is triggered by the + content of the string property "extends" of the \tts{Geant4Kernel::physicsList()} action. +\end{itemize} +These constructors are internally connected to the above callbacks to register themselves. +The constructors are instantiated using the ROOT plugin mechanism. + +\noindent +The description of the above interface is only for completeness. The basic idea is, +that the physics list with its particle and physics constructors is configured +entirely data driven using the setup mechanism described in the following +chapter. However, DDG4 is not limited to the data driven approach. Specialized +physics lists may be supplied, but there should be no need. +New physics lists could always be composed by actually providing new physics +constructors and actually publishing these using the factory methods: +\begin{code} +// Framework include files +#include "DDG4/Factories.h" + +#include "My_Very_Own_Physics_Constructor.h" +DECLARE_GEANT4_PHYSICS(My_Very_Own_Physics_Constructor) +\end{code} +where \tts{My\_Very\_Own\_Physics\_Constructor} represents a sub-class of +\tts{G4VPhysicsConstructor}. + +\newpage +%============================================================================= +\subsection{The Support of the Geant4 UI: \tw{Geant4UIMessenger}} +\label{sec:ddg4-user-manual-geant4action-base} +%============================================================================= + +\noindent +The support of interactive in Geant4 is absolutely mandatory to debug detector +setups in small steps. The Geant4 toolkit did provide for this reason +a machinery of UI commands. +\begin{figure}[h] + \begin{center} + \includegraphics[height=70mm] {DDG4-UIMessenger.png} + \caption{The design of the \tts{Geant4UIMessenger} class responsible for + the interaction between the user and the components of \DDG and Geant4.} + \label{fig:ddg4-tracking-action} + \end{center} +\end{figure} + +\noindent +The UI control is enabled, as soon as the property "Control" (boolean) is set to true. +Be default all properties of the action are exported. +Similar to the callback mechanism described above it is also feasible to +register any object callback invoking a method of a \tts{Geant4Action}-subclass. + +\noindent +The following (shortened) screen dump illustrates the usage of the +generic interface any Geant4Action offers: +\begin{unnumberedcode} +Idle> ls +Command directory path : / + Sub-directories : + /control/ UI control commands. + /units/ Available units. + /process/ Process Table control commands. + /ddg4/ Control for all named Geant4 actions + ... +Idle> cd /ddg4 +Idle> ls +... +Control for all named Geant4 actions + + Sub-directories : + /ddg4/EventAction/ Control hierarchy for Geant4 action:EventAction + /ddg4/RunAction/ Control hierarchy for Geant4 action:RunAction + /ddg4/Gun/ Control hierarchy for Geant4 action:Gun + /ddg4/GeneratorAction/ Control hierarchy for Geant4 action:GeneratorAction + /ddg4/PhysicsList/ Control hierarchy for Geant4 action:PhysicsList +Idle> ls Gun +... +Control hierarchy for Geant4 action:Gun + + Sub-directories : + Commands : + show * Show all properties of Geant4 component:Gun +... + particle * Property item of type std::string + pos_x * Property item of type double + pos_y * Property item of type double + pos_z * Property item of type double +Idle> Gun/show +... +PropertyManager: Property multiplicity = 1 +PropertyManager: Property name = 'Gun' +PropertyManager: Property particle = 'e-' +PropertyManager: Property pos_x = 0 +PropertyManager: Property pos_y = 0 +PropertyManager: Property pos_z = 0 + +Idle> Gun/pos_z 1.0 +Geant4UIMessenger: +++ Gun> Setting new property value pos_z = 1.0. +Idle> Gun/pos_y 1.0 +Geant4UIMessenger: +++ Gun> Setting new property value pos_y = 1.0. +Idle> Gun/pos_x 1.0 +Geant4UIMessenger: +++ Gun> Setting new property value pos_x = 1.0. +Idle> Gun/show +... +PropertyManager: Property pos_x = 1 +PropertyManager: Property pos_y = 1 +PropertyManager: Property pos_z = 1 + +\end{unnumberedcode} + + +\newpage +%============================================================================= +\section{Setting up DDG4} +\label{sec:ddg4-setup} +%============================================================================= + +\noindent + + +%============================================================================= +\subsection{Setting up DDG4 using XML} +\label{sec:ddg4-setup-xml} +%============================================================================= + +\noindent +A special plugin was developed to enable the configuration of \DDG using +XML structures. These files are parsed identically to the geometry setup +in \DDhep the only difference is the name of the root-element, which for +\DDG is \tts{<geant4\_setup>}. +The following code snippet shows the basic structure of a \DDG setup file: +\begin{unnumberedcode} +<geant4_setup> + <physicslist> ,,, </physicslist> <!-- Defintiion of the physics list --> + <actions> ... </actions> <!-- The list of global actions --> + <phases> ... </phases> <!-- The definition of the various phases --> + <filters> ... </filters> <!-- The list of global filter actions --> + <sequences> ... </sequences> <!-- The list of defined sequences --> + <sensitive_detectors> ... </sensitive_detectors> <!-- The list of sensitive detectors --> + <properties> ... </properties> <!-- Free format option sequences --> +</geant4_setup> +\end{unnumberedcode} +To setup a \DDG4 application any number of xml setup files may be interpreted +iteratively. In the following subsections the content of these first level sub-trees will +be discussed. + +%============================================================================= +\subsubsection{Setup of the Physics List} +\label{sec:ddg4-setup-xml-physicslist} +%============================================================================= + +\noindent +The main tag to setup a physics list is \tts{<physicslist>} with the +\tts{name} attribute defining the instance of the \tts{Geant4PhysicsList} object. +An example code snippet is shown below in Figure~\ref{fig:ddg4-setup-xml-physicslist}. + +\begin{code} +<geant4_setup> + <physicslist name="Geant4PhysicsList/MyPhysics.0"> + + <extends name="QGSP_BERT"/> <!-- Geant4 basic Physics list --> + + <particles> <!-- Particle constructors --> + <construct name="G4Geantino"/> + <construct name="G4ChargedGeantino"/> + <construct name="G4Electron"/> + <construct name="G4Gamma"/> + <construct name="G4BosonConstructor"/> + <construct name="G4LeptonConstructor"/> + <construct name="G4MesonConstructor"/> + <construct name="G4BaryonConstructor"/> + ... + </particles> + + <processes> <!-- Process constructors --> + <particle name="e[+-]" cut="1*mm"> + <process name="G4eMultipleScattering" ordAtRestDoIt="-1" ordAlongSteptDoIt="1" + ordPostStepDoIt="1"/> + <process name="G4eIonisation" ordAtRestDoIt="-1" ordAlongSteptDoIt="2" + ordPostStepDoIt="2"/> + </particle> + <particle name="mu[+-]"> + <process name="G4MuMultipleScattering" ordAtRestDoIt="-1" ordAlongSteptDoIt="1" + ordPostStepDoIt="1"/> + <process name="G4MuIonisation" ordAtRestDoIt="-1" ordAlongSteptDoIt="2" + ordPostStepDoIt="2"/> + </particle> + ... + </processes> + + <physics> <!-- Physics constructors --> + <construct name="G4EmStandardPhysics"/> + <construct name="HadronPhysicsQGSP"/> + ... + </physics> + + </physicslist> +</geant4_setup> +\end{code} +\begin{figure}[h] +\caption{XML snippet showing the configuration of a physics list.} +\label{fig:ddg4-setup-xml-physicslist} +\end{figure} + + +To trigger a call to a +\begin{itemize}\itemcompact +\item \bold{particle constructors} (line 7-14), use the \tts{<particles>} section + and define the Geant4 particle constructor to be called by name. To trigger a call to +\item \bold{physics process constructors}, as shown in line 19-30, + Define for each particle matching the name pattern (regular expression!) and the + default cut value for the corresponding processes. The attributes ordXXXX correspond + to the arguments of the Geant4 call \\ + \tts{G4ProcessManager::AddProcess(process,ordAtRestDoIt, ordAlongSteptDoIt,ordPostStepDoIt);} + The processes themself are created using the ROOT plugin mechanism. + To trigger a call to +\item \bold{physics constructors}, as shown in line 34-35, use the \tts{<physics>} section + and +\item to base all these constructs on an already existing predefined Geant4 physics list + use the \tts{<extends>} tag with the attribute containing the name of the physics list + as shown in line 4. +\end{itemize} +If only a predefined physics list is used, which probably already satisfies very many use cases, +all these section collapse to: +\begin{code} +<geant4_setup> + <physicslist name="Geant4PhysicsList/MyPhysics.0"> + <extends name="QGSP_BERT"/> <!-- Geant4 basic Physics list --> + </physicslist> +</geant4_setup> +\end{code} + +%============================================================================= +\subsubsection{Setup of Global Geant4 Actions} +\label{sec:ddg4-setup-xml-geant4-actions} +%============================================================================= + +\noindent +Global actions must be defined in the \tts{<actions>} section as shown in the following snippet: +\begin{code} +<geant4_setup> + <actions> + <action name="Geant4TestRunAction/RunInit"> + <properties Property_int="12345" + Property_double="-5e15" + Property_string="Startrun: Hello_2"/> + </action> + <action name="Geant4TestEventAction/UserEvent_2" + Property_int="1234" + Property_double="5e15" + Property_string="Hello_2" /> + </actions> +</geant4_setup> +\end{code} +The default properties of \bold{every} \tts{Geant4Action} object are: +\begin{unnumberedcode} +Name [string] Action name +OutputLevel [int] Flag to customize the level of printout +Control [boolean] Flag if the UI messenger should be installed. +\end{unnumberedcode} +The \tts{name} attribute of an action child is a qualified name: The first part +denotes the type of the plugin (i.e. its class), the second part the name of the instance. +Within one collection the instance \tts{name} must be unique. +Properties of Geant4Actions are set by placing them as attributes into the +\tts{<properties>} section. + +%============================================================================= +\subsubsection{Setup of Geant4 Filters} +\label{sec:ddg4-setup-xml-geant4-filters} +%============================================================================= +\noindent +Filters are special actions called by \tts{Geant4Sensitive}s. +Filters may be global or anonymous i.e. reusable by several sensitive detector +sequences as illustrated in Section~\ref{sec:ddg4-setup-xml-geant4-sequences}. +The setup is analogous to the setup of global actions: +\begin{code} + <filters> + <filter name="GeantinoRejectFilter/GeantinoRejector"/> + <filter name="ParticleRejectFilter/OpticalPhotonRejector"> + <properties particle="opticalphoton"/> + </filter> + <filter name="ParticleSelectFilter/OpticalPhotonSelector"> + <properties particle="opticalphoton"/> + </filter> + <filter name="EnergyDepositMinimumCut"> + <properties Cut="10*MeV"/> + </filter> + <!-- ... next global filter ... --> + </filters> +\end{code} +Global filters are accessible from the \tts{Geant4Kernel} object. + +%============================================================================= +\subsubsection{Geant4 Action Sequences} +\label{sec:ddg4-setup-xml-geant4-sequences} +%============================================================================= + +\noindent +\tts{Geant4 Action Sequences} by definition are \tts{Geant4Action} objects. +Hence, they share the setup mechanism with properties etc. For the setup +mechanism two different types of sequences are known to \DDG: +{\it{Action sequences}} and {\it{Sensitive detector sequences}}. Bot are declared in +the \tts{sequences} section: +\begin{code} +<geant4_setup> + <sequences> + <sequence name="Geant4EventActionSequence/EventAction"> <!-- Sequence "EventAction" of type + "Geant4EventActionSequence" --> + <action name="Geant4TestEventAction/UserEvent_1"> <!-- Anonymouns action --> + <properties Property_int="01234" <!-- Properties go inline --> + Property_double="1e11" + Property_string="'Hello_1'"/> + </action> + <action name="UserEvent_2"/> <!-- Global action defined in "actions" --> + <!-- Only the name is referenced here --> + <action name="Geant4Output2ROOT/RootOutput"> <!-- ROOT I/O action --> + <properties Output="simple.root"/> <!-- Output file property --> + </action> + <action name="Geant4Output2LCIO/LCIOOutput"> <!-- LCIO output action --> + <properties Output="simple_lcio"/> <!-- Output file property --> + </action> + </sequence> + + + <sequence sd="SiTrackerBarrel" type="Geant4SensDetActionSequence"> + <filter name="GeantinoRejector"/> + <filter name="EnergyDepositMinimumCut"/> + <action name="Geant4SimpleTrackerAction/SiTrackerBarrelHandler"/> + </sequence> + <sequence sd="SiTrackerEndcap" type="Geant4SensDetActionSequence"> + <filter name="GeantinoRejector"/> + <filter name="EnergyDepositMinimumCut"/> + <action name="Geant4SimpleTrackerAction/SiTrackerEndcapHandler"/> + </sequence> + <!-- ... next sequence ... --> + </sequences> +</geant4_setup> +\end{code} +Here firstly the \bold{EventAction} sequence is defined with its members. +Secondly a sensitve detector sequence is defined for the subdetector +\tts{SiTrackerBarrel} of type \tts{Geant4SensDetActionSequence}. +The sequence uses two filters: \tts{GeantinoRejector} to not generate hits +from geantinos and \tts{EnergyDepositMinimumCut} to enforce a minimal energy deposit. +These filters are global i.e. they may be applied by many subdetectors. +The setup of global filters is described in +Section~\ref{sec:ddg4-setup-xml-geant4-filters}. +Finally the action \tts{SiTrackerEndcapHandler} of type \tts{Geant4SimpleTrackerAction} +is chained, which collects the deposited energy and +creates a collection of hits. The \tts{Geant4SimpleTrackerAction} is a template +callback to illustrate the usage of sensitive elements in \DDG. +The resulting hit collection of these handlers by default have the same name as the +object instance name. +Analogous below the sensitive detector sequence for the subdetector +\tts{SiTrackerEndcap} is shown, which reuses the same filter actions, but will build its own +hit collection. + +\noindent +\bold{Plase note:} +\begin{itemize}\itemcompact +\item \bold{It was already mentioned, but once again}: Event-, run-, generator-, tracking-, + stepping- and stacking actions sequences have predefined names! + These names are fixed and part of the \bold{common knowledge}, they cannot be altered. + Please refer to + Section~\ref{sec:ddg4-user-manual-implementation-geant4action-sequences} + for the names of the global action sequences. +\item the sensitive detector sequences are matched by the attribute \tts{sd} to the + subdetectors created with the \DDhep detector description package. Values must match! +\item In the event that several xml files are parsed it is absolutely vital that + the \tts{<actions>} section is interpreted \bold{before} the \tts{sequences}. +\item For each XML file several \tts{<sequences>} are allowed. +\noindent +\end{itemize} + +%============================================================================= +\subsubsection{Setup of Geant4 Sensitive Detectors} +\label{sec:ddg4-setup-xml-geant4-sensitive detectors} +%============================================================================= +\begin{code} + <geant4_setup> + <sensitive_detectors> + <sd name="SiTrackerBarrel" + type="Geant4SensDet" + ecut="10.0*MeV" + verbose="true" + hit_aggregation="position"> + </sd> + <!-- ... next sensitive detector ... --> + </sensitive_detectors> + </geant4_setup> +\end{code} + + + +%============================================================================= +\subsubsection{Miscellaneous Setup of Geant4 Objects} +\label{sec:ddg4-setup-xml-geant4-objects} +%============================================================================= + +\noindent +This section is used for the flexible setup of auxiliary objects such as the +electromagnetic fields used in Geant4: +\begin{code} + <geant4_setup> + <properties> + <attributes name="geant4_field" + id="0" + type="Geant4FieldSetup" + object="GlobalSolenoid" + global="true" + min_chord_step="0.01*mm" + delta_chord="0.25*mm" + delta_intersection="1e-05*mm" + delta_one_step="0.001*mm" + eps_min="5e-05*mm" + eps_max="0.001*mm" + stepper="HelixSimpleRunge" + equation="Mag_UsualEqRhs"> + </attributes> + ... + </properties> + </geant4_setup> +\end{code} +Important are the tags \tts{type} and \tts{object}, which are used to firstly +define the plugin to be called and secondly define the object from the \DDhep +description to be configured for the use within Geant4. + +%============================================================================= +\subsubsection{Setup of Geant4 Phases} +\label{sec:ddg4-setup-xml-geant4-phases} +%============================================================================= + +\noindent +Phases are configured as shown below. +However, the use is \bold{discouraged}, +since it is not yet clear if there are appropriate use cases! +\begin{code} + <phases> + <phase type="RunAction/begin"> + <action name="RunInit"/> + <action name="Geant4TestRunAction/UserRunInit"> + <properties Property_int="1234" + Property_double="5e15" + Property_string="'Hello_2'"/> + </action> + </phase> + <phase type="EventAction/begin"> + <action name="UserEvent_2"/> + </phase> + <phase type="EventAction/end"> + <action name="UserEvent_2"/> + </phase> + ... + </phases> +\end{code} + +\newpage +%============================================================================= +\subsection{Setting up DDG4 using ROOT-CINT} +\label{sec:ddg4-setup-root-cint} +%============================================================================= + +\noindent +The setup of \DDG directly from the the ROOT interpreter using the AClick +mechanism is very simple, but mainly meant for purists (like me ;-)), +since it is nearly equivalent to the explicit setup within a \tts{C++} +main program. +The following code section shows how to do it. For explanation the code +secment is discussed below line by line. +\begin{code} +#include "DDG4/Geant4Config.h" +#include "DDG4/Geant4TestActions.h" +#include "DDG4/Geant4TrackHandler.h" +#include <iostream> + +using namespace std; +using namespace DD4hep; +using namespace DD4hep::Simulation; +using namespace DD4hep::Simulation::Test; +using namespace DD4hep::Simulation::Setup; + +#if defined(__MAKECINT__) +#pragma link C++ class Geant4RunActionSequence; +#pragma link C++ class Geant4EventActionSequence; +#pragma link C++ class Geant4SteppingActionSequence; +#pragma link C++ class Geant4StackingActionSequence; +#pragma link C++ class Geant4GeneratorActionSequence; +#pragma link C++ class Geant4Action; +#pragma link C++ class Geant4Kernel; +#endif + +SensitiveSeq::handled_type* setupDetector(Kernel& kernel, const std::string& name) { + SensitiveSeq sd = SensitiveSeq(kernel,name); + Sensitive sens = Sensitive(kernel,"Geant4TestSensitive/"+name+"Handler",name); + sd->adopt(sens); + sens = Sensitive(kernel,"Geant4TestSensitive/"+name+"Monitor",name); + sd->adopt(sens); + return sd; +} + +void exampleAClick() { + Geant4Kernel& kernel = Geant4Kernel::instance(LCDD::getInstance()); + kernel.loadGeometry("file:../DD4hep.trunk/DDExamples/CLICSiD/compact/compact.xml"); + kernel.loadXML("DDG4_field.xml"); + + GenAction gun(kernel,"Geant4ParticleGun/Gun"); + gun["energy"] = 0.5*GeV; // Set properties + gun["particle"] = "e-"; + gun["multiplicity"] = 1; + kernel.generatorAction().adopt(gun); + + Action run_init(kernel,"Geant4TestRunAction/RunInit"); + run_init["Property_int"] = 12345; + kernel.runAction().callAtBegin (run_init.get(),&Geant4TestRunAction::begin); + kernel.eventAction().callAtBegin(run_init.get(),&Geant4TestRunAction::beginEvent); + kernel.eventAction().callAtEnd (run_init.get(),&Geant4TestRunAction::endEvent); + + Action evt_1(kernel,"Geant4TestEventAction/UserEvent_1"); + evt_1["Property_int"] = 12345; // Set properties + evt_1["Property_string"] = "Events"; + kernel.eventAction().adopt(evt_1); + + EventAction evt_2(kernel,"Geant4TestEventAction/UserEvent_2"); + kernel.eventAction().adopt(evt_2); + + kernel.runAction().callAtBegin(evt_2.get(),&Geant4TestEventAction::begin); + kernel.runAction().callAtEnd (evt_2.get(),&Geant4TestEventAction::end); + + setupDetector(kernel,"SiVertexBarrel"); + setupDetector(kernel,"SiVertexEndcap"); + // .... more subdetectors here ..... + setupDetector(kernel,"LumiCal"); + setupDetector(kernel,"BeamCal"); + + kernel.configure(); + kernel.initialize(); + kernel.run(); + std::cout << "Successfully executed application .... " << std::endl; + kernel.terminate(); +} +\end{code} + +\noindent +\begin{tabular} {l||p{0cm}} +\docline{Line}{} +\docline{1}{The header file \tts{Geant4Config.h} contains a set of wrapper + classes to easy the creation of objects using the plugin mechanism and setting + properties to \tts{Geant4Action} objects. These helpers and the corresponding + functionality are not included in the wrapped classes themselves to not + clutter the code with stuff only used for the setup. + All contained objects are in the namespace \tts{DD4hep::Simulation::Setup}}. +\docline{6-10}{Save yourself specifying all the namespaces objects are in....} +\docline{13-19}{CINT processing pragmas. + Classes defined here will be available at the ROOT prompt + after this AClick is loaded.} +\docline{22-29}{Sampler to fill the sensitive detector sequences for each + subdetector with two entries: a handler and a monitor action. + Please note, that this here is example code and in real life specialized actions + will have to be provided for each subdetector.} +\docline{31}{Let's go for it. here the entry point starts....} +\docline{32}{Create the \tts{Geant4Kernel} object.} +\docline{33}{Load the geometry into \DDhep.} +\docline{34}{Redefine the setup of the sensitive detectors.} +\docline{36-40}{Create the generator action of type \tts{Geant4ParticleGun} with name + \tts{Gun}, set non-default properties and activate the configured object + by attaching it to the \tts{Geant4Kernel}.} +\docline{42-46}{Create a user defined begin-of-run action callback, set the properties + and attach it to the begin of run calls. To collect statistics extra member functions + are registered to be called at the beginning and the end of each event.} +\docline{48-51}{Create a user defined event action routine, set its properties + and attach it to the event action sequence.} +\docline{53-54}{Create a second event action and register it to the event action sequence. + This action will be called after the previously created action.} +\docline{56-57}{For this event action we want to receive callbacks at start- + and end-of-run to produce additional summary output.} +\docline{59-63}{Call the sampler routine to attach test actions to the subdetectors defined.} +\docline{65-66}{Configure, initialize and run the Geant4 application. + Most of the Geant4 actions will only be created here and the action sequences + created before will be attached now.} +\docline{69}{Terminate the Geant4 application and exit.} +\end{tabular} + +\newpage +\noindent +CINT currently cannot handle pointers to member functions~\footnote{This may change +in the future once ROOT uses \tts{clang} and \tts{cling} as the interpreting engine.}. +Hence the above AClick only works in compiled mode. To invoke the compilation the following +action is necessary from the ROOT prompt: + + +\begin{code} +$> root.exe + ******************************************* + * * + * W E L C O M E to R O O T * + * * + * Version 5.34/10 29 August 2013 * + * * + * You are welcome to visit our Web site * + * http://root.cern.ch * + * * + ******************************************* + +ROOT 5.34/10 (heads/v5-34-00-patches@v5-34-10-5-g0e8bac8, Sep 04 2013, 11:52:19 on linux) + +CINT/ROOT C/C++ Interpreter version 5.18.00, July 2, 2010 +Type ? for help. Commands must be C++ statements. +Enclose multiple statements between { }. +root [0] .X initAClick.C +.... Setting up the CINT include pathes and the link statements. + +root [1] .L ../DD4hep.trunk/DDG4/examples/exampleAClick.C+ +Info in <TUnixSystem::ACLiC>: creating shared library ....exampleAClick_C.so +.... some Cint warnings concerning member function pointers ..... + +root [2] exampleAClick() +.... and it starts ... +\end{code} + +\noindent +The above scripts are present in the DDG4/example directory located in svn. +The intialization script \tts{initAClick.C} may require customization +to cope with the installation pathes. + +%============================================================================= +\subsection{Setting up DDG4 using Python} +\label{sec:ddg4-setup-python} +%============================================================================= + +\noindent +Given the reflection interface of ROOT, the setup of the simulation interface +using DD4hep is of course also possible using the python interpreted language. +In the following code example the setup of Geant4 using the \tw{ClicSid} +example is shown using python~\footnote{For comparison, the same example was +used to illustrate the setup using XML files.}. + +\begin{code} +import DDG4 +from SystemOfUnits import * + +""" + + DD4hep example setup using the python configuration + + @author M.Frank + @version 1.0 + +""" +def run(): + kernel = DDG4.Kernel() + kernel.loadGeometry("file:../DD4hep.trunk/DDExamples/CLICSiD/compact/compact.xml") + kernel.loadXML("DDG4_field.xml") + + lcdd = kernel.lcdd() + print '+++ List of sensitive detectors:' + for i in lcdd.detectors(): + o = DDG4.DetElement(i.second) + sd = lcdd.sensitiveDetector(o.name()) + if sd.isValid(): + print '+++ %-32s type:%s'%(o.name(), sd.type(), ) + + # Configure Run actions + run1 = DDG4.RunAction(kernel,'Geant4TestRunAction/RunInit') + run1.Property_int = 12345 + run1.Property_double = -5e15*keV + run1.Property_string = 'Startrun: Hello_2' + print run1.Property_string, run1.Property_double, run1.Property_int + run1.enableUI() + kernel.registerGlobalAction(run1) + kernel.runAction().add(run1) + + # Configure Event actions + evt2 = DDG4.EventAction(kernel,'Geant4TestEventAction/UserEvent_2') + evt2.Property_int = 123454321 + evt2.Property_double = 5e15*GeV + evt2.Property_string = 'Hello_2 from the python setup' + evt2.enableUI() + kernel.registerGlobalAction(evt2) + + evt1 = DDG4.EventAction(kernel,'Geant4TestEventAction/UserEvent_1') + evt1.Property_int=01234 + evt1.Property_double=1e11 + evt1.Property_string='Hello_1' + evt1.enableUI() + + kernel.eventAction().add(evt1) + kernel.eventAction().add(evt2) + + # Configure I/O + evt_root = DDG4.EventAction(kernel,'Geant4Output2ROOT/RootOutput') + evt_root.Control = True + evt_root.Output = "simple.root" + evt_root.enableUI() + + evt_lcio = DDG4.EventAction(kernel,'Geant4Output2LCIO/LcioOutput') + evt_lcio.Output = "simple_lcio" + evt_lcio.enableUI() + + kernel.eventAction().add(evt_root) + kernel.eventAction().add(evt_lcio) + + # Setup particle gun + gun = DDG4.GeneratorAction(kernel,"Geant4ParticleGun/Gun") + gun.energy = 0.5*GeV + gun.particle = 'e-' + gun.multiplicity = 1 + gun.enableUI() + kernel.generatorAction().add(gun) + + # Setup global filters fur use in sensntive detectors + f1 = DDG4.Filter(kernel,'GeantinoRejectFilter/GeantinoRejector') + f2 = DDG4.Filter(kernel,'ParticleRejectFilter/OpticalPhotonRejector') + f2.particle = 'opticalphoton' + f3 = DDG4.Filter(kernel,'ParticleSelectFilter/OpticalPhotonSelector') + f3.particle = 'opticalphoton' + f4 = DDG4.Filter(kernel,'EnergyDepositMinimumCut') + f4.Cut = 10*MeV + f4.enableUI() + kernel.registerGlobalFilter(f1) + kernel.registerGlobalFilter(f2) + kernel.registerGlobalFilter(f3) + kernel.registerGlobalFilter(f4) + + # First the tracking detectors + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/SiVertexBarrel') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleTrackerAction/SiVertexBarrelHandler','SiVertexBarrel') + seq.add(act) + seq.add(f1) + seq.add(f4) + act.add(f1) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/SiVertexEndcap') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleTrackerAction/SiVertexEndcapHandler','SiVertexEndcap') + seq.add(act) + seq.add(f1) + seq.add(f4) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/SiTrackerBarrel') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleTrackerAction/SiTrackerBarrelHandler','SiTrackerBarrel') + seq.add(act) + seq.add(f1) + seq.add(f4) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/SiTrackerEndcap') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleTrackerAction/SiTrackerEndcapHandler','SiTrackerEndcap') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/SiTrackerForward') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleTrackerAction/SiTrackerForwardHandler','SiTrackerForward') + seq.add(act) + + # Now the calorimeters + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/EcalBarrel') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/EcalBarrelHandler','EcalBarrel') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/EcalEndcap') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/EcalEndCapHandler','EcalEndcap') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/HcalBarrel') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/HcalBarrelHandler','HcalBarrel') + act.adoptFilter(kernel.globalFilter('OpticalPhotonRejector')) + seq.add(act) + + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/HcalOpticalBarrelHandler','HcalBarrel') + act.adoptFilter(kernel.globalFilter('OpticalPhotonSelector')) + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/HcalEndcap') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/HcalEndcapHandler','HcalEndcap') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/HcalPlug') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/HcalPlugHandler','HcalPlug') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/MuonBarrel') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/MuonBarrelHandler','MuonBarrel') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/MuonEndcap') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/MuonEndcapHandler','MuonEndcap') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/LumiCal') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/LumiCalHandler','LumiCal') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/BeamCal') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/BeamCalHandler','BeamCal') + seq.add(act) + + # Now build the physics list: + phys = kernel.physicsList() + phys.extends = 'FTFP_BERT' + #phys.transportation = True + phys.decays = True + phys.enableUI() + + ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics') + ph.addParticleConstructor('G4BosonConstructor') + ph.addParticleConstructor('G4LeptonConstructor') + ph.addParticleProcess('e[+-]','G4eMultipleScattering',-1,1,1) + ph.addPhysicsConstructor('G4OpticalPhysics') + ph.enableUI() + phys.add(ph) + + phys.dump() + + kernel.configure() + kernel.initialize() + kernel.run() + kernel.terminate() + +if __name__ == "__main__": + run() + +\end{code} + + +%============================================================================= +\newpage +\begin{thebibliography}{9} +\input{DD4hep-bibliography.tex} +\bibitem{bib:DDSegmentations} C.Grefe et al., + "The DDSegmentation package", + Non existing documentation to be written. +\end{thebibliography} +%============================================================================= +\end{document} diff --git a/doc/LaTex/DDG4Manual.tex b/doc/LaTex/DDG4Manual.tex new file mode 100644 index 0000000000000000000000000000000000000000..b1e28334fdd79e97591f25b35164b14c76df6c15 --- /dev/null +++ b/doc/LaTex/DDG4Manual.tex @@ -0,0 +1,1576 @@ +%============================================================================= +\documentclass[10pt,a4paper]{article} +% +\input{DD4hep-setup.tex} +% +\pagestyle{fancyplain}{\fancyfoot[C]{\sffamily{DDG4 User Manual}}} +% +\begin{document} +% +\mytitle{ +DDG4 +}{ +A Simulation Toolkit for \\ +\vspace{0.5cm} +High Energy Physics Experiments\\ +\vspace{0.5cm} +using Geant4 and the \\ +\vspace{0.5cm} +DD4hep Geometry Description +}{DDG4 User Manual} +% +% +%== Abstract =============================================================== +\pagestyle{plain} +\pagenumbering{Roman} +\setcounter{page}{1} +\begin{abstract} +%============================================================================= + +\noindent +\normalsize +Simulating the detector response is an essential tool in high energy physics +to analyze the sensitivity of an experiment to the underlying physics. +Such simulation tools require a detailed though convenient detector description as +it is provided by the \DDhep toolkit. +We will present the generic simulation toolkit \DDG using the \DDhep detector +description toolkit. +The toolkit implements a modular and flexible approach to simulation activities +using Geant4. User defined simulation applications using \DDG +can easily be configured, extended using specialzed action routines. +The design is strongly driven by easy of use; +developers of detector descriptions and applications using +them should provide minimal information and minimal specific +code to achieve the desired result. + +\end{abstract} + +\vspace{8cm} + +\begin{center} +{\large{\bf{ +\begin{tabular} {| l | l | l |} +\hline +\multicolumn{3}{| c |}{} \\[0.2cm] +\multicolumn{3}{| c |}{Document History} \\[0.2cm] +\multicolumn{3}{| c |}{} \\[0.2cm] +\hline + & & \\ +Document & & \\ +version & Date & Author \\[0.2cm] \hline + & & \\ +1.0 & 19/11/2013 & Markus Frank CERN/LHCb \\ + & & \\ \hline +\end{tabular} +}}} +\end{center} + +\clearpage +% +% +%== TOC ==================================================================== +\tableofcontents +\clearpage +% +% +%============================================================================= +% Manual +%============================================================================= +\pagenumbering{arabic} +\setcounter{page}{1} + +%============================================================================= +\section{Introduction} +\label{sec:ddg4-user-manual-introduction} +%============================================================================= +\noindent +This manual should introduce to the DDG4 framework. +One goal of \DDG is to easily configure the simulation applications +capable of simulating the physics response of detector configurations +as they are used for example in high energy physics experiments. +In such simulation programs the user normally has to define the +experimental setup in terms of its geometry and in terms of its +active elements which sample the detector response. + +\noindent +The goal of \DDG is to generalize the configuration of a simulation +application to a degree, which does not force users to write code +to test a detector design. At the same time it should of course +be feasible to supply specialized user written modules which are supposed +to seamlessly operate together with standard modules supplied by the toolkit. +Detector-simulation depends strongly on the use of an underlying simulation +toolkit, the most prominent candidate nowadays being Geant4~\cite{bib:geant4}. +\DDhep supports simulation activities with Geant4 providing +an automatic translation mechanism between geometry representations. +The simulation response in the active elements of the detector +is strongly influenced by the technical +choices and precise simulations depends on the very specific detection techniques. + +\noindent +Similar to the aim of \DDhep~\cite{bib:DD4hep}, +where with time a standard palette of detector +components developed by users should become part of the toolkit, +\DDG also hopes to provide a standard palette of components used +to support simulation activities for detector layouts +where detector designers may base the simulation of a planned experiment +on these predefined components for initial design and optimization +studies. The longterm vision is to construct simulation applications +writing only new components not yet present i.e. the main work will be to +select the appropriate components from the palette and connect them +to a functional program. + +\noindent +This is not a manual to Geant4 nor the basic infrastructure of \DDhep. +It is assumed that this knowledge is present and the typical glossary +is known. + +%============================================================================= +\section{The Geant4 User Interface} +\label{sec:ddg4-user-manual-geant4-interface} +%============================================================================= + +\noindent +The Geant4 simulation toolkit~\cite{bib:geant4} implements a very complex +machinery to simulate the energy deposition of particles traversing materials. +To ease its usage for the clients and to shield clients from the complex +internals when actually implementing a simulation applications for a +given detector design, it provides several user hooks +as shown in Figure~\ref{fig:ddg4-g4runmanager-anatomy}. Each of these hooks +serves a well specialized purpose, but unfortunately also leads to very +specialized applications. One aim of \DDG is to formalize these user +actions so that the invocation at the appropriate time may be purely +data driven. +\begin{figure}[h] + \begin{center} + \includegraphics[height=70mm] {DDG4-G4RunManagerAnatomy.png} + \caption{The various user hooks provided by Geant4. Not shown here + is the callback system interfacing to the active elements + of the detector design.} + \label{fig:ddg4-g4runmanager-anatomy} + \end{center} +\end{figure} + +\noindent +In detail the following object-hooks allow the client to define user provided actions: +\begin{itemize}\itemcompact +\item The \bold{User Physics List} allows the client to customize and define + the underlying physics process(es) which define the particle interactions + inside the detector defined with the geometry description. + These interactions define the detector response in terms of + energy depositions. +\item The \bold{Run Action} is called once at the start and end of a run. + i.e. a series of generated events. These two callbacks + allow clients to define run-dependent actions such as statistics + summaries etc. +\item The \bold{Primary Generator Action} is called for every event. + During the callback all particles are created which form the + microscopic kinematic action of the particle collision. + This input may either origin directly from an event generator program + or come from file. +\item The \bold{Event Action} is called once at the start and the end of each event. + It is typically used for a simple analysis of the processed event. + If the simulated data should be written to some persistent medium, + the call at the end of the event processing is the appropriate place. +\item The \bold{Tracking Action} +\item The \bold{Stepping Action} +\item The \bold{Stacking Action} +\end{itemize} +\noindent +Geant4 provides all callbacks with the necessary information in the form of +appropriate arguments. + +\noindent +Besides the callback system, Geant4 provides callbacks whenever a particle +traverses a sensitive volume. These callbacks are called +- similar to event actions - once at the start and the end of the event, +but in addition, if either the energy deposit of a particle in the +sensitive volume exceeds some threshold. The callbacks are formalized within +the base class \tts{G4VSensitiveDetector}. + +%============================================================================= +\section{DDG4 Implementation} +\label{sec:ddg4-user-manual-implementation} +%============================================================================= + +\noindent +A basic design criteria of the a \DDG simulation application was to +process any user defined hook provided by Geant4 as a series of algorithmic +procedures, which could be implemented either using inheritance or by +a callback mechanism registering functions fulfilling a given signature. +Such sequences are provided for all actions mentioned in the list in +Section~\ref{sec:ddg4-user-manual-geant4-interface} as well as for +the callbacks to sensitive detectors. + +\noindent +The callback mechanism was introduced to allow for weak coupling between +the various actions. For example could an action performing monitoring +using histograms at the event level initialize or reset its histograms +at the start/end of each run. To do so, clearly a callback at the +start/end of a run would be necessary. + +\noindent +In the following sections a flexible and extensible interface to hooks +of Geant4 is discussed starting with the description of the basic +components \tts{Geant4Kernel} and \tts{Geant4Action} followed by the +implementation of the relevant specializations. +The specializations exposed are sequences of such actions, +which also call registered objects. +In later section the configuration and the combination of these components +forming a functional simulation application is presented. + +%============================================================================= +\subsection{The Application Core Object: \tts{Geant4Kernel}} +\label{sec:ddg4-user-manual-implementation-geant4kernel} +%============================================================================= + +\noindent +The kernel object is the central context of a \DDG simulation application and +gives all clients access to the user hooks (see Figure~\ref{fig:ddg4-geant4-kernel}). +All Geant4 callback structures are exposed so that clients can easily +objects implementing the required interface or register callbacks with the +correct signature. +\begin{figure}[h] + \begin{center} + \includegraphics[height=80mm] {DDG4-Geant4Kernel.png} + \caption{The sensitive detector design.} + \label{fig:ddg4-geant4-kernel} + \end{center} +\end{figure} + +%============================================================================= +\subsection{The Base Class of DDG4 Actions: \tts{Geant4Action}} +\label{sec:ddg4-user-manual-implementation-geant4action-base} +%============================================================================= + +\noindent +The class \tts{Geant4Action} is a common component interface providing +the basic interface to the framework to +\begin{itemize}\itemcompact +\item configure the component using a property mechanism +\item provide an appropriate interface to Geant4 interactivity. The interactivity + included a generic way to change and access properties from the Geant4 UI + prompt as well as executing registered commands. +\item As shown in Figure~\ref{fig:ddg4-implementation-geant4-action}, the + base class also provides to its sub-class a reference to the \tts{Geant4Kernel} + objects through the \tts{Geant4Context}. +\end{itemize} +The \tts{Geant4Action} is a named entity and can be uniquely identified within +a sequence attached to one Geant4 user callback. +%============================================================================= +\begin{figure}[h] + \begin{center} + \includegraphics[height=30mm] {DDG4-Geant4Action.png} + \caption{The design of the common base class \tts{Geant4Action}.} + \label{fig:ddg4-implementation-geant4-action} + \end{center} +\end{figure} + +\noindent +\DDG knowns two types of actions: global actions and anonymous actions. +Global actions are accessible externally from the \tts{Geant4Kernel} instance. +Global actions are also re-usable and hence may be contribute to several +action sequences (see the following chapters for details). Global actions +are uniquely identified by their name. +Anonymous actions are known only within one sequence and normally +are not shared between sequences. + +%============================================================================= +\subsubsection{The Properties of \bold{Geant4Action} Instances} +\label{sec:ddg4-implementation-geant4-action-properties} +%============================================================================= + +\noindent +Nearly any subclass of a \tts{Geant4Action} needs a flexible configuration +in order to be reused, modified etc. The implementation of the mechanism +uses a very flexible value conversion mechanism using \tts{boost::spirit}, +which support also conversions between unrelated types provided a dictionary +is present. + +\noindent +Properties are supposed to be member variables of a given action object. +To publish a property it needs to be declared in the constructor as shown here: +\begin{unnumberedcode} + declareProperty("OutputLevel", m_outputLevel = INFO); + declareProperty("Control", m_needsControl = false); +\end{unnumberedcode} +The internal setup of the \tts{Geant4Action} objects then ensure that +all declared properties will be set after the object construction to the +values set in the setup file. + +\noindent +\bold{Note:} Because the values can only be set \bold{after} the object +was constructed, the actual values may not be used in the constructor +of any base or sub-class. + +%============================================================================= +\subsection{Geant4 Action Sequences} +\label{sec:ddg4-user-manual-implementation-geant4action-sequences} +%============================================================================= + +\noindent +The main action sequences have a fixed name. These are +\begin{itemize} + +\item The \bold{RunAction} attached to the \tts{G4UserRunAction}, implemented + by the \tts{Geant4RunActionSequence} class and is called at the start and the end of + every run (beamOn). Members of the \tts{Geant4RunActionSequence} are of type + \tts{Geant4RunAction} and receive the callbacks by overloading the two routines: +\begin{unnumberedcode} +/// begin-of-run callback +virtual void begin(const G4Run* run); +/// End-of-run callback +virtual void end(const G4Run* run); +\end{unnumberedcode} + or register a callback with the signature {\tts{void (T::*)(const G4Run*)}} + either to receive begin-of-run or end-or-calls using the methods: +\begin{unnumberedcode} +/// Register begin-of-run callback. Types Q and T must be polymorph! +template <typename Q, typename T> void callAtBegin(Q* p, void (T::*f)(const G4Run*)); +/// Register end-of-run callback. Types Q and T must be polymorph! +template <typename Q, typename T> void callAtEnd(Q* p, void (T::*f)(const G4Run*)); +\end{unnumberedcode} + of the \tts{Geant4RunActionSequence} from the \tts{Geant4Context} object. + + +\item The \bold{EventAction} attached to the \tts{G4UserEventAction}, implemented + by the \tts{EventActionSequence} class and is called at the start and the end of + every event. Members of the \tts{Geant4EventActionSequence} are of type + \tts{Geant4EventAction} and receive the callbacks by overloading the two routines: +\begin{unnumberedcode} +/// Begin-of-event callback +virtual void begin(const G4Event* event); +/// End-of-event callback +virtual void end(const G4Event* event); +\end{unnumberedcode} + or register a callback with the signature {\tts{void (T::*)(const G4Event*)}} + either to receive begin-of-run or end-or-calls using the methods: +\begin{unnumberedcode} +/// Register begin-of-event callback +template <typename Q, typename T> void callAtBegin(Q* p, void (T::*f)(const G4Event*)); +/// Register end-of-event callback +template <typename Q, typename T> void callAtEnd(Q* p, void (T::*f)(const G4Event*)); +\end{unnumberedcode} + of the \tts{Geant4EventActionSequence} from the \tts{Geant4Context} object. + + +\item The \bold{GeneratorAction} attached to the \tts{G4VUserPrimaryGeneratorAction}, implemented + by the \tts{Geant4GeneratorActionSequence} class and is called at the start of + every event and provided all initial tracks from the Monte-Carlo generator. + Members of the \tts{Geant4GeneratorActionSequence} are of type + \tts{Geant4EventAction} and receive the callbacks by overloading the member function: +\begin{unnumberedcode} +/// Callback to generate primary particles +virtual void operator()(G4Event* event); +\end{unnumberedcode} + or register a callback with the signature {\tts{void (T::*)(G4Event*)}} + to receive calls using the method: +\begin{unnumberedcode} +/// Register primary particle generation callback. +template <typename Q, typename T> void call(Q* p, void (T::*f)(G4Event*)); +\end{unnumberedcode} + of the \tts{Geant4GeneratorActionSequence} from the \tts{Geant4Context} object. + +\end{itemize} +\begin{figure}[t] + \begin{center} + \includegraphics[width=160mm] {DDG4-TrackingAction.png} + \caption{The design of the tracking action sequence. Specialized + tracking action objects inherit from the \tts{Geant4TrackingAction} + object and must be attached to the sequence.} + \label{fig:ddg4-implementation-tracking-action} + \end{center} +\end{figure} + +\begin{itemize} +\item The \bold{TrackingAction} attached to the \tts{G4UserTrackingAction}, + implemented by the \tts{Geant4-} \tts{Tracking\-Action\-Sequence} class + and is called at the start and the end of tracking one single particle + trace through the material of the detector. + Members of the \tts{Geant4\-Tracking\-ActionSequence} are of type + \tts{Geant4TrackingAction} and receive the callbacks by overloading the member function: +\begin{unnumberedcode} +/// Pre-tracking action callback +virtual void begin(const G4Track* trk); +/// Post-tracking action callback +virtual void end(const G4Track* trk); +\end{unnumberedcode} + or register a callback with the signature {\tts{void (T::*)(const G4Step*, G4SteppingManager*)}} + to receive calls using the method: +\begin{unnumberedcode} +/// Register Pre-track action callback +template <typename Q, typename T> void callAtBegin(Q* p, void (T::*f)(const G4Track*)); +/// Register Post-track action callback +template <typename Q, typename T> void callAtEnd(Q* p, void (T::*f)(const G4Track*)); +\end{unnumberedcode} + + +\item The \bold{SteppingAction} attached to the \tts{G4UserSteppingAction}, implemented + by the \tts{Geant4-} \tts{SteppingActionSequence} class and is called for each + step when tracking a particle. + Members of the \tts{Geant4SteppingActionSequence} are of type + \tts{Geant4SteppingAction} and receive the callbacks by overloading the member function: +\begin{unnumberedcode} +/// User stepping callback +virtual void operator()(const G4Step* step, G4SteppingManager* mgr); +\end{unnumberedcode} + or register a callback with the signature {\tts{void (T::*)(const G4Step*, G4SteppingManager*)}} + to receive calls using the method: +\begin{unnumberedcode} +/// Register stepping action callback. +template <typename Q, typename T> void call(Q* p, void (T::*f)(const G4Step*, + G4SteppingManager*)); +\end{unnumberedcode} + + +\item The \bold{StackingAction} attached to the + {\tts{G4UserStackingAction}}, implemented by the \tts{Geant4-}\\ + \tts{StackingActionSequence} class. + Members of the \tts{Geant4StackingActionSequence} are of type\\ + \detdesc{html/class_d_d4hep_1_1_simulation_1_1_geant4_stacking_action.html} + {\tts{Geant4StackingAction}} and receive the callbacks by overloading the member functions: +\begin{unnumberedcode} +/// New-stage callback +virtual void newStage(); +/// Preparation callback +virtual void prepare(); +\end{unnumberedcode} + or register a callback with the signature {\tts{void (T::*)()}} + to receive calls using the method: +\begin{unnumberedcode} +/// Register begin-of-event callback. Types Q and T must be polymorph! +template <typename T> void callAtNewStage(T* p, void (T::*f)()); +/// Register end-of-event callback. Types Q and T must be polymorph! +template <typename T> void callAtPrepare(T* p, void (T::*f)()); +\end{unnumberedcode} +\end{itemize} + +\noindent +All sequence types support the method \tts{void adopt(T* member\_reference)} +to add the members. Once adopted, the sequence takes ownership and manages +the member. The design of the sequences is very similar. +Figure~\ref{fig:ddg4-implementation-tracking-action} show as an example +the design of the \tts{Geant4TrackingAction}. + +\begin{figure}[h] + \begin{center} + \includegraphics[height=110mm] {DDG4-Sensitive-detector.png} + \caption{The sensitive detector design. The actual energy deposits are + collected in user defined subclasses of the \tts{Geant4Sensitive}. + Here, as an example possible actions called \tts{TrackerHitCollector}, + \tts{TrackerDetailedHitCollector} and \tts{TrackerHitMonitor} are shown.} + \label{fig:ddg4-implementation-sensitive-detector} + \end{center} +\end{figure} + +%============================================================================= +\subsection{Sensitive Detectors} +\label{sec:ddg4-user-manual-geant4sensitivedetectors} +%============================================================================= + +\noindent +Sensitive detectors are associated by the detector designers to all active +materials, which would produce a signal which can be read out. In Geant4 this concept +is realized by using a base class \tts{G4VSensitiveDetector}, which receives +a callback at the begin and the end of the event processing and at each step +inside the active material whenever an energy deposition occurred. + +\noindent +The sensitive actions do not necessarily deal only the collection of energy +deposits, but could also be used to simply monitor the performance of the +active element e.g. by producing histograms of the absolute value or the +spacial distribution of the depositions. + +\noindent +Within \DDG the concept of sensitive detectors is implemented as a +configurable action sequence of type +\detdesc{html/class_d_d4hep_1_1_simulation_1_1_geant4_sens_det_action_sequence.html} +{\tts{Geant4SensDetActionSequence}} +calling members of the type +\detdesc{html/struct_d_d4hep_1_1_simulation_1_1_geant4_sensitive.html} +{\tts{Geant4Sensitive}} as shown in +Figure~\ref{fig:ddg4-implementation-sensitive-detector}. The actual processing +part of such a sensitive action is only called if the and of a set of +required filters of type \tts{Geant4Filter} is positive (see also +section~\ref{sec:ddg4-implementation-sensitive-detector-filters}). No filter +is also positive. Possible filters are e.g. particle filters, which ignore the +sensitive detector action if the particle is a \tts{geantino} or if the +energy deposit is below a given threshold. + +\noindent +Objects of type \tts{Geant4Sensitive} receive the callbacks by overloading the +member function: +\begin{unnumberedcode} + /// Method invoked at the begining of each event. + virtual void begin(G4HCofThisEvent* hce); + /// Method invoked at the end of each event. + virtual void end(G4HCofThisEvent* hce); + /// Method for generating hit(s) using the information of G4Step object. + virtual bool process(G4Step* step, G4TouchableHistory* history); + /// Method invoked if the event was aborted. + virtual void clear(G4HCofThisEvent* hce); +\end{unnumberedcode} +or register a callback with the signature {\tts{void (T::*)(G4HCofThisEvent*)}} +respectively {\tts{void (T::*)(G4Step*, G4TouchableHistory*)}} +to receive callbacks using the methods: +\begin{unnumberedcode} + /// Register begin-of-event callback + template <typename T> void callAtBegin(T* p, void (T::*f)(G4HCofThisEvent*)); + /// Register end-of-event callback + template <typename T> void callAtEnd(T* p, void (T::*f)(G4HCofThisEvent*)); + /// Register process-hit callback + template <typename T> void callAtProcess(T* p, void (T::*f)(G4Step*, G4TouchableHistory*)); + /// Register clear callback + template <typename T> void callAtClear(T* p, void (T::*f)(G4HCofThisEvent*)); +\end{unnumberedcode} + +%============================================================================= +\subsubsection{Sensitive Detector Filters} +\label{sec:ddg4-implementation-sensitive-detector-filters} +%============================================================================= + +\noindent +Filters are called by Geant4 before the +hit processing in the sensitive detectors start. The global filters +may be shared between many sensitive detectors. Alternatively filters +may be directly attached to the sensitive detector in question. +Attributes are directly passed as properties to the filter action. + +\newpage +%============================================================================= +\subsection{The Geant4 Physics List} +\label{sec:ddg4-implementation-physics-list} +%============================================================================= +\noindent +Geant4 provides the base class \tts{G4VUserPhysicsList}. Any user defined +physics list must provide this interface. DDG4 provides such an interface +through the ROOT plugin mechanism using the class \tts{G4VModularPhysicsList}. +The flexibility of \DDG allows for several possibilities to setup the Geant4 +physics list. +\begin{itemize} +\item The \bold{physics list} may be configured as a sequence of type + \detdesc{html/class_d_d4hep_1_1_simulation_1_1_geant4_physics_list_action_sequence.html} + {\tts{Geant4PhysicsListActionSequence}}. + Members of the \detdesc{html/class_d_d4hep_1_1_simulation_1_1_geant4_physics_list_action_sequence.html} + {\tts{Geant4PhysicsListActionSequence}} are of type + \detdesc{html/class_d_d4hep_1_1_simulation_1_1_geant4_physics_list.html} + {\tts{Geant4PhysicsList}} and receive the callbacks by overloading + the member functions: +\begin{unnumberedcode} + /// Callback to construct the physics constructors + virtual void constructProcess(Geant4UserPhysics* interface); + /// constructParticle callback + virtual void constructParticles(Geant4UserPhysics* particle); + /// constructPhysics callback + virtual void constructPhysics(Geant4UserPhysics* physics); +\end{unnumberedcode} + or register a callback with the signature {\tts{void (T::*)(Geant4UserPhysics*)}} + to receive calls using the method: +\begin{unnumberedcode} + /// Register process construction callback t + template <typename Q, typename T> void constructProcess(Q* p, void (T::*f)(Geant4UserPhysics*)); + /// Register particle construction callback + template <typename Q, typename T> void constructParticle(Q* p, void (T::*f)(Geant4UserPhysics*)); +\end{unnumberedcode} + The argument of type \detdesc{html/class_d_d4hep_1_1_simulation_1_1_geant4_user_physics.html} + {\tts{Geant4UserPhysics}} provides a basic interface to the original + \tts{G4VModular}- \tts{PhysicsList}, which allows to register physics constructors etc. + +\item In most of the cases the above approach is an overkill and often even too flexible. + Hence, alternatively, the physics list may consist of a single entry of type + \detdesc{html/class_d_d4hep_1_1_simulation_1_1_geant4_physics_list.html} + {\tts{Geant4PhysicsList}}. +\end{itemize} + +\noindent +The basic implementation of the \tts{Geant4PhysicsList} supports the usage of various +\begin{itemize}\itemcompact +\item \detdesc{}{particle constructors}, such as single particle constructors like + \tts{G4Gamma} or \tts{G4Proton}, or whole particle groups like + \tts{G4BosonConstructor} or \tts{G4IonConstrutor}, +\item \detdesc{}{physics process constructors}, such as e.g. \tts{G4GammaConversion}, + \tts{G4PhotoElectricEffect} or\\ \tts{G4ComptonScattering}, +\item \detdesc{}{physics constructors} combining particles and the corresponding + interactions, such as\\ e.g. \tts{G4OpticalPhysics}, + \tts{HadronPhysicsLHEP} or \tts{G4HadronElasticPhysics} and +\item \detdesc{}{predefined Geant4 physics lists}, such as \tts{FTFP\_BERT}, + \tts{CHIPS} or \tts{QGSP\_INCLXX}. This option is triggered by the + content of the string property "extends" of the \tts{Geant4Kernel::physicsList()} action. +\end{itemize} +These constructors are internally connected to the above callbacks to register themselves. +The constructors are instantiated using the ROOT plugin mechanism. + +\noindent +The description of the above interface is only for completeness. The basic idea is, +that the physics list with its particle and physics constructors is configured +entirely data driven using the setup mechanism described in the following +chapter. However, DDG4 is not limited to the data driven approach. Specialized +physics lists may be supplied, but there should be no need. +New physics lists could always be composed by actually providing new physics +constructors and actually publishing these using the factory methods: +\begin{code} +// Framework include files +#include "DDG4/Factories.h" + +#include "My_Very_Own_Physics_Constructor.h" +DECLARE_GEANT4_PHYSICS(My_Very_Own_Physics_Constructor) +\end{code} +where \tts{My\_Very\_Own\_Physics\_Constructor} represents a sub-class of +\tts{G4VPhysicsConstructor}. + +\newpage +%============================================================================= +\subsection{The Support of the Geant4 UI: \tw{Geant4UIMessenger}} +\label{sec:ddg4-user-manual-geant4action-base} +%============================================================================= + +\noindent +The support of interactive in Geant4 is absolutely mandatory to debug detector +setups in small steps. The Geant4 toolkit did provide for this reason +a machinery of UI commands. +\begin{figure}[h] + \begin{center} + \includegraphics[height=70mm] {DDG4-UIMessenger.png} + \caption{The design of the \tts{Geant4UIMessenger} class responsible for + the interaction between the user and the components of \DDG and Geant4.} + \label{fig:ddg4-tracking-action} + \end{center} +\end{figure} + +\noindent +The UI control is enabled, as soon as the property "Control" (boolean) is set to true. +Be default all properties of the action are exported. +Similar to the callback mechanism described above it is also feasible to +register any object callback invoking a method of a \tts{Geant4Action}-subclass. + +\noindent +The following (shortened) screen dump illustrates the usage of the +generic interface any Geant4Action offers: +\begin{unnumberedcode} +Idle> ls +Command directory path : / + Sub-directories : + /control/ UI control commands. + /units/ Available units. + /process/ Process Table control commands. + /ddg4/ Control for all named Geant4 actions + ... +Idle> cd /ddg4 +Idle> ls +... +Control for all named Geant4 actions + + Sub-directories : + /ddg4/EventAction/ Control hierarchy for Geant4 action:EventAction + /ddg4/RunAction/ Control hierarchy for Geant4 action:RunAction + /ddg4/Gun/ Control hierarchy for Geant4 action:Gun + /ddg4/GeneratorAction/ Control hierarchy for Geant4 action:GeneratorAction + /ddg4/PhysicsList/ Control hierarchy for Geant4 action:PhysicsList +Idle> ls Gun +... +Control hierarchy for Geant4 action:Gun + + Sub-directories : + Commands : + show * Show all properties of Geant4 component:Gun +... + particle * Property item of type std::string + pos_x * Property item of type double + pos_y * Property item of type double + pos_z * Property item of type double +Idle> Gun/show +... +PropertyManager: Property multiplicity = 1 +PropertyManager: Property name = 'Gun' +PropertyManager: Property particle = 'e-' +PropertyManager: Property pos_x = 0 +PropertyManager: Property pos_y = 0 +PropertyManager: Property pos_z = 0 + +Idle> Gun/pos_z 1.0 +Geant4UIMessenger: +++ Gun> Setting new property value pos_z = 1.0. +Idle> Gun/pos_y 1.0 +Geant4UIMessenger: +++ Gun> Setting new property value pos_y = 1.0. +Idle> Gun/pos_x 1.0 +Geant4UIMessenger: +++ Gun> Setting new property value pos_x = 1.0. +Idle> Gun/show +... +PropertyManager: Property pos_x = 1 +PropertyManager: Property pos_y = 1 +PropertyManager: Property pos_z = 1 + +\end{unnumberedcode} + + +\newpage +%============================================================================= +\section{Setting up DDG4} +\label{sec:ddg4-implementation-setup} +%============================================================================= + +\noindent +\DDG offers several possibilities to configure a simulation application +using +\begin{itemize}\itemcompact +\item XML files, +\item by coding a setup script loaded from the \tts{ROOT} interpreter + with the AClick mechanism. +\item by creating a setup script using \tts{python} and + \tts{ROOT}'s reflection mechanism exposed by \tts{PyROOT}. +\end{itemize} +The follwing subsection describe these different mechanism. + + +%============================================================================= +\subsection{Setting up DDG4 using XML} +\label{sec:ddg4-implementation-setup-xml} +%============================================================================= + +\noindent +A special plugin was developed to enable the configuration of \DDG using +XML structures. These files are parsed identically to the geometry setup +in \DDhep the only difference is the name of the root-element, which for +\DDG is \tts{<geant4\_setup>}. +The following code snippet shows the basic structure of a \DDG setup file: +\begin{unnumberedcode} +<geant4_setup> + <physicslist> ,,, </physicslist> <!-- Defintiion of the physics list --> + <actions> ... </actions> <!-- The list of global actions --> + <phases> ... </phases> <!-- The definition of the various phases --> + <filters> ... </filters> <!-- The list of global filter actions --> + <sequences> ... </sequences> <!-- The list of defined sequences --> + <sensitive_detectors> ... </sensitive_detectors> <!-- The list of sensitive detectors --> + <properties> ... </properties> <!-- Free format option sequences --> +</geant4_setup> +\end{unnumberedcode} +To setup a \DDG4 application any number of xml setup files may be interpreted +iteratively. In the following subsections the content of these first level sub-trees will +be discussed. + +%============================================================================= +\subsubsection{Setup of the Physics List} +\label{sec:ddg4-setup-xml-physicslist} +%============================================================================= + +\noindent +The main tag to setup a physics list is \tts{<physicslist>} with the +\tts{name} attribute defining the instance of the \tts{Geant4PhysicsList} object. +An example code snippet is shown below in Figure~\ref{fig:ddg4-setup-xml-physicslist}. + +\begin{code} +<geant4_setup> + <physicslist name="Geant4PhysicsList/MyPhysics.0"> + + <extends name="QGSP_BERT"/> <!-- Geant4 basic Physics list --> + + <particles> <!-- Particle constructors --> + <construct name="G4Geantino"/> + <construct name="G4ChargedGeantino"/> + <construct name="G4Electron"/> + <construct name="G4Gamma"/> + <construct name="G4BosonConstructor"/> + <construct name="G4LeptonConstructor"/> + <construct name="G4MesonConstructor"/> + <construct name="G4BaryonConstructor"/> + ... + </particles> + + <processes> <!-- Process constructors --> + <particle name="e[+-]" cut="1*mm"> + <process name="G4eMultipleScattering" ordAtRestDoIt="-1" ordAlongSteptDoIt="1" + ordPostStepDoIt="1"/> + <process name="G4eIonisation" ordAtRestDoIt="-1" ordAlongSteptDoIt="2" + ordPostStepDoIt="2"/> + </particle> + <particle name="mu[+-]"> + <process name="G4MuMultipleScattering" ordAtRestDoIt="-1" ordAlongSteptDoIt="1" + ordPostStepDoIt="1"/> + <process name="G4MuIonisation" ordAtRestDoIt="-1" ordAlongSteptDoIt="2" + ordPostStepDoIt="2"/> + </particle> + ... + </processes> + + <physics> <!-- Physics constructors --> + <construct name="G4EmStandardPhysics"/> + <construct name="HadronPhysicsQGSP"/> + ... + </physics> + + </physicslist> +</geant4_setup> +\end{code} +\begin{figure}[h] +\caption{XML snippet showing the configuration of a physics list.} +\label{fig:ddg4-setup-xml-physicslist} +\end{figure} + + +To trigger a call to a +\begin{itemize}\itemcompact +\item \bold{particle constructors} (line 7-14), use the \tts{<particles>} section + and define the Geant4 particle constructor to be called by name. To trigger a call to +\item \bold{physics process constructors}, as shown in line 19-30, + Define for each particle matching the name pattern (regular expression!) and the + default cut value for the corresponding processes. The attributes ordXXXX correspond + to the arguments of the Geant4 call \\ + \tts{G4ProcessManager::AddProcess(process,ordAtRestDoIt, ordAlongSteptDoIt,ordPostStepDoIt);} + The processes themself are created using the ROOT plugin mechanism. + To trigger a call to +\item \bold{physics constructors}, as shown in line 34-35, use the \tts{<physics>} section + and +\item to base all these constructs on an already existing predefined Geant4 physics list + use the \tts{<extends>} tag with the attribute containing the name of the physics list + as shown in line 4. +\end{itemize} +If only a predefined physics list is used, which probably already satisfies very many use cases, +all these section collapse to: +\begin{code} +<geant4_setup> + <physicslist name="Geant4PhysicsList/MyPhysics.0"> + <extends name="QGSP_BERT"/> <!-- Geant4 basic Physics list --> + </physicslist> +</geant4_setup> +\end{code} + +%============================================================================= +\subsubsection{Setup of Global Geant4 Actions} +\label{sec:ddg4-setup-xml-geant4-actions} +%============================================================================= + +\noindent +Global actions must be defined in the \tts{<actions>} section as shown in the following snippet: +\begin{code} +<geant4_setup> + <actions> + <action name="Geant4TestRunAction/RunInit"> + <properties Property_int="12345" + Property_double="-5e15" + Property_string="Startrun: Hello_2"/> + </action> + <action name="Geant4TestEventAction/UserEvent_2" + Property_int="1234" + Property_double="5e15" + Property_string="Hello_2" /> + </actions> +</geant4_setup> +\end{code} +The default properties of \bold{every} \tts{Geant4Action} object are: +\begin{unnumberedcode} +Name [string] Action name +OutputLevel [int] Flag to customize the level of printout +Control [boolean] Flag if the UI messenger should be installed. +\end{unnumberedcode} +The \tts{name} attribute of an action child is a qualified name: The first part +denotes the type of the plugin (i.e. its class), the second part the name of the instance. +Within one collection the instance \tts{name} must be unique. +Properties of Geant4Actions are set by placing them as attributes into the +\tts{<properties>} section. + +%============================================================================= +\subsubsection{Setup of Geant4 Filters} +\label{sec:ddg4-setup-xml-geant4-filters} +%============================================================================= +\noindent +Filters are special actions called by \tts{Geant4Sensitive}s. +Filters may be global or anonymous i.e. reusable by several sensitive detector +sequences as illustrated in Section~\ref{sec:ddg4-setup-xml-geant4-sequences}. +The setup is analogous to the setup of global actions: +\begin{code} + <filters> + <filter name="GeantinoRejectFilter/GeantinoRejector"/> + <filter name="ParticleRejectFilter/OpticalPhotonRejector"> + <properties particle="opticalphoton"/> + </filter> + <filter name="ParticleSelectFilter/OpticalPhotonSelector"> + <properties particle="opticalphoton"/> + </filter> + <filter name="EnergyDepositMinimumCut"> + <properties Cut="10*MeV"/> + </filter> + <!-- ... next global filter ... --> + </filters> +\end{code} +Global filters are accessible from the \tts{Geant4Kernel} object. + +%============================================================================= +\subsubsection{Geant4 Action Sequences} +\label{sec:ddg4-setup-xml-geant4-sequences} +%============================================================================= + +\noindent +\tts{Geant4 Action Sequences} by definition are \tts{Geant4Action} objects. +Hence, they share the setup mechanism with properties etc. For the setup +mechanism two different types of sequences are known to \DDG: +{\it{Action sequences}} and {\it{Sensitive detector sequences}}. Bot are declared in +the \tts{sequences} section: +\begin{code} +<geant4_setup> + <sequences> + <sequence name="Geant4EventActionSequence/EventAction"> <!-- Sequence "EventAction" of type + "Geant4EventActionSequence" --> + <action name="Geant4TestEventAction/UserEvent_1"> <!-- Anonymouns action --> + <properties Property_int="01234" <!-- Properties go inline --> + Property_double="1e11" + Property_string="'Hello_1'"/> + </action> + <action name="UserEvent_2"/> <!-- Global action defined in "actions" --> + <!-- Only the name is referenced here --> + <action name="Geant4Output2ROOT/RootOutput"> <!-- ROOT I/O action --> + <properties Output="simple.root"/> <!-- Output file property --> + </action> + <action name="Geant4Output2LCIO/LCIOOutput"> <!-- LCIO output action --> + <properties Output="simple_lcio"/> <!-- Output file property --> + </action> + </sequence> + + + <sequence sd="SiTrackerBarrel" type="Geant4SensDetActionSequence"> + <filter name="GeantinoRejector"/> + <filter name="EnergyDepositMinimumCut"/> + <action name="Geant4SimpleTrackerAction/SiTrackerBarrelHandler"/> + </sequence> + <sequence sd="SiTrackerEndcap" type="Geant4SensDetActionSequence"> + <filter name="GeantinoRejector"/> + <filter name="EnergyDepositMinimumCut"/> + <action name="Geant4SimpleTrackerAction/SiTrackerEndcapHandler"/> + </sequence> + <!-- ... next sequence ... --> + </sequences> +</geant4_setup> +\end{code} +Here firstly the \bold{EventAction} sequence is defined with its members. +Secondly a sensitve detector sequence is defined for the subdetector +\tts{SiTrackerBarrel} of type \tts{Geant4SensDetActionSequence}. +The sequence uses two filters: \tts{GeantinoRejector} to not generate hits +from geantinos and \tts{EnergyDepositMinimumCut} to enforce a minimal energy deposit. +These filters are global i.e. they may be applied by many subdetectors. +The setup of global filters is described in +Section~\ref{sec:ddg4-setup-xml-geant4-filters}. +Finally the action \tts{SiTrackerEndcapHandler} of type \tts{Geant4SimpleTrackerAction} +is chained, which collects the deposited energy and +creates a collection of hits. The \tts{Geant4SimpleTrackerAction} is a template +callback to illustrate the usage of sensitive elements in \DDG. +The resulting hit collection of these handlers by default have the same name as the +object instance name. +Analogous below the sensitive detector sequence for the subdetector +\tts{SiTrackerEndcap} is shown, which reuses the same filter actions, but will build its own +hit collection. + +\noindent +\bold{Plase note:} +\begin{itemize}\itemcompact +\item \bold{It was already mentioned, but once again}: Event-, run-, generator-, tracking-, + stepping- and stacking actions sequences have predefined names! + These names are fixed and part of the \bold{common knowledge}, they cannot be altered. + Please refer to + Section~\ref{sec:ddg4-user-manual-implementation-geant4action-sequences} + for the names of the global action sequences. +\item the sensitive detector sequences are matched by the attribute \tts{sd} to the + subdetectors created with the \DDhep detector description package. Values must match! +\item In the event that several xml files are parsed it is absolutely vital that + the \tts{<actions>} section is interpreted \bold{before} the \tts{sequences}. +\item For each XML file several \tts{<sequences>} are allowed. +\noindent +\end{itemize} + +%============================================================================= +\subsubsection{Setup of Geant4 Sensitive Detectors} +\label{sec:ddg4-setup-xml-geant4-sensitive detectors} +%============================================================================= +\begin{code} + <geant4_setup> + <sensitive_detectors> + <sd name="SiTrackerBarrel" + type="Geant4SensDet" + ecut="10.0*MeV" + verbose="true" + hit_aggregation="position"> + </sd> + <!-- ... next sensitive detector ... --> + </sensitive_detectors> + </geant4_setup> +\end{code} + + + +%============================================================================= +\subsubsection{Miscellaneous Setup of Geant4 Objects} +\label{sec:ddg4-setup-xml-geant4-objects} +%============================================================================= + +\noindent +This section is used for the flexible setup of auxiliary objects such as the +electromagnetic fields used in Geant4: +\begin{code} + <geant4_setup> + <properties> + <attributes name="geant4_field" + id="0" + type="Geant4FieldSetup" + object="GlobalSolenoid" + global="true" + min_chord_step="0.01*mm" + delta_chord="0.25*mm" + delta_intersection="1e-05*mm" + delta_one_step="0.001*mm" + eps_min="5e-05*mm" + eps_max="0.001*mm" + stepper="HelixSimpleRunge" + equation="Mag_UsualEqRhs"> + </attributes> + ... + </properties> + </geant4_setup> +\end{code} +Important are the tags \tts{type} and \tts{object}, which are used to firstly +define the plugin to be called and secondly define the object from the \DDhep +description to be configured for the use within Geant4. + +%============================================================================= +\subsubsection{Setup of Geant4 Phases} +\label{sec:ddg4-setup-xml-geant4-phases} +%============================================================================= + +\noindent +Phases are configured as shown below. +However, the use is \bold{discouraged}, +since it is not yet clear if there are appropriate use cases! +\begin{code} + <phases> + <phase type="RunAction/begin"> + <action name="RunInit"/> + <action name="Geant4TestRunAction/UserRunInit"> + <properties Property_int="1234" + Property_double="5e15" + Property_string="'Hello_2'"/> + </action> + </phase> + <phase type="EventAction/begin"> + <action name="UserEvent_2"/> + </phase> + <phase type="EventAction/end"> + <action name="UserEvent_2"/> + </phase> + ... + </phases> +\end{code} + +\newpage +%============================================================================= +\subsection{Setting up DDG4 using ROOT-CINT} +\label{sec:ddg4-implementation-setup-root-cint} +%============================================================================= + +\noindent +The setup of \DDG directly from the the ROOT interpreter using the AClick +mechanism is very simple, but mainly meant for purists (like me ;-)), +since it is nearly equivalent to the explicit setup within a \tts{C++} +main program. +The following code section shows how to do it. For explanation the code +secment is discussed below line by line. +\begin{code} +#include "DDG4/Geant4Config.h" +#include "DDG4/Geant4TestActions.h" +#include "DDG4/Geant4TrackHandler.h" +#include <iostream> + +using namespace std; +using namespace DD4hep; +using namespace DD4hep::Simulation; +using namespace DD4hep::Simulation::Test; +using namespace DD4hep::Simulation::Setup; + +#if defined(__MAKECINT__) +#pragma link C++ class Geant4RunActionSequence; +#pragma link C++ class Geant4EventActionSequence; +#pragma link C++ class Geant4SteppingActionSequence; +#pragma link C++ class Geant4StackingActionSequence; +#pragma link C++ class Geant4GeneratorActionSequence; +#pragma link C++ class Geant4Action; +#pragma link C++ class Geant4Kernel; +#endif + +SensitiveSeq::handled_type* setupDetector(Kernel& kernel, const std::string& name) { + SensitiveSeq sd = SensitiveSeq(kernel,name); + Sensitive sens = Sensitive(kernel,"Geant4TestSensitive/"+name+"Handler",name); + sd->adopt(sens); + sens = Sensitive(kernel,"Geant4TestSensitive/"+name+"Monitor",name); + sd->adopt(sens); + return sd; +} + +void exampleAClick() { + Geant4Kernel& kernel = Geant4Kernel::instance(LCDD::getInstance()); + kernel.loadGeometry("file:../DD4hep.trunk/DDExamples/CLICSiD/compact/compact.xml"); + kernel.loadXML("DDG4_field.xml"); + + GenAction gun(kernel,"Geant4ParticleGun/Gun"); + gun["energy"] = 0.5*GeV; // Set properties + gun["particle"] = "e-"; + gun["multiplicity"] = 1; + kernel.generatorAction().adopt(gun); + + Action run_init(kernel,"Geant4TestRunAction/RunInit"); + run_init["Property_int"] = 12345; + kernel.runAction().callAtBegin (run_init.get(),&Geant4TestRunAction::begin); + kernel.eventAction().callAtBegin(run_init.get(),&Geant4TestRunAction::beginEvent); + kernel.eventAction().callAtEnd (run_init.get(),&Geant4TestRunAction::endEvent); + + Action evt_1(kernel,"Geant4TestEventAction/UserEvent_1"); + evt_1["Property_int"] = 12345; // Set properties + evt_1["Property_string"] = "Events"; + kernel.eventAction().adopt(evt_1); + + EventAction evt_2(kernel,"Geant4TestEventAction/UserEvent_2"); + kernel.eventAction().adopt(evt_2); + + kernel.runAction().callAtBegin(evt_2.get(),&Geant4TestEventAction::begin); + kernel.runAction().callAtEnd (evt_2.get(),&Geant4TestEventAction::end); + + setupDetector(kernel,"SiVertexBarrel"); + setupDetector(kernel,"SiVertexEndcap"); + // .... more subdetectors here ..... + setupDetector(kernel,"LumiCal"); + setupDetector(kernel,"BeamCal"); + + kernel.configure(); + kernel.initialize(); + kernel.run(); + std::cout << "Successfully executed application .... " << std::endl; + kernel.terminate(); +} +\end{code} + +\noindent +\begin{tabular} {l||p{0cm}} +\docline{Line}{} +\docline{1}{The header file \tts{Geant4Config.h} contains a set of wrapper + classes to easy the creation of objects using the plugin mechanism and setting + properties to \tts{Geant4Action} objects. These helpers and the corresponding + functionality are not included in the wrapped classes themselves to not + clutter the code with stuff only used for the setup. + All contained objects are in the namespace \tts{DD4hep::Simulation::Setup}}. +\docline{6-10}{Save yourself specifying all the namespaces objects are in....} +\docline{13-19}{CINT processing pragmas. + Classes defined here will be available at the ROOT prompt + after this AClick is loaded.} +\docline{22-29}{Sampler to fill the sensitive detector sequences for each + subdetector with two entries: a handler and a monitor action. + Please note, that this here is example code and in real life specialized actions + will have to be provided for each subdetector.} +\docline{31}{Let's go for it. here the entry point starts....} +\docline{32}{Create the \tts{Geant4Kernel} object.} +\docline{33}{Load the geometry into \DDhep.} +\docline{34}{Redefine the setup of the sensitive detectors.} +\docline{36-40}{Create the generator action of type \tts{Geant4ParticleGun} with name + \tts{Gun}, set non-default properties and activate the configured object + by attaching it to the \tts{Geant4Kernel}.} +\docline{42-46}{Create a user defined begin-of-run action callback, set the properties + and attach it to the begin of run calls. To collect statistics extra member functions + are registered to be called at the beginning and the end of each event.} +\docline{48-51}{Create a user defined event action routine, set its properties + and attach it to the event action sequence.} +\docline{53-54}{Create a second event action and register it to the event action sequence. + This action will be called after the previously created action.} +\docline{56-57}{For this event action we want to receive callbacks at start- + and end-of-run to produce additional summary output.} +\docline{59-63}{Call the sampler routine to attach test actions to the subdetectors defined.} +\docline{65-66}{Configure, initialize and run the Geant4 application. + Most of the Geant4 actions will only be created here and the action sequences + created before will be attached now.} +\docline{69}{Terminate the Geant4 application and exit.} +\end{tabular} + +\newpage +\noindent +CINT currently cannot handle pointers to member functions~\footnote{This may change +in the future once ROOT uses \tts{clang} and \tts{cling} as the interpreting engine.}. +Hence the above AClick only works in compiled mode. To invoke the compilation the following +action is necessary from the ROOT prompt: + + +\begin{code} +$> root.exe + ******************************************* + * * + * W E L C O M E to R O O T * + * * + * Version 5.34/10 29 August 2013 * + * * + * You are welcome to visit our Web site * + * http://root.cern.ch * + * * + ******************************************* + +ROOT 5.34/10 (heads/v5-34-00-patches@v5-34-10-5-g0e8bac8, Sep 04 2013, 11:52:19 on linux) + +CINT/ROOT C/C++ Interpreter version 5.18.00, July 2, 2010 +Type ? for help. Commands must be C++ statements. +Enclose multiple statements between { }. +root [0] .X initAClick.C +.... Setting up the CINT include pathes and the link statements. + +root [1] .L ../DD4hep.trunk/DDG4/examples/exampleAClick.C+ +Info in <TUnixSystem::ACLiC>: creating shared library ....exampleAClick_C.so +.... some Cint warnings concerning member function pointers ..... + +root [2] exampleAClick() +.... and it starts ... +\end{code} + +\noindent +The above scripts are present in the DDG4/example directory located in svn. +The intialization script \tts{initAClick.C} may require customization +to cope with the installation pathes. + +%============================================================================= +\subsection{Setting up DDG4 using Python} +\label{sec:ddg4-implementation-setup-python} +%============================================================================= + +\noindent +Given the reflection interface of ROOT, the setup of the simulation interface +using DD4hep is of course also possible using the python interpreted language. +In the following code example the setup of Geant4 using the \tw{ClicSid} +example is shown using python~\footnote{For comparison, the same example was +used to illustrate the setup using XML files.}. + +\begin{code} +import DDG4 +from SystemOfUnits import * + +""" + + DD4hep example setup using the python configuration + + @author M.Frank + @version 1.0 + +""" +def run(): + kernel = DDG4.Kernel() + kernel.loadGeometry("file:../DD4hep.trunk/DDExamples/CLICSiD/compact/compact.xml") + kernel.loadXML("DDG4_field.xml") + + lcdd = kernel.lcdd() + print '+++ List of sensitive detectors:' + for i in lcdd.detectors(): + o = DDG4.DetElement(i.second) + sd = lcdd.sensitiveDetector(o.name()) + if sd.isValid(): + print '+++ %-32s type:%s'%(o.name(), sd.type(), ) + + # Configure Run actions + run1 = DDG4.RunAction(kernel,'Geant4TestRunAction/RunInit') + run1.Property_int = 12345 + run1.Property_double = -5e15*keV + run1.Property_string = 'Startrun: Hello_2' + print run1.Property_string, run1.Property_double, run1.Property_int + run1.enableUI() + kernel.registerGlobalAction(run1) + kernel.runAction().add(run1) + + # Configure Event actions + evt2 = DDG4.EventAction(kernel,'Geant4TestEventAction/UserEvent_2') + evt2.Property_int = 123454321 + evt2.Property_double = 5e15*GeV + evt2.Property_string = 'Hello_2 from the python setup' + evt2.enableUI() + kernel.registerGlobalAction(evt2) + + evt1 = DDG4.EventAction(kernel,'Geant4TestEventAction/UserEvent_1') + evt1.Property_int=01234 + evt1.Property_double=1e11 + evt1.Property_string='Hello_1' + evt1.enableUI() + + kernel.eventAction().add(evt1) + kernel.eventAction().add(evt2) + + # Configure I/O + evt_root = DDG4.EventAction(kernel,'Geant4Output2ROOT/RootOutput') + evt_root.Control = True + evt_root.Output = "simple.root" + evt_root.enableUI() + + evt_lcio = DDG4.EventAction(kernel,'Geant4Output2LCIO/LcioOutput') + evt_lcio.Output = "simple_lcio" + evt_lcio.enableUI() + + kernel.eventAction().add(evt_root) + kernel.eventAction().add(evt_lcio) + + # Setup particle gun + gun = DDG4.GeneratorAction(kernel,"Geant4ParticleGun/Gun") + gun.energy = 0.5*GeV + gun.particle = 'e-' + gun.multiplicity = 1 + gun.enableUI() + kernel.generatorAction().add(gun) + + # Setup global filters fur use in sensntive detectors + f1 = DDG4.Filter(kernel,'GeantinoRejectFilter/GeantinoRejector') + f2 = DDG4.Filter(kernel,'ParticleRejectFilter/OpticalPhotonRejector') + f2.particle = 'opticalphoton' + f3 = DDG4.Filter(kernel,'ParticleSelectFilter/OpticalPhotonSelector') + f3.particle = 'opticalphoton' + f4 = DDG4.Filter(kernel,'EnergyDepositMinimumCut') + f4.Cut = 10*MeV + f4.enableUI() + kernel.registerGlobalFilter(f1) + kernel.registerGlobalFilter(f2) + kernel.registerGlobalFilter(f3) + kernel.registerGlobalFilter(f4) + + # First the tracking detectors + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/SiVertexBarrel') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleTrackerAction/SiVertexBarrelHandler','SiVertexBarrel') + seq.add(act) + seq.add(f1) + seq.add(f4) + act.add(f1) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/SiVertexEndcap') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleTrackerAction/SiVertexEndcapHandler','SiVertexEndcap') + seq.add(act) + seq.add(f1) + seq.add(f4) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/SiTrackerBarrel') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleTrackerAction/SiTrackerBarrelHandler','SiTrackerBarrel') + seq.add(act) + seq.add(f1) + seq.add(f4) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/SiTrackerEndcap') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleTrackerAction/SiTrackerEndcapHandler','SiTrackerEndcap') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/SiTrackerForward') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleTrackerAction/SiTrackerForwardHandler','SiTrackerForward') + seq.add(act) + + # Now the calorimeters + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/EcalBarrel') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/EcalBarrelHandler','EcalBarrel') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/EcalEndcap') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/EcalEndCapHandler','EcalEndcap') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/HcalBarrel') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/HcalBarrelHandler','HcalBarrel') + act.adoptFilter(kernel.globalFilter('OpticalPhotonRejector')) + seq.add(act) + + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/HcalOpticalBarrelHandler','HcalBarrel') + act.adoptFilter(kernel.globalFilter('OpticalPhotonSelector')) + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/HcalEndcap') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/HcalEndcapHandler','HcalEndcap') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/HcalPlug') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/HcalPlugHandler','HcalPlug') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/MuonBarrel') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/MuonBarrelHandler','MuonBarrel') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/MuonEndcap') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/MuonEndcapHandler','MuonEndcap') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/LumiCal') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/LumiCalHandler','LumiCal') + seq.add(act) + + seq = DDG4.SensitiveSequence(kernel,'Geant4SensDetActionSequence/BeamCal') + act = DDG4.SensitiveAction(kernel,'Geant4SimpleCalorimeterAction/BeamCalHandler','BeamCal') + seq.add(act) + + # Now build the physics list: + phys = kernel.physicsList() + phys.extends = 'FTFP_BERT' + #phys.transportation = True + phys.decays = True + phys.enableUI() + + ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics') + ph.addParticleConstructor('G4BosonConstructor') + ph.addParticleConstructor('G4LeptonConstructor') + ph.addParticleProcess('e[+-]','G4eMultipleScattering',-1,1,1) + ph.addPhysicsConstructor('G4OpticalPhysics') + ph.enableUI() + phys.add(ph) + + phys.dump() + + kernel.configure() + kernel.initialize() + kernel.run() + kernel.terminate() + +if __name__ == "__main__": + run() + +\end{code} + +\newpage +%============================================================================= +\section{Existing DDG4 components} +%============================================================================= +\noindent +In the introduction the longterm goal was expressed, that with DDG4 users +should be able to pick components from a growing palette and connect the +selected components using the setup mechanisms described in +Section~\ref{sec:ddg4-implementation-setup}. + +\noindent +Such a palette based approach obviously depends on the availibility of +documentation for exisisting components describing the properties +of each component and the interaction of each component within the \DDG +framework. + +\noindent +All components defer from the basic type \tts{Geant4Action}. This means +\bold{all} components have the \bold{default} properties described in the +table below: + +\vspace{0.5cm} +\begin{tabular}{ l l p{9cm} } +\hline +Component Properties: & & \tts{default} \\ +\hline +\bold{OuputLevel} & [int] & Output level of the component to customize printouts \\ +\bold{Name} & [string] & Component name [read-only] \\ +\bold{Control} & [boolean] & Steering of the Geant4 Messenger creation \\ +\hline +\end{tabular} + + +\vspace{5cm} + +\begin{center} +{\large{\bf{ +\begin{tabular} {| p{15cm} |} +\hline\space \\ + +\noindent +{\underline{Important notice for developers:}} \\ + +\noindent +Since the documentation of developed components is VERY important, +please never forget to supply the corresponding documentation.\\ +\\ +\noindent +At least supply the minimal documentation ash shown below +in the appended examples for the "Simple" detector response and I/O +components. +\\ \space\hline +\end{tabular} +}}} +\end{center} +\clearpage + + +%============================================================================= +\subsection{Physics Lists} +%============================================================================= +\noindent + + +%============================================================================= +\subsection{Sensitive Detectors} +%============================================================================= +\noindent + +%============================================================================= +\subsubsection{Geant4SimpleTracker} +%============================================================================= +\noindent +Simple sensitive detector for tracking detectors. These trackers create one +single hit collection. The created hits may be written out with the output +modules of type "Simple" described in +Section~\ref{sec:ddg4-components-IO-ROOT-simple} +and~\ref{sec:ddg4-components-IO-ROOT-simple}. Here the basic specifications: + +\vspace{0.5cm} +\begin{tabular}{ l p{10cm} } +\hline +Basics: & \\ +\hline +\bold{Class name} & \tts{Geant4SensitiveAction<SimpleTracker>} \\ +\bold{File name} & \tts{DDG4/plugins/Geant4SDActions.cpp} \\ +\bold{Hit collection} & \tts{<detector name>} \\ +\bold{Hit class} & \tts{SimpleTracker::Hit} \\ +\bold{File name} & \tts{DDG4/include/Geant4Data.h} \\ +\hline +Component Properties: & \tts{default} \\ +\hline +\end{tabular} + +%============================================================================= +\subsubsection{Geant4SimpleCalorimeter} +%============================================================================= +\noindent +Simple sensitive detector for calorimeters. The sensitive detector creates one +single hit collection. The created hits may be written out with the output +modules of type "Simple" described in +Section~\ref{sec:ddg4-components-IO-ROOT-simple} +and~\ref{sec:ddg4-components-IO-ROOT-simple}. Here the basic specifications: + +\vspace{0.5cm} +\begin{tabular}{ l p{10cm} } +\hline +Basics: & \\ +\hline +\bold{Class name} & \tts{Geant4SensitiveAction<SimpleCalorimeter>} \\ +\bold{File name} & \tts{DDG4/plugins/Geant4SDActions.cpp} \\ +\bold{Hit collection} & \tts{<detector name>} \\ +\bold{Hit class} & \tts{SimpleCalorimeter::Hit} \\ +\bold{File name} & \tts{DDG4/include/Geant4Data.h} \\ +\hline +Component Properties: & \tts{default} \\ +\hline +\end{tabular} + + +%============================================================================= +\subsubsection{Geant4SimpleOpticalCalorimeter} +%============================================================================= +\noindent + + +%============================================================================= +\subsection{I/O Components} +%============================================================================= +\noindent + +%============================================================================= +\subsubsection{ROOT Output "Simple"} +\label{sec:ddg4-components-IO-ROOT-simple} +%============================================================================= +\noindent + +%============================================================================= +\subsubsection{LCIO Output "Simple"} +\label{sec:ddg4-components-IO-LCIO-simple} +%============================================================================= +\noindent + + + +%============================================================================= +\newpage +\begin{thebibliography}{9} +\input{DD4hep-bibliography.tex} +\bibitem{bib:DDSegmentations} C.Grefe et al., + "The DDSegmentation package", + Non existing documentation to be written. +\end{thebibliography} +%============================================================================= +\end{document} diff --git a/doc/LaTex/ednmath0.sty b/doc/LaTex/ednmath0.sty new file mode 100644 index 0000000000000000000000000000000000000000..363c6c6aa5c45a9dab4b8945c7d7ee8afd595fd1 --- /dev/null +++ b/doc/LaTex/ednmath0.sty @@ -0,0 +1,202 @@ +%% Macro package `ednmath0.sty' for LaTeX2e, +%% copyright (C) 2004 Uwe L\"uck, +%% http://www.contact-ednotes.sty.de.vu +%% --author-maintained; +%% math support for `lineno.sty' and `ednotes.sty'. +%% +\def\fileversion{v0.2b} \def\filedate{2005/01/10} +%% This program can be redistributed and/or modified under the +%% terms of the LaTeX Project Public License distributed from +%% CTAN archives in directory macros/latex/base/lppl.txt; either +%% version 1.3a of the License, or any later version. +%% The latest version of this license is in +%% http://www.latex-project.org/lppl.txt +%% There is NO WARRANTY. +%% This code is very EXPERIMENTAL! +%% +%% Please report bugs, problems, and suggestions via +%% +%% http://www.contact-ednotes.sty@web.de +% +%% * MAIN FEATURE * +% +% lineno.sty's \linelabel and ednotes.sty's commands are enabled +% to work in math mode if it's "entered in outer mode" +% (including `displaymath' and `equation' environments). +% (lineno.sty is the package by Stephan Boettcher.) +% They will even work in tabular environments that are adjusted +% to notes by package `edtable.sty'. +% +% CAVEATS: +% -- Does not work yet in environments like LaTeX's +% `eqnarray'. (This could probably repaired along the lines +% of Edtable.sty--we're short of time and will try later.) +% -- Useful error messages when (i) math mode is entered from +% inner mode or when (ii) a math display gets not line number +% are missing at present. +% +%% * USAGE: * +% +% * Most simple: * +% --If you are working with ednotes and want to use its +% commands in math mode, load ednotes.sty--version 0.8 +% onwards--with its package option `mathnotes'. +% --If you don't work with ednotes, only with lineno, you +% get the main feature of making \linelabel work in math mode +% by loading lineno.sty--version 4.1 onwards--with its +% package option `mathrefs'. +% +% * Switch off and on: * +% To reduce danger resulting from missing error messages +% ("caveat" above), you may switch these new math facilities +% off by \NoNotesToMath where you don't expect to need them. +% You may switch them on again by \NotesToMath where you want +% to use them, being aware of the danger. Both commands work +% locally, so you can replace one of them by enclosing it in +% a group. E.g., even, after \NoNotesToMath you can use an +% environment as follows: +% \begin{NotesToMath} +% <text> +% \end{NotesToMath} +% (I am not quite sure that this is useful.) +% +% * Customize ellipsis: * +% ednotes' \lemmaellipsis is changed to expand to +% \mathlemmaellipsis when entering math, and this is preset +% to be LaTeX's \mathellipsis. (This is three dots as +% \mathinner.) You can change this by redefining +% \mathlemmaellipsis, e.g.: +% \renewcommand{\mathlemmaellipsis}{\cdots} +% If you need \cdots as the ellipsis at a single place only, +% you may, of course, use the `<...>' option of \<, e.g.: +% $ x = \Anote{a\<<\cdots>bcd\>e}{Indeed?} - y $ +% +% * Customize note mode: * +% For variant readings, you may want that the note is +% usually set in math mode--so you may want that you +% needn't type the dollar signs in the note text. +% Note that you can do this by customizing \notefmt, +% and you can do this by customizing \Anotefmt (e.g.) +% to have this feature for \Anote only. +% + +\NeedsTeXFormat{LaTeX2e} +\ProvidesPackage{ednmath0}[\filedate\space\fileversion\space + math support for lineno/ednotes (ul)] +% +%% User commands: +\def\NotesToMath{\let\@LN@mathhook\@LN@labelinmath + \@bsphack \@esphack +% For \begin{NotesToMath} +} +\def\NoNotesToMath{\@bsphack + \def\@LN@mathhook{\@parmoderr\@gobble}% + \@esphack +} +\def\endNotesToMath{\@bsphack\@Esphack} +\let\endNoNotesToMath\endNotesToMath +% +%% Core code for lineno.sty: +\@ifundefined{@LN@postlabel}{% + \PackageError{ednmath0}{% + Bad lineno.sty version% + }{% + lineno.sty from 2004/08/16 or later + must be loaded earlier.% + }% +}{% + \def\@LN@labelinmath#1{% + \ifmmode + \@LN@postlabel{#1}% + \else + \@parmoderr + \fi + } +} +% +%% Core code for ednotes.sty: +\@ifundefined{@EN@note}{% +% v0.01 sent a warning in this case. Considered superfluous now. +}{% + \def\@EN@themathlemmatag{% + \ifmmode + \toks@\expandafter{\@EN@lemmatag}% + \edef\@EN@lemmatag{% + $% + \def\noexpand\lemmaellipsis{% + \noexpand\mathlemmaellipsis}% + \the\toks@ + $% + }% +% \expandafter \def \expandafter \@EN@lemmatag +% \expandafter {\expandafter $\expandafter +% \def \expandafter \lemmaellipsis \expandafter {% +% \expandafter \mathlemmaellipsis \expandafter }% +% \@EN@lemmatag $}% + \fi + } +% To be sure, \lemmaellipsis doesn't need to be changed when +% ednotes `\<...\>' feature is not used. Though I prefer to +% use one hook only in ednotes for both situations, with and +% without `\<...\>'. +% +% The final \unskip in ednotes' \@EN@lemmatag would undo a final +% \quad. That's OK: outside math the same happens. +% In v0.01, \NoNotesToMath undid ednotes changes for math mode. +% However, re-appearence of \linelabel error messages suffices. +% +% Now add lemma switch to the left of \[No]NotesToMath: + \toks@\expandafter{\NotesToMath} + \edef\NotesToMath{% + \let \noexpand\@EN@mathlemmatag \noexpand\@EN@themathlemmatag + \the\toks@ + } +% \typeout{\string\NotesToMath: \meaning\NotesToMath} + \toks@\expandafter{\NoNotesToMath} + \edef\NoNotesToMath{% + \let \noexpand\@EN@mathlemmatag \relax + \the\toks@ + } +% \typeout{\string\NoNotesToMath: \meaning\NoNotesToMath} +} +% We need no extra device for a choice for users whether the *note* +% should be set in math mode or in horizontal mode by default +% (which might depend on the kind ["layer"] of notes). +% This can be done already by customization of ednotes' \notefmt. +% However, we might change ednotes' default \notefmt to default +% \renewcommand*{\notefmt}[1]{$#1$} +% +\let\mathlemmaellipsis\mathellipsis +%% TODO: Since when has LaTeX provided \mathellipsis? +%% -> \Needs... +% +% Default: +\NotesToMath +% +\endinput + +%% TODO: Without \linenumberdisplaymath, in displaymath, +%% an error should be shown. Use, e.g., that in a displaymath +%% \ifinner is false. +%% TODO: E.g., by changing \everymath, perhaps can be warned +%% that the math group is in a box already, so the vertical +%% items will get lost. +%% TODO: Adjust `eqnarray' (in Edtable?) as well. + +%% VERSION HISTORY: +v0.01 2004/08/16 First version, sent to Christian. +v0.02 2004/08/16 Considerably simplified for ednotes. + 2004/08/19 Added ellipsis stuff, documentation, and + instructions. Uncapitalized package names. + Added \end[No]NotesToMath. + 2004/08/20 Added \@bsphack and \@esphack; corrected + ednotes extension (too much deleted, completely + wrong), introducing \@EN@themathlemmatag. +v0.02b .../08/31 Rearranged preamble concerning maintenance. +v0.1 2004/09/20 Removed mentions of `linenox0.sty'. +v0.2 2004/10/07 Removed another mention of `linenox0.sty'; + Instructions: `lineno' or `ednotes.sty' option. +v0.2a 2004/11/07 LPPL v1.3a. +v0.2b 2005/01/10 Contact via http. + + diff --git a/doc/LaTex/edtable.sty b/doc/LaTex/edtable.sty new file mode 100644 index 0000000000000000000000000000000000000000..206347539e7668d574131b783ed9f6b5059f9afa --- /dev/null +++ b/doc/LaTex/edtable.sty @@ -0,0 +1,571 @@ +%% `edtable.sty'---Uwe L"uck, direction Christian Tapp. +%% LaTeX package for tables with line numbers and +%% editorial notes. +%% +%% Copyright (C) 2003-2005 Uwe L"uck--author-maintained. +%% +\def\fileversion{1.3c} \def\filedate{2005/10/03} +%% +%% This file can be redistributed and/or modified under +%% the terms of the LaTeX Project Public License; either +%% version 1.3 of the License, or any later version. +%% The latest version of this license is in +%% http://www.latex-project.org/lppl.txt +%% We did our best to help you, but there is NO WARRANTY. +%% +%% Please send your comments via +%% +%% http://www.contact-ednotes.sty.de.vu +%% +%% * USAGE: * +% +% *Requirements/overview:* +% +% The package is made for the background of the LaTeX2e macro +% package and enhances functionality of the following packages: +% 1.) Stephan I. B"ottcher's `lineno.sty' for printing line +% numbers in the margin and a \label version \linelabel +% relating labels to line numbers; +% 2.) our `ednotes.sty' for indicating variant readings and +% other editorial remarks in separate footnote apparatuses; +% 3.) David Carlisle's `longtable.sty' for multi-page tables. +% %% TODO: supertabular etc.!? +% 4.) our `ltabptch.sty' for a patch of `longtable.sty' +% (i.e., optionally, see below). +% +% Actually, only the first package is necessary for using the +% present one. The present one needs your line numbering commands +% according to the first one and its documentation to which we +% refer here. We likewise refer to the remaining packages for the +% details of their functionality. +% +% `lineno.sty' version 4.1 and (in case it is used) `ednotes.sty' +% version 0.8 (onwards) are needed. For obtaining recent versions +% of required packages, see the CTAN folder +% /macros/latex/contrib/ednotes. +% +% *Install/load:* +% 1.) To be used, the present file must be put into a folder +% that (La)TeX searches. You should have obtained a file +% containing more detailed hints about this. +% 2.) We recommend loading this file *not* by +% \usepackage[<options>]{edtable} but by loading `lineno.sty' +% or `ednotes.sty' with package option `edtable'. +% 3.) To use the package options `longtable' and +% `nolongtablepatch' that are described below, enter them +% as options for `lineno.sty' or `ednotes.sty'. +% +% *User Commands:* +% +% 1. The package defines an environment `edtable' -- for its +% syntax we consider two cases: +% (a) Let <stdtable> be a tabular environment "like `tabular'". +% "Like" here means: (i) we have tested it with `tabular', but +% it should work with many more (e.g., from the `array' and +% `tabularx' packages) -- which share certain properties of +% implementation and requirements. Sorry, you must try, or we +% hope you will (and tell us). (For wizards: <stdtable> may +% probably be anything using a single \halign and \tabskip=0pt.) +% Definitively: +% (ii) LaTeX's standard `array' and other environments are *not* +% "like" `tabular'. Namely, environments that work only in math +% mode are not meant here. They are considered below in `b.'. +% (iii) `longtable' from the `longtable' package of the `tools' +% bundle neither is meant. An option of the present package +% deals with it as described below. Neither `supertabular' is +% meant. +% (iv) In general, usage with tabular environments that can +% break across pages as in (iii) is not recommended, at least +% when working with `ednotes.sty'. Even if some worked here, a +% shortcoming with `ednotes.sty' would be that the footnotes can +% appear on bad pages. +% -- Now the syntax is: +% \begin{edtable}{<stdtable>}<args><entries>\end{edtable} +% -- where <args> and <entries> are usual arguments and entries +% for <stdtable>. So an example is: +% \begin{edtable}{tabular}{cc} +% left upper & right upper \\ left lower & right lower +% \end{edtable} +% This produces just what <stdtable> does in an extra line, +% only adding line numbers in the margin and processing `ednotes' +% commands in the entries appropriately. +% (b) Let <stdarray> be an "array environment" like -- standard +% LaTeX's `array'! "Like" here means (i) ... analogously to +% <stdtable> above. (ii) "Text" ... oh, sorry, this is not clear +% to me at present, and I am in a hurry. %% TODO +% (iii) Nothing from the `amsmath' package seems to work here, +% sorry, I have tried a lot ... (iv) For standard LaTeX's +% `eqnarray', it is better to try the `linenomath' environment +% of `lineno.sty' [with package option `mathlines']. Its +% modifications in `amsmath' produce (at best) a spurious line +% number with the `linenomath' environment (up to now). +% -- Now the syntax is: +% \begin{edtable}[<$$$>]{<stdarray>} +% <args><entries>\end{edtable} +% -- where <args> and <entries> are usual arguments and entries +% for <stdarray>. <$$$> can be one of `$' or `$$'. Indeed, the +% <stdtable> syntax above (without [<$$$>]) *does not work* +% inside $...$ or $$...$$. -- An example: +% \begin{edtable}[$$]{array}{cc} +% a_{11} & a_{12} \\ a_{21} & a_{22} +% \end{edtable} +% Now, this produces just what <stdarray> does in an extra line +% etc. as with <stdtable>. However, \linelabel and `ednotes.sty' +% footnotes may need the `mathrefs' option of `lineno.sty'. For +% the difference between `[$]' and `[$$]', see below. +% +% 2. When working with `ednotes.sty', in +% \Anote{L1\<L2\>L3}{NOTE} +% L2 may contain &'s and \\'s, but L1, L3 must not! Analogously +% for \Bnote, etc., \Anotelabel...\donote..., etc. -- Well this +% holds for <stdtable>, hardly for <stdarray> ... %% TODO +% +% 3. On positioning: You may have wondered about `extra line' +% above. This means that `edtable' starts a new line at +% \begin{edtable} and at \end{edtable}. %% TODO: sure!? +% (a) It should be placed within a `center', `flushleft', or +% `flushright' environment for proper (vertical) spacing, but +% also works without. However, with <stdarray> and optional +% parameter `$$' of `edtable' (i.e., \begin{edtable}[$$]...), +% you can obtain the usual math display spacing *within a +% paragraph*; especially, the vertical space is less when the +% previous line is short ... and so on. +% (b) Horizontal positioning of line numbers (usually) needs a +% second run (after changing a table)! %% TODO: automatic warning. +% (For wizards: It may fail if some of \leftskip, \rightskip, +% \linewidth, and \@totalleftmargin are used in an unusual way.) +% A <dimen> register \ETextraoffset is provided whose value is +% 0pt by default and which additionally moves line numbers +% to the left (right) if given a positive (negative) value. +% %% TODO: any use? +% +% *Package options:* +% +% 1. Option `longtable' adjusts the `longtable' environment +% defined by David Carlisle's longtable.sty for use with +% `lineno.sty' and `ednotes.sty'. The option makes `longtable' +% environments appear with line numbers in the margin, according +% to `lineno.sty', and process `ednotes.sty' commands if line +% numbering is active according to `lineno.sty'. +% [We maintain an alternative package with just this function +% in a slightly different implementation.] %% -> ulnltab.sty. +% Lemmas may go across table entries as with `edtable' (see above). +% ---There might be options like `supertabular' for adjusting +% other tabular environments that cannot be handled by the +% `edtable' environment provided here---they have not been +% implemented yet! %% TODO +% +% 2. Option `nolongtablepatch' avoids loading/asking for +% `ltabptch.sty'. I.e.: according to LaTeX bugs database, +% tools/3180 and tools/3485, there have been problems with +% vertical spacing around `longtable' environments. By default +% the present package loads our `ltabptch.sty' or asks for it. +% Option `nolongtablepatch' overrides this. This is useful when +% you don't want to have the patch, especially when you use an +% "emergency stop" installation of TeX. +% +% *Wizard interface:* +% Macros \@ET@makeLineNumber, \@ET@use@outerhook, +% \@ET@execute@outerhook, \@ET@ampnotes \@ET@startlinewith, +% \@ET@trivialize@linelabel are provided as tools for adjusting +% tabular environments for use with `lineno.sty' and +% `ednotes.sty'. \@ET@step@linenumber is \let \stepLineNumber +% (from `lineno.sty'), but could be used as a hook for +% something different. See Environment `edtable' and Option +% `longtable' below for examples of application. +% %% TODO: specification here. +% +% +%% * Acknowledgements: * +% +% Stephan I. B"ottcher told us how to do it in extensive discussion +% and by providing some first code lines. We changed these essentially +% in some respects, but kept his general ideas and some parts of his +% macros, the latter even without knowing what we are doing. +% +% v1.3 is due to a request by Martin Brandenburg. +% +% * Now for internals: * +% +\NeedsTeXFormat{LaTeX2e}[1994/12/01] +% 1994/12/01: \newenvironment* etc. %% TODO: more recent needed? +\ProvidesPackage{edtable}[\filedate\space v\fileversion\space + arrays with lineno + ednotes (ul)] +% +% Alternative ideas for implementation: +% 1. There is a German package `TABMAC' enhancing `EDMAC' (cf. +% documentation of `ednotes.sty'). We could have rewritten its +% macros so it would work with `lineno.sty' and `ednotes.sty' +% in place of `EDMAC'. [TODO: "tabmac.sty"] +% 2. We redefine `longtable' by Option `longtable' because +% there seems to be only one reasonable use of the `longtable' +% environment in the course of a critical edition. This may be +% different for environments like `array' and `tabular' which +% can be used within text lines. Therefore, these environments +% are not redefined. +% 3. One might use \everycr, however: (a) it is executed +% before the first row, (b) it is executed in fake lines that +% `longtable' uses. +% 4. As an alternative to \everycr, there is the approach of +% redefining \cr and \crcr for setting \noalign. This needs +% redefining \@tabularcr etc.---not nice. We use this approach +% here for `longtable' which uses a stretching \tabskip. +% For \tabskip=0pt, we attach line numbers by a template. +% +% \RequirePackage{lineno}[2004/10/06] +% Wanted to check lineno version--causes unknown option error. +% See LaTeX bug latex/3730. + +% Options: + +%% TODO: underful page with `longtable.sty'!? +\let\if@ET@longtable\iffalse % \newif\if@ET@longtable@ +\DeclareOption{longtable}{\let\if@ET@longtable\iftrue} +\let\if@ET@ltabptch\iftrue +\DeclareOption{nolongtablepatch}{\let\if@ET@ltabptch\iffalse} +\ProcessOptions + +% Redefine \longtable if option: +\if@ET@longtable + % Stephan's direction for attaching a line number to each row + % is using \noalign in the course of \\. + % However, (1) the user should not worry about closing the table + % with \\ or without, and (2) the line number thing should not + % happen twice if \\ is the last token before \end{longtable}. + % Our solution: attach something to the beginning of \endlongtable + % which attaches line number unless an unsucceeded \\ has done it. + % This thing is activated by each row start and turned off by \\. + % Since the switch at row start may happen to be in a pbox, + % let it act globally on \endlongtable. (The \crcr at the beginning + % of \endlongtable must not be changed directly, since original + % \crcr may be required in table entries using \oalign etc.) + % + \RequirePackage{longtable}% +% \IfFileExists{longtable.sty}{\RequirePackage{longtable}}% +% {\RequirePackage{longtabl}}% +% For Atari problem, it suffices to rename `longtable.sty' +% into `longtabl.sty'. +% +% Patch for tools/3180 and tools/3485 of LaTeX bug database: + \if@ET@ltabptch + \IfFileExists{ltabptch.sty}{\RequirePackage{ltabptch}}{% + \PackageError{edtable}{% + ltabptch.sty (for improving spacing around\MessageBreak + longtable) missing! Be sure to use it always\MessageBreak + or never!% + }{% + To omit ltabptch.sty *and* escape this error,\MessageBreak + use package option `nolongtablepatch'.% + }% + } + \fi + \let\@ET@@longtable\longtable + \def\longtable{% + \ifLineNumbers + \expandafter\@ET@longtable + \else + \let\@ET@sw@cr\@ET@crcr % ... in \endlongtable. + \expandafter\@ET@@longtable + \fi + } + \def\@ET@longtable{% + % Since we have made it anyway, we use the method of redefining + % \halign for inserting the activating row start as well. + % However, redefinition must be repeated before every \LT@bchunk. + % \longtable and \LT@get@withs are good places for this. + \@ET@startlinewith\@ET@sw@cr@on + \@ET@trivialize@linelabel + \@ET@use@outerhook + \@ET@ampnotes + \let\LT@tabularcr\@ET@LT@tabularcr + \expandafter\def\expandafter\LT@get@widths\expandafter + {\LT@get@widths\@ET@startlinewith\@ET@sw@cr@on} + % Admittedly, we could make it less of a hack by using @{...} + % ---we could then leave \LT@get@widths untouched. + \@ET@@longtable + } + \def\@ET@sw@cr@on{\global\let\@ET@sw@cr\@ET@cr@attach} + % We are hacking a longtable version offering + % \def\LT@tabularcr{% + % \relax\iffalse{\fi\ifnum0=`}\fi + % \@ifstar + % {\def\crcr{\LT@crcr\noalign{\nobreak}}\let\cr\crcr + % \LT@t@bularcr}% + % {\LT@t@bularcr}} + % We need a redefinition of \cr which is not overridden by \@ifstar: + \def\@ET@LT@tabularcr{% + \relax\iffalse{\fi\ifnum0=`}\fi + \def\cr{\@ET@sw@cr}% + % So \crcr is affected by change of \@ET@sw@cr, cf. below. + \let\crcr\cr + \@ifstar + {\gdef\@ET@sw@nobreak{\nobreak + \global\let\@ET@sw@nobreak\relax}% + % {\def\cr{\@ET@sw@cr\noalign{\nobreak}}\let\cr\crcr + % Why didn't this work? %% TODO: try shorter again. + \LT@t@bularcr}% + \LT@t@bularcr + % {\let\cr\@ET@sw@cr \let\crcr\cr + % \LT@t@bularcr}% This accompanied \def\cr... above. + } + % Attach \@ET@sw@cr to beginning of \endlongtable: + \expandafter\def\expandafter\endlongtable\expandafter + {\expandafter\@ET@sw@cr\endlongtable} + \def\@ET@cr@attach{% Actually attaching line numbers. + \@ET@crcr\noalign{% Basically Stephan's approach. + % If we were not careful, following box containing line number + % could fool interline glue after longtable, even if tools/3485 + % is repaired in some way. This box should have same depth as + % the line composed previously. + \nobreak %% \@ET@ex... might cause page break. 2003/10/30. + \setbox\z@\@ET@makeLineNumber + \ht\z@-\prevdepth \dp\z@\prevdepth \box\z@ + \@ET@step@linenumber + \global\let\@ET@sw@cr\@ET@crcr % ... if called by \\. + % This also resets the \crcr starting \LT@echunk following + % \@xargarraycr or \@yargarraycr in \LT@argtabularcr. + % \let...\relax seems to suffice at well, but in case ... + \@ET@execute@outerhook %% 2003/10/30. + \@ET@sw@nobreak +% \@ET@execute@outerhook + }% + } + \let\@ET@crcr\crcr + \global\let\@ET@sw@nobreak\relax % Just to remind ... +\fi + +\let\@ET@step@linenumber\stepLineNumber +% \def\@ET@step@linenumber{\global\advance\c@linenumber\@ne} +\def\@ET@makeLineNumber{\hb@xt@\z@{\makeLineNumber}} +%% TODO: export to lineno.sty!? +% Special \halign: +% For `array' etc., we insert line numbers by a leftmost template. +% @{...} in the last argument of `array' etc. is difficult for this +% since `tabular*' has an additional argument. So we redefine +% \halign to put something to the right of the next \bgroup. +% Now, as a macro, \halign would break in an \edef or \xdef. +% Horribly, this danger has become quite real in longtable.sty's +% definition of \LT@bchunk. Only its latest version 4.10 has +% preceded \halign by a \noexpand (for mathtext.sty which +% redefines \halign as well). We need not rely on such a +% provision if we let \halign expand to \the<token register> +% for some token register. However, using \toks@ or \@temptokena +% is neither very safe---might be filled by macro ahead with +% something new. So reserve an own token register. +\newtoks\@ET@toks +\@ET@toks{\@ET@specialhalign} +% v1.3: In 'AMSmath', there are \halign's followed by explicit +% left braces. Thus '\def\@ET@specialhalign#1\bgroup{%' broke. +%% TODO ... +\def\@ET@specialhalign{% + \ifmeasuring@ \expandafter\@firstoftwo +% v1.3 2005/03/04, for `amsmath'. + \else \expandafter\@secondoftwo + \fi + {\let\halign\@ET@@halign \halign}% + {\@ifnextchar\bgroup\@ET@replace@arg\@ET@sphalign@to}} +%% TODO: change back, commenting out code above, report +%% error with `alignat'. +% \@ifnextchar\bgroup\@ET@replace@arg\@ET@sphalign@to} +% If `amsmath' not loaded (v1.3): +\AtBeginDocument{\@ifundefined{measuring@true}{% + \let\ifmeasuring@\iffalse}\relax} +\def\@ET@replace@arg#1{% + \def\@EN@tempa{#1}\def\@EN@tempb{\bgroup}% Corr. after v1.3b. + \ifx\@EN@tempa\@EN@tempb + \def\@EN@tempa{\@ET@sphalign@to\bgroup}% + \else + \def\@EN@tempa{\@ET@sphalign@to{#1}}% +% This may be wrong, #1 might be `t' from `to' ... + \fi + \@EN@tempa} +\def\@ET@sphalign@to#1\bgroup{% + \let\halign\@ET@@halign % Reset for nested arrays. + \halign#1\bgroup +% \ifmeasuring@\else % For `amsmath', moved backwards. + \@ET@startline % [Wizard interface, via \@ET@starlinewith.] +% \fi +} +% Wizard interface: +\def\@ET@startlinewith{% Next token precedes preamble. +% \let\@ET@@halign\halign % Or \AtBeginDocument? +% ... indeed: bad loop with long longtable (\LT@get@widths!?) + \def\halign{\the\@ET@toks}% + \let\@ET@startline +} +\AtBeginDocument{\let\@ET@@halign\halign} +% Or save it at start of environment only +% (don't repeat inside longtable). +% +% Outer hook for inserts: (wizard interface) +\def\@ET@execute@outerhook{% To be placed outside inner mode. + \@ET@outerhook \global\let\@ET@outerhook\@empty +} +\global\let\@ET@outerhook\@empty % Just to remind: global! +% \@EN@hookfn (ednotes) sends to outer hook: +\def\@ET@use@outerhook{% Wizard interface. + \def\@EN@hookfn{\g@addto@macro\@ET@outerhook}% +}%% TODO: move last line to `ednotes', \let\@ET@use...\@empty. +%% But this requires re-installing both packages +%% at the same time. See the `ampnotes' thing as well. +% +% Trivialize \linelabel: (wizard interface) +\def\@ET@trivialize@linelabel{\let\linelabel\@ET@linelabel} +\def\@ET@linelabel{% + \protected@edef\@currentlabel{\theLineNumber}% + \label +} +% Change ampersand at \Anote etc.: (wizard interface) +%% 2003/10/31. +% & is changed by \Anote etc. No \begin...\endgroup, +% next \\ or & after % note/donote command switches back. +% ---Global change seems to break table setup. +\begingroup +\gdef\@ET@hideamps{\catcode`\&\active} +\@ET@hideamps +\gdef\@ET@ampnotes{% + \let&\@ET@hideamp + %% & would be undefined after \\ in lemma. + \let\@ET@EN@rnote\@EN@note + \def\@EN@note{\@ET@hideamps\@ET@EN@rnote}% + \let\@ET@EN@rnotelb\@EN@notelabel + \def\@EN@notelabel{\@ET@hideamps\@ET@EN@rnotelb}% +} +%% TODO: & and \\ in \@EN@lemmaexpands!? +\endgroup +\def\@ET@hideamp{&} + +\newenvironment*{edtable}[2][]{% +% #1 $ or $$, #2 standard environment name. +%% TODO: star version!? cf. lineno.sty's `numquote'. + \def\@ET@mode{#1}% + \def\@ET@currenvir{#2}% + \ifhmode \ifnum\the\lastpenalty=-\@M\else +% \par must be executed for printing/stopping line numbers: + \@centercr\relax \noindent + \fi \fi + \ifvmode \noindent \fi % Otherwise linenumbers are indented +% -- however, not recommended. + \@ET@use@outerhook + \@ET@trivialize@linelabel + \@ET@ampnotes + \@ET@startlinewith\@ET@normal@startline + \global\advance\c@linenumber\m@ne % Stepping correction. +% (Must come after closing previous paragraph.) +% Calculate offset: + \global\advance\c@ET@array\@ne +% Saving/calling width of table (`longtable's algorithm). +% Test if there is \@flushglue on the left (center or flushleft): + \edef\@EN@tempa{\the\@flushglue}% +% ... v1.3: fool this for "$$". + \in@{$$}{#1\@nil}% \in@{#1}{#2} searches #1 in #2#1 ... + \edef\@EN@tempb{\the\ifin@\@flushglue\else\leftskip\fi}% + \ifx\@EN@tempa\@EN@tempb +% Assume \@ET@offset is 0pt else here. + \@ET@offset\linewidth + \advance\@ET@offset-% + \@ifundefined\@ET@arraywidth@csn % Shortened for v1.3. + {\linewidth\G@refundefinedtrue + \PackageWarningNoLine{edtab}{^^JLine numbers at + \@ET@currenvir\space need \jobname.aux}}% + {\csname\@ET@arraywidth@csn\endcsname}% +% Test if \@flushglue on the right (center): +% ... v1.3: fool it again. Repeat \in@ in case ... + \in@{$$}{#1\@nil}% + \edef\@EN@tempb{\the\ifin@\@flushglue\else\rightskip\fi}% + \ifx\@EN@tempa\@EN@tempb \divide\@ET@offset\tw@ \fi + \fi + \advance\@ET@offset\@totalleftmargin + \advance\@ET@offset\ETextraoffset % Offset ready. + \setbox\@tempboxa\hbox\bgroup +% v1.3: `alignat' complains later when this is \vbox instead. +% \vbox\bgroup % Tried in vain. + \ifx\@ET@mode\@empty\else $\fi + \csname#2\endcsname +}{% + \csname end\@ET@currenvir \endcsname + \ifx\@ET@mode\@empty\else $\fi + \egroup + \@ET@step@linenumber % Stepping correction. + \if@filesw + \immediate\write\@auxout{% + \gdef\expandafter\noexpand + \csname\@ET@arraywidth@csn\endcsname + {\the\wd\@tempboxa}}% +%% TODO: warning if changed!? + \fi +% No automatic line number at array line: + \nolinenumbers + \@ET@mode\ensuremath{\vcenter{\box\@tempboxa}}\@ET@mode % v1.3. + \@ET@execute@outerhook + \ifhmode \@centercr\relax \fi +% \par must be executed for proper restart of printing line numbers +% (think so). + \@endpetrue % Outside \@flushglue environment, avoid indent ahead. +%% TODO: slightly change for math mode around? Or give an error +%% in math mode. +} +%% TODO: make \edtable \outer!? +\def\@ET@normal@startline{% + \@ET@step@linenumber + \llap{\@ET@makeLineNumber \hskip\@ET@offset}% +} +\newdimen\@ET@offset +\newdimen\ETextraoffset +%% TODO: export to lineno.sty!? +\newcount\c@ET@array +\def\@ET@arraywidth@csn{ET@a@\romannumeral\c@ET@array} +% +%% TODO: .dtx +\endinput + +%% VERSION HISTORY: +v0.22 2003/01/13 First version, named `edtab02.sty', sent around, + together with ednotes.sty. +v0.23 2003/01/22 Added version history. +v0.24 2003/01/27 Copyright notice. +%%% v0.3 2003/03/03 Requires linenox0.sty. %% RETREATED +%% TODO: reconsider, see `lineno[x].sty'. +v0.25 2003/03/05 Added <ednotes.sty@web.de>. +v0.26 2003/03/23 Added \@ET@startlinewith to wizard command list; + moved redefinition \LT@get@widths from option code + into \@ET@longtable so this really happens in + line number mode only; moved \let\@ET@@halign\halign + from \@ET@startlinewith to \AtBeginDocument. +v0.27 2003/06/02 Added \ifvmode \noindent \fi to `edtable' definition; + 2003/06/10 added `lemma cannot run' to instructions. +v0.28 2003/10/31 \@ET@cr@attach: moved \@ET@execu..., added \nobreak. + Added \@ET@ampnotes and documentation: now working + across entries. +v1.0 2004/05/13 `ednotes.sty' etc., updated copyright. Renamed as + `edtable.sty' for TUGboat article. + \RequirePackage{lineno}, changed doc. accordingly. + Removed `may be released under different name'. +v1.10 2004/07/27 Looking for `longtabl.sty' for my Atari! + 2004/08/22 Added warning (screen/documentation) concerning + ltabptch.sty. + 2004/08/23 Added suggestion of option `nolongtablepatch'; + LPPL v1.3. +v1.2 2004/08/31 Rearranged preamble concerning maintenance, + removed `preliminary release'. + 2004/10/06 \newif -> \let...; option `nolongtablepatch'; + changed documentation accordingly and for + loading edtable.sty by lineno/ednotes option; + \let\@ET@step@linenumber\stepLineNumber; use + \ifLineNumbers. + 2004/10/07 Needed version numbers. + 2004/10/08 ltabptch warning -> error! + 2004/10/11 Disabled \RequirePackage{lineno}[...]; undid + the `longtabl.sty' thing from 2004/07/27. + 2004/10/12 latex/3730. +v1.2a 2004/11/07 LPPL v1.3a. +v1.2b 2005/01/10 Contact via http. +v1.3b 2005/03/04 Support for environments like `array' + environment. The description of `edtable' was + wrong in this respect! +v1.3 2005/03/07 Adaptations in documentation, and extended usage + instructions very much, correcting some + errors as well. Acknowledgement to M. B. +v1.3a 2005/03/09 Corrected numbering in `usage'. +v1.3c 2005/03/15 \@centercr\relax, TODO on math mode. + 2005/04/09 `editory' -> `editorial'. diff --git a/doc/LaTex/fnlineno.sty b/doc/LaTex/fnlineno.sty new file mode 100644 index 0000000000000000000000000000000000000000..5c53da606c756bc4502c8b02242dc618297b6168 --- /dev/null +++ b/doc/LaTex/fnlineno.sty @@ -0,0 +1,1149 @@ +\NeedsTeXFormat{LaTeX2e}[1994/12/01] +\ProvidesPackage{fnlineno}[2011/01/07 v0.55 + numbers to footnote lines (UL)] + +%% Copyright (C) 2010 Uwe Lueck, +%% http://www.contact-ednotes.sty.de.vu +%% -- author-maintained in the sense of LPPL below -- +%% +%% This file can be redistributed and/or modified under +%% the terms of the LaTeX Project Public License; either +%% version 1.3c of the License, or any later version. +%% The latest version of this license is in +%% http://www.latex-project.org/lppl.txt +%% We did our best to help you, but there is NO WARRANTY. +%% +%% Please report bugs, problems, and suggestions via +%% +%% http://www.contact-ednotes.sty.de.vu +%% +%% {\it This work has been supported +%% % and is owned %% wrong, owner is RUB -- 2011/02/09 +%% by the Deutsche Forschungsgemeinschaft (DFG), +%% organized %% 2010/12/18 TODO!? +%% by Prof.~Dr.\ Dr.\ Christian Tapp +%% at Ruhr-Universit\"at Bochum, Germany.} +%% %% 2010/12/18: +%% Christian also has constructed some critical tests. +%% +%% === Installing and Calling === +%% The file 'fnlineno.sty' is provided ready, installation only requires +%% putting it somewhere where \TeX\ finds it +%% (which may need updating the filename data +%% base).\footnote{\url{http://www.tex.ac.uk/cgi-bin/texfaq2html?label=inst-wlcf}} +%% +%% As usually, 'fnlineno.sty' is loaded by +%% % \begin{verbatim} +%% `\usepackage{fnlineno}' +%% % \end{verbatim} +%% below the `\documentclass' line and before `\begin{document}'. +%% +%% === Limitations === +%% v0.55 %%% v0.5 %% 2011/02/09 +%% should really work +%% the way users expect, %% 2011/02/09 +%% but please consider: +%% % In the \strong{present version (v0.4)}, 'flnineno.sty' is just +%% % ``work in progress"---with at least the following issues: +%% \begin{enumerate} +%% % \item Lines are numbered in an order +%% % that you may not like, in the presence of +%% % footnotes. +%% % Overcoming this failure by automagic +%% % will be the major further work on the package! +%% % (v0.5!?) +%% % +%% % \item The package is not expected to work with 'manyfoot' +%% % (neither 'ednotes' ... future work!). +%% +%% \item Nothing is known about compatibility with +%% packages (other than 'manyfoot' and 'bigfoot') +%% providing footnote features beyond standard \LaTeX. +%% +%% \item `\lipsum[<opt-arg>]' in main text produces +%% a different number of paragraphs ... +%% +%% %% 2010/12/18: +%% % \item `\pagebreak' (without optional argument, or +%% % `\pagebreak[4]') in footnotes prints footnote parts +%% % (splits) in wrong order.\footnote{TODO: +%% % (i)~extra case (using flag) in &\output +%% % with $&\outputpenalty=-10000$; +%% % \emph{or} +%% % (ii)~redefine &\pagebreak in footnotes ...} +%% %% 2010/12/19, "tried" "assumed" 2010/12/21: +%% \item v0.41 tried supporting `\pagebreak' in footnotes +%% for manual control of splitting footnotes. +%% %% 2010/12/20f.: +%% However, it wrongly assumed that `\pagebreak[4]' +%% forces a footnote split, cf. Section~\ref{sec:sw}; +%% users better still don't use `\pagebreak' +%% in footnotes! +%% +%% \item Much of the code is ``guessed" without complete +%% knowledge of \TeX\ internals and without having +%% tested many possible cases. +%% %% 2010/12/27: +%% \item \emph{Local} switching to ``pagewise" numbering +%% won't be possible for a while; we rather assume +%% that you \emph{always} want ``pagewise" numbering. +%% +%% \item Nothing has been tried to offer choices about the +%% \emph{style} of numbering footnotes. +%% \end{enumerate} +%% +%% \pagebreak %% 2011/02/09 +%% == Implementation == +%% === Terms === +%% ``\strong{OTR}" is short for \textit{``output routine"}, +%% ``\strong{MVL}" is short for \textit{``main vertical list"}. +%% %%% TODO "acro" +%% +%% === Basic Strategy === +%% \LaTeX's |\@footnotetext| writes the footnote text into the +%% insertion register. For numbering the footnote lines, +%% \emph{we here} do not execute this `\@footnotetext' +%% immediately after placing |\@footnotemark|, +%% but postpone its |\insert| a little so it +%% is executed only after the main text paragraph has been +%% broken into lines. Right below the line that contains the +%% footnote mark, a special new ``slot" of the \strong{OTR} +%% is called that interchanges ``the page so far" with the +%% footnote text. When the latter has been typeset, +%% another ``slot" of the OTR puts ``the page so far" +%% back to the MVL and immediately after that fills the footnote +%% text as just typeset on the MVL into the `\insert' register. +%% +%% Passing footnotes from horizontal mode to vertical mode +%% resembles 'lineno''s `\PostponeVadjust', but a +%% different \strong{list} |\FNLN@list| +%% must store code +%% (\textit{a})~for the footnote \strong{mark} and +%% (\textit{b})~for the footnote \strong{text}. +%% %%% (TODO: move this paragraph) +%% +%% === Package Options === +%% A package option |[check-latex]| %% typo article 2010/12/31 +%% for checking vital \LaTeX\ internals may once be offered +%% (TODO 2010/12/12) ... +\newif\if@FNLN@check@ +\DeclareOption{check-latex}{\@FNLN@check@true} +\ProcessOptions +%% +%% === Footnote Commands === +%% ==== Standard Footnotes ==== +%% The following macro |\FNLN@ltx@fntext| %% more 2010/12/16 +%% is a copy of \LaTeX's `\@footnotetext' +%% that we are varying. It may be used for a check +%% if the `\@footnotetext' that 'fnlineno.sty' encounters +%% is the one expected (TODO). +%% In line numbering mode, this code may never be needed +%% all at once, rather we will have to see which material +%% must be used at which point of our unusual way of +%% processeing footnotes. +\if@FNLN@check@ + \long\def\FNLN@ltx@fntext#1{\insert\footins{% + \reset@font\footnotesize + \interlinepenalty\interfootnotelinepenalty + \splittopskip\footnotesep + \splitmaxdepth \dp\strutbox \floatingpenalty \@MM + \hsize\columnwidth \@parboxrestore + \protected@edef\@currentlabel{% + \csname p@footnote\endcsname\@thefnmark + }% + \color@begingroup + \@makefntext{% + \rule\z@\footnotesep\ignorespaces#1\@finalstrut\strutbox}% + \color@endgroup}}% +\fi +%% +%% ==== Modifying Footnote Commands ==== +%% In order to number |\footnote| lines and make +%% `\linelabel' available in footnotes, it seems to suffice +%% (with standard \LaTeX) to \strong{redefine} +%% the internal |\@footnotetext|. +%% In line numbering mode, `\@footnotetext' will act as +%% |\FNLN@text|, +%% % \begin{itemize} +%% % \item[(i)] +%% (\textit{i})~% +%% placing a ``signal" \strong{output penalty} +%% below the current line via `\vadjust' and +%% % \item[(ii)] +%% (\textit{ii})~% +%% appending the footnote text to the +%% \strong{list} |\FNLN@list| of \strong{footnote texts}. +%% % \end{itemize} +%% +%% |\FNLN@@text| stores the `\@footnotetext' found, +%% we might check if it is `\FNLN@ltx@fntext' ... %% TODO +\let\FNLN@@text\@footnotetext +\def\@footnotetext{% + \ifLineNumbers \expandafter \FNLN@text + \else \expandafter \FNLN@@text + \fi} +\def \FNLN@text {% %% 2010/12/31 arg read later + \vadjust{\penalty-\FNLN@M@swap@codepen}% +%% Standard \LaTeX's `\@footnotetext' expands `\@thefnmark' +%% to produce the footnote mark at the page bottom, +%% right after it has been determined for the mark +%% in the main text. \emph{Here} the footnote text +%% will be typeset only when \emph{other} footnote marks +%% may have been formed for typesetting the main text +%% paragraph before. +%% %%% (TODO clearer wording) +%% In the \strong{footnote list} +%% macro |\FNLN@list|, the (\dqtd{`&\protect'ed}) +%% \emph{current} expansion <mark> of `\@thefnmark' +%% is stored as an item preceding the footnote text +%% <text>. One footnote entry in `\FNLN@list' +%% thus has the form \lq`<mark>\@lt<text>\@lt'\rq. +%% \LaTeX's internal `\g@addto@macro' is used to \emph{append} +%% an entry to the list (at the right). The OTR will later +%% take the entries from the left of the list. +%% +%% The argument of the auxiliary/temporary `\@tempa' +%% will contain the footnote text and thus must be able to +%% carry `\par' tokens. We therefore need a `\long' version of +%% `\protected@edef': + \let\@@protect\protect + \let\protect\@unexpandable@protect + \afterassignment\restore@protect + \long \edef \@tempa ##1{% + \noexpand\g@addto@macro \noexpand\FNLN@list {% + \@thefnmark \noexpand\@lt ##1\noexpand \@lt}}% +%% ... issuing +%% \lq`\g@addto@macro\FNLN@list{<mark>\elt<text>\@lt}'\rq\ ... + \@tempa %% reads arg +} +%% Here we initialize |\FNLN@list|: +\let\FNLN@list\@empty +%% +%% === Output Routines === +%% ==== 'lineno''s Output Routine ==== +%% The following is a copy of 'lineno''s OTR +%% that we are varying. It may be used for a check +%% if the OTR that 'fnlineno.sty' encounters +%% is the one expected (TODO). +\if@FNLN@check@ + \def\FNLN@lno@output {% + \LineNoTest + \if@tempswa + \ifnum\outputpenalty=-\@Mllbcodepen + \WriteLineNo + \else + \ifnum\outputpenalty=-\@Mppvacodepen + \PassVadjustList + \else + \LineNoLaTeXOutput + \fi + \fi + \else + \MakeLineNo + \fi + } +%% The ``signal penalties" used here are + \mathchardef\FNLN@M@llbl@codepen=11111 + \mathchardef\FNLN@M@ppva@codepen=11112 +\fi +%% Their names should mean ```\linelabel' code penalty" and +%% ```\PostponeVadjust' code penalty." +%% +%% |\TheLineNoLaTeXOutput|: +%% It turns out to be inconvenient here +%% that 'lineno' sacrifices access +%% to the \emph{primitive} `\output' (```\@tempa'"; +%% TODO: auxiliary package before loading 'lineno'!?; +%% later change 'lineno.sty' indeed). +%% So to change the OTR we use `\LineNoLaTeXOutput' as a hook +%% for adding additional cases of `\outputpenalt'ies. +%% We take a copy of `\LineNoLaTeXOutput' here. +\let\TheLineNoLaTeXOutput\LineNoLaTeXOutput +%% +%% ==== Tools for Temporary Parameter Changes ==== +%% |\GStoreReg{<register>}|\quad +%% (or\quad |\GStoreReg<register>|\\[\smallskipamount] +%% when <register> is a single token---\lq`\count0'\rq\ +%% being a counterexample ...)\quad +%% stores the current content of <register> +%% (\emph{globally}) as an internal macro so that it can be +%% restored later by\\[\smallskipamount] +%% |\RestoreReg{<register>}|\quad +%% \mbox{(or\quad }|\RestoreReg<register>|)\\[\smallskipamount] +%% or \emph{globally} by\\[\smallskipamount] +%% |\GRestoreReg{<register>}|\quad (|\GRestoreReg<register>|) +%% \\[\smallskipamount] +%% (The OTR runs in a local group!---Recall that assignments +%% to ``special dimens"---\TeX book p.\,271---are +%% automatically global.) +%% <register> is something that can be prefixed by `\the' +%% to read its content and to which you can assign a value +%% <value> by \lq<register><value>\rq. +%% (TODO: could also be some `\catcode'!) +%% %% and TODO allow changing name space! +\newcommand*{\GStoreReg}[1]{% + \expandafter \xdef \csname GS\string#1\endcsname {\the #1}} +\newcommand*{\RestoreReg}[1]{#1\csname GS\string#1\endcsname \relax} +\newcommand*{\GRestoreReg}{\global\RestoreReg} +%% |\GStoreSetReg{<register>}{<value>}| assigns %%% the new value +%% <value> to <register> (locally) after executing `\GStoreSet', +%% |\GStoreGSetReg| does the same \emph{globally} +%% (and still argument braces aren't needed when a single +%% token refers to the register). +\newcommand*{\g@storesetreg}[3]{\GStoreReg{#2}#1#2#3\relax} +\newcommand*{\GStoreSetReg} {\g@storesetreg\relax} +\newcommand*{\GStoreGSetReg}{\g@storesetreg\global} +%% (These preliminaries might go into an own new package, TODO! +%% + loop on list of <register>s ...) %% 2010/12/19 +%% +%% ==== The basic hook ==== +%% \label{sec:sw} +%% We use two more penalties triggering the ``MVL swaps:" +\mathchardef\FNLN@M@swap@codepen =11113 +\mathchardef\FNLN@M@insert@codepen=11114 +%% v0.41 deals with |\pagebreak| in footnote texts, +%% using a flag |\if@FNLN@sw@| that must be set globally. +%% %% 2011/01/07: +%% It turned out not to work properly; however, the new +%% switch has served a different purpose for ``continuous +%% line numbering," cf. section~\ref{sec:cont}. +\newif\if@FNLN@sw@ \global\@FNLN@sw@false %% v0.41 +%% When a `\pagebreak' triggers the OTR while typesetting +%% the footnote text, the page content is collected +%% in a box |\FNLN@holdft|: +\newsavebox\FNLN@holdft %% v0.41 +%% Using |\LineNoLaTeXOutput| for hooking into the OTR: +\renewcommand*{\LineNoLaTeXOutput}{% + \ifnum\outputpenalty=-\FNLN@M@swap@codepen + \SwapFootnoteMain + \else + \ifnum\outputpenalty=-\FNLN@M@insert@codepen + \InsertFootnote + \else + \if@FNLN@sw@ %% v0.41 +% \showthe\outputpenalty %% 2010/12/20 + \global\setbox \FNLN@holdft \vbox{% + \unvbox\FNLN@holdft +%% %% moved here, clarified 2010/12/21: +%% TODO from v0.41: `\pagebreak[4]' does not seem to force (reliably) +%% splitting a footnote; if the footnote is not split here, +%% at present the `\baselineskip' is lost, +%% see the footnote paragraph starting +%% with \qtd{C} in `edfndemo.pdf' as of 2010/12/21. +%% We would need some measuring ... `\pagebreak' +%% might be redefined ... resembling \LaTeX's `\@specialoutput'! + \unvbox\@cclv +%% TODO same problem here, see the footnote paragraph starting +%% with \qtd{D} in `edfndemo.pdf' as of 2010/12/21. + \penalty\outputpenalty}% + %% TODO reset page book-keeping!? %% v0.41 + \else + \TheLineNoLaTeXOutput %% "the real \LineNoLaTeXOuput" + \fi + \fi + \fi +} +%% \strong{An idea:}\quad Instead of so many `\ifnum', use +%% \[`\csname<chars>\the\outputpenalty\endcsname'\] +%% ... in 'lineno.sty', when you really have a broad +%% range of `\outputpenalties' useful to be +%% described by `\ifnum' range checks ... +%% +%% ==== Typesetting the Footnote Text ==== +%% |\SwapFootnoteMain| is the slot of the OTR that our +%% modified `\@footnotetext' calls with +%% $`\outputpenalty'=-`\FNLN@M@swap@codepen'$. +%% The ``column so far" is stored in a new box register +%% |\FLNL@holdcol|. +\newsavebox\FNLN@holdcol +\newcommand*{\SwapFootnoteMain}{% + \global \setbox\FNLN@holdcol \vbox{\unvbox\@cclv}% +%% (... cf. `\@holdpg' in \LaTeX.) +%% +%% The entire text of a footnote is typeset on top of +%% the MVL. `\vsize' is maximized temporarily to avoid +%% that the footnote text is broken across pages. + \GStoreGSetReg\vsize\maxdimen +%% However, the user may want to use `\pagebreak' +%% in a footnote in order to control manually where +%% a ``long" footnote is split. v0.41 tries to support +%% this: + \global\@FNLN@sw@true %% v0.41 +%% ... cf. Section~\ref{sec:sw}. +%% +%% There shouldn't be any `\topskip', the space +%% on top of a footnote is controlled by `\footnotesep' +%% entirely: + \GStoreGSetReg\topskip\z@skip +%% (`\nointerlineskip' as well as setting `\topskip' +%% locally instead fails ... according to `\showlists' ...) +%% +%% Resetting |\pagegoal| +%% (why doesn't it switch to $`\vsize'=`\maxdimen'$ automatically?), +%% |\pagetotal|, and the other ``special dimens" +%% (\TeX book p.\,271; rather experimental ... +%% I think it is important to restore them later ...) + \GStoreSetReg\pagegoal \vsize + \GStoreSetReg\pagetotal\z@ + \GStoreSetReg\pagestretch\z@ + \GStoreSetReg\pagefilstretch\z@ + \GStoreSetReg\pagefillstretch\z@ + \GStoreSetReg\pagefilllstretch\z@ + \GStoreSetReg\pageshrink\z@ + \GStoreSetReg\pagedepth\z@ +%% We must choose certain settings from `\@footnotetext' +%% such as font: + \reset@font\footnotesize + \interlinepenalty\interfootnotelinepenalty +%% \LaTeX's `split' things here are relevant at +%% `\insert\footins' only: (TODO!?) +% \splittopskip\footnotesep +% \splitmaxdepth \dp\strutbox \floatingpenalty \@MM + \hsize\columnwidth \@parboxrestore +%% The previous lines were from \LaTeX's `\@footnotetext'. +%% Now we need to restore the `\@thefnmark' that belongs +%% to the current footnote text. We use a macro that +%% tears two items from |\FNLN@list| and executes the +%% rest of \LaTeX's `\@footnotetext': + \expandafter \FNLN@typeset \FNLN@list \@@ +% \showthe\vsize +%% ... so a `\vsize' assignment without `\global' +%% is noted here, and an analogous `\topskip' assignment +%% is not!? TODO ... +} +%% |\FNLN@typeset| first removes something %% reworded 2010/12/26 +%% from the list of footnotes, similarly to \LaTeX's |\@xnext| +%% and 'lineno''s `\@LN@xnext', then executes a +%% remaining portion of \LaTeX's `\@footnotetext'. +%% The footnote text may contain `\par' tokens, +%% so the definition must be `\long': +\long\def \FNLN@typeset #1\@lt #2\@lt #3\@@{% + \gdef\FNLN@list{#3}% + \def\@thefnmark{#1}% +%% This was our own, and next \LaTeX\ continues: + \protected@edef\@currentlabel{% + \csname p@footnote\endcsname\@thefnmark + }% + \color@begingroup +%% We insert starting the 'lineno' settings ... + \linenumbers + \setfootnotelinenumbers %% 2010/12/25 +%% ... \LaTeX\ again (v0.41 exports dealing with +%% closing `\par' to `finstrut.sty'): + \@makefntext{% + \rule\z@\footnotesep\ignorespaces +%% We replace `#1' by `#2\par' (`\linenumberpar'), +%% so we really need `finstrut.sty': + #2\par + \@finalstrut\strutbox}% + \color@endgroup +%% Now we trigger the ``swap back slot" of the OTR: + \penalty-\FNLN@M@insert@codepen +} +\RequirePackage{finstrut} +%% +%% ==== &\insert\ the Footnote Text ==== +%% |\InsertFootnote| is the slot of the OTR that executes +%% `\insert\footins' with the numbered footnote text. +%% The ``column so far" stored in `\FNLN@holdcol' +%% is put onto the top of the MVL, and then parts of +%% \LaTeX's `\@footnotetext' are performed that haven't +%% been done earlier, applied to the footnote text +%% that the OTR should have found in `\box255'. +%% Before however, the previous `\topskip', `\vsize', and the +%% `\page'... book-keeping parameters are restored: +\newcommand*{\InsertFootnote}{% + \GRestoreReg\topskip \GRestoreReg\vsize +%% (... \emph{global} restoring of `\vsize' proved vital with +%% 'edfndemo' 2010/12/17 ...) + \RestoreReg \pagegoal \RestoreReg\pagetotal + \RestoreReg \pagestretch + \RestoreReg \pagefilstretch + \RestoreReg \pagefillstretch + \RestoreReg \pagefilllstretch + \RestoreReg \pageshrink \RestoreReg\pagedepth + \unvbox\FNLN@holdcol + \insert\footins{% + \splittopskip\footnotesep + \splitmaxdepth \dp\strutbox \floatingpenalty \@MM +%% Support of `\pagebreak' with v0.41: + \unvbox\FNLN@holdft %% v0.41 + \unvbox\@cclv}% + \global\@FNLN@sw@false %% v0.41 +%% With v0.5, global settings for ``pagewise" numbering +%% must be restored: %% 2010/12/26 + \unsetfootnotelinenumbers +} +%% +%% === ``Continuous'' Numbering === +%% \label{sec:cont} +%% ==== Goal ==== +%% With v0.5, for the first time we try to get a +%% ``pagewise" numbering such that, if a main text line +%% has a footnote, +%% (\textit{i})~its printed number is just the natural +%% successor of the printed number of the previous main +%% text line +%% (instead of continuing previous numbering with the +%% lines of the footnote first), +%% and (\textit{ii})~the printed numbers of footnote lines +%% just continue the printed numbers of the main text lines. +%% This ``obvious'' desirement is not easy to achieve; +%% already pagewise numbering of main text lines, +%% without numbering footnote lines, has been somewhat +%% ingenious. +%% +%% ==== How to Number Lines Pagewise ==== +%% The basic idea of 'lineno''s pagewise numbering is: +%% \begin{enumerate} +%% \item Each numbered line of the document is identified +%% by a unique counter value, an ``absolute" number. +%% \item For each page (and column), the range of absolute +%% line numbers occurring on them is recorded +%% (or actually: the first and the last number). +%% \item The ``public," ``human-readable" (``pagewise") +%% format of a given absolute line number $l$ is generated by +%% (\textit{i})~finding the page (and column) with +%% first number $n$ and last number $k$ such that +%% $n\leq l\leq k$, +%% (\textit{ii}) ``printing" $l-n+1$ in ``columnwise" +%% mode, otherwise $l-m+1$ where $m$ is the first +%% absolute line number in the left-hand column of the +%% same page. +%% \end{enumerate} +%% \strong{Generating} the ``pagewise" representation for a +%% given absolute line number $l$ thus may be summarized as +%% \emph{finding the corresponding \emph{\strong{offset}} value} +%% to be subtracted ($n$, $n+1$, $m$, or $m+1$ ...). +%% +%% When \emph{footnote} lines are to be numbered as well, +%% a little problem is the order in which main text and +%% footnote lines increment the absolute counter. +%% 'lineno''s mechanism for this is started immediately +%% after a paragraph has been broken into lines. +%% Each line of the paragraph then calls a macro +%% generating the line number. 'fnlineno' now interrupts +%% numbering of main text lines at a line issuing a footnote. +%% The footnote text is typeset, including numbering its +%% lines at each end of a footnote paragraph. When the +%% footnote text has been sent into the `\insert' register, +%% numbering of main text lines is resumed. +%% +%% Up to v0.4 (a development version), we used the \emph{same} +%% absolute counter for main text and footnote lines. +%% When a page $p$ has more than one main text line and the first +%% one has a long footnote continued on the next page~$p+1$, +%% there is no ``range" of absolute line numbers +%% characterizing page~$p$ any more, +%% because the greatest absolute line number of page~$p$ +%% exceeds the absolute line numbers of the footnote continued +%% on page~$p+1$. +%% +%% 'lineno''s procedure can be revived by numbering +%% main text lines and footnote lines independently +%% from each other. We use \emph{two} absolute counters, +%% one is incremented with main text lines only, +%% the other with footnote lines only. +%% Numbering of main text lines just will not be affected +%% by numbering of the footnote lines. +%% +%% Almost the same will hold for footnote lines. +%% Each page (and column) will have a characteristic +%% ``range" of absolute footnote line numbers $\{n,\dots,k\}$. +%% The only notable difference will be that for footnote line~$l$ +%% we print $(l-n+1)+(K-N+1) = (K+l)-(N+n)+2$ instead of +%% $l-n+1$---where $\{N,\dots,K\}$ is the range of \emph{main text} +%% line numbers of the page (and column). +%% +%% The previous discussion of \strong{generating} the printed +%% line number from its absolute version +%% has assumed that corresponding \strong{offset} values +%% have been given somehow, or that the ``line number ranges" +%% for pages are known from somewhere. +%% In fact, these ranges are \strong{computed} at the +%% \strong{start} of a \LaTeX\ run \emph{before} typesetting, +%% when reading the `.aux' file for the first +%% time. They are used in the entire document. +%% While typesetting, each numbered line of main text leaves +%% a record of its absolute number and page number in the new +%% version of the `.aux' file that the run creates, +%% a two-parameter macro `\@LN'. With 'fnlineno.sty', +%% there will be new `\@FLN' entries of the same type. +%% These `.aux' entries are used for building +%% the page range data for the next run. +%% When the document source has been changed, at least +%% \emph{two runs} will usually be required +%% to get correct line numbers in page margins, +%% and \emph{another} run will be needed so references +%% to line numbers by `\ref' and `\linelabel' are correct. +%% +%% ==== Summary of Changes ==== +%% Variants of 'lineno.sty''s code for ``pagewise" +%% numbering are following. Sometimes we generalize +%% `pagewise' stuff from 'lineno' and re-implement pagewise +%% numbering of main text lines as a special case, +%% the other special case being numbering of footnote lines. +%% +%% Five things need modifications: +%% \begin{description} +%% \item[Building page info macros:] +%% Processing `\@LN' and `\@FLN' `.aux' entries will +%% use shared building macros, the difference is +%% obtained by switching \strong{name spaces}. +%% (It may be notable that a page may get one +%% info macro for main text and another for +%% footnote text, if it contains footnote text.) +%% \item[Logging:] +%% While typesetting, the shared logging macro +%% is switched to write either `\@LN' or `\@FLN' +%% to the `.aux' file. Also, `\c@linenumber' +%% may refer to either the main text or to the +%% footnote text counter. +%% \item[Generating ``pagewise" format:] +%% The choice of `\c@linenumber' also determines +%% which counter is incremented, and again +%% name spaces for page info macros are switched. +%% For footnote lines, +%% a tail macro for adding the number of main text lines +%% will be activated. +%% \item[Referencing:] +%% The `.aux' file may have entries from `\linelabel' +%% containing large numbers from an ``absolute" counter. +%% In generating the ``human-readable" number, +%% it must be known whether it is a main text or a +%% footnote line number. +%% %% 2010/12/28: +%% An additional complication is referring to a +%% main text line from a footnote and vice versa---thinking +%% of global changes in generating the number. +%% Or even think of the case referring from unnumbered text +%% to numbered text! +%% (I have wondered before if the entry couldn't be +%% the ready human-readable number, TODO!) +%% %% 2010/12/27: +%% \item[Lists of ``vertical tasks":] +%% 'lineno.sty' (v4) has introduced two lists of +%% tasks that were issued in horizontal mode +%% but only can be completed after breaking a paragraph +%% into lines: one for `\linelabel's and one for `\vadjust' +%% items that must wait until the line number has been +%% attached. It is essential that the tasks are processed +%% in the same order in vertical mode as they were +%% issued in horizontal mode. As we are now interrupting +%% processing of main text paragraphs for processing +%% footnotes, tasks for footnote text must be lined up +%% in separate lists than tasks for main text. +%% This is indeed essential for the previous issue +%% of getting `\linelabel' work in footnotes as well +%% as in main text. +%% \end{description} +%% +%% ==== Info Building ==== +%% % These macros +%% |\@LN|, |\@FLN|, and |\@FNLN| +%% are processed at reading the `.aux' file before typesetting only. +%% The \strong{interface} to \strong{generating} +%% ``pagewise" and footnote line numbers just are |\LN@Pfirst| +%% and |\FLN@Pfirst|, eventually pointing to the first page/column +%% with numbered main text lines or footnote lines, resp. +\def \FLN@Pfirst {\nextLN\relax} +%% This initialization of `\FLN@Pfirst' is just the same +%% as the one of `\LN@Pfirst' in 'lineno.sty'; +%% their expansions are changed as soon +%% as such a page is found, replacing the `\relax' by the +%% corresponding page info macro. +%% +%% `\LN@Pfirst' and `\FLN@Pfirst' are passed to +%% |\testFirstNumberedPage| via the hook |\FNLN@first@numbered| +%% that by default is the same as `\LN@first': +\def \FNLN@first@numbered {\LN@Pfirst} +%% (oh, it must be `\def' here to recognize the change ...). +%% This must be changed by `\setfootnotelinenumbers' +%% (`\let' then, as when called the change will have happened). +%% +%% Moreover, they are passed to |\NumberedPageCache| +%% (the page info macro where a search starts, +%% ``current" page/column) as its initialization; +%% the ``generating" macros then change the +%% latter macro following `\nextLN' in the page info macros. +%% +%% In this sense, no other ``name space switching" is needed +%% for communication with other functions. +%% +%% 'lineno.sty' has changed |\LastNumberedPage| globally ... +%% the last page with numbered \emph{footnote} lines +%% may well be another one than the last page with +%% numbered \emph{main} text lines ... +%% But fortunately, also `\LastNumberedPage' +%% is needed in reading the `.aux' before typesetting only +%% (`\@onlypreamble' is \LaTeX's disabling command): +\@onlypreamble\LastNumberedPage +%% In 'lineno.sty', we have `\def\LastNumberedPage{first}'. +%% We need the same for the footnote variant |\FNLN@last@numbered| +%% (to be handled globally!): +\global \let \FNLN@last@numbered \LastNumberedPage +\@onlypreamble \FNLN@last@numbered +%% |\@FNLN{<names>}<last-numbered>{<line>}{<page>}| +%% \\[\smallskipamount] +%% generalizes 'lineno.sty''s `\@LN{<line>}{<page>}' +%% to re-implement it. +%% There is an additional parameter argument <names> +%% for choosing name spaces +%% and a parameter <last-numbered> for choosing the macro +%% storing the ``last numbered page." +%% (An argument without braces expects a macro name.) +\newcommand* \@FNLN [4]{{% + \expandafter\@@LN + \csname #1#4C\@LN@column \expandafter\endcsname + \csname #1O#4\endcsname + {#3}{#4}{#1}{#2}}} +\@onlypreamble\@FNLN +%% As in 'lineno.sty' `\@LN' calls `\@@LN', a new variant +%% of `\@@LN' is called by `\@FLN' here, but it gets one +%% additional parameter for passing <names> +%% and another for passing <last-numbered> from `\@FLN'. +%% So the new syntax is\\[\smallskipamount] +%% |\@@LN<info><first-page-line>{<line>}{<page>}{<names>}<last-numbered>|: +\renewcommand* \@@LN [6]{% + \ifx#1\relax + \ifx#2\relax\gdef#2{#3}\fi + \expandafter\@@@LN\csname #5#6\endcsname#1% + \xdef#1{\lastLN{#3}\firstLN{#3}% + \pageLN{#4}{\@LN@column}{#2}\nextLN\relax}% + \else + \def\lastLN##1{\noexpand\lastLN{#3}}% + \xdef#1{#1}% + \fi + \xdef#6{#4C\@LN@column}} +\@onlypreamble\@@LN +%% 'lineno.sty''s |\@@@LN| does not need any adjustment. +%% +%% 'lineno.sty''s |\@LN{<line>}{<page>}| is reimplemented as +\def \@LN {\@FNLN{LN@P}\LastNumberedPage} +%% ---so `\@LN' really does the same as before, including name spaces. +%% +%% |\@FLN{<line>}{<page>}| is the other special case of the +%% new `\@FNLN'---an `F' precedes the earlier names, and +%% |\FNLN@last@numbered| is the storing macro initialized above: +\def \@FLN {\@FNLN{FLN@P}\FNLN@last@numbered} +%% For logging, we make both unexpandable: %% 2010/12/27 +% \AtBeginDocument{\let\@LN\relax \let\@FLN\relax} +%% ... but this way nothing appears in the file!? TODO ... +\@onlypreamble\@LN \@onlypreamble\@FLN +%% For reading the `.aux' finally, we do what +%% 'lineno' does with `\@LN': +\AtEndDocument{\let\@FLN\@gobbletwo} +%% +%% ==== Tool for Reusing Global Operations with Macros ==== +%% %% 2010/12/28 +%% 'lineno.sty' v4 provides list handling (changing lists globally) +%% and global changes of `\NumberedPageCache'. +%% We want to use them in ``main text" mode +%% as well as in ``footnote" mode. +%% To use such an operation on <ln-macro> for <fln-macro>, +%% we `\global\let<ln-macro><fln-macro>', apply the operations, +%% and finally `\global\let<fln-macro><ln-macro>'. +%% However, we are not only interested in how <fln-macro> +%% is changed this way, rather <ln-macro> also is used as input +%% for some operations, and we can choose which <fln-macro> +%% should be used as input. To switch from working on/with +%% <fln-1> to <fln-2> using <ln-macro> with an option +%% to use <fln-1> later again, a tool +%% |\GStoreUse<ln-macro><fln-1><fln-2>| is provided +%% (should render later switchings much better readable): +\newcommand* \GStoreUse [3]{\global\let#2#1\global\let#1#3} +%% I.e., current content of #1 is stored in #2, then +%% #1 attains the content of #3. +%% +%% ==== General Settings for Typesetting Stage ==== +%% % %% 2011/01/01: %% 2011/01/02: wrong! +%% % With 'ednotes', it turns out that the heading is not quite +%% % correct, 'ednotes'' special `\newlabel' mechanism evaluates +%% % `\getpagewiselinelabel' already for building its note +%% % info macros at the first reading of the `.aux' file. +%% +%% %% 2010/12/27: +%% Oh my dear, it seems that all the switching +%% for the footnote variant of `pagewise' must be global +%% (I can't find something useful using `\aftergroup' quickly). +%% Therefore, I render 'lineno''s |\setpagewisenumbers| +%% acting globally: +\renewcommand*\setpagewiselinenumbers{% + \global\let \theLineNumber \thePagewiseLineNumber + \global\let \c@linenumber \c@pagewiselinenumber + \global\let \makeLineNumber \makePagewiseLineNumber +} +%% I just force this, hehe ... +\setpagewiselinenumbers +%% As a counterpart to `\c@pagelinenumber', +%% |\c@footnotelinenumber| is reserved for the +%% absolute footnote line numbers: +\newcount\c@footnotelinenumber +%% %% 2011/01/01 severe-bug fix, why didn't show up?: +%% |\FNLN@@cache| stores `\NumberedPageCache' +%% as from ``main" mode: +\let \FNLN@@cache \NumberedPageCache +%% |\FNLN@cache| stores `\NumberedPageCache' +%% as from ``footnote" mode; its initial content is the +%% counterpart or analogue to `\LN@Pfirst': +\def \FNLN@cache {\FLN@Pfirst} +%% %% 2010/12/28: +%% |\FNLN@foot@cache| and |\FNLN@main@cache| +%% switch |\NumberedPageCache|: +\def \FNLN@foot@cache {% + \GStoreUse \NumberedPageCache \FNLN@@cache \FNLN@cache} +\def \FNLN@main@cache {% + \GStoreUse \NumberedPageCache \FNLN@cache \FNLN@@cache} +%% |\FNLN@labels| will be the counterpart to +%% 'lineno.sty''s `\@LN@labellist': +\global\let \FNLN@labels \@empty +%% |\FNLN@vadjusts| will be the counterpart to +%% 'lineno''s `\@LN@vadjustlist': +\global\let \FNLN@vadjusts \@empty +%% %% separation for referencing 2010/12/28: +%% Settings for footnote line numbers first resemble +%% `\setpagewiselinenumbers'; but more changes +%% are needed, and results from main text numbering +%% must be stored. +%% Some of the settings are needed \emph{locally} for +%% generating numbers for labels, collected in +%% |\setgetfootnotelinenumbers|; for this purpose +%% nothing must be stored explicitly: +\newcommand* \setgetfootnotelinenumbers {% +%% Change of `\theLineNumber' is omitted as we are \emph{reading}, +%% not writing a label. + \let\c@linenumber\c@footnotelinenumber +% \let\makeLineNumber\makeFootnoteLineNumber +%% But in fact, |\makeFootnoteLineNumber| and +%% |\makePagewiseLineNumber| will be the same. +%% The difference is made by the choice of +%% |\FNLN@first@numbered| and |\NumberedPageCache| +%% for the line range searches. + \let \FNLN@first@numbered \FLN@Pfirst + \let \FNLN@finish \FNLN@add +} +%% |\setfootnotelinenumbers| performs all the settings +%% for typesetting footnotes in line numbering mode +%% \emph{globally}, +%% including storing results from typesetting main text: +\newcommand* \setfootnotelinenumbers {% + \globaldefs\@ne +%% The previous line also renders `\setgetfootnotelinenumbers' global: + \setgetfootnotelinenumbers +%% |\theLineNumber| is used for `\linelabel' entries. +%% `\thePagewiseLineNumber' is replaced by +%% |\theFootnoteLineNumber|: + \let\theLineNumber\theFootnoteLineNumber +%% Logging to `.aux': + \def \FNLN@log {\string\@FLN}% +%% %% 2010/12/28: +%% Starting range search: |\NumberedPageCache| + \FNLN@foot@cache +%% Reusing 'lineno''s task list operations: + \GStoreUse \@LN@labellist \FNLN@@labels \FNLN@labels + \GStoreUse \@LN@vadjustlist \FNLN@@vadjusts \FNLN@vadjusts + \globaldefs\z@ +} +%% For switching back to ``main text mode," +%% again some settings may need a local variant---for +%% processing line references from footnotes to main text! +%% This is the purpose of |\setgetpagewiselinenumbers|: +\newcommand* \setgetpagewiselinenumbers {% + \let \FNLN@first@numbered \LN@Pfirst + \let \FNLN@finish \@gobbletwo +} +%% |\unsetfootnotelinenumbers| stores the ``current" +%% page with footnote lines and loads the ``most recent" +%% page with main text lines---and more ...: +\newcommand* \unsetfootnotelinenumbers {% + \gdef \FNLN@log {\string\@LN}% + \FNLN@main@cache +%% Task lists: %% 2010/12/28 + \GStoreUse \@LN@labellist \FNLN@labels \FNLN@@labels + \GStoreUse \@LN@vadjustlist \FNLN@vadjusts \FNLN@@vadjusts + \globaldefs\@ne \setgetpagewiselinenumbers \globaldefs\z@ %% v0.53 + \setpagewiselinenumbers +} +%% |\makeFootnoteLineNumber| actually only copies +%% |\makePagewiseLineNumber|, different results are obtained +%% be changing hooks. The command first calls +%% logging---|\logtheLineNumber|, +%% then generating the ``public" line number---|\getLineNumber| +%% (which in turn only is a copy of |\testNumberedPage| +%% in 'lineno.sty'). +\@ifdefinable\makeFootnoteLineNumber + {\let \makeFootnoteLineNumber \makePagewiseLineNumber} +%% +%% ==== Logging ==== +%% |\logtheLineNumber| is redefined to log both +%% main text and footnote line numbers. +\def \logtheLineNumber {% + \protected@write\@auxout{}{% + \FNLN@log{\the\c@linenumber}{\noexpand\the\c@LN@truepage}}} +%% |\FNLN@log| is the hook for the difference, +%% its default expansion |\@LN| is made for +%% \emph{main text} line numbers: +\gdef \FNLN@log {\string\@LN} +%% +%% ==== ``Public" Line Numbers ==== +%% Fortunately, these commands don't need to know much about +%% name spaces. The interfaces to them are +%% |\NumberedPageCache|---changing globally---and +%% |\FNLN@first@numbered|. Our +%% |\FNLN@cache| is initialized +%% by analogy to its counterpart `\NumberedPageCache' +%% (a minute name space change): +\def \FNLN@cache {\FLN@Pfirst} +%% |\testFirstNumberedPage{<integer>}| from 'lineno.sty' +%% is modified by replacing `\LN@Pfirst' only: +\renewcommand* \testFirstNumberedPage [1]{% + \ifnum#1>\c@linenumber + \def\nextLN##1{% + \testNextNumberedPage\FNLN@first@numbered}% + \else + \let\nextLN\@gobble + \def\pageLN{\gotNumberedPage{#1}}% + \fi} +%% |\testNumberedPage| and |\testNextNumberedPage| from 'lineno' +%% don't need any modification. |\testLastNumberedPage| +%% is modified in 'edfnotes.sty'. %% 2011/01/07 +%% +%% |\gotNumberedPage| just needs a closing hook +%% `\FNLN@finish' to allow for footnote lines. +\renewcommand* \gotNumberedPage [4]{% + \oddNumberedPagefalse + \ifodd \if@twocolumn #3\else #2\fi\relax\oddNumberedPagetrue\fi + \advance\c@linenumber\@ne + \ifcolumnwiselinenumbers + \subtractlinenumberoffset{#1}% + \else + \subtractlinenumberoffset{#4}% + \fi +% \show\FNLN@finish + \FNLN@finish{#2}{#3}% +} +%% |\FNLN@finish{<page>}{<column>}| gobbles both +%% arguments with \emph{main} text lines, +%% but will add the number of main text lines to +%% \emph{footnote} line numbers: +\global\let \FNLN@finish \@gobbletwo +%% Then it will act as |\FNLN@add|. We run the page info macro +%% for the same page (column; if defined). +\newcommand* \FNLN@add [2]{% + \expandafter \let\expandafter \@tempa\csname LN@P#1C#2\endcsname + \ifx\@tempa\relax + \else + \advance\c@linenumber\@ne + \ifcolumnwiselinenumbers + \let\firstLN\subtractlinenumberoffset +%% ... rather assuming `\realpagewiselinenumbers'. + \let\pageLN\@gobblethree + \else + \let\firstLN\@gobble + \def\pageLN##1##2##3{\subtractlinenumberoffset{##3}}% + \fi + \def\lastLN##1{\subtractlinenumberoffset{-##1}}% + \let\nextLN\@gobble +%% ... TODO all needed? + \@tempa + \fi +} +%% +%% ==== Referencing ==== +%% Now that we are using two separate counters for main text lines +%% and footnote lines (v0.5), correct references to footnote lines +%% using |\linelabel| and `\ref' need further adjustments. +%% % +%% 'lineno.sty''s `\thePagewiseLineNumber' +%% and `\getpagewiselinenumber{<integer>}' +%% are generalized and re-implemented +%% % by |\theWiseLineNumber| and |\getwiselinenumber| +%% by macros that then serve to implement +%% referring to footnote line numbers. +%% +%% |\theWiseLineNumber{<trans>}| leaves a `\protect'ed call +%% to a one-parameter macro <trans> in the `.aux' file: +\newcommand* \theWiseLineNumber [1]{\protect #1{\the\c@linenumber}} +%% |\getwiselinenumber{<choice>}{<integer>}| executes <choice> +%% before applying `\testNumberedPage' to <integer>---within +%% a local group: +\newcommand* \getwiselinenumber [2]{{% +%% Some wisdom is needed to take account of the current +%% ``numbering state" from which `\ref' was called. +%% \begin{description} +%% \item[Referring to main text line:]\leavevmode +%% \begin{itemize} +%% \item Unless called from numbered footnote, +%% no extra care is needed. +%% \item If called from numbered footnote, +%% `\setgetpagewiselinenumbers' +%% and temporary switching of `\NumberedPageCache' +%% is needed. +%% \end{itemize} +%% \item[Referring to footnote line:]\leavevmode +%% \begin{itemize} +%% \item If called from numbered footnote, +%% no extra care is needed. +%% \item Otherwise, `\setgetfootnotelinenumbers' +%% and temporary switching of `\NumberedPageCache' +%% is needed. +%% \end{itemize} +%% \end{description} + \ifx#1\relax %% to main text + \if@FNLN@sw@ %% from footnote + \setgetpagewiselinenumbers + \FNLN@main@cache + \let \FNLN@restore@cache \FNLN@foot@cache + \fi + \else %% to footnote + \if@FNLN@sw@ \else %% from elsewhere + #1% + \FNLN@foot@cache + \let \FNLN@restore@cache \FNLN@main@cache + \fi + \fi + \c@linenumber #2\relax\testNumberedPage + \thelinenumber + \FNLN@restore@cache +}} +\let \FNLN@restore@cache \relax +%% |\getpagewiselinenumber| doesn't need any <choice>---we +%% assume that the label was written in the default `pagewise' +%% mode (but it is difficult, though, `\relax' is essential!): +% \renewcommand* \getpagewiselinenumber {\getwiselinenumber\relax} %!! +%% 2010/12/31, a compatibility problem with 'ednotes'' `\newlabel' +%% mechanism shows up. 'ednotes' ``undefines" `\getpagewiselinenumber' +%% and restores it only `\AtBeginDocument'. We must ensure that +%% 'ednotes' will not override our new version of +%% `\getpagewiselinenumber'. +%% (TODO in my view another motivation to write ``ready" numbers +%% without `\getpagewiselinenumbers' directly.) +%% +%% We might assume that 'ednotes' (if at all) is loaded directly +%% and loads 'lineno.sty' +%% (that is the usual and recommended way of using 'ednotes') +%% and that this will happen before 'fnlineno.sty' is loaded. +%% But now that we have spent some time understanding the +%% situation, we can deal with the case as well that 'lineno.sty' +%% is loaded first, then 'fnlineno.sty' is loaded, and then 'ednotes'. +%% (I have assumed earlier that 'fnlineno.sty' is loaded after +%% 'lineno.sty' ...) +\AtBeginDocument{% + \def \getpagewiselinenumber {\getwiselinenumber\relax}% sic! + \let \@EN@getpagewiselno \getpagewiselinenumber} +%% For |\thePagewiseLineNumber|, <trans> is `\getpagewiselinenumber': +\renewcommand* \thePagewiseLineNumber {% + \theWiseLineNumber\getpagewiselinenumber} +%% |\getfootnotelinenumber{<integer>}| considers <integer> +%% the absolute number of a \emph{footnote} line. The <choice> +%% therefore is `\setgetfootnotelinenumbers': +\newcommand* \getfootnotelinenumber {% + \getwiselinenumber\setgetfootnotelinenumbers} +%% Finally, |\theFootnoteLineNumber| is how `\linelabel' +%% refers to a \emph{footnote} line. `\theWiseLineNumber' +%% is called with <trans> being `\getfootnotelinenumber': +\newcommand* \theFootnoteLineNumber {% + \theWiseLineNumber\getfootnotelinenumber} +%% +%% === Leaving the Package File === +\endinput +%% +%% == Acknowledgements == +%% %% 2010/12/19 +%% On the 'texhax' mailing list, Boris Veytsman recommended +%% using Victor \mbox{Eijk}\-hout's \textit{\TeX\ by Topic} to me, +%% and Andrej Lapshin pointed me to David Salomon's work +%% on output routines +%% (TUGboat 1990 and 1994, also available as a book, +%% as Ulrich Dirr tells me). +%% It helped me a lot to read about output routines +%% in these works, beyond the \TeX book. +%% The abbreviations \lq OTR\rq\ and \lq MVL\rq\ are +%% Salomon's.---And %% added 2010/12/27 +%% recall Christian's work and support +%% by the DFG named at the start of the package file.---And +%% ... the ideas of how to implement +%% (\textit i)~attaching line numbers, +%% (\textit{ii})~`\linelabel', and +%% (\textit{iii})~numbering lines ``pagewise"---so flexibly, +%% compatibly with many other \LaTeX\ packages, still +%% are Stephan's ... +%% +%% == VERSION HISTORY == +v0.1 2010/12/08 very first, \linelabel works in footnote + SENT TO Christian, problems with "long" footnotes + +v0.2 2010/12/08 corr. "manifoot" + 2010/12/09 moving doc. from .tex to here, + different doc. sectioning; + \@footnotetext modified (user feature!); + \@doclearpage NOT modified!; \if@FNLN@placing@ + 2010/12/10 ignore dummy footnote split; + \FNLNpar, \AutoPars, \ExplicitPars, + more on limitations + 2010/12/11 more trying, almost anew ... + JUST STORED + +v0.3 2010/12/12 new approach, removed much before proceeding + 2010/12/13 -- this was putting \box\footins onto MVL, + bad with those penalties + JUST STORED + +v0.4 2010/12/14 another new approach: + typeset footnote on MVL immediately -- + described strategy + 2010/12/15 ... continued, choice of hooking into \output + (...swap...) + 2010/12/16 ... continued; rearranged sections ... + \FNLN@@fntext vs. ...ltx... + 2010/12/17 success with \pagegoal ...; \GStoreReg etc.; + ...@fntext shortened + 2010/12/18 another two limitations: \pagebreak in fn., + guessed/tested; another note to <register>; + ack. Christian; directed -> organized!? + SENT TO Christian/Stephan + +v0.41 2010/12/19 support of \pagebreak with \if@FNLN@sw@ etc.; + TODO on lists of <register>s + 2010/12/20 debugging: \if...true; \setbox...ft; + \@finalstrut in vmode exported to finstrut.sty; + notes on how v0.41 still fails with \pagebreak + 2010/12/21 additional notes on *two* \pagebreak's + +v0.5 2010/12/21 restructuring doc., check@latex@ -> check@, + own account of lineno's pagewise mode + 2010/12/22 ... continued ... + 2010/12/23 ... continued ... + 2010/12/24 ... continued ... + 2010/12/25 moved this to pwlineno, replaced ... + more on \FNLN@typeset, + \setfootnotelinenumbers + 2010/12/26 new summary of implementation, + rearranged code sections; logging settled +v0.51 2010/12/27 "build" settled, typesetting, logging reformated; + ack.s: "recall"; all settings global, + "public" works + JUST STORED, MARGINAL NUMBERS OK, + \linelabel in footnote broken + [2010/12/28] +v0.52 2010/12/28 own label and vadjust lists for footnotes; + local settings for referencing, + tool and care for global changes (...Cache) + (TODO write ready in .aux? needs another run) + \linelabel's ok, MARGINAL NOTES MAIN BROKEN +v0.53 2010/12/28 debugging; OK; minor doc. modifications; + less "limitations"; \\[\smallskipamount] + TO CHRISTIAN 2010-12-29 +v0.54 2010/12/31 typo options; \FNLN@text without arg, + \getpagewiselinenumber with ednotes + 2011/01/01 \FNLN@cache, \FNLN@@cache initialized; + doc. "Typesetting Stage" qualification + 2011/01/02 that qualification was wrong + 2011/01/03 samepage@hook + TO CHRISTIAN SAME DAY +v0.55 2011/01/04 samepage@hook emptied here as well; + 2011/01/06 edited version history + 2011/01/07 note on \if@FNLN@sw@ with v0.5; + finally without support for samepage@hook! + note on \testLastNumberedPage + PART OF EDFN RELEASE r0.5 (together with edfnotes v0.2) +v0.55a 2011/02/09 corr. owner; "Limitations" updated; \pagebreak diff --git a/doc/LaTex/iopams.sty b/doc/LaTex/iopams.sty new file mode 100644 index 0000000000000000000000000000000000000000..044dde929745d48d13601b572a0f586728ebf0a4 --- /dev/null +++ b/doc/LaTex/iopams.sty @@ -0,0 +1,87 @@ +%% +%% This is file `iopams.sty' +%% File to include AMS fonts and extra definitions for bold greek +%% characters for use with iopart.cls +%% +\NeedsTeXFormat{LaTeX2e} +\ProvidesPackage{iopams}[1997/02/13 v1.0] +\RequirePackage{amsgen}[1995/01/01] +\RequirePackage{amsfonts}[1995/01/01] +\RequirePackage{amssymb}[1995/01/01] +\RequirePackage{amsbsy}[1995/01/01] +% +\iopamstrue % \newif\ifiopams in iopart.cls & iopbk2e.cls +% % allows optional text to be in author guidelines +% +% Bold lower case Greek letters +% +\newcommand{\balpha}{\boldsymbol{\alpha}} +\newcommand{\bbeta}{\boldsymbol{\beta}} +\newcommand{\bgamma}{\boldsymbol{\gamma}} +\newcommand{\bdelta}{\boldsymbol{\delta}} +\newcommand{\bepsilon}{\boldsymbol{\epsilon}} +\newcommand{\bzeta}{\boldsymbol{\zeta}} +\newcommand{\bfeta}{\boldsymbol{\eta}} +\newcommand{\btheta}{\boldsymbol{\theta}} +\newcommand{\biota}{\boldsymbol{\iota}} +\newcommand{\bkappa}{\boldsymbol{\kappa}} +\newcommand{\blambda}{\boldsymbol{\lambda}} +\newcommand{\bmu}{\boldsymbol{\mu}} +\newcommand{\bnu}{\boldsymbol{\nu}} +\newcommand{\bxi}{\boldsymbol{\xi}} +\newcommand{\bpi}{\boldsymbol{\pi}} +\newcommand{\brho}{\boldsymbol{\rho}} +\newcommand{\bsigma}{\boldsymbol{\sigma}} +\newcommand{\btau}{\boldsymbol{\tau}} +\newcommand{\bupsilon}{\boldsymbol{\upsilon}} +\newcommand{\bphi}{\boldsymbol{\phi}} +\newcommand{\bchi}{\boldsymbol{\chi}} +\newcommand{\bpsi}{\boldsymbol{\psi}} +\newcommand{\bomega}{\boldsymbol{\omega}} +\newcommand{\bvarepsilon}{\boldsymbol{\varepsilon}} +\newcommand{\bvartheta}{\boldsymbol{\vartheta}} +\newcommand{\bvaromega}{\boldsymbol{\varomega}} +\newcommand{\bvarrho}{\boldsymbol{\varrho}} +\newcommand{\bvarzeta}{\boldsymbol{\varsigma}} %NB really sigma +\newcommand{\bvarsigma}{\boldsymbol{\varsigma}} +\newcommand{\bvarphi}{\boldsymbol{\varphi}} +% +% Bold upright capital Greek letters +% +\newcommand{\bGamma}{\boldsymbol{\Gamma}} +\newcommand{\bDelta}{\boldsymbol{\Delta}} +\newcommand{\bTheta}{\boldsymbol{\Theta}} +\newcommand{\bLambda}{\boldsymbol{\Lambda}} +\newcommand{\bXi}{\boldsymbol{\Xi}} +\newcommand{\bPi}{\boldsymbol{\Pi}} +\newcommand{\bSigma}{\boldsymbol{\Sigma}} +\newcommand{\bUpsilon}{\boldsymbol{\Upsilon}} +\newcommand{\bPhi}{\boldsymbol{\Phi}} +\newcommand{\bPsi}{\boldsymbol{\Psi}} +\newcommand{\bOmega}{\boldsymbol{\Omega}} +% +% Bold versions of miscellaneous symbols +% +\newcommand{\bpartial}{\boldsymbol{\partial}} +\newcommand{\bell}{\boldsymbol{\ell}} +\newcommand{\bimath}{\boldsymbol{\imath}} +\newcommand{\bjmath}{\boldsymbol{\jmath}} +\newcommand{\binfty}{\boldsymbol{\infty}} +\newcommand{\bnabla}{\boldsymbol{\nabla}} +\newcommand{\bdot}{\boldsymbol{\cdot}} +% +% Symbols for caption +% +\renewcommand{\opensquare}{\mbox{$\square$}} +\renewcommand{\opentriangle}{\mbox{$\vartriangle$}} +\renewcommand{\opentriangledown}{\mbox{$\triangledown$}} +\renewcommand{\opendiamond}{\mbox{$\lozenge$}} +\renewcommand{\fullsquare}{\mbox{$\blacksquare$}} +\newcommand{\fulldiamond}{\mbox{$\blacklozenge$}} +\newcommand{\fullstar}{\mbox{$\bigstar$}} +\newcommand{\fulltriangle}{\mbox{$\blacktriangle$}} +\newcommand{\fulltriangledown}{\mbox{$\blacktriangledown$}} + +\endinput +%% +%% End of file `iopams.sty'. diff --git a/doc/LaTex/lineno.sty b/doc/LaTex/lineno.sty new file mode 100644 index 0000000000000000000000000000000000000000..53a7b5242abe2a7a7b8e8ad83a9dc2a935442bc7 --- /dev/null +++ b/doc/LaTex/lineno.sty @@ -0,0 +1,3484 @@ + \iffalse; awk '/S[H]ELL1/' lineno.sty|sh;exit; + ... see bottom for .tex documentation ... + +Macro file lineno.sty for LaTeX: attach line numbers, refer to them. + \fi +\def\fileversion{v4.41} \def\filedate{2005/11/02} %VERSION + +%%% Copyright 1995--2003 Stephan I. B"ottcher <boettcher@physik.uni-kiel.de>; +%%% Copyright 2002--2005 Uwe L"uck, http://www.contact-ednotes.sty.de.vu +%%% for version 4 and code from former Ednotes bundle +%%% --author-maintained. +%%% +%%% This file can be redistributed and/or modified under +%%% the terms of the LaTeX Project Public License; either +%%% version 1.3a of the License, or any later version. +%%% The latest version of this license is in +%%% http://www.latex-project.org/lppl.txt +%%% We did our best to help you, but there is NO WARRANTY. +% +%%% $Id: lineno.sty,v 3.14.2.2 2004/09/13 19:30:39 stephan Exp $ %% was v4.00. +% \title{\texttt{\itshape +%% %% (UL 2004/10/09:) Italic TT is evil +%% %% ... or nice front page layout!? +%% +% lineno.sty \ \fileversion\ \filedate +% \unskip}\\\ \\ +% A \LaTeX\ package to attach +% \\ line numbers to paragraphs +% \unskip}\author{% +% Stephan I. B\"ottcher +% \\ Uwe L\"uck +% \unskip}\date{% +% boettcher@physik.uni-kiel.de +% \\ http://contact-ednotes.sty.de.vu +%% \\ stephan@nevis.columbia.edu +%% \\ Stephan.Boettcher@cern.ch +% \\} +% +% \documentclass[a4paper,12pt]{article}%D +% \usepackage{lineno}%D +%% %% (New v4.00) +% \catcode`\_\active\let_~ +%% %% Beware math!? (/New v4.00) +% \def~{\verb~} +% \let\lessthan< +% \catcode`\<\active +% \def<#1>{$\langle${\itshape#1}\/$\rangle$} +% \catcode`\|\active +%% (New v4.1: \tt star; in box anyway.) +% \def|#1{\ttfamily\string#1} +%% \def|#1{{\ttfamily\string#1}} +%% (/New v4.1) +% \newenvironment{code} +% {\par\runninglinenumbers +% \modulolinenumbers[1]% +% \linenumbersep.3em +% \footnotesize +% \def\linenumberfont +% {\normalfont\tiny\itshape}} +% {} +%% %% (New v4.00) +% {\makeatletter \gdef\scs#1{\texttt +% {\protect\@backslashchar#1}}} +% \def\old{\par\footnotesize} +%% %% (/New v4.00) +%% %% (New v4.1) +% {\catcode`\/\active +% \gdef\path{\begingroup\catcode`\/\active +% \let/\slash\dopath} +% \gdef\dopath#1{\slash\unpenalty#1\endgroup}} +%% %% (/New v4.1) +% +% \begin{document}%D +%% \DocInput{lineno}%D +% \pagewiselinenumbers +% \maketitle +% \pagestyle{headings} +% \tableofcontents +% \sloppy +% +%% %% New v4.00: `...section{%' + \unskip +% \section{% +% Introductions +%% %% New v4.00: `s' +% \unskip} +% +% (New v4.00) Parts of former first section +% have been rendered separate subsections for package +% version_v4.00. (/New v4.00) +% +% \subsection{% +% Introduction to versions $\textrm{v}\lessthan4$ +% \unskip} +% +% This package provides line numbers on paragraphs. +% After \TeX\ has broken a paragraph into lines there will +% be line numbers attached to them, with the possibility to +% make references through the \LaTeX\ ~\ref~, ~\pageref~ +% cross reference mechanism. This includes four issues: +% \begin{itemize} +% \item attach a line number on each line, +% \item create references to a line number, +% \item control line numbering mode, +% \item count the lines and print the numbers. +% \end{itemize} +% The first two points are implemented through patches to +% the output routine. The third by redefining ~\par~, ~\@par~ +% and ~\@@par~. The counting is easy, as long as you want +% the line numbers run through the text. If they shall +% start over at the top of each page, the aux-file as well +% as \TeX s memory have to carry a load for each counted line. +% +% I wrote this package for my wife Petra, who needs it for +% transcriptions of interviews. This allows her to +% precisely refer to passages in the text. It works well +% together with ~\marginpar~s, but not too well with displaymath. +% ~\footnote~s are a problem, especially when they +% are split, but we may get there. +% (New v4.00 UL) Version v4.00 overcomes the problem, I believe. +% (/UL /New v4.00) +% +% lineno.sty works +% surprisingly well with other packages, for +% example, ~wrapfig.sty~. So please try if it +% works with whatever you need, and if it does, +% please tell me, and if it does not, tell me as +% well, so I can try to fix it. +% +% \subsection{% +% Introduction to versions v4.00ff. (UL) +% \unskip} +% +% ~lineno.sty~ has been maintained by Stephan until version_v3.14. +% From version_v4.00 onwards, maintenance is shifting towards +% Uwe L\"uck (UL), who is the author of v4\dots code and of v4\dots +% changes in documentation. This came about as follows. +% +% Since late 2002, Christian Tapp and Uwe L\"uck have employed +% ~lineno.sty~ for their ~ednotes.sty~, a package supporting +% critical editions---cf. +% \[\mbox{\tt +% http://ednotes.sty.de.vu +% \unskip}\] +% ---while you find ~ednotes.sty~ and surrounding files in +% CTAN folder \path{macros/latex/contrib/ednotes}. +% +% Soon, some weaknesses of ~lineno.sty~ showed up, mainly since +% Christian's critical editions (using ~ednotes.sty~) needed lots +% of ~\linelabel~s and footnotes. (These weaknesses are due to +% weaknesses of \LaTeX's ~\marginpar~ mechanism that Stephan +% used for ~\linelabel~.) So we changed some ~lineno.sty~ +% definitions in some extra files, which moreover offered new +% features. We sent these files to Stephan, hoping he would take +% the changes into ~lineno.sty~. However, he was too short of time. +% +% Writing a TUGboat article on Ednotes in 2004, we hoped to +% reduce the number of files in the Ednotes bundle and so asked +% Stephan again. Now he generously offered maintenance to me, so +% I could execute the changes on my own. +% +% The improvements are as follows: +% \begin{itemize}\item +% [(i)] Footnotes placement approaches intentions better +% (footnotes formerly liked to pile up at late pages). +% \item +% [(ii)] The number of ~\linelabel~s in one paragraph is no longer +% limited to 18. +% \item +% [(iii)] ~\pagebreak~, ~\nopagebreak~, ~\vspace~, and the star +% and optional versions of ~\\~ work as one would expect +% (section_\ref{s:MVadj}). %% Added for v4.1 +% \item +% [(iv)] A command is offered which chooses the first line number +% to be printed in the margin +% (subsection_\ref{ss:Mod}). %% Added for v4.1 +% \item +% [(v)] (New v4.1) \LaTeX\ tabular environments (optionally) +% get line numbers as well, and you can refer to them in the +% usual automatic way. (It may be considered a shortcoming that, +% precisely, \emph{rows} are numbered, not lines.---See +% subsection_\ref{ss:Tab}.) +% \item +% [(vi)] We are moving towards referring to math items +% (subsection_\ref{ss:MathRef} and the hooks in +% subsection_\ref{ss:LL}). +% (/New v4.1) +% \end{itemize} +% (Thanks to Stephan for making this possible!) +% +%% Unpublish: +%% You may trace the earlier developments of these changes by +%% requesting our files ~linenox0.sty~, ~linenox1.sty~, and +%% ~lnopatch.sty~. Most of our changes have been in ~linenox0.sty~. +%% Our ~linenox1.sty~ has extended ~linenox0.sty~ for one single +%% purpose in a not very stable way. +%%% (See ~\linenumberpar~ below). +%% ~lnopatch.sty~ has done the first line number thing referred +%% to in case_(iv) up to now. +%% (New v4.1) +%% Case_(v) earlier was provided by our ~edtab02.sty~---now +%% called ~edtable.sty~. +%% (/New v4.1) +% +% Ednotes moreover profits from Stephan's offer with regard +% to the documentation of our code which yielded these +% improvements formerly. This documentation now becomes +% printable, being part of the ~lineno.sty~ documentation. +% +% Of course, Stephan's previous ~lineno.sty~ versions were a great +% and ingenious work and exhibit greatest \TeX pertise. I never +% could have done this. I learnt a lot in studying the code when +% Christian pointed out strange output results and error +% messages, and there are still large portions of ~lineno.sty~ +% which I don't understand (consider only pagewise numbering of +% lines). Fortunately, Stephan has offered future help if +% needed.---My code for attaching line numbers to \emph{tabular +% environments} (as mentioned above, now still in +% ~edtable.sty~) %% %% TODO +% developed from macros which Stephan and Christian experimented +% with in December 2002. Stephan built the basics. +% (However, I then became too proud to follow his advice only to +% use and modify ~longtable.sty~.) +% +% There are some issues concerning use of counters on which I +% don't agree with Stephan and where I would like to change the +% code if ~lineno.sty~ is ``mine'' as Stephan offered. However, +% Stephan is afraid of compatibility problems from which, in +% particular, his wife could suffer in the near future. So he +% demanded that I change as little as possible for my first +% version. Instead of executing changes that I plan I just offer +% my opinions at the single occasions. I hope to get in touch +% this way with users who consider subtle features vital which I +% consider strange. +% +% On the other hand, the sections on improvements of the +% implementation have been blown up very much and may be tiring +% and litte understandable for mere \emph{users}. These users +% may profit from the present presentation just by jumping to +% sections_\ref{s:Opts} and_\ref{s:UserCmds}. There is a user's +% guide ulineno.tex which may be even more helpful, but it has +% not been updated for a while. %% TODO +% +% \subsection{% +% Availability +% \unskip} +% +% In case you have found the present file otherwise than from +% CTAN: A recent version and documentation of this package +% should be available from CTAN folder +% \path{macros/latex/contrib/lineno}. +% Or mail to one of the addresses at top of file. +% +% \subsection{% +% Introductory code +% \unskip} +% +% This style option is written for \LaTeXe, November 1994 or later, +% since we need the ~\protected@write~ macro. +% +% (New v4.00) And we use ~\newcommand*~ for +% controlling length of user macro arguments, which has been +% available since December 1994. +%% + +\NeedsTeXFormat{LaTeX2e}[1994/12/01] +%% [1994/11/04] +\ProvidesPackage{lineno} + [\filedate\space line numbers on paragraphs \fileversion] +% (/New v4.00) +%% +%% History of versions: +%% v1.00 1995/03/31 SIB: first release for Petra's interview transcriptions +%% v1.01 1995/10/28 SIB: added ~pagewise~ mode +%% v1.02 1995/11/15 SIB: added ~modulo~ option +%% v1.03 1995/12/05 SIB: pagewise: try to reduce the hash-size requirements +%% v2.00 1995/12/06 SIB: .. it works, new user interface +%% v2.01 1996/09/17 SIB: put into CVS +%% v2.02 1997/03/17 SIB: add: \@reinserts, for footnotes +%% v2.04 1998/03/09 SIB: add: linenomath environment +%% v2.05 1998/04/26 SIB: add: prevgraf test +%% v2.06 1999/03/02 SIB: LPPL added +%% v3.00 1999/06/11 SiB: include the extension in the main file +%% v3.01 1999/08/28 SiB: \@reinserts -> \holdinginserts +%% v3.02 2000/03/10 SiB: \@LN@output +%% v3.03 2000/07/01 SiB: \@LN@ExtraLabelItems, hyperref +%% v3.04 2000/12/17 SiB: longtable compatibility. +%% v3.05 2001/01/02 SiB: [fleqn] detection. +%% v3.05a 2001/01/04 SiB: [fleqn] detection reverted for eqnarray. +%% v3.06 2001/01/17 SiB: [twocolumn] mode support. +%% v3.07 2001/07/30 SiB: [hyperref] option obsoleted. +%% v3.08 2001/08/02 SiB: linenomath wrapping for \[ \] +%% v3.08a 2001/08/04 SiB: linenomath wrapping for \[ \] fixed +%% v3.08b 2002/01/27 SiB: enquotation typo fix +%% v3.09 2003/01/14 SIB: hyperref detection fix +%% v3.10 2003/04/15 FMi: \MakeLineNo fix for deep boxes +%% v3.10a 2003/11/12 Uwe Lück: \lineref typo fix +%% v4.00 2004/09/02 UL: included linenox0, linenox1, lnopatch code with +%% documentation, usually indicated by `New v4.00'; +%% discussions of old code, indicated by `UL'; +%% LPPL v.1 -> LPPL v1.3, `program' -> `file'; +%% first lines with \filedate and \fileversion, +%% according nawk lines; `November 1994 or later', +%% some earlier documentation typos (including a few +%% bad minus signs), { -> {% and } -> \unskip} at +%% line ends (so, e.g., alignment in TOC works); \scs. +%% 2004/09/03 UL: removed everything which indicated that the +%% present file were named `lineno4.sty'. +%% v4.1 2004/09/19 UL: Inserted Stephan's identification line, removed +%% some TODOs and remarks from v4.00. +%% 2004/10/04 UL: Added acknowledgement for Daniel Doherty; +%% `(New v4.00)' with [|\firstlinenumber]; changed +%% TODOs; Refining -> Redefining (\vadjust). +%% 2004/10/05 UL: ednmath0 -> mathrefs; \catcode`\~ -> \active; +%% \path; refined section on options `mathrefs'; +%% changes in introduction. +%% 2004/10/06 UL: Changed/removed TODOs, e.g., for edtable.sty. +%% 2004/10/11 UL: Reminders: linenox0/1/lnopatch.sty obsolete; +%% \tt star in list of commands. +%% 2004/10/12 UL: Corrected blank lines in lineno.tex. +%% 2004/10/19 UL: Fixed minor typos; remark on \if@LN@edtable. +%% v4.1a 2004/11/07 UL: LPPL v1.3a. +%% v4.1b 2004/11/13 UL: Comment on \outputpenalty values. +%% v4.1c 2005/01/10 UL: Contact via http. +%% v4.11 2005/02/20 UL: Error message with \linelabel when not numbering. +%% 2005/03/07 UL: Removed \linelabel from ss:Tab heading, consider +%% marginal line numbers as well, revised ss:Tab. +%% Added a few lines on missing explanations to +%% s:UserCmds. Corrected some code alignments. +%% 2005/03/08 UL: Require recent edtable.sty. +%% + +%% v4.2 2005/03/21 UL: "Physical page" counter works with \include. +%% 2005/04/17 UL: Raised options section above extensions section +%% (v4.00 disabled `displaymath' option); +%% third arg for \@ifundefined{mathindent}; +%% "bunch of options"; +%% 2005/04/24 UL: compatibility with tamefloats; vplref.sty. +%% 2005/04/25 UL: \number -> \the; wondered -> $$; subsec. appbas; +%% CrtlLN sec -> subsec.; \newcommand* wherever ...; +%% doc. on `other output routines' and `addpageno' +%% (this changed from `varioref'). +%% 2005/04/27 UL: =1\relax -> =\@ne, 0\relax ..., \hb@xt@, +%% \ifx\@@par\@@@par -> \ifLineNumbers, typos, +%% \pagestyle{headings}, LaTeX -> \LaTeX. +%% v4.21 2005/04/28 UL: linenomath section: removed wrong \else's, +%% \holding...: \thr@@, \@LN@outer@holdins, \global. +%% v4.22 2005/05/01 UL: \unvbox\@outputbox; \@LN@col without #1, +%% 2005/05/08 UL: global/local \internall..., \resetl... global, +%% shortened discussions of this and of \newcounter. +%% 2005/05/09 UL: corr.: doc. typo, version history, bad lines; +%% percent; \chardef for modulo, +%% \value{firstlinenumber}. +%% v4.3 2005/05/10 UL: \@backslashchar -> \char`\\ in \scs. +%% 2005/05/11 UL: \linenumbers sets ...outer@holdins; tidied up +%% documentation regarding earlier versions. +%% 2005/05/12 UL: `linenomath' without spurious number above; +%% `displaymath' default; edmac homepage -> +%% ednotes.sty.de.vu, \endlinenomath without +%% numbers: no change of \holdinginserts; +%% \linelabel doesn't go to .aux or mark, +%% hyperref detected; undone 2005/05/10 (bad mark). +%% 2005/05/13 UL: Reworked hyperref detection (new subsec.). +%% 2005/05/15 UL: More typo fixes, corrected terrible confusions in +%% the discussion (v4.22/v4.3) of \new/\stepcounter; +%% new subsec. in `Line number ...'; another +%% implementation of `hyperref' detection. +%% 2005/05/16 UL: Final minor changes. +%% v4.31b /06/14 UL: Extended explanation of \firstlinenumbers +%% and package options; \@LN@ifgreat@critical; +%% \modulolinenumbers*. Sent to Ednotes.news only. +%% v4.31 2005/06/15 UL: \modulolinenumbers* with \firstlinenumber{1}; +%% " -> ``/''; more doc. on \firstlinenumber . +%% 2005/06/20 UL: Typo fix. +%% 2005/10/01 UL: Warning about \mod...* with pagewise mode. +%% v4.31a /10/02 UL: Minor changes of appearance of doc., e.g., +%% \[ for $$. +%% v4.32b /10/15 UL: Support for \addvspace; removed comments that +%% had been invisible already for some time; +%% made clear with which environments the +%% linenomath environment is not needed. +%% v4.32ab /10/15 UL: Observe \if@nobreak with support for \addvspace. +%% v4.32 2005/10/17 UL: Just made it official and sent it to CTAN. +%% v4.33b /10/23 UL: \if@nobreak\nobreak\fi -> \nobreak . +%% v4.33ab /10/24 UL: \LineNoLaTeXOutput without \@tempswafalse; +%% undid v4.22: \[unv]box\@outputbox (space is OK, +%% \unvbox pushes short columns down); \@LN@kern@z@ . +%% v4.4b 2005/10/24 UL: Another tidying-up of the discussion of +%% \stepcounter{linenumber}; \@LN@screenoff@pen +%% replaces \@LN@kern@z@, \@LN@depthbox . +%% v4.4 2005/10/27 UL: Just made official for CTAN. +%% v4.4a 2005/10/29 UL: Undid change of discussion of +%% \stepcounter{linenumber} (confusion again). +%% v4.41 2005/11/02 UL: Raised \CheckCommand*. +%% +%% Acknowledgements: +%% v3.06: Donald Arseneau, pointed to mparhack.sty. +%% v3.07+: Frank Mittelbach, points out inconsistencies in the +%% user interface. +%% v3.10: Frank Mittelbach \MakeLineNo fix for deep boxes +%% v4.00: Daniel Doherty points out clash of \pagewise... with resetting +%% page number. +%% v4.21: Much testing work by Erik Luijten. +%% v4.3: `displaymath' default by Erik Luijten's suggestion. +%% v4.31: \modulolinenumbers* is an idea of Hillel Chayim Yisraeli's. +%% v4.32: Support for \addvspace due to Saravanan M.'s observation. +%% v4.33: Different support for \addvspace due to bug reports by +%% Saravanan M.'s and David Josef Dev. +%% v4.4: David Josef Dev points out that \kern\z@ after a paragraph +%% tends to place its final baseline wrongly. +% +% +% \section{% +% Put the line numbers to the lines +% \unskip} +% +% (New v4.00) This section contained the most +% basic package code previously. For various purposes of +% version_4\dots, much of these basics have been to be modified. +% Much of my (UL's) reasoning on these modifications has been to +% be reported. Sorry, the present section has been blown up +% awfully thus and contains ramifications that may be difficult +% to trace. We add some ~\subsection~ commands in order to cope +% with the new situation. (/New v4.00) +% +% \subsection{% +% Basic code of \texttt{lineno.sty} \scs{output} +% \unskip}\label{ss:output} +% +% The line numbers have to be attached by the output +% routine. We simply set the ~\interlinepenalty~ to $-100000$. +% The output routine will be called after each line in the +% paragraph, except the last, where we trigger by ~\par~. +% The ~\linenopenalty~ is small enough to compensate a bunch of +% penalties (e.g., with ~\samepage~). +% +% (New v3.04) Longtable uses +% ~\penalty~$-30000$. The lineno penalty range was +% shrunk to $-188000 \dots -32000$. (/New v3.04) +% (New v4.00) New values are listed below (11111f.). (/New v4.00) + +\newcount\linenopenalty\linenopenalty=-100000 + +%% TODO v4.4+: +% (UL) Hm. It is never needed below +% that this is a counter. ~\def\linenopenalty{-100000\relax}~ +% would do. (I guess this consumes more memory, but it +% is more important to save counters than to save memory.) +% I was frightened by ~-\linenopenalty~ below, but indeed +% \TeX\ interprets the string ~--100000~ as 100000. +% Has any user or extension package writer ever called +% ~\linenopenalty=xxx~, or could I really change this?---The +% counter is somewhat faster than the macro. Together with the +% compatibility question this seems to support keeping the +% counter. (???) +%% Note that Stephan chose ~\mathchardef~ below, +%% so his choice above seems to have been deliberate. +%% <- no point, \mathchardef token is fast. +% (/UL) + +\mathchardef\linenopenaltypar=32000 + +% So let's make a hook to ~\output~, the direct way. The \LaTeX\ +% macro ~\@reinserts~ puts the footnotes back on the page. +% +% (New v3.01) ~\@reinserts~ badly +% screws up split footnotes. The bottom part is +% still on the recent contributions list, and the +% top part will be put back there after the bottom +% part. Thus, since lineno.sty does not play well +% with ~\inserts~ anyway, we can safely experiment +% with ~\holdinginserts~, without making things +% much worse. +% +% Or that's what I thought, but: Just activating +% ~\holdinginserts~ while doing the ~\par~ will +% not do the trick: The ~\output~ routine may be +% called for a real page break before all line +% numbers are done, and how can we get control +% over ~\holdinginserts~ at that point? +% +% Let's try this: When the ~\output~ routine is +% run with ~\holdinginserts=3~ for a real page +% break, then we reset ~\holdinginserts~ and +% restart ~\output~. +% +% Then, again, how do we keep the remaining +% ~\inserts~ while doing further line numbers? +% +% If we find ~\holdinginserts~=$-3$ we activate it again +% after doing ~\output~. (/New v3.01) +% +% (New v3.02) To work with +% multicol.sty, the original output routine is now +% called indirectly, instead of being replaced. +% When multicol.sty changes ~\output~, it is a +% toks register, not the real thing. (/New v3.02) +% +% (New v4.00) Two further complications are added. +%% +%% TODO v4.3+: Or three, ~\@nobreakfalse~ after ~\MakeLineNo~ +%% for getting rid of ~\@LN@nopagebreak~. +% \begin{itemize}\item +% [(i)] Problems with footnotes formerly resulted from +% \LaTeX's ~\@reinserts~ in ~\@specialoutput~ which Stephan's +% ~\linelabel~ called via the ~\marginpar~ mechanism. +% \item +% [(ii)] \LaTeX\ commands using ~\vadjust~ formerly didn't work +% as one would have hoped. The problem is as follows: +% Printing the line number results from +% a box that the output routine inserts at the place of the +% ~\interlinepenalty~. ~\vadjust~ items appear \emph{above} the +% ~\interlinepenalty~ (\TeX book p._105). So ~\pagebreak~, e.g., +% formerly sent the line number to the next page, while the +% penalty from ~\nopagebreak~ could not tie the following line, +% since it was screened off by the line number box.---Our trick +% is putting the ~\vadjust~ items into a list macro from which +% the output routine transfers them into the vertical list, +% below the line number box. +% \end{itemize} +% In this case_(ii), like in case_(i), footnotes would suffer +% if ~\holdinginserts~ were non-positive. Indeed, in both +% cases_(i) and_(ii) we tackle the footnote problem by extending +% that part of Stephan's output routine that is active when +% ~\holdinginserts~ is positive. This extension writes the line +% number ~\newlabel~ to the .aux file (which was formerly done +% under $~\holdinginserts~=-3$) and handles the ~\vadjust~ +% items.---To trigger ~\output~ and its ~\linelabel~ or, resp., +% ~\vadjust~ part, the list of signal penalties started +% immediately before is increased here (first for ~\linelabel~, +% second for postponed ~\vadjust~ items): + +\mathchardef\@Mllbcodepen=11111 +\mathchardef\@Mppvacodepen=11112 + +% (/New v4.00) (New v4.2) David Kastrup urges to use a private +% name instead of ~\the\output~ (LaTeX-L-list). Otherwise an +% ~\output~ routine loaded later and using ~\newtoks\output~ +% again may get lost entirely. So we change use of ~\@LN@output~, +% using it for the former purpose. Reference to what appeared +% with the name of ~\output~ here lasts for a few lines and then +% is given away. + +\let\@tempa\output +\newtoks\output +\let\@LN@output\output +\output=\expandafter{\the\@tempa} + +% Now we add two cases to Stephan's output routine. (New v4.00) + +\@tempa={% +% (/New 4.2) + \LineNoTest + \if@tempswa +%% +%% (UL) Learnt that even in def.s blank line means ~\par~. +%% to leave visual space in present file with having a +%% blank line neither in present nor in .tex file, +%% use double comment mark (`%%'). (/UL) +%% +% (New v4.00) +% We insert recognition of waiting ~\linelabel~ items--- +%% + \ifnum\outputpenalty=-\@Mllbcodepen + \WriteLineNo +%% +% ---and of waiting ~\vadjust~ items: +%% + \else + \ifnum\outputpenalty=-\@Mppvacodepen + \PassVadjustList + \else +%% +%% Now we give control back to Stephan. +% (/New v4.00) (New v4.2) Outsource ``Standard'' output +% ---which occurs so rarely---to subsection_\ref{ss:LLO}: +%% + \LineNoLaTeXOutput +% (/New v4.2) (New v4.00) +% Two new ~\fi~s for the ~\linelabel~ and ~\vadjust~ tests--- +%% + \fi + \fi +%% +% ---and the remaining is +%%%next three lines are +% Stephan's code again: +% (/New v4.00) +%% + \else + \MakeLineNo + \fi + } + +% (New v4.00) Our new macros +% ~\WriteLineNo~ and ~\PassVadjustList~ will be dealt with in +% sections_\ref{s:LNref} and_\ref{ss:PVadj}. (/New v4.00) +% +% \subsection{% +% \scs{LineNoTest} +% \unskip} +% +% The float mechanism inserts ~\interlinepenalty~s during +% ~\output~. So carefully reset it before going on. Else +% we get doubled line numbers on every float placed in +% horizontal mode, e.g, from ~\linelabel~. +% +% Sorry, neither a ~\linelabel~ nor a ~\marginpar~ should +% insert a penalty, else the following linenumber +% could go to the next page. Nor should any other +% float. So let us suppress the ~\interlinepenalty~ +% altogether with the ~\@nobreak~ switch. +% +% Since (ltspace.dtx, v1.2p)[1996/07/26], the ~\@nobreaktrue~ does +% it's job globally. We need to do it locally here. + +\def\LineNoTest{% + \let\@@par\@@@par + \ifnum\interlinepenalty<-\linenopenaltypar + \advance\interlinepenalty-\linenopenalty + \@LN@nobreaktrue + \fi + \@tempswatrue + \ifnum\outputpenalty>-\linenopenaltypar\else + \ifnum\outputpenalty>-188000\relax + \@tempswafalse + \fi + \fi + } + +\def\@LN@nobreaktrue{\let\if@nobreak\iftrue} % renamed v4.33 + +% (UL) I thought here were +% another case of the save stack problem explained in \TeX book, +% p._301, namely through both local and global changing +% ~\if@nobreak~. However, ~\@LN@nobreak~ is called during +% ~\@LN@output~ only, while ~\@nobreaktrue~ is called by \LaTeX's +% ~\@startsection~ only. The latter never happens during +% ~\@LN@output~. So there is no local value of ~\if@nobreak~ on +% save stack when ~\@nobreaktrue~ acts, since ~\the\@LN@output~ +% (where ~\@LN@output~ is a new name for the original ~\output~) +% is executed within a group (\TeX book p._21). +%% +%% 2004/09/19 Removed nonsense here according to Stephan 2004/09/04. +%% +% (/UL) +% +% \subsection{% +% Other output routines (v4.2) +% \unskip}\label{ss:LLO} +% +% I had thought of dealing with bad interference of footnotes +% (and ~\enlargethispage~) with (real) ~\marginpar~s and floats +% \emph{here}. Yet this is done in +% \[ +% ~http://~\mbox{[CTAN]} +% ~/macros/latex/contrib/tamefloats/tameflts.sty~ +% \] +% now, and I prefer striving for compatibility with the latter. +% (See there for expanding on the problem.) +% This requires returning the special absolute value of +% ~\holdinginserts~ that ~lineno.sty~ finds at the end of a newly +% typeset paragraph---now done in subsection_\ref{ss:calls} +% (~\linenumberpar~). +% The former ~\LineNoHoldInsertsTest~ has been filled into here. +%% ---`3' is replaced by ~\thr@@~ for a while. ~\thr@@~ is +%% useful practice since plain \TeX, but Stephan may have been +%% wise in suspecting that \LaTeX\ once could forsake ~\thr@@~. +%% The same holds for ~\@M=10000~. +% Note: when the following code is invoked, we have +% ~\if@tempswa~_ =_~\iftrue~. +% WARNING: I am still not sure whether the present code is good +% for cooperating with other packages that use ~\holdinginserts~. + +\def\LineNoLaTeXOutput{% + \ifnum \holdinginserts=\thr@@ % v4.33 without \@tempswafalse + \global\holdinginserts-\thr@@ + \unvbox\@cclv + \ifnum \outputpenalty=\@M \else \penalty\outputpenalty \fi + \else + \if@twocolumn \let\@makecol\@LN@makecol \fi + \the\@LN@output % finally following David Kastrup's advice. + \ifnum \holdinginserts=-\thr@@ + \global\holdinginserts\thr@@ \fi + \fi +} + +% \textit{More on dealing with output routines from other +% packages:} +% Since ~lineno.sty~'s output routine is called at least once +% for each output line, I think it should be in \TeX's +% original ~\output~, while output routines dealing with +% building pages and with floats etc.\ should be filled into +% registers addressed by ~\output~ after ~\newtoks\output~. +% Therefore \begin{enumerate} +% \item +% ~tameflts.sty~ should be loaded \emph{after} ~lineno.sty~; +% \item +% if a class changes ~\output~ (APS journal class revtex4, +% e.g.), ~lineno.sty~ should be loaded by ~\RequirePackage~ +% [here presumably following some options in +% brackets]~{lineno}~ \emph{preceding} ~\documentclass~. +% \item +% If you actually maintain such a class, please consider +% loading ~lineno.sty~ on some draft option. The bunch of +% lineno's package options may be a problem, but perhaps the +% purpose of your class is offering only very few of lineno's +% options anyway, maybe just one. +% \end{enumerate} +% The latter may also be needed with classes that don't follow +% David Kastrup's rule on changing ~\output~. +% +% \subsection{% +% \scs{MakeLineNo}: Actually attach line number +% \unskip}\label{ss:MLN} +% +% We have to return all the page to the current page, and +% add a box with the line number, without adding +% breakpoints, glue or space. The depth of our line number +% should be equal to the previous depth of the page, in +% case the page breaks here, and the box has to be moved up +% by that depth. +% +% The ~\interlinepenalty~ comes after the ~\vadjust~ from a +% ~\linelabel~, so we increment the line number \emph{after} +% printing it. The macro ~\makeLineNumber~ produces the +% text of the line number, see section \ref{appearance}. +% +% (UL) I needed a while to understand +% the sentence on incrementing. Correctly: writing the +% ~\newlabel~ to the .aux file is triggered by the signal +% penalty that ~\end@float~ inserts via ~\vadjust~. +% However, this could be changed by our new ~\PostponeVadjust~. +% After ~\c@linenumber~ has been introduced as a \LaTeX\ +% counter, it might be preferable that it behaved like standard +% \LaTeX\ counters which are incremented shortly before printing. +% But this may be of little practical relevance in this case, +% as ~\c@linenumber~ is driven in a very non-standard +% way.---However still, this behaviour of ~\c@linenumber~ +% generates a problem with our ~edtable.sty~. +%% \unskip---Before, +%% I thought that Stephan had reported his reasoning incorrectly +%% and rather did this because of his ~\resetlinenumber~ which +%% initializes ~\c@linenumber~ to 1 instead of 0---the latter is +%% usual with \LaTeX\ counters. Cf._additional comment at +%% ~\resetlinenumber~. +% (/UL). +% +% Finally we put in the natural ~\interlinepenalty~, except +% after the last line. +% +% (New v3.10) Frank Mittelbach points out that box255 may be +% less deep than the last box inside, so he proposes to +% measure the page depth with ~\boxmaxdepth=\maxdimen~. +% (/New v3.10) +% +% (UL, New v4.00) We also resume the matter of +% ~\vadjust~ items that was started in section_\ref{ss:output}. +% +% \TeX\ puts only nonzero interline +% penalties into the vertical list (\TeX book p._105), while +% ~lineno.sty~ formerly replaced the signal interline penalty by +% something closing with an explicit penalty of the value that +% the interline penalty would have without ~lineno.sty~. +% This is usually 0. Now, explicit vertical penalties can be +% very nasty with respect to ~\nopagebreak~, e.g., a low (even +% positive) ~\widowpenalty~ may force a widow where you +% explicitly tried to forbid it by ~\nopagebreak~ +% (see explanation soon below). +% The ~\nopagebreak~ we create here would never work if all +% those zero penalties were present.---On +% the other hand, we cannot just omit Stephan's zero penalties, +% because \TeX\ puts a penalty of 10000 after what ~lineno.sty~ +% inserts (\TeX book p._125). This penalty must be overridden +% to allow page breaks between ordinary lines. To revive +% ~\nopagebreak~, we therefore replace those zero (or low) +% penalties by penalties that the user demanded by +% ~\nopagebreak~.---This mechanism is not perfect and does not +% exactly restore the original \LaTeX\ working of ~\pagebreak~ +% and ~\nopagebreak~. Viz., if there are several vertical +% penalties after a line which were produced by closely sitting +% ~\[no]pagebreak~s, without ~lineno.sty~ the lowest penalty would +% be effective (cf._\TeX book exercise_14.10). Our mechanism, by +% contrast, chooses the \emph{last} user-set penalty of the line +% as the effective one. It would not be very difficult to come +% more close to the original mechanism, but until someone urges +% us we will cling to the present simple way. You may consider an +% advantage of the difference between our mechanism and the +% original one that the user here can actually override low +% penalties by ~\nopagebreak~, which may be what a lay \LaTeX\ +% user would expect. +%% ---Zero glue would do instead of zero +%% penalty! This could make things easier. Maybe next time. +%% <- v4.4: No, problem with column depth. +% (/UL, /New v4.00) + +\def\MakeLineNo{% + \@LN@maybe@normalLineNumber % v4.31 + \boxmaxdepth\maxdimen\setbox\z@\vbox{\unvbox\@cclv}% + \@tempdima\dp\z@ \unvbox\z@ + \sbox\@tempboxa{\hb@xt@\z@{\makeLineNumber}}% +%% +% (New v4.00) Previously, +% \begin{old}\begin{verbatim} +% % \stepcounter{linenumber}% +% \end{verbatim} +% \end{old} +%% %% TODO: Still first `\begin{old}'? +% followed. (Of course, there was no +% comment mark; I put it there to make +% reading the actual code easy.) +% +% (New v4.22: improved) Why not just +% \[~\global\advance\c@linenumber\@ne~?\] +% ~\stepcounter~ additionally resets ``subordinate'' +% counters, but which could these (usefully) be? +% Again, may be column counters with ~edtable.sty~!? +% +% But then, our ~edtable.sty~ and its ~longtable~ option +% should use it as well. So use a shorthand supporting +% uniformity. You can even use it as a hook for choosing +% ~\global\advance\c@linenumber\@ne~ instead of our choice. +% (/New v4.22) +%% + \stepLineNumber +%% +% (New v4.4) Now +%% + \ht\@tempboxa\z@ \@LN@depthbox +%% +% appends the box containing the line number without changing +% ~\prevdepth~---see end of section. +% Now is the time for inserting the $\dots$ (/New v4.4) +%% The line number has now been placed (it may be invisible +%% depending on the modulo feature), so +%% we can insert the +% ~\vadjust~ items. We cannot do this much later, because +% their right place is above the artificial interline +% penalty which Stephan's code will soon insert +% (cf._\TeX book p._105). The next command is just ~\relax~ +% if no ~\vadjust~ items have been accumulated for the +% current line. Otherwise it is a list macro inserting +% the ~\vadjust~ items and finally resetting itself. +% (This is made in section_\ref{ss:PVadj} below.) +% If the final item is a penalty, it is stored so it can +% compete with other things about page breaking. +%% + \@LN@do@vadjusts + \count@\lastpenalty +%% +% At this place, +% \begin{old}\begin{verbatim} +% % \ifnum\outputpenalty=-\linenopenaltypar\else +% \end{verbatim} +% \end{old} +% originally followed. We need something \emph{before} the +% ~\else~: +%% + \ifnum\outputpenalty=-\linenopenaltypar + \ifnum\count@=\z@ \else +%% +% So final ~\pagebreak[0]~ or ~\nopagebreak[0]~ has no +% effect---but this will make a difference after headings only, +% where nobody should place such a thing anyway. +%% + \xdef\@LN@parpgbrk{% + \penalty\the\count@ + \global\let\noexpand\@LN@parpgbrk + \noexpand\@LN@screenoff@pen}% v4.4 +%% +% That penalty will replace former ~\kern\z@~ in +% ~\linenumberpar~, see subsection_\ref{ss:calls}.---A +% few days earlier, I tried to send just a penalty value. +% However, the ~\kern\z@~ in ~\linenumberpar~ is crucial, +% as I then found out. See below.---The final penalty is +% repeated, but this does no harm. (It would not be very +% difficult to avoid the repeating, but it may even be +% less efficient.) It may be repeated due to the previous +% ~\xdef~, but it may be repeated as well below in the +% present macro where artificial interline penalty is to +% be overridden. +%% + \fi + \else +%% +% (/New v4.00) +%% Corrected code alignment with v4.11. + \@tempcnta\outputpenalty + \advance\@tempcnta -\linenopenalty +%% +% (New v4.00) +% \begin{old}\begin{verbatim} +% % \penalty\@tempcnta +% \end{verbatim} +% \end{old} +% followed previously. To give ~\nopagebreak~ a chance, +% we do +%% Corrected code alignment with v4.11. + \penalty \ifnum\count@<\@tempcnta \@tempcnta \else \count@ \fi +%% +% instead.---In ~linenox0.sty~, the ~\else~ thing once was omitted. +% Sergei Mariev's complaint (thanks!) showed that it is vital +% (see comment before ~\MakeLineNo~). +% The remaining ~\fi~ from previous package version closes the +% ~\ifnum\outputpenalty~\dots +% (/New v4.00) +%% + \fi + } + +% (New v4.00) + +\newcommand\stepLineNumber{\stepcounter{linenumber}} + +% For reason, see use above. (/New v4.00) +%% %% TODO v4.4+: ~\newcommand~ more often!? +% +% (New v4.4) The depth preserving trick is drawn here from +% ~\MakeLineNo~ because it will be used again in +% section_\ref{ss:calls}. + +\def\@LN@depthbox{% + \dp\@tempboxa=\@tempdima + \nointerlineskip \kern-\@tempdima \box\@tempboxa} + +% (/New v4.4) +% +% \section{% +% Control line numbering +% \unskip} +% \subsection{% +% Inserting \scs{output} calls %% own subsec. v4.4. +% \unskip}\label{ss:calls} +% The line numbering is controlled via ~\par~. \LaTeX\ +% saved the \TeX-primitive ~\par~ in ~\@@par~. We push it +% one level further out, and redefine ~\@@par~ to insert +% the ~\interlinepenalty~ needed to trigger the +% line numbering. And we need to allow pagebreaks after a +% paragraph. +% +% New (2.05beta): the prevgraf test. A paragraph that ends with a +% displayed equation, a ~\noindent\par~ or ~wrapfig.sty~ produce empty +% paragraphs. These should not get a spurious line number via +% ~\linenopenaltypar~. + +\let\@@@par\@@par +\newcount\linenoprevgraf + +% (UL) And needs ~\linenoprevgraf~ +% to be a counter? Perhaps there may be a paragraph having +% thousands of lines, so ~\mathchardef~ doesn't suffice (really??). +%% +%% %% TODO: limitations of lines per paragraph elsewhere? +%% %% Signal penalties, e.g.!? ~\deadcycles~!? +%% +% A macro ending on ~\relax~ might suffice, but would be +% somewhat slow. I think I will use ~\mathchardef~ next time. +% Or has any user used ~\linenoprevgraf~? (/UL) + +%% v4.33: changed code alignment for better understanding. +\def\linenumberpar{% + \ifvmode \@@@par \else + \ifinner \@@@par \else + \xdef\@LN@outer@holdins{\the\holdinginserts}% v4.2 + \advance \interlinepenalty \linenopenalty + \linenoprevgraf \prevgraf + \global \holdinginserts \thr@@ + \@@@par + \ifnum\prevgraf>\linenoprevgraf + \penalty-\linenopenaltypar + \fi +%% +% (New v4.00) +% \begin{old}\begin{verbatim} +% % \kern\z@ +% \end{verbatim} +% \end{old} +% was here previously. What for? +% According to \TeX book p._125, Stephan's +% interline penalty is changed into 10000. At the end of a +% paragraph, the ~\parskip~ would follow that penalty of 10000, +% so there could be a page break neither at the +% ~\parskip~ nor at the ~\baselineskip~ (\TeX book p._110)---so +% there could never be a page break between two paragraphs. +% So something must screen off the 10000 penalty. +% Indeed, the ~\kern~ is a place to break. +% (Stephan once knew this: see `allow pagebreaks' above.) +% +% Formerly, I tried to replace ~\kern\z@~ by +% \begin{old}\begin{verbatim} +% % \penalty\@LN@parpgpen\relax +% \end{verbatim} +% \end{old} +% ---but this allows a page break after heading. So: +%% + \@LN@parpgbrk +%% +%% After heading, ~\kern\z@~ resulting from previous line +%% (see below) is followed by ~\write~ or ~\penalty10000~, +%% so causes no page break. +% +% These and similar changes were formerly done by ~linenox1.sty~. +% (/New v4.00) +% +% (New v4.4) +% A ~\belowdisplayskip~ may precede the previous when the paragraph +% ends on a display-math; or there may be a ~\topsep~ from a list, etc. +% ~\addvspace~ couldn't take account for it with ~\kern\z@~ +% here. v4.32 therefore moved the space down -- with at least two +% bad consequences. +% Moreover, David Josef Dev observes that ~\kern\z@~ may +% inappropriately yield column depth 0pt. +% For these reasons, we introduce ~\@LN@screenoff@pen~ below. +% (/New v4.4) +%% + \global\holdinginserts\@LN@outer@holdins % v4.2 + \advance\interlinepenalty -\linenopenalty + \fi % from \ifinner ... \else + \fi} % from \ifvmode ... \else + +% (New v4.00, v4.4) Initialize ~\@LN@parpgbrk~, accounting +% for earlier space and for appropriate columndepth. +% We use former ~\MakeLineNo~'s depth-preverving trick +% ~\@LN@depthbox~ again: + +\def\@LN@screenoff@pen{% + \ifdim\lastskip=\z@ + \@tempdima\prevdepth \setbox\@tempboxa\null + \@LN@depthbox \fi} + +\global\let\@LN@parpgbrk\@LN@screenoff@pen + +% (/New v4.4, v4.00) +% \subsection{% +% Turning on/off %% own subsec. v4.4. +% \unskip}\label{ss:OnOff} +% The basic commands to enable and disable line numbers. +% ~\@par~ and ~\par~ are only touched, when they are ~\let~ +% to ~\@@@par~/~\linenumberpar~. The line number may be +% reset to 1 with the star-form, or set by an optional +% argument ~[~<number>~]~. +% +% (New v4.00) We add ~\ifLineNumbers~ etc.\ since +% a number of our new adjustments need to know whether +% linenumbering is active. This just provides a kind of +% shorthand for ~\ifx\@@par\linenumberpar~; moreover it is +% more stable: who knows what may happen to ~\@@par~?---A +% caveat: ~\ifLineNumbers~ may be wrong. E.g., it may be +% ~\iffalse~ where it acts, while a ~\linenumbers~ a few +% lines below---in the same paragraph---brings about that +% the line where the ~\ifLineNumbers~ appears gets a +% marginal number. +%% Better implementation suggested below. +%% +% (New v4.3) Just noticed: Such tricks have been +% disallowed with v4.11, see subsections_\ref{ss:LL} +% and_\ref{ss:OnOff}.---Moreover, the switching between +% meanings of ~\linelabel~ for a possible error message +% as of v4.11 is removed. Speed is difficult to esteem +% and also depends on applications. Just use the most +% simple code you find. (/New v4.3) + +\newif\ifLineNumbers \LineNumbersfalse + +% (/New v4.00) + +\def\linenumbers{% + \LineNumberstrue % v4.00 + \xdef\@LN@outer@holdins{\the\holdinginserts}% v4.3 +%% +% (New v4.3) The previous line is for ~{linenomath}~ +% in a first numbered paragraph. (/New v4.3) +%% + \let\@@par\linenumberpar + % \let\linelabel\@LN@linelabel % v4.11, removed v4.3 + \ifx\@par\@@@par\let\@par\linenumberpar\fi + \ifx\par\@@@par\let\par\linenumberpar\fi + \@LN@maybe@moduloresume % v4.31 + \@ifnextchar[{\resetlinenumber}%] + {\@ifstar{\resetlinenumber}{}}% + } + +\def\nolinenumbers{% + \LineNumbersfalse % v4.00 + \let\@@par\@@@par + % \let\linelabel\@LN@LLerror % v4.11, removed v4.3 + \ifx\@par\linenumberpar\let\@par\@@@par\fi + \ifx\par\linenumberpar\let\par\@@@par\fi + } + +% (New v4.00) Moreover, it is useful to switch to +% ~\nolinenumbers~ in ~\@arrayparboxrestore~. We postpone this +% to section_\ref{ss:ReDef} where we'll have an appending macro +% for doing this. (/New v4.00) +% +% What happens with a display math? Since ~\par~ is not executed, +% when breaking the lines before a display, they will not get +% line numbers. Sorry, but I do not dare to change +% ~\interlinepenalty~ globally, nor do I want to redefine +% the display math environments here. +% \begin{displaymath} +% display \ math +% \end{displaymath} +% See the subsection below, for a wrapper environment to make +% it work. But that requires to wrap each and every display +% in your \LaTeX\ source %%. +%% v4.3: +% (see option ~displaymath~ in subsections_\ref{ss:v3opts} +% and_\ref{ss:display} for some relief [UL]). +% +% The next two commands are provided to turn on line +% numbering in a specific mode. Please note the difference: +% for pagewise numbering, ~\linenumbers~ comes first to +% inhibit it from seeing optional arguments, since +% re-/presetting the counter is useless. + +\def\pagewiselinenumbers{\linenumbers\setpagewiselinenumbers} +\def\runninglinenumbers{\setrunninglinenumbers\linenumbers} + +% Finally, it is a \LaTeX\ style, so we provide for the use +% of environments, including the suppression of the +% following paragraph's indentation. +% +%% TODO: v4.4+: +% (UL) I am drawing the following +% private thoughts of Stephan's to publicity so that others may +% think about them---or to remind myself of them in an efficient +% way. (/UL) +%% UL changed `%%%' to `% %' below. +%% TODO: add \par to \linenumbers, if called from an environment. %% v4.3 +%% ToDO: add an \@endpe hack if \linenumbers are turned on +% \begin{old}\begin{verbatim} +% % TO DO: add \par to \linenumbers, if called from an environment. +% % To DO: add an \@endpe hack if \linenumbers are turned on +% % in horizontal mode. {\par\parskip\z@\noindent} or +% % something. +% \end{verbatim} +% \end{old} +% (UL) However, I rather think that ~\linenumbers~ and %% v4.31 +% ~\nolinenumbers~ should execute a ~\par~ already. (Then the +% ~\par~s in the following definitions should be removed.) (/UL) + +\@namedef{linenumbers*}{\par\linenumbers*} +\@namedef{runninglinenumbers*}{\par\runninglinenumbers*} + +\def\endlinenumbers{\par\@endpetrue} +\let\endrunninglinenumbers\endlinenumbers +\let\endpagewiselinenumbers\endlinenumbers +\expandafter\let\csname endlinenumbers*\endcsname\endlinenumbers +\expandafter\let\csname endrunninglinenumbers*\endcsname\endlinenumbers +\let\endnolinenumbers\endlinenumbers + +% +% \subsection{% +% Display math +% \unskip}\label{ss:DM} +% +% Now we tackle the problem to get display math working. +% There are different options. +% \begin{enumerate}\item[ +% 1.] Precede every display math with a ~\par~. +% Not too good. +% \item[ +% 2.] Change ~\interlinepenalty~ and associates globally. +% Unstable. +% \item[ +% 3.] Wrap each display math with a ~{linenomath}~ +% environment. +% \end{enumerate} +% We'll go for option 3. See if it works: +% \begin{linenomath} +% \begin{equation} +% display \ math +% \end{equation} +% \end{linenomath} +% The star form ~{linenomath*}~ should also number the lines +% of the display itself, +% \begin{linenomath*} +% \begin{eqnarray} +% multi && line \\ +% display && math \\ +% & +% \begin{array}{c} +% with \\ +% array +% \end{array} +% & +% \end{eqnarray} +% \end{linenomath*} +% including multline displays. +% +% First, here are two macros to turn +% on linenumbering on paragraphs preceeding displays, with +% numbering the lines of the display itself, or without. +% The ~\ifx..~ tests if line numbering is turned on. It +% does not harm to add these wrappers in sections that are +% not numbered. Nor does it harm to wrap a display +% twice, e.q, in case you have some ~{equation}~s wrapped +% explicitely, and later you redefine ~\equation~ to do it +% automatically. +% +% (New v4.3) To avoid the spurious line number above a +% display in vmode, I insert ~\ifhmode~. (/New v4.3) + +\newcommand\linenomathNonumbers{% + \ifLineNumbers +%% \ifx\@@par\@@@par\else + \ifnum\interlinepenalty>-\linenopenaltypar + \global\holdinginserts\thr@@ + \advance\interlinepenalty \linenopenalty + \ifhmode % v4.3 + \advance\predisplaypenalty \linenopenalty + \fi + \fi + \fi + \ignorespaces + } + +\newcommand\linenomathWithnumbers{% + \ifLineNumbers +%% \ifx\@@par\@@@par\else + \ifnum\interlinepenalty>-\linenopenaltypar + \global\holdinginserts\thr@@ + \advance\interlinepenalty \linenopenalty + \ifhmode % v4.3 + \advance\predisplaypenalty \linenopenalty + \fi + \advance\postdisplaypenalty \linenopenalty + \advance\interdisplaylinepenalty \linenopenalty + \fi + \fi + \ignorespaces + } + +% The ~{linenomath}~ environment has two forms, with and +% without a star. The following two macros define the +% environment, where the stared/non-stared form does/doesn't number the +% lines of the display or vice versa. + +\newcommand\linenumberdisplaymath{% + \def\linenomath{\linenomathWithnumbers}% + \@namedef{linenomath*}{\linenomathNonumbers}% + } + +\newcommand\nolinenumberdisplaymath{% + \def\linenomath{\linenomathNonumbers}% + \@namedef{linenomath*}{\linenomathWithnumbers}% + } + +\def\endlinenomath{% + \ifLineNumbers % v4.3 + \global\holdinginserts\@LN@outer@holdins % v4.21 + \fi + \global % v4.21 support for LaTeX2e earlier than 1996/07/26. + \@ignoretrue +} +\expandafter\let\csname endlinenomath*\endcsname\endlinenomath + +% The default is not to number the lines of a display. But +% the package option ~mathlines~ may be used to switch +% that behavior. + +\nolinenumberdisplaymath + +% +% \section{% +% Line number references +% \unskip}\label{s:LNref} +% \subsection{% +% Internals %% New subsec. v4.3. +% \unskip} +% The only way to get a label to a line number in a +% paragraph is to ask the output routine to mark it. +% +% (New v4.00) The following two paragraphs don't hold any +% longer, see below. (/New v4.00) +% \begin{old}\begin{verbatim} +% % We use the marginpar mechanism to hook to ~\output~ for a +% % second time. Marginpars are floats with number $-1$, we +% % fake marginpars with No $-2$. Originally, every negative +% % numbered float was considered to be a marginpar. +% % +% % The float box number ~\@currbox~ is used to transfer the +% % label name in a macro called ~\@LNL@~<box-number>. +% \end{verbatim} +% \end{old} +% A ~\newlabel~ is written to the aux-file. The reference +% is to ~\theLineNumber~, \emph{not} ~\thelinenumber~. +% This allows to hook in, as done below for pagewise line +% numbering. +% +% (New v3.03) The ~\@LN@ExtraLabelItems~ are added for a hook +% to keep packages like ~{hyperref}~ happy. (/New v3.03) +% +% (New v4.00) +% We fire the ~\marginpar~ mechanism, so we leave \LaTeX's +% ~\@addmarginpar~ untouched. +% \begin{old}\begin{verbatim} +% % \let\@LN@addmarginpar\@addmarginpar +% % \def\@addmarginpar{% +% % \ifnum\count\@currbox>-2\relax +% % \expandafter\@LN@addmarginpar +% % \else +% % \@cons\@freelist\@currbox +% % \protected@write\@auxout{}{% +% % \string\newlabel +% % {\csname @LNL@\the\@currbox\endcsname}% +% % {{\theLineNumber}{\thepage}\@LN@ExtraLabelItems}}% +% % \fi} +% \end{verbatim} +% \end{old} +% OK, we keep Stephan's ~\@LN@ExtraLabelItems~: +% (/New v4.00) + +\let\@LN@ExtraLabelItems\@empty + +% (New v4.00) +% We imitate the ~\marginpar~ mechanism without using the +% ~\@freelist~ boxes. ~\linelabel~ will indeed place a signal +% penalty (~\@Mllbcodepen~, new), and it will put a label into +% some list macro ~\@LN@labellist~. A new part of the output +% routine will take the labels from the list and will write +% ~\newlabel~s to the .aux file. +% +% The following is a version of \LaTeX's ~\@xnext~. + +\def\@LN@xnext#1\@lt#2\@@#3#4{\def#3{#1}\gdef#4{#2}} + +% This takes an item ~#1~ from a list ~#4~ into ~#3~; +% to be used as ~\expandafter\@LN@xnext#4\@@#3#4~. +% Our lists use ~\@lt~ after each item for separating. +% Indeed, there will be another list macro which can +% appear as argument ~#4~, this will be used for moving +% ~\vadjust~ items (section_\ref{ss:PVadj}). +% The list for ~\linelabel~s is the following: + +\global\let\@LN@labellist\@empty + +% The next is the new part of the output routine writing the +% ~\newlabel~ to the .aux file. Since it is no real page output, +% the page is put back to top of the main vertical list. + +\def\WriteLineNo{% + \unvbox\@cclv + \expandafter \@LN@xnext \@LN@labellist \@@ + \@LN@label \@LN@labellist + \protected@write\@auxout{}{\string\newlabel{\@LN@label}% + {{\theLineNumber}{\thepage}\@LN@ExtraLabelItems}}% +} + +% (/New v4.00) +% +% \subsection{% +% The \scs{linelabel} command +% \unskip}\label{ss:LL} +% To refer to a place in line ~\ref{~<foo>~}~ at page +% ~\pageref{~<foo>~}~ you place a ~\linelabel{~<foo>~}~ at +% that place. +% +% \linelabel{demo} +% \marginpar{\tiny\raggedright +% See if it works: This paragraph +% starts on page \pageref{demo}, line +% \ref{demo}. +% \unskip}% +% (New v4.11) +% \begin{old}\begin{verbatim} +% % If you use this command outside a ~\linenumbers~ +% % paragraph, you will get references to some bogus +% % line numbers, sorry. But we don't disable the command, +% % because only the ~\par~ at the end of a paragraph may +% % decide whether to print line numbers on this paragraph +% % or not. A ~\linelabel~ may legally appear earlier than +% % ~\linenumbers~. +% \end{verbatim} +% \end{old} +% This trick is better not allowed---see subsections_\ref{ss:LL} +% and_\ref{ss:OnOff}. +% (/New v4.11) +% +% ~\linelabel~ +% \begin{old}\begin{verbatim} +% %, via a fake float number $-2$, %% new mechanism v4.00 +% \end{verbatim} +% \end{old} +% puts a +% ~\penalty~ into a ~\vadjust~, which triggers the +% pagebuilder after putting the current line to the main +% vertical list. A ~\write~ is placed on the main vertical +% list, which prints a reference to the current value of +% ~\thelinenumber~ and ~\thepage~ at the time of the +% ~\shipout~. +% +% A ~\linelabel~ is allowed only in outer horizontal mode. +% In outer vertical mode we start a paragraph, and ignore +% trailing spaces (by fooling ~\@esphack~). +% +% (New v4.00) We aim at relaxing the previous condition. +% We insert a hook ~\@LN@mathhook~ and a shorthand +% ~\@LN@postlabel~ to support the ~mathrefs~ option which +% allows ~\linelabel~ in math mode. +% +% The next paragraph is no longer valid. +% \begin{old}\begin{verbatim} +% % The argument of ~\linelabel~ is put into a macro with a +% % name derived from the number of the allocated float box. +% % Much of the rest is dummy float setup. +% \end{verbatim} +% \end{old} +% (/New v4.00) +% +% (New v4.11) +% \begin{old}\begin{verbatim} +% % \def\linelabel#1{% +% \end{verbatim} +% \end{old} +% I forgot ~\linenumbers~ today, costed me hours or so. + +\def\@LN@LLerror{\PackageError{lineno}{% + \string\linelabel\space without \string\linenumbers}{% + Just see documentation. (New feature v4.11)}\@gobble} + +% (New v4.3) Here some things have changed for v4.3. +% The previous ~#1~ has been replaced by ~\@gobble~. +% Ensuing, the ~\linelabel~ error message is re-implemented. +% I find it difficult to compare efficiency of slight +% alternatives---so choose an easy one. Explicit switching +% in ~\linenumbers~ and ~\nolinenumbers~ is an additional +% command that may better be avoided. + +\newcommand\linelabel{% + \ifLineNumbers \expandafter \@LN@linelabel + \else \expandafter \@LN@LLerror \fi} +%%\let\linelabel\@LN@LLerror + +\gdef\@LN@linelabel#1{% +%% +% ~\gdef~ for hyperref ``symbolically''. (/New v4.11) +%% + \ifx\protect\@typeset@protect +%% +% $\gets$ And a ~\linelabel~ should never be replicated in a +% mark or a TOC entry. (/New v4.3) +%% + \ifvmode + \ifinner \else + \leavevmode \@bsphack \@savsk\p@ + \fi + \else + \@bsphack + \fi + \ifhmode + \ifinner + \@parmoderr + \else +%% +% (New v4.00) +%% + \@LN@postlabel{#1}% +% \begin{old}\begin{verbatim} +% % \@floatpenalty -\@Mii +% % \@next\@currbox\@freelist +% % {\global\count\@currbox-2% +% % \expandafter\gdef\csname @LNL@\the\@currbox\endcsname{#1}}% +% % {\@floatpenalty\z@ \@fltovf \def\@currbox{\@tempboxa}}% +% % \begingroup +% % \setbox\@currbox \color@vbox \vbox \bgroup \end@float +% % \endgroup +% % \@ignorefalse \@esphack +% \end{verbatim} +% \end{old} +% (/New v4.00) +%% + \@esphack +%% +% (New v4.00) +% The ~\@ignorefalse~ was appropriate before because the +% ~\@Esphack~ in ~\end@float~ set ~\@ignoretrue~. Cf._\LaTeX's +% ~\@xympar~. (/New v4.00) +%% + \fi + \else +%% +% (New v4.00) +%% + \@LN@mathhook{#1}% +% \begin{old}\begin{verbatim} +% % \@parmoderr +% \end{verbatim} +% \end{old} +% Instead of complaining, you may just do your job. +% (/New v4.00) +%% + \fi + \fi + } + +% (New v4.00) The shorthand just does what happened +% with ~linenox0.sty~ before ~ednmath0.sty~ (New v4.1: +% now ~mathrefs~ option) appeared, and +% the hook is initialized to serve the same purpose. +% So errors come just where Stephan had built them in, +% and this is just the \LaTeX\ ~\marginpar~ behaviour. + +\def\@LN@postlabel#1{\g@addto@macro\@LN@labellist{#1\@lt}% + \vadjust{\penalty-\@Mllbcodepen}} +\def\@LN@mathhook#1{\@parmoderr} + +% (/New v4.00) +% +% \modulolinenumbers[3] +% \firstlinenumber{1} +% \section{% +% The appearance of the line numbers +% \unskip}\label{appearance} +% \subsection{% +% Basic code %% own subsec. v4.2. +% \unskip} +% +% The line numbers are set as ~\tiny\sffamily\arabic{linenumber}~, +% $10pt$ left of the text. With options to place it +% right of the text, or . . . +% +% . . . here are the hooks: + +\def\makeLineNumberLeft{% + \hss\linenumberfont\LineNumber\hskip\linenumbersep} + +\def\makeLineNumberRight{% + \linenumberfont\hskip\linenumbersep\hskip\columnwidth + \hb@xt@\linenumberwidth{\hss\LineNumber}\hss} + +\def\linenumberfont{\normalfont\tiny\sffamily} + +\newdimen\linenumbersep +\newdimen\linenumberwidth + +\linenumberwidth=10pt +\linenumbersep=10pt + +% Margin switching requires ~pagewise~ numbering mode, but +% choosing the left or right margin for the numbers always +% works. + +\def\switchlinenumbers{\@ifstar + {\let\makeLineNumberOdd\makeLineNumberRight + \let\makeLineNumberEven\makeLineNumberLeft}% + {\let\makeLineNumberOdd\makeLineNumberLeft + \let\makeLineNumberEven\makeLineNumberRight}% + } + +\def\setmakelinenumbers#1{\@ifstar + {\let\makeLineNumberRunning#1% + \let\makeLineNumberOdd#1% + \let\makeLineNumberEven#1}% + {\ifx\c@linenumber\c@runninglinenumber + \let\makeLineNumberRunning#1% + \else + \let\makeLineNumberOdd#1% + \let\makeLineNumberEven#1% + \fi}% + } + +\def\leftlinenumbers{\setmakelinenumbers\makeLineNumberLeft} +\def\rightlinenumbers{\setmakelinenumbers\makeLineNumberRight} + +\leftlinenumbers* + +% ~\LineNumber~ is a hook which is used for the modulo stuff. +% It is the command to use for the line number, when you +% customize ~\makeLineNumber~. Use ~\thelinenumber~ to +% change the outfit of the digits. +% +% +% We will implement two modes of operation: +% \begin{itemize} +% \item numbers ~running~ through (parts of) the text +% \item ~pagewise~ numbers starting over with one on top of +% each page. +% \end{itemize} +% Both modes have their own count register, but only one is +% allocated as a \LaTeX\ counter, with the attached +% facilities serving both. + +\newcounter{linenumber} +\newcount\c@pagewiselinenumber +\let\c@runninglinenumber\c@linenumber + +% Only the running mode counter may be reset, or preset, +% for individual paragraphs. The pagewise counter must +% give a unique anonymous number for each line. +% +% (New v4.3) ~\newcounter{linenumber}~ +% was the only ~\newcounter~ in the whole package, and +% formerly I was near using ~\newcount~ instead. Yet +% ~\newcounter~ may be quite useful for ~\includeonly~. +% It also supports resetting ``subcounters'', but what +% could these be? Well, ~edtable~ might introduce a +% subcounter for columns. +% (Note that \LaTeX's setting commands would work with +% ~\newcount\c@linenumber~ already, apart from this. +% And perhaps sometimes ~\refstepcounter{linenumber}~ +% wouldn't work---cf._my discussion of ~\stepcounter~ in +% subsection_\ref{ss:MLN}, similarly ~\refstep...~ would +% be quite useless. +% Even the usual redefinitions of ~\thelinenumber~ would +% work. It is nice, on the other hand, that +% ~\thelinenumber~ is predefined here. \LaTeX's +% initialization of the value perhaps just serves making +% clear \LaTeX\ counters should always be changed +% globally.---Shortened and improved the discussion here.) +% (/New v4.3) +% +% (New v4.22) +% ~\c@linenumber~ usually is---globally---incremented by +% ~\stepcounter~ (at present), so resetting it locally would +% raise the save stack problem of \TeX book p._301, moreover +% it would be is useless, there is no hope of keeping the +% values local (but see subsection_\ref{ss:ILN}). So I insert +% ~\global~: (/New v4.22) + +\newcommand*\resetlinenumber[1][\@ne]{% + \global % v4.22 + \c@runninglinenumber#1\relax} + +% (New v4.00) +% \begin{old}\begin{verbatim} +% % \newcommand\resetlinenumber[1][1]{\c@runninglinenumber#1} +% \end{verbatim} +% \end{old} +% Added ~\relax~, being quite sure that this does no harm +% and is quite important, as with ~\setcounter~ etc. +% I consider this a bug fix (although perhaps no user has +% ever had a problem with this). (/New v4.00) +% +% (v4.22: I had made much fuss about resetting subordinate +% counters here---removed, somewhat postponed.) +% +%% TODO v4.4+: +%% \newcommand*\resetlinenumber[1][\@ne]{% +%% \ifx\c@linenumber\c@runninglinenumber +%% \global\c@linenumber#1\relax +%% \global\advance\c@linenumber\m@ne +%% \stepLineNumber +%% \else +%% \PackageError{lineno}%% Shorthand!? +%% {You can't reset line number in pagewise mode}% +%% {This should suffice.}% +%% \fi +%% } +% +% \subsection{% +% Running line numbers +% \unskip} +% +% Running mode is easy, ~\LineNumber~ and ~\theLineNumber~ +% produce ~\thelinenumber~, which defaults to +% ~\arabic{linenumber}~, using the ~\c@runninglinenumber~ +% counter. This is the default mode of operation. + +\def\makeRunningLineNumber{\makeLineNumberRunning} + +\def\setrunninglinenumbers{% + \def\theLineNumber{\thelinenumber}% + \let\c@linenumber\c@runninglinenumber + \let\makeLineNumber\makeRunningLineNumber + } + +\setrunninglinenumbers\resetlinenumber + +% +% \subsection{% +% Pagewise line numbers +% \unskip}\label{ss:PW} +% +% Difficult, if you think about it. The number has to be +% printed when there is no means to know on which page it +% will end up, except through the aux-file. My solution +% is really expensive, but quite robust. +% +% With version ~v2.00~ the hashsize requirements are +% reduced, because we do not need one controlsequence for +% each line any more. But this costs some computation time +% to find out on which page we are. +% +% ~\makeLineNumber~ gets a hook to log the line and page +% number to the aux-file. Another hook tries to find out +% what the page offset is, and subtracts it from the counter +% ~\c@linenumber~. Additionally, the switch +% ~\ifoddNumberedPage~ is set true for odd numbered pages, +% false otherwise. + +\def\setpagewiselinenumbers{% + \let\theLineNumber\thePagewiseLineNumber + \let\c@linenumber\c@pagewiselinenumber + \let\makeLineNumber\makePagewiseLineNumber + } + +\def\makePagewiseLineNumber{\logtheLineNumber\getLineNumber + \ifoddNumberedPage + \makeLineNumberOdd + \else + \makeLineNumberEven + \fi + } + +% Each numbered line gives a line to the aux file +% \begin{verse} +% ~\@LN{~<line>~}{~<page>~}~ +% \end{verse} +% very similar to the ~\newlabel~ business, except that we need +% an arabic representation of the page number, not what +% there might else be in ~\thepage~. + +\def\logtheLineNumber{\protected@write\@auxout{}{% +%% +% (New v4.00) (UL) +% As Daniel Doherty observed, the earlier line +% \begin{old}\begin{verbatim} +% % \string\@LN{\the\c@linenumber}{\noexpand\the\c@page}}} +% \end{verbatim} +% \end{old} +% here may lead into an infinite loop when the user resets +% the page number (think of ~\pagenumbering~, e.g.). +% Stephan and I brief\/ly discussed the matter and decided +% to introduce a ``physical''-page counter to which +% ~\logtheLineNumber~ refers. It was Stephan's idea to use +% ~\cl@page~ for reliably augmenting the ``physical''-page +% counter. However, this relies on the output routine once +% doing ~\stepcounter{page}~. Before Stephan's +% suggestion, I had thought of appending the stepping to +% \LaTeX's ~\@outputpage~.---So the macro definition ends +% as follows. +%% + \string\@LN{\the\c@linenumber}{% +%% +% (New v4.2) +%% \noexpand\number\n@LN@truepage}}} +%% +% The `truepage' counter must start with ~\c@~ so it works +% with ~\include~, and the ~\@addtoreset~ below is needed +% for the same purpose. +%% + \noexpand\the\c@LN@truepage}}} + +%% \newcount\n@LN@truepage +%% \g@addto@macro\cl@page{\global\advance\n@LN@truepage\@ne} +\newcount\c@LN@truepage +\g@addto@macro\cl@page{\global\advance\c@LN@truepage\@ne} +\@addtoreset{LN@truepage}{@ckpt} + +% (/New v4.2) I had thought of offering more +% features of a \LaTeX\ counter. However, the user should +% better \emph{not} have access to this counter. ~\c@page~ +% should suffice as a pagewise master counter.---To be sure, +% along the present lines the user \emph{can} manipulate +% ~\c@LN@truepage~ by ~\stepcounter{page}~. E.g., she might +% do this in order to manually insert a photograph. Well, +% seems not to harm. +% +% The above usage of ~\g@addto@macro~ and ~\cl@page~ may be +% not as stable as Stephan intended. His proposal used +% ~\xdef~ directly. But he used ~\cl@page~ as well, and who +% knows \dots{} And as to ~\g@addto@macro~, I have introduced +% it for list macros anyway. +% (/UL) (/New v4.00) +% +% From the aux-file we get one macro ~\LN@P~<page> for each +% page with line numbers on it. This macro calls four other +% macros with one argument each. These macros are +% dynamically defined to do tests and actions, to find out +% on which page the current line number is located. +% +% We need sort of a pointer to the first page with line +% numbers, initiallized to point to nothing: + +\def\LastNumberedPage{first} +\def\LN@Pfirst{\nextLN\relax} + +% The four dynamic macros are initiallized to reproduce +% themselves in an ~\xdef~ + +\let\lastLN\relax % compare to last line on this page +\let\firstLN\relax % compare to first line on this page +\let\pageLN\relax % get the page number, compute the linenumber +\let\nextLN\relax % move to the next page + +% During the end-document run through the aux-files, we +% disable ~\@LN~. I may put in a check here later, to give +% a rerun recommendation. + +\AtEndDocument{\let\@LN\@gobbletwo} + +% Now, this is the tricky part. First of all, the whole +% definition of ~\@LN~ is grouped, to avoid accumulation +% on the save stack. Somehow ~\csname~<cs>~\endcsname~ pushes +% an entry, which stays after an ~\xdef~ to that <cs>. +% +% If ~\LN@P~<page> is undefined, initialize it with the +% current page and line number, with the +% \emph{pointer-to-the-next-page} pointing to nothing. And +% the macro for the previous page will be redefined to point +% to the current one. +% +% If the macro for the current page already exists, just +% redefine the \emph{last-line-number} entry. +% +% Finally, save the current page number, to get the pointer to the +% following page later. + +\def\@LN#1#2{{\expandafter\@@LN + \csname LN@P#2C\@LN@column\expandafter\endcsname + \csname LN@PO#2\endcsname + {#1}{#2}}} + +\def\@@LN#1#2#3#4{\ifx#1\relax + \ifx#2\relax\gdef#2{#3}\fi + \expandafter\@@@LN\csname LN@P\LastNumberedPage\endcsname#1% + \xdef#1{\lastLN{#3}\firstLN{#3}% + \pageLN{#4}{\@LN@column}{#2}\nextLN\relax}% + \else + \def\lastLN##1{\noexpand\lastLN{#3}}% + \xdef#1{#1}% + \fi + \xdef\LastNumberedPage{#4C\@LN@column}} + +% The previous page macro gets its pointer to the +% current one, replacing the ~\relax~ with the cs-token +% ~\LN@P~<page>. + +\def\@@@LN#1#2{{\def\nextLN##1{\noexpand\nextLN\noexpand#2}% + \xdef#1{#1}}} + +% Now, to print a line number, we need to find the page, +% where it resides. This will most probably be the page where +% the last one came from, or maybe the next page. However, it can +% be a completely different one. We maintain a cache, +% which is ~\let~ to the last page's macro. But for now +% it is initialized to expand ~\LN@first~, where the poiner +% to the first numbered page has been stored in. + +\def\NumberedPageCache{\LN@Pfirst} + +% To find out on which page the current ~\c@linenumber~ is, +% we define the four dynamic macros to do something usefull +% and execute the current cache macro. ~\lastLN~ is run +% first, testing if the line number in question may be on a +% later page. If so, disable ~\firstLN~, and go on to the +% next page via ~\nextLN~. + +\def\testLastNumberedPage#1{\ifnum#1<\c@linenumber + \let\firstLN\@gobble + \fi} + +% Else, if ~\firstLN~ finds out that we need an earlier +% page, we start over from the beginning. Else, ~\nextLN~ +% will be disabled, and ~\pageLN~ will run +% ~\gotNumberedPage~ with four arguments: the first line +% number on this column, the page number, the column +% number, and the first line on the page. + +\def\testFirstNumberedPage#1{\ifnum#1>\c@linenumber + \def\nextLN##1{\testNextNumberedPage\LN@Pfirst}% + \else + \let\nextLN\@gobble + \def\pageLN{\gotNumberedPage{#1}}% + \fi} + +% We start with ~\pageLN~ disabled and ~\nextLN~ defined to +% continue the search with the next page. + +\long\def \@gobblethree #1#2#3{} + +\def\testNumberedPage{% + \let\lastLN\testLastNumberedPage + \let\firstLN\testFirstNumberedPage + \let\pageLN\@gobblethree + \let\nextLN\testNextNumberedPage + \NumberedPageCache + } + +% When we switch to another page, we first have to make +% sure that it is there. If we are done with the last +% page, we probably need to run \TeX\ again, but for the +% rest of this run, the cache macro will just return four +% zeros. This saves a lot of time, for example if you have +% half of an aux-file from an aborted run, in the next run +% the whole page-list would be searched in vain again and +% again for the second half of the document. +% +% If there is another page, we iterate the search. + +\def\testNextNumberedPage#1{\ifx#1\relax + \global\def\NumberedPageCache{\gotNumberedPage0000}% + \PackageWarningNoLine{lineno}% + {Linenumber reference failed, + \MessageBreak rerun to get it right}% + \else + \global\let\NumberedPageCache#1% + \fi + \testNumberedPage + } + +% \linelabel{demo2} +% \marginpar{\tiny\raggedright +% Let's see if it finds the label +% on page \pageref{demo}, +% line \ref{demo}, and back here +% on page \pageref{demo2}, line +% \ref{demo2}. +% \unskip}% +% To separate the official hooks from the internals there is +% this equivalence, to hook in later for whatever purpose: + +\let\getLineNumber\testNumberedPage + +% So, now we got the page where the number is on. We +% establish if we are on an odd or even page, and calculate +% the final line number to be printed. + +\newif\ifoddNumberedPage +\newif\ifcolumnwiselinenumbers +\columnwiselinenumbersfalse + +\def\gotNumberedPage#1#2#3#4{\oddNumberedPagefalse + \ifodd \if@twocolumn #3\else #2\fi\relax\oddNumberedPagetrue\fi + \advance\c@linenumber\@ne + \ifcolumnwiselinenumbers + \subtractlinenumberoffset{#1}% + \else + \subtractlinenumberoffset{#4}% + \fi + } + +% You might want to run the pagewise mode with running line +% numbers, or you might not. It's your choice: + +\def\runningpagewiselinenumbers{% + \let\subtractlinenumberoffset\@gobble + } + +\def\realpagewiselinenumbers{% + \def\subtractlinenumberoffset##1{\advance\c@linenumber-##1\relax}% + } + +\realpagewiselinenumbers + +% For line number references, we need a protected call to +% the whole procedure, with the requested line number stored +% in the ~\c@linenumber~ counter. This is what gets printed +% to the aux-file to make a label: + +\def\thePagewiseLineNumber{\protect + \getpagewiselinenumber{\the\c@linenumber}}% + +% And here is what happens when the label is refered to: + +\def\getpagewiselinenumber#1{{% + \c@linenumber #1\relax\testNumberedPage + \thelinenumber + }} + +% % +% A summary of all per line expenses: +% \begin{description}\item +% [CPU:] The ~\output~ routine is called for each line, +% and the page-search is done. +% \item +% [DISK:] One line of output to the aux-file for each +% numbered line +% \item +% [MEM:] One macro per page. Great improvement over v1.02, +% which had one control sequence per line in +% addition. It blew the hash table after some five +% thousand lines. +% \end{description} +% +% \subsection{% +% Twocolumn mode (New v3.06) +% \unskip} +% +% Twocolumn mode requires another patch to the ~\output~ +% routine, in order to print a column tag to the .aux +% file. + +\AtBeginDocument{% v4.2, revtex4.cls (e.g.). + % <- TODO v4.4+: Or better in \LineNoLaTeXOutput!? + \let\@LN@orig@makecol\@makecol} +\def\@LN@makecol{% + \@LN@orig@makecol + \setbox\@outputbox \vbox{% + \boxmaxdepth \@maxdepth + \protected@write\@auxout{}{% + \string\@LN@col{\if@firstcolumn1\else2\fi}% + }% + \box\@outputbox + }% \vbox +} %% TODO cf. revtexln.sty. + +\def\@LN@col{\def\@LN@column} % v4.22, removed #1. +\@LN@col{1} + +% +% \subsection{% +% Numbering modulo $m$, starting at $f$ +%% Numbering modulo 5 +% \unskip}\label{ss:Mod} +% +% Most users want to have only one in five lines numbered. +% ~\LineNumber~ is supposed to produce the outfit of the +% line number attached to the line, while ~\thelinenumber~ +% is used also for references, which should appear even if +% they are not multiples of five. +% +% (New v4.00) Moreover, some users want to +% control which line number should be printed first. Support +% of this is now introduced here---see ~\firstlinenumber~ +% below.---~numline.sty~ by Michael Jaegermann and +% James Fortune offers controlling which \emph{final} +% line numbers should not be printed. What is +% it good for? We ignore this here until some user demands +% it.---Peter Wilson's ~ledmac.sty~ offers much different +% choices of line numbers to be printed, due to Wayne Sullivan. +% (/New v4.00) +% +% (New v4.22) ~\c@linenumbermodulo~ is rendered a +% fake counter, as discussed since v4.00. So it can +% no longer be set by ~\setcounter~. ~\modulolinenumbers~ +% serves this purpose. Well, does anybody want to do +% what worked with ~\addtocounter~? (Then please tell +% me.)---At least, ~\value~ still works. For the same +% purpose I rename the fake `firstlinenumber' counter +% ~\n@...~ to ~\c@...~. (/New v4.22) +% \begin{old}\begin{verbatim} +% % \newcount\c@linenumbermodulo % removed for v4.22 +% \end{verbatim} +% \end{old} +% +%% Removed for v4.22: +%% (UL) On my question why, e.g., +%% ~\chardef~ would not have sufficed, Stephan couldn't remember +%% exactly; guessed that he wanted to offer \LaTeX\ counter +%% facilities. However, the typical ones don't come this way. +%% So I'm quite sure that I will change this next time. +%% +%% However, I observed at least two times that users gave a very +%% high value to ~\c@linenumbermodulo~ in order to suppress +%% printing of the line number. One of these users preferred an +%% own way of handling line numbers, just wanted to use +%% ~\linelabel~ and ~ednotes.sty~ features. Should we support this? +%% I rather would like to advise them to +%% ~\let\makeLineNumber\relax~. (/UL) +% +% (New v4.00) \par +% ~\themodulolinenumber~ waits for being declared +% ~\LineNumber~ by ~\modulolinenumbers~. (This has +% been so before, no change.) Here is how it +% looked before: +% \begin{old}\begin{verbatim} +% % \def\themodulolinenumber{{\@tempcnta\c@linenumber +% % \divide\@tempcnta\c@linenumbermodulo +% % \multiply\@tempcnta\c@linenumbermodulo +% % \ifnum\@tempcnta=\c@linenumber\thelinenumber\fi +% % }} +% \end{verbatim} +% \end{old} +% (UL) This was somewhat slow. This arithmetic +% happens at every line. This time I tend to declare an extra +%% TODO v4.4+ +% line counter (as opposed to my usual recommendations to use +% counters as rarely as possible) which is stepped every line. +% It could be incremented in the same way as ~\c@LN@truepage~ +% is incremented via ~\cl@page~! This is another point in favour +% of ~{linenumber}~ being a \LaTeX\ counter! +% When this new counter equals ~\c@linenumbermodulo~, it is reset, +% and ~\thelinenumber~ is executed.---It gets much slower by my +% support of controlling the first line number below. I should +% improve this.---On +%% %% TODO v4.4+--pagewise!? +% the other hand, time expense means very little nowadays, +% while the number of \TeX\ counters still is limited. +% +% For the same purpose, moreover, attaching the line number +% box could be intercepted earlier (in ~\MakeLineNo~), +% without changing ~\LineNumber~. However, this may be +% bad for the latter's announcement as a wizard interface +% in section_\ref{s:UserCmds}. +%% +%% I wonder about Stephan's group. Its only effect is that +%% ~\@tempcnta~ is restored after using it. What for is this? +%% I tend to remove the group braces. %% TODO v4.4+ +% (/UL) +% +% Here is the new code. It is very near to my ~lnopatch.sty~ +% code which introduced the first line number feature +% before.---I add starting with a ~\relax~ which is so often +% recommended---without understanding this really. At least, +% it will not harm.---Former group braces appear as +% ~\begingroup~/~\endgroup~ here. + +\def\themodulolinenumber{\relax + \ifnum\c@linenumber<\c@firstlinenumber \else + \begingroup + \@tempcnta\c@linenumber + \advance\@tempcnta-\c@firstlinenumber + \divide\@tempcnta\c@linenumbermodulo + \multiply\@tempcnta\c@linenumbermodulo + \advance\@tempcnta\c@firstlinenumber + \ifnum\@tempcnta=\c@linenumber \thelinenumber \fi + \endgroup + \fi +} + +% (/New v4.00) +% +% The user command to set the modulo counter: +% (New v4.31) \dots\ a star variant is introduced to implement +% Hillel Chayim Yisraeli's idea to print the first line number +% after an interruption of the edited text by some editor's +% text, regardless of the modulo. If it is 1, it is printed only +% with ~\firstlinenumber{1}~. I.e., you use ~\modulolinenumbers*~ +% for the new feature, without the star you get the simpler +% behaviour that we have had so far. And you can switch back +% from the refined behaviour to the simple one by using +% ~\modulolinenumbers~ without the star.---This enhancement +% is accompanied by a new package option ~modulo*~ which just +% executes ~\modulolinenumbers*~ +% (subsection_\ref{ss:v3opts}).---`With ~\firstlinenumber{1}~' +% exactly means: `1' is printed if and only if the last +% ~\firstlinenumber~ before or in the paragraph that follows +% the ``interruption'' has argument `1' (or something +% \emph{expanding} to `1', or (to) something that \TeX\ +% ``reads'' as 1, e.g.: a \TeX\ count register storing +% 1).---At present, this behaviour may be unsatisfactory with +% pagewise line-numbering $\dots$ I'll make an experimental +% extra package if someone complains \dots + +\newcommand\modulolinenumbers{% + \@ifstar + {\def\@LN@maybe@moduloresume{% + \global\let\@LN@maybe@normalLineNumber + \@LN@normalLineNumber}% + \@LN@modulolinenos}% + {\let\@LN@maybe@moduloresume\relax \@LN@modulolinenos}% +} + +\global\let\@LN@maybe@normalLineNumber\relax +\let\@LN@maybe@moduloresume\relax +\gdef\@LN@normalLineNumber{% + \ifnum\c@linenumber=\c@firstlinenumber \else + \ifnum\c@linenumber>\@ne + \def\LineNumber{\thelinenumber}% + \fi + \fi +%% +% ~\def~ instead of ~\let~ enables taking account of a +% redefinition of ~\thelinenumber~ in a present numbering +% environment (e.g.). +%% + \global\let\@LN@maybe@normalLineNumber\relax} + +% Instead of changing ~\LineNumber~ directly by +% ~LN@moduloresume~, these tricks enable ~\modulolinenumbers*~ +% to act as locally as I can make it. I don't know how to +% avoid that the output routine switches back to the normal +% modulo behaviour by a global change. (An ~\aftergroup~ may +% fail in admittedly improbable cases.) + +\newcommand*\@LN@modulolinenos[1][\z@]{% +%% +% The definition of this macro is that of the former +% ~\modulolinenumbers~. (/New v4.31) +%% + \let\LineNumber\themodulolinenumber + \ifnum#1>\@ne + \chardef % v4.22, note below + \c@linenumbermodulo#1\relax + \else\ifnum#1=\@ne +% \begin{old}\begin{verbatim} +% % \def\LineNumber{\thelinenumber}% +% \end{verbatim} +% \end{old} +% (New v4.00) I am putting something here to enable +% ~\firstlinenumber~ with $~\c@linenumbermodulo~=1$. +% With ~lnopatch.sty~, a trick was offered for this purpose. +% It is now obsolete. +% + \def\LineNumber{\@LN@ifgreat\thelinenumber}% +%% +% (/New v4.00) +%% + \fi\fi + } + +% (New v4.00) The default of ~\@LN@ifgreat~ is + +\let\@LN@ifgreat\relax + +% The previous changes as soon as ~\firstlinenumber~ is used: + +\newcommand*\firstlinenumber[1]{% + \chardef\c@firstlinenumber#1\relax +%% +% No counter, little values allowed only---OK?---(UL) +% The change is local---OK? The good thing is that +% ~\global\firstlinenumber{~<number>~}~ works. Moreover, +% ~\modulolinenumbers~ acts locally as well. (/UL) +% +% (New v4.31) +%% + \let\@LN@ifgreat\@LN@ifgreat@critical} + +\def\@LN@ifgreat@critical{% + \ifnum\c@linenumber<\c@firstlinenumber + \expandafter \@gobble + \fi}% + +% (/New v4.31) +% +% The default +% value of ~\c@firstlinenumber~ %% v4.31 +% is 0. This is best for what one would expect from modulo +% printing. + +\let\c@firstlinenumber=\z@ + +% +% For usage and effects of ~\modulolinenumbers~ and %% v4.31 +% ~\firstlinenumbers~, please consult section_\ref{s:UserCmds}. +% Two details on ~\firstlinenumbers~ here: +% (i)_~\firstlinenumber~ acts on a paragraph if and only if +% (a)_the paragraph is broken into lines ``in line-numbering +% mode'' (after ~\linenumbers~, e.g.); +% (b)_it is the last occurrence of a ~\firstlinenumbers~ +% before or in the paragraph. +% (The practical applications of this that I can imagine +% don't seem appealing to me.) +% Cf._the explanation above of how ~\modulolinenumbers~ and +% ~\firstlinenumbers~ interact---for this and for (ii), +% which is concerned with possible arguments for +% ~\firstlinenumbers~. +% +% Note that the line numbers of the present section +% demonstrate the two devices. (/New v4.00) + +%%\setcounter{linenumbermodulo}{5} +\chardef\c@linenumbermodulo=5 % v4.2; ugly? +\modulolinenumbers[1] + +% (New v4.22) The new implementation through ~\chardef~ +% decreases the functionality and raises certain compatibility +% problems. I face this without fear. The maximum modulo value +% is now ~255~. I expect that this suffices for usual applications. +% However, some users have ``abused'' ~lineno.sty~ to get +% ~ednotes.sty~ features without line numbers, so have set the +% modulo to a value beyond the total number of lines in their +% edition. This ought to be replaced by +% ~\let\makeLineNumber\relax~. (/New v4.22) +% +% \section{% +% Package options +% \unskip}\label{s:Opts} +% +% (New v4.1) +% The last heading formerly was the heading of what is now +% subsection_\ref{ss:v3opts}. The options declared there were +% said to execute user commands only. This was wrong already +% concerning ~displaymath~ and ~hyperref~. At least, however, +% these options were no or almost no occasion to skip definitions +% or allocations. This is different with the options that we now +% insert. +% +%% (New v4.2) v4.00 moved the ``options'' below the +%% ``extensions''. This was bad with ~\do@mlineno~ in +%% subsection_\ref{ss:v3opts} which is to control +%% subsection_\ref{ss:display}---undone here. (/New v4.2) +% +% \subsection{% +% Extended referencing to line numbers. (v4.2) +% \unskip} +% This subsection explains and declares package option ~addpageno~. %% v4.31 +% +% If a line to whose number you refer by ~\ref~ is not on the +% present page, it may be useful to add the number of the page +% on which the line occurs---and perhaps it should not be added +% otherwise. In general, you could use the Standard \LaTeX\ +% package varioref for this. However, the latter usually +% produces verbose output like `on the preceding page'--- +% unless costumized---, while in critical editions, e.g., one +% may prefer just adding the page number and some mark on the +% left of the line number, irrespectively of how far the page is +% apart etc. To support this, package option ~addpageno~ +% provides a command ~\vpagelineref~ to be used in place of +% ~\ref~. This produces, e.g., `34.15' when referring to line_15 +% on page_34 while the present page is not 34. You can customize +% the outcome, see the package file ~vplref.sty~ where the code +% and further details are. You may conceive of +% ~\vpagelineref~ as a certain customization of varioref's +% ~\vref~. +% +% This implies that option ~addpageno~ requires the files +% ~vplref.sty~ and ~varioref.sty~. ~addpageno~ automatically +% loads both of them. Yet you can also load ~varioref.sty~ +% on your own to use its package options. +% +% Of course, you might better introduce a shorter command name +% for ~\vpagelineref~ for your work, while we cannot predict +% here what shorthand will fit your work. E.g., +% ~\newcommand{\lref}{\vpagelineref}~. +% +% If you really want to add the page number in \emph{any} case, +% use, e.g., some ~\myref~ instead of ~\ref~, after +% \[~newcommand*{\myref}{\pageref{#1}.\ref{#1}}~\] +% or what you like. You don't need the ~addpageno~ option in +% this case. +% +% ~addpageno~ is due to a suggestion by Sergei Mariev. + +\DeclareOption{addpageno}{% + \AtEndOfPackage{\RequirePackage{vplref}[2005/04/25]}} + +% \subsection{% +% \scs{linelabel} in math mode +% \unskip}\label{ss:MathRef} +% +% We have made some first steps towards allowing ~\linelabel~ in +% math mode. Because our code for this is presently experimental, +% we leave it to the user to decide for the experiment by calling +% option ~mathrefs~. We are in a hurry now and thus leave the +% code, explanations, and discussion in the separate package +% ~ednmath0.sty~. Maybe we later find the time to improve the +% code and move the relevant content of ~ednmath0.sty~ to here. +% The optimal situation would be to define ~\linelabel~ from +% the start so it works in math mode, omitting the ~mathrefs~ +% option. +% +% Actually, this package even provides adjustments for analogously +% allowing ~ednotes.sty~ commands in math mode. Loading the package +% is postponed to ~\AtBeginDocument~ when we know whether these +% adjustments are needed. + +\DeclareOption{mathrefs}{\AtBeginDocument + {\RequirePackage{ednmath0}[2004/08/20]}} + +% +% \subsection{% +% Arrays, tabular environments (Revised v4.11) +% \unskip}\label{ss:Tab} +% +% This subsection explains and declares package options %% v4.31 +% ~edtable~, ~longtable~, and ~nolongtablepatch~. +% +% The standard \LaTeX\ tabular environments come as single +% boxes, so the ~lineno.sty~ versions before v4.00 treated them as +% (parts of) single lines, printing (at most) one line number +% beside each and stepping the line number counter once only. +% Moreover, ~\linelabel~s got lost. Of course, tables are +% usually so high that you will want to treat each row like a +% line. (Christian Tapp even desires that the lines of table +% entries belonging to a single row are treated like ordinary +% lines.) Footnotes get lost in such environments as well, which +% was bad for ~ednotes.sty~. +% +% We provide adjustments to count lines, print their numbers +% etc.\ as desired at least for \emph{some} \LaTeX\ tabular +% environments. (Like with other details, ``some'' is to some +% extent explained in ~edtable.sty~.) We do this similarly as +% with option ~mathrefs~ before. We leave code +% and explanations in the separate package ~edtable.sty~. +% (For wizards: this package provides adjustments for +% ~ednotes.sty~ as well. However, in the present case we don't try +% to avoid them unless ~ednotes.sty~ is loaded.) +% Package option ~edtable~ +% defines---by loading ~edtable.sty~---an environment ~{edtable}~ +% which is able to change some \LaTeX\ tabular environments +% with the desired effects. (v4.11: ~edtable.sty~ v1.3 counts +% \LaTeX's ~{array}~ [etc.\@] as a ``tabular environment'' as +% well.) +% +% The ~{edtable}~ environment doesn't help with ~longtable.sty~, +% however. To make up for this, ~{longtable}~ is adjusted in a +% different way---and this happens only when another ~lineno.sty~ +% option ~longtable~ is called. In this case, option ~edtable~ +% needn't be called explicitly: option ~longtable~ works as if +% ~edtable~ had been called. +% +% Now, we are convinced that vertical spacing around +% ~{longtable}~ works wrongly---see \LaTeX\ bugs database +% tools/3180 and 3485, or see explanations in the package +% ~ltabptch.sty~ (which is to be obtained from CTAN folder +% \path{macros/latex/ltabptch}). Our conviction is so strong +% that the ~longtable~ option loads---after ~longtable.sty~---the +% patch package ~ltabptch.sty~. If the user doesn't want this +% (maybe preferring her own arrangement with the vertical +% spacing), she can forbid it by calling ~nolongtablepatch~. +% +% The following code just collects some choices, which are +% then executed in section_\ref{ss:ExOpt}. We use an ~\if...~ +% without ~\newif~ since ~\if...true~ and ~\if...false~ +% would occur at most two times and only within the present +% package. (~\AtEndOfClass{\RequirePackage{edtable}}~ +% could be used instead, I just overlooked this. Now I don't +% change it because it allows to change the version requirement +% at one place only.) + +\let\if@LN@edtable\iffalse + +\DeclareOption{edtable}{\let\if@LN@edtable\iftrue} + +\DeclareOption{longtable}{\let\if@LN@edtable\iftrue + \PassOptionsToPackage{longtable}{edtable}} + +\DeclareOption{nolongtablepatch}{% + \PassOptionsToPackage{nolongtablepatch}{edtable}} + +% (/New v4.1) +% +% \subsection{% +% Switch among settings +% \unskip}\label{ss:v3opts} +% +% There is a bunch of package options that execute %% v4.2 +%% There is a bunch of package options, all of them executing +%% executing only user commands (see below). %% Cf. start of section. +% user commands only. +% +% Options ~left~ (~right~) put the line numbers on the left +% (right) margin. This works in all modes. ~left~ is the +% default. + +\DeclareOption{left}{\leftlinenumbers*} + +\DeclareOption{right}{\rightlinenumbers*} + +% Option ~switch~ (~switch*~) puts the line numbers on the +% outer (inner) margin of the text. This requires running +% the pagewise mode, but we turn off the page offset +% subtraction, getting sort of running numbers again. The +% ~pagewise~ option may restore true pagewise mode later. + +\DeclareOption{switch}{\setpagewiselinenumbers + \switchlinenumbers + \runningpagewiselinenumbers} + +\DeclareOption{switch*}{\setpagewiselinenumbers + \switchlinenumbers*% + \runningpagewiselinenumbers} + +% In twocolumn mode, we can switch the line numbers to +% the outer margin, and/or start with number 1 in each +% column. Margin switching is covered by the ~switch~ +% options. + +\DeclareOption{columnwise}{\setpagewiselinenumbers + \columnwiselinenumberstrue + \realpagewiselinenumbers} + +% The options ~pagewise~ and ~running~ select the major +% linenumber mechanism. ~running~ line numbers refer to a real +% counter value, which can be reset for any paragraph, +% even getting multiple paragraphs on one page starting +% with line number one. ~pagewise~ line numbers get a +% unique hidden number within the document, but with the +% opportunity to establish the page on which they finally +% come to rest. This allows the subtraction of the page +% offset, getting the numbers starting with 1 on top of each +% page, and margin switching in twoside formats becomes +% possible. The default mode is ~running~. +% +% The order of declaration of the options is important here +% ~pagewise~ must come after ~switch~, to overide running +% pagewise mode. ~running~ comes last, to reset the running +% line number mode, e.g, after selecting margin switch mode +% for ~pagewise~ running. Once more, if you specify all +% three of the options ~[switch,pagewise,running]~, the +% result is almost nothing, but if you later say +% ~\pagewiselinenumbers~, you get margin switching, with +% real pagewise line numbers. +% +\DeclareOption{pagewise}{\setpagewiselinenumbers + \realpagewiselinenumbers} + +\DeclareOption{running}{\setrunninglinenumbers} + +% The option ~modulo~ causes only those linenumbers to be +% printed which are multiples of five. + +\DeclareOption{modulo}{\modulolinenumbers\relax} + +% Option ~modulo*~ modifies ~modulo~ in working like +% ~\modulolinenumbers*~---see section_\ref{s:UserCmds}. + +\DeclareOption{modulo*}{\modulolinenumbers*\relax} + +% The package option ~mathlines~ switches the behavior of +% the ~{linenomath}~ environment with its star-form. +% Without this option, the ~{linenomath}~ environment does +% not number the lines of the display, while the star-form +% does. With this option, its just the opposite. +% +%%% 1999-06-10: renamed ~displaymath~ to ~mathlines~. + +\DeclareOption{mathlines}{\linenumberdisplaymath} + +% ~displaymath~ now calls for wrappers of the standard +% \LaTeX\ display math environment. This was previously +% done by ~mlineno.sty~. +% +% (New v4.3) Option `displaymath' becomes default according +% to Erik \mbox{Luijten}'s suggestion. I was finally convinced +% of this as soon as I discovered how to avoid a spurious line +% number above ~\begin{linenomath}~ (subsection_\ref{ss:DM}). +% ~\endlinenomath~ provides ~\ignorespaces~, so what could go +% wrong now? + +\DeclareOption{displaymath}{\PackageWarningNoLine{lineno}{% + Option [displaymath] is obsolete -- default now!}} +%% +%%\let\do@mlineno\relax +%%\DeclareOption{displaymath}{\let\do@mlineno\@empty} +% (/New v4.3) +% +% \subsection{% +% Compatibility with \texttt{hyperref} %% own subsec. v4.3. +% \unskip} +% The ~hyperref~ package, via ~nameref~, requires three more +% groups in the second argment of a ~\newlabel~. Well, why +% shouldn't it get them? (New v3.07) The presence of the +% ~nameref~ package is now detected automatically +% ~\AtBeginDocument~. (/New v3.07) (Fixed in v3.09) We try +% to be smart, and test ~\AtBeginDocument~ if the ~nameref~ +% package is loaded, but ~hyperref~ postpones the loading of +% ~nameref~ too, so this is all in vain. +% +% (New v4.3) But we can also test at the first ~\linelabel~. +% Regarding the error-message for misplaced ~\linelabel~ from v4.11: +% previously, ~\linenumbers~ rendered ~\linelabel~ the genuine +% version of ~\linelabel~ from the start on. This doesn't work +% now, since ~\@LN@linelabel~ may change its meaning after the +% first ~\linenumbers~ and before a next one (if there is some). +% (/New v4.3) + +\DeclareOption{hyperref}{\PackageWarningNoLine{lineno}{% + Option [hyperref] is obsolete. + \MessageBreak The hyperref package is detected automatically.}} + +\AtBeginDocument{% + \@ifpackageloaded{nameref}{% +%% +% (New v4.3) ``Global'' is merely ``symbolic'' ~\AtBeginDoc...~. +% If ~nameref~ is not detected here, the next ~\@LN@linelabel~ +% will do almost the same, then globally indeed. +%% + \gdef\@LN@ExtraLabelItems{{}{}{}}% + }{% + \global\let\@LN@@linelabel\@LN@linelabel + \gdef\@LN@linelabel{% +%% +% ~\@ifpackageloaded~ is ``preamble only'', its---very +% internal---preamble definition is replicated here: +%% + \expandafter + \ifx\csname ver@nameref.sty\endcsname\relax \else + \gdef\@LN@ExtraLabelItems{{}{}{}}% + \fi +%% +% Now aim at the ``usual'' behaviour: +%% + \global\let\@LN@linelabel\@LN@@linelabel + \global\let\@LN@@linelabel\relax + \@LN@linelabel + }% + }% +} + +% (/New v4.3) +% +% (New v4.1) +% \subsection{% +% A note on calling so many options +% \unskip} +% +% The number of package options may stimulate worrying about how to +% \emph{enter} all the options that one would like to use---they may +% not fit into one line. Fortunately, you can safely break code lines +% after the commas separating the option names in the ~\usepackage~ +% command (no comment marks needed). +% +% \subsection{% +% Execute options +% \unskip}\label{ss:ExOpt} +% +% We stop declaring options and execute the ones that are +% called by the user. (/New v4.1) + +\ProcessOptions + +% (New v4.1) Now we know whether ~edtable.sty~ is wanted +% and (if it is) with which options it is to be called. + +\if@LN@edtable \RequirePackage{edtable}[2005/03/07] \fi + +% (/New v4.1) +% +% \section{% +% Former package extensions +% \label{s:Xt}\unskip} +% +% The extensions in this section were previously supplied +% in separate ~.sty~ files. +% +% \subsection{% +% $display math$ +% \unskip}\label{ss:display} +%% (New v4.32) +% (New v4.3) From now on, you no longer need to type +% the ~{linenomath}~ environment with the ~\[~, ~{equation}~, +% and ~{eqnarray}~ environments---and you no longer need to +% use the former package option ~displaymath~ for this feature. +% (/New v4.3) +%% (/New v4.32) +% +% The standard \LaTeX\ display math environments are +% wrapped in a ~{linenomath}~ environment. +% +% (New 3.05) The ~[fleqn]~ option of the standard +% \LaTeX\ classes defines the display math +% environments such that line numbers appear just +% fine. Thus, we need not do any tricks when +% ~[fleqn]~ is loaded, as indicated by presents of +% the ~\mathindent~ register. (/New 3.05) +% +% (New 3.05a) for ~{eqnarray}~s we rather keep the +% old trick. (/New 3.05a) +% +% (New 3.08) Wrap ~\[~ and ~\]~ into ~{linenomath}~, +% instead of ~{displaymath}~. Also save the definition +% of ~\equation~, instead of replicating the current +% \LaTeX\ definition. (/New 3.08) + +%%\ifx\do@mlineno\@empty + \@ifundefined{mathindent}{ + +%% \AtBeginDocument{% + \let\LN@displaymath\[% + \let\LN@enddisplaymath\]% + \renewcommand\[{\begin{linenomath}\LN@displaymath}% + \renewcommand\]{\LN@enddisplaymath\end{linenomath}}% +% + \let\LN@equation\equation + \let\LN@endequation\endequation + \renewenvironment{equation}% + {\linenomath\LN@equation}% + {\LN@endequation\endlinenomath}% +%% } + + }{}% \@ifundefined{mathindent} -- 3rd arg v4.2, was \par! + +%%\AtBeginDocument{% + \let\LN@eqnarray\eqnarray + \let\LN@endeqnarray\endeqnarray + \renewenvironment{eqnarray}% + {\linenomath\LN@eqnarray}% + {\LN@endeqnarray\endlinenomath}% +%%} + +%%\fi + +% (UL) Indeed. The \LaTeX\ macros are saved for +% unnumbered mode, which is detected by ~\linenomath~. +% (/UL) +% +% \subsection{% +% Line numbers in internal vertical mode +% \unskip}\label{ss:ILN} +% +% The command ~\internallinenumbers~ adds line numbers in +% internal vertical mode, but with limitations: we assume +% fixed baseline skip. +% +% (v4.22) v3.10 provided a global (~\global\advance~) +% as well as a local version (star-form, using +% ~\c@internallinenumber~). ~\resetlinenumbers~ acted +% locally and was here used with the global version---save +% stack danger, \TeX book p._301---in v4.00 I +% disabled the global version therefore. Now I find that +% it is better to keep a global version, and the now global +% ~\resetlinenumbers~ is perfect for this. The global version +% allows continuing the ``internal'' numbers in the ensuing +% ``external'' text, and---unless reset by brackets +% argument---continuing the above series of line numbers. +% As with v3.10, the local version always starts with +% line number one. A new ~\@LN@iglobal~ steps ~\global~ly +% in the global version, otherwise it is ~\relax~. +% (I also remove all my stupid discussions as of v4.00. +% And I use ~\newcommand~.) (v4.22) + +\let\@LN@iglobal\global % v4.22 + +\newcommand\internallinenumbers{\setrunninglinenumbers + \let\@@par\internallinenumberpar + \ifx\@par\@@@par\let\@par\internallinenumberpar\fi + \ifx\par\@@@par\let\par\internallinenumberpar\fi + \ifx\@par\linenumberpar\let\@par\internallinenumberpar\fi + \ifx\par\linenumberpar\let\par\internallinenumberpar\fi + \@ifnextchar[{\resetlinenumber}%] + {\@ifstar{\let\c@linenumber\c@internallinenumber + \let\@LN@iglobal\relax % v4.22 + \c@linenumber\@ne}{}}% + } + +\let\endinternallinenumbers\endlinenumbers +\@namedef{internallinenumbers*}{\internallinenumbers*} +\expandafter\let\csname endinternallinenumbers*\endcsname\endlinenumbers + +\newcount\c@internallinenumber +\newcount\c@internallinenumbers + +\newcommand\internallinenumberpar{% + \ifvmode\@@@par\else\ifinner\@@@par\else\@@@par + \begingroup + \c@internallinenumbers\prevgraf + \setbox\@tempboxa\hbox{\vbox{\makeinternalLinenumbers}}% + \dp\@tempboxa\prevdepth + \ht\@tempboxa\z@ + \nobreak\vskip-\prevdepth + \nointerlineskip\box\@tempboxa + \endgroup + \fi\fi + } + +\newcommand\makeinternalLinenumbers{% + \ifnum\c@internallinenumbers>\z@ % v4.2 + \hb@xt@\z@{\makeLineNumber}% + \@LN@iglobal % v4.22 + \advance\c@linenumber\@ne + \advance\c@internallinenumbers\m@ne + \expandafter\makeinternalLinenumbers\fi + } + % TODO v4.4+: star: line numbers right!? cf. lnocapt.sty + +% +% \subsection{% +% Line number references with offset +% \unskip} +% +% This extension defines macros to refer to line +% numbers with an offset, e.g., to refer to a line +% which cannot be labeled directly (display math). +% This was formerly knows as ~rlineno.sty~. +% +% To refer to a pagewise line number with offset: +% \begin{quote} +% ~\linerefp[~<OFFSET>~]{~<LABEL>~}~ +% \end{quote} +% To refer to a running line number with offset: +% \begin{quote} +% ~\linerefr[~<OFFSET>~]{~<LABEL>~}~ +% \end{quote} +% To refer to a line number labeled in the same mode as currently +% selected: +% \begin{quote} +% ~\lineref[~<OFFSET>~]{~<LABEL>~}~ +% \end{quote} + +\newcommand\lineref{% + \ifx\c@linenumber\c@runninglinenumber + \expandafter\linerefr + \else + \expandafter\linerefp + \fi +} + +\newcommand*\linerefp[2][\z@]{{% + \let\@thelinenumber\thelinenumber + \edef\thelinenumber{\advance\c@linenumber#1\relax + \noexpand\@thelinenumber}% + \ref{#2}% +}} + +% This goes deep into \LaTeX's internals. + +\newcommand*\linerefr[2][\z@]{{% + \def\@@linerefadd{\advance\c@linenumber#1}% + \expandafter\@setref\csname r@#2\endcsname + \@linerefadd{#2}% +}} + +\newcommand*\@linerefadd[2]{\c@linenumber=#1\@@linerefadd\relax + \thelinenumber} + +%% TODO v4.4+: Insert `LN' in internal command names? +% +% \subsection{% +% Numbered quotation environments +% \unskip} +% +% The ~{numquote}~ and ~{numquotation}~ +% environments are like ~{quote}~ and +% ~{quotation}~, except there will be line +% numbers. +% +% An optional argument gives the number to count +% from. A star ~*~ (inside or outside the closing +% ~}~) prevent the reset of the line numbers. +% Default is to count from one. +% +% (v4.22: A local version using ~\c@internallinenumber~ +% might be useful, see subsection_\ref{ss:ILN}.) %% TODO v4.4+ + +\newcommand\quotelinenumbers + {\@ifstar\linenumbers{\@ifnextchar[\linenumbers{\linenumbers*}}} + +\newdimen\quotelinenumbersep +\quotelinenumbersep=\linenumbersep +\let\quotelinenumberfont\linenumberfont + +\newcommand\numquotelist + {\leftlinenumbers + \linenumbersep\quotelinenumbersep + \let\linenumberfont\quotelinenumberfont + \addtolength{\linenumbersep}{-\@totalleftmargin}% + \quotelinenumbers + } + +\newenvironment{numquote} {\quote\numquotelist}{\endquote} +\newenvironment{numquotation} {\quotation\numquotelist}{\endquotation} +\newenvironment{numquote*} {\quote\numquotelist*}{\endquote} +\newenvironment{numquotation*}{\quotation\numquotelist*}{\endquotation} + +% +% \subsection{% +% Frame around a paragraph +% \unskip} +% +% The ~{bframe}~ environment draws a frame around +% some text, across page breaks, if necessary. +% +% This works only for plain text paragraphs, +% without special height lines. All lines must be +% ~\baselineskip~ apart, no display math. + +\newenvironment{bframe} + {\par + \@tempdima\textwidth + \advance\@tempdima 2\bframesep + \setbox\bframebox\hb@xt@\textwidth{% + \hskip-\bframesep + \vrule\@width\bframerule\@height\baselineskip\@depth\bframesep + \advance\@tempdima-2\bframerule + \hskip\@tempdima + \vrule\@width\bframerule\@height\baselineskip\@depth\bframesep + \hskip-\bframesep + }% + \hbox{\hskip-\bframesep + \vrule\@width\@tempdima\@height\bframerule\@depth\z@}% + \nointerlineskip + \copy\bframebox + \nobreak + \kern-\baselineskip + \runninglinenumbers + \def\makeLineNumber{\copy\bframebox\hss}% + } + {\par + \kern-\prevdepth + \kern\bframesep + \nointerlineskip + \@tempdima\textwidth + \advance\@tempdima 2\bframesep + \hbox{\hskip-\bframesep + \vrule\@width\@tempdima\@height\bframerule\@depth\z@}% + } + +\newdimen\bframerule +\bframerule=\fboxrule + +\newdimen\bframesep +\bframesep=\fboxsep + +\newbox\bframebox + +% +% +% \section{% +% Move \scs{vadjust} items (New v4.00) +% \unskip}\label{s:MVadj} +% +% This section completes reviving ~\pagebreak~, ~\nopagebreak~, +% ~\vspace~, and the star and optional form of ~\\~. This was +% started in section_\ref{ss:output} and resumed in +% section_\ref{ss:MLN} and subsection_\ref{ss:calls}. +% The problem was explained in section_\ref{ss:output}: +% ~\vadjust~ items come out at a bad position, and the +% \LaTeX\ commands named before work with ~\vadjust~ indeed. +% Our solution was sketched there as well. +% +% According to the caveat in subsection_\ref{ss:OnOff} concerning +% ~\ifLineNumbers~, the \LaTeX\ commands enumerated may go +% wrong if you switch line numbering inside or at the end of +% a paragraph. +%% %% TODO v4.4+ +% +% \subsection{% +% Redefining \scs{vadjust} +% \unskip}\label{ss:PVadj} +% +% ~\vadjust~ will temporarily be changed into the following +% command. + +\def\PostponeVadjust#1{% + \global\let\vadjust\@LN@@vadjust +%% +% This undoes a ~\global\let\vadjust\PostponeVadjust~ which will +% start each of the refined \LaTeX\ commands. The ~\global~s +% are most probably superfluous. They might be useful should one +% ~\vadjust~ appear in a group starting after the change of +% ~\vadjust~ into ~\PostponeVadjust~. +% (UL) Even the undoing may be superfluous, cf._discussion +% in section_\ref{ss:ReDef} below. (UL) +%% + \vadjust{\penalty-\@Mppvacodepen}% + \g@addto@macro\@LN@vadjustlist{#1\@lt}% +} +\let\@LN@@vadjust\vadjust +\global\let\@LN@vadjustlist\@empty +\global\let\@LN@do@vadjusts\relax + +% These ~\global~s are just to remind that +% all the changes of the strings after ~\let~ should be +% ~\global~ (\TeX book p._301). ~\@LN@vadjustlist~ collects +% the ~\vadjust~ items of a paragraph. ~\PassVadjustList~ +% tears one ~\vadjust~ item for the current line out of +% ~\@LN@vadjustlist~ and puts it into ~\@LN@do@vadjusts~. +% The latter is encountered each line in ~\MakeLineNo~ +% (section_\ref{ss:MLN}), while those \LaTeX\ ~\vadjust~ +% commands will come rather rarely. So I decided that +% ~\@LN@do@vadjust~ is ~\relax~ until a ~\vadjust~ item +% is waiting. In the latter case, ~\@LN@do@vadjusts~ +% is turned into a list macro which resets itself to +% ~\relax~ when the other contents have been placed in +% the vertical list.---~\PassVadjustList~ is invoked by +% the output routine (section_\ref{ss:output}), so the +% ~\box255~ must be put back. + +\def\PassVadjustList{% + \unvbox\@cclv + \expandafter \@LN@xnext \@LN@vadjustlist \@@ + \@tempa \@LN@vadjustlist + \ifx\@LN@do@vadjusts\relax + \gdef\@LN@do@vadjusts{\global\let\@LN@do@vadjusts\relax}% + \fi + \expandafter \g@addto@macro \expandafter \@LN@do@vadjusts + \expandafter {\@tempa}% +} + +% +% \subsection{% +% Redefining the \LaTeX\ commands +% \unskip}\label{ss:ReDef} +% +% Now we change ~\pagebreak~ etc.\ +% so that they use ~\PostponeVadjust~ in place of ~\vadjust~. +% We try to do this as independently as possible of the +% implementation of the \LaTeX\ commands to be redefined. +% Therefore, we don't just copy macro definition code from any +% single implementation (say, latest \LaTeX) and insert our +% changes, but attach a conditional +% ~\global\let\vadjust\PostponeVadjust~ +% to their left ends in a way which should work rather +% independantly of their actual code. +% However, ~\vadjust~ should be the primitive again after +% execution of the command. So the ~\global\let...~ may be used +% only if it's guaranteed that a ~\vadjust~ is near.---(UL) +% Sure? In line numbering mode, probably each ~\vadjust~ +% coming from a \LaTeX\ command should be ~\PostponeVadjust~. +% ~\marginpar~s and floats seem to be the only cases which +% are not explicitly dealt with in the present section. +% This would be a way to avoid ~\@LN@nobreaktrue~! +% Of course, the ~\vadjust~s that the present package uses +% then must be replaced by ~\@LN@@vadjust~.---Maybe +% next time. (/UL) +%% %% TODO v4.4+ +% +% The next command and something else will be added to the +% \LaTeX\ commands we are concerned with here. + +\DeclareRobustCommand\@LN@changevadjust{% + \ifvmode\else\ifinner\else + \global\let\vadjust\PostponeVadjust + \fi\fi +} + +% (UL) What about math mode? Math display? Warn? (/UL) +%% %% TODO v4.4+ +% +% ~\@tempa~ will now become a two place macro which adds first +% argument (single token), enclosed by ~\ifLineNumbers~\,\dots +% ~\fi~ to the left of second argument. As long as we need it, +% we can't use the star form of ~\DeclareRobustCommand~ or +% the like, because AMS-\LaTeX\ uses ~\@tempa~ for ~\@ifstar~. +% (New v4.41) And for the same reason, that ~\CheckCommand*~ +% had to be raised! (/New v4.41) + +\CheckCommand*\@parboxrestore{\@arrayparboxrestore\let\\\@normalcr} + +\def\@tempa#1#2{% + \expandafter \def \expandafter#2\expandafter{\expandafter + \ifLineNumbers\expandafter#1\expandafter\fi#2}% +} + +% (UL) This ~\ifLineNumber~ can be fooled by +% ~\linenumbers~ ahead etc. It might be better to place +% a signal penalty in any case and let the output routine +% decide what to do. +%% +%% And when this has been done, remove warnings about this. +% (/UL) +% +% We use the occasion to switch off linenumbers where they +% don't work anyway and where we don't want them, +% especially in footnotes: + +\@tempa\nolinenumbers\@arrayparboxrestore + +% We hope this suffices $\dots$ let's check one thing +% at least: [(New v4.41) see ~\CheckCommand~ above (/New v4.41)] +% +% Now for the main theme of the section. +% The next lines assume that ~\vspace~, ~\pagebreak~, and +% ~\nopagebreak~ use ~\vadjust~ whenever they occur outside +% vertical mode; moreover, that they don't directly read +% an argument. Indeed ~\pagebreak~ and ~\nopagebreak~ first +% call something which tests for a left bracket ahead, +% while ~\vspace~ first tests for a star. + +\@tempa\@LN@changevadjust\vspace +\@tempa\@LN@changevadjust\pagebreak +\@tempa\@LN@changevadjust\nopagebreak + +% ~\\~, however, uses ~\vadjust~ only in star or optional form. +% We relax independency of implementation in assuming +% that ~\@normalcr~ is the fragile version of ~\\~ +% (and we use ~\@ifstar~!). +%% +%% \@ifstar reimplemented 1995/10/16, but seems to be much older. +%% TODO v4.4+: +%% \def\@LN@cr{% +%% \@ifnextchar*{\@LN@changevadjust\@normalcr}% +%% {\@ifnextchar[{\@LN@changevadjust\@normalcr}\@normalcr}% +%% } +%% ---same number of tokens, expansion step less. +%% +% (Using a copy of ~\\~ would be safer, but an ugly repetition +% of ~\protect~.) +%% %% TODO v4.4+ + +\DeclareRobustCommand\\{% + \ifLineNumbers + \expandafter \@LN@cr + \else + \expandafter \@normalcr + \fi +} +\def\@LN@cr{% + \@ifstar{\@LN@changevadjust\@normalcr*}% + {\@ifnextchar[{\@LN@changevadjust\@normalcr}\@normalcr}% +} + +% Moreover we hope that ~\newline~ never leads to a ~\vadjust~, +% although names of some commands invoked by ~\\~ contain +% ~newline~. At last, this seems to have been OK since 1989 or +% even earlier. +% +% \modulolinenumbers[1] +% \firstlinenumber{0} +% Let's have a few tests.\vspace*{.5\baselineskip} +% Testing ~\pagebreak~ and ~\nopagebreak~ would be too expensive +% here, but---oops!---we have just experienced a successful +% ~\vspace*{.5\baselineskip}~. A +% ~\\*[.5\baselineskip]~\\*[.5\baselineskip] may look even more +% drastical, but this time we are happy about it. Note that the +% line numbers have moved with the lines. Without our changes, +% one line number\vadjust{\kern.5\baselineskip} would have +% ``anticipated'' the move of the next line, just as you can +% observe it now. +% (/New v4.00) +% +% \switchlinenumbers +% +% \subsection{% +% Reminder on obsoleteness +% \unskip} +% +% (New v4.1) We have completed inclusion of the earlier +% extension packages ~linenox0.sty~, ~linenox1.sty~, and +% ~lnopatch.sty~. If one of them is loaded, though, +% we produce an error message before something weird happens. +% We avoid ~\newif~ because the switchings occur so rarely. + +\AtBeginDocument{% + \let\if@LN@obsolete\iffalse + \@ifpackageloaded{linenox0}{\let\if@LN@obsolete\iftrue}\relax + \@ifpackageloaded{linenox1}{\let\if@LN@obsolete\iftrue}\relax + \@ifpackageloaded{lnopatch}{\let\if@LN@obsolete\iftrue}\relax + \if@LN@obsolete + \PackageError{lineno}{Obsolete extension package(s)}{% + With lineno.sty version 4.00 or later,\MessageBreak + linenox0/linenox1/lnopatch.sty must no longer be loaded.}% + \fi +} + +% +% \modulolinenumbers[1] +% \section{% +% The final touch +% \unskip} +% +% There is one deadcycle for each line number. + +\advance\maxdeadcycles 100 + +\endinput + +% +% \section{% +% The user commands +% \unskip}\label{s:UserCmds} +% +% The user commands to turn on and off line numbering +% are +% \begin{description}\item +% [|\linenumbers] \ \par +% Turn on line numbering in the current mode. +% +% \item +% [|\linenumbers*] \ \par$\qquad$ +% and reset the line number to 1. +% \def\NL{<number>]}\item +%% %% Boldface italic occurs here, which is evil. (UL) +% [|\linenumbers[\NL] \ \par$\qquad$ +% and start with <number>. +% \item +% [|\nolinenumbers] \ \par +% Turn off line numbering. +% \item +% [|\runninglinenumbers*[\NL] \ \par +% Turn on ~running~ line numbers, with the same optional +% arguments as ~\linenumbers~. The numbers are running +% through the text over pagebreaks. When you turn +% numbering off and on again, the numbers will continue, +% except, of cause, if you ask to reset or preset the +% counter. +% \item +% [|\pagewiselinenumbers] \ \par +% Turn on ~pagewise~ line numbers. The lines on each +% page are numbered beginning with one at the first +% ~pagewise~ numbered line. +% \item +% [|\resetlinenumber[\NL] \ \par +% Reset ~[~Set~]~ the line number to 1 +% ~[~<number>~]~. +% \item +% [|\setrunninglinenumbers] \ \par +% Switch to ~running~ line number mode. Do \emph{not} +% turn it on or off. +% \item +% [|\setpagewiselinenumbers] \ \par +% Switch to ~pagewise~ line number mode. Do \emph{not} +% turn it on or off. +% \item +% [|\switchlinenumbers*] \ \par +% Causes margin switching in pagewise modes. With the +% star, put the line numbers on the inner margin. +% \item +% [|\leftlinenumbers*] \ \par +% \item +% [|\rightlinenumbers*] \ \par +% Set the line numbers in the left/right margin. With the +% star this works for both modes of operation, without +% the star only for the currently selected mode. +% \item +% [|\runningpagewiselinenumbers] \ \par +% When using the pagewise line number mode, do not +% subtract the page offset. This results in running +% line numbers again, but with the possibility to switch +% margins. Be careful when doing line number +% referencing, this mode status must be the same while +% setting the paragraph and during references. +% \item +% [|\realpagewiselinenumbers] \ \par +% Reverses the effect of ~\runningpagewiselinenumbers~. +% \item +% [|\modulolinenumbers[\NL] \ \par +% Give a number only to lines which are multiples of +% ~[~<number>~]~. If <number> is not specified, the +% current value in the counter ~linenumbermodulo~ is +% retained. <number>=1 turns this off without changing +% ~linenumbermodulo~. The counter is initialized to 5. +%% +%% %% TODO v4.4+: `counter', he says. Cf._above. +%% +%% (New v4.31) +% \item +% [|\modulolinenumbers*[\NL] \ \par +% Like ~\modulolinenumbers~, the only difference being +% that the first line number after a ~\linenumbers~ +% (or ~\runninglinenumbers~, ~\pagewiselinenumbers~, +% ~\quotelinenumbers~) is printed regardless of the +% modulo---yet `1' is printed only after (or \dots) +% ~\firstlinenumber{1}~. +% This also applies to the first line of a +% ~{linenumbers}~ or respective environment. +% See subsection_\ref{ss:Mod} for another explanation. +% The behaviour may be unsatisfactory with pagewise +% line-numbering. +%% (/New v4.31) +%% (New v4.00) +% \item +% [|\firstlinenumber] \ \par +% ~\firstlinenumber{~<filino>~}~ brings about that +% (after it) line numbers less than <filino> do +% \emph{not} appear in the margin. Moreover, with +% ~\modulolinenumbers[~<number>~]~, just the line +% numbers which are <filino> plus a multiple of +% <number> are printed.---If you had +% ~\firstlinenumber{~<pos>~}~ with some $\mbox{<pos>}>0$ +% and want to switch to printing multiples of, e.g., +% 4, you best do ~\modulolinenumbers[4]~ and +% ~\firstlinenumber{0}~. (See subsection_\ref{ss:Mod} +% for technical details.) +%% (/New v4.00) +% \item +% [|\linenumberdisplaymath] \ \par +% Number the lines of a display math in a ~{linenomath}~ +% environment, but do not in a ~{linenomath*}~ +% environment. This is used by the package option +% ~[mathlines]~. +% \item +% [|\nolinenumberdisplaymath] \ \par +% Do not Number the lines of a display math in a +% ~{linenomath}~ environment, but do in a +% ~{linenomath*}~ environment. This is the default. +% \item +% [|\linelabel] \ \par +% Set a ~\linelabel{~<foo>~}~ to the line number where +% this commands is in. Refer to it with the \LaTeX\ +% referencing commands ~\ref{~<foo>~}~ and +% ~\pageref{~<foo>~}~. +% \end{description} +% The commands can be used globally, locally within groups +% or as environments. It is important to know that they +%% +%% %% TODO: \linelabel? others? +%% +% take action only when the ~\par~ is executed. The +%% +%% %% TODO: sure? ~\modulo...~, e.g.? well, in a sense ... +%% +% ~\end{~<mode>~linenumbers}~ commands provide a ~\par~. +% Examples: +% \begin{verse} +% ~{\linenumbers~ <text> ~\par}~ \\ +% \ \\ +% ~\begin{linenumbers}~ \\ +% <text> \\ +% ~\end{linenumbers}~ \\ +% \ \\ +% <paragraph> ~{\linenumbers\par}~ \\ +% \ \\ +% ~\linenumbers~ \\ +% <text> ~\par~ \\ +% ~\nolinenumbers~ \\ +% \ \\ +% ~\linenumbers~ \\ +% <paragraph> ~{\nolinenumbers\par}~ \\ +% \end{verse} +% (New v4.00) +% However, the examples containing <paragraph> show what you +% should \emph{not} do, at least if you use ~\pagebreak~, +% ~\nopagebreak~, ~\vspace~, ~\\*~ or +% ~\\[~<space>~]~---cf._section_\ref{s:MVadj}. +% +% The same care should be applied to the ``wizard'' devices +% ~\ifLineNumbers~ (subsection_\ref{ss:OnOff}) and +% ~\PostponeVadjust~ (section_\ref{ss:PVadj}). +% (/New v4.00) +% +% (New v4.11) Oh, and the commands and environments of +% section_{s:Xt} are missing. Sorry, I am in a hurry now. +% May be next time.% %% TODO v4.4+ +% ---And the environments ~{linenomath}~ and ~{linenomath*}~should +% get an own paragraph. In short, each math display, equation, +% or ~{eqnarray}~ should be ``wrapped'' in one of ~{linenomath}~ +% and ~{linenomath*}~. +% +% \subsection{% +% Customization hooks +% \unskip} +% +% There are several hooks to customize the appearance of the +% line numbers, and some low level hooks for special +% effects. +% \begin{description}\item +% [|\thelinenumber] \ \par +% This macro should give the representation of the line +% number in the \LaTeX-counter ~linenumber~. The +% default is provided by \LaTeX: \par$\qquad$ +% ~\arabic{linenumber}~ +% \item +% [|\makeLineNumberLeft] \ \par +% This macro is used to attach a line number to the left +% of the text page. This macro should fill an ~\hbox to 0pt~ +% which will be placed at the left margin of the +% page, with the reference point aligned to the line to +% which it should give a number. Please use the macro +% ~\LineNumber~ to refer to the line number. +% +% The default definition is \par$\qquad$ +% ~\hss\linenumberfont\LineNumber\hskip\linenumbersep~ +% \item +% [|\makeLineNumberRight] \ \par +% Like ~\makeLineNumberLeft~, but for line numbers on +% the right margin. +% +% The default definition is \par$\qquad$ +% ~\linenumberfont\hskip\linenumbersep\hskip\textwidth~ \par$\qquad$ +% ~\hbox to\linenumberwidth{\hss\LineNumber}\hss~ +% \item +% [|\linenumberfont] \ \par +% This macro is initialized to \par$\qquad$ +% ~\normalfont\tiny\sffamily~ +% \item +% [|\linenumbersep] \ \par +% This dimension register sets the separation of the +% linenumber to the text. Default value is ~10pt~. +% \item +% [|\linenumberwidth] \ \par +% This dimension register sets the width of the line +% number box on the right margin. The distance of the +% right edge of the text to the right edge of the line +% number is ~\linenumbersep~ + ~\linenumberwidth~. The +% default value is ~10pt~. +% \item +% [|\theLineNumber] (for wizards) \ \par +% This macro is called for printing a ~\newlabel~ entry +% to the aux-file. Its definition depends on the mode. +% For running line numbers it's just ~\thelinenumber~, +% while in pagewise mode, the page offset subtraction +% is done in here. +% \item +% [|\makeLineNumber] (for wizards) \ \par +% This macro produces the line numbers. The definition +% depends on the mode. In the running line numbers +% mode it just expands ~\makeLineNumberLeft~. +% \item +% [|\LineNumber] (for wizards) \ \par +% This macro is called by ~\makeLineNumber~ to typeset +% the line number. This hook is changed by the modulo +% mechanism +%% %%%. +% and by ~\firstlinenumber~. +%% %% New v4.00 +% \end{description} +%% +%% TODO: \stepLineNumber---another wizard command!? +%% Not sure, may be retreated. +% \end{document}%D +------------------------------------------------------------------------------ + %SSTOPP +%% TODO v4.4+: Check for unwanted comment marks in new comments +%% (resulting from manual aligning): search `New v4.2' +%% and/or ` % '! +%% TODO v4.4+: Check for missing comment marks where a paragraph +%% should end/start. Also to prevent empty "code" lines. +%% Especially, new comments at section ends must be +%% followed by comment mark lines. +%% And prevent ~\par~s from blank lines in definitions! +%% See `visual space' above. +%% For proper appearance in lineno.tex, note that a comment +%% in a final code line changes behaviour. +%% TODO v4.4+: Require README for redistribution? +%% TODO v4.4+: Since discussions of code have increased so much, it +%% would be appropriate not to give to this file +%% extension `.sty' (e.g., `dty'!??). ?? Is quickly read though! +%% A .sty extraction may be possible even if the present +%% file is neither a .doc nor a .dtx. (!???) +%% Use awk line below (etc.) for .doc at least; + .ins or so. +%% ^ must not be caps! To escape awk. +%% TODO v4.4+: Underfull lines!? (due to long code quotations) +%% TODO v4.4+: Sometimes paragraph indents may be appropriate. +%% TODO Swap first line (`\iffalse...') with corresponding below. + Or do *not* swap, maybe nawk is more reliable. +%% TODO v4.4+: Ponder Stephan's mail from 2004/09/02. +%% TODO v4.4+: +%% use \@ET@makeLineNumber. +%% plus almost all `(UL)' +%% plus lots of bad boxes messages +%% change v4.3 TODOs when postponed +%% remove {old} environments. + +------------------------------------------------------------------------------ + +# awk command lines for v4.00, mixed with former ones: + +echo "Don't bother about unknown 'iffalse'." # SHELL1 +nawk '/A[W]K/' lineno.sty | nawk -f - lineno.sty >lineno.tex; # SHELL1 +latex lineno; latex lineno; latex lineno; latex lineno; # SHELL1 + +BEGIN{DOC=-1; # AWK DOC A W K + BEGINCODE = "\\begin{code}\\begin{verbatim}"; # AWK + ENDCODE = "\\end{verbatim}\n\\end{code}"; } # AWK + BEGINCODE = "% \\begin{macrocode}"; # DOC A W K + ENDCODE = "% \\end{macrocode}"; } # DOC A W K +/^[ \t]*$/ { ECNT++; next; } # AWK DOC A W K +/\\documentclass/{ sub("article","ltxdoc") } # DOC A W K +/%D$/ { sub("^%* *",""); sub("%D$",""); # DOC A W K + print > "lineno.drv"; next } # DOC A W K +/^%%/ { next; } # AWK DOC A W K +/^%/ { if (!DOC) { print ENDCODE; } # AWK DOC A W K + DOC=1; ECNT=0; # AWK DOC A W K + sub("^% *",""); # AWK + sub("^% *","% "); # DOC A W K + print; next; } # AWK DOC A W K +/%VERSION/ { sub("%VERSION",""); print; next; } # AWK +/%SSTOPP/ { exit } # AWK +DOC<0 { next } # AWK DOC A W K +/^-+-$/ { if (!DOC) print ENDCODE; exit } # AWK DOC A W K +{ if (DOC) { ECNT=DOC=0; print BEGINCODE; } # AWK DOC A W K + while (ECNT>0) { print " "; ECNT--; } # AWK DOC A W K + print $0; } # AWK DOC A W K + +# New v4.00, UL: know nothing about awk; found present solution +# in hours of trial and error. + +% Earlier (should be inhibited by %SSTOPP above and otherwise): +echo "expect errors for unknown commands 'iffalse' and 'fi'";# SHELL0 SHELL#1 +awk '/A[W]K/' lineno.sty | awk -f - lineno.sty >lineno.tex; # SHELL0 +latex lineno; latex lineno; latex lineno; latex lineno; # SHELL0 +nawk '/A[W]K/' lineno4.sty | nawk -f - lineno4.sty >lineno4.tex; # SHELL#1 +latex lineno4; latex lineno4; latex lineno4; latex lineno4; # SHELL#1 + +awk '/DOC A [W] K/' lineno.sty | awk -f - lineno.sty >lineno.doc; # DOC SH + +BEGIN{DOC=-1; # A#WK DOC A W K + BEGINCODE = "\\begin{code}\\begin{verbatim}"; # A#WK + ENDCODE = "\\end{verbatim}\n\\end{code}"; } # A#WK + BEGINCODE = "% \\begin{macrocode}"; # DOC A W K + ENDCODE = "% \\end{macrocode}"; } # DOC A W K +/^[ \t]*$/ { ECNT++; next; } # A#WK DOC A W K +/\\documentclass/{ sub("article","ltxdoc") } # DOC A W K +/%D$/ { sub("^%* *",""); sub("%D$",""); # DOC A W K + print > "lineno.drv"; next } # DOC A W K +/^%%/ { next; } # A#WK DOC A W K +/^%/ { if (!DOC) { print ENDCODE; } # A#WK DOC A W K + DOC=1; ECNT=0; # A#WK DOC A W K + sub("^% *",""); # A#WK + sub("^% *","% "); # DOC A W K + print; next; } # A#WK DOC A W K +DOC<0 { next } # A#WK DOC A W K +/^-+-$/ { if (!DOC) print ENDCODE; exit } # A#WK DOC A W K +{ if (DOC) { ECNT=DOC=0; print BEGINCODE; } # A#WK DOC A W K + while (ECNT>0) { print " "; ECNT--; } # A#WK DOC A W K + print $0; } # A#WK DOC A W K + + +------------------------------------------------------------------------------ + +If you are looking here because of the two top lines of the file: + +A .tex documentation of this macro file can be obtained by + + sh lineno.sty + +under UNIX.--You may find this hint little helpful. One +reason may be that the awk versions to which you have access +don't work suitably. Another reason may be that you don't have +access to UNIX (in some sense). However, a .tex, .dvi, or .pdf +version of such a documentation should be available from CTAN, +in the same folder as the present file. When we typed this, that +folder was /macros/latex/contrib/lineno. If this has changed in +the meantime, a CTAN search should lead you to a folder +containing such a documentation. Or you may get help from one of +the e-mail addresses above. + + diff --git a/doc/LaTex/vplref.sty b/doc/LaTex/vplref.sty new file mode 100644 index 0000000000000000000000000000000000000000..d3b0697f131f45134f8460720e6102bd5cf494df --- /dev/null +++ b/doc/LaTex/vplref.sty @@ -0,0 +1,74 @@ +%% `vplref.sty' +%% -- extended line number referencing with lineno.sty. + +\def\filedate{2005/04/25} \def\fileversion{0.2a} + +%% Copyright (C) 2004, 2005 Uwe Lueck, +%% http://contact-ednotes.sty.de.vu --author-maintained +%% -- support of lineno.sty for varioref.sty. + +%% This file can be redistributed and/or modified under +%% the terms of the LaTeX Project Public License; either +%% version 1.3 of the License, or any later version. +%% The latest version of this license is in +%% http://www.latex-project.org/lppl.txt +%% We did our best to help you, but there is NO WARRANTY. + +%% USAGE: +% +% \vpagelineref{<label>} expands to +% +% a) \ref{<label>} +% -- if on same page as \linelabel{<label>} +% +% b) \LineWithPage{<label>} -- otherwise. +% +% \LineWithPage{<label>} expands -- by default -- to +% +% \pageref{<label>}.\ref{<label>} +% +% This can be customized by editing +% +% \renewcommand*{\LineWithPage}[1]{\pageref{#1}.\ref{#1}} +% +% in your document preamble, after vplref.sty has been loaded +% (which may have happened through lineno.sty with option +% `addpageno'). + +%% IMPLEMENTATION: + +\NeedsTeXFormat{LaTeX2e}[1994/12/01] %% \Declare...* +\ProvidesPackage{vplref}[\filedate\space v\fileversion \space + page-line cross-refs] %% UL 2011/02/13 + +\AtBeginDocument{\RequirePackage{lineno,varioref}} + +%% Anderer Ansatz: GPNo (\FirstOnPage) + +\DeclareRobustCommand*\vpagelineref[1]{{% +% \def\reftextcurrent{\lineref{#1}}%% First vpageref arg. + \let\reftextfaraway\LineWithPage + \def\reftextafter{\reftextfaraway{#1}}% + \let\reftextbefore\reftextafter + \let\reftextfaceafter\reftextafter + \let\reftextfacebefore\reftextafter +%% <- Looks somewhat stupid, but varioref.sty has its merits +%% as compared with the mechanism in ednotes.sty. + \vpageref[\ref{#1}][]{#1}%% The robust alternative. +%% Here and with \LineWithPage, \lineref seems more appropriate +%% than \ref, but it produces errors when labels have not been +%% defined. This seems to be an incompatibility with lineno.sty. +}} + +%% Customizable format for different page: +\newcommand*\LineWithPage[1]{\pageref{#1}.\ref{#1}} + +\endinput + +VERSION HISTORY: +v0.1 2004/10/19 First, sent to Sergei Mariev. +v0.11 2004/10/19 Fit to recent varioref version; + sent to Sergei. +v0.2 2005/04/25 \Require... \AtBeginDocument. +v0.2a 2011/02/13 add. caption to \ProvidesPackage +